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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Kekiiwaa/Localize | refs/heads/master | Source/LocalizeConfig.swift | mit | 2 | //
//
// LocalizeSwift.swift
// Localize
//
// Copyright © 2019 @andresilvagomez.
//
import Foundation
class LocalizeConfig: NSObject {
var provider: LocalizeType
var fileName: String
var defaultLanguage: String
var currentLanguage: String?
init(
provider: LocalizeType = .strings,
fileName: String = "strings",
defaultLanguage: String = "en",
currentLanguage: String? = nil,
bundle: Bundle = .main) {
self.provider = provider
self.fileName = fileName
self.defaultLanguage = defaultLanguage
self.currentLanguage = currentLanguage
}
}
| aa3f357b5f2952088dc0e3a32e1342b6 | 20.965517 | 46 | 0.640502 | false | false | false | false |
allbto/iOS-DynamicRegistration | refs/heads/master | Pods/Swiftility/Swiftility/Swiftility/Classes/Extensions/UIKit/UIViewExtensions.swift | mit | 1 | //
// UIViewExtensions.swift
// Swiftility
//
// Created by Allan Barbato on 9/22/15.
// Copyright © 2015 Allan Barbato. All rights reserved.
//
import UIKit
// MARK: - Constraints
extension UIView
{
public func addConstraintsWithVisualFormat(format: String, views: [String : UIView] = [:], options: NSLayoutFormatOptions = NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: [String : AnyObject]? = nil)
{
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: options, metrics: metrics, views: views))
}
}
// MARK: - Animations
extension UIView
{
public func addFadeTransition(duration: CFTimeInterval)
{
let animation:CATransition = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.type = kCATransitionFade
animation.duration = duration
self.layer.addAnimation(animation, forKey: kCATransitionFade)
}
}
// MARK: - Screenshot
extension UIView
{
public func screenshot() -> UIImage?
{
let rect = self.bounds
UIGraphicsBeginImageContext(rect.size)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
self.layer.renderInContext(context)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
// MARK: - Frame convinience
extension UIView
{
public func makeFrameIntegral()
{
self.frame = CGRectIntegral(self.frame)
}
public var size: CGSize {
get { return self.frame.size }
set(value) {
var newFrame = self.frame;
newFrame.size.width = value.width;
newFrame.size.height = value.height;
self.frame = newFrame
}
}
public var left: CGFloat {
get { return self.frame.origin.x }
set(value) {
var newFrame = self.frame;
newFrame.origin.x = value;
self.frame = newFrame;
}
}
public var top: CGFloat {
get { return self.frame.origin.y }
set(value) {
var newFrame = self.frame;
newFrame.origin.y = value;
self.frame = newFrame;
}
}
public var right: CGFloat {
get { return self.frame.origin.x + self.frame.size.width }
set(value) {
var newFrame = self.frame;
newFrame.origin.x = value - frame.size.width;
self.frame = newFrame;
}
}
public var bottom: CGFloat {
get { return self.frame.origin.y + self.frame.size.height }
set(value) {
var newFrame = self.frame;
newFrame.origin.y = value - frame.size.height;
self.frame = newFrame;
}
}
public var width: CGFloat {
get { return self.frame.size.width }
set(value) {
var newFrame = self.frame;
newFrame.size.width = value;
self.frame = newFrame;
}
}
public var height: CGFloat {
get { return self.frame.size.height }
set(value) {
var newFrame = self.frame;
newFrame.size.height = value;
self.frame = newFrame;
}
}
public var centerY: CGFloat {
get { return self.center.y }
set(value) {
self.center = CGPointMake(self.center.x, value)
}
}
public var centerX: CGFloat {
get { return self.center.x }
set(value) {
self.center = CGPointMake(value, self.center.y);
}
}
// MARK: - Margins
public var bottomMargin: CGFloat {
get {
guard let unwrappedSuperview = self.superview else {
return 0
}
return unwrappedSuperview.height - self.bottom;
}
set(value) {
guard let unwrappedSuperview = self.superview else { return }
var frame = self.frame;
frame.origin.y = unwrappedSuperview.height - value - self.height;
self.frame = frame;
}
}
public var rightMargin: CGFloat {
get {
guard let unwrappedSuperview = self.superview else {
return 0
}
return unwrappedSuperview.width - self.right;
}
set(value) {
guard let unwrappedSuperview = self.superview else { return }
var frame = self.frame;
frame.origin.y = unwrappedSuperview.width - value - self.width;
self.frame = frame;
}
}
// MARK: - Center
public func centerInSuperview()
{
if let u = self.superview {
self.center = CGPointMake(CGRectGetMidX(u.bounds), CGRectGetMidY(u.bounds));
}
}
public func centerVertically()
{
if let unwrappedOptional = self.superview {
self.center = CGPointMake(self.center.x, CGRectGetMidY(unwrappedOptional.bounds));
}
}
public func centerHorizontally()
{
if let unwrappedOptional = self.superview {
self.center = CGPointMake(CGRectGetMidX(unwrappedOptional.bounds), self.center.y);
}
}
// MARK: - Subviews
public func removeAllSubviews()
{
while (self.subviews.count > 0) {
if let view = self.subviews.last {
view.removeFromSuperview()
}
}
}
}
| d2f79fb76377315c88d77515663c629f | 24.590308 | 215 | 0.548976 | false | false | false | false |
lkzhao/Hero | refs/heads/master | LegacyExamples/Examples/ImageGallery/ImageGalleryCollectionViewController.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[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 Hero
class ImageGalleryViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var columns = 3
lazy var cellSize: CGSize = CGSize(width: self.view.bounds.width/CGFloat(self.columns),
height: self.view.bounds.width/CGFloat(self.columns))
override func viewDidLoad() {
super.viewDidLoad()
collectionView.reloadData()
collectionView.indicatorStyle = .white
}
@IBAction func switchLayout(_ sender: Any) {
// just replace the root view controller with the same view controller
// animation is automatic! Holy
let next = (UIStoryboard(name: "ImageGallery", bundle: nil).instantiateViewController(withIdentifier: "imageGallery") as? ImageGalleryViewController)!
next.columns = columns == 3 ? 5 : 3
hero.replaceViewController(with: next)
}
}
extension ImageGalleryViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = (viewController(forStoryboardName: "ImageViewer") as? ImageViewController)!
vc.selectedIndex = indexPath
if let navigationController = navigationController {
navigationController.pushViewController(vc, animated: true)
} else {
present(vc, animated: true, completion: nil)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ImageLibrary.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let imageCell = (collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as? ImageCell)!
imageCell.imageView.image = ImageLibrary.thumbnail(index:indexPath.item)
imageCell.imageView.hero.id = "image_\(indexPath.item)"
imageCell.imageView.hero.modifiers = [.fade, .scale(0.8)]
imageCell.imageView.isOpaque = true
return imageCell
}
}
extension ImageGalleryViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return cellSize
}
}
extension ImageGalleryViewController: HeroViewControllerDelegate {
func heroWillStartAnimatingTo(viewController: UIViewController) {
if (viewController as? ImageGalleryViewController) != nil {
collectionView.hero.modifiers = [.cascade(delta:0.015, direction:.bottomToTop, delayMatchedViews:true)]
} else if (viewController as? ImageViewController) != nil {
let cell = collectionView.cellForItem(at: collectionView.indexPathsForSelectedItems!.first!)!
collectionView.hero.modifiers = [.cascade(delta: 0.015, direction: .radial(center: cell.center), delayMatchedViews: true)]
} else {
collectionView.hero.modifiers = [.cascade(delta:0.015)]
}
}
func heroWillStartAnimatingFrom(viewController: UIViewController) {
view.hero.modifiers = nil
if (viewController as? ImageGalleryViewController) != nil {
collectionView.hero.modifiers = [.cascade(delta:0.015), .delay(0.25)]
} else {
collectionView.hero.modifiers = [.cascade(delta:0.015)]
}
if let vc = viewController as? ImageViewController,
let originalCellIndex = vc.selectedIndex,
let currentCellIndex = vc.collectionView?.indexPathsForVisibleItems[0],
let targetAttribute = collectionView.layoutAttributesForItem(at: currentCellIndex) {
collectionView.hero.modifiers = [.cascade(delta:0.015, direction:.inverseRadial(center:targetAttribute.center))]
if !collectionView.indexPathsForVisibleItems.contains(currentCellIndex) {
// make the cell visible
collectionView.scrollToItem(at: currentCellIndex,
at: originalCellIndex < currentCellIndex ? .bottom : .top,
animated: false)
}
}
}
}
| 8aa5b33e8e04c3094a61c6880d6d19d8 | 46.504587 | 158 | 0.73793 | false | false | false | false |
dreamsxin/swift | refs/heads/master | stdlib/private/StdlibUnittestFoundationExtras/StdlibUnittestFoundationExtras.swift | apache-2.0 | 3 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ObjectiveC
import Foundation
internal var _temporaryNSLocaleCurrentLocale: NSLocale? = nil
extension NSLocale {
@objc
public class func _swiftUnittest_currentLocale() -> NSLocale {
return _temporaryNSLocaleCurrentLocale!
}
}
public func withOverriddenNSLocaleCurrentLocale<Result>(
_ temporaryLocale: NSLocale,
_ body: @noescape () -> Result
) -> Result {
let oldMethod = class_getClassMethod(
NSLocale.self, #selector(NSLocale.current))
precondition(oldMethod != nil, "could not find +[NSLocale currentLocale]")
let newMethod = class_getClassMethod(
NSLocale.self, #selector(NSLocale._swiftUnittest_currentLocale))
precondition(newMethod != nil, "could not find +[NSLocale _swiftUnittest_currentLocale]")
precondition(_temporaryNSLocaleCurrentLocale == nil,
"nested calls to withOverriddenNSLocaleCurrentLocale are not supported")
_temporaryNSLocaleCurrentLocale = temporaryLocale
method_exchangeImplementations(oldMethod, newMethod)
let result = body()
method_exchangeImplementations(newMethod, oldMethod)
_temporaryNSLocaleCurrentLocale = nil
return result
}
public func withOverriddenNSLocaleCurrentLocale<Result>(
_ temporaryLocaleIdentifier: String,
_ body: @noescape () -> Result
) -> Result {
precondition(
NSLocale.availableLocaleIdentifiers().contains(temporaryLocaleIdentifier),
"requested locale \(temporaryLocaleIdentifier) is not available")
return withOverriddenNSLocaleCurrentLocale(
NSLocale(localeIdentifier: temporaryLocaleIdentifier), body)
}
/// Executes the `body` in an autorelease pool if the platform does not
/// implement the return-autoreleased optimization.
///
/// (Currently, only the i386 iOS and watchOS simulators don't implement the
/// return-autoreleased optimization.)
@inline(never)
public func autoreleasepoolIfUnoptimizedReturnAutoreleased(
_ body: @noescape () -> Void
) {
#if arch(i386) && (os(iOS) || os(watchOS))
autoreleasepool(body)
#else
body()
#endif
}
| 73fdde9da1981ef96cfa57b82e62a56c | 32.48 | 91 | 0.71366 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/InstantPageAnchorItem.swift | gpl-2.0 | 1 | //
// InstantPageAnchorItem.swift
// Telegram
//
// Created by keepcoder on 14/08/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TelegramCore
final class InstantPageAnchorItem: InstantPageItem {
var frame: CGRect
let medias: [InstantPageMedia] = []
let wantsView: Bool = false
let hasLinks: Bool = false
let isInteractive: Bool = false
let separatesTiles: Bool = false
let anchor: String
init(frame: CGRect, anchor: String) {
self.anchor = anchor
self.frame = frame
}
func drawInTile(context: CGContext) {
}
func matchesAnchor(_ anchor: String) -> Bool {
return self.anchor == anchor
}
func matchesView(_ node: InstantPageView) -> Bool {
return false
}
func view(arguments: InstantPageItemArguments, currentExpandedDetails: [Int : Bool]?) -> (InstantPageView & NSView)? {
return nil
}
func linkSelectionViews() -> [InstantPageLinkSelectionView] {
return []
}
func distanceThresholdGroup() -> Int? {
return nil
}
func distanceThresholdWithGroupCount(_ count: Int) -> CGFloat {
return 0.0
}
}
| d7b4e7ec3bf6ab5a323f6ec18d08327e | 20.807018 | 122 | 0.614642 | false | false | false | false |
GraphQLSwift/GraphQL | refs/heads/main | Sources/GraphQL/Utilities/ASTFromValue.swift | mit | 1 | /**
* Produces a GraphQL Value AST given a Map value.
*
* A GraphQL type must be provided, which will be used to interpret different
* JavaScript values.
*
* | Map Value | GraphQL Value |
* | ------------- | -------------------- |
* | .dictionary | Input Object |
* | .array | List |
* | .bool | Boolean |
* | .string | String / Enum Value |
* | .int | Int |
* | .double | Float |
*
*/
func astFromValue(
value: Map,
type: GraphQLInputType
) throws -> Value? {
if let type = type as? GraphQLNonNull {
guard let nonNullType = type.ofType as? GraphQLInputType else {
throw GraphQLError(
message: "Expected GraphQLNonNull to contain an input type \(type)"
)
}
return try astFromValue(value: value, type: nonNullType)
}
guard value != .null else {
return nil
}
// Convert array to GraphQL list. If the GraphQLType is a list, but
// the value is not an array, convert the value using the list's item type.
if let type = type as? GraphQLList {
guard let itemType = type.ofType as? GraphQLInputType else {
throw GraphQLError(
message: "Expected GraphQLList to contain an input type \(type)"
)
}
if case let .array(value) = value {
var valuesASTs: [Value] = []
for item in value {
if let itemAST = try astFromValue(value: item, type: itemType) {
valuesASTs.append(itemAST)
}
}
return ListValue(values: valuesASTs)
}
return try astFromValue(value: value, type: itemType)
}
// Populate the fields of the input object by creating ASTs from each value
// in the JavaScript object according to the fields in the input type.
if let type = type as? GraphQLInputObjectType {
guard case let .dictionary(value) = value else {
return nil
}
let fields = type.fields
var fieldASTs: [ObjectField] = []
for (fieldName, field) in fields {
let fieldType = field.type
if
let fieldValue = try astFromValue(
value: value[fieldName] ?? .null,
type: fieldType
)
{
let field = ObjectField(name: Name(value: fieldName), value: fieldValue)
fieldASTs.append(field)
}
}
return ObjectValue(fields: fieldASTs)
}
guard let leafType = type as? GraphQLLeafType else {
throw GraphQLError(
message: "Expected scalar non-object type to be a leaf type: \(type)"
)
}
// Since value is an internally represented value, it must be serialized
// to an externally represented value before converting into an AST.
let serialized = try leafType.serialize(value: value)
guard serialized != .null else {
return nil
}
// Others serialize based on their corresponding scalar types.
if case let .number(number) = serialized {
switch number.storageType {
case .bool:
return BooleanValue(value: number.boolValue)
case .int:
return IntValue(value: String(number.intValue))
case .double:
return FloatValue(value: String(number.doubleValue))
case .unknown:
break
}
}
if case let .string(string) = serialized {
// Enum types use Enum literals.
if type is GraphQLEnumType {
return EnumValue(value: string)
}
// ID types can use Int literals.
if type == GraphQLID, Int(string) != nil {
return IntValue(value: string)
}
// Use JSON stringify, which uses the same string encoding as GraphQL,
// then remove the quotes.
struct Wrapper: Encodable {
let map: Map
}
let data = try GraphQLJSONEncoder().encode(Wrapper(map: serialized))
guard let string = String(data: data, encoding: .utf8) else {
throw GraphQLError(
message: "Unable to convert data to utf8 string: \(data)"
)
}
return StringValue(value: String(string.dropFirst(8).dropLast(2)))
}
throw GraphQLError(message: "Cannot convert value to AST: \(serialized)")
}
| 0bdbe1ef7e424881310276a68aa4b079 | 31.428571 | 88 | 0.554185 | false | false | false | false |
fe9lix/Protium | refs/heads/master | iOS/Protium/src/gifs/GifGateway.swift | mit | 1 | import Foundation
import RxSwift
import RxCocoa
import JASON
typealias GifPage = (offset: Int, limit: Int)
typealias GifList = (items: [Gif], totalCount: Int)
// Protocol that is also implemented by GifStubGateway (see Tests).
// Each methods returns an Observable, which allows for chaining calls, mapping results etc.
protocol GifGate {
func searchGifs(query: String, page: GifPage) -> Observable<GifList>
func fetchTrendingGifs(limit: Int) -> Observable<GifList>
}
enum GifGateError: Error {
case parsingFailed
}
// This Gateway simply uses URLSession and its Rx extension.
// You might want to use your favorite networking stack here...
final class GifGateway: GifGate {
private let reachabilityService: ReachabilityService
private let session: URLSession
private let urlComponents: URLComponents
init(reachabilityService: ReachabilityService) {
self.reachabilityService = reachabilityService
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10.0
session = URLSession(configuration: configuration)
// Base URLs, API Keys etc. would normally be passed in via initialized parameters
// but are hard-coded here for demo purposes.
var urlComponents = URLComponents(string: "https://api.giphy.com/v1/gifs")!
urlComponents.queryItems = [URLQueryItem(name: "api_key", value: "dc6zaTOxFJmzC")]
self.urlComponents = urlComponents
}
// MARK: - Public API
func searchGifs(query: String, page: GifPage) -> Observable<GifList> {
return fetchGifs(path: "/search", params: ["q": query], page: page)
}
func fetchTrendingGifs(limit: Int) -> Observable<GifList> {
return fetchGifs(path: "/trending", params: [:], page: (offset: 0, limit: limit))
}
// MARK: - Private Methods
// Fetches a page of gifs. The JSON response is parsed into Model objects and wrapped in an Observable.
private func fetchGifs(path: String, params: [String: String], page: GifPage) -> Observable<GifList> {
var urlParams = params
urlParams["offset"] = String(page.offset)
urlParams["limit"] = String(page.limit)
return json(url(path: path, params: urlParams)) { json in
let items = json["data"].map(Gif.init)
let pagination = json["pagination"]
let totalCount = (pagination["total_count"].int ?? pagination["count"].int) ?? items.count
return (items, totalCount)
}
}
// Performs the actual call on URLSession, retries on failure and performs the parsing on a background queue.
private func json<T>(_ url: URL, parse: @escaping (JSON) -> T?) -> Observable<T> {
return session.rx
.json(url: url)
.retry(1)
.retryOnBecomesReachable(url, reachabilityService: reachabilityService)
.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.map { result in
guard let model = parse(JSON(result)) else { throw GifGateError.parsingFailed }
return model
}
}
// Constructs the complete URL based on the base url components, the path, and params for the query string.
private func url(path: String, params: [String: String]) -> URL {
var components = urlComponents
components.path += path
let queryItems = params.map { keyValue in URLQueryItem(name: keyValue.0, value: keyValue.1) }
components.queryItems = queryItems + components.queryItems!
return components.url!
}
}
| 7c0ba6b6117ec9466f62cc7bf584733a | 40.522727 | 113 | 0.664477 | false | true | false | false |
cuappdev/podcast-ios | refs/heads/master | old/Podcast/NullProfileCollectionViewCell.swift | mit | 1 | //
// NullProfileCollectionViewCell.swift
// Podcast
//
// Created by Jack Thompson on 2/28/18.
// Copyright © 2018 Cornell App Development. All rights reserved.
//
import UIKit
import SnapKit
class NullProfileCollectionViewCell: UICollectionViewCell {
let addIconSize: CGFloat = 16
//current user null profile
var addIcon: UIImageView!
//other user null profile
var nullLabel: UILabel!
let labelHeight: CGFloat = 21
static var heightForCurrentUser: CGFloat = 100
static var heightForUser: CGFloat = 24
override init(frame: CGRect) {
super.init(frame: frame)
addIcon = UIImageView()
addIcon.image = #imageLiteral(resourceName: "add_icon")
addSubview(addIcon)
addIcon.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.height.equalTo(addIconSize)
}
nullLabel = UILabel()
nullLabel.text = ""
nullLabel.font = ._14RegularFont()
nullLabel.textColor = .slateGrey
nullLabel.textAlignment = .left
addSubview(nullLabel)
nullLabel.snp.makeConstraints { (make) in
make.top.leading.equalToSuperview()
make.height.equalTo(labelHeight)
}
}
override func layoutSubviews() {
super.layoutSubviews()
addCornerRadius(height: frame.height)
}
func setup(for user: User, isMe: Bool) {
if isMe {
backgroundColor = .lightGrey
nullLabel.isHidden = true
addIcon.isHidden = false
}
else {
backgroundColor = .clear
nullLabel.text = "\(user.firstName) has not subscribed to any series yet."
nullLabel.isHidden = false
addIcon.isHidden = true
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 55f12280379f37a31827e79a2a6e5457 | 25.72973 | 86 | 0.603134 | false | false | false | false |
zzyrd/ChicagoFoodInspection | refs/heads/master | ChicagoFoodApp/ChicagoFoodApp/JSONParser.swift | mit | 1 | //
// JSONParser.swift
// ChicagoFoodApp
//
// Created by zhang zhihao on 4/23/17.
// Copyright © 2017 YUNFEI YANG. All rights reserved.
//
import Foundation
class JSONParser {
static let dateFormatter = DateFormatter()
class func parse(_ data: Data) -> [FoodFacility] {
var foodfacilities = [FoodFacility]()
if let json = try? JSONSerialization.jsonObject(with: data, options: []),
let root = json as? [String: Any],
let dataNodes = root["data"] as? [[Any]]
{
for dataNode in dataNodes{
//parse facility
let address = dataNode[14] as? String ?? ""
let name = dataNode[9] as? String ?? ""
let type = dataNode[12] as? String ?? ""
let li = dataNode[11] as? String ?? ""
let license = Int(li) ?? -1
let riskvalue = dataNode[13] as? String ?? ""
let la = dataNode[22] as? String ?? ""
let latitude = Double(la) ?? 0.0
let lo = dataNode[23] as? String ?? ""
let longitude = Double(lo) ?? 0.0
//manually check risk value
let risk: Decimal
if riskvalue == "Risk 1 (High)" {
risk = 1
}
else if riskvalue == "Risk 2 (Medium)" {
risk = 2
}
else if riskvalue == "Risk 3 (Low)" {
risk = 3
}
else{
risk = 0
}
var newFacility: FoodFacility
//get the facility by name if there is one stored in foodfacilities
let facilityChecking = foodfacilities.first(where: { (element) -> Bool in
return element.name == name
})
if facilityChecking == nil {
newFacility = FoodFacility(address: address, name: name, type: type, license: license, risk: risk, latitude: latitude, longitude: longitude, favorited: false)
}
else{//force unwrap the facilityChecking because it is not nil
newFacility = facilityChecking!
}
//parse inspection
let inspectID = dataNode[8] as? String ?? ""
let id = Int(inspectID) ?? -1
let dateStr = dataNode[18] as? String ?? ""
let inspectType = dataNode[19] as? String ?? ""
let result = dataNode[20] as? String ?? ""
let violation = dataNode[21] as? String ?? ""
//get date, month, and year from dateStr
let str_index = dateStr.index(dateStr.startIndex, offsetBy: 10)
let realDate = dateStr.substring(to: str_index)
dateFormatter.dateFormat = "yyyy/MM/dd"
let storedDate = dateFormatter.date(from: realDate)
if let date = storedDate {
newFacility.inspections.append(FoodInspection(type: inspectType, result: result, violation: violation, id: id, date: date))
}
//when not find any facility in foodfacilities by name, then add new facility to the list
if facilityChecking == nil {
foodfacilities.append(newFacility)
}
else{
if let index = foodfacilities.index(where: { (element) -> Bool in
return element.name == newFacility.name
}) {
foodfacilities[index] = newFacility
}
}
}
}
print("Task is done !")
return foodfacilities
}
}
| 4541f4d238c02dc59036a95daf8c37b3 | 44.793814 | 186 | 0.419181 | false | true | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/00859-x.swift | apache-2.0 | 1 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func f<T {
struct c {
let t: P {
func e(true {
}
override func i() {
for b {
public subscript ({
protocol d = "
func b<Int], d.A""\() {
}
assert(T? {
protocol A where T) {
}
let start = {
}
func b> {
class func c: B<T! {
var _ c) -> () -> Any, U>) {
}
}
}
let i(array: d {
struct A {
if true }
}
}
}
}
print(((self.c == .Iterator.c)
}
func b: c] in
var b {
enum A {
}
protocol a {
}
class A) { c] = "
| dbcef849a990cafdc71a070e3ba66191 | 16.369565 | 79 | 0.637046 | false | false | false | false |
fgengine/quickly | refs/heads/master | Quickly/Animation/Ease/QAnimationEaseExponencial.swift | mit | 1 | //
// Quickly
//
public final class QAnimationEaseExponencialIn : IQAnimationEase {
public init() {
}
public func perform(_ x: Double) -> Double {
return (x == 0) ? x : pow(2, 10 * (x - 1))
}
}
public final class QAnimationEaseExponencialOut : IQAnimationEase {
public init() {
}
public func perform(_ x: Double) -> Double {
return (x == 1) ? x : 1 - pow(2, -10 * x)
}
}
public final class QAnimationEaseExponencialInOut : IQAnimationEase {
public init() {
}
public func perform(_ x: Double) -> Double {
if x == 0 || x == 1 { return x }
if x < 1 / 2 {
return 1 / 2 * pow(2, (20 * x) - 10)
} else {
let h = pow(2, (-20 * x) + 10)
return -1 / 2 * h + 1
}
}
}
| f4e3edf631aecde13716cd4f3ff974f2 | 18.380952 | 69 | 0.492629 | false | false | false | false |
Pursuit92/antlr4 | refs/heads/master | runtime/Swift/Antlr4/org/antlr/v4/runtime/ANTLRInputStream.swift | bsd-3-clause | 3 | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
/**
* Vacuum all input from a {@link java.io.Reader}/{@link java.io.InputStream} and then treat it
* like a {@code char[]} buffer. Can also pass in a {@link String} or
* {@code char[]} to use.
*
* <p>If you need encoding, pass in stream/reader with correct encoding.</p>
*/
public class ANTLRInputStream: CharStream {
public static let READ_BUFFER_SIZE: Int = 1024
public static let INITIAL_BUFFER_SIZE: Int = 1024
/** The data being scanned */
internal var data: [Character]
/** How many characters are actually in the buffer */
internal var n: Int
/** 0..n-1 index into string of next char */
internal var p: Int = 0
/** What is name or source of this char stream? */
public var name: String?
public init() {
n = 0
data = [Character]()
}
/** Copy data in string to a local char array */
public init(_ input: String) {
self.data = Array(input.characters) // input.toCharArray();
self.n = input.length
}
/** This is the preferred constructor for strings as no data is copied */
public init(_ data: [Character], _ numberOfActualCharsInArray: Int) {
self.data = data
self.n = numberOfActualCharsInArray
}
/*
public convenience init(_ r : Reader) throws; IOException {
self.init(r, INITIAL_BUFFER_SIZE, READ_BUFFER_SIZE);
}
public convenience init(_ r : Reader, _ initialSize : Int) throws; IOException {
self.init(r, initialSize, READ_BUFFER_SIZE);
}
public init(_ r : Reader, _ initialSize : Int, _ readChunkSize : Int) throws; IOException {
load(r, initialSize, readChunkSize);
}
public convenience init(_ input : InputStream) throws; IOException {
self.init(InputStreamReader(input), INITIAL_BUFFER_SIZE);
}
public convenience init(_ input : InputStream, _ initialSize : Int) throws; IOException {
self.init(InputStreamReader(input), initialSize);
}
public convenience init(_ input : InputStream, _ initialSize : Int, _ readChunkSize : Int) throws; IOException {
self.init(InputStreamReader(input), initialSize, readChunkSize);
}
public func load(r : Reader, _ size : Int, _ readChunkSize : Int)
throws; IOException
{
if ( r==nil ) {
return;
}
if ( size<=0 ) {
size = INITIAL_BUFFER_SIZE;
}
if ( readChunkSize<=0 ) {
readChunkSize = READ_BUFFER_SIZE;
}
// print("load "+size+" in chunks of "+readChunkSize);
try {
// alloc initial buffer size.
data = new char[size];
// read all the data in chunks of readChunkSize
var numRead : Int=0;
var p : Int = 0;
do {
if ( p+readChunkSize > data.length ) { // overflow?
// print("### overflow p="+p+", data.length="+data.length);
data = Arrays.copyOf(data, data.length * 2);
}
numRead = r.read(data, p, readChunkSize);
// print("read "+numRead+" chars; p was "+p+" is now "+(p+numRead));
p += numRead;
} while (numRead!=-1); // while not EOF
// set the actual size of the data available;
// EOF subtracted one above in p+=numRead; add one back
n = p+1;
//print("n="+n);
}
finally {
r.close();
}
}
*/
/** Reset the stream so that it's in the same state it was
* when the object was created *except* the data array is not
* touched.
*/
public func reset() {
p = 0
}
public func consume() throws {
if p >= n {
assert(LA(1) == ANTLRInputStream.EOF, "Expected: LA(1)==IntStream.EOF")
throw ANTLRError.illegalState(msg: "annot consume EOF")
}
// print("prev p="+p+", c="+(char)data[p]);
if p < n {
p += 1
//print("p moves to "+p+" (c='"+(char)data[p]+"')");
}
}
public func LA(_ i: Int) -> Int {
var i = i
if i == 0 {
return 0 // undefined
}
if i < 0 {
i += 1 // e.g., translate LA(-1) to use offset i=0; then data[p+0-1]
if (p + i - 1) < 0 {
return ANTLRInputStream.EOF// invalid; no char before first char
}
}
if (p + i - 1) >= n {
//print("char LA("+i+")=EOF; p="+p);
return ANTLRInputStream.EOF
}
//print("char LA("+i+")="+(char)data[p+i-1]+"; p="+p);
//print("LA("+i+"); p="+p+" n="+n+" data.length="+data.length);
return data[p + i - 1].unicodeValue
}
public func LT(_ i: Int) -> Int {
return LA(i)
}
/** Return the current input symbol index 0..n where n indicates the
* last symbol has been read. The index is the index of char to
* be returned from LA(1).
*/
public func index() -> Int {
return p
}
public func size() -> Int {
return n
}
/** mark/release do nothing; we have entire buffer */
public func mark() -> Int {
return -1
}
public func release(_ marker: Int) {
}
/** consume() ahead until p==index; can't just set p=index as we must
* update line and charPositionInLine. If we seek backwards, just set p
*/
public func seek(_ index: Int) throws {
var index = index
if index <= p {
p = index // just jump; don't update stream state (line, ...)
return
}
// seek forward, consume until p hits index or n (whichever comes first)
index = min(index, n)
while p < index {
try consume()
}
}
public func getText(_ interval: Interval) -> String {
let start: Int = interval.a
var stop: Int = interval.b
if stop >= n {
stop = n - 1
}
let count = stop - start + 1;
if start >= n {
return ""
}
return String(data[start ..< (start + count)])
}
public func getSourceName() -> String {
guard let name = name , !name.isEmpty else {
return ANTLRInputStream.UNKNOWN_SOURCE_NAME
}
return name
}
public func toString() -> String {
return String(data)
}
}
| 045f26d540c7db1d043fcedae1f5f3bd | 29.214286 | 117 | 0.525561 | false | false | false | false |
StorageKit/StorageKit | refs/heads/develop | Tests/Storages/Realm/RealmDataStorageTests.swift | mit | 1 | //
// RealmDataStorageTests.swift
// StorageKit
//
// Copyright (c) 2017 StorageKit (https://github.com/StorageKit)
//
// 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.
//
@testable import StorageKit
import RealmSwift
import XCTest
class RealmDataStorageTests: XCTestCase {
var sut: RealmDataStorage!
override func setUp() {
super.setUp()
var configuration = RealmDataStorage.Configuration()
configuration.ContextRepoType = SpyContextRepo.self
configuration.RealmContextType = SpyRealmContext.self
sut = RealmDataStorage(configuration: configuration)
}
override func tearDown() {
sut = nil
SpyContextRepo.clean()
SpyRealmContext.clean()
super.tearDown()
}
}
// MARK: - init
extension RealmDataStorageTests {
func test_Init_MainContextIsNotNil() {
XCTAssertNotNil(sut.mainContext)
}
func test_Init_MainContextIsRightValue() {
XCTAssertTrue(type(of: sut.mainContext!) == SpyRealmContext.self)
}
func test_Init_RealmContextTypeInitIsCalled() {
XCTAssertTrue(SpyRealmContext.isInitCalled)
}
func test_Init_RealmContextTypeInitIsCalledWithRightArgument() {
XCTAssertTrue(SpyRealmContext.initRealmTypeArgument == Realm.self)
}
func test_Init_ContextRepoInitIsCalled() {
XCTAssertTrue(SpyContextRepo.isInitCalled)
}
func test_Init_ContextRepoInitIsCalledWithRightArgument() {
XCTAssertNil(SpyContextRepo.initCleaningIntervalArgumet)
}
func test_Init_ContextRepoStoreIsCalled() {
XCTAssertTrue(SpyContextRepo.isStoreCalled)
}
func test_Init_ContextRepoStoreIsCalledWithRightArguments() {
XCTAssertTrue(SpyContextRepo.storeContextArgumet === sut.mainContext)
XCTAssertEqual(SpyContextRepo.storeQueueArgumet, .main)
}
}
// MARK: - performBackgroundTask(_:)
extension RealmDataStorageTests {
func test_PerformBackgrounTask_ClosureIsCalledInRightQueue() {
let expectation = self.expectation(description: "")
sut.performBackgroundTask { _ in
let name = __dispatch_queue_get_label(nil)
let queueName = String(cString: name, encoding: .utf8)
XCTAssertEqual(queueName, "com.StorageKit.realmDataStorage")
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func test_PerformBackgrounTask_RealmContextTypeInitIsCalled() {
SpyContextRepo.clean()
let expectation = self.expectation(description: "")
sut.performBackgroundTask { _ in
XCTAssertTrue(SpyRealmContext.isInitCalled)
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func test_PerformBackgrounTask_RealmContextTypeInitIsCalledWithRightArgument() {
SpyContextRepo.clean()
let expectation = self.expectation(description: "")
sut.performBackgroundTask { _ in
XCTAssertTrue(SpyRealmContext.initRealmTypeArgument == Realm.self)
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func test_PerformBackgrounTask_ContextRepoStoreIsCalled() {
SpyContextRepo.clean()
let expectation = self.expectation(description: "")
sut.performBackgroundTask { _ in
XCTAssertTrue(SpyContextRepo.isStoreCalled)
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func test_PerformBackgrounTask_ContextRepoStoreIsCalledWithRightArgument() {
SpyContextRepo.clean()
let expectation = self.expectation(description: "")
sut.performBackgroundTask { context in
XCTAssertTrue(SpyContextRepo.storeContextArgumet === context)
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
}
// MARK: - getThreadSafeEntities(_:)
extension RealmDataStorageTests {
func test_GetThreadSafeEntities_NoObjects_ThrowsError() {
do {
try sut.getThreadSafeEntities(for: DummyStorageContext(), originalContext: DummyStorageContext(), originalEntities: [DummyStorageEntity(), DummyStorageEntity()]) { (_: [DummyStorageEntity]) in XCTFail() }
} catch StorageKitErrors.Entity.wrongType {
XCTAssertTrue(true)
} catch { XCTFail() }
}
func test_GetThreadSafeEntities_StorageContextNotRealmContext_ThrowsError() {
do {
try sut.getThreadSafeEntities(for: DummyStorageContext(), originalContext: DummyStorageContext(), originalEntities: [Object(), Object()]) { (_: [Object]) in XCTFail() }
} catch StorageKitErrors.Context.wrongType {
XCTAssertTrue(true)
} catch { XCTFail() }
}
}
| dcd338bb56a4f8a92cb2d96770847369 | 29.220339 | 216 | 0.750795 | false | true | false | false |
ilyapuchka/GhostAPI | refs/heads/master | GhostAPI/GhostAPI/Models/Tag.swift | mit | 1 | //
// Tag.swift
// GhostAPI
//
// Created by Ilya Puchka on 30.08.15.
// Copyright © 2015 Ilya Puchka. All rights reserved.
//
import Foundation
import SwiftNetworking
public struct Tag: JSONConvertible {
public typealias Id = Int
private(set) public var id: Tag.Id!
private(set) public var uuid: NSUUID!
public let name: String
public let slug: String!
init(id: Tag.Id? = nil, uuid: NSUUID? = nil, name: String, slug: String? = nil) {
self.id = id
self.uuid = uuid
self.name = name
self.slug = slug
}
public init(name: String) {
self.init(id: nil, uuid: nil, name: name, slug: nil)
}
}
//MARK: - JSONDecodable
extension Tag {
enum Keys: String {
case id, uuid, name, slug
}
public init?(jsonDictionary: JSONDictionary?) {
guard let
json = JSONObject(jsonDictionary),
id = json[Keys.id.rawValue] as? Tag.Id,
uuid = json[Keys.uuid.rawValue] as? String,
name = json[Keys.name.rawValue] as? String,
slug = json[Keys.slug.rawValue] as? String
else {
return nil
}
self.init(id: id, uuid: NSUUID(UUIDString: uuid), name: name, slug: slug)
}
}
//MARK: - JSONEncodable
extension Tag {
public var jsonDictionary: JSONDictionary {
return [Keys.name.rawValue: name]
}
} | 7028e7513df1ab2ac36465c324359e5a | 21.967742 | 85 | 0.581167 | false | false | false | false |
Pluto-Y/SwiftyImpress | refs/heads/master | Source/Class/Transform.swift | mit | 1 | //
// Transform.swift
// SwiftyImpress
//
// Created by Pluto Y on 11/10/2016.
// Copyright © 2016 com.pluto-y. All rights reserved.
//
public extension CATransform3D {
public var scaleX: CGFloat {
let layer = CALayer()
layer.transform = self
return layer.value(forKeyPath: "transform.scale.x") as? CGFloat ?? 1.0
}
public var scaleY: CGFloat {
let layer = CALayer()
layer.transform = self
return layer.value(forKeyPath: "transform.scale.y") as? CGFloat ?? 1.0
}
public var scaleZ: CGFloat {
let layer = CALayer()
layer.transform = self
return layer.value(forKeyPath: "transform.scale.z") as? CGFloat ?? 1.0
}
public var translationX: CGFloat {
let layer = CALayer()
layer.transform = self
return layer.value(forKeyPath: "transform.translation.x") as? CGFloat ?? 0.0
}
public var translationY: CGFloat {
let layer = CALayer()
layer.transform = self
return layer.value(forKeyPath: "transform.translation.y") as? CGFloat ?? 0.0
}
public var translationZ: CGFloat {
let layer = CALayer()
layer.transform = self
return layer.value(forKeyPath: "transform.translation.z") as? CGFloat ?? 0.0
}
public var rotationX: CGFloat {
let layer = CALayer()
layer.transform = self
return ((layer.value(forKeyPath: "transform.rotation.x") as? CGFloat) ?? 0.0) * 180 / CGFloat(M_PI)
}
public var rotationY: CGFloat {
let layer = CALayer()
layer.transform = self
return (layer.value(forKeyPath: "transform.rotation.y") as? CGFloat ?? 0.0) * 180 / CGFloat(M_PI)
}
public var rotationZ: CGFloat {
let layer = CALayer()
layer.transform = self
return (layer.value(forKeyPath: "transform.rotation.z") as? CGFloat ?? 0.0) * 180 / CGFloat(M_PI)
}
public var description: String {
return "tx:\(translationX),\nty:\(translationY),\ntz:\(translationZ),\nsx:\(scaleX),\nsy:\(scaleY),\nsz:\(scaleZ),\nrx:\(rotationX),\nrx:\(rotationY),\nrz:\(rotationZ)"
}
}
public struct Axis: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static var x = Axis(rawValue: 1 << 0)
public static var y = Axis(rawValue: 1 << 1)
public static var z = Axis(rawValue: 1 << 2)
public static var all: Axis = [.x, .y, .z]
}
public enum TransformElement {
case translation(Axis, CGFloat)
case scale(Axis, CGFloat)
case rotation(Axis, CGFloat)
case transform(CATransform3D)
}
public typealias Transform = (CATransform3D) -> CATransform3D
precedencegroup SIConnectionGroup {
associativity: left
}
infix operator -->: SIConnectionGroup
public func -->(left: @escaping Transform, right: @escaping Transform) -> Transform {
return { transform in
right(left(transform))
}
}
public func translation(_ value: CGFloat, _ coordinate: Axis = .x) -> Transform {
return { transform in
guard !coordinate.contains(.all) else { return CATransform3DTranslate(transform, value, value, value) }
var transform = transform
if coordinate.contains(.x) {
transform = CATransform3DTranslate(transform, value, 0, 0)
}
if coordinate.contains(.y) {
transform = CATransform3DTranslate(transform, 0, value, 0)
}
if coordinate.contains(.z) {
transform = CATransform3DTranslate(transform, 0, 0, value)
}
return transform
}
}
public func rotation(_ angle: CGFloat, _ coordinate: Axis = .z) -> Transform {
return { transform in
guard !coordinate.contains(.all) else { return CATransform3DRotate(transform, angle, 1, 1, 1) }
var transform = transform
let value = angle / 180 * CGFloat(M_PI)
if coordinate.contains(.x) {
transform = CATransform3DRotate(transform, value, 1, 0, 0)
}
if coordinate.contains(.y) {
transform = CATransform3DRotate(transform, value, 0, 1, 0)
}
if coordinate.contains(.z) {
transform = CATransform3DRotate(transform, value, 0, 0, 1)
}
transform.m34 = -1/200.0
return transform
}
}
public func scale(_ scale: CGFloat, _ coordinate: Axis = .all) -> Transform {
return { transform in
guard !coordinate.contains(.all) else { return CATransform3DScale(transform, scale, scale, scale) }
var transform = transform
if coordinate.contains(.x) {
transform = CATransform3DScale(transform, scale, 0, 0)
}
if coordinate.contains(.y) {
transform = CATransform3DScale(transform, 0, scale, 0)
}
if coordinate.contains(.z) {
transform = CATransform3DScale(transform, 0, 0, scale)
}
return transform
}
}
public func transform(_ transform: CATransform3D) -> Transform {
return { t in
return CATransform3DConcat(transform, t)
}
}
public func pure(_ transform: CATransform3D) -> Transform {
return { t in
return CATransform3DConcat(transform, t)
}
}
public func makeTransforms(_ transforms: [Transform], from transform: CATransform3D = CATransform3DIdentity) -> CATransform3D {
return transforms.reduce(pure(CATransform3DIdentity)) { result, next in
result --> next
}(transform)
}
| 5360f4f98bc77077103904d85d2b4d01 | 29.571429 | 176 | 0.614306 | false | false | false | false |
Dwarven/ShadowsocksX-NG | refs/heads/develop | Example/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift | apache-2.0 | 5 | //
// DispatchQueueConfiguration.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/23/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Dispatch
import struct Foundation.TimeInterval
struct DispatchQueueConfiguration {
let queue: DispatchQueue
let leeway: DispatchTimeInterval
}
private func dispatchInterval(_ interval: Foundation.TimeInterval) -> DispatchTimeInterval {
precondition(interval >= 0.0)
// TODO: Replace 1000 with something that actually works
// NSEC_PER_MSEC returns 1000000
return DispatchTimeInterval.milliseconds(Int(interval * 1000.0))
}
extension DispatchQueueConfiguration {
func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
let cancel = SingleAssignmentDisposable()
self.queue.async {
if cancel.isDisposed {
return
}
cancel.setDisposable(action(state))
}
return cancel
}
func scheduleRelative<StateType>(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable {
let deadline = DispatchTime.now() + dispatchInterval(dueTime)
let compositeDisposable = CompositeDisposable()
let timer = DispatchSource.makeTimerSource(queue: self.queue)
timer.schedule(deadline: deadline, leeway: self.leeway)
// TODO:
// This looks horrible, and yes, it is.
// It looks like Apple has made a conceputal change here, and I'm unsure why.
// Need more info on this.
// It looks like just setting timer to fire and not holding a reference to it
// until deadline causes timer cancellation.
var timerReference: DispatchSourceTimer? = timer
let cancelTimer = Disposables.create {
timerReference?.cancel()
timerReference = nil
}
timer.setEventHandler(handler: {
if compositeDisposable.isDisposed {
return
}
_ = compositeDisposable.insert(action(state))
cancelTimer.dispose()
})
timer.resume()
_ = compositeDisposable.insert(cancelTimer)
return compositeDisposable
}
func schedulePeriodic<StateType>(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
let initial = DispatchTime.now() + dispatchInterval(startAfter)
var timerState = state
let timer = DispatchSource.makeTimerSource(queue: self.queue)
timer.schedule(deadline: initial, repeating: dispatchInterval(period), leeway: self.leeway)
// TODO:
// This looks horrible, and yes, it is.
// It looks like Apple has made a conceputal change here, and I'm unsure why.
// Need more info on this.
// It looks like just setting timer to fire and not holding a reference to it
// until deadline causes timer cancellation.
var timerReference: DispatchSourceTimer? = timer
let cancelTimer = Disposables.create {
timerReference?.cancel()
timerReference = nil
}
timer.setEventHandler(handler: {
if cancelTimer.isDisposed {
return
}
timerState = action(timerState)
})
timer.resume()
return cancelTimer
}
}
| 7b542face1b02e0b765d4ab48d2a6069 | 32.461538 | 164 | 0.643103 | false | false | false | false |
dasdom/Storybard2CodeApp | refs/heads/master | Storyboard2Code/Elements/Button.swift | mit | 2 | import Foundation
final class Button: View {
let buttonType: String?
private var states: [ButtonState] = []
init(id: String, buttonType: String?, elementType: ElementType, userLabel: String, properties: [Property]) {
self.buttonType = buttonType
super.init(id: id, elementType: elementType, userLabel: userLabel, properties: properties)
}
required init(dict: [String : String]) {
fatalError("init(dict:) has not been implemented")
}
override func initString(objC: Bool = false) -> String {
var string = "\(userLabel) = "
if buttonType == "roundedRect" {
string += "\(elementType.className)(type: .system)\n"
} else {
assert(false, "Not supported yet")
string += "Not supported yet"
}
return string
}
func add(state: ButtonState) {
states.append(state)
}
override func setupString(objC: Bool) -> String {
var string = super.setupString(objC: objC)
for state in states {
string += state.codeString(userLabel)
}
return string
}
}
| 1e2719e60c406183e2aefebf1d875862 | 24.309524 | 110 | 0.638758 | false | false | false | false |
TintPoint/Overlay | refs/heads/master | Sources/CustomizableProtocols/ViewCustomizable.swift | mit | 1 | //
// ViewCustomizable.swift
// Overlay
//
// Created by Justin Jia on 6/18/16.
// Copyright © 2016 TintPoint. MIT license.
//
import UIKit
/// A protocol that describes a view that can be customized.
public protocol ViewCustomizable {
/// Refreshes the view's appearance.
/// You should call this method after you:
/// 1. Created a view programmatically.
/// 2. Changed a view's states.
/// 3. Changed a view's styles.
/// - Parameter includingSubviews: A `Bool` that indicates whether the view's subviews (and subviews' subviews...) should also be refreshed.
func refresh(includingSubviews: Bool)
}
private extension ViewCustomizable {
/// Customizes the view's appearance.
func customizeView() {
customizeViewLayout()
customizeViewDesign()
customizeViewColor()
customizeViewFont()
customizeViewImage()
customizeViewText()
customizeViewTextAlignment()
}
/// Customizes the view's layout.
func customizeViewLayout() {
if let view = self as? CustomLayout {
view.customizeLayout(using: view.contentNib)
}
}
/// Customizes the view's design.
func customizeViewDesign() {
if let view = self as? CustomDesign {
view.customizeDesign(using: view.design)
}
if let view = self as? CustomActivityIndicatorViewDesign {
view.customizeActivityIndicatorViewDesign(using: view.design)
}
if let view = self as? CustomBarButtonItemDesign {
view.customizeBarButtonItemDesign(using: view.design)
}
if let view = self as? CustomBarItemDesign {
view.customizeBarItemDesign(using: view.design)
}
if let view = self as? CustomButtonDesign {
view.customizeButtonDesign(using: view.design)
}
if let view = self as? CustomCollectionViewDesign {
view.customizeCollectionViewDesign(using: view.design)
}
if let view = self as? CustomControlDesign {
view.customizeControlDesign(using: view.design)
}
if let view = self as? CustomDatePickerDesign {
view.customizeDatePickerDesign(using: view.design)
}
if let view = self as? CustomImageViewDesign {
view.customizeImageViewDesign(using: view.design)
}
if let view = self as? CustomLabelDesign {
view.customizeLabelDesign(using: view.design)
}
if let view = self as? CustomNavigationBarDesign {
view.customizeNavigationBarDesign(using: view.design)
}
if let view = self as? CustomPageControlDesign {
view.customizePageControlDesign(using: view.design)
}
if let view = self as? CustomPickerViewDesign {
view.customizePickerViewDesign(using: view.design)
}
if let view = self as? CustomProgressViewDesign {
view.customizeProgressViewDesign(using: view.design)
}
if let view = self as? CustomScrollViewDesign {
view.customizeScrollViewDesign(using: view.design)
}
if let view = self as? CustomSearchBarDesign {
view.customizeSearchBarDesign(using: view.design)
}
if let view = self as? CustomSegmentedControlDesign {
view.customizeSegmentedControlDesign(using: view.design)
}
if let view = self as? CustomSliderDesign {
view.customizeSliderDesign(using: view.design)
}
if let view = self as? CustomStackViewDesign {
view.customizeStackViewDesign(using: view.design)
}
if let view = self as? CustomStepperDesign {
view.customizeStepperDesign(using: view.design)
}
if let view = self as? CustomSwitchDesign {
view.customizeSwitchDesign(using: view.design)
}
if let view = self as? CustomTabBarDesign {
view.customizeTabBarDesign(using: view.design)
}
if let view = self as? CustomTabBarItemDesign {
view.customizeTabBarItemDesign(using: view.design)
}
if let view = self as? CustomTableViewDesign {
view.customizeTableViewDesign(using: view.design)
}
if let view = self as? CustomTextFieldDesign {
view.customizeTextFieldDesign(using: view.design)
}
if let view = self as? CustomTextViewDesign {
view.customizeTextViewDesign(using: view.design)
}
if let view = self as? CustomToolbarDesign {
view.customizeToolbarDesign(using: view.design)
}
if let view = self as? CustomViewDesign {
view.customizeViewDesign(using: view.design)
}
if let view = self as? CustomWebViewDesign {
view.customizeWebViewDesign(using: view.design)
}
}
/// Customizes the view's colors.
func customizeViewColor() {
guard self is ColorStyleRepresentable else {
return
}
if let view = self as? CustomBackgroundColor {
view.customizeBackgroundColor(using: view.backgroundColorStyle)
}
if let view = self as? CustomBadgeColor {
view.customizeBadgeColor(using: view.badgeColorStyle)
}
if let view = self as? CustomBarTintColor {
view.customizeBarTintColor(using: view.barTintColorStyle)
}
if let view = self as? CustomBorderColor {
view.customizeBorderColor(using: view.borderColorStyle)
}
if let view = self as? CustomColor {
view.customizeColor(using: view.colorStyle)
}
if let view = self as? CustomMaximumTrackTintColor {
view.customizeMaximumTrackTintColor(using: view.maximumTrackTintColorStyle)
}
if let view = self as? CustomMinimumTrackTintColor {
view.customizeMinimumTrackTintColor(using: view.minimumTrackTintColorStyle)
}
if let view = self as? CustomOnTintColor {
view.customizeOnTintColor(using: view.onTintColorStyle)
}
if let view = self as? CustomPlaceholderTextColor {
view.customizePlaceholderTextColor(using: view.placeholderTextColorStyle)
}
if let view = self as? CustomProgressTintColor {
view.customizeProgressTintColor(using: view.progressTintColorStyle)
}
if let view = self as? CustomSectionIndexBackgroundColor {
view.customizeSectionIndexBackgroundColor(using: view.sectionIndexBackgroundColorStyle)
}
if let view = self as? CustomSectionIndexColor {
view.customizeSectionIndexColor(using: view.sectionIndexColorStyle)
}
if let view = self as? CustomSectionIndexTrackingBackgroundColor {
view.customizeSectionIndexTrackingBackgroundColor(using: view.sectionIndexTrackingBackgroundColorStyle)
}
if let view = self as? CustomSeparatorColor {
view.customizeSeparatorColor(using: view.separatorColorStyle)
}
if let view = self as? CustomShadowColor {
view.customizeShadowColor(using: view.shadowColorStyle)
}
if let view = self as? CustomTextColor {
view.customizeTextColor(using: view.textColorStyle)
}
if let view = self as? CustomThumbTintColor {
view.customizeThumbTintColor(using: view.thumbTintColorStyle)
}
if let view = self as? CustomTintColor {
view.customizeTintColor(using: view.tintColorStyle)
}
if let view = self as? CustomTitleColor {
view.customizeTitleColor(using: view.titleColorStyle)
}
if let view = self as? CustomTitleShadowColor {
view.customizeTitleShadowColor(using: view.titleShadowColorStyle)
}
if let view = self as? CustomTrackTintColor {
view.customizeTrackTintColor(using: view.trackTintColorStyle)
}
if let view = self as? CustomUnselectedItemTintColor {
view.customizeUnselectedItemTintColor(using: view.unselectedItemTintColorStyle)
}
}
/// Customizes the view's fonts.
func customizeViewFont() {
guard self is FontStyleRepresentable else {
return
}
if let view = self as? CustomTitleFont {
view.customizeTitleFont(using: view.titleFontStyle)
}
if let view = self as? CustomFont {
view.customizeFont(using: view.fontStyle)
}
}
/// Customizes the view's images.
func customizeViewImage() {
guard self is ImageStyleRepresentable else {
return
}
if let view = self as? CustomBackgroundImage {
view.customizeBackgroundImage(using: view.backgroundImageStyle)
}
if let view = self as? CustomDecrementImage {
view.customizeDecrementImage(using: view.decrementImageStyle)
}
if let view = self as? CustomHighlightedImage {
view.customizeHighlightedImage(using: view.highlightedImageStyle)
}
if let view = self as? CustomImage {
view.customizeImage(using: view.imageStyle)
}
if let view = self as? CustomIncrementImage {
view.customizeIncrementImage(using: view.incrementImageStyle)
}
if let view = self as? CustomLandscapeImagePhone {
view.customizeLandscapeImagePhone(using: view.landscapeImagePhoneStyle)
}
if let view = self as? CustomMaximumTrackImage {
view.customizeMaximumTrackImage(using: view.maximumTrackImageStyle)
}
if let view = self as? CustomMaximumValueImage {
view.customizeMaximumValueImage(using: view.maximumValueImageStyle)
}
if let view = self as? CustomMinimumTrackImage {
view.customizeMinimumTrackImage(using: view.minimumTrackImageStyle)
}
if let view = self as? CustomMinimumValueImage {
view.customizeMinimumValueImage(using: view.minimumValueImageStyle)
}
if let view = self as? CustomOffImage {
view.customizeOffImage(using: view.offImageStyle)
}
if let view = self as? CustomOnImage {
view.customizeOnImage(using: view.onImageStyle)
}
if let view = self as? CustomProgressImage {
view.customizeProgressImage(using: view.progressImageStyle)
}
if let view = self as? CustomScopeBarButtonBackgroundImage {
view.customizeScopeBarButtonBackgroundImage(using: view.scopeBarButtonBackgroundImageStyle)
}
if let view = self as? CustomSearchFieldBackgroundImage {
view.customizeSearchFieldBackgroundImage(using: view.searchFieldBackgroundImageStyle)
}
if let view = self as? CustomSelectedImage {
view.customizeSelectedImage(using: view.selectedImageStyle)
}
if let view = self as? CustomShadowImage {
view.customizeShadowImage(using: view.shadowImageStyle)
}
if let view = self as? CustomThumbImage {
view.customizeThumbImage(using: view.thumbImageStyle)
}
if let view = self as? CustomTrackImage {
view.customizeTrackImage(using: view.trackImageStyle)
}
}
/// Customizes the view's texts.
func customizeViewText() {
guard self is TextStyleRepresentable else {
return
}
if let view = self as? CustomPlaceholder {
view.customizePlaceholder(using: view.placeholderStyle)
}
if let view = self as? CustomPrompt {
view.customizePrompt(using: view.promptStyle)
}
if let view = self as? CustomSegmentTitles {
view.customizeSegmentTitles(using: view.segmentTitleStyles)
}
if let view = self as? CustomScopeButtonTitles {
view.customizeScopeButtonTitles(using: view.scopeButtonTitleStyles)
}
if let view = self as? CustomText {
view.customizeText(using: view.textStyle)
}
if let view = self as? CustomTitle {
view.customizeTitle(using: view.titleStyle)
}
}
/// Customizes the view's text alignments.
func customizeViewTextAlignment() {
guard self is TextAlignmentStyleRepresentable else {
return
}
if let view = self as? CustomTitleTextAlignment {
view.customizeTitleTextAlignment(using: view.titleTextAlignmentStyle)
}
if let view = self as? CustomTextAlignment {
view.customizeTextAlignment(using: view.textAlignmentStyle)
}
}
}
extension UIView: ViewCustomizable {
open override func awakeFromNib() {
super.awakeFromNib()
refresh()
}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
refresh()
}
public func refresh(includingSubviews: Bool = false) {
customizeView()
if includingSubviews {
for subview in subviews {
subview.refresh(includingSubviews: true)
}
}
}
}
extension UIBarItem: ViewCustomizable {
open override func awakeFromNib() {
super.awakeFromNib()
refresh()
}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
refresh()
}
public func refresh(includingSubviews: Bool = false) {
customizeView()
}
}
| 54111c2b76cc6869d5453e79c9519add | 30.505747 | 144 | 0.634075 | false | false | false | false |
Zewo/Zeal | refs/heads/master | Zeal/HTTPClient/HTTPSerializer.swift | mit | 1 | // HTTPSerializer.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 URI
import HTTP
struct HTTPSerializer: HTTPRequestSerializerType {
func serializeRequest(client: TCPStreamType, request: HTTPRequest, completion: (Void throws -> Void) -> Void) {
var string = "\(request.method) \(request.uri) HTTP/\(request.majorVersion).\(request.minorVersion)\r\n"
for (name, value) in request.headers {
string += "\(name): \(value)\r\n"
}
string += "\r\n"
var data = string.utf8.map { Int8($0) }
data += request.body
client.send(data, completion: completion)
}
}
| 1f45386d3d1583ed68fe170c8b8b55f2 | 39.209302 | 115 | 0.711972 | false | false | false | false |
jmkr/SimpleAssetPicker | refs/heads/master | SimpleAssetPicker/AssetCollectionViewCell.swift | mit | 1 | //
// AssetCollectionViewCell.swift
// SimpleAssetPicker
//
// Created by John Meeker on 6/27/16.
// Copyright © 2016 John Meeker. All rights reserved.
//
import UIKit
import PureLayout
class AssetCollectionViewCell: UICollectionViewCell {
var representedAssetIdentifier: String = ""
fileprivate var didSetupConstraints: Bool = false
lazy var imageView: UIImageView! = {
let imageView = UIImageView.newAutoLayout()
imageView.contentMode = .scaleAspectFill
return imageView
}()
lazy var gradientView: GradientView! = {
return GradientView.newAutoLayout()
}()
lazy var checkMarkImageView: UIImageView! = {
let imageView = UIImageView.newAutoLayout()
imageView.alpha = 0.0
return imageView
}()
lazy var livePhotoBadgeImageView: UIImageView! = {
return UIImageView.newAutoLayout()
}()
lazy var cameraIconImageView: UIImageView! = {
return UIImageView.newAutoLayout()
}()
lazy var videoLengthLabel: UILabel! = {
let label = UILabel.newAutoLayout()
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 13.0)
return label
}()
override func prepareForReuse() {
super.prepareForReuse()
self.imageView.image = nil
self.livePhotoBadgeImageView.image = nil
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
updateConstraints()
}
fileprivate func setupViews() {
self.clipsToBounds = true
self.backgroundColor = .white
self.addSubview(self.imageView)
self.addSubview(self.gradientView)
self.addSubview(self.checkMarkImageView)
self.addSubview(self.livePhotoBadgeImageView)
self.addSubview(self.cameraIconImageView)
self.addSubview(self.videoLengthLabel)
}
override var isSelected: Bool {
get {
return super.isSelected
}
set {
if newValue {
super.isSelected = true
self.imageView.alpha = 0.6
UIView.animate(withDuration: 0.1, delay: 0.0, options: [.curveEaseIn, .allowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: 0.98, y: 0.98)
self.checkMarkImageView.alpha = 1.0
}, completion: { (finished) -> Void in
UIView.animate(withDuration: 0.1, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransform.identity
}, completion:nil)
})
} else if newValue == false {
super.isSelected = false
self.imageView.alpha = 1.0
UIView.animate(withDuration: 0.1, delay: 0.0, options: [.curveEaseIn, .allowUserInteraction], animations: { () -> Void in
//self.transform = CGAffineTransformMakeScale(1.02, 1.02)
self.checkMarkImageView.alpha = 0.0
}, completion: { (finished) -> Void in
UIView.animate(withDuration: 0.1, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransform.identity
}, completion:nil)
})
}
}
}
override func updateConstraints() {
if !didSetupConstraints {
self.imageView.autoPinEdgesToSuperviewEdges()
self.gradientView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .top)
self.gradientView.autoSetDimension(.height, toSize: 30)
self.checkMarkImageView.autoPinEdge(toSuperviewEdge: .top, withInset: 4)
self.checkMarkImageView.autoPinEdge(toSuperviewEdge: .right, withInset: 4)
self.checkMarkImageView.autoSetDimensions(to: CGSize(width: 18, height: 18))
self.livePhotoBadgeImageView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 4)
self.livePhotoBadgeImageView.autoPinEdge(toSuperviewEdge: .left, withInset: 4)
self.livePhotoBadgeImageView.autoSetDimensions(to: CGSize(width: 20, height: 20))
self.cameraIconImageView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 4)
self.cameraIconImageView.autoPinEdge(toSuperviewEdge: .left, withInset: 4)
self.cameraIconImageView.autoSetDimensions(to: CGSize(width: 20, height: 17))
self.videoLengthLabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: 4)
self.videoLengthLabel.autoPinEdge(toSuperviewEdge: .right, withInset: 4)
didSetupConstraints = true
}
super.updateConstraints()
}
func getTimeStringOfTimeInterval(_ timeInterval: TimeInterval) -> String {
let ti = NSInteger(timeInterval)
let seconds = ti % 60
let minutes = (ti / 60) % 60
let hours = (ti / 3600)
if hours > 0 {
return String(format: "%0.d:%0.d:%0.2d",hours,minutes,seconds)
} else if minutes > 0 {
return String(format: "%0.d:%0.2d",minutes,seconds)
} else {
return String(format: "0:%0.2d",seconds)
}
}
}
| 29f765279b9f88f1e21d60dfdad8c2a0 | 35.516556 | 146 | 0.60827 | false | false | false | false |
CM-Studio/NotLonely-iOS | refs/heads/master | NotLonely-iOS/ViewController/Find/FindViewController.swift | mit | 1 | //
// FindViewController.swift
// NotLonely-iOS
//
// Created by plusub on 3/24/16.
// Copyright © 2016 cm. All rights reserved.
//
import UIKit
class FindViewController: BaseViewController {
var overlay: UIView!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 160.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension FindViewController: UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("InterestPeopleCell", forIndexPath: indexPath)
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("InterestCircleCell", forIndexPath: indexPath)
return cell
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 6
} else {
return 4
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
} | 96d8a62169a7505208e37a526c1753ca | 27.37037 | 113 | 0.653821 | false | false | false | false |
aiqiuqiu/Tuan | refs/heads/master | Tuan/Deal/HMSortsViewController.swift | mit | 2 | //
// HMSortsViewController.swift
// Tuan
//
// Created by nero on 15/5/15.
// Copyright (c) 2015年 nero. All rights reserved.
//
import UIKit
class HMSortButton:UIButton {
var sort:HMSort = HMSort() {
willSet {
self.title = newValue.label
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.bgImage = "btn_filter_normal"
self.selectedBgImage = "btn_filter_selected"
self.titleColor = UIColor.blackColor()
self.selectedTitleColor = UIColor.whiteColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class HMSortsViewController: UIViewController {
var seletedButton:HMSortButton?
override func viewDidLoad() {
super.viewDidLoad()
// 设置在popover中的尺寸
self.preferredContentSize = self.view.size;
// 根据排序模型的个数,创建对应的按钮
let buttonX:CGFloat = 20.0
let buttonW = view.width - 2 * buttonX
let buttonP:CGFloat = 15
var sorts = HMMetaDataTool.sharedMetaDataTool().sorts as! Array<HMSort>
var contentH:CGFloat = 0
for i in 0 ..< sorts.count {
// 创建按钮
let button = HMSortButton(frame: CGRectZero)
// 取出模型
button.sort = sorts[i]
// 设置尺寸
button.x = buttonX
button.width = buttonW
button.height = 30
button.y = buttonP + CGFloat(i) * ( button.height + buttonP)
button.addTarget(self, action: Selector("sortButtonClick:"), forControlEvents: UIControlEvents.TouchDown)
view.addSubview(button)
contentH = button.maxX + buttonP
}
// // 设置contentSize
let scrollview = self.view as! UIScrollView
scrollview.contentSize = CGSize(width: 0, height: contentH)
}
func sortButtonClick(button:HMSortButton) {
self.seletedButton?.selected = false
button.selected = true
self.seletedButton = button
// 2.发出通知
HMNotificationCenter.postNotificationName(HMSortNotification.HMSortDidSelectNotification, object: nil, userInfo: [HMSortNotification.HMSelectedSort:button.sort])
}
/** 当前选中的排序 */
// @property (strong, nonatomic) HMSort *selectedSort;
var selectedSort:HMSort! {
willSet {
//
if newValue == nil {return }
let subview = self.view.subviews
for button in subview{
if let sortButton = button as? HMSortButton {
if sortButton.sort == newValue {
seletedButton?.selected = false
sortButton.selected = true
seletedButton = sortButton
}
}
}
}
}
}
| 63fe8311e6f2b67b20dda31464062390 | 28.262626 | 169 | 0.571626 | false | false | false | false |
kouky/ORSSerialPort | refs/heads/master | Examples/RequestResponseDemo/Swift/Sources/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// RequestResponseDemo
//
// Created by Andrew Madsen on 3/14/15.
// Copyright (c) 2015 Open Reel Software. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Cocoa
import ORSSerial
class MainViewController: NSViewController {
@IBOutlet weak var temperaturePlotView: TemperaturePlotView!
let serialPortManager = ORSSerialPortManager.sharedSerialPortManager()
let boardController = SerialBoardController()
override func viewDidLoad() {
self.boardController.addObserver(self, forKeyPath: "temperature", options: NSKeyValueObservingOptions(), context: MainViewControllerKVOContext)
}
// MARK: KVO
let MainViewControllerKVOContext = UnsafeMutablePointer<()>()
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context != MainViewControllerKVOContext {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
if object as! NSObject == self.boardController && keyPath == "temperature" {
self.temperaturePlotView.addTemperature(self.boardController.temperature)
}
}
}
| f604981d56309c87791ef625b8243c12 | 40.388889 | 154 | 0.77047 | false | false | false | false |
Yummypets/YPImagePicker | refs/heads/master | Source/Configuration/YPColors.swift | mit | 1 | //
// YPColors.swift
// YPImagePicker
//
// Created by Nik Kov || nik-kov.com on 13.04.2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
public struct YPColors {
// MARK: - Common
/// The common tint color which is used for done buttons in navigation bar, multiple items selection and so on.
public var tintColor = UIColor.ypSystemBlue
/// A color for navigation bar spinner.
/// Default is nil, which is default iOS gray UIActivityIndicator.
public var navigationBarActivityIndicatorColor: UIColor?
/// A color for circle for selected items in multiple selection
/// Default is nil, which takes tintColor.
public var multipleItemsSelectedCircleColor: UIColor?
/// The background color of the bottom of photo and video screens.
public var photoVideoScreenBackgroundColor: UIColor = .offWhiteOrBlack
/// The background color of the library and space between collection view cells.
public var libraryScreenBackgroundColor: UIColor = .offWhiteOrBlack
/// The background color of safe area. For example under the menu items.
public var safeAreaBackgroundColor: UIColor = .offWhiteOrBlack
/// A color for background of the asset container. You can see it when bouncing the image.
public var assetViewBackgroundColor: UIColor = .offWhiteOrBlack
/// A color for background in filters.
public var filterBackgroundColor: UIColor = .offWhiteOrBlack
/// A color for background in selections gallery. When multiple items selected.
public var selectionsBackgroundColor: UIColor = .offWhiteOrBlack
/// A color for bottom buttons (photo, video, all photos).
public var bottomMenuItemBackgroundColor: UIColor = .clear
/// A color for for bottom buttons selected text.
public var bottomMenuItemSelectedTextColor: UIColor = .ypLabel
/// A color for for bottom buttons not selected text.
public var bottomMenuItemUnselectedTextColor: UIColor = .ypSecondaryLabel
/// The color of the crop overlay.
public var cropOverlayColor: UIColor = UIColor.ypSystemBackground.withAlphaComponent(0.4)
/// The default color of all navigation bars except album's.
public var defaultNavigationBarColor: UIColor = .offWhiteOrBlack
// MARK: - Trimmer
/// The color of the main border of the view
public var trimmerMainColor: UIColor = .ypLabel
/// The color of the handles on the side of the view
public var trimmerHandleColor: UIColor = .ypSystemBackground
/// The color of the position indicator
public var positionLineColor: UIColor = .ypSystemBackground
// MARK: - Cover selector
/// The color of the cover selector border
public var coverSelectorBorderColor: UIColor = .offWhiteOrBlack
// MARK: - Progress bar
/// The color for the progress bar when processing video or images. The all track color.
public var progressBarTrackColor: UIColor = .ypSystemBackground
/// The color of completed track for the progress bar
public var progressBarCompletedColor: UIColor?
/// The color of the Album's NavigationBar background
public var albumBarTintColor: UIColor = .ypSystemBackground
/// The color of the Album's left and right items color
public var albumTintColor: UIColor = .ypLabel
/// The color of the Album's title color
public var albumTitleColor: UIColor = .ypLabel
}
| d7ee16b89ffe16e4bde338702d61952b | 39.05814 | 115 | 0.725109 | false | false | false | false |
amraboelela/swift | refs/heads/master | test/SILGen/external-keypath.swift | apache-2.0 | 4 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -enable-resilience -emit-module -o %t/ExternalKeyPaths.swiftmodule -module-name ExternalKeyPaths %S/Inputs/ExternalKeyPaths.swift
// RUN: %target-swift-emit-silgen -swift-version 5 -I %t %s | %FileCheck %s
import ExternalKeyPaths
struct Local {
var x: Int
var y: String
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}16externalKeyPaths
func externalKeyPaths<T: Hashable, U>(_ x: T, _ y: U, _ z: Int) {
// CHECK: keypath $WritableKeyPath<External<Int>, Int>, (root $External<Int>; {{.*}} external #External.property<Int>)
_ = \External<Int>.property
// CHECK: keypath $WritableKeyPath<External<Int>, Int>, (root $External<Int>; {{.*}} external #External.intProperty<Int>)
_ = \External<Int>.intProperty
// CHECK: keypath $WritableKeyPath<External<T>, T>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_0>; {{.*}} external #External.property<T>) <T, U>
_ = \External<T>.property
// CHECK: keypath $WritableKeyPath<External<T>, Int>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_0>; {{.*}} external #External.intProperty<T>) <T, U>
_ = \External<T>.intProperty
// CHECK: keypath $WritableKeyPath<External<U>, U>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_1>; {{.*}} external #External.property<U>) <T, U>
_ = \External<U>.property
// CHECK: keypath $WritableKeyPath<External<U>, Int>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_1>; {{.*}} external #External.intProperty<U>) <T, U>
_ = \External<U>.intProperty
// CHECK: keypath $KeyPath<External<Int>, Int>, (root $External<Int>; {{.*}} external #External.subscript<Int, Int>) (%2)
_ = \External<Int>.[z]
// CHECK: keypath $KeyPath<External<T>, T>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_0>; {{.*}} external #External.subscript<T, T>) <T, U> ({{.*}})
_ = \External<T>.[x]
// CHECK: keypath $KeyPath<External<U>, U>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_1>; {{.*}} external #External.subscript<U, T>) <T, U> ({{.*}})
_ = \External<U>.[x]
// CHECK: keypath $KeyPath<External<Local>, Int>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (
// CHECK-SAME: root $External<Local>;
// CHECK-SAME: external #External.subscript<Local, T>
// CHECK-SAME: stored_property #Local.x : $Int) <T, U> ({{.*}})
_ = \External<Local>.[x].x
// CHECK: keypath $KeyPath<External<Local>, String>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (
// CHECK-SAME: root $External<Local>;
// CHECK-SAME: external #External.subscript<Local, T>
// CHECK-SAME: stored_property #Local.y : $String) <T, U> ({{.*}})
_ = \External<Local>.[x].y
// CHECK: keypath $KeyPath<ExternalEmptySubscript, Int>, (
// CHECK-SAME: root $ExternalEmptySubscript;
// CHECK-SAME: external #ExternalEmptySubscript.subscript
_ = \ExternalEmptySubscript.[]
// CHECK: keypath $KeyPath<External<Int>, Int>, (
// CHECK-SAME: root $External<Int>;
// CHECK-SAME: gettable_property
// CHECK-SAME: external #External.privateSetProperty
_ = \External<Int>.privateSetProperty
// CHECK: keypath $KeyPath<External<Int>, Int>, (
// CHECK-SAME: root $External<Int>;
// CHECK-SAME: gettable_property
// CHECK-SAME: external #External.subscript
_ = \External<Int>.[privateSet: 0]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}testProtocolRequirement
func testProtocolRequirement<T: ExternalProto>(_: T.Type) {
// CHECK: keypath $WritableKeyPath<T, Int>,
// CHECK-NOT: external #ExternalProto.protoReqt
_ = \T.protoReqt
}
| c59ce8bbf52f0a6f02242693c469cdb3 | 45.552632 | 166 | 0.647258 | false | false | false | false |
tristanchu/FlavorFinder | refs/heads/master | FlavorFinder/FlavorFinder/RegisterView.swift | mit | 1 | //
// RegisterView.swift
// FlavorFinder
//
// Handles the register view for within the container
//
// Created by Courtney Ligh on 2/1/16.
// Copyright © 2016 TeamFive. All rights reserved.
//
import Foundation
import UIKit
import Parse
class RegisterView : UIViewController, UITextFieldDelegate {
// Navigation in containers (set during segue)
var buttonSegue : String!
// MARK: messages ------------------------------------
// validation error messages
let EMAIL_INVALID = "That doesn't look like an email!"
let USERNAME_INVALID = "Usernames must be between \(USERNAME_CHAR_MIN) and \(USERNAME_CHAR_MAX) characters."
let PASSWORD_INVALID = "Passwords must be between \(PASSWORD_CHAR_MIN) and \(PASSWORD_CHAR_MAX) characters."
let PW_MISMATCH = "Passwords don't match!"
let MULTIPLE_INVALID = "Please fix errors and resubmit."
// request error messages
let REQUEST_ERROR_TITLE = "Uhoh!"
let GENERIC_ERROR = "Oops! An error occurred on the server. Please try again."
let USERNAME_IN_USE = "That username is already in use. Please pick a new one!"
let EMAIL_IN_USE = "Email already associated with an account!"
// Toast Text:
let REGISTERED_MSG = "Registed new user " // + username dynamically
// MARK: Properties -----------------------------------
// Text Labels:
@IBOutlet weak var signUpPromptLabel: UILabel!
@IBOutlet weak var warningTextLabel: UILabel!
// Text Fields:
@IBOutlet weak var usernameSignUpField: UITextField!
@IBOutlet weak var pwSignUpField: UITextField!
@IBOutlet weak var retypePwSignUpField: UITextField!
@IBOutlet weak var emailSignUpField: UITextField!
// Buttons (for UI)
@IBOutlet weak var backToLoginButton: UIButton!
@IBOutlet weak var createAccountButton: UIButton!
let backBtnString =
String.fontAwesomeIconWithName(.ChevronLeft) + " Back to login"
// MARK: Actions -----------------------------------
@IBAction func createAccountAction(sender: AnyObject) {
if (emailSignUpField.text != nil && usernameSignUpField.text != nil &&
pwSignUpField.text != nil && retypePwSignUpField.text != nil) {
// Make request:
requestNewUser(emailSignUpField.text!,
username: usernameSignUpField.text!,
password: pwSignUpField.text!,
pwRetyped: retypePwSignUpField.text!)
// request new user calls on success
}
}
@IBAction func backToLoginAction(sender: AnyObject) {
if let parent = parentViewController as? ContainerViewController {
parent.segueIdentifierReceivedFromParent(buttonSegue)
}
}
// MARK: Override Functions --------------------------
/* viewDidLoad
called when app first loads view
*/
override func viewDidLoad() {
super.viewDidLoad()
// Set font awesome chevron:
backToLoginButton.setTitle(backBtnString, forState: .Normal)
// set up text fields:
setUpTextField(usernameSignUpField)
setUpTextField(pwSignUpField)
setUpTextField(retypePwSignUpField)
setUpTextField(emailSignUpField)
// set border button:
setDefaultButtonUI(createAccountButton)
}
// MARK: Functions ------------------------------------
/* setUpTextField
assigns delegate, sets left padding to 5
*/
func setUpTextField(field: UITextField) {
field.delegate = self
field.setTextLeftPadding(5)
}
/* requestNewUser
requests that Parse creates a new user
*/
func requestNewUser(email: String, username: String, password: String, pwRetyped: String) -> PFUser? {
if fieldsAreValid(email, username: username, password: password, pwRetyped: pwRetyped) {
let newUser = PFUser()
newUser.username = username
newUser.email = email
newUser.password = password
newUser.signUpInBackgroundWithBlock { (succeeded, error) -> Void in
if error == nil {
if succeeded {
self.registerSuccess(newUser)
} else {
self.handleError(error)
}
} else {
self.handleError(error)
}
}
return newUser
}
return nil
}
/* fieldsAreValid
checks if entered fields are valid input
*/
func fieldsAreValid(email: String, username: String, password: String, pwRetyped: String) -> Bool {
if isInvalidUsername(username) {
alertUserBadInput(USERNAME_INVALID)
return false
}
if isInvalidPassword(password) {
alertUserBadInput(PASSWORD_INVALID)
return false
}
if pwRetyped.isEmpty {
alertUserBadInput(PW_MISMATCH)
return false
}
if password != pwRetyped {
alertUserBadInput(PW_MISMATCH)
return false
}
if isInvalidEmail(email) {
alertUserBadInput( EMAIL_INVALID)
return false
}
return true
}
/* registerSuccess
actually registers user
*/
func registerSuccess(user: PFUser) {
setUserSession(user)
if let parentVC = self.parentViewController?.parentViewController as! LoginModuleParentViewController? {
if isUserLoggedIn() {
let registeredMsg = self.REGISTERED_MSG + "\(currentUser!.username!)"
parentVC.view.makeToast(registeredMsg, duration: TOAST_DURATION, position: .Bottom)
}
parentVC.loginSucceeded()
}
}
/* handleError
let us know if there is a parse error
*/
func handleError(error: NSError?) {
if let error = error {
print("\(error)")
// error - username already in use:
if error.code == 202 {
alertUserRegisterError(USERNAME_IN_USE)
// error - email already in use
} else if error.code == 203 {
alertUserRegisterError(EMAIL_IN_USE)
// error - generic error
} else {
alertUserRegisterError(GENERIC_ERROR)
}
} else {
print("nil error")
}
}
/* alertUserBadInput
creates popup alert for when user submits bad input
- helper function to make above code cleaner:
*/
func alertUserBadInput(title: String) {
alertPopup(title, msg: self.MULTIPLE_INVALID,
actionTitle: OK_TEXT, currController: self)
}
/* alertUserRegisterError
- helper function to create alert when parse rejects registration
*/
func alertUserRegisterError(msg: String){
alertPopup(self.REQUEST_ERROR_TITLE , msg: msg,
actionTitle: OK_TEXT, currController: self)
}
}
| e763b96f698118ce1db154cfd0d48eac | 32.674641 | 112 | 0.595482 | false | false | false | false |
kzaher/RxFeedback | refs/heads/master | Examples/Support/UIAlertController+Prompt.swift | mit | 1 | //
// UIAlertController+Prompt.swift
// RxFeedback
//
// Created by Krunoslav Zaher on 5/11/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import UIKit
import RxSwift
public protocol ActionConvertible: CustomStringConvertible {
var style: UIAlertAction.Style { get }
}
extension UIAlertController {
public static func prompt<T: ActionConvertible>(
message: String,
title: String?,
actions: [T],
parent: UIViewController,
type: UIAlertController.Style = .alert,
configure: @escaping (UIAlertController) -> () = { _ in }
) -> Observable<(UIAlertController, T)> {
return Observable.create { observer in
let promptController = UIAlertController(title: title, message: message, preferredStyle: type)
for action in actions {
let action = UIAlertAction(title: action.description, style: action.style, handler: { [weak promptController] alertAction -> Void in
guard let controller = promptController else {
return
}
observer.on(.next((controller, action)))
observer.on(.completed)
})
promptController.addAction(action)
}
configure(promptController)
parent.present(promptController, animated: true, completion: nil)
return Disposables.create()
}
}
}
public enum AlertAction {
case ok
case cancel
case delete
case confirm
}
extension AlertAction : ActionConvertible {
public var description: String {
switch self {
case .ok:
return NSLocalizedString("OK", comment: "Ok action for the alert controller")
case .cancel:
return NSLocalizedString("Cancel", comment: "Cancel action for the alert controller")
case .delete:
return NSLocalizedString("Delete", comment: "Delete action for the alert controller")
case .confirm:
return NSLocalizedString("Confirm", comment: "Confirm action for the alert controller")
}
}
public var style: UIAlertAction.Style {
switch self {
case .ok:
return .`default`
case .cancel:
return .cancel
case .delete:
return .destructive
case .confirm:
return .`default`
}
}
}
| 51755508582816521caf1234e6d52a7a | 29.1625 | 148 | 0.606714 | false | false | false | false |
yarshure/Surf | refs/heads/UIKitForMac | SurfToday/TodayViewController.swift | bsd-3-clause | 1 | //
// TodayViewController.swift
// SurfToday
//
// Created by networkextension on 16/2/9.
// Copyright © 2016年 yarshure. All rights reserved.
//
import UIKit
import NotificationCenter
import NetworkExtension
import SwiftyJSON
import DarwinCore
import SFSocket
import Crashlytics
import Fabric
import Charts
import XRuler
import Xcon
class StatusConnectedCell:UITableViewCell {
@IBOutlet weak var configLabel: UILabel!
@IBOutlet weak var statusSwitch: UISwitch!
@IBOutlet weak var speedContainView:UIView!
@IBOutlet weak var downLabel: UILabel!
@IBOutlet weak var upLabel: UILabel!
@IBOutlet weak var downSpeedLabel: UILabel!
@IBOutlet weak var upSpeedLabel: UILabel!
@IBOutlet weak var cellLabel: UILabel!
@IBOutlet weak var wifiLabel: UILabel!
@IBOutlet weak var cellInfoLabel: UILabel!
@IBOutlet weak var wifiInfoLabel: UILabel!
}
class ProxyGroupCell:UITableViewCell {
@IBOutlet weak var configLabel: UILabel!
@IBOutlet weak var starView: UIImageView!
}
import Reachability
func version() ->Int {
return 10
}
class TodayViewController: SFTableViewController, NCWidgetProviding {
//@IBOutlet weak var tableView: UITableView!
var appearDate:Date = Date()
@IBOutlet var chartsView:ChartsView!
var config:String = ""
var proxyConfig:String = ""
var sysVersion = 10 //sysVersion()
var report:SFVPNStatistics = SFVPNStatistics.shared
var proxyGroup:ProxyGroupSettings!
var showServerHost = false
var lastTraffic:STTraffic = DataCounters("240.7.1.9")
var timer:Timer?
let dnsqueue:DispatchQueue = DispatchQueue(label: "com.abigt.dns")
var autoRedail = false
let reachability = Reachability()!
var charts:[Double] = []
override init(style: UITableView.Style) {
super.init(style: style)
prepareApp()
self.proxyGroup = ProxyGroupSettings.share
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
prepareApp()
self.proxyGroup = ProxyGroupSettings.share
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareApp()
self.proxyGroup = ProxyGroupSettings.share
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 66.0
}else {
return 44.0
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let ext = self.extensionContext {
if ext.widgetActiveDisplayMode == .expanded {
return displayCount()
}else {
let count = displayCount()
if count >= 2 {
return 2
}else {
return 1
}
}
}
return 1
}
func displayCount() -> Int{
if proxyGroup.proxys.count < proxyGroup.widgetProxyCount {
return proxyGroup.proxys.count + 1
}else {
return proxyGroup.widgetProxyCount + 1
}
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.row == 0 {
return nil
}else {
return indexPath
}
// if indexPath.row == proxyGroup.proxys.count {
// return nil
// }
}
func running() ->Bool {
if let m = SFVPNManager.shared.manager {
if m.connection.status == .connected {
return true
}
}
return false
}
func startStopToggled() {
do {
let selectConf = ProxyGroupSettings.share.config
let result = try SFVPNManager.shared.startStopToggled(selectConf)
if !result {
Timer.scheduledTimer(timeInterval: 5.0, target: self
, selector: #selector(TodayViewController.registerStatus), userInfo: nil, repeats: false)
// SFVPNManager.shared.loadManager({[unowned self] (manager, error) in
// if let error = error {
// print(error.localizedDescription)
// }else {
// print("start/stop action")
// if self.autoRedail {
// self.startStopToggled()
// self.autoRedail = false
// }
//
// }
// })
}
} catch let error{
//SFVPNManager.shared.xpc()
print(error.localizedDescription)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath , animated: true)
let pIndex = indexPath.row - 1
if pIndex == -1 {
return
}
if proxyGroup.selectIndex == pIndex {
showServerHost = !showServerHost
}else {
proxyGroup.selectIndex = pIndex
try! proxyGroup.save()
if running() {
// do {
// try SFVPNManager.shared.startStopToggled("")
// } catch let e {
// print(e.localizedDescription)
// }
autoRedail = true
startStopToggled()
//changeProxy(index: pIndex)
}
}
tableView.reloadData()
}
func changeProxy(index:Int) {
let me = SFVPNXPSCommand.CHANGEPROXY.rawValue + "|\(index)"
if let m = SFVPNManager.shared.manager , m.connection.status == .connected {
if let session = m.connection as? NETunnelProviderSession,
let message = me.data(using: .utf8)
{
do {
try session.sendProviderMessage(message) { [weak self] response in
guard let response = response else {return}
if let r = String.init(data: response, encoding: .utf8) , r == proxyChangedOK{
self!.alertMessageAction(r,complete: nil)
} else {
self!.alertMessageAction("Failed to Change Proxy",complete: nil)
}
}
} catch let e as NSError{
alertMessageAction("Failed to Change Proxy,reason \(e.description)",complete: nil)
}
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//
var color = UIColor.darkText
if ProxyGroupSettings.share.wwdcStyle {
color = UIColor.white
}
// var count = 0
// if proxyGroup.proxys.count < proxyGroup.widgetProxyCount {
// count = proxyGroup.proxys.count
// }else {
// count = proxyGroup.widgetProxyCount
// }
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "main2") as! StatusConnectedCell
var flag = false
if let m = SFVPNManager.shared.manager, m.isEnabled{
if m.connection.status == .connected {
flag = true
}
}
// if sysVersion < 10 {
// if let _ = tunname(){
// flag = true
// }
// }
cell.statusSwitch.isOn = flag
if flag {
print("connected ")
cell.downLabel.text = "\u{f35d}"
cell.downLabel.isHidden = false
cell.upLabel.isHidden = false
cell.downLabel.textColor = color//UIColor.whiteColor()
cell.upLabel.text = "\u{f366}"
cell.upLabel.textColor = color//UIColor.whiteColor()
let t = report.lastTraffice
cell.downSpeedLabel.text = t.toString(x: t.rx,label: "",speed: true)
cell.downSpeedLabel.textColor = color// UIColor.whiteColor()
cell.upSpeedLabel.text = t.toString(x: t.tx,label: "",speed: true)
cell.upSpeedLabel.textColor = color //UIColor.whiteColor()
cell.configLabel.textColor = color
cell.cellLabel.textColor = color
cell.cellInfoLabel.textColor = color
cell.wifiLabel.textColor = color
cell.wifiInfoLabel.textColor = color
cell.cellLabel.isHidden = false
cell.cellLabel.text = "\u{f274}"
cell.cellInfoLabel.isHidden = false
cell.wifiLabel.isHidden = false
cell.wifiInfoLabel.isHidden = false
cell.wifiLabel.text = "\u{f25c}"
let x = report.cellTraffice.rx + report.cellTraffice.tx
let y = report.wifiTraffice.rx + report.wifiTraffice.tx
cell.cellInfoLabel.text = report.cellTraffice.toString(x:x,label: "",speed: false)
cell.wifiInfoLabel.text = report.cellTraffice.toString(x:y,label: "",speed: false)
cell.speedContainView.isHidden = false
cell.configLabel.isHidden = true
cell.downSpeedLabel.isHidden = false
cell.upSpeedLabel.isHidden = false
if reachability.isReachableViaWiFi {
cell.cellLabel.textColor = UIColor.gray
}
if reachability.isReachableViaWWAN {
cell.wifiLabel.textColor = UIColor.gray
}
}else {
print("not connected ")
cell.configLabel.isHidden = false
cell.speedContainView.isHidden = false
cell.statusSwitch.isHidden = false
cell.downLabel.isHidden = true
cell.upLabel.isHidden = true
cell.downSpeedLabel.isHidden = true
cell.upSpeedLabel.isHidden = true
cell.cellLabel.isHidden = true
cell.cellInfoLabel.isHidden = true
cell.wifiLabel.isHidden = true
cell.wifiInfoLabel.isHidden = true
if ProxyGroupSettings.share.widgetProxyCount == 0 {
cell.configLabel.text = "Today Widget Disable"
}else {
let s = ProxyGroupSettings.share.config
if !s.isEmpty {
config = s
cell.configLabel.text = config //+ " Disconnect " //configLabel.text = config
}else {
cell.configLabel.text = "add config use A.BIG.T"
}
}
cell.configLabel.textColor = color
}
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "proxy") as! ProxyGroupCell
let pIndex = indexPath.row - 1
let proxy = proxyGroup.proxys[pIndex]
var configString:String
var ts = ""
if !proxy.kcptun {
if proxy.tcpValue != 0 {
if proxy.tcpValue > 0.0 {
ts = String(format: " %.0fms", proxy.tcpValue*1000)
//cell.subLabel.textColor = UIColor.cyanColor()
//print("111")
}else {
print("222")
ts = " Ping: Error"
//cell.subLabel.textColor = UIColor.redColor()
}
}else {
print("333")
}
}else {
ts = " kcptun"
}
if showServerHost {
configString = proxy.showString() + " " + proxy.serverAddress + ":" + proxy.serverPort + ts
}else {
if proxyGroup.showCountry {
configString = proxy.countryFlagFunc() + ts
}else {
configString = proxy.showString() + ts
}
}
cell.configLabel.textColor = color
cell.configLabel.text = configString
if proxyGroup.selectIndex == pIndex {
cell.starView.isHidden = false
}else {
cell.starView.isHidden = true
}
return cell
}
}
func showTraffice() ->Bool {
if NSObject.version() >= 10 {
if let m = SFVPNManager.shared.manager {
if m.connection.status == .connected || m.connection.status == .connecting{
return true
}
}else {
return false
}
}else {
if let m = SFVPNManager.shared.manager {
//profile
if m.connection.status == .connected || m.connection.status == .connecting{
return true
}else {
return false
}
}else {
return report.show
}
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
Fabric.with([Crashlytics.self])
Fabric.with([Answers.self])
try! reachability.startNotifier()
if #available(iOSApplicationExtension 10.0, *) {
self.extensionContext!.widgetLargestAvailableDisplayMode = .expanded
} else {
updateSize()
}
if ProxyGroupSettings.share.widgetProxyCount == 0 {
removeTodayProfile()
}else {
profileStatus()
}
}
func profileStatus() {
NETunnelProviderManager.loadAllFromPreferences() { [weak self ](managers, error) -> Void in
if let managers = managers {
if managers.count > 0 {
if let m = managers.first {
SFVPNManager.shared.manager = m
if m.connection.status == .connected {
//self!.statusCell!.statusSwitch.on = true
}
self!.registerStatus()
}
self!.tableView.reloadData()
}
}
}
}
@IBAction func addProifile() {
//print("on")
if let m = SFVPNManager.shared.manager {
if m.connection.status == .connected {
//self.statusCell!.statusSwitch.on = true
}
self.registerStatus()
}else {
loadManager()
}
tableView.reloadData()
}
func reloadStatus(){
//Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #, userInfo: <#T##Any?#>, repeats: <#T##Bool#>)
if NSObject.version() >= 10 {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(TodayViewController.trafficReport(_:)), userInfo: nil, repeats: true)
}else {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(TodayViewController.trafficReport(_:)), userInfo: nil, repeats: true)
}
}
func requestReportXPC() {
//print("000")
if let m = SFVPNManager.shared.manager , m.connection.status == .connected {
//print("\(m.protocolConfiguration)")
let date = NSDate()
let me = SFVPNXPSCommand.FLOWS.rawValue + "|\(date)"
if let session = m.connection as? NETunnelProviderSession,
let message = me.data(using: .utf8)
{
do {
try session.sendProviderMessage(message) { [weak self] response in
if response != nil {
self!.processData(data: response!)
} else {
//self!.alertMessageAction("Got a nil response from the provider",complete: nil)
}
}
} catch {
//alertMessageAction("Failed to Get result ",complete: nil)
}
}else {
//alertMessageAction("Connection not Stated",complete: nil)
}
}else {
//alertMessageAction("message dont init",complete: nil)
tableView.reloadData()
}
}
@objc func trafficReport(_ t:Timer) {
if let m = SFVPNManager.shared.manager, m.connection.status == .connected {
//requestReportXPC()
}
guard let last = DataCounters("240.7.1.9") else {return}
report.cellTraffice.tx = last.wwanSent
report.cellTraffice.rx = last.wwanReceived
report.wifiTraffice.tx = last.wiFiSent
report.wifiTraffice.rx = last.wiFiReceived
if reachability.isReachableViaWWAN {
report.lastTraffice.tx = last.wwanSent - lastTraffic.wwanSent
report.lastTraffice.rx = last.wwanReceived - lastTraffic.wwanReceived
}else {
report.lastTraffice.tx = last.wiFiSent - lastTraffic.wiFiSent
report.lastTraffice.rx = last.wiFiReceived - lastTraffic.wiFiReceived
}
//NSLog("%ld,%ld", last.TunSent , lastTraffic.TunSent)
charts.append(Double(report.lastTraffice.rx))
print(charts)
if charts.count > 60 {
charts.remove(at: 0)
}
chartsView.update(charts)
lastTraffic = last
self.report.show = last.show
tableView.reloadData()
}
func updateSize(){
proxyGroup = ProxyGroupSettings.share
try! proxyGroup.loadProxyFromFile()
var count = 1
if proxyGroup.proxys.count < proxyGroup.widgetProxyCount {
count += proxyGroup.proxys.count
}else {
count += proxyGroup.widgetProxyCount
}
self.preferredContentSize = CGSize.init(width: 0, height: 44*CGFloat(count))
}
@available(iOSApplicationExtension 10.0, *)
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
proxyGroup = ProxyGroupSettings.share
try! proxyGroup.loadProxyFromFile()
var count = 1
if proxyGroup.proxys.count < proxyGroup.widgetProxyCount {
count += proxyGroup.proxys.count
}else {
count += proxyGroup.widgetProxyCount
}
NSLog("max hegith %.02f", maxSize.height)
switch activeDisplayMode {
case .expanded:
//self.preferredContentSize = CGSize.init(width:maxSize.width,height:260)
if proxyGroup.widgetFlow == false {
self.preferredContentSize = CGSize.init(width: 0, height: 44 * CGFloat(count) + 22 )
}else {
self.preferredContentSize = CGSize.init(width: 0, height: 44 * CGFloat(count) + 22 + 150)
}
case .compact:
//size = CGSize.init(width: 0, height: 44 * CGFloat(count))
self.preferredContentSize = maxSize //CGSize.init(width: maxSize.width, height: 88.0)
@unknown default:
break
}
self.tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
appearDate = Date()
try! proxyGroup.loadProxyFromFile()
if proxyGroup.widgetFlow == false {
chartsView.isHidden = true
chartsView.frame.size.height = 0
}else {
chartsView.isHidden = false
chartsView.frame.size.height = 150
}
if proxyGroup.proxys.count > 0 {
//tcpScan()
}
reloadStatus()
registerStatus()
tableView.reloadData()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let t = timer {
t.invalidate()
}
let now = Date()
let ts = now.timeIntervalSince(appearDate)
Answers.logCustomEvent(withName: "Today",
customAttributes: [
"Usage": ts,
])
if let m = SFVPNManager.shared.manager {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NEVPNStatusDidChange, object: m.connection)
}
}
func loadManager() {
//print("loadManager")
let vpnmanager = SFVPNManager.shared
if !vpnmanager.loading {
vpnmanager.loadManager() {
[weak self] (manager, error) -> Void in
if let _ = manager {
self!.tableView.reloadData()
self!.registerStatus()
vpnmanager.xpc()
}
}
}else {
print("vpnmanager loading")
}
}
@objc func registerStatus(){
if let m = SFVPNManager.shared.manager {
// Register to be notified of changes in the status.
NotificationCenter.default.addObserver(forName: NSNotification.Name.NEVPNStatusDidChange, object: m.connection, queue: OperationQueue.main, using: { [weak self] notification in
if let strong = self {
if let o = notification.object {
if let c = o as? NEVPNConnection, c.status == .disconnected {
if strong.autoRedail {
strong.autoRedail = false
_ = try! SFVPNManager.shared.startStopToggled(ProxyGroupSettings.share.config)
}
}
}
strong.tableView.reloadData()
}
})
}else {
}
}
func removeTodayProfile(){
NETunnelProviderManager.loadAllFromPreferences() { (managers, error) -> Void in
if let managers = managers {
if managers.count > 0 {
var temp:NETunnelProviderManager?
let identify = "Surfing Today"
for mm in managers {
if mm.localizedDescription == identify {
temp = mm
}
}
//print(temp?.localizedDescription)
if let t = temp{
t.removeFromPreferences(completionHandler: { (error) in
if let e = error{
print(identify + " reomve error \(e.localizedDescription)")
}else {
print(identify + "removed ")
}
})
}
}
}
}
}
@IBAction func enable(_ sender: UISwitch) {
if NSObject.version() >= 10 {
if let m = SFVPNManager.shared.manager {
let s = ProxyGroupSettings.share.config
if s.isEmpty{
return
}
if m.isEnabled {
do {
_ = try SFVPNManager.shared.startStopToggled(s)
}catch let e as NSError {
print(e)
}
}else {
//27440171 today widget error
let url = URL.init(string:"abigt://start" )
self.extensionContext!.open(url!, completionHandler: { (s) in
if s {
print("good")
}
})
//SFVPNManager.shared.enabledToggled(true)
}
}else {
//statusCell!.configLabel.text = config + " please add profile"
//print("manager invalid")
loadManager()
sender.isOn = false
}
}else {
//9 只能用双profile
if ProxyGroupSettings.share.widgetProxyCount != 0 {
if let m = SFVPNManager.shared.manager {
let s = ProxyGroupSettings.share.config
if s.isEmpty{
return
}
if m.isEnabled {
print("profile enabled ")
}
do {
_ = try SFVPNManager.shared.startStopToggled(s)
}catch let e as NSError {
print(e)
}
}else {
//statusCell!.configLabel.text = config + " please add profile"
//print("manager invalid")
if sender.isOn {
loadManager()
sender.isOn = false
}else {
report.show = false
closeTun()
sender.isOn = false
}
}
}else {
}
}
// tableView.reloadData()
}
func closeTun(){
let queue = DispatchQueue(label:"com.abigt.socket")//, DISPATCH_QUEUE_CONCURRENT
queue.async( execute: {
//let start = NSDate()
// Look up the host...
let socketfd: Int32 = socket(Int32(AF_INET), SOCK_STREAM, Int32(IPPROTO_TCP))
let remoteHostName = "localhost"
//let port = Intp.serverPort
guard let remoteHost = gethostbyname2((remoteHostName as NSString).utf8String, AF_INET)else {
return
}
// Copy the info into the socket address structure...
var remoteAddr = sockaddr_in()
remoteAddr.sin_family = sa_family_t(AF_INET)
bcopy(remoteHost.pointee.h_addr_list[0], &remoteAddr.sin_addr.s_addr, Int(remoteHost.pointee.h_length))
remoteAddr.sin_port = UInt16(3128).bigEndian
// Now, do the connection...
//https://swift.org/migration-guide/se-0107-migrate.html
let rc = withUnsafePointer(to: &remoteAddr) {
// Temporarily bind the memory at &addr to a single instance of type sockaddr.
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
connect(socketfd, $0, socklen_t(MemoryLayout<sockaddr_in>.stride))
}
}
if rc < 0 {
}else {
}
let main = DispatchQueue.main
main.async(execute: {
[weak self] in
if let StrongSelft = self {
StrongSelft.tableView.reloadData()
//print("reload")
}
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func requestReport() {
//print("000")
if let m = SFVPNManager.shared.manager {//where m.connection.status == .Connected
//print("\(m.protocolConfiguration)")
let date = NSDate()
let me = SFVPNXPSCommand.STATUS.rawValue + "|\(date)"
if let session = m.connection as? NETunnelProviderSession,
let message = me.data(using: String.Encoding.utf8), m.connection.status == .connected
{
do {
try session.sendProviderMessage(message) { [weak self] response in
if response != nil {
self!.processData(data: response! )
} else {
//self!.alertMessageAction("Got a nil response from the provider",complete: nil)
}
}
} catch {
//alertMessageAction("Failed to Get result ",complete: nil)
}
}else {
//alertMessageAction("Connection not Stated",complete: nil)
//statusCell!.configLabel.text = config + " " + m.connection.status.description
}
}else {
//statusCell!.configLabel.text = config
//alertMessageAction("message dont init",complete: nil)
}
}
func processData(data:Data) {
//results.removeAll()
//print("111")
//let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
let obj = try! JSON.init(data: data)
if obj.error == nil {
//alertMessageAction("message dont init",complete: nil)
//report.map(j: obj)
report.netflow.mapObject(j: obj["netflow"])
chartsView.updateFlow(report.netflow)
//statusCell!.configLabel.text = "\(report.lastTraffice.report()) mem:\(report.memoryString())"
//tableView.reloadSections(NSIndexSet.init(index: 2), withRowAnimation: .Automatic)
}else {
// if let m = SFVPNManager.shared.manager {
// statusCell!.configLabel.text = config + " " + m.connection.status.description
// statusCell!.statusSwitch.on = true
// }else {
// statusCell!.configLabel.text = "VPN Manager Error"
// statusCell!.statusSwitch.on = false
// }
//
}
tableView.reloadData()
}
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets{
return UIEdgeInsets.init(top: 5, left: 44, bottom: 0, right: 0)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
self.tableView.contentSize = size
self.tableView.reloadData()
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.newData)
}
}
extension TodayViewController{
func tcpScan(){
let queue = DispatchQueue(label: "com.abigt.socket")//, DISPATCH_QUEUE_CONCURRENT)
for p in ProxyGroupSettings.share.proxys {
print(p.showString() + " now scan " )
if p.kcptun {
continue
}
queue.async( execute: {
let start = Date()
// Look up the host...
let socketfd: Int32 = socket(Int32(AF_INET), SOCK_STREAM, Int32(IPPROTO_TCP))
let remoteHostName = p.serverAddress
//let port = Intp.serverPort
guard let remoteHost = gethostbyname2((remoteHostName as NSString).utf8String, AF_INET)else {
return
}
let d = NSDate()
p.dnsValue = d.timeIntervalSince(start)
var remoteAddr = sockaddr_in()
remoteAddr.sin_family = sa_family_t(AF_INET)
bcopy(remoteHost.pointee.h_addr_list[0], &remoteAddr.sin_addr.s_addr, Int(remoteHost.pointee.h_length))
remoteAddr.sin_port = UInt16(p.serverPort)!.bigEndian
// Now, do the connection...
//https://swift.org/migration-guide/se-0107-migrate.html
let rc = withUnsafePointer(to: &remoteAddr) {
// Temporarily bind the memory at &addr to a single instance of type sockaddr.
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
connect(socketfd, $0, socklen_t(MemoryLayout<sockaddr_in>.stride))
}
}
if rc < 0 {
print("\(p.serverAddress):\(p.serverPort) socket connect failed")
//throw BlueSocketError(code: BlueSocket.SOCKET_ERR_CONNECT_FAILED, reason: self.lastError())
p.tcpValue = -1
}else {
let end = Date()
p.tcpValue = end.timeIntervalSince(start)
close(socketfd)
}
DispatchQueue.main.async( execute: { [weak self] in
if let StrongSelft = self {
StrongSelft.tableView.reloadData()
print("reload")
}
})
})
}
}
}
| 96bd69af0d2fc4c48ce2bbfacb672052 | 35.121926 | 189 | 0.486796 | false | false | false | false |
RLovelett/UIBadge | refs/heads/master | UIBadge/ViewController.swift | mit | 1 | //
// ViewController.swift
// UIBadge
//
// Created by Ryan Lovelett on 8/28/15.
// Copyright © 2015 SAIC. All rights reserved.
//
import UIKit
extension Int {
static func random(range: Range<Int> ) -> Int {
var offset = 0
// allow negative ranges
if range.startIndex < 0 {
offset = abs(range.startIndex)
}
let mini = UInt32(range.startIndex + offset)
let maxi = UInt32(range.endIndex + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
class ViewController: UIViewController {
@IBOutlet weak var zeroAsNil: UIBadge!
@IBOutlet weak var dispZero: UIBadge!
@IBOutlet weak var tens: UIBadge!
@IBOutlet weak var hundreds: UIBadge!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("incrementBadge"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func incrementBadge() {
zeroAsNil.badgeValue = (zeroAsNil.badgeValue + 1) % 2
dispZero.badgeValue = (dispZero.badgeValue + Int.random(1...10)) % 10
tens.badgeValue = (tens.badgeValue + Int.random(1...100)) % 100
hundreds.badgeValue = (hundreds.badgeValue + Int.random(1...1000)) % 1000
}
}
| 443211cced447d037cceb3ad35f11618 | 25 | 127 | 0.684615 | false | false | false | false |
DianQK/rx-sample-code | refs/heads/master | RxDataSourcesExample/Expandable/ViewController.swift | mit | 1 | //
// ViewController.swift
// Expandable
//
// Created by DianQK on 8/17/16.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import RxExtensions
private typealias ProfileSectionModel = AnimatableSectionModel<ProfileSectionType, ProfileItem>
class ViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
private let dataSource = RxTableViewSectionedAnimatedDataSource<ProfileSectionModel>()
override func viewDidLoad() {
super.viewDidLoad()
do {
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
}
do {
dataSource.animationConfiguration = AnimationConfiguration(insertAnimation: .automatic, reloadAnimation: .automatic, deleteAnimation: .fade)
dataSource.configureCell = { dataSource, tableView, indexPath, item in
switch item.type {
case let .display(title, type, _):
let infoCell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.normalCell, for: indexPath)!
infoCell.detailTextLabel?.text = type.subTitle
if let textLabel = infoCell.textLabel {
title.asObservable()
.bindTo(textLabel.rx.text)
.disposed(by: infoCell.rx.prepareForReuseBag)
}
return infoCell
case let .input(input):
switch input {
case let .datePick(date):
let datePickerCell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.datePickerCell, for: indexPath)!
(datePickerCell.rx.date <-> date).disposed(by: datePickerCell.rx.prepareForReuseBag)
return datePickerCell
case let .level(level):
let sliderCell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.sliderCell, for: indexPath)!
(sliderCell.rx.value <-> level).disposed(by: sliderCell.rx.prepareForReuseBag)
return sliderCell
case let .status(title, isOn):
let switchCell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.switchCell, for: indexPath)!
switchCell.title = title
(switchCell.rx.isOn <-> isOn).disposed(by: switchCell.rx.prepareForReuseBag)
return switchCell
case let .textField(text, placeholder):
let textFieldCell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.textFieldCell, for: indexPath)!
textFieldCell.placeholder = placeholder
(textFieldCell.rx.text <-> text).disposed(by: textFieldCell.rx.prepareForReuseBag)
return textFieldCell
case let .title(title, _):
let titleCell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.normalItemCell, for: indexPath)!
titleCell.textLabel?.text = title
return titleCell
}
}
}
dataSource.titleForHeaderInSection = { dataSource, section in
return dataSource[section].model.rawValue
}
}
do {
tableView.rx.modelSelected(ProfileItem.self)
.subscribe(onNext: { item in
switch item.type {
case let .display(_, _, isExpanded):
isExpanded.value = !isExpanded.value
case let .input(input):
switch input {
case let .title(title, favorite):
favorite.value = title
default:
break
}
}
})
.disposed(by: rx.disposeBag)
tableView.rx.enableAutoDeselect()
.disposed(by: rx.disposeBag)
}
do {
let fullname = ProfileItem(defaultTitle: "Xutao Song", displayType: .fullname)
let dateOfBirth = ProfileItem(defaultTitle: "2016年9月30日", displayType: .dateOfBirth)
let maritalStatus = ProfileItem(defaultTitle: "Married", displayType: .maritalStatus)
let favoriteSport = ProfileItem(defaultTitle: "Football", displayType: .favoriteSport)
let favoriteColor = ProfileItem(defaultTitle: "Red", displayType: .favoriteColor)
let level = ProfileItem(defaultTitle: "3", displayType: .level)
let firstSectionItems = Observable.combineLatest(fullname.allItems, dateOfBirth.allItems, maritalStatus.allItems) { $0 + $1 + $2 }
let secondSectionItems = Observable.combineLatest(favoriteSport.allItems, favoriteColor.allItems, resultSelector: +)
let thirdSectionItems = level.allItems
let firstSection = firstSectionItems.map { ProfileSectionModel(model: .personal, items: $0) }
let secondSection = secondSectionItems.map { ProfileSectionModel(model: .preferences, items: $0) }
let thirdSection = thirdSectionItems.map { ProfileSectionModel(model: .workExperience, items: $0) }
Observable.combineLatest(firstSection, secondSection, thirdSection) { [$0, $1, $2] }
.bindTo(tableView.rx.items(dataSource: dataSource))
.disposed(by: rx.disposeBag)
}
}
}
| 834fe8b4e1a6fcca747dec70fe839f28 | 44.65873 | 152 | 0.58665 | false | false | false | false |
nh7a/Geohash | refs/heads/main | Tests/GeohashTests/GeohashTests.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2019 Naoki Hiroshima
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import XCTest
@testable import Geohash
final class GeohashTests: XCTestCase {
func testDecode() {
XCTAssertNil(Geohash.decode(hash: "garbage"))
XCTAssertNil(Geohash.decode(hash: "u$pruydqqvj"))
let (lat, lon) = Geohash.decode(hash: "u4pruydqqvj")!
XCTAssertTrue(lat.min == 57.649109959602356)
XCTAssertTrue(lat.max == 57.649111300706863)
XCTAssertTrue(lon.min == 10.407439023256302)
XCTAssertTrue(lon.max == 10.407440364360809)
}
func testEncode() {
let (lat, lon) = (57.64911063015461, 10.40743969380855)
let chars = "u4pruydqqvj"
for i in 1...chars.count {
XCTAssertTrue(Geohash.encode(latitude: lat, longitude: lon, length: i) == String(chars.prefix(i)))
}
}
static var allTests = [
("testDecode", testDecode),
("testEncode", testEncode),
]
}
#if canImport(CoreLocation)
import CoreLocation
final class GeohashCoreLocationTests: XCTestCase {
func testCoreLocation() {
XCTAssertFalse(CLLocationCoordinate2DIsValid(CLLocationCoordinate2D(geohash: "garbage")))
let c = CLLocationCoordinate2D(geohash: "u4pruydqqvj")
XCTAssertTrue(CLLocationCoordinate2DIsValid(c))
XCTAssertTrue(c.geohash(length: 11) == "u4pruydqqvj")
}
static var allTests = [
("testCoreLocation", testCoreLocation),
]
}
#endif
| b3ca88541c9b283ef4700568a66bf2da | 35.84058 | 110 | 0.704957 | false | true | false | false |
karwa/swift | refs/heads/master | test/Sema/object_literals_osx.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift
// REQUIRES: OS=macosx
struct S: _ExpressibleByColorLiteral {
init(_colorLiteralRed: Float, green: Float, blue: Float, alpha: Float) {}
}
let y: S = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)
let y2 = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) // expected-error{{could not infer type of color literal}} expected-note{{import AppKit to use 'NSColor' as the default color literal type}}
let y3 = #colorLiteral(red: 1, bleen: 0, grue: 0, alpha: 1) // expected-error{{cannot convert value of type '(red: Int, bleen: Int, grue: Int, alpha: Int)' to expected argument type '(red: Float, green: Float, blue: Float, alpha: Float)'}}
struct I: _ExpressibleByImageLiteral {
init(imageLiteralResourceName: String) {}
}
let z: I = #imageLiteral(resourceName: "hello.png")
let z2 = #imageLiteral(resourceName: "hello.png") // expected-error{{could not infer type of image literal}} expected-note{{import AppKit to use 'NSImage' as the default image literal type}}
struct Path: _ExpressibleByFileReferenceLiteral {
init(fileReferenceLiteralResourceName: String) {}
}
let p1: Path = #fileLiteral(resourceName: "what.txt")
let p2 = #fileLiteral(resourceName: "what.txt") // expected-error{{could not infer type of file reference literal}} expected-note{{import Foundation to use 'URL' as the default file reference literal type}}
let text = #fileLiteral(resourceName: "TextFile.txt").relativeString! // expected-error{{type of expression is ambiguous without more context}}
// rdar://problem/49861813
#fileLiteral() // expected-error {{cannot convert value of type '()' to expected argument type '(resourceName: String)'}}
| ea7882431a28566c5004f652c08df202 | 56.793103 | 239 | 0.732697 | false | false | false | false |
ixx1232/FoodTrackerStudy | refs/heads/master | FoodTracker/FoodTracker/Meal.swift | mit | 1 | //
// Meal.swift
// FoodTracker
//
// Created by apple on 15/12/24.
// Copyright © 2015年 www.ixx.com. All rights reserved.
//
import UIKit
class Meal: NSObject, NSCoding {
// MARK: Properties
// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals")
// MARK: Types
struct PropertyKey {
static let nameKey = "name"
static let photoKey = "photo"
static let ratingKey = "rating"
}
var name: String
var photo : UIImage?
var rating: Int
// MARK: Initialization
init?(name: String, photo: UIImage?, rating: Int) {
self.name = name
self.photo = photo
self.rating = rating
super.init()
if name.isEmpty || rating < 0 {
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
aCoder.encodeObject(photo, forKey: PropertyKey.photoKey)
aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as? UIImage
let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey)
self.init(name: name, photo: photo, rating: rating)
}
}
| 88529d683b46824672801ee6d1920ff7 | 26.612903 | 166 | 0.627921 | false | false | false | false |
CoolCodeFactory/Antidote | refs/heads/master | AntidoteArchitectureExample/AppCoordinator.swift | mit | 1 | //
// AppCoordinator.swift
// AntidoteArchitectureExample
//
// Created by Dmitriy Utmanov on 16/09/16.
// Copyright © 2016 Dmitry Utmanov. All rights reserved.
//
import UIKit
class AppCoordinator: BaseCoordinatorProtocol {
var childCoordinators: [CoordinatorProtocol] = []
var closeHandler: () -> () = { }
weak var window: UIWindow!
fileprivate var isAuthenticated = true
required init(window: UIWindow) {
self.window = window
}
func start(animated: Bool) {
closeHandler = {
self.finish(animated: animated)
}
if authenticated() {
let menuFlowCoordinator = MenuFlowCoordinator(window: window)
addChildCoordinator(menuFlowCoordinator)
menuFlowCoordinator.closeHandler = { [unowned menuFlowCoordinator] in
menuFlowCoordinator.finish(animated: animated)
self.removeChildCoordinator(menuFlowCoordinator)
self.closeHandler()
}
menuFlowCoordinator.start(animated: animated)
} else {
let authenticationFlowCoordinator = AuthenticationFlowCoordinator(window: window)
addChildCoordinator(authenticationFlowCoordinator)
authenticationFlowCoordinator.closeHandler = { [unowned authenticationFlowCoordinator] in
authenticationFlowCoordinator.finish(animated: animated)
self.removeChildCoordinator(authenticationFlowCoordinator)
self.closeHandler()
}
authenticationFlowCoordinator.start(animated: animated)
}
}
func finish(animated: Bool) {
self.removeAllChildCoordinators()
start(animated: animated)
}
}
extension AppCoordinator {
func authenticated() -> Bool {
isAuthenticated = !isAuthenticated
return isAuthenticated
}
}
| 476ead773b552f3a7a10a49bc6d3c105 | 29.365079 | 101 | 0.644537 | false | false | false | false |
CorlaOnline/ACPaginatorViewController | refs/heads/master | ACPaginatorViewController/Classes/ACPaginatorViewController.swift | mit | 1 | //
// ACPaginatorViewController.swift
// Pods
//
// Created by Alex Corlatti on 16/06/16.
//
//
open class ACPaginatorViewController: UIPageViewController {
open var paginationDelegate: ACPaginatorViewControllerDelegate?
open var orderedViewControllers: [UIViewController] = []
open var currentViewControllerIndex: Int = 0
override open func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
paginationDelegate?.pageControl?.numberOfPages = orderedViewControllers.count
paginationDelegate?.paginatorViewController?(self, didUpdatePageCount: orderedViewControllers.count)
guard orderedViewControllers.count > 0 else { return }
if currentViewControllerIndex >= orderedViewControllers.count {
currentViewControllerIndex = orderedViewControllers.count - 1
} else if currentViewControllerIndex < 0 {
currentViewControllerIndex = 0
}
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard currentViewControllerIndex < orderedViewControllers.count && currentViewControllerIndex >= 0 else { return }
setViewControllers([orderedViewControllers[currentViewControllerIndex]], direction: .forward, animated: true, completion: nil)
paginationDelegate?.pageControl?.currentPage = currentViewControllerIndex
paginationDelegate?.paginatorViewController?(self, didUpdatePageIndex: currentViewControllerIndex)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ACPaginatorViewController: UIPageViewControllerDataSource {
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
//guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else { return nil }
guard let page = viewController as? ACPaginatorProtocol else { return nil }
let viewControllerIndex = page.paginatorIndex
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else { return nil }
guard orderedViewControllers.count > previousIndex else { return nil }
currentViewControllerIndex = previousIndex
return orderedViewControllers[currentViewControllerIndex]
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
//guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else { return nil }
guard let page = viewController as? ACPaginatorProtocol else { return nil }
let viewControllerIndex = page.paginatorIndex
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
guard orderedViewControllersCount != nextIndex else { return nil }
guard orderedViewControllersCount > nextIndex else { return nil }
currentViewControllerIndex = nextIndex
return orderedViewControllers[currentViewControllerIndex]
}
}
extension ACPaginatorViewController: UIPageViewControllerDelegate {
public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
/*guard
let firstViewController = viewControllers?.first,
let index = orderedViewControllers.index(of: firstViewController) else { return }
*/
guard let firstViewController = viewControllers?.first as? ACPaginatorProtocol else { return }
let index = firstViewController.paginatorIndex
paginationDelegate?.pageControl?.currentPage = index
paginationDelegate?.paginatorViewController?(self, didUpdatePageIndex: index)
}
}
| d0f2c5a3e49b5389d0d0c1df510b09b3 | 32.552846 | 197 | 0.726678 | false | false | false | false |
SandcastleApps/partyup | refs/heads/master | PartyUP/AuthenticationManager.swift | mit | 1 | //
// AuthenticationManager.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2016-04-17.
// Copyright © 2016 Sandcastle Application Development. All rights reserved.
//
import Foundation
import KeychainAccess
import AWSCore
import AWSCognito
enum AuthenticationState: Int {
case Unauthenticated, Transitioning, Authenticated
}
class AuthenticationManager: NSObject, AWSIdentityProviderManager {
static let AuthenticationStatusChangeNotification = "AuthenticationStateChangeNotification"
static let shared = AuthenticationManager()
var authentics: [AuthenticationProvider] {
return authenticators.map { $0 as AuthenticationProvider }
}
let user = User()
var identity: NSUUID? {
if let identity = credentialsProvider?.identityId {
return NSUUID(UUIDString: identity[identity.endIndex.advancedBy(-36)..<identity.endIndex])
} else {
return nil
}
}
var isLoggedIn: Bool {
return authenticators.reduce(false) { return $0 || $1.isLoggedIn }
}
private(set) var state: AuthenticationState = .Transitioning
override init() {
authenticators = [FacebookAuthenticationProvider(keychain: keychain)]
super.init()
}
func loginToProvider(provider: AuthenticationProvider, fromViewController controller: UIViewController) {
if let provider = provider as? AuthenticationProviding {
postTransitionToState(.Transitioning, withError: nil)
provider.loginFromViewController(controller, completionHander: AuthenticationManager.reportLoginWithError(self))
}
}
func logout() {
authenticators.forEach{ $0.logout() }
AWSCognito.defaultCognito().wipe()
credentialsProvider?.clearKeychain()
reportLoginWithError(nil)
}
func reportLoginWithError(error: NSError?) {
var task: AWSTask?
if credentialsProvider == nil {
task = self.initialize()
} else {
credentialsProvider?.invalidateCachedTemporaryCredentials()
credentialsProvider?.identityProvider.clear()
task = credentialsProvider?.getIdentityId()
}
task?.continueWithBlock { task in
var state: AuthenticationState = .Unauthenticated
if self.isLoggedIn { state = .Authenticated }
self.postTransitionToState(state, withError: task.error)
return nil
}
}
// MARK: - Identity Provider Manager
func logins() -> AWSTask {
let tasks = authenticators.map { $0.token() }
return AWSTask(forCompletionOfAllTasksWithResults: tasks).continueWithSuccessBlock { task in
if let tokens = task.result as? [String] {
var logins = [String:String]()
for authentic in zip(self.authenticators,tokens) {
logins[authentic.0.identityProviderName] = authentic.1
}
return logins
} else {
return nil
}
}
}
// MARK: - Application Delegate Integration
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let isHandled = authenticators.reduce(false) { $0 || $1.application(application, didFinishLaunchingWithOptions: launchOptions) }
resumeSession()
return isHandled
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
return authenticators.reduce(false) { $0 || $1.application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) }
}
// MARK: - Private
private let keychain = Keychain(service: NSBundle.mainBundle().bundleIdentifier!)
private var authenticators = [AuthenticationProviding]()
private var credentialsProvider: AWSCognitoCredentialsProvider?
private func resumeSession() {
for auth in authenticators {
if auth.wasLoggedIn {
auth.resumeSessionWithCompletionHandler(AuthenticationManager.reportLoginWithError(self))
}
}
if credentialsProvider == nil {
reportLoginWithError(nil)
}
}
private func initialize() -> AWSTask? {
credentialsProvider = AWSCognitoCredentialsProvider(
regionType: PartyUpKeys.AwsRegionType,
identityPoolId: PartyUpKeys.AwsIdentityPool,
identityProviderManager: self)
let configuration = AWSServiceConfiguration(
region: PartyUpKeys.AwsRegionType,
credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
return self.credentialsProvider?.getIdentityId()
}
private func postTransitionToState(state: AuthenticationState, withError error: NSError?) {
let old = self.state
self.state = state
dispatch_async(dispatch_get_main_queue()) {
let notify = NSNotificationCenter.defaultCenter()
var info: [String:AnyObject] = ["old" : old.rawValue, "new" : state.rawValue]
if error != nil { info["error"] = error }
notify.postNotificationName(AuthenticationManager.AuthenticationStatusChangeNotification, object: self, userInfo: info)
}
}
}
| a5dbf90903b99ae6743379cfb9568ad4 | 31.745098 | 151 | 0.724152 | false | false | false | false |
CodaFi/swift | refs/heads/main | validation-test/compiler_crashers_fixed/00172-swift-archetypebuilder-inferrequirementswalker-walktotypepost.swift | apache-2.0 | 65 | // 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
// RUN: not %target-swift-frontend %s -typecheck
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
<c b:
func b<c {
enum b {
func b
var _ = b
func b((Any, e))(e: (Any) -> <d>(()-> d) -> f
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
class func i()
}
class k: c{ class func i {
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
func b(c) -> <d>(() -> d) {
}
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
self.b = b
}
}
struct c<e> {
let d: i h
}
func f(h: b) -> <e>(()-> e
c
j)
func c<k>() -> (k, > k) -> k {
d h d.f 1, k(j, i)))
class k {
typealias h = h
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
protocol f {
k g d {
k d
k k
}
j j<l : d> : d {
k , d>
}
class f: f {
}
class B : l {
}
k l = B
class f<i : f
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
func h<j>() -> (j, j -> j) -> j {
var f: ({ (c: e, f: e -> e) -> return f(c)
}(k, i)
let o: e = { c, g
return f(c)
}(l) -> m) -> p>, e>
}
class n<j : n>
protocol A {
func c() -> String
}
class B {
func d() -> String {
return ""
}
}
class C: B, A {
override func d() -> String {
return ""
}
func c() -> String {
return ""
}
}
func e<T where T: A, T: B>(t: T) {
t.c()
}
struct c<d: Sequence, b where Optional<b> == d.Iterator.Element>
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
protocol b {
class func e()
}
struct c {
var d: b.Type
func e() {
d.e()
}
}
func a<T>() {
enum b {
case c
}
}
func r<t>() {
f f {
i i
}
}
struct i<o : u> {
o f: o
}
func r<o>() -> [i<o>] {
p []
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
typealias h = n
protocol g {
func i() -> l func o() -> m {
q""
}
}
func j<t k t: g, t: n>(s: t) {
s.i()
}
protocol r {
}
protocol f : r {
}
protocol i : r {
}
j
)
func n<w>() -> (w, w -> w) -> w {
o m o.q = {
}
{
w) {
k }
}
protocol n {
class func q()
}
class o: n{ class func q {}
func p(e: Int = x) {
}
let c = p
c()
func r<o: y, s q n<s> ==(r(t))
protocol p : p {
}
protocol p {
class func c()
}
class e: p {
class func c() { }
}
(e() u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) {
}
class i {
func d((h: (Any, AnyObject)) {
d(h)
}
}
d
h)
func d<i>() -> (i, i -> i) -> i {
i j i.f = {
}
protocol d {
class func f()
}
class i: d{ class func f {}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
func a(b: Int = 0) {
}
let c = a
c()
protocol a : a {
}
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
struct c<e> {
let d: [( h
}
func b(g: f) -> <e>(()-> e) -> i
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
func d() -> String {
return 1
k f {
typealias c
}
class g<i{
}
d(j i)
class h {
typealias i = i
}
func o() as o).m.k()
func p(k: b) -> <i>(() -> i) -> b {
n { o f "\(k): \(o())" }
}
struct d<d : n, o:j n {
l p
}
protocol o : o {
}
func o<
import Foundation
class k<f>: NSObject {
d e: f
g(e: f) {
j h.g()
}
}
d
protocol i : d { func d
i
struct l<e : Sequence> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
)
var d = b
=b as c=b
o
}
class f<p : k, p : k where p.n == p> : n {
}
class f<p, p> {
}
protocol k {
typealias n
}
o: i where k.j == f> {l func k() { }
}
(f() as n).m.k()
func k<o {
enum k {
func o
var _ = protocol g {
typealias f
typealias e
}
struct c<h : g> : g {
typealias f = h
typealias e = a<c<h>, f>
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g = g
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h: j, m {
q o m() -> String {
n ""
}
o u() -> S, q> {
}
protocol u {
typealias u
}
class p {
typealias u = u
}
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
p d
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class r {
typealias n = n
func c<e>() -> (e -> e) -> e {
e, e -> e) ->)func d(f: b) -> <e>(() -> e) -> b {
return { g in}
protocol p {
class func g()
}
class h: p {
class func g() { }
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
o t = p
}
struct h : n {
t : n q m.t == m> (h: m) {
}
func q<t : n q t.t == g> (h: t) {
}
q(h())
func r(g: m) -> <s>(() -> s) -> n
b
protocol d : b { func b
func d(e: = { (g: h, f: h -> h) -> h in
return f(g)
}
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
func f(c: i, l: i) -> (((i, i) -> i) -> i) {
b {
(h -> i) d $k
}
let e: Int = 1, 1)
class g<j :g
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
func ^(d: e, Bool) -> Bool {g !(d)
}
protocol d {
f func g()
f e: d {
f func g() { }
}
(e() h d).i()
e
protocol g : e { func e
>)
}
struct n : C {
class p {
typealias n = n
}
l
l)
func l<u>() -> (u, u -> u) -> u {
n j n.q = {
}
{
u) {
h }
}
protocol l {
class {
func n() -> q {
return ""
}
}
class C: s, l {
t) {
return {
(s: (t, t) -> t) -> t o
return s(c, u)
-> Any) -> Any l
k s(j, t)
}
}
func b(s: (((Any, Any) -> Any) -> Any)
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
u) {
o }
}
s m {
class func s()
}
class p: m{ class func s {}
s p {
func m() -> String
}
class n {
func p() -> String {
q ""
}
}
class e: n, p {
v func> String {
q ""
}
{
r m = m
}
func s<o : m, o : p o o.m == o> (m: o) {
}
func s<v : p o v.m == m> (u: String) -> <t>(() -> t) -
protocol A {
func c()l k {
func l() -> g {
m ""
}
}
class C: k, A {
j func l()q c() -> g {
m ""
}
}
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
f g
}
struct d<i : b> : b {
typealias b = i
typealias g = a<d<i>i) {
}
let d = a
d()
a=d g a=d
protocol a : a {
}
class a {
typealias b = b
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
| bbdf3966870b4abbd712f0766725e45f | 12.954145 | 79 | 0.41595 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/SwiftUI/Mac/Get-It-master/Get It/openTerminalButton.swift | mit | 1 | //
// openTerminalButton.swift
// Get It
//
// Created by Kevin De Koninck on 05/02/2017.
// Copyright © 2017 Kevin De Koninck. All rights reserved.
//
import Cocoa
class installButton: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.layer?.backgroundColor = blueColor.cgColor
self.layer?.cornerRadius = 15.0
self.layer?.masksToBounds = true
}
override func awakeFromNib() {
super.awakeFromNib()
//text
let style = NSMutableParagraphStyle()
style.alignment = .center
self.attributedTitle = NSAttributedString(string: "Install", attributes: [ NSAttributedString.Key.foregroundColor : NSColor.white,
NSAttributedString.Key.paragraphStyle : style,
NSAttributedString.Key.font: NSFont(name: "Arial", size: 18)!])
}
}
| d7fcbd7c577fa61d0e27b616f99a7579 | 32.322581 | 146 | 0.552759 | false | false | false | false |
adamontherun/Study-iOS-With-Adam-Live | refs/heads/master | DragAndDropPlaceholder/DragAndDropPlaceholder/ViewController.swift | mit | 1 | //😘 it is 8/9/17
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var donkeyImageView: UIImageView!
let photo = Photo(image: #imageLiteral(resourceName: "donkey"))
override func viewDidLoad() {
super.viewDidLoad()
donkeyImageView.image = photo.image
let dragInteraction = UIDragInteraction(delegate: self)
donkeyImageView.addInteraction(dragInteraction)
donkeyImageView.isUserInteractionEnabled = true
}
}
extension ViewController: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
let itemProvider = NSItemProvider(object: photo)
let dragItem = UIDragItem(itemProvider: itemProvider)
return [dragItem]
}
}
| 9414a64205d416a1aa166eaedeb81751 | 29.37037 | 118 | 0.715854 | false | false | false | false |
JChauncyChandler/MizzouClasses | refs/heads/master | IT/4001/Fall_2017/Example_1/SwiftLanguageBasics/Swift Language Basics/main.swift | mit | 1 | //
// main.swift
// Swift Language Basics
//
// Created by Jackson Chandler on 9/8/17.
// Copyright © 2017 Jackson Chandler. All rights reserved.
//
import Foundation
let sample1: UInt8 = 0x3A
var sample2: UInt8 = 58
var heartRate: Int = 85
var deposits: Double = 135002796
let acceleration: Float = 9.800
var mass: Float = 14.6
var distance: Double = 129.763001
var lost: Bool = true
var expensive: Bool = true
var choice: Int = 2
let integral: Character = "\u{222B}"
let greeting: String = "Hello"
var name: String = "Karen"
if ( sample1 == sample2){
print("The samples are equal")
}
else{
print("The samples are not equal.")
}
if(heartRate >= 40 && heartRate <= 80){
print("Heart rate is normal.")
}else{
print("Heart rate is not normal.")
}
if(deposits >= 100000000){
print("You are exceedingly wealthy")
}else{
print("Sorry you are so poor.")
}
var force = mass * acceleration
print("force =", force)
print(distance, " is the distance.")
if(lost == true && expensive == true){
print("I am really sorry! I will get the manager.")
}
if(lost == true && expensive == false){
print("Here is coupon for 10% off.")
}
switch choice{
case 1:
print("You choose 1.")
case 2:
print("You choose 2.")
case 3:
print("You choose 3.")
default:
print("You made an unkown choice")
}
print(integral, "is an integral.")
var i: Int = 5
for i in 5...10{
print("i =", i)
}
var age: Int = 0
while age < 6{
print("age =", age)
age += 1
}
print(greeting, name)
| c408d36897d4941a0fd3b697449cb1ca | 16.894118 | 59 | 0.639711 | false | false | false | false |
frankthamel/swift_practice | refs/heads/master | Closures.playground/Contents.swift | apache-2.0 | 1 | //: Playground - noun: a place where people can play
import UIKit
//: Closures
//this function takes a String and prints it
func printString (name : String ) {
print("My name is \(name).")
}
printString("Frank")
/*
Asign the function we just declared to a constant.
Note that we do not add paranthaces "()" at the
end of the function name.
*/
let printStringFunction = printString
printStringFunction("Anne")
func displayString (myPrintStringFunc : (String) -> ()){
myPrintStringFunc("Charuka")
}
displayString(printStringFunction)
//using the filter function
let allNumbers = [1 , 2 , 3, 4, 5 ,6 ,7 ,8 ,9]
func isEven(i : Int ) -> Bool {
return i % 2 == 0
}
let ifEven = isEven
let evenNumbers = allNumbers.filter(ifEven)
//capturing variables
func printerFunc () -> (Int) -> () {
var runningTotal = 0
func printInteger(number : Int) -> (){
runningTotal += 10
print("The number you entered is \(number). Running total \(runningTotal)")
}
return printInteger
}
let printNumbers = printerFunc()
printNumbers(2)
printNumbers(2)
let printNumbersTwo = printerFunc()
printNumbersTwo(3)
printNumbers(2)
printNumbersTwo(3)
//closures and expressions
func doubler (i : Int) -> Int {
return i * 2
}
let doublerFunction = doubler
doublerFunction(2)
var sCouunt = [1,2,3,4,5,6,7]
let doubleNumbers = sCouunt.map(doublerFunction)
//expressions
let trippleNumbers = sCouunt.map({(i:Int) -> Int in return i * 3})
trippleNumbers
//sort an array using closure expressions
var nameArray = ["Frank" , "Anne" , "Charuka" , "Kapila" , "Bandara"]
// let sortedArray = nameArray.sort()
//let sortedArray = sorted(nameArray , {(s1 : String , s2: String) -> Bool in return s1 > s2})
// Rule #1
[1,2,3,4,5,6].map({(i : Int)-> Int in return i * 3})
//Rule #2 Infering type from context
[1,2,3,4,5,6].map({i in return i * 3})
//Rule #3 Implisit Returns from single Expression Closures
[1,2,3,4,5,6].map({i in i * 3})
//Rule #4 Shorthand argument names
[1,2,3,4,5,6].map({$0 * 3})
//Rule #5 Traling closures
[1,2,3,4,5,6].map(){$0 * 3}
[1,2,3,4,5,6].map(){
(var digit) -> Int in
if digit % 2 == 0 {
return digit / 2
}else {
return digit
}
}
//Rule #6 Ignoring Parentheses
[1,2,3,4,5,6].map {$0 * 3}
| c70d51fd65394484c7749e5dc8574547 | 18.233333 | 94 | 0.646447 | false | false | false | false |
p4checo/APNSubGroupOperationQueue | refs/heads/master | Sources/OperationSubGroupMap.swift | mit | 1 | //
// OperationSubGroupMap.swift
// APNSubGroupOperationQueue
//
// Created by André Pacheco Neves on 12/02/2017.
// Copyright © 2017 André Pacheco Neves. All rights reserved.
//
import Foundation
/// `OperationSubGroupMap` is a class which contains an `OperationQueue`'s serial subgroups and synchronizes access to
/// them.
///
/// The subgroups are stored as a `[Key : [Operation]]`, and each subgroup array contains all the scheduled subgroup's
/// operations which are pending and executing. Finished `Operation`s are automatically removed from the subgroup after
/// completion.
final class OperationSubGroupMap<Key: Hashable> {
/// The lock which syncronizes access to the subgroup map.
fileprivate let lock: UnfairLock
/// The operation subgroup map.
fileprivate var subGroups: [Key : [Operation]]
/// Instantiates a new `OperationSubGroupMap`.
init() {
lock = UnfairLock()
subGroups = [:]
}
// MARK: - Public
/// Register the specified operation in the subgroup identified by `key`, and create a `CompletionOperation` to ensure
/// the operation is removed from the subgroup on completion.
///
/// Once added to the `OperationQueue`, the operation will only be executed after all currently existing operations
/// in the same subgroup finish executing (serial processing), but can be executed concurrently with other
/// subgroups' operations.
///
/// - Parameters:
/// - op: The `Operation` to be added to the queue.
/// - key: The subgroup's identifier key.
/// - Returns: An `[Operation]` containing the registered operation `op` and it's associated `CompletionOperation`,
/// which *must* both be added to the `OperationQueue`.
func register(_ op: Operation, withKey key: Key) -> [Operation] {
return register([op], withKey: key)
}
/// Wrap the specified block in a `BlockOperation`, register it in the subgroup identified by `key`, and create a
/// `CompletionOperation` to ensure the operation is removed from the subgroup on completion.
///
/// Once added to the `OperationQueue`, the operation will only be executed after all currently existing operations
/// in the same subgroup finish executing (serial processing), but can be executed concurrently with other
/// subgroups' operations.
///
/// - Parameters:
/// - block: The `Operation` to be added to the queue.
/// - key: The subgroup's identifier key.
/// - Returns: An `[Operation]` containing the registered operation `op` and it's associated `CompletionOperation`,
/// which both *must* be added to the `OperationQueue`.
func register(_ block: @escaping () -> Void, withKey key: Key) -> [Operation] {
return register([BlockOperation(block: block)], withKey: key)
}
///
/// - Parameters:
/// - ops: The `[Operation]` to be added to the queue.
/// - key: The subgroup's identifier key.
/// - Returns: An `[Operation]` containing the registered operation `ops` and their associated
/// `CompletionOperation`, which *must* all be added to the `OperationQueue`.
func register(_ ops: [Operation], withKey key: Key) -> [Operation] {
lock.lock()
defer { lock.unlock() }
var newOps = [Operation]()
var subGroup = subGroups[key] ?? []
ops.forEach { op in
let completionOp = createCompletionOperation(for: op, withKey: key)
setupDependencies(for: op, completionOp: completionOp, subGroup: subGroup)
let opPair = [op, completionOp]
newOps.append(contentsOf: opPair)
subGroup.append(contentsOf: opPair)
}
subGroups[key] = subGroup
return newOps
}
// MARK: SubGroup querying
/// Return a snapshot of currently scheduled (i.e. non-finished) operations of the subgroup identified by `key`.
///
/// - Parameter key: The subgroup's identifier key.
/// - Returns: An `[Operation]` containing a snapshot of all currently scheduled (non-finished) subgroup operations.
public subscript(key: Key) -> [Operation] {
return operations(forKey: key)
}
/// Return a snapshot of currently scheduled (i.e. non-finished) operations of the subgroup identified by `key`.
///
/// - Parameter key: The subgroup's identifier key.
/// - Returns: An `[Operation]` containing a snapshot of all currently scheduled (non-finished) subgroup operations.
public func operations(forKey key: Key) -> [Operation] {
lock.lock()
defer { lock.unlock() }
return subGroups[key]?.filter { !($0 is CompletionOperation) } ?? []
}
// MARK: - Private
/// Set up dependencies for an operation being registered in a subgroup.
///
/// This consists of:
/// 1. Add dependency from the `completionOp` to the registered `op`
/// 2. Add dependency from `op` to the last operation in the subgroup, *if the subgroup isn't empty*.
///
/// - Parameters:
/// - op: The operation being registered.
/// - completionOp: The completion operation
/// - subGroup: The subgroup where the operation is being registered.
private func setupDependencies(for op: Operation, completionOp: CompletionOperation, subGroup: [Operation]) {
completionOp.addDependency(op)
// new operations only need to depend on the group's last operation
if let lastOp = subGroup.last {
op.addDependency(lastOp)
}
}
/// Create a completion operation for an operation being registered in a subgroup. The produced
/// `CompletionOperation` is responsible for removing the operation being registered (and itself) from the subgroup.
///
/// - Parameters:
/// - op: The operation being registered.
/// - key: The subgroup's identifier key.
/// - Returns: A `CompletionOperation` containing the removal of `op` from the subgroup identified by `key`
private func createCompletionOperation(for op: Operation, withKey key: Key) -> CompletionOperation {
let completionOp = CompletionOperation()
completionOp.addExecutionBlock { [unowned self, weak weakCompletionOp = completionOp] in
self.lock.lock()
defer { self.lock.unlock() }
guard let completionOp = weakCompletionOp else {
assertionFailure("💥: The completion operation must not be nil")
return
}
guard var subGroup = self.subGroups[key] else {
assertionFailure("💥: A group must exist in the dicionary for the finished operation's key!")
return
}
assert([op, completionOp] == subGroup[0...1],
"💥: op and completionOp must be the first 2 elements in the subgroup's array")
self.subGroups[key] = subGroup.count == 2 ? nil : {
subGroup.removeFirst(2)
return subGroup
}()
}
return completionOp
}
}
| dbb50aa04e5124e3f5c55df75c9034f6 | 40.899408 | 122 | 0.647649 | false | false | false | false |
testpress/ios-app | refs/heads/master | ios-app/UI/BaseQuestionsDataSource.swift | mit | 1 | //
// BaseQuestionsDataSource.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import RealmSwift
class BaseQuestionsDataSource: NSObject, UIPageViewControllerDataSource {
var attemptItems = [AttemptItem]()
init(_ attemptItems: [AttemptItem] = [AttemptItem]()) {
super.init()
self.attemptItems = attemptItems
}
func viewControllerAtIndex(_ index: Int) -> BaseQuestionsViewController? {
if (attemptItems.count == 0) || (index >= attemptItems.count) {
return nil
}
let attemptItem = attemptItems[index]
try! Realm().write {
attemptItem.index = index
}
let viewController = getQuestionsViewController()
viewController.attemptItem = attemptItem
return viewController
}
func getQuestionsViewController() -> BaseQuestionsViewController {
return BaseQuestionsViewController()
}
func indexOfViewController(_ viewController: BaseQuestionsViewController) -> Int {
return viewController.attemptItem!.index
}
// MARK: - Page View Controller Data Source
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore
viewController: UIViewController) -> UIViewController? {
var index = indexOfViewController(viewController as! BaseQuestionsViewController)
if index == 0 {
return nil
}
index -= 1
return viewControllerAtIndex(index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter
viewController: UIViewController) -> UIViewController? {
var index = indexOfViewController(viewController as! BaseQuestionsViewController)
index += 1
if index == attemptItems.count {
return nil
}
return viewControllerAtIndex(index)
}
}
| d16fbdcb5cd271997fc5341b341e7c07 | 35.023256 | 92 | 0.683021 | false | false | false | false |
avito-tech/Marshroute | refs/heads/master | Example/NavigationDemo/Common/Services/CategoriesProvider/CategoriesProviderImpl.swift | mit | 1 | import Foundation
final class CategoriesProviderImpl: CategoriesProvider {
// MARK: - CategoriesProvider
func topCategory() -> Category {
return Category(
title: "categories.selectCategory".localized,
id: "-1",
subcategories: self.allCategories()
)
}
func categoryForId(_ categoryId: CategoryId) -> Category {
let allCategories = self.allCategoryDictionaries()
return categoryForId(categoryId, inCategories: allCategories)!
}
// MARK: - Private
private func allCategories() -> [Category] {
let allCategories = self.allCategoryDictionaries()
return allCategories.map { category(categoryDictionary: $0) }
}
private func allCategoryDictionaries() -> [[String: AnyObject]] {
let path = Bundle.main.path(forResource: "Categories", ofType: "plist")
return NSArray(contentsOfFile: path!) as! [[String: AnyObject]]
}
private func categoryForId(_ categoryId: String, inCategories categoryDictionaries: [[String: AnyObject]]) -> Category? {
for categoryDictionary in categoryDictionaries {
if let id = categoryDictionary["id"] as? CategoryId, id == categoryId {
return category(categoryDictionary: categoryDictionary)
}
if let subCategoryDictionaries = categoryDictionary["subcategories"] as? [[String: AnyObject]] {
if let result = categoryForId(categoryId, inCategories: subCategoryDictionaries) {
return result
}
}
}
return nil
}
private func category(categoryDictionary: [String: AnyObject]) -> Category {
return Category(
title: categoryDictionary["title"] as! String,
id: categoryDictionary["id"] as! CategoryId,
subcategories: subcategories(categoryDictionaries: categoryDictionary["subcategories"] as? [[String: AnyObject]])
)
}
private func subcategories(categoryDictionaries: [[String: AnyObject]]?) -> [Category]? {
if let categoryDictionaries = categoryDictionaries {
return categoryDictionaries.map { category(categoryDictionary: $0) }
}
return nil
}
}
| 851eb11ce25f3ccbf8acf6dbfe56f047 | 38.517241 | 125 | 0.629581 | false | false | false | false |
SimonFairbairn/SwiftyMarkdown | refs/heads/master | Pods/SwiftyMarkdown/Sources/SwiftyMarkdown/SwiftyMarkdown+macOS.swift | mit | 2 | //
// SwiftyMarkdown+macOS.swift
// SwiftyMarkdown
//
// Created by Simon Fairbairn on 17/12/2019.
// Copyright © 2019 Voyage Travel Apps. All rights reserved.
//
import Foundation
#if os(macOS)
import AppKit
extension SwiftyMarkdown {
func font( for line : SwiftyLine, characterOverride : CharacterStyle? = nil ) -> NSFont {
var fontName : String?
var fontSize : CGFloat?
var globalBold = false
var globalItalic = false
let style : FontProperties
// What type are we and is there a font name set?
switch line.lineStyle as! MarkdownLineStyle {
case .h1:
style = self.h1
case .h2:
style = self.h2
case .h3:
style = self.h3
case .h4:
style = self.h4
case .h5:
style = self.h5
case .h6:
style = self.h6
case .codeblock:
style = self.code
case .blockquote:
style = self.blockquotes
default:
style = self.body
}
fontName = style.fontName
fontSize = style.fontSize
switch style.fontStyle {
case .bold:
globalBold = true
case .italic:
globalItalic = true
case .boldItalic:
globalItalic = true
globalBold = true
case .normal:
break
}
if fontName == nil {
fontName = body.fontName
}
if let characterOverride = characterOverride {
switch characterOverride {
case .code:
fontName = code.fontName ?? fontName
fontSize = code.fontSize
case .link:
fontName = link.fontName ?? fontName
fontSize = link.fontSize
case .bold:
fontName = bold.fontName ?? fontName
fontSize = bold.fontSize
globalBold = true
case .italic:
fontName = italic.fontName ?? fontName
fontSize = italic.fontSize
globalItalic = true
default:
break
}
}
fontSize = fontSize == 0.0 ? nil : fontSize
let finalSize : CGFloat
if let existentFontSize = fontSize {
finalSize = existentFontSize
} else {
finalSize = NSFont.systemFontSize
}
var font : NSFont
if let existentFontName = fontName {
if let customFont = NSFont(name: existentFontName, size: finalSize) {
font = customFont
} else {
font = NSFont.systemFont(ofSize: finalSize)
}
} else {
font = NSFont.systemFont(ofSize: finalSize)
}
if globalItalic {
let italicDescriptor = font.fontDescriptor.withSymbolicTraits(.italic)
font = NSFont(descriptor: italicDescriptor, size: 0) ?? font
}
if globalBold {
let boldDescriptor = font.fontDescriptor.withSymbolicTraits(.bold)
font = NSFont(descriptor: boldDescriptor, size: 0) ?? font
}
return font
}
func color( for line : SwiftyLine ) -> NSColor {
// What type are we and is there a font name set?
switch line.lineStyle as! MarkdownLineStyle {
case .h1, .previousH1:
return h1.color
case .h2, .previousH2:
return h2.color
case .h3:
return h3.color
case .h4:
return h4.color
case .h5:
return h5.color
case .h6:
return h6.color
case .body:
return body.color
case .codeblock:
return code.color
case .blockquote:
return blockquotes.color
case .unorderedList, .unorderedListIndentFirstOrder, .unorderedListIndentSecondOrder, .orderedList, .orderedListIndentFirstOrder, .orderedListIndentSecondOrder:
return body.color
case .yaml:
return body.color
case .referencedLink:
return body.color
}
}
}
#endif
| 4bf9f4d74380fb2ef95ee835ea840e9f | 21.520548 | 162 | 0.680657 | false | false | false | false |
DopamineLabs/DopamineKit-iOS | refs/heads/master | BoundlessKit/Classes/Extensions/UIColorExtensions.swift | mit | 1 | //
// UIColorExtensions.swift
// BoundlessKit
//
// Created by Akash Desai on 12/1/17.
//
import Foundation
public extension UIColor {
var rgba: String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgba:Int = (Int)(r*255)<<24 | (Int)(g*255)<<16 | (Int)(b*255)<<8 | (Int)(a*255)<<0
return String(format:"#%08x", rgba).uppercased()
}
var rgb: String {
return String(rgba.dropLast(2))
}
@objc
class func from(rgba: String) -> UIColor? {
var colorString:String = rgba.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
if (colorString.hasPrefix("#")) {
colorString.removeFirst()
}
if colorString.count == 6 {
colorString += "FF"
} else if colorString.count != 8 {
return nil
}
var rgbaValue:UInt32 = 0
Scanner(string: colorString).scanHexInt32(&rgbaValue)
return UIColor(
red: CGFloat((rgbaValue & 0xFF000000) >> 24) / 255.0,
green: CGFloat((rgbaValue & 0x00FF0000) >> 16) / 255.0,
blue: CGFloat((rgbaValue & 0x0000FF00) >> 8) / 255.0,
alpha: CGFloat(rgbaValue & 0x000000FF) / 255.0
)
}
/// This function takes a hex string and alpha value and returns its UIColor
///
/// - parameters:
/// - rgb: A hex string with either format `"#ffffff"` or `"ffffff"` or `"#FFFFFF"`.
/// - alpha: The alpha value to apply to the color. Default is `1.0`.
///
/// - returns:
/// The corresponding UIColor for valid hex strings, `nil` otherwise.
///
@objc
class func from(rgb: String, alpha: CGFloat = 1.0) -> UIColor? {
return UIColor.from(rgba: rgb)?.withAlphaComponent(alpha)
}
}
| c1076c265946b4dd3a15b7d3e8990905 | 28.402985 | 112 | 0.543655 | false | false | false | false |
WANGjieJacques/KissPaginate | refs/heads/master | Example/KissPaginate/WithPaginateViewController.swift | mit | 1 | //
// ViewController.swift
// KissPaginate
//
// Created by WANG Jie on 10/05/2016.
// Copyright (c) 2016 WANG Jie. All rights reserved.
//
import UIKit
import KissPaginate
class WithPaginateViewController: PaginateViewController {
@IBOutlet weak var noElementLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
refreshElements(sender: nil)
}
override var getElementsClosure: (_ page: Int, _ successHandler: @escaping GetElementsSuccessHandler, _ failureHandler: @escaping (Error) -> Void) -> Void {
return getElementList
}
func getElementList(_ page: Int, successHandler: @escaping GetElementsSuccessHandler, failureHandler: (_ error: Error) -> Void) {
let elements = (0...20).map { "page \(page), element index" + String($0) }
delay(2) {
successHandler(elements, true)
}
}
override func displayNoElementIfNeeded(noElement: Bool) {
noElementLabel.isHidden = !noElement
}
}
extension WithPaginateViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
let element = getElement(String.self, at: (indexPath as NSIndexPath).row)
cell.textLabel?.text = element
if elements.count == (indexPath as NSIndexPath).row + 1 {
loadNextPage()
}
return cell
}
}
| 9807548a91f196d2a8ca2dad1ac3eab0 | 30.846154 | 160 | 0.67029 | false | false | false | false |
Appudo/Appudo.github.io | refs/heads/master | static/dashs/probe/c/s/6/3.swift | apache-2.0 | 1 |
import libappudo
import libappudo_run
import libappudo_env
import Foundation
typealias ErrorResult = Int
let ErrorDefault = 1
let ErrorNone = 0
enum PostType : Int32, Codable {
case USER_REGISTER = 0
case USER_LOGIN = 1
case USER_LOGOUT = 2
case USER_LIST = 3
case USER_REMOVE = 4
case USER_PASSWORD_RESET = 5
case USER_PASSWORD_RECOVER = 6
case USER_LOGIN_CHECK = 8
case USER_ADD = 9
case USER_INVITE = 10
case USER_ADD_TO_GROUP = 11
case USER_REMOVE_FROM_GROUP = 12
case USER_GROUP_GET = 13
case USER_GROUP_UPDATE = 14
case USER_GROUP_LIST = 15
case USER_GROUP_ADD = 16
case USER_GROUP_REMOVE = 17
case USER_GET = 18
case USER_UPDATE = 19
case PROBE_LIST = 40
case PROBE_ADD = 41
case PROBE_GET = 42
case PROBE_UPDATE = 43
case PROBE_REMOVE = 44
case PROBE_USES_GET = 45
case PROBE_SETTING_LIST = 46
case PROBE_SETTING_ADD = 47
case PROBE_SETTING_REMOVE = 48
case MODULE_LIST = 60
case MODULE_GET = 61
case MODULE_PACK = 62
case MODULE_USES_GET = 63
case MODULE_ADD = 64
case MODULE_UPDATE = 65
case MODULE_REMOVE = 66
case MODULE_DOWLOAD = 67
case MODULE_INSTALL = 68
case MODULE_SHARE = 69
case MODULE_CODE_LOAD = 70
case MODULE_INSTANCE_LIST = 72
case MODULE_INSTANCE_ADD = 73
case MODULE_INSTANCE_REMOVE = 74
case MODULE_INSTANCE_SETTING_GET = 75
case RUN_LIST = 81
case RUN_GET = 82
case RUN_ADD = 84
case RUN_UPDATE_OPTIONS = 83
case RUN_UPDATE = 85
case RUN_REMOVE = 86
case RUN_USES_GET = 87
case RUN_INSTANCE_LIST = 88
case RUN_INSTANCE_ADD = 89
case RUN_INSTANCE_REMOVE = 90
case RUN_INSTANCE_UPDATE = 91
case RUN_INSTANCE_SETTING_GET = 93
case SETTING_GET = 100
case SETTING_UPDATE = 101
case REPO_LIST = 120
case REPO_ADD = 121
case REPO_UPDATE = 122
case REPO_REMOVE = 123
case CROSS_LIST = 140
case CROSS_ADD = 141
case CROSS_UPDATE = 142
case CROSS_REMOVE = 143
}
struct PostParam : FastCodable {
let cmd : PostType
}
struct IdParam : FastCodable {
let id : Int
}
struct TwoInt32Param : FastCodable {
let a : Int32
let b : Int32
}
struct ThreeInt32Param : FastCodable {
let a : Int32
let b : Int32
let c : Int32
}
struct TwoStringParam : FastCodable {
let a : String
let b : String
}
struct UpdateParam : FastCodable {
let a : String?
let b : String?
let c : String?
let d : String?
let e : String?
let m : Int?
let n : Int?
let o : Int?
let p : Int?
let q : Int?
}
/* ----------------------------------------------- */
/* user handling */
/* ----------------------------------------------- */
struct UserPermissions: OptionSet {
let rawValue: Int32
static let NONE = UserPermissions(rawValue: 0)
static let ADMIN_ALL = UserPermissions(rawValue: 1 << 0)
static let RUN_ADD = UserPermissions(rawValue: 1 << 1)
static let DISASSEMBLER_USE = UserPermissions(rawValue: 1 << 2)
static let PROBE_ADD = UserPermissions(rawValue: 1 << 3)
static let MODULE_ADD = UserPermissions(rawValue: 1 << 4)
static let MODULE_SHARE = UserPermissions(rawValue: 1 << 5)
static let USER_EDIT = UserPermissions(rawValue: 1 << 6)
static let SETTING_EDIT = UserPermissions(rawValue: 1 << 7)
static let ACCOUNT_EDIT = UserPermissions(rawValue: 1 << 8)
static let ACCOUNT_REMOVE = UserPermissions(rawValue: 1 << 9)
static let REPO_EDIT = UserPermissions(rawValue: 1 << 10)
static let CHAT_USE = UserPermissions(rawValue: 1 << 11)
static let MODULE_SOURCE = UserPermissions(rawValue: 1 << 12)
static let USER_CHANGE_LOGIN = UserPermissions(rawValue: 1 << 13)
static let REPO_ADD = UserPermissions(rawValue: 1 << 14)
func has(_ perm : UserPermissions) -> Bool {
return contains(.ADMIN_ALL) || contains(perm)
}
}
struct GroupPermissions: OptionSet {
let rawValue: Int32
static let RUN_EDIT = GroupPermissions(rawValue: 1 << 0)
static let PROBE_EDIT = GroupPermissions(rawValue: 1 << 1)
static let PROBE_VIEW_KEY = GroupPermissions(rawValue: 1 << 2)
static let MODULE_EDIT = GroupPermissions(rawValue: 1 << 3)
static let MODULE_SOURCE_EDIT = GroupPermissions(rawValue: 1 << 4)
static let MODULE_SETUP = GroupPermissions(rawValue: 1 << 5)
static let REPO_EDIT = GroupPermissions(rawValue: 1 << 6)
}
struct LoginTicket : FastCodable {
let r : Int32
let p : Int
let n : Int
let t : Int
}
struct LoginInfo {
let id : Int32
let perm : UserPermissions
let keep : Bool
}
struct LoginStringParam : FastCodable {
let a : String
let b : String?
let c : String?
let l : Int?
}
struct LoginIntParam : FastCodable {
let a : Int
let l : Int?
}
func debug(_ msg : String) {
if var f = <!Dir.tmp.open("debug.txt", [.O_CREAT, .O_RDWR]) {
if let s = <!f.stat,
s.size > 32000 {
_ = <!f.truncate(0)
}
_ = <!f.append("\(msg)\n")
}
}
var _loginArray : TimedArray? = {
do {
return try TimedArray(5*60)
} catch {
return nil
}
}()
func beforeVarParse() -> EventResult {
_ = Page.markSensitive(postKey:"password")
return .OK
}
func afterVarParse(sensitive : UnsafeTmpString) -> EventResult {
if sensitive.is_nil == false {
Page.userData = sensitive
}
return .OK
}
/*
* Try user login with name and password.
* There is an exponential backoff that increases
* with each failed login after the current backoff
* time is expired.
*/
func user_login(_ keep : Bool, _ password : UnsafeTmpString) -> ErrorResult {
let name = Post.name.value
var err = AsyncError()
let qry = SQLQry("""
WITH time AS (SELECT id, attempts = 0 OR ($2 > (last_login + (1 << attempts))) AS expired FROM users WHERE login = $1 AND locked = FALSE),
upd AS (UPDATE users SET last_login = (CASE WHEN time.expired = TRUE THEN $2
ELSE last_login END),
attempts = (CASE WHEN attempts < 32 AND time.expired = TRUE
THEN attempts + 1
ELSE attempts END)
FROM time
WHERE users.id = time.id RETURNING users.id, last_login, attempts)
SELECT users.id, key, salt, upd.last_login, upd.attempts, perm, expired, settings #>> '{}' FROM users, upd, time WHERE users.id = upd.id;
""")
let login_time = Date().to1970
qry.values = [name, login_time]
if(err <! qry.exec()) != false {
let id = qry.getAsInt32(0, 0) ?? -1
let key = qry.getAsText(0, 1) ?? ""
let salt = qry.getAsText(0, 2) ?? ""
let perm = qry.getAsInt32(0, 5) ?? 0
let expired = qry.getAsBool(0, 6) ?? false
if expired,
key == user_login_keyFrom(salt:salt, password:password),
let cookie = user_login_add(id:id, perm:perm, keep:keep) {
let settings = qry.getAsText(0, 7) ?? "{}"
print(#"{"r":0,"d":\#(id),"p":\#(perm),"c":\#(cookie),"s":\#(settings)}"#)
return ErrorNone
} else {
let last_login = qry.getAsInt(0, 3) ?? -1
let attempts = qry.getAsInt32(0, 4) ?? -1
let dist = 1 << Int(attempts)
print(#"{"r":1, "a":\#(attempts), "l":\#((last_login + dist) - login_time)}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
/*
* Generate login cookie.
*/
func user_cookie_gen(idx : Int32, t : Int, n : Int, p : Int) -> String {
return #"{"r":\#(idx),"t":\#(t),"n":\#(n),"p":\#(p)}"#
}
/*
* Generate json escaped login cookie.
*/
func user_cookie_genEscaped(idx : Int32, t : Int, n : Int, p : Int) -> String {
return #""{\"r\":\#(idx),\"t\":\#(t),\"n\":\#(n),\"p\":\#(p)}""#
}
/*
* Generate key with random salt from password.
*/
func user_login_keyFrom(password : UnsafeTmpString) -> (String, String)? {
let bufferA = ManagedCharBuffer.create(128)
var bufferB = ManagedCharBuffer.create(192)
if let rawSaltLen = <!Rand.bytes(bufferA, sizeLimit:64),
let saltLen = <!Base64.encode(bufferA, bufferB, inSizeLimit:rawSaltLen),
let salt = bufferB.toString(getBase64len(&bufferB, saltLen)),
let rawCryptLen = <!SCRYPT.create(password, bufferB, bufferA, outSizeLimit:128, saltSizeLimit:getBase64len(&bufferB, saltLen)),
let cryptLen = <!Base64.encode(bufferA, bufferB, inSizeLimit:rawCryptLen),
let cryptKey = bufferB.toString(getBase64len(&bufferB, cryptLen)) {
return (cryptKey, salt)
}
return nil
}
/*
* Generate key with salt from password.
*/
func user_login_keyFrom(salt : String, password : UnsafeTmpString) -> String? {
let bufferA = ManagedCharBuffer.create(128)
var bufferB = ManagedCharBuffer.create(192)
if let saltLen = bufferB.fill(salt),
let rawCryptLen = <!SCRYPT.create(password, bufferB, bufferA, outSizeLimit:128, saltSizeLimit:saltLen),
let cryptLen = <!Base64.encode(bufferA, bufferB, inSizeLimit:rawCryptLen) {
return bufferB.toString(getBase64len(&bufferB, cryptLen))
}
return nil
}
/*
* Add new login ticket to TimedArray, database and cookie.
*/
func user_login_add(id : Int32, perm : Int32, keep : Bool = false) -> String? {
let p : Int = user_ticket_fromInfo(id:id, perm:perm, keep:keep)
var cookie = ""
if let rt = <!Rand.int64(),
let rn = <!Rand.int64(),
let arr = _loginArray {
let idx = arr.Insert(rt, rn, p)
if(idx == 0) {
return nil;
}
cookie = user_cookie_gen(idx:idx, t:rt, n:rn, p:p)
let qry = SQLQry("UPDATE users SET attempts = 0, login_cookie = $2, keep = $3 WHERE id = $1")
qry.values = [id, cookie, keep]
if <!qry.exec() == false {
return nil
}
Cookie.lt.set(cookie, expire:keep ? (60*60*24*265) : (5*60), secureOnly:true)
return user_cookie_genEscaped(idx:idx, t:rt, n:rn, p:p)
}
return nil;
}
/*
* Logout user on permission change.
*/
func user_change_logout(id : Int32) -> Void {
let qry = SQLQry("""
UPDATE users u SET login_cookie = NULL FROM
(SELECT id, login_cookie FROM users WHERE id = $1 FOR UPDATE) o
WHERE u.id = o.id RETURNING o.login_cookie;
""")
qry.values = [id]
if <!qry.exec() != false,
let ticket = qry.getAsText(0, 0),
let info = LoginTicket.from(json:ticket),
let arr = _loginArray {
_ = arr.Remove(info.r)
}
}
/*
* Remove ticket from TimedArray, database and cookie.
*/
func user_login_remove(id : Int32) -> Bool {
let ticket = Cookie.lt.value
Cookie.lt.remove()
let qry = SQLQry("UPDATE users SET login_cookie = NULL WHERE id = $1")
qry.values = [id]
if <!qry.exec() == false {
return false
}
if let arr = _loginArray,
let info = LoginTicket.from(json:ticket) {
if(user_ticket_toId(info.p) == id &&
arr.Remove(info.r) == false) {
return false
}
}
return true
}
/*
* Check if ticket is alive in TimedArray or database.
*/
func user_login_get(_ info : LoginTicket) -> Bool {
let linfo = user_ticket_toInfo(info.p)
var idx : Int32 = 0
if let arr = _loginArray,
let v = arr.GetAndUpdate(info.r),
v.0 == info.t,
v.1 == info.n,
user_ticket_toId(v.2) == linfo.id {
Page.userData = linfo
return true
}
var new_cookie = ""
let old_cookie = user_cookie_gen(idx:info.r, t:info.t, n:info.n, p:info.p)
if let rt = <!Rand.int64(),
let rn = <!Rand.int64(),
let arr = _loginArray {
idx = arr.Insert(rt, rn, Int(-1))
if(idx == 0) {
return false;
}
new_cookie = user_cookie_gen(idx:idx, t:rt, n:rn, p:info.p)
let qry = SQLQry("UPDATE users SET login_cookie = $3 WHERE id = $1 AND login_cookie = $2 AND keep = TRUE RETURNING id;")
qry.values = [linfo.id, old_cookie, new_cookie]
if <!qry.exec() == false || qry.numRows == 0 {
_ = arr.Remove(idx)
return false
}
Cookie.lt.set(new_cookie, expire:(60*60*24*265), secureOnly:true)
Page.userData = linfo
return arr.Update(idx, rt, rn, info.p)
}
return false
}
/*
* Validate login.
*/
func _user_login_check() -> Bool {
let ticket = Cookie.lt.value
if ticket != "",
let info = LoginTicket.from(json:ticket) { // does login ticket exist and format is ok?
return user_login_get(info) != false // is ticket alive?
}
return false
}
/*
* Check login only if needed.
*/
func user_login_check(_ type : PostType) -> Bool {
return type == .USER_LOGIN ||
type == .USER_REGISTER ||
type == .USER_PASSWORD_RESET ||
type == .USER_PASSWORD_RECOVER ||
type == .USER_LOGIN_CHECK ||
_user_login_check()
}
func user_ticket_toId(_ p : Int) -> Int32 {
return Int32(bitPattern:UInt32(p & 0xFFFFFFFF))
}
func user_getInfo() -> LoginInfo? {
return Page.userData as? LoginInfo
}
func user_getPerm() -> UserPermissions {
if let data = Page.userData as? LoginInfo {
return data.perm
}
return UserPermissions()
}
func user_ticket_toPerm(_ p : Int) -> UserPermissions {
let _p = UInt(bitPattern:p)
return UserPermissions(rawValue:Int32(bitPattern:UInt32((_p >> 32) & 0x7FFFFFFF)))
}
func user_ticket_toInfo(_ p : Int) -> LoginInfo {
let _p = UInt(bitPattern:p)
return LoginInfo(id:Int32(bitPattern:UInt32(_p & 0xFFFFFFFF)), perm:UserPermissions(rawValue:Int32(bitPattern:UInt32((_p >> 32) & 0x7FFFFFFF))), keep:(_p & ~0x7FFFFFFFFFFFFFFF) != 0)
}
func user_ticket_fromInfo(id : Int32, perm : Int32, keep : Bool) -> Int {
return Int(bitPattern:(UInt(id) | UInt(perm & 0x7FFFFFFF) << 32) | ((keep ? UInt(1) : UInt(0)) << 63))
}
/*
* Check current login.
*/
func user_check() -> ErrorResult {
let ticket = Cookie.lt.value
if ticket != "",
let info = LoginTicket.from(json:ticket),
user_login_get(info) != false {
let li = user_ticket_toInfo(info.p)
let cookie = user_cookie_genEscaped(idx:info.r, t:info.t, n:info.n, p:info.p)
print(#"{"r":0,"d":\#(li.id),"p":\#(li.perm.rawValue),"c":\#(cookie)}"#)
if(!li.keep) {
let cookie = user_cookie_gen(idx:info.r, t:info.t, n:info.n, p:info.p)
Cookie.lt.set(cookie, expire:5*60, secureOnly:true)
}
return ErrorNone
}
return ErrorDefault
}
/*
* Logout current user.
*/
func user_logout() -> ErrorResult {
var err = AsyncError()
var id : Int32 = -1
let ticket = Cookie.lt.value
if ticket != "",
let info = LoginTicket.from(json:ticket) {
id = user_ticket_toId(info.p)
}
if(Post.ext_data.value != "") {
let qry = SQLQry("UPDATE users SET login_cookie = NULL, settings = $2 WHERE id = $1;")
qry.values = [id, Post.ext_data.value]
if(err <! qry.exec()) != false {
}
} else {
let qry = SQLQry("UPDATE users SET login_cookie = NULL WHERE id = $1;")
qry.values = [id]
if(err <! qry.exec()) != false {
}
}
Cookie.lt.remove()
print(#"{"r":0}"#)
return ErrorNone
}
func getBase64len(_ buffer : inout ManagedCharBuffer, _ bufferLen : Int) -> Int {
var len = bufferLen
len -= 1
len -= buffer.data[len] == 61 ? 1 : 0
len -= buffer.data[len] == 61 ? 1 : 0
return len + 1
}
func user_login_reset_ticket() -> String? {
let inBuffer = ManagedCharBuffer.create(128)
var outBuffer = ManagedCharBuffer.create(128)
if let r = <!Rand.bytes(inBuffer, sizeLimit:22),
let e = <!Base64.encode(inBuffer, outBuffer, inOffset:0, inSizeLimit:r) {
return outBuffer.toString(getBase64len(&outBuffer, e))
}
return nil
}
func user_login_reset() -> ErrorResult {
if let data = LoginStringParam.from(json:Post.ext_data.value) {
let login = data.a
let lID = data.l ?? 1
let time = Date().to1970
// remove old items after 60 * 5 * 12 seconds = 30 minutes
var qry = SQLQry("""
DELETE FROM users_register WHERE time + 3600 < $1::bigint and type = 1
""")
qry.values = [time]
_ = <!qry.exec()
// create random ticket
guard let ticket = user_login_reset_ticket() else {
return ErrorDefault
}
_ = <!SQLQry.begin()
// store ticket to db
qry = SQLQry("""
WITH qry AS (
SELECT id FROM users WHERE login = $1
),
ins AS (
INSERT INTO users_register (users_id, ticket, time, type) SELECT id, $2, $3, 1 FROM qry RETURNING users_id
)
SELECT mail FROM users, ins WHERE users.id = ins.users_id;
""")
qry.values = [login, ticket, time]
if <!qry.exec() == false {
return ErrorDefault
}
let mail = qry.getAsText(0, 0) ?? ""
// send validation mail with template
var m = Mail()
m.CTtype = "text/html"
if var f = <!Dir.login_reset.open("reset_template", .O_APPUDO) {
let url = Link.to(url:"", isLocal:true).toHostString(true)
_ = <!f.write(#"{"url":"\#(url)","name":"\#(login)","ticket":"\#(ticket)","lID":\#(lID)}"#)
if let r = <!f.readAsText(8),
let s = <!f.readAsText(Int(r) ?? 0),
<!m.send(mail, s, f) != false {
print(#"{"r":0}"#)
_ = <!SQLQry.end()
return ErrorNone
}
}
_ = <!SQLQry.rollback()
}
return ErrorDefault
}
func user_login_recover(_ password : UnsafeTmpString) -> ErrorResult {
if let data = LoginStringParam.from(json:Post.ext_data.value),
let gen = user_login_keyFrom(password:password) {
let login = data.a
let ticket = data.b ?? ""
let qry = SQLQry("""
WITH qry AS (
SELECT id FROM users WHERE login = $1
),
del AS (
DELETE FROM users_register USING qry WHERE users_id = qry.id AND ticket = $2 AND type = 1 RETURNING users_id
)
UPDATE users SET key = $3, salt = $4 FROM del WHERE id = del.users_id RETURNING id;
""")
qry.values = [login, ticket, gen.0, gen.1]
if <!qry.exec() != false && qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
}
return ErrorDefault
}
func user_register(_ password : UnsafeTmpString) -> ErrorResult {
let time = Date().to1970
// remove old items after 60 * 60 * 24 × 30 seconds = 30 days
// pending from db
let qry = SQLQry("""
WITH qry AS (
DELETE FROM users_register WHERE time + 2592000 < $1::bigint and type = 0
RETURNING users_id
)
DELETE FROM users
USING qry
WHERE id = qry.users_id;
""")
qry.values = [time]
if <!qry.exec() != false {
/*
for i in 0..<qry.numRows {
if let mail = qry.getAsText(i, 0) {
}
}
*/
}
if let data = LoginStringParam.from(json:Post.ext_data.value),
let gen = user_login_keyFrom(password:password) {
let login = data.a
let ticket = data.b ?? ""
let mail = data.c ?? ""
_ = <!SQLQry.begin()
let qry = SQLQry("""
WITH del AS (
DELETE FROM users_register WHERE ticket = $3 RETURNING users_id
)
UPDATE users SET login = $1, key = $4, salt = $5 FROM del WHERE users.id = del.users_id AND users.mail = $2 RETURNING id;
""")
qry.values = [login, mail, ticket, gen.0, gen.1]
if <!qry.exec() == false {
return ErrorDefault
}
if qry.numRows != 0 {
_ = <!SQLQry.end()
print(#"{"r":0}"#)
return ErrorNone
}
_ = <!SQLQry.rollback()
}
return ErrorDefault
}
func user_invite() -> ErrorResult {
let time = Date().to1970
let perm = user_getPerm()
if perm.has(.USER_EDIT),
let data = LoginIntParam.from(json:Post.ext_data.value) {
let lID = data.l ?? 1
guard let ticket = user_login_reset_ticket() else {
return ErrorDefault
}
_ = <!SQLQry.begin()
let qry = SQLQry("""
WITH ins AS (
INSERT INTO users_register (users_id, ticket, time, type)
SELECT id, $2, $3, 0 FROM users WHERE id = $1 RETURNING users_id
)
SELECT mail FROM users, ins WHERE id = ins.users_id;
""")
qry.values = [data.a, ticket, time]
if <!qry.exec() == false {
return ErrorDefault
}
if qry.numRows != 0 {
let mail = qry.getAsText(0, 0) ?? ""
// send validation mail with template
var m = Mail()
m.CTtype = "text/html"
if var f = <!Dir.login_invite.open("invite_template", .O_APPUDO) {
let url = Link.to(url:"", isLocal:true).toHostString(true)
_ = <!f.write(#"{"url":"\#(url)","mail":"\#(mail)","ticket":"\#(ticket)","lID":\#(lID)}"#)
if let r = <!f.readAsText(8),
let s = <!f.readAsText(Int(r) ?? 0),
<!m.send(mail, s, f) != false {
print(#"{"r":0}"#)
_ = <!SQLQry.end()
return ErrorNone
}
}
}
_ = <!SQLQry.rollback()
}
return ErrorDefault
}
func user_add() -> ErrorResult {
let perm = user_getPerm()
if perm.has(.USER_EDIT),
let data = LoginStringParam.from(json:Post.ext_data.value) {
let mail = data.a
let user_perm = data.l ?? 0
let qry = SQLQry("""
INSERT INTO users (login, mail, login_cookie, key, last_login, salt, attempts, keep, perm)
SELECT NULL, $1, NULL, '', 0, '', 0, FALSE, $2
RETURNING id;
""")
qry.values = [mail, user_perm]
if <!qry.exec() == false {
return ErrorDefault
}
let id = qry.getAsInt32(0, 0) ?? -1
print(#"{"r":0,"d":\#(id)}"#)
return ErrorNone
}
return ErrorDefault
}
func user_update(_ password : UnsafeTmpString) -> ErrorResult {
if let user = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value),
let userId = data.m {
let admin = user.perm.has(.USER_EDIT)
if(admin || (user.id == userId && user.perm.has(.ACCOUNT_EDIT))) {
let change_login = user.perm.has(.USER_CHANGE_LOGIN)
var qryArgs : [Any] = [userId]
var optArg = 2
var args = ""
if password.is_nil == false {
if change_login == true,
let gen = user_login_keyFrom(password:password) {
args += "key = $\(optArg),salt = $\(optArg + 1),"
qryArgs.append(gen.0)
qryArgs.append(gen.1)
optArg += 2
} else {
return ErrorDefault
}
}
if let login = data.a {
if(!change_login) {
return ErrorDefault
}
args += "login = $\(optArg),"
qryArgs.append(login)
optArg += 1
}
if let mail = data.b {
args += "mail = $\(optArg),"
qryArgs.append(mail)
optArg += 1
}
if let perm = data.n {
args += "perm = $\(optArg),"
qryArgs.append(perm)
optArg += 1
}
if let locked = data.o {
args += "locked = $\(optArg),"
qryArgs.append(locked == 1 ? true : false)
optArg += 1
}
let qryStr = """
UPDATE users SET \(args.dropLast()) WHERE id = $1 RETURNING id
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
var err = AsyncError()
if (err <! qry.exec()) != false {
if(qry.numRows != 0) {
if let _ = data.n,
user.id != userId {
user_change_logout(id:Int32(userId))
}
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
}
return ErrorDefault
}
func user_update_group() -> ErrorResult {
if let user = user_getInfo(),
user.perm.has(.USER_EDIT),
let data = UpdateParam.from(json:Post.ext_data.value),
let groupId = data.m {
var qryArgs : [Any] = [groupId]
var optArg = 2
var args = ""
var update_perm = "SELECT"
if let name = data.a {
args += "name = $\(optArg),"
qryArgs.append(name)
optArg += 1
}
if let desc = data.b {
args += "description = $\(optArg),"
qryArgs.append(desc)
optArg += 1
}
let update = optArg == 2 ?
"SELECT"
:
"UPDATE groups SET \(args.dropLast()) WHERE id = $1 RETURNING id"
if let userId = data.n,
let perm = data.o {
update_perm = "UPDATE users_groups SET perm = $\(optArg + 1) WHERE users_id = $\(optArg) AND groups_id = $1 RETURNING users_id"
qryArgs.append(userId)
qryArgs.append(perm)
optArg += 2
}
let qryStr = """
WITH update_perm AS (
\(update_perm)
),
update AS (
\(update)
)
SELECT * FROM update_perm, update;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
var err = AsyncError()
if (err <! qry.exec()) != false {
if(qry.numRows != 0) {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func user_remove() -> ErrorResult {
if let user = user_getInfo(),
let data = LoginIntParam.from(json:Post.ext_data.value),
user.perm.has(.USER_EDIT) || (data.a == user.id && user.perm.has(.ACCOUNT_REMOVE)) {
let id = data.a
let rm = data.l ?? 1
let qry = (id == user.id || rm == 1) ?
SQLQry("""
WITH _runs AS (
DELETE FROM runs WHERE users_id = $1 RETURNING TRUE
),
_modules AS (
DELETE FROM modules WHERE users_id = $1 RETURNING TRUE
),
_probes AS (
DELETE FROM probes WHERE users_id = $1 RETURNING TRUE
),
_repos AS (
DELETE FROM repositories WHERE users_id = $1 RETURNING TRUE
),
del AS (
DELETE FROM users WHERE users.id = $1 RETURNING users.id
)
SELECT id, $2::integer, (SELECT TRUE FROM _runs, _modules, _probes, _repos) FROM del;
""")
:
SQLQry("""
WITH _runs AS (
UPDATE runs SET users_id = $2 WHERE users_id = $1 RETURNING TRUE
),
_modules AS (
UPDATE modules SET users_id = $2 WHERE users_id = $1 RETURNING TRUE
),
_probes AS (
UPDATE probes SET users_id = $2 WHERE users_id = $1 RETURNING TRUE
),
_repos AS (
UPDATE repositories SET users_id = $2 WHERE users_id = $1 RETURNING TRUE
),
del AS (
DELETE FROM users WHERE users.id = $1 RETURNING users.id
)
SELECT id, (SELECT TRUE FROM _runs, _modules, _probes, _repos) FROM del;
""")
qry.values = [id, user.id]
if <!qry.exec() == false || qry.numRows == 0 {
return ErrorDefault
}
print(#"{"r":0}"#)
return ErrorNone
}
return ErrorDefault
}
struct UserListParam : FastCodable {
let i : Int?
let p : Int?
let o : Int?
let f1 : String?
}
func printUser(_ id : Int32, _ name : String, _ mail : Bool) {
print(#"{"id":\#(id),"n":"\#(name)""#)
if(mail) {
print(#","m":1"#)
}
print("},")
}
func user_list() -> ErrorResult {
if let user = user_getInfo(),
user.perm.has(.USER_EDIT) != false,
let info = UserListParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 1:
fallthrough
default:
orderQry += "login "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page]
var filterQry = "TRUE "
var optArg = 3
if let f1 = info.f1 {
filterQry += "AND login LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
let qryStr = """
SELECT id, CASE WHEN login IS NULL THEN mail ELSE login END,
CASE WHEN login IS NULL THEN TRUE ELSE FALSE END,
row_number() OVER (\(orderQry)) AS nr FROM users u
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 3) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0),
let name = qry.getAsText(i, 1) {
let mail = qry.getAsBool(i, 2) ?? false
printUser(id, name, mail)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
struct UserGroupParam : FastCodable {
let i : Int?
let p : Int?
let o : Int?
let f1 : String?
let f2 : String?
let f3 : Bool?
let id : Int32?
}
func printGroup(_ id : Int32, _ name : String) {
print(#"{"id":\#(id),"n":"\#(name)"},"#)
}
func user_list_group() -> ErrorResult {
if let user = user_getInfo(),
let info = UserGroupParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let id = info.id ?? user.id
var admin = user.perm.has(.USER_EDIT)
if info.id != nil {
if(!admin) {
return ErrorDefault
}
admin = false
}
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 2:
orderQry += "g.description::bytea "
case 1:
fallthrough
default:
orderQry += "g.name::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page]
var filterQry = "TRUE "
var optArg = 3
if let f1 = info.f1 {
filterQry += "AND g.name LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if let f2 = info.f2 {
filterQry += "AND g.description LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f2)
}
if(!admin) {
filterQry += "AND id IN(SELECT groups_id FROM users_groups WHERE users_id = $\(optArg))"
qryArgs.append(id)
}
let qryStr = """
SELECT g.id, g.name,
row_number() OVER (\(orderQry)) AS nr FROM groups g
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0),
let name = qry.getAsText(i, 1) {
printGroup(id, name)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
func user_add_group() -> ErrorResult {
let perm = user_getPerm()
if perm.has(.USER_EDIT),
let data = UpdateParam.from(json:Post.ext_data.value) {
if let name = data.a,
let description = data.b {
let qry = SQLQry("INSERT INTO groups(name, description) VALUES ($1, $2) RETURNING id;")
qry.values = [name, description]
var err = AsyncError()
if (err <! qry.exec()) != false {
let id = qry.getAsInt32(0, 0) ?? -1
print(#"{"r":0,"d":\#(id)}"#)
return ErrorNone
} else {
return ErrorResult(err.asSQL.rawValue)
}
} else if let userId = data.n,
let groupId = data.m {
let qry = SQLQry("INSERT INTO users_groups(users_id, groups_id, perm) VALUES ($1, $2, 0) RETURNING users_id;")
qry.values = [userId, groupId]
var err = AsyncError()
if (err <! qry.exec()) != false {
print(#"{"r":0}"#)
return ErrorNone
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func user_remove_group() -> ErrorResult {
let perm = user_getPerm()
if perm.has(.USER_EDIT),
let data = UpdateParam.from(json:Post.ext_data.value),
let groupId = data.m {
if let userId = data.n {
let qry = SQLQry("DELETE FROM users_groups WHERE users_id = $1 AND groups_id = $2 RETURNING users_id;")
qry.values = [userId, groupId]
var err = AsyncError()
if (err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
} else {
let qry = SQLQry("DELETE FROM groups WHERE id = $1 RETURNING id;")
qry.values = [groupId]
var err = AsyncError()
if (err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func user_add_to_group() -> ErrorResult {
let perm = user_getPerm()
if perm.has(.USER_EDIT),
let data = ThreeInt32Param.from(json:Post.ext_data.value) {
let userId = data.a
let groupId = data.b
let perm = data.c
let qry = SQLQry("INSERT INTO users_groups (users_id, groups_id, perm) VALUES ($1, $2, $3);")
qry.values = [userId, groupId, perm]
var err = AsyncError()
if (err <! qry.exec()) != false {
print(#"{"r":0}"#)
return ErrorNone
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
return ErrorDefault
}
func user_remove_from_group() -> ErrorResult {
let perm = user_getPerm()
if perm.has(.USER_EDIT),
let data = TwoInt32Param.from(json:Post.ext_data.value) {
let userId = data.a
let groupId = data.b
let qry = SQLQry("DELETE FROM users_groups WHERE users_id = $1 AND groups_id = $2 RETURNING users_id;")
qry.values = [userId, groupId]
var err = AsyncError()
if (err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
return ErrorDefault
}
func user_get() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.USER_EDIT) != false
if(admin || uinfo.id == data.id) {
let qry = SQLQry("SELECT id, login, mail, perm, locked, last_login FROM users WHERE id = $1;")
qry.values = [data.id]
var err = AsyncError()
if (err <! qry.exec()) != false && qry.numRows != 0 {
let id = qry.getAsInt32(0, 0) ?? -1
let login = qry.getAsText(0, 1) ?? ""
let mail = qry.getAsText(0, 2) ?? ""
let perm = qry.getAsInt32(0, 3) ?? 0
let locked = qry.getAsBool(0, 4) ?? false
let last_login = qry.getAsInt(0, 5) ?? 0
print(#"{"r":0,"id":\#(id),"p":\#(perm),"n":"\#(login)","m":"\#(mail)","l":\#(locked ? 1 : 0),"t":"\#(last_login)"}"#)
return ErrorNone
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func user_get_group_setting() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value),
let groupId = data.m {
let userId = data.n ?? -1
let admin = uinfo.perm.has(.USER_EDIT) != false
if(admin || (data.n != nil && uinfo.id == userId)) {
let qry = SQLQry("SELECT g.id, g.name, g.description, a.perm FROM groups g LEFT OUTER JOIN users_groups a ON(g.id = a.groups_id AND a.users_id = $1) WHERE g.id = $2;")
qry.values = [data.n == nil ? Optional<Int>.none as Any : userId, groupId]
var err = AsyncError()
if (err <! qry.exec()) != false && qry.numRows != 0 {
let id = qry.getAsInt32(0, 0) ?? -1
let name = qry.getAsText(0, 1) ?? ""
let desc = qry.getAsText(0, 2) ?? ""
let perm = qry.getAsInt32(0, 3) ?? 0
print(#"{"r":0,"id":\#(id),"p":\#(perm),"n":"\#(name)","d":"\#(desc)"}"#)
return ErrorNone
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
struct UsesParam : FastCodable {
let i : Int?
let p : Int?
let o : Int?
let f1 : String?
let f2 : String?
let id : Int
}
func printUse(_ id : Int32, _ name : String, _ perm : Int32) {
print(#"{"id":\#(id),"n":"\#(name)","p":\#(perm)},"#)
}
func uses_get(_ info : UsesParam, _ table : String) -> ErrorResult {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 2:
orderQry += "u.description::bytea "
case 1:
fallthrough
default:
orderQry += "u.login::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page, info.id]
var filterQry = "TRUE "
var optArg = 4
if let f1 = info.f1 {
filterQry += "AND u.login LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if let f2 = info.f2 {
filterQry += "AND u.description LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f2)
}
let qryStr = """
WITH sel AS (
SELECT users_id, groups_id FROM \(table) WHERE id = $3
),
perm AS (
SELECT s.users_id, perm FROM users_groups g, sel s WHERE g.groups_id = s.groups_id
),
unordered AS (
SELECT DISTINCT ON(u.id) u.id, u.login, CASE WHEN p.perm IS NULL THEN -1 ELSE p.perm END,
row_number() OVER (\(orderQry)) AS nr FROM users u LEFT OUTER JOIN perm p ON (p.users_id = u.id)
WHERE ((u.perm & \(UserPermissions.ADMIN_ALL.rawValue)) != 0 OR u.id IN (SELECT users_id FROM sel) OR p.users_id = u.id)
AND \(filterQry)
LIMIT $2::bigint OFFSET $1::bigint
)
SELECT * FROM unordered
ORDER BY nr DESC;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 3) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0),
let name = qry.getAsText(i, 1),
let perm = qry.getAsInt32(i, 2) {
printUse(id, name, perm)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
return ErrorDefault
}
/* ----------------------------------------------- */
/* probe handling */
/* ----------------------------------------------- */
struct ProbeParam : FastCodable {
let id : Int?
let i : Int?
let p : Int?
let o : Int?
let f1 : String?
let f2 : String?
let f3 : Bool?
}
func printProbe(_ id : Int32, _ name : String) {
print(#"{"id":\#(id),"n":"\#(name)"},"#)
}
func printConnectedProbe(_ id : Int32, _ pid : Int32, _ identifier : String) {
print(#"{"id":\#(id),"pid":\#(id),"n":"\#(identifier)"},"#)
}
func probe_list() -> ErrorResult {
if let user = user_getInfo(),
let info = ProbeParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let connected = info.f3 ?? false
let admin = user.perm.has(.ADMIN_ALL)
let ident = connected ? "identifier " : "login "
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 2:
orderQry += "n.description::bytea "
case 1:
fallthrough
default:
orderQry += ident + "::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page]
var filterQry = connected ? "p.id = a.probes_id " : "TRUE "
var optArg = 3
if let f1 = info.f1 {
filterQry += "AND \(ident) LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if let f2 = info.f2 {
filterQry += "AND description LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f2)
}
if(!admin) {
filterQry += "AND (groups_id IN(SELECT groups_id FROM users_groups WHERE users_id = $\(optArg)) OR users_id = $\(optArg))"
qryArgs.append(user.id)
}
let qryStr = """
SELECT p.id, \(ident),
row_number() OVER (\(orderQry)) AS nr \(connected ? ",a.probes_settings_id" : "") FROM probes p \(connected ? ",probes_active a" : "")
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0),
let name = qry.getAsText(i, 1) {
if(connected) {
let pid = qry.getAsInt32(i, 3) ?? -1
printConnectedProbe(id, pid, name)
} else {
printProbe(id, name)
}
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
struct ProbeAddParam : FastCodable {
let n : String
let d : String
let g : Int?
}
func probe_add(_ key : UnsafeTmpString) -> ErrorResult {
if let uinfo = user_getInfo(),
uinfo.perm.has(.PROBE_ADD) != false,
let data = ProbeAddParam.from(json:Post.ext_data.value) {
_ = <!SQLQry.begin()
let qry = SQLQry("""
WITH ins AS (
INSERT INTO probes(login, description, groups_id, users_id, key) VALUES ($1, $2, $3, $4, $5) RETURNING id
)
INSERT INTO probes_settings(probes_id) SELECT id FROM ins RETURNING probes_id;
""")
qry.values = [data.n, data.d, data.g ?? Optional<Int>.none as Any, uinfo.id, key]
var err = AsyncError()
if (err <! qry.exec()) != false {
let id = qry.getAsInt32(0, 0) ?? -1
if let _ = err <! Dir.disassembly.mkpath("\(id)", [.U0700, .G0050, .O0001]) {
_ = <!SQLQry.end()
print(#"{"r":0, "d": \#(id)}"#)
return ErrorNone
} else {
_ = <!SQLQry.rollback()
if(err.hasError) {
return ErrorResult(err.errValue)
}
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
return ErrorDefault
}
struct ProbeGetParam : FastCodable {
let pid : Int?
let sid : Int?
}
func probe_get() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = ProbeGetParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH probe AS (
SELECT id, login, key, groups_id, users_id, description FROM probes WHERE id = $2
),
setting AS (
SELECT probes_id, identifier, settings FROM probes_settings WHERE id = $3
),
res AS(
SELECT CASE WHEN id IS NULL THEN probes_id ELSE id END, login, key, groups_id, users_id, description, identifier, settings
FROM probe m FULL JOIN setting s ON(m.id = s.probes_id)
),
perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, probes p, res
WHERE g.users_id = $1
AND p.id = res.id
AND p.groups_id = g.groups_id
)
SELECT login,
(CASE WHEN $4::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.PROBE_VIEW_KEY.rawValue)) != 0 THEN key ELSE NULL END),
users_id, groups_id, description, identifier, settings #>> '{}' FROM res m, perm p WHERE
($4::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.PROBE_EDIT.rawValue)) != 0)
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.pid ?? Optional<Int32>.none as Any, data.sid ?? Optional<Int32>.none as Any, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
let login = qry.getAsText(0, 0) ?? ""
let key = qry.getAsText(0, 1) ?? ""
let users_id = qry.getAsInt32(0, 2) ?? -1
let groups_id = qry.getAsInt32(0, 3) ?? -1
let desc = qry.getAsText(0, 4) ?? ""
let identifier = qry.getAsText(0, 5) ?? ""
let settings = qry.getAsText(0, 6) ?? "{}"
let sid = data.sid == nil ? "" : #""i":"\#(identifier)","s":\#(settings),"#
let pid = data.pid == nil ? "" : #""n":"\#(login)","k":"\#(key)","d":"\#(desc)","u":\#(users_id),"g":\#(groups_id),"#
print(#"{\#(pid)\#(sid)"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func probe_remove() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, probes p
WHERE g.users_id = $1
AND p.id = $2
AND p.groups_id = g.groups_id
),
del AS (
DELETE FROM probes m USING perm p WHERE id = $2 AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.PROBE_EDIT.rawValue)) != 0) RETURNING m.id
)
DELETE FROM probes_settings s USING del WHERE probes_id = del.id RETURNING s.id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
_ = Dir.disassembly.remove("\(data.id)")
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func probe_update(_ password : UnsafeTmpString) -> ErrorResult {
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let user_edit = uinfo.perm.has(.USER_EDIT)
let empty = "SELECT"
var update_probe = empty
var update_setting = empty
var args = ""
var qryArgs : [Any] = [uinfo.id, data.m ?? Optional<Int32>.none as Any, data.n ?? Optional<Int32>.none as Any, admin]
var optArg = 5
if let login = data.a {
args += "login = $\(optArg),"
qryArgs.append(login)
optArg += 1
}
if password.is_nil == false {
args += "key = $\(optArg),"
qryArgs.append(password)
optArg += 1
}
if let description = data.b {
args += "description = $\(optArg),"
qryArgs.append(description)
optArg += 1
}
if let users_id = data.o {
if user_edit == false {
return ErrorDefault
}
args += "users_id = $\(optArg),"
qryArgs.append(users_id)
optArg += 1
}
if let groups_id = data.p {
if user_edit == false {
return ErrorDefault
}
args += "groups_id = $\(optArg),"
qryArgs.append(groups_id)
optArg += 1
}
if(args != "") {
update_probe = "UPDATE probes p SET \(args.dropLast()) FROM has, probe WHERE p.id = probe.id AND has.perm RETURNING p.id"
}
args = ""
if let identifier = data.c {
args += "identifier = $\(optArg),"
qryArgs.append(identifier)
optArg += 1
}
if let settings = data.d {
args += "settings = $\(optArg),"
qryArgs.append(settings)
optArg += 1
}
if(args != "") {
update_setting = "UPDATE probes_settings s SET \(args.dropLast()) FROM has WHERE s.id = $3 AND has.perm RETURNING s.id"
}
let qryStr = """
WITH probe AS (
SELECT CASE WHEN $2::bigint IS NULL THEN (SELECT probes_id FROM probes_settings WHERE id = $3::bigint) ELSE $2::bigint END AS id
),
perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, probes p, probe
WHERE g.users_id = $1
AND p.id = probe.id
AND p.groups_id = g.groups_id
),
has AS (
SELECT ($4::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.PROBE_EDIT.rawValue)) != 0) AS perm
FROM probes m, perm p, probe WHERE m.id = probe.id
),
upd1 AS (
\(update_probe)
),
upd2 AS (
\(update_setting)
)
SELECT* FROM upd1, upd2;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func probe_get_uses() -> ErrorResult {
let perm = user_getPerm()
if perm.has(.USER_EDIT) != false,
let info = UsesParam.from(json:Post.ext_data.value) {
return uses_get(info, "probes")
}
return ErrorDefault
}
func printProbeSetting(_ id : Int32, _ name : String) {
print(#"{"id":\#(id),"n":"\#(name)"},"#)
}
func probe_list_settings() -> ErrorResult {
if let user = user_getInfo(),
let info = ProbeParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let admin = user.perm.has(.ADMIN_ALL)
let probeId = info.id ?? -1
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 1:
fallthrough
default:
orderQry += "s.identifier::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page, probeId]
var filterQry = "s.probes_id = $3 "
var optArg = 4
if let f1 = info.f1 {
filterQry += "AND s.identifier LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if(!admin) {
filterQry += "AND probes_id IN(SELECT p.id FROM probes p, users_groups g WHERE (g.users_id = $\(optArg) AND g.groups_id = p.groups_id) OR p.users_id = $\(optArg))"
qryArgs.append(user.id)
}
let qryStr = """
SELECT s.id, s.identifier,
row_number() OVER (\(orderQry)) AS nr FROM probes_settings s
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0) {
let name = qry.getAsText(i, 1) ?? ""
printProbeSetting(id, name)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
func probe_add_setting() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value),
let identifier = data.a {
let admin = uinfo.perm.has(.ADMIN_ALL)
if let setting_id = data.m {
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, probes p, probes_settings s
WHERE g.users_id = $1
AND s.id = $2
AND s.probes_id = p.id
AND p.groups_id = g.groups_id
),
sel AS (
SELECT m.id FROM probes m, probes_settings s, perm p WHERE s.id = $2 AND m.id = s.probes_id AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.PROBE_EDIT.rawValue)) != 0)
)
INSERT INTO probes_settings(probes_id, identifier, settings) SELECT probes_id, $4, settings
FROM probes_settings s, sel
WHERE s.id = $2 AND probes_id = sel.id RETURNING id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, setting_id, admin, identifier]
var err = AsyncError()
if (err <! qry.exec()) != false {
if let id = qry.getAsInt32(0, 0) {
print(#"{"r":0, "d": \#(id)}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
} else
if let probe_id = data.n {
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, probes p
WHERE g.users_id = $1
AND p.id = $2
AND p.groups_id = g.groups_id
),
sel AS (
SELECT m.id FROM probes m, perm p WHERE m.id = $2 AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.PROBE_EDIT.rawValue)) != 0)
)
INSERT INTO probes_settings(probes_id, identifier) SELECT id, $4
FROM sel
WHERE sel.id IS NOT NULL RETURNING id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, probe_id, admin, identifier]
var err = AsyncError()
if (err <! qry.exec()) != false {
if let id = qry.getAsInt32(0, 0) {
print(#"{"r":0, "d": \#(id)}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
}
return ErrorDefault
}
func probe_remove_setting() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, probes p, probes_settings s
WHERE g.users_id = $1
AND s.id = $2
AND s.probes_id = p.id
AND p.groups_id = g.groups_id
),
sel AS (
SELECT m.id FROM probes m, probes_settings s, perm p WHERE s.id = $2 AND m.id = s.probes_id AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.PROBE_EDIT.rawValue)) != 0)
)
DELETE FROM probes_settings s USING sel WHERE s.id = $2 AND probes_id = sel.id RETURNING s.id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
/* ----------------------------------------------- */
/* module handling */
/* ----------------------------------------------- */
struct ModuleParam : FastCodable {
let id : Int?
let i : Int?
let p : Int?
let o : Int?
let f1 : String?
let f2 : String?
let f3 : Bool?
}
func printModule(_ id : Int32, _ name : String) {
print(#"{"id":\#(id),"n":"\#(name)"},"#)
}
func module_list() -> ErrorResult {
if let user = user_getInfo(),
let info = ModuleParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let admin = user.perm.has(.ADMIN_ALL)
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 2:
orderQry += "m.description::bytea "
case 1:
fallthrough
default:
orderQry += "m.name::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page]
var filterQry = "TRUE "
var optArg = 3
if let f1 = info.f1 {
filterQry += "AND m.name LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if let f2 = info.f2 {
filterQry += "AND m.description LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f2)
}
if(!admin) {
filterQry += "AND (groups_id IN(SELECT groups_id FROM users_groups WHERE users_id = $\(optArg)) OR users_id = $\(optArg))"
qryArgs.append(user.id)
}
let qryStr = """
SELECT m.id, m.name,
row_number() OVER (\(orderQry)) AS nr FROM modules m
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0),
let name = qry.getAsText(i, 1) {
printModule(id, name)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
struct ModuleAddParam : FastCodable {
let n : String
let d : String
let i : String
let l : Int
let g : Int?
}
func module_add() -> ErrorResult {
if let uinfo = user_getInfo(),
uinfo.perm.has(.MODULE_ADD) != false,
let data = ModuleAddParam.from(json:Post.ext_data.value) {
_ = <!SQLQry.begin()
let qry = SQLQry("""
WITH ins_modules AS (
INSERT INTO modules(name, description, groups_id, users_id, locked) VALUES ($1, $2, $3, $4, $5) RETURNING id
)
INSERT INTO module_instances (modules_id, name) SELECT ins_modules.id, $6 RETURNING modules_id;
""")
qry.values = [data.n, data.d, data.g ?? Optional<Int>.none as Any, uinfo.id, data.l, data.i]
var err = AsyncError()
if (err <! qry.exec()) != false {
let id = qry.getAsInt32(0, 0) ?? -1
if let _ = err <! Dir.module_gen_source.mkpath("\(id)", [.U0700, .G0050, .O0001]),
let d = err <! Dir.module_source.mkpath("\(id)", [.U0700, .G0050, .O0001]),
let _ = err <! d.open("config.html", [.O_CREAT,.O_RDONLY]),
let _ = err <! d.open("run.html", [.O_CREAT,.O_RDONLY]),
let _ = err <! d.open("setup.html", [.O_CREAT,.O_RDONLY]) {
_ = <!SQLQry.end()
print(#"{"r":0, "d": \#(id)}"#)
return ErrorNone
} else {
_ = Dir.module_source.remove("\(id)")
_ = Dir.module_gen_source.remove("\(id)")
_ = <!SQLQry.rollback()
if(err.hasError) {
return ErrorResult(err.errValue)
}
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
return ErrorDefault
}
func module_remove() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m
WHERE g.users_id = $1
AND m.id = $2
AND m.groups_id = g.groups_id
)
DELETE FROM modules m USING perm p WHERE id = $2 AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.MODULE_EDIT.rawValue)) != 0) RETURNING m.id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
_ = Dir.module_source.remove("\(data.id)")
_ = Dir.module_gen_source.remove("\(data.id)")
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func module_update() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let user_edit = uinfo.perm.has(.USER_EDIT)
let empty = "SELECT"
var update_module = empty
var update_instance = empty
var args = ""
var qryArgs : [Any] = [uinfo.id, data.m ?? Optional<Int32>.none as Any, data.n ?? Optional<Int32>.none as Any, admin]
var optArg = 5
if let description = data.a {
args += "description = $\(optArg),"
qryArgs.append(description)
optArg += 1
}
if let options = data.b {
args += "options = $\(optArg),"
qryArgs.append(options)
optArg += 1
}
if let name = data.c {
args += "name = $\(optArg),"
qryArgs.append(name)
optArg += 1
}
if let users_id = data.o {
if user_edit == false {
return ErrorDefault
}
args += "users_id = $\(optArg),"
qryArgs.append(users_id)
optArg += 1
}
if let groups_id = data.p {
if user_edit == false {
return ErrorDefault
}
args += "groups_id = $\(optArg),"
qryArgs.append(groups_id)
optArg += 1
}
if let locked = data.q {
args += "locked = $\(optArg),"
qryArgs.append(locked)
optArg += 1
}
if(args != "") {
update_module = "UPDATE modules m SET \(args.dropLast()) FROM has, module WHERE m.id = module.id AND has.perm RETURNING m.id"
}
args = ""
if let name = data.d {
args += "name = $\(optArg),"
qryArgs.append(name)
optArg += 1
}
if let options = data.e {
args += "options = $\(optArg),"
qryArgs.append(options)
optArg += 1
}
if(args != "") {
update_instance = "UPDATE module_instances i SET \(args.dropLast()) FROM has WHERE i.id = $3 AND has.perm RETURNING i.id"
}
let qryStr = """
WITH module AS (
SELECT CASE WHEN $2::bigint IS NULL THEN (SELECT modules_id FROM module_instances WHERE id = $3::bigint) ELSE $2::bigint END AS id
),
perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m, module
WHERE g.users_id = $1
AND m.id = module.id
AND m.groups_id = g.groups_id
),
has AS (
SELECT ($4::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.MODULE_EDIT.rawValue)) != 0) AS perm
FROM modules m, perm p, module WHERE m.id = module.id
),
upd1 AS (
\(update_module)
),
upd2 AS (
\(update_instance)
)
SELECT * FROM upd1, upd2;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
struct ModuleGetParam : FastCodable {
let mid : Int?
let iid : Int?
}
func module_get() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = ModuleGetParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH module AS (
SELECT id, name, users_id, groups_id, description, locked FROM modules WHERE id = $2
),
instance AS (
SELECT modules_id, name, options FROM module_instances WHERE id = $3
),
res AS(
SELECT CASE WHEN id IS NULL THEN modules_id ELSE id END, m.name, users_id, groups_id, description, locked, i.name AS iname, options
FROM module m FULL JOIN instance i ON(m.id = i.modules_id)
),
perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m, res
WHERE g.users_id = $1
AND m.id = res.id
AND m.groups_id = g.groups_id
)
SELECT name, users_id, groups_id, description, locked,
CASE WHEN p.perm IS NULL THEN -1 ELSE p.perm END
,iname, options #>> '{}' FROM res m, perm p WHERE
($4::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.MODULE_EDIT.rawValue)) != 0)
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.mid ?? Optional<Int32>.none as Any, data.iid ?? Optional<Int32>.none as Any, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
let name = qry.getAsText(0, 0) ?? "";
let users_id = qry.getAsInt32(0, 1) ?? -1;
let groups_id = qry.getAsInt32(0, 2) ?? -1;
let desc = qry.getAsText(0, 3) ?? "";
let locked = qry.getAsBool(0, 4) ?? true;
let perm = qry.getAsInt32(0, 5) ?? -1;
let iname = qry.getAsText(0, 6) ?? "";
let options = qry.getAsText(0, 7) ?? "{}";
let iid = data.iid == nil ? "" : #""o":\#(options),"i":"\#(iname)","#
let mid = data.mid == nil ? "" : #""n":"\#(name)","d":"\#(desc)","p":\#(perm),"u":\#(users_id),"g":\#(groups_id),"l":\#(locked ? 1 : 0),"#
print(#"{\#(mid)\#(iid)"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func module_download() -> ErrorResult {
// TODO gen package from module
return ErrorDefault
}
func module_install() -> ErrorResult {
// TODO
return ErrorDefault
}
func module_share() -> ErrorResult {
// TODO
return ErrorDefault
}
func package_compress(dir : FileItem) -> Bool {
var err = AsyncError()
if let bin = err <! Dir.bin.open("appudo_archiver", .O_RDONLY) {
if let _ = err <! Process.exec(bin, args:["appudo_archiver", "-c", "-o", "result.tar.gz", "out"], env:["PATH=/usr/lib"],
cwd:dir, flags:.SUID) {
return true
}
}
return false
}
func module_pack() -> ErrorResult {
var err = AsyncError()
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value),
uinfo.perm.has(.MODULE_SHARE),
let name = data.a,
let moduleId = data.m {
let admin = uinfo.perm.has(.ADMIN_ALL)
if var tmp = <!FileItem.create_tmp(Dir.tmp, "pkgXXXXXX", flags:[.O_DIRECTORY, .O_RDONLY], mode:[.S_IRWXU, .S_IRWXG]) {
_ = <!tmp.mkpath("out", [.U0700, .G0050, .O0001])
defer {
_ = <!tmp.remove(outer:true)
}
if var minfo = <!tmp.open("out/minfo", [.O_CREAT, .O_RDWR]) {
var qry = SQLQry("""
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m
WHERE g.users_id = $1
AND m.id = $2
AND m.groups_id = g.groups_id
)
SELECT name, description, options #>> '{}', locked FROM modules m, perm p WHERE m.id = $2 AND
($3::Boolean IS TRUE OR m.users_id = $1);
""")
qry.values = [uinfo.id, moduleId , admin]
if <!qry.exec() == false || qry.numRows != 1 {
Page.resultStatus = .S_404
return ErrorNone
}
let buffer = ManagedCharBuffer.create(64)
var cbor = CBOR(buffer:buffer)
var nm = qry.getAsUnsafeData(0, 0)
var desc = qry.getAsUnsafeData(0, 1)
var opt = qry.getAsUnsafeData(0, 2)
let locked = qry.getAsBool(0, 3) ?? true
var num : Int32 = 1
num += nm.is_nil ? 0 : 1
num += desc.is_nil ? 0 : 1
num += opt.is_nil ? 0 : 1
_ = cbor.put(mapSize:2)
_ = cbor.put(sstring:"m")
_ = cbor.put(mapSize:num)
if !nm.is_nil {
_ = cbor.put(sstring:"n")
_ = cbor.put(stringSize:nm.size)
_ = <!minfo.write(cbor, nm)
cbor.reset()
}
if !desc.is_nil {
_ = cbor.put(sstring:"d")
_ = cbor.put(stringSize:desc.size)
_ = <!minfo.write(cbor, desc)
cbor.reset()
}
if !opt.is_nil {
_ = cbor.put(sstring:"o")
_ = cbor.put(stringSize:opt.size)
_ = <!minfo.write(cbor, opt)
cbor.reset()
}
nm.clear()
desc.clear()
opt.clear()
withExtendedLifetime(qry) {
}
_ = cbor.put(sstring:"l")
_ = cbor.put(bool:locked)
_ = cbor.put(sstring:"i")
qry = SQLQry("""
SELECT id, name, options #>> '{}' FROM module_instances WHERE modules_id = $1;
""")
qry.values = [moduleId]
qry.singleRowMode = true
_ = cbor.put_array()
if(err <! qry.exec()) != false {
repeat {
if qry.numRows != 0 {
let iid = qry.getAsInt32(0, 0) ?? -1
let name = qry.getAsUnsafeData(0, 1)
let v = qry.getAsUnsafeData(0, 2)
_ = cbor.put(mapSize:3)
_ = cbor.put(sstring:"r")
_ = cbor.put(int:iid)
_ = cbor.put(sstring:"n")
_ = cbor.put(stringSize:name.size)
_ = <!minfo.write(cbor, name)
cbor.reset()
_ = cbor.put(sstring:"o")
if !v.is_nil {
_ = cbor.put(stringSize:v.size)
_ = <!minfo.write(cbor, v)
} else {
_ = cbor.put(sstring:"{}")
_ = <!minfo.write(cbor)
}
cbor.reset()
}
} while(<!qry.cont() != false)
} else {
Page.resultStatus = .S_404
return ErrorNone
}
_ = cbor.put_end()
_ = <!minfo.write(cbor)
if let d = <!Dir.module_source.open("\(moduleId)", .O_PATH) {
_ = <!d.copy("out/source", tmp)
}
if let d = <!Dir.module_gen_source.open("\(moduleId)", .O_PATH) {
_ = <!d.copy("out/gen", tmp)
}
if package_compress(dir:tmp),
let out = <!tmp.open("result.tar.gz", .O_RDONLY) {
_ = Page.addResultHeader("Content-Disposition: attachment; filename=\(name)\r\n")
_ = Page.addResultHeader("Content-Transfer-Encoding: binary\r\n");
if send(exclusive:out) {
return ErrorNone
}
}
}
}
}
Page.resultStatus = .S_404
return ErrorNone
}
func module_load_code() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = TwoInt32Param.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let type = data.b
var f = ""
if(type < 64) {
let moduleId = data.a
if(type == 0 || type == 3) {
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m
WHERE g.users_id = $1
AND m.id = $2
AND m.groups_id = g.groups_id
)
SELECT m.users_id FROM modules m
LEFT OUTER JOIN perm p ON((p.perm & \(GroupPermissions.MODULE_SETUP.rawValue)) != 0)
WHERE (m.users_id = $1 OR $3::Boolean IS TRUE OR perm IS NOT NULL) AND m.id = $2;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, moduleId, admin]
var err = AsyncError()
if(err <! qry.exec()) == false || qry.numRows == 0 {
Page.resultStatus = .S_401
return ErrorNone
}
}
}
switch(type) {
case 0:
f = "\(moduleId)/setup.html"
case 1:
f = "\(moduleId)/config.html"
case 3:
f = "\(moduleId)/setup.tmpl"
case 4:
f = "\(moduleId)/config.tmpl"
case 5:
f = "\(moduleId)/run.tmpl"
default: // 2
f = "\(moduleId)/run.html"
}
if let o = <!Dir.module_source.open(f, .O_RDONLY) {
if(<!Page.setMime("html") != false && send(exclusive:o)) {
return ErrorNone
}
}
} else {
let miid = data.a
var moduleId = -1
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm, min(i.modules_id) AS modules_id, min(m.users_id) AS users_id
FROM module_instances i, modules m
LEFT OUTER JOIN users_groups g ON(g.users_id = $1 AND m.groups_id = g.groups_id)
WHERE i.id = $2
AND i.modules_id = m.id
)
SELECT p.modules_id FROM module_instances i, perm p
WHERE (p.users_id = $1 OR $3::Boolean IS TRUE OR (p.perm & \(GroupPermissions.MODULE_SETUP.rawValue)) != 0) AND i.id = $2 AND i.modules_id = p.modules_id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, miid, admin]
var err = AsyncError()
if(err <! qry.exec()) == false || qry.numRows == 0 {
Page.resultStatus = .S_401
return ErrorNone
}
moduleId = Int(qry.getAsInt32(0, 0) ?? -1)
}
switch(type) {
case 64:
f = "\(moduleId)/\(miid)/ebpf.h"
case 65:
f = "\(moduleId)/\(miid)/ebpf.c"
case 66:
f = "\(moduleId)/\(miid)/user.h"
default:
f = "\(moduleId)/\(miid)/user.cpp"
}
if let o = <!Dir.module_gen_source.open(f, .O_RDONLY) {
if(<!Page.setMime("txt") != false && send(exclusive:o)) {
return ErrorNone
}
}
}
}
Page.resultStatus = .S_404
return ErrorNone
}
func printModuleInstance(_ id : Int32, _ name : String) {
print(#"{"id":\#(id),"n":"\#(name)"},"#)
}
func module_list_instances() -> ErrorResult {
if let user = user_getInfo(),
let info = ModuleParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let admin = user.perm.has(.ADMIN_ALL)
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 1:
fallthrough
default:
orderQry += "i.name::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page, info.id ?? Optional<Int>.none as Any]
var filterQry = "($3::integer IS NULL OR i.modules_id = $3) "
var optArg = 4
if let f1 = info.f1 {
filterQry += "AND i.name LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if(!admin) {
filterQry += "AND modules_id IN(SELECT p.id FROM modules p, users_groups g WHERE (g.users_id = $\(optArg) AND g.groups_id = p.groups_id) OR p.users_id = $\(optArg))"
qryArgs.append(user.id)
}
let qryStr = """
SELECT i.id, i.name,
row_number() OVER (\(orderQry)) AS nr FROM module_instances i
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0) {
let name = qry.getAsText(i, 1) ?? ""
printModuleInstance(id, name)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
func module_add_instance() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value),
let name = data.a {
let admin = uinfo.perm.has(.ADMIN_ALL)
if let instance_id = data.m {
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m, module_instances i
WHERE g.users_id = $1
AND i.id = $2
AND i.modules_id = m.id
AND m.groups_id = g.groups_id
),
sel AS (
SELECT m.id FROM modules m, module_instances i, perm p WHERE i.id = $2 AND m.id = i.modules_id AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.MODULE_EDIT.rawValue)) != 0)
)
INSERT INTO module_instances(modules_id, name, options) SELECT modules_id, $4, options
FROM module_instances i, sel
WHERE i.id = $2 AND modules_id = sel.id RETURNING id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, instance_id, admin, name]
var err = AsyncError()
if (err <! qry.exec()) != false {
if let id = qry.getAsInt32(0, 0) {
print(#"{"r":0, "d": \#(id)}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
} else
if let module_id = data.n {
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m
WHERE g.users_id = $1
AND m.id = $2
AND m.groups_id = g.groups_id
),
sel AS (
SELECT m.id FROM modules m, perm p WHERE m.id = $2 AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.MODULE_EDIT.rawValue)) != 0)
)
INSERT INTO module_instances(modules_id, name) SELECT id, $4
FROM sel
WHERE sel.id IS NOT NULL RETURNING id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, module_id, admin, name]
var err = AsyncError()
if (err <! qry.exec()) != false {
if let id = qry.getAsInt32(0, 0) {
print(#"{"r":0, "d": \#(id)}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
}
return ErrorDefault
}
func module_remove_instance() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules p, module_instances i
WHERE g.users_id = $1
AND i.id = $2
AND i.modules_id = p.id
AND p.groups_id = g.groups_id
),
sel AS (
SELECT m.id FROM modules m, module_instances i, perm p WHERE i.id = $2 AND m.id = i.modules_id AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.MODULE_EDIT.rawValue)) != 0)
)
DELETE FROM module_instances i USING sel WHERE i.id = $2 AND modules_id = sel.id RETURNING i.modules_id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
let moduleId = qry.getAsInt(0, 0) ?? -1
_ = <!Dir.module_gen_source.remove("\(moduleId)/\(data.id)")
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func module_instance_get_settings() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = TwoInt32Param.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
var qryStr = ""
if(data.b == 0) {
qryStr = """
WITH instance AS (
SELECT i.options, users_id, groups_id FROM modules m, module_instances i WHERE i.id = $2 AND m.id = i.modules_id
),
perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, instance i
WHERE g.users_id = $1
AND i.groups_id = g.groups_id
)
SELECT options #>> '{}' FROM instance i, perm p WHERE
($3::Boolean IS TRUE OR i.users_id = $1 OR p.perm IS NOT NULL)
"""
} else {
qryStr = """
WITH instance AS (
SELECT i.options, users_id, groups_id FROM modules m, module_instances i, run_instances r
WHERE r.id = $2
AND m.id = i.modules_id
AND i.id = r.module_instances_id
),
perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, instance i
WHERE g.users_id = $1
AND i.groups_id = g.groups_id
)
SELECT options #>> '{}' FROM instance i, perm p WHERE
($3::Boolean IS TRUE OR i.users_id = $1 OR p.perm IS NOT NULL)
"""
}
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.a, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
let options = qry.getAsText(0, 0) ?? "{}";
print(#"{"d":\#(options),"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func module_get_uses() -> ErrorResult {
let perm = user_getPerm()
if perm.has(.USER_EDIT) != false,
let info = UsesParam.from(json:Post.ext_data.value) {
return uses_get(info, "modules")
}
return ErrorDefault
}
/* ----------------------------------------------- */
/* run handling */
/* ----------------------------------------------- */
struct RunParam : FastCodable {
let i : Int?
let p : Int?
let o : Int?
let f1 : String?
let f2 : String?
let f3 : Bool?
}
func printRun(_ id : Int32, _ name : String) {
print(#"{"id":\#(id),"n":"\#(name)"},"#)
}
func run_list() -> ErrorResult {
if let user = user_getInfo(),
let info = RunParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let admin = user.perm.has(.ADMIN_ALL)
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 2:
orderQry += "r.description::bytea "
case 1:
fallthrough
default:
orderQry += "r.name::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page]
var filterQry = "TRUE "
var optArg = 3
if let f1 = info.f1 {
filterQry += "AND r.name LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if let f2 = info.f2 {
filterQry += "AND r.description LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f2)
}
if(!admin) {
filterQry += "AND (groups_id IN(SELECT groups_id FROM users_groups WHERE users_id = $\(optArg)) OR users_id = $\(optArg))"
qryArgs.append(user.id)
}
let qryStr = """
SELECT r.id, r.name,
row_number() OVER (\(orderQry)) AS nr FROM runs r
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0),
let name = qry.getAsText(i, 1) {
printRun(id, name)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
func run_get() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, runs r
WHERE g.users_id = $1
AND r.id = $2
AND r.groups_id = g.groups_id
)
SELECT name, description, options #>> '{}', users_id, groups_id FROM runs r, perm p WHERE id = $2 AND
($3::Boolean IS TRUE OR r.users_id = $1 OR (p.perm & \(GroupPermissions.RUN_EDIT.rawValue)) != 0);
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
let name = qry.getAsText(0, 0) ?? ""
let desc = qry.getAsText(0, 1) ?? ""
let options = qry.getAsText(0, 2) ?? "{}"
let user_id = qry.getAsInt32(0, 3) ?? -1
let group_id = qry.getAsInt32(0, 4) ?? -1
print(#"{"r":0,"n":"\#(name)","d":"\#(desc)","o":\#(options),"u":\#(user_id),"g":\#(group_id)}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func _run_update_options(uid : Int32, perm : UserPermissions, data : IdParam) -> ErrorResult {
let admin = perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, runs r
WHERE g.users_id = $1
AND r.id = $2
AND r.groups_id = g.groups_id
)
SELECT i.id, i.module_instances_id, i.options #>> '{}' FROM run_instances i, runs r, perm p WHERE runs_id = $2 AND r.id = runs_id AND
($3::Boolean IS TRUE OR r.users_id = $1 OR (p.perm & \(GroupPermissions.RUN_EDIT.rawValue)) != 0);
"""
if var out = <!FileItem.create_tmp(),
let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uid, data.id, admin]
qry.singleRowMode = true
let buffer = ManagedCharBuffer.create(64)
var cbor = CBOR(buffer:buffer)
var err = AsyncError()
_ = cbor.put_array()
_ = <!out.write(cbor)
cbor.reset()
if(err <! qry.exec()) != false {
repeat {
if qry.numRows != 0 {
let riid = qry.getAsInt32(0, 0) ?? -1
let miid = qry.getAsInt32(0, 1) ?? -1
let v = qry.getAsUnsafeData(0, 2)
_ = cbor.put(mapSize:3)
_ = cbor.put(sstring:"r")
_ = cbor.put(int:riid)
_ = cbor.put(sstring:"m")
_ = cbor.put(int:miid)
_ = cbor.put(sstring:"o")
if !v.is_nil {
_ = cbor.put(stringSize:v.size)
_ = <!out.write(cbor)
_ = <!out.write(v)
} else {
_ = cbor.put(sstring:"{}")
_ = <!out.write(cbor)
}
cbor.reset()
}
} while(<!qry.cont() != false)
}
_ = cbor.put_end()
_ = <!out.write(cbor)
let file = "settings.json"
if qry.hasError == false,
let target = <!Dir.run_binary.open("\(data.id)", .O_PATH) {
_ = <!target.remove(file)
if <!out.link_open(file, target, hard:true) != false {
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
return ErrorDefault
}
func run_update_options() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let res = _run_update_options(uid:uinfo.id, perm:uinfo.perm, data:data)
if(res == ErrorNone) {
print(#"{"r":0}"#)
return ErrorNone
} else {
return res
}
}
return ErrorDefault
}
func run_update() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value),
let run_id = data.m {
let admin = uinfo.perm.has(.ADMIN_ALL)
let user_edit = uinfo.perm.has(.USER_EDIT)
let empty = "SELECT"
var update = empty
var args = ""
var qryArgs : [Any] = [uinfo.id, run_id, admin]
var optArg = 4
if let description = data.a {
args += "description = $\(optArg),"
qryArgs.append(description)
optArg += 1
}
if let options = data.b {
args += "options = $\(optArg),"
qryArgs.append(options)
optArg += 1
}
if let name = data.c {
args += "name = $\(optArg),"
qryArgs.append(name)
optArg += 1
}
if let users_id = data.n {
if user_edit == false {
return ErrorDefault
}
args += "users_id = $\(optArg),"
qryArgs.append(users_id)
optArg += 1
}
if let groups_id = data.o {
if user_edit == false {
return ErrorDefault
}
args += "groups_id = $\(optArg),"
qryArgs.append(groups_id)
optArg += 1
}
if(args != "") {
update = "UPDATE runs r SET \(args.dropLast()) FROM has WHERE r.id = $2 AND has.perm RETURNING r.id"
}
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, runs r
WHERE g.users_id = $1
AND r.id = $2
AND r.groups_id = g.groups_id
),
has AS (
SELECT ($3::Boolean IS TRUE OR r.users_id = $1 OR (p.perm & \(GroupPermissions.RUN_EDIT.rawValue)) != 0) AS perm
FROM runs r, perm p WHERE r.id = $2
),
upd AS (
\(update)
)
SELECT * FROM upd;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
struct RunAddParam : FastCodable {
let n : String
let d : String
let g : Int?
}
func run_add() -> ErrorResult {
if let uinfo = user_getInfo(),
uinfo.perm.has(.RUN_ADD) != false,
let data = RunAddParam.from(json:Post.ext_data.value) {
_ = <!SQLQry.begin()
let qry = SQLQry("INSERT INTO runs(name, description, groups_id, users_id) VALUES ($1, $2, $3, $4) RETURNING id;")
qry.values = [data.n, data.d, data.g ?? Optional<Int>.none as Any, uinfo.id]
var err = AsyncError()
if (err <! qry.exec()) != false {
let id = qry.getAsInt32(0, 0) ?? -1
if let _ = err <! Dir.run_binary.mkpath("\(id)", [.U0700, .G0050, .O0001]) {
_ = <!SQLQry.end()
print(#"{"r":0, "d": \#(id)}"#)
return ErrorNone
} else {
_ = <!SQLQry.rollback()
if(err.hasError) {
return ErrorResult(err.errValue)
}
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
return ErrorDefault
}
func run_remove() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m
WHERE g.users_id = $1
AND m.id = $2
AND m.groups_id = g.groups_id
)
DELETE FROM runs m USING perm p WHERE id = $2 AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.RUN_EDIT.rawValue)) != 0) RETURNING m.id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
_ = Dir.run_binary.remove("\(data.id)")
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func run_get_uses() -> ErrorResult {
let perm = user_getPerm()
if perm.has(.USER_EDIT) != false,
let info = UsesParam.from(json:Post.ext_data.value) {
return uses_get(info, "runs")
}
return ErrorDefault
}
func printRunInstance(_ id : Int32, _ mid : Int32, _ name : String) {
print(#"{"id":\#(id),"mid":\#(mid),"n":"\#(name)"},"#)
}
func run_list_instances() -> ErrorResult {
if let user = user_getInfo(),
let info = ModuleParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let admin = user.perm.has(.ADMIN_ALL)
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 1:
fallthrough
default:
orderQry += "i.name::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page, info.id ?? Optional<Int>.none as Any]
var filterQry = "($3::integer IS NULL OR i.runs_id = $3) "
var optArg = 4
if let f1 = info.f1 {
filterQry += "AND i.name LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if(!admin) {
filterQry += "AND runs_id IN(SELECT r.id FROM runs r, users_groups g WHERE (g.users_id = $\(optArg) AND g.groups_id = r.groups_id) OR r.users_id = $\(optArg))"
qryArgs.append(user.id)
}
let qryStr = """
SELECT i.id, m.modules_id, i.name,
row_number() OVER (\(orderQry)) AS nr FROM run_instances i, module_instances m
WHERE \(filterQry) AND i.module_instances_id = m.id
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0) {
let mid = qry.getAsInt32(i, 1) ?? -1
let name = qry.getAsText(i, 2) ?? ""
printRunInstance(id, mid, name)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
func run_add_instance() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value),
let run_id = data.n,
let module_inst_id = data.m,
let name = data.a {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, runs r
WHERE g.users_id = $1
AND r.id = $2
AND r.groups_id = g.groups_id
),
sel AS (
SELECT r.id FROM runs r, perm p WHERE r.id = $2 AND
($4::Boolean IS TRUE OR r.users_id = $1 OR (p.perm & \(GroupPermissions.RUN_EDIT.rawValue)) != 0)
),
ins AS (
INSERT INTO run_instances(runs_id, module_instances_id, name, visible) SELECT id, $3, $5, $6
FROM sel
WHERE sel.id IS NOT NULL RETURNING run_instances.id, run_instances.module_instances_id)
SELECT ins.id, modules_id FROM module_instances, ins WHERE ins.module_instances_id = module_instances.id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, run_id, module_inst_id, admin, name, (data.o ?? 0) == 1]
var err = AsyncError()
if (err <! qry.exec()) != false {
if let id = qry.getAsInt32(0, 0),
let mid = qry.getAsInt32(0, 1){
print(#"{"r":0,"d": \#(id),"m": \#(mid)}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func run_update_instance() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = UpdateParam.from(json:Post.ext_data.value),
let run_instance_id = data.m {
let admin = uinfo.perm.has(.ADMIN_ALL)
let empty = "SELECT"
var update = empty
var args = ""
var qryArgs : [Any] = [uinfo.id, run_instance_id, admin]
var optArg = 4
if let options = data.b {
args += "options = $\(optArg),"
qryArgs.append(options)
optArg += 1
}
if let name = data.a {
args += "name = $\(optArg),"
qryArgs.append(name)
optArg += 1
}
if let visible = data.n {
args += "visible = $\(optArg),"
qryArgs.append(visible)
optArg += 1
}
if(args != "") {
update = "UPDATE run_instances r SET \(args.dropLast()) FROM has WHERE r.id = $2 AND has.perm RETURNING r.runs_id"
}
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, runs r, run_instances i
WHERE g.users_id = $1
AND i.id = $2
AND r.id = i.runs_id
AND r.groups_id = g.groups_id
),
has AS (
SELECT ($3::Boolean IS TRUE OR r.users_id = $1 OR (p.perm & \(GroupPermissions.RUN_EDIT.rawValue)) != 0) AS perm
FROM runs r, perm p, run_instances i WHERE i.id = $2 AND r.id = i.runs_id
),
upd AS (
\(update)
)
SELECT * FROM upd;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
if data.b != nil {
let run_id = qry.getAsInt32(0, 0) ?? -1;
_ = _run_update_options(uid:uinfo.id, perm:uinfo.perm, data:IdParam(id:Int(run_id)))
}
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func run_instance_get_settings() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH instance AS (
SELECT i.options, users_id, groups_id FROM runs r, run_instances i WHERE i.id = $2 AND r.id = i.runs_id
),
perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, instance i
WHERE g.users_id = $1
AND i.groups_id = g.groups_id
)
SELECT options #>> '{}' FROM instance i, perm p WHERE
($3::Boolean IS TRUE OR i.users_id = $1 OR p.perm IS NOT NULL);
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
let options = qry.getAsText(0, 0) ?? "{}"
print(#"{"r":0,"d":\#(options)}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
func run_remove_instance() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, runs r, run_instances i
WHERE g.users_id = $1
AND i.id = $2
AND i.runs_id = r.id
AND r.groups_id = g.groups_id
),
sel AS (
SELECT r.id FROM runs r, run_instances i, perm p WHERE i.id = $2 AND r.id = i.runs_id AND
($3::Boolean IS TRUE OR r.users_id = $1 OR (p.perm & \(GroupPermissions.RUN_EDIT.rawValue)) != 0)
)
DELETE FROM run_instances i USING sel WHERE i.id = $2 AND runs_id = sel.id RETURNING i.runs_id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
let run_id = qry.getAsInt32(0, 0) ?? -1;
_ = _run_update_options(uid:uinfo.id, perm:uinfo.perm, data:IdParam(id:Int(run_id)))
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
/* ----------------------------------------------- */
/* settings handling */
/* ----------------------------------------------- */
func setting_get() -> ErrorResult {
let qry = SQLQry("SELECT data #>> '{}' FROM global_settings;")
if <!qry.exec() != false,
let data = qry.getAsText(0, 0) {
print(#"{"r":0,"d":\#(data)}"#)
return ErrorNone
}
return ErrorDefault
}
func setting_update() -> ErrorResult {
let qry = SQLQry("UPDATE global_settings SET data = $1;")
qry.values = [Post.ext_data.value];
if let user = user_getInfo(),
user.perm.has(.SETTING_EDIT),
<!qry.exec() != false,
let data = qry.getAsText(0, 0) {
print(#"{"r":0,"d":\#(data)}"#)
return ErrorNone
}
return ErrorDefault
}
/* ----------------------------------------------- */
/* repo handling */
/* ----------------------------------------------- */
struct RepoParam : FastCodable {
let i : Int?
let p : Int?
let o : Int?
let f1 : String?
let f2 : String?
let f3 : Bool?
}
func printRepo(_ id : Int32, _ name : String) {
print(#"{"id":\#(id),"n":"\#(name)"},"#)
}
func repo_list() -> ErrorResult {
if let user = user_getInfo(),
let info = RepoParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let admin = user.perm.has(.ADMIN_ALL)
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 2:
orderQry += "r.description::bytea "
case 1:
fallthrough
default:
orderQry += "r.url::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page]
var filterQry = "TRUE "
var optArg = 3
if let f1 = info.f1 {
filterQry += "AND r.url LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if let f2 = info.f2 {
filterQry += "AND r.description LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f2)
}
if(!admin) {
filterQry += "AND (groups_id IN(SELECT groups_id FROM users_groups WHERE users_id = $\(optArg)) OR users_id = $\(optArg))"
qryArgs.append(user.id)
}
let qryStr = """
SELECT r.id, r.url,
row_number() OVER (\(orderQry)) AS nr FROM repositories r
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let id = qry.getAsInt32(i, 0),
let name = qry.getAsText(i, 1) {
printRepo(id, name)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
return ErrorDefault
}
struct RepoAddParam : FastCodable {
let u : String
let d : String
let g : Int?
}
func repo_add(_ password : UnsafeTmpString) -> ErrorResult {
if let uinfo = user_getInfo(),
uinfo.perm.has(.REPO_ADD) != false,
let data = RepoAddParam.from(json:Post.ext_data.value) {
let qry = SQLQry("INSERT INTO repositories(url, key, description, groups_id, users_id) VALUES ($1, $2, $3, $4, $5) RETURNING id;")
qry.values = [data.u, password.is_nil ? Optional<UnsafeTmpString>.none as Any : password, data.d, data.g ?? Optional<Int>.none as Any, uinfo.id]
var err = AsyncError()
if (err <! qry.exec()) != false {
let id = qry.getAsInt32(0, 0) ?? -1
print(#"{"r":0,"d": \#(id)}"#)
return ErrorNone
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
return ErrorDefault
}
func repo_update() -> ErrorResult {
// TODO
return ErrorDefault
}
func repo_remove() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
let qryStr = """
WITH perm AS (
SELECT bit_or(perm) AS perm FROM users_groups g, modules m
WHERE g.users_id = $1
AND m.id = $2
AND m.groups_id = g.groups_id
)
DELETE FROM repositories m USING perm p WHERE id = $2 AND
($3::Boolean IS TRUE OR m.users_id = $1 OR (p.perm & \(GroupPermissions.REPO_EDIT.rawValue)) != 0) RETURNING m.id;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = [uinfo.id, data.id, admin]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
/* ----------------------------------------------- */
/* cross compiler handling */
/* ----------------------------------------------- */
struct CrossParam : FastCodable {
let i : Int?
let p : Int?
let o : Int?
let f1 : String?
let f2 : String?
let f3 : Bool?
}
func printCross(_ prefix : String, _ triple : String) {
print(#"{"p":"\#(prefix)","n":"\#(triple)"},"#)
}
func cross_list() -> ErrorResult {
if let user = user_getInfo(),
let info = CrossParam.from(json:Post.ext_data.value) {
let items_per_page = info.i ?? 10
let page_offset = info.p ?? 0
let admin = user.perm.has(.ADMIN_ALL)
if admin {
var orderQry = ""
if let order = info.o {
orderQry = "ORDER BY "
switch(order >> 1) {
case 2:
orderQry += "c.description::bytea "
case 1:
fallthrough
default:
orderQry += "c.triple::bytea "
}
orderQry += (order & 1) == 1 ? "DESC " : "ASC "
}
var qryArgs : [Any] = [page_offset, items_per_page]
var filterQry = "TRUE "
var optArg = 3
if let f1 = info.f1 {
filterQry += "AND c.triple LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f1)
}
if let f2 = info.f2 {
filterQry += "AND c.description LIKE '%' || $\(optArg) || '%' "
optArg += 1
qryArgs.append(f2)
}
let qryStr = """
SELECT c.compiler_prefix, c.triple,
row_number() OVER (\(orderQry)) AS nr FROM cross_compilers c
WHERE \(filterQry)
ORDER BY nr DESC
LIMIT $2::bigint OFFSET $1::bigint;
"""
if let qry = try? SQLQry(dirty_and_dangerous:qryStr) {
qry.values = qryArgs
if <!qry.exec() == false {
return ErrorDefault
}
var max = 0
print(#"{"r":0,"d":["#)
if(qry.numRows != 0) {
max = qry.getAsInt(0, 2) ?? 0
for i in 0..<qry.numRows {
if let prefix = qry.getAsText(i, 0),
let name = qry.getAsText(i, 1) {
printCross(prefix, name)
}
}
_ = revert_print(1)
}
print(#"],"m":\#(max)}"#)
return ErrorNone
}
}
}
return ErrorDefault
}
struct CrossAddParam : FastCodable {
let p : String
let t : String
let d : String
}
func cross_add(_ password : UnsafeTmpString) -> ErrorResult {
if let uinfo = user_getInfo(),
uinfo.perm.has(.ADMIN_ALL) != false,
let data = CrossAddParam.from(json:Post.ext_data.value) {
let qry = SQLQry("INSERT INTO cross_compilers(compiler_prefix, triple, description) VALUES ($1, $2, $3) RETURNING id;")
qry.values = [data.p, data.t, data.d]
var err = AsyncError()
if (err <! qry.exec()) != false {
print(#"{"r":0}"#)
return ErrorNone
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
return ErrorDefault
}
func cross_update() -> ErrorResult {
// TODO
return ErrorDefault
}
func cross_remove() -> ErrorResult {
if let uinfo = user_getInfo(),
let data = IdParam.from(json:Post.ext_data.value) {
let admin = uinfo.perm.has(.ADMIN_ALL)
if admin {
let qry = SQLQry("DELETE FROM cross_compilers WHERE id = $2")
qry.values = [data.id]
var err = AsyncError()
if(err <! qry.exec()) != false {
if qry.numRows != 0 {
print(#"{"r":0}"#)
return ErrorNone
}
} else {
return ErrorResult(err.asSQL.rawValue)
}
}
}
return ErrorDefault
}
/* ----------------------------------------------- */
/* disassembly handling */
/* ----------------------------------------------- */
/* ----------------------------------------------- */
/* main */
/* ----------------------------------------------- */
func main() {
var res = ErrorDefault
if(Page.schema == .HTTPS && Page.requestMethod == .POST) {
if let param = PostParam.from(json:Post.data.value) {
let sensitive = Page.userData as? UnsafeTmpString ?? UnsafeTmpString()
if(user_login_check(param.cmd)) {
switch(param.cmd) {
case .USER_REGISTER:
if sensitive.is_nil == false {
res = user_register(sensitive)
}
case .USER_LOGIN:
if sensitive.is_nil == false {
res = user_login((Int(Post.ext_data.value) ?? 0) == 1, sensitive)
}
case .USER_LOGOUT:
res = user_logout()
case .USER_LIST:
res = user_list()
case .USER_REMOVE:
res = user_remove()
case .USER_PASSWORD_RESET:
res = user_login_reset()
case .USER_PASSWORD_RECOVER:
if sensitive.is_nil == false {
res = user_login_recover(sensitive)
}
case .USER_LOGIN_CHECK:
res = user_check()
case .USER_ADD:
res = user_add()
case .USER_INVITE:
res = user_invite()
case .USER_ADD_TO_GROUP:
res = user_add_to_group()
case .USER_REMOVE_FROM_GROUP:
res = user_remove_from_group()
case .USER_GROUP_GET:
res = user_get_group_setting()
case .USER_GROUP_UPDATE:
res = user_update_group()
case .USER_GROUP_LIST:
res = user_list_group()
case .USER_GROUP_ADD:
res = user_add_group()
case .USER_GROUP_REMOVE:
res = user_remove_group()
case .USER_GET:
res = user_get()
case .USER_UPDATE:
res = user_update(sensitive)
case .PROBE_LIST:
res = probe_list()
case .PROBE_ADD:
if sensitive.is_nil == false {
res = probe_add(sensitive)
}
case .PROBE_GET:
res = probe_get()
case .PROBE_UPDATE:
res = probe_update(sensitive)
case .PROBE_REMOVE:
res = probe_remove()
case .PROBE_USES_GET:
res = probe_get_uses()
case .PROBE_SETTING_LIST:
res = probe_list_settings()
case .PROBE_SETTING_ADD:
res = probe_add_setting()
case .PROBE_SETTING_REMOVE:
res = probe_remove_setting()
case .MODULE_LIST:
res = module_list()
case .MODULE_GET:
res = module_get()
case .MODULE_USES_GET:
res = module_get_uses()
case .MODULE_ADD:
res = module_add()
case .MODULE_UPDATE:
res = module_update()
case .MODULE_REMOVE:
res = module_remove()
case .MODULE_DOWLOAD:
res = module_download()
case .MODULE_INSTALL:
res = module_install()
case .MODULE_SHARE:
res = module_share()
case .MODULE_PACK:
res = module_pack()
case .MODULE_CODE_LOAD:
res = module_load_code()
case .MODULE_INSTANCE_LIST:
res = module_list_instances()
case .MODULE_INSTANCE_ADD:
res = module_add_instance()
case .MODULE_INSTANCE_REMOVE:
res = module_remove_instance()
case .MODULE_INSTANCE_SETTING_GET:
res = module_instance_get_settings()
case .RUN_LIST:
res = run_list()
case .RUN_GET:
res = run_get()
case .RUN_ADD:
res = run_add()
case .RUN_UPDATE:
res = run_update()
case .RUN_UPDATE_OPTIONS:
res = run_update_options()
case .RUN_REMOVE:
res = run_remove()
case .RUN_USES_GET:
res = run_get_uses()
case .RUN_INSTANCE_LIST:
res = run_list_instances()
case .RUN_INSTANCE_ADD:
res = run_add_instance()
case .RUN_INSTANCE_REMOVE:
res = run_remove_instance()
case .RUN_INSTANCE_UPDATE:
res = run_update_instance()
case .RUN_INSTANCE_SETTING_GET:
res = run_instance_get_settings()
case .SETTING_GET:
res = setting_get()
case .SETTING_UPDATE:
res = setting_update()
case .REPO_LIST:
res = repo_list()
case .REPO_ADD:
res = repo_add(sensitive)
case .REPO_UPDATE:
res = repo_update()
case .REPO_REMOVE:
res = repo_remove()
case .CROSS_LIST:
res = cross_list()
case .CROSS_ADD:
res = cross_add(sensitive)
case .CROSS_UPDATE:
res = cross_update()
case .CROSS_REMOVE:
res = cross_remove()
}
if(res == ErrorNone) {
return
}
} else {
print(#"{"r":1,"l":1}"#)
return
}
}
} else {
}
print(#"{"r":\#(res)}"#)
} | bc78725c265ae8cfc5347e83f059ebff | 34.854532 | 190 | 0.417692 | false | false | false | false |
LiuSky/XBDialog | refs/heads/master | XBDialog/Classes/Menu/MenuPresentationController.swift | mit | 1 | //
// MenuPresentationController.swift
// XBDialog
//
// Created by xiaobin liu on 2018/2/28.
// Copyright © 2018年 Sky. All rights reserved.
//
import UIKit
/// MARK - 菜单栏控制器
public class MenuPresentationController: BasePresentationController {
public var firstOffset: CGPoint = .zero
public var percent: CGFloat = 0.01
fileprivate var pan: UIPanGestureRecognizer?
public override func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
pan = UIPanGestureRecognizer.init(target: self, action: #selector(MenuPresentationController.pan(gesture:)))
self.presentedView?.addGestureRecognizer(pan!)
}
public override var frameOfPresentedViewInContainerView: CGRect {
get {
if let frame = containerView?.frame {
let width = frame.width
let height = frame.height
switch (config as! MenuConfig).menuType {
case .bottomHeight(let h):
let y = height - h
return CGRect(x: 0, y: y, width: width, height: h)
case .bottomHeightFromViewRate(let rate):
let rateH = height * rate
let y = height - rateH
return CGRect(x: 0, y: y, width: width, height: rateH)
case .leftWidth(let w):
return CGRect(x: 0, y: 0, width: w, height: height)
case .leftWidthFromViewRate(let rate):
let rateW = rate * width
return CGRect(x: 0, y: 0, width: rateW, height: height)
case .rightWidth(let w):
return CGRect(x: width - w, y: 0, width: w, height: height)
case .rightWidthFromViewRate(let rate):
let rateW = rate * width
return CGRect(x: width - rateW , y: 0, width: rateW, height: height)
case .leftFullScreen , .rightFullScreen:
return CGRect(x: 0, y: 0, width: width, height: height)
}
} else if let f = self.presentedView?.frame {
return f
}
return CGRect.zero
} set {}
}
@objc func pan(gesture:UIPanGestureRecognizer) {
if let c = config as? MenuConfig , c.isDraggable {
let view = self.presentedViewController.view
switch gesture.state {
case .began:
c.drivenInteractive = UIPercentDrivenInteractiveTransition()
firstOffset = gesture.translation(in: view)
self.presentedViewController.dismiss(animated: true, completion: nil)
case .changed:
let current = gesture.translation(in: view)
let percent = self.calculatePercent(offset: current, config: c)
self.presentingViewScale(percent: percent, animate: false)
c.drivenInteractive?.update(percent)
case .ended , .cancelled :
let currentPercent = c.drivenInteractive?.percentComplete ?? 0.0
if c.draggableCompletedPrecent < currentPercent {
c.drivenInteractive?.finish()
} else {
self.presentingViewScale(percent: 0.01, animate: true)
c.drivenInteractive?.cancel()
}
c.drivenInteractive = nil
default:
break
}
} else {
percent = 0.001
if let c = config as? MenuConfig {
c.drivenInteractive?.cancel()
c.drivenInteractive = nil
}
}
}
fileprivate func presentingViewScale(percent:CGFloat , animate:Bool) {
self.percent = percent
let fix = (CGFloat(1.0) - config.presentingScale) * percent + config.presentingScale
if fix >= config.presentingScale {
if animate {
UIView.animate(withDuration: 0.1, animations: {
self.presentingViewController.view.transform = CGAffineTransform(scaleX: fix, y: fix)
})
} else {
self.presentingViewController.view.transform = CGAffineTransform(scaleX: fix, y: fix)
}
}
}
fileprivate func calculatePercent (offset:CGPoint , config:MenuConfig) -> CGFloat {
var percent: CGFloat = 0.001
if let view = presentedViewController.view {
switch config.menuType {
case .bottomHeight(_) , .bottomHeightFromViewRate(_):
percent = (offset.y - firstOffset.y) / (view.frame.height + 1)
case .rightWidth(_) , .rightWidthFromViewRate(_) , .rightFullScreen:
percent = (offset.x - firstOffset.x) / (view.frame.width + 1)
case .leftWidth(_) , .leftWidthFromViewRate(_) , .leftFullScreen:
percent = (firstOffset.x - offset.x) / (view.frame.width + 1)
}
}
if percent <= 0 {
return 0.001
} else if percent >= 1 {
return 0.99
} else {
return percent
}
}
}
| 42066c78097e673129b09322b3a44b0e | 38.343284 | 116 | 0.542299 | false | true | false | false |
PlutoMa/Swift-LeetCode | refs/heads/master | Code/Problem083.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
class Solution {
func deleteDuplicates(_ head: ListNode?) -> ListNode? {
guard head != nil else {
return nil
}
var start = head
var end = head!.next
let result = start
while end != nil {
if end!.val > start!.val {
start!.next = end
start = end
}
end = end!.next
}
start!.next = end
return result
}
}
let head = ListNode(1)
head.next = ListNode(1)
head.next?.next = ListNode(2)
head.next?.next?.next = ListNode(3)
head.next?.next?.next?.next = ListNode(3)
let result = Solution().deleteDuplicates(head)
var output = result
while output != nil {
print(output!.val)
output = output!.next
}
| 78e96a645ae162a28fe2fe08cf02dc69 | 21 | 59 | 0.549495 | false | false | false | false |
bdougie/ios-exercises | refs/heads/master | SwiftExercises.playground/section-1.swift | mit | 2 | import UIKit
/*
Strings
*/
func favoriteCheeseStringWithCheese(cheese: String) -> String {
// WORK HERE
return "My favorite cheese is \(cheese)"
}
let fullSentence = favoriteCheeseStringWithCheese("cheddar")
// Make fullSentence say "My favorite cheese is cheddar."
/*
Arrays & Dictionaries
*/
let numberArray = [1, 2, 3, 4]
// Add 5 to this array
// WORK HERE
var newArray = numberArray
newArray.append(5)
let numberDictionary = [1 : "one", 2 : "two", 3 : "three", 4 : "four"]
// Add 5 : "five" to this dictionary
// WORK HERE
var newDictionary = numberDictionary
newDictionary[5] = "five"
newDictionary
/*
Loops
*/
// Use a closed range loop to print 1 - 10, inclusively
// WORK HERE
for num in 1...10 {
println(num)
}
// Use a half-closed range loop to print 1 - 10, inclusively
// WORK HERE
for num in 1..<10 {
println(num)
}
let worf = [
"name": "Worf",
"rank": "lieutenant",
"information": "son of Mogh, slayer of Gowron",
"favorite drink": "prune juice",
"quote" : "Today is a good day to die."]
let picard = [
"name": "Jean-Luc Picard",
"rank": "captain",
"information": "Captain of the USS Enterprise",
"favorite drink": "tea, Earl Grey, hot"]
let characters = [worf,picard]
func favoriteDrinksArrayForCharacters(characters:Array<Dictionary<String, String>>) -> Array<String> {
// return an array of favorite drinks, like ["prune juice", "tea, Earl Grey, hot"]
// WORK HERE
var characterArray = [String]()
for i in 0...1 {
characterArray.append(characters[i]["favorite drink"]!)
}
return characterArray
}
let favoriteDrinks = favoriteDrinksArrayForCharacters(characters)
/*
Functions
*/
// Make a function that inputs an array of strings and outputs the strings separated by a semicolon
let strings = ["milk", "eggs", "bread", "challah"]
// WORK HERE - make your function and pass `strings` in
var foo = ""
func concatArray (stringArray:Array<String>) -> String {
for streeng in stringArray {
foo += streeng + ";"
}
println(foo)
return foo
}
let expectedOutput = "milk;eggs;bread;challah"
/*
Closures
*/
let cerealArray = ["Golden Grahams", "Cheerios", "Trix", "Cap'n Crunch OOPS! All Berries", "Cookie Crisp"]
var sortedCereal = cerealArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
sortedCereal
// Use a closure to sort this array alphabetically
// WORK HERE
| 6aa11b1b386bd993e57d6edf40e0bdcb | 20.198276 | 119 | 0.673038 | false | false | false | false |
jordanhamill/Stated | refs/heads/master | Sources/Stated/DSL/StateTransitionTriggerDSL.swift | mit | 1 | extension StateTransitionTrigger {
public func performingSideEffect(_ sideEffect: @escaping (StateMachine, StateTo, StateFrom, SentInput<Arguments>) -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> {
return StateTransitionTriggerWithSideEffect(
inputSlot: self.inputSlot,
transition: self.transition,
sideEffect: sideEffect
)
}
public func performingSideEffect(_ sideEffect: @escaping (StateMachine, StateTo, StateFrom) -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> {
return self.performingSideEffect { stateMachine, to, from, input in
sideEffect(stateMachine, to, from)
}
}
public func performingSideEffect(_ sideEffect: @escaping (StateMachine, StateTo) -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> {
return self.performingSideEffect { stateMachine, to, _, _ in
sideEffect(stateMachine, to)
}
}
public func performingSideEffect(_ sideEffect: @escaping (StateMachine) -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> {
return self.performingSideEffect { stateMachine, _, _, _ in
sideEffect(stateMachine)
}
}
public func performingSideEffect(_ sideEffect: @escaping () -> Void) -> StateTransitionTriggerWithSideEffect<Arguments, StateFrom, StateTo> {
return self.performingSideEffect { _, _, _, _ in
sideEffect()
}
}
}
///
/// Sugar for performing a side effect when a state transition occurs.
/// This is an alias for `StateTransitionTrigger.performingSideEffect`.
/// ```
/// anInput.given(fromState).transition(to: toState).performingSideEffect { stateMachine, toState, fromState, input in print("Side Effect") }
/// ```
/// Using operators you can get a table-like structure for easier reference:
/// ```
/// let triggerableStateTransition = anInput | fromState => toState | { stateMachine, toState, fromState, input in print("Side Effect") }
/// ```
///
public func |<ArgumentsForToState, StateFrom, StateTo>(
stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>,
sideEffect: @escaping (StateMachine, StateTo, StateFrom, SentInput<ArgumentsForToState>) -> Void)
-> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> {
return stateTransitionTrigger.performingSideEffect(sideEffect)
}
///
/// Sugar for performing a side effect when a state transition occurs.
/// This is an alias for `StateTransitionTrigger.performingSideEffect`.
/// ```
/// anInput.given(fromState).transition(to: toState).performingSideEffect { stateMachine, toState, fromState in print("Side Effect") }
/// ```
/// Using operators you can get a table-like structure for easier reference:
/// ```
/// let triggerableStateTransition = anInput | fromState => toState | { stateMachine, toState, fromState in print("Side Effect") }
/// ```
///
public func |<ArgumentsForToState, StateFrom, StateTo>(
stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>,
sideEffect: @escaping (StateMachine, StateTo, StateFrom) -> Void)
-> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> {
return stateTransitionTrigger.performingSideEffect(sideEffect)
}
///
/// Sugar for performing a side effect when a state transition occurs.
/// This is an alias for `StateTransitionTrigger.performingSideEffect`.
/// ```
/// anInput.given(fromState).transition(to: toState).performingSideEffect { stateMachine, toState in print("Side Effect") }
/// ```
/// Using operators you can get a table-like structure for easier reference:
/// ```
/// let triggerableStateTransition = anInput | fromState => toState | { stateMachine, toState in print("Side Effect") }
/// ```
///
public func |<ArgumentsForToState, StateFrom, StateTo>(
stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>,
sideEffect: @escaping (StateMachine, StateTo) -> Void)
-> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> {
return stateTransitionTrigger.performingSideEffect(sideEffect)
}
///
/// Sugar for performing a side effect when a state transition occurs.
/// This is an alias for `StateTransitionTrigger.performingSideEffect`.
/// ```
/// anInput.given(fromState).transition(to: toState).performingSideEffect { stateMachine in print("Side Effect") }
/// ```
/// Using operators you can get a table-like structure for easier reference:
/// ```
/// let triggerableStateTransition = anInput | fromState => toState | { stateMachine in print("Side Effect") }
/// ```
///
public func |<ArgumentsForToState, StateFrom, StateTo>(
stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>,
sideEffect: @escaping (StateMachine) -> Void)
-> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> {
return stateTransitionTrigger.performingSideEffect(sideEffect)
}
///
/// Sugar for performing a side effect when a state transition occurs.
/// This is an alias for `StateTransitionTrigger.performingSideEffect`.
/// ```
/// anInput.given(fromState).transition(to: toState).performingSideEffect { print("Side Effect") }
/// ```
/// Using operators you can get a table-like structure for easier reference:
/// ```
/// let triggerableStateTransition = anInput | fromState => toState | { print("Side Effect") }
/// ```
///
public func |<ArgumentsForToState, StateFrom, StateTo>(
stateTransitionTrigger: StateTransitionTrigger<ArgumentsForToState, StateFrom, StateTo>,
sideEffect: @escaping () -> Void)
-> StateTransitionTriggerWithSideEffect<ArgumentsForToState, StateFrom, StateTo> {
return stateTransitionTrigger.performingSideEffect(sideEffect)
}
| b27f2d2769247a91b042042434108c16 | 47.430894 | 199 | 0.727715 | false | false | false | false |
LudvigOdin/ARNModalTransition | refs/heads/master | ARNModalTransition/Carthage/Checkouts/ARNTransitionAnimator/Source/ARNTransitionAnimator.swift | mit | 1 | //
// ARNTransitionAnimator.swift
// ARNTransitionAnimator
//
// Created by xxxAIRINxxx on 2015/02/26.
// Copyright (c) 2015 xxxAIRINxxx. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
public enum ARNTransitionAnimatorDirection: Int {
case Top
case Bottom
case Left
case Right
}
public enum ARNTransitionAnimatorOperation: Int {
case None
case Push
case Pop
case Present
case Dismiss
}
public class ARNTransitionAnimator: UIPercentDrivenInteractiveTransition {
// animation setting
public var usingSpringWithDamping : CGFloat = 1.0
public var transitionDuration : NSTimeInterval = 0.5
public var initialSpringVelocity : CGFloat = 0.1
// interactive gesture
public weak var gestureTargetView : UIView? {
willSet {
self.unregisterPanGesture()
}
didSet {
self.registerPanGesture()
}
}
public var panCompletionThreshold : CGFloat = 100.0
public var direction : ARNTransitionAnimatorDirection = .Bottom
public var contentScrollView : UIScrollView?
public var interactiveType : ARNTransitionAnimatorOperation = .None {
didSet {
if self.interactiveType == .None {
self.unregisterPanGesture()
} else {
self.registerPanGesture()
}
}
}
// handlers
public var presentationBeforeHandler : ((containerView: UIView, transitionContext: UIViewControllerContextTransitioning) ->())?
public var presentationAnimationHandler : ((containerView: UIView, percentComplete: CGFloat) ->())?
public var presentationCancelAnimationHandler : ((containerView: UIView) ->())?
public var presentationCompletionHandler : ((containerView: UIView, completeTransition: Bool) ->())?
public var dismissalBeforeHandler : ((containerView: UIView, transitionContext: UIViewControllerContextTransitioning) ->())?
public var dismissalAnimationHandler : ((containerView: UIView, percentComplete: CGFloat) ->())?
public var dismissalCancelAnimationHandler : ((containerView: UIView) ->())?
public var dismissalCompletionHandler : ((containerView: UIView, completeTransition: Bool) ->())?
// private
private weak var fromVC : UIViewController!
private weak var toVC : UIViewController!
private(set) var operationType : ARNTransitionAnimatorOperation
private(set) var isPresenting : Bool = true
private(set) var isTransitioning : Bool = false
private var gesture : UIPanGestureRecognizer?
private var transitionContext : UIViewControllerContextTransitioning?
private var panLocationStart : CGFloat = 0.0
deinit {
self.unregisterPanGesture()
}
// MARK: Constructor
public init(operationType: ARNTransitionAnimatorOperation, fromVC: UIViewController, toVC: UIViewController) {
self.operationType = operationType
self.fromVC = fromVC
self.toVC = toVC
switch (self.operationType) {
case .Push, .Present:
self.isPresenting = true
case .Pop, .Dismiss:
self.isPresenting = false
case .None:
break
}
}
// MARK: Private Methods
private func registerPanGesture() {
self.unregisterPanGesture()
self.gesture = UIPanGestureRecognizer(target: self, action: "handlePan:")
self.gesture!.delegate = self
self.gesture!.maximumNumberOfTouches = 1
if let _gestureTargetView = self.gestureTargetView {
_gestureTargetView.addGestureRecognizer(self.gesture!)
} else {
switch (self.interactiveType) {
case .Push, .Present:
self.fromVC.view.addGestureRecognizer(self.gesture!)
case .Pop, .Dismiss:
self.toVC.view.addGestureRecognizer(self.gesture!)
case .None:
break
}
}
}
private func unregisterPanGesture() {
if let _gesture = self.gesture {
if let _view = _gesture.view {
_view.removeGestureRecognizer(_gesture)
}
_gesture.delegate = nil
}
self.gesture = nil
}
private func fireBeforeHandler(containerView: UIView, transitionContext: UIViewControllerContextTransitioning) {
if self.isPresenting {
self.presentationBeforeHandler?(containerView: containerView, transitionContext: transitionContext)
} else {
self.dismissalBeforeHandler?(containerView: containerView, transitionContext: transitionContext)
}
}
private func fireAnimationHandler(containerView: UIView, percentComplete: CGFloat) {
if self.isPresenting {
self.presentationAnimationHandler?(containerView: containerView, percentComplete: percentComplete)
} else {
self.dismissalAnimationHandler?(containerView: containerView, percentComplete: percentComplete)
}
}
private func fireCancelAnimationHandler(containerView: UIView) {
if self.isPresenting {
self.presentationCancelAnimationHandler?(containerView: containerView)
} else {
self.dismissalCancelAnimationHandler?(containerView: containerView)
}
}
private func fireCompletionHandler(containerView: UIView, completeTransition: Bool) {
if self.isPresenting {
self.presentationCompletionHandler?(containerView: containerView, completeTransition: completeTransition)
} else {
self.dismissalCompletionHandler?(containerView: containerView, completeTransition: completeTransition)
}
}
private func animateWithDuration(duration: NSTimeInterval, containerView: UIView, completeTransition: Bool, completion: (() -> Void)?) {
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: self.usingSpringWithDamping,
initialSpringVelocity: self.initialSpringVelocity,
options: .CurveEaseOut,
animations: {
if completeTransition {
self.fireAnimationHandler(containerView, percentComplete: 1.0)
} else {
self.fireCancelAnimationHandler(containerView)
}
}, completion: { finished in
self.fireCompletionHandler(containerView, completeTransition: completeTransition)
completion?()
})
}
// MARK: Gesture
func handlePan(recognizer: UIPanGestureRecognizer) {
var window : UIWindow? = nil
switch (self.interactiveType) {
case .Push, .Present:
window = self.fromVC.view.window
case .Pop, .Dismiss:
window = self.toVC.view.window
case .None:
return
}
var location = recognizer.locationInView(window)
location = CGPointApplyAffineTransform(location, CGAffineTransformInvert(recognizer.view!.transform))
var velocity = recognizer .velocityInView(window)
velocity = CGPointApplyAffineTransform(velocity, CGAffineTransformInvert(recognizer.view!.transform))
if recognizer.state == .Began {
switch (self.direction) {
case .Top, .Bottom:
self.panLocationStart = location.y
case .Left, .Right:
self.panLocationStart = location.x
}
if let _contentScrollView = self.contentScrollView {
if _contentScrollView.contentOffset.y <= 0.0 {
self.startGestureTransition()
_contentScrollView.bounces = false
}
} else {
self.startGestureTransition()
}
} else if recognizer.state == .Changed {
var bounds = CGRectZero
switch (self.interactiveType) {
case .Push, .Present:
bounds = self.fromVC.view.bounds
case .Pop, .Dismiss:
bounds = self.toVC.view.bounds
case .None:
break
}
var animationRatio: CGFloat = 0.0
switch self.direction {
case .Top:
animationRatio = (self.panLocationStart - location.y) / CGRectGetHeight(bounds)
case .Bottom:
animationRatio = (location.y - self.panLocationStart) / CGRectGetHeight(bounds)
case .Left:
animationRatio = (self.panLocationStart - location.x) / CGRectGetWidth(bounds)
case .Right:
animationRatio = (location.x - self.panLocationStart) / CGRectGetWidth(bounds)
}
if let _contentScrollView = self.contentScrollView {
if self.isTransitioning == false && _contentScrollView.contentOffset.y <= 0 {
self.startGestureTransition()
} else {
self.updateInteractiveTransition(animationRatio)
}
} else {
self.updateInteractiveTransition(animationRatio)
}
} else if recognizer.state == .Ended {
var velocityForSelectedDirection: CGFloat = 0.0
switch (self.direction) {
case .Top, .Bottom:
velocityForSelectedDirection = velocity.y
case .Left, .Right:
velocityForSelectedDirection = velocity.x
}
if velocityForSelectedDirection > self.panCompletionThreshold && (self.direction == .Right || self.direction == .Bottom) {
self.finishInteractiveTransitionAnimated(true)
} else if velocityForSelectedDirection < -self.panCompletionThreshold && (self.direction == .Left || self.direction == .Top) {
self.finishInteractiveTransitionAnimated(true)
} else {
let animated = self.contentScrollView?.contentOffset.y <= 0
self.cancelInteractiveTransitionAnimated(animated)
}
self.resetGestureTransitionSetting()
} else {
self.resetGestureTransitionSetting()
if self.isTransitioning {
self.cancelInteractiveTransitionAnimated(true)
}
}
}
func startGestureTransition() {
if self.isTransitioning == false {
self.isTransitioning = true
switch (self.interactiveType) {
case .Push:
self.fromVC.navigationController?.pushViewController(self.toVC, animated: true)
case .Present:
self.fromVC.presentViewController(self.toVC, animated: true, completion: nil)
case .Pop:
self.toVC.navigationController?.popViewControllerAnimated(true)
case .Dismiss:
self.toVC.dismissViewControllerAnimated(true, completion: nil)
case .None:
break
}
}
}
func resetGestureTransitionSetting() {
self.isTransitioning = false
}
}
// MARK: UIViewControllerAnimatedTransitioning
extension ARNTransitionAnimator: UIViewControllerAnimatedTransitioning {
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return self.transitionDuration
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()
self.transitionContext = transitionContext
self.fireBeforeHandler(containerView!, transitionContext: transitionContext)
self.animateWithDuration(
self.transitionDuration(transitionContext),
containerView: containerView!,
completeTransition: true) {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
public func animationEnded(transitionCompleted: Bool) {
self.transitionContext = nil
}
}
// MARK: UIViewControllerTransitioningDelegate
extension ARNTransitionAnimator: UIViewControllerTransitioningDelegate {
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresenting = true
return self
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresenting = false
return self
}
public func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if self.gesture != nil && (self.interactiveType == .Push || self.interactiveType == .Present) {
self.isPresenting = true
return self
}
return nil
}
public func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if self.gesture != nil && (self.interactiveType == .Pop || self.interactiveType == .Dismiss) {
self.isPresenting = false
return self
}
return nil
}
}
// MARK: UIViewControllerInteractiveTransitioning
extension ARNTransitionAnimator {
public override func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()
// FIXME : UINavigationController not called animator UIViewControllerTransitioningDelegate
switch (self.interactiveType) {
case .Push, .Present:
self.isPresenting = true
case .Pop, .Dismiss:
self.isPresenting = false
case .None:
break
}
self.transitionContext = transitionContext
self.fireBeforeHandler(containerView!, transitionContext: transitionContext)
}
}
// MARK: UIPercentDrivenInteractiveTransition
extension ARNTransitionAnimator {
public override func updateInteractiveTransition(percentComplete: CGFloat) {
super.updateInteractiveTransition(percentComplete)
if let transitionContext = self.transitionContext {
let containerView = transitionContext.containerView()
self.fireAnimationHandler(containerView!, percentComplete: percentComplete)
}
}
public func finishInteractiveTransitionAnimated(animated: Bool) {
super.finishInteractiveTransition()
if let transitionContext = self.transitionContext {
let containerView = transitionContext.containerView()
self.animateWithDuration(
animated ? self.transitionDuration(transitionContext) : 0,
containerView: containerView!,
completeTransition: true) {
transitionContext.completeTransition(true)
}
}
}
public func cancelInteractiveTransitionAnimated(animated: Bool) {
super.cancelInteractiveTransition()
if let transitionContext = self.transitionContext {
let containerView = transitionContext.containerView()
self.animateWithDuration(
animated ? self.transitionDuration(transitionContext) : 0,
containerView: containerView!,
completeTransition: false) {
transitionContext.completeTransition(false)
}
}
}
}
// MARK: UIGestureRecognizerDelegate
extension ARNTransitionAnimator: UIGestureRecognizerDelegate {
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return self.contentScrollView != nil ? true : false
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer
otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
}
| 7f3b41cdfc94f1a1627bca87619ff1f0 | 36.887356 | 224 | 0.641466 | false | false | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library | refs/heads/master | Example/Pods/ZIPFoundation/Sources/ZIPFoundation/Archive+Reading.swift | bsd-3-clause | 1 | //
// Archive+Reading.swift
// ZIPFoundation
//
// Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
extension Archive {
/// Read a ZIP `Entry` from the receiver and write it to `url`.
///
/// - Parameters:
/// - entry: The ZIP `Entry` to read.
/// - url: The destination file URL.
/// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed).
/// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance.
/// - progress: A progress object that can be used to track or cancel the extract operation.
/// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`.
/// - Throws: An error if the destination file cannot be written or the entry contains malformed content.
public func extract(_ entry: Entry, to url: URL, bufferSize: UInt32 = defaultReadChunkSize, skipCRC32: Bool = false,
progress: Progress? = nil) throws -> CRC32 {
let fileManager = FileManager()
var checksum = CRC32(0)
switch entry.type {
case .file:
guard !fileManager.itemExists(at: url) else {
throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path])
}
try fileManager.createParentDirectoryStructure(for: url)
let destinationRepresentation = fileManager.fileSystemRepresentation(withPath: url.path)
guard let destinationFile: UnsafeMutablePointer<FILE> = fopen(destinationRepresentation, "wb+") else {
throw CocoaError(.fileNoSuchFile)
}
defer { fclose(destinationFile) }
let consumer = { _ = try Data.write(chunk: $0, to: destinationFile) }
checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32,
progress: progress, consumer: consumer)
case .directory:
let consumer = { (_: Data) in
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
}
checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32,
progress: progress, consumer: consumer)
case .symlink:
guard !fileManager.itemExists(at: url) else {
throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path])
}
let consumer = { (data: Data) in
guard let linkPath = String(data: data, encoding: .utf8) else { throw ArchiveError.invalidEntryPath }
try fileManager.createParentDirectoryStructure(for: url)
try fileManager.createSymbolicLink(atPath: url.path, withDestinationPath: linkPath)
}
checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32,
progress: progress, consumer: consumer)
}
let attributes = FileManager.attributes(from: entry)
try fileManager.setAttributes(attributes, ofItemAtPath: url.path)
return checksum
}
/// Read a ZIP `Entry` from the receiver and forward its contents to a `Consumer` closure.
///
/// - Parameters:
/// - entry: The ZIP `Entry` to read.
/// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed).
/// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance.
/// - progress: A progress object that can be used to track or cancel the extract operation.
/// - consumer: A closure that consumes contents of `Entry` as `Data` chunks.
/// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`..
/// - Throws: An error if the destination file cannot be written or the entry contains malformed content.
public func extract(_ entry: Entry, bufferSize: UInt32 = defaultReadChunkSize, skipCRC32: Bool = false,
progress: Progress? = nil, consumer: Consumer) throws -> CRC32 {
var checksum = CRC32(0)
let localFileHeader = entry.localFileHeader
fseek(self.archiveFile, entry.dataOffset, SEEK_SET)
progress?.totalUnitCount = self.totalUnitCountForReading(entry)
switch entry.type {
case .file:
guard let compressionMethod = CompressionMethod(rawValue: localFileHeader.compressionMethod) else {
throw ArchiveError.invalidCompressionMethod
}
switch compressionMethod {
case .none: checksum = try self.readUncompressed(entry: entry, bufferSize: bufferSize,
skipCRC32: skipCRC32, progress: progress, with: consumer)
case .deflate: checksum = try self.readCompressed(entry: entry, bufferSize: bufferSize,
skipCRC32: skipCRC32, progress: progress, with: consumer)
}
case .directory:
try consumer(Data())
progress?.completedUnitCount = self.totalUnitCountForReading(entry)
case .symlink:
let localFileHeader = entry.localFileHeader
let size = Int(localFileHeader.compressedSize)
let data = try Data.readChunk(of: size, from: self.archiveFile)
checksum = data.crc32(checksum: 0)
try consumer(data)
progress?.completedUnitCount = self.totalUnitCountForReading(entry)
}
return checksum
}
// MARK: - Helpers
private func readUncompressed(entry: Entry, bufferSize: UInt32, skipCRC32: Bool,
progress: Progress? = nil, with consumer: Consumer) throws -> CRC32 {
let size = Int(entry.centralDirectoryStructure.uncompressedSize)
return try Data.consumePart(of: size, chunkSize: Int(bufferSize), skipCRC32: skipCRC32,
provider: { (_, chunkSize) -> Data in
return try Data.readChunk(of: Int(chunkSize), from: self.archiveFile)
}, consumer: { (data) in
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
try consumer(data)
progress?.completedUnitCount += Int64(data.count)
})
}
private func readCompressed(entry: Entry, bufferSize: UInt32, skipCRC32: Bool,
progress: Progress? = nil, with consumer: Consumer) throws -> CRC32 {
let size = Int(entry.centralDirectoryStructure.compressedSize)
return try Data.decompress(size: size, bufferSize: Int(bufferSize), skipCRC32: skipCRC32,
provider: { (_, chunkSize) -> Data in
return try Data.readChunk(of: chunkSize, from: self.archiveFile)
}, consumer: { (data) in
if progress?.isCancelled == true { throw ArchiveError.cancelledOperation }
try consumer(data)
progress?.completedUnitCount += Int64(data.count)
})
}
}
| bab8e655d982bab35ab4ba58b5245cd1 | 54.56391 | 120 | 0.624628 | false | false | false | false |
XSega/Words | refs/heads/master | Vendors/SRCountdownTimer/SRCountdownTimer.swift | mit | 1 | /*
MIT License
Copyright (c) 2017 Ruslan Serebriakov <[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
@objc public protocol SRCountdownTimerDelegate: class {
@objc optional func timerDidUpdateCounterValue(newValue: Int)
@objc optional func timerDidStart()
@objc optional func timerDidPause()
@objc optional func timerDidResume()
@objc optional func timerDidEnd()
}
public class SRCountdownTimer: UIView {
public var lineWidth: CGFloat = 2.0
public var lineColor: UIColor = .black
public var trailLineColor: UIColor = UIColor.lightGray.withAlphaComponent(0.5)
public var isLabelHidden: Bool = false
public var labelFont: UIFont?
public var labelTextColor: UIColor?
public var timerFinishingText: String?
public weak var delegate: SRCountdownTimerDelegate?
private var timer: Timer?
private var totalTime: TimeInterval = 1
private var elapsedTime: TimeInterval = 0
private let fireInterval: TimeInterval = 0.01 // ~60 FPS
private lazy var counterLabel: UILabel = {
let label = UILabel()
self.addSubview(label)
label.textAlignment = .center
label.frame = self.bounds
if let font = self.labelFont {
label.font = font
}
if let color = self.labelTextColor {
label.textColor = color
}
return label
}()
private var currentCounterValue: Int = 0 {
didSet {
if !isLabelHidden {
if let text = timerFinishingText, currentCounterValue == 0 {
counterLabel.text = text
} else {
counterLabel.text = "\(currentCounterValue)"
}
}
delegate?.timerDidUpdateCounterValue?(newValue: currentCounterValue)
}
}
// MARK: Inits
override public init(frame: CGRect) {
if frame.width != frame.height {
fatalError("Please use a rectangle frame for SRCountdownTimer")
}
super.init(frame: frame)
layer.cornerRadius = frame.width / 2
clipsToBounds = true
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()
let radius = (rect.width - lineWidth) / 2
let currentAngle = CGFloat((.pi * 2 * elapsedTime) / totalTime)
context?.setLineWidth(lineWidth)
// Main line
context?.beginPath()
context?.addArc(
center: CGPoint(x: rect.midX, y:rect.midY),
radius: radius,
startAngle: currentAngle - .pi / 2,
endAngle: .pi * 2 - .pi / 2,
clockwise: false)
context?.setStrokeColor(lineColor.cgColor)
context?.strokePath()
// Trail line
context?.beginPath()
context?.addArc(
center: CGPoint(x: rect.midX, y:rect.midY),
radius: radius,
startAngle: -.pi / 2,
endAngle: currentAngle - .pi / 2,
clockwise: false)
context?.setStrokeColor(trailLineColor.cgColor)
context?.strokePath()
}
// MARK: Public methods
/**
* Starts the timer and the animation. If timer was previously runned, it'll invalidate it.
* - Parameters:
* - beginingValue: Value to start countdown from.
* - interval: Interval between reducing the counter(1 second by default)
*/
public func start(beginingValue: Int, interval: TimeInterval = 1) {
totalTime = TimeInterval(beginingValue) * interval
elapsedTime = 0
currentCounterValue = beginingValue
print("Start timer")
timer?.invalidate()
timer = Timer(timeInterval: fireInterval, repeats: true) { timer in
self.elapsedTime += self.fireInterval
if self.elapsedTime < self.totalTime {
self.setNeedsDisplay()
let computedCounterValue = beginingValue - Int(self.elapsedTime / interval)
if computedCounterValue != self.currentCounterValue {
self.currentCounterValue = computedCounterValue
}
} else {
self.callEndDelegate()
}
}
RunLoop.main.add(timer!, forMode: .defaultRunLoopMode)
delegate?.timerDidStart?()
}
/**
* Pauses the timer with saving the current state
*/
public func pause() {
timer?.fireDate = Date.distantFuture
delegate?.timerDidPause?()
}
/**
* Resumes the timer from the current state
*/
public func resume() {
timer?.fireDate = Date()
delegate?.timerDidResume?()
}
/**
* End the timer
*/
public func end() {
self.currentCounterValue = 0
timer?.invalidate()
print("End timer")
}
public func callEndDelegate() {
end()
delegate?.timerDidEnd?()
}
}
| 9fca7f07790d1d9725c4f6bc73fc4382 | 30.640625 | 95 | 0.62963 | false | false | false | false |
CocoaHeads-Shanghai/MeetupPresentations | refs/heads/master | 2016_03_31 Meeting #15 Begin a New Start/Presentation && Demo/5 Swift Tips in 5 Minutes.playground/Pages/Easier Configuration.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import UIKit
import XCPlayground
/// - SeeAlso: [Reader Submissions - New Year's 2016](http://nshipster.com/new-years-2016/)
@warn_unused_result
public func Init<Type>(value : Type, @noescape block: (object: Type) -> Void) -> Type {
block(object: value)
return value
}
//: Good
let textLabel = Init(UILabel()) {
$0.font = UIFont.boldSystemFontOfSize(13.0)
$0.text = "Hello, World"
$0.textAlignment = .Center
}
//: Not that good
let anotherLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFontOfSize(13.0)
label.text = "Hello, World"
label.textAlignment = .Center
return label
}()
textLabel
anotherLabel
//: [Next](@next)
| 0cdefaf48fcbadd8ab9187da454aaaa1 | 21.34375 | 91 | 0.664336 | false | false | false | false |
flypaper0/ethereum-wallet | refs/heads/release/1.1 | ethereum-wallet/Classes/BusinessLayer/Core/Services/Transaction/TransactionService.swift | gpl-3.0 | 1 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import Geth
class TransactionService: TransactionServiceProtocol {
private let context: GethContext
private let client: GethEthereumClient
private let keystore: KeystoreService
private let chain: Chain
private let factory: TransactionFactoryProtocol
private let transferType: CoinType
init(core: Ethereum, keystore: KeystoreService, transferType: CoinType) {
self.context = core.context
self.client = core.client
self.chain = core.chain
self.keystore = keystore
self.transferType = transferType
let factory = TransactionFactory(keystore: keystore, core: core)
self.factory = factory
}
func sendTransaction(with info: TransactionInfo, passphrase: String, queue: DispatchQueue, result: @escaping (Result<GethTransaction>) -> Void) {
Ethereum.syncQueue.async {
do {
let account = try self.keystore.getAccount(at: 0)
let transaction = try self.factory.buildTransaction(with: info, type: self.transferType)
let signedTransaction = try self.keystore.signTransaction(transaction, account: account, passphrase: passphrase, chainId: self.chain.chainId)
try self.sendTransaction(signedTransaction)
queue.async {
result(.success(signedTransaction))
}
} catch {
queue.async {
result(.failure(error))
}
}
}
}
private func sendTransaction(_ signedTransaction: GethTransaction) throws {
try client.sendTransaction(context, tx: signedTransaction)
}
}
| 0e6c958f9eb62e33c577d744bba83c53 | 31.693878 | 149 | 0.71161 | false | false | false | false |
tqtifnypmb/huntaway | refs/heads/master | Sources/Huntaway/Request.swift | mit | 1 | //
// Request.swift
// Huntaway
//
// The MIT License (MIT)
//
// Copyright (c) 2016 tqtifnypmb
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public class Request {
private let url: NSURL
private let method: HTTPClient.Method
// auth
var basic: (String, String)?
var digest: (String, String)?
var HTTPCookies: [String: String]? = nil
var HTTPHeaders: [String: String]? = nil
init(url: NSURL, method: HTTPClient.Method) {
self.url = url
self.method = method
}
public var allowRedirect: Bool = true
public var timeoutInterval: NSTimeInterval = 240.0
public var cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy
public var cellularAccess = true
public var networkServiceType: NSURLRequestNetworkServiceType = .NetworkServiceTypeDefault
public var shouldHandleCookies = true
public var rememberRedirectHistory = false
public var maxRedirect = Int.max
var current_redirect_count = 0
var basicAuthSettings: NSURLCredential? {
guard let basicSettings = self.basic else { return nil }
let credential = NSURLCredential(user: basicSettings.0, password: basicSettings.1, persistence: .None)
return credential
}
var diegestAuthSettings: NSURLCredential? {
guard let digestSettings = self.digest else { return nil }
let credential = NSURLCredential(user: digestSettings.0, password: digestSettings.1, persistence: .None)
return credential
}
/// Indicate whether data of this request send in stream mode.
/// If you want to send a file that's too big to be read into memory
/// you should turn this on.
public var stream: Bool = false
/// Indicate whether this request should be handled by a session that
/// outlast this life.
public var outlast: Bool = false
/// Data that's going to be sent.
public var data: NSData? = nil
/// File that's going to be sent
public var filePath: NSURL? = nil
public var URL: NSURL {
return self.url
}
public var HTTPMethod: HTTPClient.Method {
return self.method
}
public func setCookies(cookies: [String: String]) {
self.HTTPCookies = self.HTTPCookies ?? [:]
for (key, value) in cookies {
self.HTTPCookies![key] = value
}
}
public func setHeaders(headers: [String: String]) {
self.HTTPHeaders = self.HTTPHeaders ?? [:]
for (key, value) in headers {
// Users're not allow to set these headers
// see [NSURLSessionConfiguration]
switch key.uppercaseString {
case "AUTHORIZATION":
continue
case "CONNECTION":
continue
case "HOST":
continue
case "WWW-AUTHENTICATE":
continue
default:
self.HTTPHeaders![key] = value
}
}
}
public func basicAuth(user user: String, passwd: String) {
self.basic = (user, passwd)
}
public func digestAuth(user user: String, passwd: String) {
self.digest = (user, passwd)
}
}
| dc2d32da353f1e96cb2f88e16400aff1 | 32.469231 | 112 | 0.64353 | false | false | false | false |
astrokin/EZSwiftExtensions | refs/heads/master | EZSwiftExtensionsTests/UILabelTests.swift | mit | 2 | //
// UILabelTests.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 8/25/16.
// Copyright © 2016 Goktug Yilmaz. All rights reserved.
//
import XCTest
@testable import EZSwiftExtensions
class UILabelTests: XCTestCase {
func testInit() {
let label = UILabel(x: 0, y: 0, w: 200, h: 50)
let expected = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
let label2 = UILabel(x: 0, y: 0, w: 200, h: 50, fontSize: 20)
XCTAssertEqual(label.frame, expected.frame)
XCTAssertEqual(label2.font.pointSize, 20)
}
func testSet() {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
label.set(text: "EZSwiftExtensions✅", duration: 1)
XCTAssertEqual(label.text, "EZSwiftExtensions✅")
label.text = ""
label.set(text: "EZSwiftExtensions🚀", duration: 0)
XCTAssertEqual(label.text, "EZSwiftExtensions🚀")
label.text = ""
label.set(text: "EZSwiftExtensions❤️", duration: 1)
XCTAssertEqual(label.text, "EZSwiftExtensions❤️")
}
var waitExpectation: XCTestExpectation?
func wait(duration: TimeInterval) {
waitExpectation = expectation(description: "wait")
Timer.scheduledTimer(timeInterval: duration, target: self,
selector: #selector(UILabelTests.onTimer), userInfo: nil, repeats: false)
waitForExpectations(timeout: duration + 3, handler: nil)
}
func onTimer() {
waitExpectation?.fulfill()
}
}
| 1437a2b36400760a27175dc2866d65e0 | 30.470588 | 120 | 0.603115 | false | true | false | false |
OscarSwanros/swift | refs/heads/master | test/stdlib/NewStringAppending.swift | apache-2.0 | 12 | // RUN: %target-run-stdlib-swift | %FileCheck %s
// REQUIRES: executable_test
//
// Parts of this test depend on memory allocator specifics. The test
// should be rewritten soon so it doesn't expose legacy components
// like OpaqueString anyway, so we can just disable the failing
// configuration
//
// Memory allocator specifics also vary across platforms.
// REQUIRES: CPU=x86_64, OS=macosx
import Foundation
import Swift
func hexAddrVal<T>(_ x: T) -> String {
return "@0x" + String(UInt64(unsafeBitCast(x, to: Int.self)), radix: 16)
}
func hexAddr(_ x: AnyObject?) -> String {
if let owner = x {
if let y = owner as? _HeapBufferStorage<_StringBufferIVars, UInt16> {
return ".native\(hexAddrVal(y))"
}
if let y = owner as? NSString {
return ".cocoa\(hexAddrVal(y))"
}
else {
return "?Uknown?\(hexAddrVal(owner))"
}
}
return "nil"
}
func repr(_ x: NSString) -> String {
return "\(NSStringFromClass(object_getClass(x)))\(hexAddr(x)) = \"\(x)\""
}
func repr(_ x: _StringCore) -> String {
if x.hasContiguousStorage {
if let b = x.nativeBuffer {
let offset = x.elementWidth == 2
? b.start - UnsafeMutableRawPointer(x.startUTF16)
: b.start - UnsafeMutableRawPointer(x.startASCII)
return "Contiguous(owner: "
+ "\(hexAddr(x._owner))[\(offset)...\(x.count + offset)]"
+ ", capacity = \(b.capacity))"
}
return "Contiguous(owner: \(hexAddr(x._owner)), count: \(x.count))"
}
else if let b2 = x.cocoaBuffer {
return "Opaque(buffer: \(hexAddr(b2))[0...\(x.count)])"
}
return "?????"
}
func repr(_ x: String) -> String {
return "String(\(repr(x._core))) = \"\(x)\""
}
// ===------- Appending -------===
// CHECK: --- Appending ---
print("--- Appending ---")
var s = "⓪" // start non-empty
// To make this test independent of the memory allocator implementation,
// explicitly request initial capacity.
s.reserveCapacity(8)
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer0:[x0-9a-f]+]][0...2], capacity = 8)) = "⓪1"
s += "1"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer1:[x0-9a-f]+]][0...8], capacity = 8)) = "⓪1234567"
s += "234567"
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer2:[x0-9a-f]+]][0...9], capacity = 16)) = "⓪12345678"
// CHECK-NOT: .native@[[buffer1]]
s += "8"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer2]][0...16], capacity = 16)) = "⓪123456789012345"
s += "9012345"
print("\(repr(s))")
// -- expect a reallocation here
// Appending more than the next level of capacity only takes as much
// as required. I'm not sure whether this is a great idea, but the
// point is to prevent huge amounts of fragmentation when a long
// string is appended to a short one. The question, of course, is
// whether more appends are coming, in which case we should give it
// more capacity. It might be better to always grow to a multiple of
// the current capacity when the capacity is exceeded.
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer3:[x0-9a-f]+]][0...48], capacity = 48))
// CHECK-NOT: .native@[[buffer2]]
s += s + s
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4:[x0-9a-f]+]][0...49], capacity = 96))
// CHECK-NOT: .native@[[buffer3]]
s += "C"
print("\(repr(s))")
var s1 = s
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4]][0...49], capacity = 96))
print("\(repr(s1))")
/// The use of later buffer capacity by another string forces
/// reallocation
// CHECK-NEXT: String{{.*}} = {{.*}}X"
// CHECK-NOT: .native@[[buffer4]]
s1 += "X"
print("\(repr(s1))")
/// Appending to an empty string re-uses the RHS
// CHECK-NEXT: .native@[[buffer4]]
var s2 = String()
s2 += s
print("\(repr(s2))")
| bace248148b572920948a9664412aa6c | 28.389313 | 108 | 0.633247 | false | false | false | false |
multinerd/Mia | refs/heads/master | Mia/Testing/NotificationAlerts/SANotificationView.swift | mit | 1 | import Foundation
import UIKit
open class SANotificationView {
class var mainInstance : SANotificationView {
struct Static {
static let inst : SANotificationView = SANotificationView()
}
return Static.inst
}
fileprivate func currentViewController() -> UIViewController? {
var presentedWindow = UIApplication.shared.keyWindow?.rootViewController
while let pWindow = presentedWindow?.presentedViewController
{
presentedWindow = pWindow
}
return presentedWindow
}
fileprivate func currentWindow() -> UIWindow {
let presentedWindow = UIApplication.shared.keyWindow
return presentedWindow!
}
private var statusBarView = UIView()
private var statusBarLabel = UILabel()
private var isNavbarPresent : Bool = false
private var SABarViewTimer : Timer!
private var SABarView = UIView()
private var SABarBgView = UIView()
private var SABarTitleLabel = UILabel()
private var SABarLabel = UILabel()
private var SABarImageView = UIImageView()
private var SABarPullView = UIImageView()
// MARK: - showStatusBarBanner
open class func showStatusBarBanner(message:String,backgroundColor:UIColor,textColor:UIColor,showTime:Int){
//statusBarView
mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
mainInstance.statusBarView.backgroundColor = backgroundColor
mainInstance.currentWindow().addSubview(mainInstance.statusBarView)
//statusBarLabel
mainInstance.statusBarLabel.frame = CGRect(x: 0, y: 0, width: mainInstance.currentWindow().frame.width, height: 0)
mainInstance.statusBarLabel.text = message
mainInstance.statusBarLabel.textAlignment = .center
mainInstance.statusBarLabel.font = UIFont.systemFont(ofSize: 12)
mainInstance.statusBarLabel.textColor = textColor
mainInstance.statusBarLabel.numberOfLines = 1
mainInstance.statusBarView.addSubview(mainInstance.statusBarLabel)
//Animation
UIView.animate(withDuration: 0.3) {
if UIDevice().userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height == 2436 {
//iPhone X
print("This view doesn't support iphoneX.Please use showTinyBanner")
// mainInstance.statusBarView.frame = CGRect(x: 0, y:UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 20)
// mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 20)
}else{
mainInstance.statusBarView.window?.windowLevel = UIWindowLevelStatusBar+1
mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height)
mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height)
}
}
Timer.scheduledTimer(timeInterval: TimeInterval(showTime), target: self, selector: #selector(removeStatusView), userInfo: nil, repeats: false)
}
// MARK: - showBanner
open class func showBanner(title:String,message:String,textColor:UIColor,image:UIImage,backgroundColor:UIColor,showTime:Int){
//SABarBgView
mainInstance.SABarBgView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
mainInstance.SABarBgView.backgroundColor = backgroundColor
mainInstance.currentWindow().addSubview(mainInstance.SABarBgView)
//SABarView
mainInstance.SABarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
mainInstance.SABarView.backgroundColor = backgroundColor
mainInstance.SABarView.layer.masksToBounds = true
mainInstance.currentWindow().addSubview(mainInstance.SABarView)
//SABarTitleLabel
mainInstance.SABarTitleLabel.frame = CGRect(x: 80, y: UIApplication.shared.statusBarFrame.height+5, width: mainInstance.currentWindow().frame.width-90, height: 10)
mainInstance.SABarTitleLabel.text = title
mainInstance.SABarTitleLabel.textAlignment = .left
mainInstance.SABarTitleLabel.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 16)
mainInstance.SABarTitleLabel.sizeToFit()
mainInstance.SABarTitleLabel.textColor = textColor
mainInstance.SABarTitleLabel.numberOfLines = 1
mainInstance.SABarView.addSubview(mainInstance.SABarTitleLabel)
//SABarLabel
mainInstance.SABarLabel.frame = CGRect(x: 80, y: UIApplication.shared.statusBarFrame.height+25, width: mainInstance.currentWindow().frame.width-90, height: 15)
mainInstance.SABarLabel.text = message
mainInstance.SABarLabel.textAlignment = .left
mainInstance.SABarLabel.font = UIFont(name: "AppleSDGothicNeo-Light", size: 12)
mainInstance.SABarLabel.lineBreakMode = .byWordWrapping
mainInstance.SABarLabel.textColor = .black
mainInstance.SABarLabel.numberOfLines = 1
mainInstance.SABarView.addSubview(mainInstance.SABarLabel)
//SAImageView
mainInstance.SABarImageView.frame = CGRect(x: 20, y: UIApplication.shared.statusBarFrame.height, width: 50, height: 50)
mainInstance.SABarView.addSubview(mainInstance.SABarImageView)
mainInstance.SABarImageView.image = image
mainInstance.SABarImageView.layer.cornerRadius = mainInstance.SABarImageView.frame.height/2
mainInstance.SABarImageView.layer.masksToBounds = true
//SAPullImageView
mainInstance.SABarPullView.frame = CGRect(x: 0, y: 0, width: 70, height: 5)
mainInstance.SABarPullView.center = CGPoint(x: mainInstance.currentWindow().frame.width/2, y: UIApplication.shared.statusBarFrame.height+64-7)
mainInstance.SABarPullView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.7)
mainInstance.SABarPullView.layer.cornerRadius = mainInstance.SABarPullView.frame.height/2
mainInstance.SABarView.addSubview(mainInstance.SABarPullView)
//Gesture
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(removeBarView))
swipeUp.direction = UISwipeGestureRecognizerDirection.up
mainInstance.SABarView.addGestureRecognizer(swipeUp)
//Animation
UIView.animate(withDuration: 0.3, animations: {
mainInstance.SABarBgView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height+64)
mainInstance.SABarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height+64)
}) { (true) in
dropShadow(view: mainInstance.SABarBgView, scale: true)
}
mainInstance.SABarViewTimer = Timer.scheduledTimer(timeInterval: TimeInterval(showTime), target: self, selector: #selector(removeBarView), userInfo: nil, repeats: false)
}
// MARK: - showBanner without bgcolor and text color
open class func showBanner(title:String,message:String,image:UIImage,showTime:Int){
showBanner(title: title, message: message, textColor: .black, image: image, backgroundColor: .white, showTime: showTime)
}
// MARK: - showTinyBanner
open class func showTinyBanner(message:String,backgroundColor:UIColor,textColor:UIColor,showTime:Int){
//statusBarView
let nav = UIApplication.shared.keyWindow?.rootViewController
if (nav is UINavigationController) {
let navc = nav as? UINavigationController
if navc?.isNavigationBarHidden ?? false {
//no navigation bar
mainInstance.isNavbarPresent = false
mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
}
else {
// navigation bar
mainInstance.isNavbarPresent = true
mainInstance.statusBarView.frame = CGRect(x: 0, y:44+UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 0)
}
}
mainInstance.statusBarView.backgroundColor = backgroundColor
mainInstance.currentViewController()?.view.addSubview(mainInstance.statusBarView)
//statusBarLabel
mainInstance.statusBarLabel.frame = CGRect(x: 0, y: 0, width: mainInstance.currentWindow().frame.width, height: 0)
mainInstance.statusBarLabel.text = message
mainInstance.statusBarLabel.textAlignment = .center
mainInstance.statusBarLabel.font = UIFont.systemFont(ofSize: 12)
mainInstance.statusBarLabel.textColor = textColor
mainInstance.statusBarLabel.numberOfLines = 1
mainInstance.statusBarView.addSubview(mainInstance.statusBarLabel)
//Animation
UIView.animate(withDuration: 0.3) {
if mainInstance.isNavbarPresent{
mainInstance.statusBarView.frame = CGRect(x: 0, y:44+UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 20)
mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 20)
}else{
mainInstance.statusBarView.window?.windowLevel = UIWindowLevelStatusBar+1
mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: UIApplication.shared.statusBarFrame.height+20)
mainInstance.statusBarLabel.frame = CGRect(x: 0, y:UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 20)
}
}
if showTime == 0 {} else{
Timer.scheduledTimer(timeInterval: TimeInterval(showTime), target: self, selector: #selector(removeTinyBanner), userInfo: nil, repeats: false)
}
}
//MARK: - show permanent tiny banner
open class func showTinyBanner(message:String,backgroundColor:UIColor,textColor:UIColor){
showTinyBanner(message: message, backgroundColor: backgroundColor, textColor: textColor, showTime: 0)
}
//MARK:- Remove views
@objc open class func removeStatusView(){
UIView.animate(withDuration: 0.3, animations: {
mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
}) { (true) in
mainInstance.statusBarView.window?.windowLevel = UIWindowLevelStatusBar-1
}
}
@objc private class func removeBarView(){
mainInstance.SABarViewTimer.invalidate()
UIView.animate(withDuration: 0.3) {
mainInstance.SABarBgView.layer.shadowOpacity = 0.0
mainInstance.SABarBgView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
mainInstance.SABarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
}
}
@objc public class func removeTinyBanner(){
UIView.animate(withDuration: 0.3) {
if mainInstance.isNavbarPresent{
mainInstance.statusBarView.frame = CGRect(x: 0, y:44+UIApplication.shared.statusBarFrame.height, width: mainInstance.currentWindow().frame.width, height: 0)
}else{
mainInstance.statusBarView.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
mainInstance.statusBarView.window?.windowLevel = UIWindowLevelStatusBar-1
}
mainInstance.statusBarLabel.frame = CGRect(x: 0, y:0, width: mainInstance.currentWindow().frame.width, height: 0)
}
}
private class func dropShadow(view:UIView,scale:Bool) {
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.darkText.cgColor
view.layer.shadowOpacity = 0.5
view.layer.shadowOffset = CGSize(width: -1, height: 1)
view.layer.shadowRadius = 1
view.layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath
view.layer.shouldRasterize = true
view.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
| a2d9f484fa343a5ad1a0e3005fadc860 | 42.811075 | 189 | 0.657546 | false | false | false | false |
russbishop/swift | refs/heads/master | test/SILGen/local_recursion.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | FileCheck %s
// CHECK-LABEL: sil hidden @_TF15local_recursion15local_recursionFTSi1ySi_T_ : $@convention(thin) (Int, Int) -> () {
// CHECK: bb0([[X:%0]] : $Int, [[Y:%1]] : $Int):
func local_recursion(_ x: Int, y: Int) {
func self_recursive(_ a: Int) {
self_recursive(x + a)
}
// Invoke local functions by passing all their captures.
// CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE:@_TFF15local_recursion15local_recursionFTSi1ySi_T_L_14self_recursivefSiT_]]
// CHECK: apply [[SELF_RECURSIVE_REF]]([[X]], [[X]])
self_recursive(x)
// CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE]]
// CHECK: [[CLOSURE:%.*]] = partial_apply [[SELF_RECURSIVE_REF]]([[X]])
let sr = self_recursive
// CHECK: apply [[CLOSURE]]([[Y]])
sr(y)
func mutually_recursive_1(_ a: Int) {
mutually_recursive_2(x + a)
}
func mutually_recursive_2(_ b: Int) {
mutually_recursive_1(y + b)
}
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1:@_TFF15local_recursion15local_recursionFTSi1ySi_T_L_20mutually_recursive_1fSiT_]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]([[X]], [[Y]], [[X]])
mutually_recursive_1(x)
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]]
_ = mutually_recursive_1
func transitive_capture_1(_ a: Int) -> Int {
return x + a
}
func transitive_capture_2(_ b: Int) -> Int {
return transitive_capture_1(y + b)
}
// CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE:@_TFF15local_recursion15local_recursionFTSi1ySi_T_L_20transitive_capture_2fSiSi]]
// CHECK: apply [[TRANS_CAPTURE_REF]]([[X]], [[X]], [[Y]])
transitive_capture_2(x)
// CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE]]
// CHECK: [[CLOSURE:%.*]] = partial_apply [[TRANS_CAPTURE_REF]]([[X]], [[Y]])
let tc = transitive_capture_2
// CHECK: apply [[CLOSURE]]([[X]])
tc(x)
// CHECK: [[CLOSURE_REF:%.*]] = function_ref @_TFF15local_recursion15local_recursionFTSi1ySi_T_U_FSiT_
// CHECK: apply [[CLOSURE_REF]]([[X]], [[X]], [[Y]])
let _: Void = {
self_recursive($0)
transitive_capture_2($0)
}(x)
// CHECK: [[CLOSURE_REF:%.*]] = function_ref @_TFF15local_recursion15local_recursionFTSi1ySi_T_U0_FSiT_
// CHECK: [[CLOSURE:%.*]] = partial_apply [[CLOSURE_REF]]([[X]], [[Y]])
// CHECK: apply [[CLOSURE]]([[X]])
let f: (Int) -> () = {
self_recursive($0)
transitive_capture_2($0)
}
f(x)
}
// CHECK: sil shared [[SELF_RECURSIVE]]
// CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int):
// CHECK: [[SELF_REF:%.*]] = function_ref [[SELF_RECURSIVE]]
// CHECK: apply [[SELF_REF]]({{.*}}, [[X]])
// CHECK: sil shared [[MUTUALLY_RECURSIVE_1]]
// CHECK: bb0([[A:%0]] : $Int, [[Y:%1]] : $Int, [[X:%2]] : $Int):
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_2:@_TFF15local_recursion15local_recursionFTSi1ySi_T_L_20mutually_recursive_2fSiT_]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[X]], [[Y]])
// CHECK: sil shared [[MUTUALLY_RECURSIVE_2]]
// CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int):
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[Y]], [[X]])
// CHECK: sil shared [[TRANS_CAPTURE_1:@_TFF15local_recursion15local_recursionFTSi1ySi_T_L_20transitive_capture_1fSiSi]]
// CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int):
// CHECK: sil shared [[TRANS_CAPTURE]]
// CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int):
// CHECK: [[TRANS_CAPTURE_1_REF:%.*]] = function_ref [[TRANS_CAPTURE_1]]
// CHECK: apply [[TRANS_CAPTURE_1_REF]]({{.*}}, [[X]])
func plus<T>(_ x: T, _ y: T) -> T { return x }
func toggle<T, U>(_ x: T, _ y: U) -> U { return y }
func generic_local_recursion<T, U>(_ x: T, y: U) {
func self_recursive(_ a: T) {
self_recursive(plus(x, a))
}
self_recursive(x)
_ = self_recursive
func transitive_capture_1(_ a: T) -> U {
return toggle(a, y)
}
func transitive_capture_2(_ b: U) -> U {
return transitive_capture_1(toggle(b, x))
}
transitive_capture_2(y)
_ = transitive_capture_2
func no_captures() {}
no_captures()
_ = no_captures
func transitive_no_captures() {
no_captures()
}
transitive_no_captures()
_ = transitive_no_captures
}
func local_properties(_ x: Int, y: Int) -> Int {
var self_recursive: Int {
return x + self_recursive
}
var transitive_capture_1: Int {
return x
}
var transitive_capture_2: Int {
return transitive_capture_1 + y
}
func transitive_capture_fn() -> Int {
return transitive_capture_2
}
return self_recursive + transitive_capture_fn()
}
| 6d4c7a733bb3e8e52348325a38ce5fe5 | 32.503497 | 162 | 0.600083 | false | false | false | false |
pawanpoudel/CompositeValidation | refs/heads/master | CompositeValidationTests/Validators/PhoneNumberLengthValidatorSpec.swift | mit | 1 | import Quick
import Nimble
class PhoneNumberLengthValidatorSpec: QuickSpec {
override func spec() {
var validator: PhoneNumberLengthValidator!
var phoneNumber: String!
var error: NSError?
var isPhoneNumberValid: Bool!
beforeEach {
validator = PhoneNumberLengthValidator()
}
afterEach {
error = nil
}
context("when phone number is greater than or equal to 10 characters, but less than or equal to 20 characters") {
beforeEach {
phoneNumber = "1234512345"
isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error)
}
it("it is valid") {
expect(isPhoneNumberValid).to(beTrue())
}
it("error should be nil") {
expect(error).to(beNil())
}
}
context("when phone number is less than 10 characters") {
beforeEach {
phoneNumber = "123456789"
isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error)
}
it("it is invalid") {
expect(isPhoneNumberValid).to(beFalse())
}
it("correct error domain is set") {
expect(error?.domain).to(equal(PhoneNumberValidatorErrorDomain))
}
it("correct error code is set") {
expect(error?.code).to(equal(PhoneNumberValidatorErrorCode.InvalidLength.rawValue))
}
}
context("when phone number is greater than 20 characters") {
beforeEach {
phoneNumber = "123451234512345123451"
isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error)
}
it("it is invalid") {
expect(isPhoneNumberValid).to(beFalse())
}
it("correct error domain is set") {
expect(error?.domain).to(equal(PhoneNumberValidatorErrorDomain))
}
it("correct error code is set") {
expect(error?.code).to(equal(PhoneNumberValidatorErrorCode.InvalidLength.rawValue))
}
}
}
}
| fc40472990e74f8c1b42e7926abba263 | 31.589041 | 121 | 0.516604 | false | false | false | false |
qvacua/vimr | refs/heads/master | Workspace/Sources/Workspace/WorkspaceToolButton.swift | mit | 1 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
import Commons
public final class WorkspaceToolButton: NSView, NSDraggingSource {
private static let titlePadding = CGSize(width: 8, height: 2)
private static let dummyButton = WorkspaceToolButton(title: "Dummy")
private var isHighlighted = false
private let title: NSMutableAttributedString
private var trackingArea = NSTrackingArea()
@available(*, unavailable)
required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") }
static let toolUti = "com.qvacua.vimr.tool"
static func == (left: WorkspaceToolButton, right: WorkspaceToolButton) -> Bool {
guard let leftTool = left.tool, let rightTool = right.tool else {
return false
}
return leftTool == rightTool
}
var location = WorkspaceBarLocation.top
var isSelected: Bool {
self.tool?.isSelected ?? false
}
var theme: Workspace.Theme {
self.tool?.theme ?? Workspace.Theme.default
}
weak var tool: WorkspaceTool?
static func dimension() -> CGFloat {
self.dummyButton.intrinsicContentSize.height
}
static func size(forLocation loc: WorkspaceBarLocation) -> CGSize {
switch loc {
case .top, .bottom:
return self.dummyButton.intrinsicContentSize
case .right, .left:
return CGSize(
width: self.dummyButton.intrinsicContentSize.height,
height: self.dummyButton.intrinsicContentSize.width
)
}
}
init(title: String) {
self.title = NSMutableAttributedString(string: title, attributes: [
NSAttributedString.Key.font: NSFont.systemFont(ofSize: 11),
])
super.init(frame: .zero)
self.configureForAutoLayout()
self.title.addAttribute(
NSAttributedString.Key.foregroundColor,
value: self.theme.foreground,
range: NSRange(location: 0, length: self.title.length)
)
self.wantsLayer = true
}
func repaint() {
if self.isHighlighted {
self.highlight()
} else {
self.dehighlight()
}
self.title.addAttribute(
NSAttributedString.Key.foregroundColor,
value: self.theme.foreground,
range: NSRange(location: 0, length: self.title.length)
)
self.needsDisplay = true
}
func highlight() {
self.isHighlighted = true
self.layer?.backgroundColor = self.theme.barButtonHighlight.cgColor
}
func dehighlight() {
self.isHighlighted = false
self.layer?.backgroundColor = self.theme.barButtonBackground.cgColor
}
}
// MARK: - NSView
public extension WorkspaceToolButton {
override var intrinsicContentSize: NSSize {
let titleSize = self.title.size()
let padding = WorkspaceToolButton.titlePadding
switch self.location {
case .top, .bottom:
return CGSize(
width: titleSize.width + 2 * padding.width,
height: titleSize.height + 2 * padding.height
)
case .right, .left:
return CGSize(
width: titleSize.height + 2 * padding.height,
height: titleSize.width + 2 * padding.width
)
}
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let padding = WorkspaceToolButton.titlePadding
switch self.location {
case .top, .bottom:
self.title.draw(at: CGPoint(x: padding.width, y: padding.height))
case .right:
self.title.draw(
at: CGPoint(x: padding.height, y: self.bounds.height - padding.width),
angle: -(.pi / 2)
)
case .left:
self.title.draw(
at: CGPoint(x: self.bounds.width - padding.height, y: padding.width),
angle: .pi / 2
)
}
}
override func updateTrackingAreas() {
self.removeTrackingArea(self.trackingArea)
self.trackingArea = NSTrackingArea(
rect: self.bounds,
options: [.mouseEnteredAndExited, .activeInActiveApp],
owner: self,
userInfo: nil
)
self.addTrackingArea(self.trackingArea)
super.updateTrackingAreas()
}
override func mouseDown(with event: NSEvent) {
guard let nextEvent = self.window!.nextEvent(matching: [.leftMouseUp, .leftMouseDragged]) else {
return
}
switch nextEvent.type {
case .leftMouseUp:
self.tool?.toggle()
return
case .leftMouseDragged:
let pasteboardItem = NSPasteboardItem()
pasteboardItem.setString(
self.tool!.uuid,
forType: NSPasteboard.PasteboardType(WorkspaceToolButton.toolUti)
)
let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem)
draggingItem.setDraggingFrame(self.bounds, contents: self.snapshot())
self.beginDraggingSession(with: [draggingItem], event: event, source: self)
return
default:
return
}
}
override func mouseEntered(with _: NSEvent) {
if self.isSelected {
return
}
self.highlight()
}
override func mouseExited(with _: NSEvent) {
if self.isSelected {
return
}
self.dehighlight()
}
// Modified version of snapshot() from https://www.raywenderlich.com/136272/drag-and-drop-tutorial-for-macos
private func snapshot() -> NSImage {
let pdfData = self.dataWithPDF(inside: self.bounds)
guard let image = NSImage(data: pdfData) else {
return NSImage()
}
let result = NSImage()
let rect = CGRect(origin: .zero, size: image.size)
result.size = rect.size
result.lockFocus()
self.theme.barButtonHighlight.set()
rect.fill()
image.draw(in: rect)
result.unlockFocus()
return result
}
}
// MARK: - NSDraggingSource
public extension WorkspaceToolButton {
@objc(draggingSession: sourceOperationMaskForDraggingContext:)
func draggingSession(_: NSDraggingSession,
sourceOperationMaskFor _: NSDraggingContext) -> NSDragOperation
{
.move
}
@objc(draggingSession: endedAtPoint:operation:)
func draggingSession(
_: NSDraggingSession,
endedAt screenPoint: NSPoint,
operation _: NSDragOperation
) {
guard let pointInWindow = self.window?
.convertFromScreen(CGRect(origin: screenPoint, size: .zero))
else {
return
}
let pointInView = self.convert(pointInWindow, from: nil)
// Sometimes if the drag ends, the button does not get dehighlighted.
if !self.frame.contains(pointInView), !(self.tool?.isSelected ?? false) {
self.dehighlight()
}
}
}
| 4a4152c09201ca22c546acc742e263e0 | 24.456 | 110 | 0.670333 | false | false | false | false |
BalestraPatrick/Tweetometer | refs/heads/develop | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitTodayExample/TodayViewController.swift | apache-2.0 | 4 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import NotificationCenter
import UIKit
@available(iOSApplicationExtension 10.0, *)
final class TodayViewController: UIViewController, NCWidgetProviding, ListAdapterDataSource {
lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self)
}()
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
let data = "Maecenas faucibus mollis interdum. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.".components(separatedBy: " ")
override func viewDidLoad() {
super.viewDidLoad()
adapter.collectionView = collectionView
adapter.dataSource = self
view.addSubview(collectionView)
// Enables the 'Show More' button in the widget interface
extensionContext?.widgetLargestAvailableDisplayMode = .expanded
}
override func loadView() {
view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 110))
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
// MARK: NCWidgetProviding
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
preferredContentSize = maxSize
}
// MARK: ListAdapterDataSource
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return data as [ListDiffable]
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
return LabelSectionController()
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
return nil
}
}
| b711959fbb79feef123b17fb51f686df | 34.550725 | 177 | 0.731349 | false | false | false | false |
OlenaPianykh/Garage48KAPU | refs/heads/master | KAPU/LoginVC.swift | mit | 1 | //
// ViewController.swift
// KAPU
//
// Created by Vasyl Khmil on 3/4/17.
// Copyright © 2017 Vasyl Khmil. All rights reserved.
//
import UIKit
import FirebaseCore
import FirebaseAuth
import FirebaseDatabase
import FirebaseMessaging
class LoginVC: UIViewController {
var databaseRef: FIRDatabaseReference!
@IBOutlet private weak var emailField: UITextField!
@IBOutlet private weak var firstNameField: UITextField!
@IBOutlet private weak var passwordField: UITextField!
var loader: KapuLoader?
override func viewDidLoad() {
self.databaseRef = FIRDatabase.database().reference()
self.loader = KapuLoader()
}
@IBAction private func signUpPressed() {
self.signUp()
}
private func signUp() {
guard
let email = self.emailField.text,
let password = self.passwordField.text,
let firstname = self.firstNameField.text else {
return
}
FIRAuth.auth()?.createUser(withEmail: email, password: password) {
(user, error) in
guard let userId = user?.uid else {
print("\(error)")
return
}
if let user = user {
let changeRequest = user.profileChangeRequest()
changeRequest.displayName = firstname
changeRequest.commitChanges { error in
if error != nil {
print("An error occured.")
} else {
print("name saved")
}
}
}
PushManager.shared.subscribeToAllFeeds()
let usersTable = FIRDatabase.database().reference().child("users")
usersTable.child(userId).setValue(["email" : email, "first_name" : firstname])
}
}
@IBAction private func logInPressed() {
self.login()
}
private func login() {
if let providerData = FIRAuth.auth()?.currentUser?.providerData {
print("user is signed in")
} else {
FIRAuth.auth()?.createUser(withEmail: "[email protected]", password: "test123") { (user, error) in
if error == nil {
print("You have successfully logged in")
PushManager.shared.subscribeToAllFeeds()
FIRMessaging.messaging().subscribe(toTopic: "topics/app")
/* let kapu = Kapu(title: "Peace On Earth A Wonderful Wish But No Way?",
body: "The following article covers a topic that has recently moved to center stage–at least it seems that way. If you’ve been thinking you need to know more about unconditional love, here’s your",
categoryName: "Transportation",
creationDate: "05 Jan 2017, 10:30PM",
creatorName: "Annie Roger")
if let loader = self.loader {
loader.addNew(kapu: kapu)
}*/
} else {
PushManager.shared.subscribeToAllFeeds()
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
}
| 401a31e97906a6311623b6e6220ec0d1 | 32.857143 | 229 | 0.523734 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/UI/Search/SearchViewController.swift | mit | 1 | //
// SearchViewController.swift
// Accented
//
// Created by Tiangong You on 8/27/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import KMPlaceholderTextView
class SearchViewController: UIViewController, Composer, UITextViewDelegate {
@IBOutlet weak var composerView: UIView!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var searchButton: UIButton!
@IBOutlet weak var textView: KMPlaceholderTextView!
@IBOutlet weak var titleView: UIView!
@IBOutlet weak var composerHeightConstraint: NSLayoutConstraint!
private let cornerRadius : CGFloat = 20
private let statusViewPaddingTop : CGFloat = 20
private let titleBarMaskLayer = CAShapeLayer()
private let titleBarRectCorner = UIRectCorner([.topLeft, .topRight])
private let transitionController = ComposerPresentationController()
private var currentStatusView : UIView?
override var nibName: String? {
return "SearchViewController"
}
init() {
super.init(nibName: "SearchViewController", bundle: nil)
modalPresentationStyle = .custom
transitioningDelegate = transitionController
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
composerView.backgroundColor = ThemeManager.sharedInstance.currentTheme.composerBackground
textView.placeholderColor = ThemeManager.sharedInstance.currentTheme.composerPlaceholderTextColor
textView.textColor = ThemeManager.sharedInstance.currentTheme.composerTextColor
composerView.alpha = 0
composerView.layer.cornerRadius = cornerRadius
textView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.becomeFirstResponder()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateTitlebarCorners()
}
private func updateTitlebarCorners() {
let path = UIBezierPath(roundedRect: titleView.bounds,
byRoundingCorners: titleBarRectCorner,
cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
titleBarMaskLayer.path = path.cgPath
titleView.layer.mask = titleBarMaskLayer
}
@IBAction func backButtonDidTap(_ sender: Any) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
@IBAction func searchButtonDidTap(_ sender: Any) {
dismiss(animated: false) {
NavigationService.sharedInstance.navigateToSearchResultPage(keyword: self.textView.text)
}
}
// MARK: - EntranceAnimation
func entranceAnimationWillBegin() {
composerView.transform = CGAffineTransform(translationX: 0, y: -composerHeightConstraint.constant)
}
func performEntranceAnimation() {
composerView.transform = CGAffineTransform.identity
composerView.alpha = 1
}
func entranceAnimationDidFinish() {
// Ignore
}
// MARK: - ExitAnimation
func exitAnimationWillBegin() {
composerView.resignFirstResponder()
}
func performExitAnimation() {
self.view.transform = CGAffineTransform(translationX: 0, y: -composerHeightConstraint.constant)
self.view.alpha = 0
}
func exitAnimationDidFinish() {
// Ignore
}
// MARK: - UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
searchButton.isEnabled = (textView.text.lengthOfBytes(using: String.Encoding.utf8) != 0)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
if textView.text.lengthOfBytes(using: String.Encoding.utf8) != 0 {
textView.resignFirstResponder()
dismiss(animated: false) {
NavigationService.sharedInstance.navigateToSearchResultPage(keyword: self.textView.text)
}
}
return false
}
return true
}
}
| 6022cb042dcfbff3c382524c0b62b91e | 32.192308 | 116 | 0.661414 | false | false | false | false |
brentdax/swift | refs/heads/master | test/SILGen/types.swift | apache-2.0 | 1 |
// RUN: %target-swift-emit-silgen -module-name types -parse-as-library -enable-sil-ownership %s | %FileCheck %s
class C {
var member: Int = 0
// Methods have method calling convention.
// CHECK-LABEL: sil hidden @$s5types1CC3foo1xySi_tF : $@convention(method) (Int, @guaranteed C) -> () {
func foo(x x: Int) {
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[THIS:%[0-9]+]] : @guaranteed $C):
member = x
// CHECK-NOT: copy_value
// CHECK: [[FN:%[0-9]+]] = class_method %1 : $C, #C.member!setter.1
// CHECK: apply [[FN]](%0, %1) : $@convention(method) (Int, @guaranteed C) -> ()
// CHECK-NOT: destroy_value
}
// CHECK: } // end sil function '$s5types1CC3foo1xySi_tF'
}
struct S {
var member: Int
// CHECK-LABEL: sil hidden @{{.*}}1SV3foo{{.*}} : $@convention(method) (Int, @inout S) -> ()
mutating
func foo(x x: Int) {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[THIS:%[0-9]+]] : @trivial $*S):
member = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[THIS]] : $*S
// CHECK: [[MEMBER:%[0-9]+]] = struct_element_addr [[WRITE]] : $*S, #S.member
// CHECK: assign [[X]] to [[MEMBER]] : $*Int
}
class SC {
// CHECK-LABEL: sil hidden @$s5types1SV2SCC3bar{{.*}}
func bar() {}
}
}
func f() {
class FC {
func zim() {}
}
}
func g(b b : Bool) {
if (b) {
class FC {
func zim() {}
}
} else {
class FC {
func zim() {}
}
}
}
struct ReferencedFromFunctionStruct {
let f: (ReferencedFromFunctionStruct) -> () = {x in ()}
let g: (ReferencedFromFunctionEnum) -> () = {x in ()}
}
enum ReferencedFromFunctionEnum {
case f((ReferencedFromFunctionEnum) -> ())
case g((ReferencedFromFunctionStruct) -> ())
}
// CHECK-LABEL: sil hidden @$s5types34referencedFromFunctionStructFieldsyyAA010ReferencedcdE0Vc_yAA0gcD4EnumOctADF{{.*}} : $@convention(thin) (@guaranteed ReferencedFromFunctionStruct) -> (@owned @callee_guaranteed (@guaranteed ReferencedFromFunctionStruct) -> (), @owned @callee_guaranteed (@guaranteed ReferencedFromFunctionEnum) -> ()) {
// CHECK: bb0([[X:%.*]] : @guaranteed $ReferencedFromFunctionStruct):
// CHECK: [[F:%.*]] = struct_extract [[X]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.f
// CHECK: [[COPIED_F:%.*]] = copy_value [[F]] : $@callee_guaranteed (@guaranteed ReferencedFromFunctionStruct) -> ()
// CHECK: [[G:%.*]] = struct_extract [[X]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.g
// CHECK: [[COPIED_G:%.*]] = copy_value [[G]] : $@callee_guaranteed (@guaranteed ReferencedFromFunctionEnum) -> ()
// CHECK: [[RESULT:%.*]] = tuple ([[COPIED_F]] : {{.*}}, [[COPIED_G]] : {{.*}})
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$s5types34referencedFromFunctionStructFieldsyyAA010ReferencedcdE0Vc_yAA0gcD4EnumOctADF'
func referencedFromFunctionStructFields(_ x: ReferencedFromFunctionStruct)
-> ((ReferencedFromFunctionStruct) -> (), (ReferencedFromFunctionEnum) -> ()) {
return (x.f, x.g)
}
// CHECK-LABEL: sil hidden @$s5types32referencedFromFunctionEnumFieldsyyAA010ReferencedcdE0OcSg_yAA0gcD6StructVcSgtADF
// CHECK: bb{{[0-9]+}}([[F:%.*]] : @owned $@callee_guaranteed (@guaranteed ReferencedFromFunctionEnum) -> ()):
// CHECK: bb{{[0-9]+}}([[G:%.*]] : @owned $@callee_guaranteed (@guaranteed ReferencedFromFunctionStruct) -> ()):
func referencedFromFunctionEnumFields(_ x: ReferencedFromFunctionEnum)
-> (
((ReferencedFromFunctionEnum) -> ())?,
((ReferencedFromFunctionStruct) -> ())?
) {
switch x {
case .f(let f):
return (f, nil)
case .g(let g):
return (nil, g)
}
}
// CHECK-LABEL: sil private @$s5types1fyyF2FCL_C3zimyyF
// CHECK-LABEL: sil private @$s5types1g1bySb_tF2FCL_C3zimyyF
// CHECK-LABEL: sil private @$s5types1g1bySb_tF2FCL0_C3zimyyF
| 19c1a241df36317876661e8af2e7db49 | 37.942857 | 340 | 0.620201 | false | false | false | false |
Hunter-Li-EF/HLAlbumPickerController | refs/heads/master | Example/Tests/Tests.swift | mit | 1 | // https://github.com/Quick/Quick
import Quick
import Nimble
import HLAlbumPickerController
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| 0ef6f4ab95ea4ef79acb987b36416292 | 22.68 | 63 | 0.370777 | false | false | false | false |
jessesquires/Cartography | refs/heads/master | CartographyTests/EdgeSpec.swift | mit | 1 | import Cartography
import Nimble
import Quick
class EdgeSpec: QuickSpec {
override func spec() {
var superview: View!
var view: View!
beforeEach {
superview = TestView(frame: CGRectMake(0, 0, 400, 400))
view = TestView(frame: CGRectZero)
superview.addSubview(view)
constrain(view) { view in
view.height == 200
view.width == 200
}
}
describe("LayoutProxy.top") {
it("should support relative equalities") {
layout(view) { view in
view.top == view.superview!.top
}
expect(view.frame.minY).to(equal(0))
}
it("should support relative inequalities") {
layout(view) { view in
view.top <= view.superview!.top
view.top >= view.superview!.top
}
expect(view.frame.minY).to(equal(0))
}
it("should support addition") {
layout(view) { view in
view.top == view.superview!.top + 100
}
expect(view.frame.minY).to(equal(100))
}
it("should support subtraction") {
layout(view) { view in
view.top == view.superview!.top - 100
}
expect(view.frame.minY).to(equal(-100))
}
}
describe("LayoutProxy.right") {
it("should support relative equalities") {
layout(view) { view in
view.right == view.superview!.right
}
expect(view.frame.maxX).to(equal(400))
}
it("should support relative inequalities") {
layout(view) { view in
view.right <= view.superview!.right
view.right >= view.superview!.right
}
expect(view.frame.maxX).to(equal(400))
}
it("should support addition") {
layout(view) { view in
view.right == view.superview!.right + 100
}
expect(view.frame.maxX).to(equal(500))
}
it("should support subtraction") {
layout(view) { view in
view.right == view.superview!.right - 100
}
expect(view.frame.maxX).to(equal(300))
}
}
describe("LayoutProxy.bottom") {
it("should support relative equalities") {
layout(view) { view in
view.bottom == view.superview!.bottom
}
expect(view.frame.maxY).to(equal(400))
}
it("should support relative inequalities") {
layout(view) { view in
view.bottom <= view.superview!.bottom
view.bottom >= view.superview!.bottom
}
expect(view.frame.maxY).to(equal(400))
}
it("should support addition") {
layout(view) { view in
view.bottom == view.superview!.bottom + 100
}
expect(view.frame.maxY).to(equal(500))
}
it("should support subtraction") {
layout(view) { view in
view.bottom == view.superview!.bottom - 100
}
expect(view.frame.maxY).to(equal(300))
}
}
describe("LayoutProxy.left") {
it("should support relative equalities") {
layout(view) { view in
view.left == view.superview!.left
}
expect(view.frame.minX).to(equal(0))
}
it("should support relative inequalities") {
layout(view) { view in
view.left <= view.superview!.left
view.left >= view.superview!.left
}
expect(view.frame.minX).to(equal(0))
}
it("should support addition") {
layout(view) { view in
view.left == view.superview!.left + 100
}
expect(view.frame.minX).to(equal(100))
}
it("should support subtraction") {
layout(view) { view in
view.left == view.superview!.left - 100
}
expect(view.frame.minX).to(equal(-100))
}
}
describe("LayoutProxy.centerX") {
it("should support relative equalities") {
layout(view) { view in
view.centerX == view.superview!.centerX
}
expect(view.frame.midX).to(equal(200))
}
it("should support relative inequalities") {
layout(view) { view in
view.centerX <= view.superview!.centerX
view.centerX >= view.superview!.centerX
}
expect(view.frame.midX).to(equal(200))
}
it("should support addition") {
layout(view) { view in
view.centerX == view.superview!.centerX + 100
}
expect(view.frame.midX).to(equal(300))
}
it("should support subtraction") {
layout(view) { view in
view.centerX == view.superview!.centerX - 100
}
expect(view.frame.midX).to(equal(100))
}
it("should support multiplication") {
layout(view) { view in
view.centerX == view.superview!.centerX * 2
}
expect(view.frame.midX).to(equal(400))
}
it("should support division") {
layout(view) { view in
view.centerX == view.superview!.centerX / 2
}
expect(view.frame.midX).to(equal(100))
}
}
describe("LayoutProxy.centerX") {
it("should support relative equalities") {
layout(view) { view in
view.centerX == view.superview!.centerX
}
expect(view.frame.midY).to(equal(200))
}
it("should support relative inequalities") {
layout(view) { view in
view.centerX <= view.superview!.centerX
view.centerX >= view.superview!.centerX
}
expect(view.frame.midY).to(equal(200))
}
it("should support addition") {
layout(view) { view in
view.centerX == view.superview!.centerX + 100
}
expect(view.frame.midY).to(equal(300))
}
it("should support subtraction") {
layout(view) { view in
view.centerX == view.superview!.centerX - 100
}
expect(view.frame.midY).to(equal(100))
}
it("should support multiplication") {
layout(view) { view in
view.centerX == view.superview!.centerX * 2
}
expect(view.frame.midY).to(equal(400))
}
it("should support division") {
layout(view) { view in
view.centerX == view.superview!.centerX / 2
}
expect(view.frame.midY).to(equal(100))
}
}
#if os(iOS)
describe("on iOS only") {
beforeEach {
view.layoutMargins = UIEdgeInsets(top: -10, left: -20, bottom: -30, right: -40)
}
describe("LayoutProxy.topMargin") {
it("should support relative equalities") {
layout(view) { view in
view.topMargin == view.superview!.top
}
expect(view.frame.minY).to(equal(10))
}
}
describe("LayoutProxy.rightMargin") {
it("should support relative equalities") {
layout(view) { view in
view.rightMargin == view.superview!.right
}
expect(view.frame.maxX).to(equal(360))
}
}
describe("LayoutProxy.bottomMargin") {
it("should support relative equalities") {
layout(view) { view in
view.bottomMargin == view.superview!.bottom
}
expect(view.frame.maxY).to(equal(370))
}
}
describe("LayoutProxy.leftMargin") {
it("should support relative equalities") {
layout(view) { view in
view.leftMargin == view.superview!.left
}
expect(view.frame.minX).to(equal(20))
}
}
}
#endif
}
}
| f7eb8af8a815041b958a8d743dd5a0af | 29.01278 | 95 | 0.436129 | false | false | false | false |
Zeitblick/Zeitblick-iOS | refs/heads/master | Zeitblick/StartViewController.swift | gpl-3.0 | 1 | //
// StartViewController.swift
// Zeitblick
//
// Created by Bastian Clausdorff on 29.10.16.
// Copyright © 2016 Epic Selfie. All rights reserved.
//
import UIKit
import Async
import Alamofire
import PromiseKit
import SwiftyJSON
enum StartError: Error {
case invalidData
}
class StartViewController: UIViewController {
typealias Me = StartViewController
private static let hasSelfieTopConstant: CGFloat = 42
@IBOutlet weak var photoButton: DesignableButton!
@IBOutlet weak var selfieImageView: DesignableImageView!
var logoHasSelfieConstraint: NSLayoutConstraint!
@IBOutlet var logoNoSelfieConstraint: NSLayoutConstraint!
@IBOutlet weak var logo: UIImageView!
@IBOutlet weak var logoSubtitle: UILabel!
var resultImage: UIImage?
var metadata: ImageMetadata?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
logoHasSelfieConstraint = logo.topAnchor.constraint(equalTo: view.topAnchor)
logoHasSelfieConstraint.constant = Me.hasSelfieTopConstant
resetController()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pickPhoto(_ sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
Alerts.photo(viewController: self,
takePhotoAction: { [weak self] in
guard let strongSelf = self else {
return
}
imagePicker.sourceType = .camera
imagePicker.cameraDevice = .front
strongSelf.present(imagePicker, animated: true) {
UIApplication.shared.setStatusBarHidden(true, with: .fade)
}
},
choosePhotoAction: { [weak self] in
guard let strongSelf = self else {
return
}
imagePicker.sourceType = .photoLibrary
strongSelf.present(imagePicker, animated: true, completion: nil)
})
}
func resetController() {
selfieImageView.image = nil
selfieImageView.isHidden = true
photoButton.isHidden = false
logoHasSelfieConstraint.isActive = false
logoNoSelfieConstraint.isActive = true
logoSubtitle.isHidden = false
}
}
extension StartViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("selected photo")
dismiss(animated: true) { [weak self] in
UIApplication.shared.setStatusBarHidden(false, with: .fade)
self?.view.showLoading()
}
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
return
}
// Change UI
selfieImageView.image = image
selfieImageView.isHidden = false
photoButton.isHidden = true
logoNoSelfieConstraint.isActive = false
logoHasSelfieConstraint.isActive = true
logoSubtitle.isHidden = true
let q = DispatchQueue.global()
// Find match
firstly {
return try GoogleVision().analyse(image: image)
}.then { visionResponseJson -> Promise<ImageMetadata> in
dump(visionResponseJson)
return try ZeitblickBackend().findSimilarEmotion(json: visionResponseJson)
}.then { [weak self] metadata -> Promise<UIImage> in
self?.metadata = metadata
return try GoogleDatastore().getImage(inventoryNumber: metadata.inventoryNumber)
}.then { [weak self] image -> Void in
print("got image")
self?.resultImage = image
guard let result = self?.resultImage, let metadata = self?.metadata, let selfie = self?.selfieImageView.image else {
throw StartError.invalidData
}
let controller = ResultController(resultImage: result , metadata: metadata, selfieImage: selfie, errorHappened: false)
self?.present(controller, animated: false) {
self?.resetController()
}
}.always(on: q) { [weak self] in
self?.view.hideLoading()
}.catch { [weak self] error in
print(error)
let errorImage = R.image.errorJpg()
let controller = ResultController(resultImage: errorImage!, errorHappened: true)
self?.present(controller, animated: false) {
self?.resetController()
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true) {
UIApplication.shared.setStatusBarHidden(false, with: .fade)
}
}
}
| aedba5599a5a10a4323c5124a183a98c | 32.472973 | 130 | 0.635042 | false | false | false | false |
brightec/CustomCollectionViewLayout | refs/heads/master | CustomCollectionLayout/CollectionViewController.swift | mit | 1 | // Copyright 2017 Brightec
//
// 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 CollectionViewController: UIViewController {
let contentCellIdentifier = "ContentCellIdentifier"
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UINib(nibName: "ContentCollectionViewCell", bundle: nil),
forCellWithReuseIdentifier: contentCellIdentifier)
}
}
// MARK: - UICollectionViewDataSource
extension CollectionViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 50
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// swiftlint:disable force_cast
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellIdentifier,
for: indexPath) as! ContentCollectionViewCell
if indexPath.section % 2 != 0 {
cell.backgroundColor = UIColor(white: 242/255.0, alpha: 1.0)
} else {
cell.backgroundColor = UIColor.white
}
if indexPath.section == 0 {
if indexPath.row == 0 {
cell.contentLabel.text = "Date"
} else {
cell.contentLabel.text = "Section"
}
} else {
if indexPath.row == 0 {
cell.contentLabel.text = String(indexPath.section)
} else {
cell.contentLabel.text = "Content"
}
}
return cell
}
}
// MARK: - UICollectionViewDelegate
extension CollectionViewController: UICollectionViewDelegate {
}
| 9e6a8a88c22630878c2f649a3526c394 | 31.184211 | 121 | 0.653312 | false | false | false | false |
wenluma/swift | refs/heads/master | test/IRGen/generic_vtable.swift | mit | 1 | // RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK
// REQUIRES: CPU=x86_64
public class Base {
public func m1() {}
public func m2() {}
}
public class Derived<T> : Base {
public override func m2() {}
public func m3() {}
}
// CHECK-LABEL: @_T014generic_vtable4BaseCMn = {{(protected )?}}constant
// -- flags: has vtable
// CHECK-SAME: i32 4,
// -- vtable offset
// CHECK-SAME: i32 10,
// -- vtable size
// CHECK-SAME: i32 3
// --
// CHECK-SAME: section "{{.*}}", align 8
// CHECK-LABEL: @_T014generic_vtable7DerivedCMn = {{(protected )?}}constant
// -- flags: has vtable
// CHECK-SAME: i32 4,
// -- vtable offset
// CHECK-SAME: i32 14,
// -- vtable size
// CHECK-SAME: i32 1
// --
// CHECK-SAME: section "{{.*}}", align 8
// CHECK-LABEL: define private %swift.type* @create_generic_metadata_Derived(%swift.type_pattern*, i8**)
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata({{.*}})
// CHECK: [[METADATA2:%.*]] = call %swift.type* @swift_initClassMetadata_UniversalStrategy({{.*}})
// CHECK: [[WORDS:%.*]] = bitcast %swift.type* [[METADATA2]] to i8**
// CHECK: [[VTABLE0:%.*]] = getelementptr inbounds i8*, i8** [[WORDS]], i32 11
// CHECK: store i8* bitcast (void (%T14generic_vtable7DerivedC*)* @_T014generic_vtable7DerivedC2m2yyF to i8*), i8** [[VTABLE0]], align 8
// CHECK: [[VTABLE1:%.*]] = getelementptr inbounds i8*, i8** [[WORDS]], i32 12
// CHECK: store i8* bitcast (%T14generic_vtable7DerivedC* (%T14generic_vtable7DerivedC*)* @_T014generic_vtable7DerivedCACyxGycfc to i8*), i8** [[VTABLE1]], align 8
// CHECK: ret %swift.type* [[METADATA]]
| 19c6ff4ba84c546e811493d4d8fb1b5d | 36.813953 | 163 | 0.646371 | false | false | false | false |
zxwWei/SWiftWeiBlog | refs/heads/master | XWWeibo/XWWeibo/Classes/Model(模型)/Profile(我)/Controller/XWProfileTableVC.swift | apache-2.0 | 2 | //
// XWProfileTableVC.swift
// XWWeibo
//
// Created by apple on 15/10/26.
// Copyright © 2015年 ZXW. All rights reserved.
//
import UIKit
class XWProfileTableVC: XWcompassVc {
override func viewDidLoad() {
super.viewDidLoad()
}
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 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
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.
}
*/
}
| 7171d55104e7a3f6b7916400c6c3fa48 | 30.67033 | 157 | 0.676266 | false | false | false | false |
JQJoe/RxDemo | refs/heads/develop | Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Observable+BindingTest.swift | apache-2.0 | 7 | //
// Observable+BindingTest.swift
// Tests
//
// Created by Krunoslav Zaher on 4/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import XCTest
import RxSwift
import RxTest
class ObservableBindingTest : RxTest {
}
// multicast
extension ObservableBindingTest {
func testMulticast_Cold_Completed() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(40, 0),
next(90, 1),
next(150, 2),
next(210, 3),
next(240, 4),
next(270, 5),
next(330, 6),
next(340, 7),
completed(390)
])
let res = scheduler.start {
xs.multicast({ PublishSubject<Int>() }) { $0 }
}
XCTAssertEqual(res.events, [
next(210, 3),
next(240, 4),
next(270, 5),
next(330, 6),
next(340, 7),
completed(390)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
}
func testMulticast_Cold_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(40, 0),
next(90, 1),
next(150, 2),
next(210, 3),
next(240, 4),
next(270, 5),
next(330, 6),
next(340, 7),
error(390, testError)
])
let res = scheduler.start {
xs.multicast({ PublishSubject<Int>() }) { $0 }
}
XCTAssertEqual(res.events, [
next(210, 3),
next(240, 4),
next(270, 5),
next(330, 6),
next(340, 7),
error(390, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
}
func testMulticast_Cold_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(40, 0),
next(90, 1),
next(150, 2),
next(210, 3),
next(240, 4),
next(270, 5),
next(330, 6),
next(340, 7),
])
let res = scheduler.start {
xs.multicast({ PublishSubject<Int>() }) { $0 }
}
XCTAssertEqual(res.events, [
next(210, 3),
next(240, 4),
next(270, 5),
next(330, 6),
next(340, 7),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 1000)
])
}
func testMulticast_Cold_Zip() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(40, 0),
next(90, 1),
next(150, 2),
next(210, 3),
next(240, 4),
next(270, 5),
next(330, 6),
next(340, 7),
completed(390)
])
let res = scheduler.start {
xs.multicast({ PublishSubject<Int>() }) { Observable.zip($0, $0) { a, b in a + b } }
}
XCTAssertEqual(res.events, [
next(210, 6),
next(240, 8),
next(270, 10),
next(330, 12),
next(340, 14),
completed(390)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
}
func testMulticast_SubjectSelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(210, 1),
next(240, 2),
completed(300)
])
let res = scheduler.start {
xs.multicast({ () throws -> PublishSubject<Int> in throw testError }) { $0 }
}
XCTAssertEqual(res.events, [
error(200, testError)
])
XCTAssertEqual(xs.subscriptions, [
])
}
func testMulticast_SelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(210, 1),
next(240, 2),
completed(300)
])
let res = scheduler.start {
xs.multicast({ PublishSubject<Int>() }) { _ -> Observable<Int> in throw testError }
}
XCTAssertEqual(res.events, [
error(200, testError)
])
XCTAssertEqual(xs.subscriptions, [
])
}
}
// refCount
extension ObservableBindingTest {
func testRefCount_DeadlockSimple() {
let subject = MySubject<Int>()
var nEvents = 0
let observable = TestConnectableObservable(o: Observable.of(0, 1, 2), s: subject)
let d = observable.subscribe(onNext: { n in
nEvents += 1
})
defer {
d.dispose()
}
observable.connect().dispose()
XCTAssertEqual(nEvents, 3)
}
func testRefCount_DeadlockErrorAfterN() {
let subject = MySubject<Int>()
var nEvents = 0
let observable = TestConnectableObservable(o: Observable.concat([Observable.of(0, 1, 2), Observable.error(testError)]), s: subject)
let d = observable.subscribe(onError: { n in
nEvents += 1
})
defer {
d.dispose()
}
observable.connect().dispose()
XCTAssertEqual(nEvents, 1)
}
func testRefCount_DeadlockErrorImmediatelly() {
let subject = MySubject<Int>()
var nEvents = 0
let observable = TestConnectableObservable(o: Observable.error(testError), s: subject)
let d = observable.subscribe(onError: { n in
nEvents += 1
})
defer {
d.dispose()
}
observable.connect().dispose()
XCTAssertEqual(nEvents, 1)
}
func testRefCount_DeadlockEmpty() {
let subject = MySubject<Int>()
var nEvents = 0
let observable = TestConnectableObservable(o: Observable.empty(), s: subject)
let d = observable.subscribe(onCompleted: {
nEvents += 1
})
defer {
d.dispose()
}
observable.connect().dispose()
XCTAssertEqual(nEvents, 1)
}
func testRefCount_ConnectsOnFirst() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(210, 1),
next(220, 2),
next(230, 3),
next(240, 4),
completed(250)
])
let subject = MySubject<Int>()
let conn = TestConnectableObservable(o: xs.asObservable(), s: subject)
let res = scheduler.start { conn.refCount() }
XCTAssertEqual(res.events, [
next(210, 1),
next(220, 2),
next(230, 3),
next(240, 4),
completed(250)
])
XCTAssertTrue(subject.isDisposed)
}
func testRefCount_NotConnected() {
_ = TestScheduler(initialClock: 0)
var disconnected = false
var count = 0
let xs: Observable<Int> = Observable.deferred {
count += 1
return Observable.create { obs in
return Disposables.create {
disconnected = true
}
}
}
let subject = MySubject<Int>()
let conn = TestConnectableObservable(o: xs, s: subject)
let refd = conn.refCount()
let dis1 = refd.subscribe { _ -> Void in () }
XCTAssertEqual(1, count)
XCTAssertEqual(1, subject.subscribeCount)
XCTAssertFalse(disconnected)
let dis2 = refd.subscribe { _ -> Void in () }
XCTAssertEqual(1, count)
XCTAssertEqual(2, subject.subscribeCount)
XCTAssertFalse(disconnected)
dis1.dispose()
XCTAssertFalse(disconnected)
dis2.dispose()
XCTAssertTrue(disconnected)
disconnected = false
let dis3 = refd.subscribe { _ -> Void in () }
XCTAssertEqual(2, count)
XCTAssertEqual(3, subject.subscribeCount)
XCTAssertFalse(disconnected)
dis3.dispose()
XCTAssertTrue(disconnected)
}
func testRefCount_Error() {
let xs: Observable<Int> = Observable.error(testError)
let res = xs.publish().refCount()
_ = res.subscribe { event in
switch event {
case .next:
XCTAssertTrue(false)
case .error(let error):
XCTAssertErrorEqual(error, testError)
case .completed:
XCTAssertTrue(false)
}
}
_ = res.subscribe { event in
switch event {
case .next:
XCTAssertTrue(false)
case .error(let error):
XCTAssertErrorEqual(error, testError)
case .completed:
XCTAssertTrue(false)
}
}
}
func testRefCount_Publish() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(210, 1),
next(220, 2),
next(230, 3),
next(240, 4),
next(250, 5),
next(260, 6),
next(270, 7),
next(280, 8),
next(290, 9),
completed(300)
])
let res = xs.publish().refCount()
var d1: Disposable!
let o1 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(215) { d1 = res.subscribe(o1) }
scheduler.scheduleAt(235) { d1.dispose() }
var d2: Disposable!
let o2 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(225) { d2 = res.subscribe(o2) }
scheduler.scheduleAt(275) { d2.dispose() }
var d3: Disposable!
let o3 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(255) { d3 = res.subscribe(o3) }
scheduler.scheduleAt(265) { d3.dispose() }
var d4: Disposable!
let o4 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(285) { d4 = res.subscribe(o4) }
scheduler.scheduleAt(320) { d4.dispose() }
scheduler.start()
XCTAssertEqual(o1.events, [
next(220, 2),
next(230, 3)
])
XCTAssertEqual(o2.events, [
next(230, 3),
next(240, 4),
next(250, 5),
next(260, 6),
next(270, 7)
])
XCTAssertEqual(o3.events, [
next(260, 6)
])
XCTAssertEqual(o4.events, [
next(290, 9),
completed(300)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(215, 275),
Subscription(285, 300)
])
}
}
// replay
extension ObservableBindingTest {
func testReplayCount_Basic() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
error(600, testError)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(550) { connection.dispose() }
scheduler.scheduleAt(650) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 5),
next(450, 6),
next(450, 7),
next(520, 11),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 550),
Subscription(650, 800)
])
}
func testReplayCount_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
error(600, testError)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 5),
next(450, 6),
next(450, 7),
next(520, 11),
next(560, 20),
error(600, testError),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 600),
])
}
func testReplayCount_Complete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
completed(600)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 5),
next(450, 6),
next(450, 7),
next(520, 11),
next(560, 20),
completed(600)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 600),
])
}
func testReplayCount_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
completed(600)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replay(3) }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(475) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(550) { connection.dispose() }
scheduler.scheduleAt(650) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 5),
next(450, 6),
next(450, 7),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 550),
Subscription(650, 800),
])
}
func testReplayOneCount_Basic() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
error(600, testError)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(550) { connection.dispose() }
scheduler.scheduleAt(650) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 7),
next(520, 11),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 550),
Subscription(650, 800)
])
}
func testReplayOneCount_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
error(600, testError)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 7),
next(520, 11),
next(560, 20),
error(600, testError),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 600),
])
}
func testReplayOneCount_Complete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
completed(600)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 7),
next(520, 11),
next(560, 20),
completed(600)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 600),
])
}
func testReplayOneCount_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
completed(600)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replay(1) }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(475) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(550) { connection.dispose() }
scheduler.scheduleAt(650) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 7),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 550),
Subscription(650, 800),
])
}
func testReplayAll_Basic() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
error(600, testError)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replayAll() }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(200) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(550) { connection.dispose() }
scheduler.scheduleAt(650) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 3),
next(450, 4),
next(450, 1),
next(450, 8),
next(450, 5),
next(450, 6),
next(450, 7),
next(520, 11),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 400),
Subscription(500, 550),
Subscription(650, 800)
])
}
func testReplayAll_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
error(600, testError)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replayAll() }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 8),
next(450, 5),
next(450, 6),
next(450, 7),
next(520, 11),
next(560, 20),
error(600, testError),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 600),
])
}
func testReplayAll_Complete() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
completed(600)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replayAll() }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(Defaults.disposed) { subscription.dispose() }
scheduler.scheduleAt(300) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 8),
next(450, 5),
next(450, 6),
next(450, 7),
next(520, 11),
next(560, 20),
completed(600)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(300, 400),
Subscription(500, 600),
])
}
func testReplayAll_Dispose() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
completed(600)
])
var ys: ConnectableObservable<Int>! = nil
var subscription: Disposable! = nil
var connection: Disposable! = nil
let res = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.replayAll() }
scheduler.scheduleAt(450, action: { subscription = ys.subscribe(res) })
scheduler.scheduleAt(475) { subscription.dispose() }
scheduler.scheduleAt(250) { connection = ys.connect() }
scheduler.scheduleAt(400) { connection.dispose() }
scheduler.scheduleAt(500) { connection = ys.connect() }
scheduler.scheduleAt(550) { connection.dispose() }
scheduler.scheduleAt(650) { connection = ys.connect() }
scheduler.scheduleAt(800) { connection.dispose() }
scheduler.start()
XCTAssertEqual(res.events, [
next(450, 4),
next(450, 1),
next(450, 8),
next(450, 5),
next(450, 6),
next(450, 7),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(250, 400),
Subscription(500, 550),
Subscription(650, 800),
])
}
}
// shareReplay(1)
extension ObservableBindingTest {
func _testIdenticalBehaviorOfShareReplayOptimizedAndComposed(_ action: @escaping (_ transform: @escaping ((Observable<Int>) -> Observable<Int>)) -> Void) {
action { $0.shareReplay(1) }
action { $0.replay(1).refCount() }
}
func testShareReplay_DeadlockImmediatelly() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
var nEvents = 0
let observable = transform(Observable.of(0, 1, 2))
_ = observable.subscribe(onNext: { n in
nEvents += 1
})
XCTAssertEqual(nEvents, 3)
}
}
func testShareReplay_DeadlockEmpty() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
var nEvents = 0
let observable = transform(Observable.empty())
_ = observable.subscribe(onCompleted: { n in
nEvents += 1
})
XCTAssertEqual(nEvents, 1)
}
}
func testShareReplay_DeadlockError() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
var nEvents = 0
let observable = transform(Observable.error(testError))
_ = observable.subscribe(onError: { _ in
nEvents += 1
})
XCTAssertEqual(nEvents, 1)
}
}
func testShareReplay1_DeadlockErrorAfterN() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
var nEvents = 0
let observable = transform(Observable.concat([Observable.of(0, 1, 2), Observable.error(testError)]))
_ = observable.subscribe(onError: { n in
nEvents += 1
})
XCTAssertEqual(nEvents, 1)
}
}
func testShareReplay1_Basic() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
error(600, testError)
])
var ys: Observable<Int>! = nil
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = transform(xs.asObservable()) }
scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(400) { subscription1.dispose() }
scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(415) { subscription2.dispose() }
scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(455) { subscription1.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
// 1rt batch
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
// 2nd batch
next(440, 13),
next(450, 9)
])
XCTAssertEqual(res2.events, [
next(355, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(335, 415),
Subscription(440, 455)
])
}
}
func testShareReplay1_Error() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
error(365, testError),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
])
var ys: Observable<Int>! = nil
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = transform(xs.asObservable()) }
scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(400) { subscription1.dispose() }
scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(415) { subscription2.dispose() }
scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(455) { subscription1.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
// 1rt batch
next(340, 8),
next(360, 5),
error(365, testError),
// 2nd batch
next(440, 5),
error(440, testError),
])
XCTAssertEqual(res2.events, [
next(355, 8),
next(360, 5),
error(365, testError),
])
// unoptimized version of replay subject will make a subscription and kill it immediatelly
XCTAssertEqual(xs.subscriptions[0], Subscription(335, 365))
XCTAssertTrue(xs.subscriptions.count <= 2)
XCTAssertTrue(xs.subscriptions.count == 1 || xs.subscriptions[1] == Subscription(440, 440))
}
}
func testShareReplay1_Completed() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
completed(365),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
])
var ys: Observable<Int>! = nil
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = transform(xs.asObservable()) }
scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(400) { subscription1.dispose() }
scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(415) { subscription2.dispose() }
scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(455) { subscription1.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
// 1rt batch
next(340, 8),
next(360, 5),
completed(365),
// 2nd batch
next(440, 5),
completed(440)
])
XCTAssertEqual(res2.events, [
next(355, 8),
next(360, 5),
completed(365)
])
// unoptimized version of replay subject will make a subscription and kill it immediatelly
XCTAssertEqual(xs.subscriptions[0], Subscription(335, 365))
XCTAssertTrue(xs.subscriptions.count <= 2)
XCTAssertTrue(xs.subscriptions.count == 1 || xs.subscriptions[1] == Subscription(440, 440))
}
}
func testShareReplay1_Canceled() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
completed(365),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
])
var ys: Observable<Int>! = nil
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = transform(xs.asObservable()) }
scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(400) { subscription1.dispose() }
scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(415) { subscription2.dispose() }
scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(455) { subscription1.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
// 1rt batch
completed(365),
// 2nd batch
completed(440)
])
XCTAssertEqual(res2.events, [
completed(365)
])
// unoptimized version of replay subject will make a subscription and kill it immediatelly
XCTAssertEqual(xs.subscriptions[0], Subscription(335, 365))
XCTAssertTrue(xs.subscriptions.count <= 2)
XCTAssertTrue(xs.subscriptions.count == 1 || xs.subscriptions[1] == Subscription(440, 440))
}
}
}
// shareReplay(1)
extension ObservableBindingTest {
func testShareReplayLatestWhileConnected_DeadlockImmediatelly() {
var nEvents = 0
let observable = Observable.of(0, 1, 2).shareReplayLatestWhileConnected()
_ = observable.subscribe(onNext: { n in
nEvents += 1
})
XCTAssertEqual(nEvents, 3)
}
func testShareReplayLatestWhileConnected_DeadlockEmpty() {
var nEvents = 0
let observable = Observable<Int>.empty().shareReplayLatestWhileConnected()
_ = observable.subscribe(onCompleted: { n in
nEvents += 1
})
XCTAssertEqual(nEvents, 1)
}
func testShareReplayLatestWhileConnected_DeadlockError() {
var nEvents = 0
let observable = Observable<Int>.error(testError).shareReplayLatestWhileConnected()
_ = observable.subscribe(onError: { _ in
nEvents += 1
})
XCTAssertEqual(nEvents, 1)
}
func testShareReplayLatestWhileConnected_DeadlockErrorAfterN() {
var nEvents = 0
let observable = Observable.concat([Observable.of(0, 1, 2), Observable.error(testError)]).shareReplayLatestWhileConnected()
_ = observable.subscribe(onError: { n in
nEvents += 1
})
XCTAssertEqual(nEvents, 1)
}
func testShareReplayLatestWhileConnected_Basic() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
error(600, testError)
])
var ys: Observable<Int>! = nil
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.shareReplayLatestWhileConnected() }
scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(400) { subscription1.dispose() }
scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(415) { subscription2.dispose() }
scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(455) { subscription1.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
// 1rt batch
next(340, 8),
next(360, 5),
next(370, 6),
next(390, 7),
// 2nd batch
next(450, 9)
])
XCTAssertEqual(res2.events, [
next(355, 8),
next(360, 5),
next(370, 6),
next(390, 7),
next(410, 13)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(335, 415),
Subscription(440, 455)
])
}
func testShareReplayLatestWhileConnected_Error() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
error(365, testError),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
])
var ys: Observable<Int>! = nil
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.shareReplayLatestWhileConnected() }
scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(400) { subscription1.dispose() }
scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(415) { subscription2.dispose() }
scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(455) { subscription1.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
// 1rt batch
next(340, 8),
next(360, 5),
error(365, testError),
// 2nd batch
next(450, 9),
])
XCTAssertEqual(res2.events, [
next(355, 8),
next(360, 5),
error(365, testError),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(335, 365),
Subscription(440, 455)
])
}
func testShareReplayLatestWhileConnected_Completed() {
_testIdenticalBehaviorOfShareReplayOptimizedAndComposed { transform in
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(110, 7),
next(220, 3),
next(280, 4),
next(290, 1),
next(340, 8),
next(360, 5),
completed(365),
next(370, 6),
next(390, 7),
next(410, 13),
next(430, 2),
next(450, 9),
next(520, 11),
next(560, 20),
])
var ys: Observable<Int>! = nil
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
scheduler.scheduleAt(Defaults.created) { ys = xs.shareReplayLatestWhileConnected() }
scheduler.scheduleAt(335) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(400) { subscription1.dispose() }
scheduler.scheduleAt(355) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(415) { subscription2.dispose() }
scheduler.scheduleAt(440) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(455) { subscription1.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
// 1rt batch
next(340, 8),
next(360, 5),
completed(365),
// 2nd batch
next(450, 9),
])
XCTAssertEqual(res2.events, [
next(355, 8),
next(360, 5),
completed(365)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(335, 365),
Subscription(440, 455)
])
}
}
}
| ef0f8cdfadf06d8e4dc8cadcbaeb04e1 | 28.914881 | 159 | 0.510348 | false | true | false | false |
watson-developer-cloud/ios-sdk | refs/heads/master | Sources/DiscoveryV2/Models/QueryResultPassage.swift | apache-2.0 | 1 | /**
* (C) Copyright IBM Corp. 2019, 2021.
*
* 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
/**
A passage query result.
*/
public struct QueryResultPassage: Codable, Equatable {
/**
The content of the extracted passage.
*/
public var passageText: String?
/**
The position of the first character of the extracted passage in the originating field.
*/
public var startOffset: Int?
/**
The position after the last character of the extracted passage in the originating field.
*/
public var endOffset: Int?
/**
The label of the field from which the passage has been extracted.
*/
public var field: String?
/**
Estimate of the probability that the passage is relevant.
*/
public var confidence: Double?
/**
An arry of extracted answers to the specified query.
*/
public var answers: [ResultPassageAnswer]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case passageText = "passage_text"
case startOffset = "start_offset"
case endOffset = "end_offset"
case field = "field"
case confidence = "confidence"
case answers = "answers"
}
}
| 1f3dcc30f6b11ac84234590bf77ceeba | 27.28125 | 93 | 0.674033 | false | false | false | false |
jaouahbi/OMCircularProgress | refs/heads/master | OMCircularProgress/Classes/Extensions/CGRect+Extensions.swift | apache-2.0 | 2 | //
// Copyright 2015 - Jorge Ouahbi
//
// 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.
//
//
// CGRect+Extension.swift
//
// Created by Jorge Ouahbi on 25/11/15.
// Copyright © 2015 Jorge Ouahbi. All rights reserved.
//
import UIKit
/// CGRect Extension
extension CGRect{
/// Apply affine transform
///
/// - parameter t: affine transform
mutating func apply(_ t:CGAffineTransform) {
self = self.applying(t)
}
/// Center in rect
///
/// - parameter mainRect: main rect
///
/// - returns: center CGRect in main rect
func center(_ mainRect:CGRect) -> CGRect{
let dx = mainRect.midX - self.midX
let dy = mainRect.midY - self.midY
return self.offsetBy(dx: dx, dy: dy);
}
/// Construct with size
///
/// - parameter size: CGRect size
///
/// - returns: CGRect
public init(_ size:CGSize) {
self.init(origin: CGPoint.zero,size: size)
}
/// Construct with origin
///
/// - parameter origin: CGRect origin
///
/// - returns: CGRect
public init(_ origin:CGPoint) {
self.init(origin: origin,size: CGSize.zero)
}
/// Min radius from rectangle
public var minRadius:CGFloat {
return size.min() * 0.5;
}
/// Max radius from a rectangle (pythagoras)
public var maxRadius:CGFloat {
return 0.5 * sqrt(size.width * size.width + size.height * size.height)
}
/// Construct with points
///
/// - parameter point1: CGPoint
/// - parameter point2: CGPoint
///
/// - returns: CGRect
public init(_ point1:CGPoint,point2:CGPoint) {
self.init(point1)
size.width = abs(point2.x-self.origin.x)
size.height = abs(point2.y-self.origin.y)
}
}
| 4e518c19522bab7f68a2482257f7bd62 | 26.282353 | 78 | 0.61147 | false | false | false | false |
kyleduo/TinyPNG4Mac | refs/heads/master | source/tinypng4mac/views/SpinnerProgressIndicator.swift | mit | 1 | //
// SpinnerProgressIndicator.swift
// tinypng4mac
//
// Created by kyle on 16/7/6.
// Copyright © 2016年 kyleduo. All rights reserved.
//
import Cocoa
class SpinnerProgressIndicator: NSView {
var progress: Double = 0 {
didSet {
self.needsDisplay = true
}
}
var max: Double = 6
var min: Double = 0
var tintColor: NSColor
required init?(coder: NSCoder) {
tintColor = NSColor.white
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
let size = self.bounds.size
let diam = [size.height, size.width].min()!
let lineWidth: CGFloat = 1
let centerPoint = CGPoint(x: size.width / 2, y: size.height / 2)
let rect = NSRect.init(
x: centerPoint.x - diam / 2 + lineWidth / 2,
y: centerPoint.y - diam / 2 + lineWidth / 2,
width: diam - lineWidth,
height: diam - lineWidth);
let circle = NSBezierPath.init(ovalIn: rect)
tintColor.set()
circle.lineWidth = lineWidth
circle.stroke()
let path = NSBezierPath.init()
path.move(to: centerPoint)
let startAngle: Double = 90
let endAngle = startAngle - progress / max * 360
path.appendArc(withCenter: centerPoint, radius: diam / 2 - lineWidth / 2, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true);
path.close()
path.fill()
}
}
| b235b3a4dd43aa252b71a7e01c3dd8e5 | 22.214286 | 155 | 0.668462 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS | refs/heads/master | SmartReceipts/Common/Exchange/OpenExchangeRates.swift | agpl-3.0 | 3 | //
// OpenExchangeRates.swift
// SmartReceipts
//
// Created by Jaanus Siim on 02/06/16.
// Copyright © 2016 Will Baumann. All rights reserved.
//
import Foundation
private let OpenEchangeRatesAPIHistorycalAddress = "https://openexchangerates.org/api/historical/"
class OpenExchangeRates {
static let sharedInstance = OpenExchangeRates()
fileprivate var rates = [String: [ExchangeRate]]()
func exchangeRate(_ base: String, target: String, onDate date: Date, forceRefresh: Bool, completion: @escaping (NSDecimalNumber?, NSError?) -> ()) {
let dayString = date.dayString()
let dayCurrencyKey = "\(dayString)-\(base)"
Logger.debug("Retrieve \(base) to \(target) on \(dayString)")
if !forceRefresh, let dayValues = rates[dayCurrencyKey], let rate = dayValues.filter({ $0.currency == target}).first {
Logger.debug("Have cache hit")
completion(rate.rate, nil)
return
} else if (forceRefresh) {
Logger.debug("Refresh forced")
}
Logger.debug("Perform remote fetch")
let requestURL = URL(string: "\(OpenEchangeRatesAPIHistorycalAddress)\(dayString).json?base=\(base)&app_id=\(OpenExchangeAppID)")!
Logger.debug("\(requestURL)")
let request = URLRequest(url: requestURL)
let task = URLSession.shared.dataTask(with: request, completionHandler: {
data, response, error in
Logger.debug("Request completed")
if let error = error {
completion(nil, error as NSError?)
return
}
guard var rates = ExchangeRate.loadFromData(data!) else {
completion(nil, nil)
return
}
if let rate = rates.filter({ $0.currency == target }).first {
completion(rate.rate, nil)
} else {
// add unsupported currency marker
rates.append(ExchangeRate(currency: target, rate: .minusOne()))
completion(.minusOne(), nil)
}
self.rates[dayCurrencyKey] = rates
})
task.resume()
}
}
| aff2af293dd3c5457ce55166e661bf45 | 34.857143 | 152 | 0.571492 | false | false | false | false |
SoySauceLab/CollectionKit | refs/heads/master | Examples/CollectionKitExamples/AnimatorExample/AnimatorExampleViewController.swift | mit | 1 | //
// AnimatorExampleViewController.swift
// CollectionKitExample
//
// Created by Luke Zhao on 2017-09-04.
// Copyright © 2017 lkzhao. All rights reserved.
//
import UIKit
import CollectionKit
class AnimatorExampleViewController: CollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
let animators = [
("Default", Animator()),
("Wobble", WobbleAnimator()),
("Edge Shrink", EdgeShrinkAnimator()),
("Zoom", ZoomAnimator()),
]
let imagesCollectionView = CollectionView()
let visibleFrameInsets = UIEdgeInsets(top: 0, left: -100, bottom: 0, right: -100)
let imageProvider = BasicProvider(
dataSource: testImages,
viewSource: ClosureViewSource(viewGenerator: { (data, index) -> UIImageView in
let view = UIImageView()
view.layer.cornerRadius = 5
view.clipsToBounds = true
return view
}, viewUpdater: { (view: UIImageView, data: UIImage, at: Int) in
view.image = data
}),
sizeSource: UIImageSizeSource(),
layout: WaterfallLayout(columns: 2, spacing: 10).transposed().inset(by: bodyInset).insetVisibleFrame(by: visibleFrameInsets),
animator: animators[0].1
)
imagesCollectionView.provider = imageProvider
let buttonsCollectionView = CollectionView()
buttonsCollectionView.showsHorizontalScrollIndicator = false
let buttonsProvider = BasicProvider(
dataSource: animators,
viewSource: { (view: SelectionButton, data: (String, Animator), at: Int) in
view.label.text = data.0
view.label.textColor = imageProvider.animator === data.1 ? .white : .black
view.backgroundColor = imageProvider.animator === data.1 ? .lightGray : .white
},
sizeSource: { _, data, maxSize in
return CGSize(width: data.0.width(withConstraintedHeight: maxSize.height, font: UIFont.systemFont(ofSize:18)) + 20, height: maxSize.height)
},
layout: FlowLayout(lineSpacing: 10).transposed()
.inset(by: UIEdgeInsets(top: 10, left: 16, bottom: 0, right: 16)),
animator: WobbleAnimator(),
tapHandler: { context in
imageProvider.animator = context.data.1
// clear previous styles
for cell in imagesCollectionView.visibleCells {
cell.alpha = 1
cell.transform = .identity
}
context.setNeedsReload()
}
)
buttonsCollectionView.provider = buttonsProvider
let buttonsViewProvider = SimpleViewProvider(
views: [buttonsCollectionView],
sizeStrategy: (.fill, .absolute(44))
)
let providerViewProvider = SimpleViewProvider(
identifier: "providerContent",
views: [imagesCollectionView],
sizeStrategy: (.fill, .fill)
)
provider = ComposedProvider(
layout: RowLayout("providerContent").transposed(),
sections: [
buttonsViewProvider,
providerViewProvider
]
)
}
}
| 9bd5f67bc931489bc281886e9071703b | 31.054348 | 147 | 0.660563 | false | false | false | false |
proversity-org/edx-app-ios | refs/heads/master | Source/RouterEnvironment.swift | apache-2.0 | 1 | //
// RouterEnvironment.swift
// edX
//
// Created by Akiva Leffert on 11/30/15.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
@objc class RouterEnvironment: NSObject, OEXAnalyticsProvider, OEXConfigProvider, DataManagerProvider, OEXInterfaceProvider, NetworkManagerProvider, ReachabilityProvider, OEXRouterProvider, OEXSessionProvider, OEXStylesProvider {
let analytics: OEXAnalytics
let config: OEXConfig
let dataManager: DataManager
let reachability: Reachability
let interface: OEXInterface?
let networkManager: NetworkManager
weak var router: OEXRouter?
let session: OEXSession
let styles: OEXStyles
@objc init(
analytics: OEXAnalytics,
config: OEXConfig,
dataManager: DataManager,
interface: OEXInterface?,
networkManager: NetworkManager,
reachability: Reachability,
session: OEXSession,
styles: OEXStyles
)
{
self.analytics = analytics
self.config = config
self.dataManager = dataManager
self.interface = interface
self.networkManager = networkManager
self.reachability = reachability
self.session = session
self.styles = styles
super.init()
}
}
| cc1e51e930229b101684cffae555f568 | 28.581395 | 229 | 0.684748 | false | true | false | false |
Takanu/Pelican | refs/heads/master | Sources/Pelican/Session/Types/UserSession.swift | mit | 1 | //
// UserSession.swift
// party
//
// Created by Takanu Kyriako on 26/06/2017.
//
//
import Foundation
/**
A high-level class for managing states and information for each user that attempts to interact with your bot
(and that isn't immediately blocked by the bot's blacklist).
UserSession is also used to handle InlineQuery and ChosenInlineResult routes, as ChatSessions cannot receive inline updates.
*/
open class UserSession: Session {
// CORE INTERNAL VARIABLES
public private(set) var tag: SessionTag
public private(set) var dispatchQueue: SessionDispatchQueue
/// The user information associated with this session.
public private(set) var info: User
/// The ID of the user associated with this session.
public private(set) var userID: String
/// The chat sessions this user is currently actively occupying.
/// -- Not currently functional, undecided if it will be implemented
//public var chatSessions: [SessionTag] = []
// API REQUESTS
// Shortcuts for API requests.
public private(set) var requests: MethodRequest
// DELEGATES / CONTROLLERS
/// Delegate for creating, modifying and getting other Sessions.
public private(set) var sessions: SessionRequest
/// Handles and matches user requests to available bot functions.
public var baseRoute: Route
/// Stores what Moderator-controlled permissions the User Session has.
public private(set) var mod: SessionModerator
/// Handles timeout conditions.
public private(set) var timeout: TimeoutMonitor
/// Handles flood conditions.
public private(set) var flood: FloodMonitor
/// Stores a link to the schedule, that allows events to be executed at a later date.
public private(set) var schedule: Schedule
/// Pre-checks and filters unnecessary updates.
public private(set) var filter: UpdateFilter
// TIME AND ACTIVITY
public private(set) var timeStarted = Date()
public required init?(bot: PelicanBot, tag: SessionTag) {
if tag.user == nil { return nil }
self.tag = tag
self.info = tag.user!
self.userID = tag.user!.tgID
self.sessions = SessionRequest(bot: bot)
self.baseRoute = Route(name: "base", routes: [])
self.mod = SessionModerator(tag: tag, moderator: bot.mod)!
self.timeout = TimeoutMonitor(tag: tag, schedule: bot.schedule)
self.flood = FloodMonitor()
self.filter = UpdateFilter()
self.schedule = bot.schedule
self.requests = MethodRequest(tag: tag)
self.dispatchQueue = SessionDispatchQueue(tag: tag, label: "com.pelican.usersession_\(tag.sessionID)",qos: .userInitiated)
}
open func postInit() {
}
open func cleanup() {
self.baseRoute.close()
self.timeout.close()
self.flood.clearAll()
self.dispatchQueue.cancelAll()
self.filter.reset()
}
public func update(_ update: Update) {
if filter.verifyUpdate(update) == false {
self.timeout.bump(update)
self.flood.handle(update)
return
}
dispatchQueue.async {
// Bump the timeout controller first so if flood or another process closes the Session, a new timeout event will not be added.
self.timeout.bump(update)
// This needs revising, whatever...
_ = self.baseRoute.handle(update)
// Bump the flood controller after
self.flood.handle(update)
}
}
}
| d184e319773e29a5a89a985c64b88272 | 25.152 | 129 | 0.718568 | false | false | false | false |
krevis/MIDIApps | refs/heads/main | Applications/SysExLibrarian/ImportController.swift | bsd-3-clause | 1 | /*
Copyright (c) 2002-2021, Kurt Revis. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
import Cocoa
import SnoizeMIDI
class ImportController {
init(windowController: MainWindowController, library: Library) {
self.mainWindowController = windowController
self.library = library
guard Bundle.main.loadNibNamed("Import", owner: self, topLevelObjects: &topLevelObjects) else { fatalError() }
}
// Main window controller sends this to begin the process
func importFiles(_ paths: [String], showingProgress: Bool) {
precondition(filePathsToImport.isEmpty)
filePathsToImport = paths
shouldShowProgress = showingProgress && areAnyFilesDirectories(paths)
showImportWarning()
}
// MARK: Actions
@IBAction func cancelImporting(_ sender: Any?) {
// No need to lock just to set a boolean
importCancelled = true
}
@IBAction func endSheetWithReturnCodeFromSenderTag(_ sender: Any?) {
if let window = mainWindowController?.window,
let sheet = window.attachedSheet,
let senderView = sender as? NSView {
window.endSheet(sheet, returnCode: NSApplication.ModalResponse(rawValue: senderView.tag))
}
}
// MARK: Private
private var topLevelObjects: NSArray?
@IBOutlet private var importSheetWindow: NSPanel!
@IBOutlet private var progressIndicator: NSProgressIndicator!
@IBOutlet private var progressMessageField: NSTextField!
@IBOutlet private var progressIndexField: NSTextField!
@IBOutlet private var importWarningSheetWindow: NSPanel!
@IBOutlet private var doNotWarnOnImportAgainCheckbox: NSButton!
private weak var mainWindowController: MainWindowController?
private weak var library: Library?
private var workQueue: DispatchQueue?
// Transient data
private var filePathsToImport: [String] = []
private var shouldShowProgress = false
private var importCancelled = false
}
extension ImportController /* Preferences keys */ {
static var showWarningOnImportPreferenceKey = "SSEShowWarningOnImport"
}
extension ImportController /* Private */ {
private func areAnyFilesDirectories(_ paths: [String]) -> Bool {
for path in paths {
var isDirectory = ObjCBool(false)
if FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && isDirectory.boolValue {
return true
}
}
return false
}
private func showImportWarning() {
guard let library = library else { return }
let areAllFilesInLibraryDirectory = filePathsToImport.allSatisfy({ library.isPathInFileDirectory($0) })
if areAllFilesInLibraryDirectory || UserDefaults.standard.bool(forKey: Self.showWarningOnImportPreferenceKey) == false {
importFiles()
}
else {
doNotWarnOnImportAgainCheckbox.intValue = 0
mainWindowController?.window?.beginSheet(importWarningSheetWindow, completionHandler: { modalResponse in
self.importWarningSheetWindow.orderOut(nil)
if modalResponse == .OK {
if self.doNotWarnOnImportAgainCheckbox.integerValue == 1 {
UserDefaults.standard.set(false, forKey: Self.showWarningOnImportPreferenceKey)
}
self.importFiles()
}
else {
// Cancelled
self.finishedImport()
}
})
}
}
private func importFiles() {
if shouldShowProgress {
importFilesShowingProgress()
}
else {
// Add entries immediately
let (newEntries, badFiles) = addFilesToLibrary(filePathsToImport)
finishImport(newEntries, badFiles)
}
}
//
// Import with progress display
// Main queue: setup, updating progress display, teardown
//
private func importFilesShowingProgress() {
guard let mainWindow = mainWindowController?.window else { return }
importCancelled = false
updateImportStatusDisplay("", 0, 0)
mainWindow.beginSheet(importSheetWindow) { _ in
self.importSheetWindow.orderOut(nil)
}
let paths = self.filePathsToImport
if workQueue == nil {
workQueue = DispatchQueue(label: "Import", qos: .userInitiated)
}
workQueue?.async {
self.workQueueImportFiles(paths)
}
}
static private var scanningString = NSLocalizedString("Scanning...", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "Scanning...")
static private var xOfYFormatString = NSLocalizedString("%u of %u", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "importing sysex: x of y")
private func updateImportStatusDisplay(_ filePath: String, _ fileIndex: Int, _ fileCount: Int) {
if fileCount == 0 {
progressIndicator.isIndeterminate = true
progressIndicator.usesThreadedAnimation = true
progressIndicator.startAnimation(nil)
progressMessageField.stringValue = Self.scanningString
progressIndexField.stringValue = ""
}
else {
progressIndicator.isIndeterminate = false
progressIndicator.maxValue = Double(fileCount)
progressIndicator.doubleValue = Double(fileIndex + 1)
progressMessageField.stringValue = FileManager.default.displayName(atPath: filePath)
progressIndexField.stringValue = String.localizedStringWithFormat(Self.xOfYFormatString, fileIndex + 1, fileCount)
}
}
//
// Import with progress display
// Work queue: recurse through directories, filter out inappropriate files, and import
//
private func workQueueImportFiles(_ paths: [String]) {
autoreleasepool {
let expandedAndFilteredFilePaths = workQueueExpandAndFilterFiles(paths)
var newEntries = [LibraryEntry]()
var badFiles = [String]()
if expandedAndFilteredFilePaths.count > 0 {
(newEntries, badFiles) = addFilesToLibrary(expandedAndFilteredFilePaths)
}
DispatchQueue.main.async {
self.doneImportingInWorkQueue(newEntries, badFiles)
}
}
}
private func workQueueExpandAndFilterFiles(_ paths: [String]) -> [String] {
guard let library = library else { return [] }
let fileManager = FileManager.default
var acceptableFilePaths = [String]()
for path in paths {
if importCancelled {
acceptableFilePaths.removeAll()
break
}
var isDirectory = ObjCBool(false)
if !fileManager.fileExists(atPath: path, isDirectory: &isDirectory) {
continue
}
autoreleasepool {
if isDirectory.boolValue {
// Handle this directory's contents recursively
do {
let childPaths = try fileManager.contentsOfDirectory(atPath: path)
var fullChildPaths = [String]()
for childPath in childPaths {
let fullChildPath = NSString(string: path).appendingPathComponent(childPath) as String
fullChildPaths.append(fullChildPath)
}
let acceptableChildren = workQueueExpandAndFilterFiles(fullChildPaths)
acceptableFilePaths.append(contentsOf: acceptableChildren)
}
catch {
// ignore
}
}
else {
if fileManager.isReadableFile(atPath: path) && library.typeOfFile(atPath: path) != .unknown {
acceptableFilePaths.append(path)
}
}
}
}
return acceptableFilePaths
}
private func doneImportingInWorkQueue(_ newEntries: [LibraryEntry], _ badFiles: [String]) {
if let window = mainWindowController?.window,
let sheet = window.attachedSheet {
window.endSheet(sheet)
}
finishImport(newEntries, badFiles)
}
//
// Check if each file is already in the library, and then try to add each new one
//
private func addFilesToLibrary(_ paths: [String]) -> ([LibraryEntry], [String]) {
// Returns successfully created library entries, and paths for files that could not
// be successfully imported.
// NOTE: This may be happening in the main queue or workQueue.
guard let library = library else { return ([], []) }
var addedEntries = [LibraryEntry]()
var badFilePaths = [String]()
// Find the files which are already in the library, and pull them out.
let (existingEntries, filePaths) = library.findEntries(forFilePaths: paths)
// Try to add each file to the library, keeping track of the successful ones.
let fileCount = filePaths.count
for (fileIndex, filePath) in filePaths.enumerated() {
// If we're not in the main thread, update progress information and tell the main thread to update its UI.
if !Thread.isMainThread {
if importCancelled {
break
}
DispatchQueue.main.async {
self.updateImportStatusDisplay(filePath, fileIndex, fileCount)
}
}
autoreleasepool {
if let addedEntry = library.addEntry(forFile: filePath) {
addedEntries.append(addedEntry)
}
else {
badFilePaths.append(filePath)
}
}
}
addedEntries.append(contentsOf: existingEntries)
return (addedEntries, badFilePaths)
}
//
// Finishing up
//
private func finishImport(_ newEntries: [LibraryEntry], _ badFiles: [String]) {
mainWindowController?.showNewEntries(newEntries)
showErrorMessageForFilesWithNoSysEx(badFiles)
finishedImport()
}
private func finishedImport() {
filePathsToImport = []
importCancelled = false
}
private func showErrorMessageForFilesWithNoSysEx(_ badFiles: [String]) {
let badFileCount = badFiles.count
guard badFileCount > 0 else { return }
guard let window = mainWindowController?.window,
window.attachedSheet == nil
else { return }
var informativeText: String = ""
if badFileCount == 1 {
informativeText = NSLocalizedString("No SysEx data could be found in this file. It has not been added to the library.", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "message when no sysex data found in file")
}
else {
let format = NSLocalizedString("No SysEx data could be found in %u of the files. They have not been added to the library.", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "format of message when no sysex data found in files")
informativeText = String.localizedStringWithFormat(format, badFileCount)
}
let messageText = NSLocalizedString("Could not read SysEx", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of alert when can't read a sysex file")
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = messageText
alert.informativeText = informativeText
alert.beginSheetModal(for: window, completionHandler: nil)
}
}
| 32883f09fdbbba36186033ebc27fb46d | 34.633929 | 249 | 0.620145 | false | false | false | false |
yonasstephen/swift-of-airbnb | refs/heads/master | airbnb-main/airbnb-main/ImageShrinkAnimationController.swift | mit | 1 | //
// ImageShrinkAnimationController.swift
// airbnb-main
//
// Created by Yonas Stephen on 11/4/17.
// Copyright © 2017 Yonas Stephen. All rights reserved.
//
import UIKit
protocol ImageShrinkAnimationControllerProtocol {
func getInitialImageFrame() -> CGRect
}
class ImageShrinkAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
var destinationFrame = CGRect.zero
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from),
fromVC is ImageShrinkAnimationControllerProtocol,
let toVC = transitionContext.viewController(forKey: .to) else {
return
}
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let containerView = transitionContext.containerView
containerView.backgroundColor = UIColor.white
containerView.addSubview(toVC.view)
// setup cell image snapshot
let initialFrame = (fromVC as! ImageShrinkAnimationControllerProtocol).getInitialImageFrame()
let finalFrame = destinationFrame
let snapshot = fromVC.view.resizableSnapshotView(from: initialFrame, afterScreenUpdates: false, withCapInsets: .zero)!
snapshot.frame = initialFrame
containerView.addSubview(snapshot)
let widthDiff = initialFrame.width - finalFrame.width
// setup snapshot to the left of selected cell image
let leftFinalFrame = CGRect(x: 0, y: finalFrame.origin.y, width: finalFrame.origin.x, height: finalFrame.height)
let leftInitialFrameWidth = leftFinalFrame.width + widthDiff
let leftInitialFrame = CGRect(x: -leftInitialFrameWidth, y: initialFrame.origin.y, width: leftInitialFrameWidth, height: initialFrame.height)
let leftSnapshot = toVC.view.resizableSnapshotView(from: leftFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)!
leftSnapshot.frame = leftInitialFrame
containerView.addSubview(leftSnapshot)
// setup snapshot to the right of selected cell image
let rightFinalFrameX = finalFrame.origin.x + finalFrame.width
let rightFinalFrame = CGRect(x: rightFinalFrameX, y: finalFrame.origin.y, width: screenWidth - rightFinalFrameX, height: finalFrame.height)
let rightInitialFrame = CGRect(x: screenWidth, y: initialFrame.origin.y, width: rightFinalFrame.width + widthDiff, height: initialFrame.height)
let rightSnapshot = toVC.view.resizableSnapshotView(from: rightFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)!
rightSnapshot.frame = rightInitialFrame
containerView.addSubview(rightSnapshot)
// setup snapshot to the bottom of selected cell image
let bottomFinalFrameY = finalFrame.origin.y + finalFrame.height
let bottomFinalFrame = CGRect(x: 0, y: bottomFinalFrameY, width: screenWidth, height: screenHeight - bottomFinalFrameY)
let bottomInitialFrame = CGRect(x: 0, y: bottomFinalFrame.height, width: screenWidth, height: screenHeight)
let bottomSnapshot = toVC.view.resizableSnapshotView(from: bottomFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)!
bottomSnapshot.frame = bottomInitialFrame
containerView.addSubview(bottomSnapshot)
// setup snapshot to the top of selected cell image
let topFinalFrame = CGRect(x: 0, y: 0, width: screenWidth, height: finalFrame.origin.y)
let topInitialFrame = CGRect(x: 0, y: -topFinalFrame.height, width: topFinalFrame.width, height: topFinalFrame.height)
let topSnapshot = toVC.view.resizableSnapshotView(from: topFinalFrame, afterScreenUpdates: false, withCapInsets: .zero)!
topSnapshot.frame = topInitialFrame
containerView.addSubview(topSnapshot)
// setup the bottom component of the origin view
let fromVCBottomInitialFrameY = initialFrame.origin.y + initialFrame.height
let fromVCBottomInitialFrame = CGRect(x: 0, y: fromVCBottomInitialFrameY, width: screenWidth, height: screenHeight - fromVCBottomInitialFrameY)
let fromVCBottomFinalFrame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: fromVCBottomInitialFrame.height)
let fromVCSnapshot = fromVC.view.resizableSnapshotView(from: fromVCBottomInitialFrame, afterScreenUpdates: false, withCapInsets: .zero)!
fromVCSnapshot.frame = fromVCBottomInitialFrame
containerView.addSubview(fromVCSnapshot)
toVC.view.isHidden = true
fromVC.view.isHidden = true
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: 0.3, animations: {
//fromVCSnapshot.alpha = 0
fromVCSnapshot.frame = fromVCBottomFinalFrame
}, completion: { _ in
fromVCSnapshot.removeFromSuperview()
})
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: {
snapshot.frame = finalFrame
leftSnapshot.frame = leftFinalFrame
rightSnapshot.frame = rightFinalFrame
bottomSnapshot.frame = bottomFinalFrame
topSnapshot.frame = topFinalFrame
}, completion: { _ in
toVC.view.isHidden = false
fromVC.view.isHidden = false
snapshot.removeFromSuperview()
leftSnapshot.removeFromSuperview()
rightSnapshot.removeFromSuperview()
bottomSnapshot.removeFromSuperview()
topSnapshot.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| 59637970a9f6e989d374e2fc8581c83c | 46.755906 | 151 | 0.694641 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/UI/Common/Components/Drawer/DrawerOpenAnimator.swift | mit | 1 | //
// DrawerOpenAnimator.swift
// Accented
//
// Created by You, Tiangong on 6/16/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
class DrawerOpenAnimator: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning {
private var animationContext : DrawerAnimationContext
init(animationContext : DrawerAnimationContext) {
self.animationContext = animationContext
super.init()
}
// MARK: UIViewControllerAnimatedTransitioning
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.2
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
let fromView = fromViewController?.view
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
let duration = self.transitionDuration(using: transitionContext)
let animationOptions : UIViewAnimationOptions = (animationContext.interactive ? .curveLinear : .curveEaseOut)
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: {
if fromView != nil {
let scale = CGAffineTransform(scaleX: 0.94, y: 0.94)
var translation : CGAffineTransform
switch(self.animationContext.anchor) {
case .bottom:
translation = CGAffineTransform(translationX: 0, y: -25)
case .left:
translation = CGAffineTransform(translationX: 25, y: 0)
case .right:
translation = CGAffineTransform(translationX: -25, y: 0)
}
fromView!.transform = scale.concatenating(translation)
}
toView.transform = CGAffineTransform.identity
}) { (finished) in
let transitionCompleted = !transitionContext.transitionWasCancelled
transitionContext.completeTransition(transitionCompleted)
}
}
}
| 542d929e81de534e516c42f6b50e51cf | 39.381818 | 117 | 0.656461 | false | false | false | false |
EasyIOS/EasyIOS-Swift | refs/heads/master | Pod/Classes/Extend/EUI/EUI+TextFieldProperty.swift | mit | 2 | //
// EUI+TextFieldProperty.swift
// medical
//
// Created by zhuchao on 15/5/1.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import Foundation
class TextFieldProperty:ViewProperty{
var placeholder:NSData?
var placeholderStyle = ""
var text:NSData?
var keyboardType = UIKeyboardType.Default
override func view() -> UITextField{
let view = UITextField()
view.tagProperty = self
view.keyboardType = self.keyboardType
let str = NSAttributedString(fromHTMLData:self.text, attributes: ["html":self.style])
view.defaultTextAttributes = str.attributesAtIndex(0, effectiveRange:nil)
view.attributedPlaceholder = NSAttributedString(fromHTMLData: self.placeholder, attributes: ["html":self.placeholderStyle])
self.renderViewStyle(view)
return view
}
override func renderTag(pelement: OGElement) {
self.tagOut += ["placeholder","placeholder-style","text","keyboard-type"]
super.renderTag(pelement)
if let text = EUIParse.string(pelement, key: "text"),
let newHtml = Regex("\\{\\{(\\w+)\\}\\}").replace(text, withBlock: { (regx) -> String in
let keyPath = regx.subgroupMatchAtIndex(0)?.trim
self.bind["text"] = keyPath
return ""
}) {
self.contentText = newHtml
}
self.text = "1".dataUsingEncoding(NSUTF8StringEncoding)?.dataByReplacingOccurrencesOfData("\\n".dataUsingEncoding(NSUTF8StringEncoding), withData: "\n".dataUsingEncoding(NSUTF8StringEncoding))
if let placeholderStyle = EUIParse.string(pelement,key: "placeholder-style") {
self.placeholderStyle = "html{" + placeholderStyle + "}"
}
if let placeholder = EUIParse.string(pelement,key: "placeholder") {
self.placeholder = placeholder.dataUsingEncoding(NSUTF8StringEncoding)?.dataByReplacingOccurrencesOfData("\\n".dataUsingEncoding(NSUTF8StringEncoding), withData: "\n".dataUsingEncoding(NSUTF8StringEncoding))
}
if let keyboardType = EUIParse.string(pelement, key: "keyboard-type") {
self.keyboardType = keyboardType.keyboardType
}
}
}
| 23d1ede2d9cb92d559fc9e8e85ae61b0 | 39.5 | 219 | 0.647266 | false | false | false | false |
ColinConduff/BlocFit | refs/heads/master | BlocFit/Main Components/Map/MapController.swift | mit | 1 | //
// MapController.swift
// BlocFit
//
// Created by Colin Conduff on 1/8/17.
// Copyright © 2017 Colin Conduff. All rights reserved.
//
import CoreData
import GoogleMaps
import HealthKit
protocol MapNotificationDelegate: class {
func blocMembersDidChange(_ blocMembers: [BlocMember])
func didPressActionButton() -> Bool
func loadSavedRun(run: Run)
}
protocol MapControllerProtocol: class {
var mapRunModel: MapRunModel { get }
var authStatusIsAuthAlways: Bool { get }
var cameraPosition: GMSCameraPosition { get }
var paths: [Path] { get }
var run: Run? { get }
var seconds: Int { get }
var mapRunModelDidChange: ((MapRunModel) -> ())? { get set }
var authStatusDidChange: ((MapControllerProtocol) -> ())? { get set }
var cameraPositionDidChange: ((MapControllerProtocol) -> ())? { get set }
var pathsDidChange: ((MapControllerProtocol) -> ())? { get set }
var secondsDidChange: ((MapControllerProtocol) -> ())? { get set }
init(requestMainDataDelegate: RequestMainDataDelegate, scoreReporterDelegate: ScoreReporterDelegate, context: NSManagedObjectContext)
func cameraPositionNeedsUpdate()
}
class MapController: NSObject, CLLocationManagerDelegate, MapControllerProtocol, MapNotificationDelegate {
var mapRunModel: MapRunModel { didSet { self.mapRunModelDidChange?(mapRunModel) } }
var authStatusIsAuthAlways = false { didSet { self.authStatusDidChange?(self) } }
var cameraPosition: GMSCameraPosition { didSet { self.cameraPositionDidChange?(self) } }
var paths = [Path]() { didSet { self.pathsDidChange?(self) } }
var seconds = 0 { didSet { self.secondsDidChange?(self) } }
var run: Run? {
didSet {
guard let run = run else { return }
self.setDashboardModel(using: run)
}
}
var mapRunModelDidChange: ((MapRunModel) -> ())?
var authStatusDidChange: ((MapControllerProtocol) -> ())?
var cameraPositionDidChange: ((MapControllerProtocol) -> ())?
var pathsDidChange: ((MapControllerProtocol) -> ())?
var secondsDidChange: ((MapControllerProtocol) -> ())?
weak var requestMainDataDelegate: RequestMainDataDelegate!
weak var scoreReporterDelegate: ScoreReporterDelegate!
let locationManager = CLLocationManager()
let context: NSManagedObjectContext
let owner: Owner
var currentlyRunning = false
var timer = Timer()
required init(requestMainDataDelegate: RequestMainDataDelegate,
scoreReporterDelegate: ScoreReporterDelegate,
context: NSManagedObjectContext) {
self.requestMainDataDelegate = requestMainDataDelegate
self.scoreReporterDelegate = scoreReporterDelegate
self.context = context
owner = try! Owner.get(context: context)!
mapRunModel = MapRunModel(secondsElapsed: 0,
score: 0,
totalDistanceInMeters: 0,
secondsPerMeter: 0)
cameraPosition = GMSCameraPosition.camera(withLatitude: 37.35,
longitude: -122.0,
zoom: 18.0)
authStatusIsAuthAlways = CLLocationManager.authorizationStatus() == .authorizedAlways
super.init()
initializeLocationManagement()
HealthKitManager.authorize()
}
private func initializeLocationManagement() {
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.activityType = .fitness
locationManager.distanceFilter = 10
locationManager.allowsBackgroundLocationUpdates = true
}
// CLLocationManagerDelegate Methods
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
authStatusIsAuthAlways = (status == .authorizedAlways)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("location manager error")
print(error)
}
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
var paths = [Path]()
for location in locations {
if location.horizontalAccuracy < 20 {
let lastRunPoint = run?.runPoints?.lastObject as? RunPoint
updateRun(currentLocation: location)
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
if let lastLatitude = lastRunPoint?.latitude,
let lastLongitude = lastRunPoint?.longitude {
let path = Path(fromLat: lastLatitude,
fromLong: lastLongitude,
toLat: latitude,
toLong: longitude)
paths.append(path)
}
updateCameraPosition(latitude: latitude, longitude: longitude)
}
}
self.paths = paths
}
func cameraPositionNeedsUpdate() {
if let coordinate = locationManager.location?.coordinate {
updateCameraPosition(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
}
private func updateCameraPosition(latitude: Double, longitude: Double) {
let target = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
cameraPosition = GMSCameraPosition.camera(withTarget: target, zoom: 18.0)
}
// MapNotificationDelegate Method
func loadSavedRun(run: Run) {
self.run = run
guard let runPoints = run.runPoints?.array as? [RunPoint] else { return }
var paths = [Path]()
var lastRunPoint: RunPoint? = nil
for runPoint in runPoints {
if let lastRunPoint = lastRunPoint {
let path = Path(fromLat: lastRunPoint.latitude,
fromLong: lastRunPoint.longitude,
toLat: runPoint.latitude,
toLong: runPoint.longitude)
paths.append(path)
}
lastRunPoint = runPoint
}
self.paths = paths
if let latitude = lastRunPoint?.latitude,
let longitude = lastRunPoint?.longitude {
updateCameraPosition(latitude: latitude, longitude: longitude)
}
}
private func updateRun(currentLocation: CLLocation) {
guard let run = run else { return }
try? run.update(currentLocation: currentLocation)
setDashboardModel(using: run)
}
private func setDashboardModel(using run: Run) {
mapRunModel = MapRunModel(secondsElapsed: Double(run.secondsElapsed),
score: Int(run.score),
totalDistanceInMeters: run.totalDistanceInMeters,
secondsPerMeter: run.secondsPerMeter)
}
// MapNotificationDelegate Method
func blocMembersDidChange(_ blocMembers: [BlocMember]) {
guard let run = run else { return }
try? run.update(blocMembers: blocMembers)
}
// Logic for responding to action button click //
// MapNotificationDelegate Method
func didPressActionButton() -> Bool {
if authStatusIsAuthAlways {
if currentlyRunning {
stopRunning()
} else {
startRunning()
}
currentlyRunning = !currentlyRunning
} else {
authStatusIsAuthAlways = false // trigger didSet
}
return authStatusIsAuthAlways
}
private func startRunning() {
let blocMembers = requestMainDataDelegate.getCurrentBlocMembers()
run = try! Run.create(owner: owner, blocMembers: blocMembers, context: context)
startTrackingData()
}
private func startTrackingData() {
locationManager.startUpdatingLocation()
seconds = 0
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in self.seconds += 1 }
}
private func stopRunning() {
locationManager.stopUpdatingLocation()
timer.invalidate()
if let run = run {
saveRunToHealthKit(run)
scoreReporterDelegate.submitScore(run: run)
scoreReporterDelegate.submitScore(owner: owner)
}
}
private func saveRunToHealthKit(_ run: Run) {
guard let start = run.startTime as? Date,
let end = run.endTime as? Date else { return }
HealthKitManager.save(meters: run.totalDistanceInMeters,
start: start,
end: end)
}
}
| d61d65d85fef85ecc5ab85f3116b989e | 34.942085 | 137 | 0.593834 | false | false | false | false |
thiagotmb/BEPiD-Challenges-2016 | refs/heads/master | 2016-04-06-Complications/TouristComplicationChallenge/TouristComplicationChallenge WatchKit Extension/ComplicationController.swift | mit | 2 | //
// ComplicationController.swift
// TouristComplicationChallenge WatchKit Extension
//
// Created by Thiago-Bernardes on 4/6/16.
// Copyright © 2016 TB. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
if complication.family == .UtilitarianLarge {
let complicationTemplate = CLKComplicationTemplateUtilitarianLargeFlat()
complicationTemplate.textProvider = CLKSimpleTextProvider(text: "05:50 - 😎")
handler(complicationTemplate)
}
}
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.Forward, .Backward])
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
// Call the handler with the current timeline entry
var emoji = "🤑"
if TaskModel.completedTasks().count < 3 {
emoji = "😐"
}
if complication.family == .UtilitarianLarge {
let complicationTemplate = CLKComplicationTemplateUtilitarianLargeFlat()
complicationTemplate.textProvider = CLKSimpleTextProvider(text: ("6:40" + emoji))
let complicationEntry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: complicationTemplate)
handler(complicationEntry)
}
handler(nil)
}
func reloadData() {
// 1
let server = CLKComplicationServer.sharedInstance()
guard let complications = server.activeComplications
where complications.count > 0 else { return }
for complication in complications {
server.reloadTimelineForComplication(complication)
}
}
}
| 11d23c6d0d621b0223a3615f6fec9efc | 29.688312 | 157 | 0.648752 | false | false | false | false |
SuPair/firefox-ios | refs/heads/master | Client/Frontend/Browser/BrowserViewController/BrowserViewController+DownloadQueueDelegate.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
extension BrowserViewController: DownloadQueueDelegate {
func downloadQueue(_ downloadQueue: DownloadQueue, didStartDownload download: Download) {
// If no other download toast is shown, create a new download toast and show it.
guard let downloadToast = self.downloadToast else {
let downloadToast = DownloadToast(download: download, completion: { buttonPressed in
// When this toast is dismissed, be sure to clear this so that any
// subsequent downloads cause a new toast to be created.
self.downloadToast = nil
// Handle download cancellation
if buttonPressed, !downloadQueue.isEmpty {
downloadQueue.cancelAllDownloads()
let downloadCancelledToast = ButtonToast(labelText: Strings.DownloadCancelledToastLabelText, backgroundColor: UIColor.Photon.Grey60, textAlignment: .center)
self.show(toast: downloadCancelledToast)
}
})
show(toast: downloadToast, duration: nil)
return
}
// Otherwise, just add this download to the existing download toast.
downloadToast.addDownload(download)
}
func downloadQueue(_ downloadQueue: DownloadQueue, didDownloadCombinedBytes combinedBytesDownloaded: Int64, combinedTotalBytesExpected: Int64?) {
downloadToast?.combinedBytesDownloaded = combinedBytesDownloaded
}
func downloadQueue(_ downloadQueue: DownloadQueue, download: Download, didFinishDownloadingTo location: URL) {
print("didFinishDownloadingTo(): \(location)")
}
func downloadQueue(_ downloadQueue: DownloadQueue, didCompleteWithError error: Error?) {
guard let downloadToast = self.downloadToast, let download = downloadToast.downloads.first else {
return
}
DispatchQueue.main.async {
downloadToast.dismiss(false)
if error == nil {
let downloadCompleteToast = ButtonToast(labelText: download.filename, imageName: "check", buttonText: Strings.DownloadsButtonTitle, completion: { buttonPressed in
if buttonPressed {
self.openURLInNewTab(HomePanelType.downloads.localhostURL, isPrivate: self.tabManager.selectedTab?.isPrivate ?? false, isPrivileged: true)
UnifiedTelemetry.recordEvent(category: .action, method: .view, object: .downloadsPanel, value: .downloadCompleteToast)
}
})
self.show(toast: downloadCompleteToast, duration: DispatchTimeInterval.seconds(8))
} else {
let downloadFailedToast = ButtonToast(labelText: Strings.DownloadFailedToastLabelText, backgroundColor: UIColor.Photon.Grey60, textAlignment: .center)
self.show(toast: downloadFailedToast, duration: nil)
}
}
}
}
| 8daaca4f2b2870107b7855a3c5df7153 | 46.462687 | 178 | 0.66478 | false | false | false | false |
sleekbyte/tailor | refs/heads/master | src/test/swift/com/sleekbyte/tailor/functional/RuleTest.swift | mit | 1 | import Foundation; import Cocoa
let kMaximum = 42
let my_constant = 12
class SomeClass {
// class definition goes here
func timesTwo(myValue: Int) -> Int {
let my_local_constant = 7
return my_local_constant + myValue
}
}
enum someEnumeration {
// enumeration definition goes here
};
enum compassPoint {
case North
case South;
case East
case west
}
struct someStructure {
// structure definition goes here
}
protocol someProtocol {
// protocol definition goes here
}
//
var airports = [("YYZ"): "Toronto"]
var counter = (0)
//
// first line over max-file-length limit
while (counter < 1) {
counter++
}
// missing trailing newline | ede75f826305c6328441b3aabfa58fe3 | 16.375 | 42 | 0.661383 | false | false | false | false |
himadrisj/SiriPay | refs/heads/dev | Client/SiriPay/ezPay-SiriIntent/IntentHandler.swift | mit | 1 | //
// IntentHandler.swift
// ezPay-SiriIntent
//
// Created by Himadri Sekhar Jyoti on 11/09/16.
// Copyright
//
import Intents
// As an example, this class is set up to handle Message intents.
// You will want to replace this or add other intents as appropriate.
// The intents you wish to handle must be declared in the extension's Info.plist.
// You can test your example integration by saying things to Siri like:
// "Send a message using <myApp>"
// "<myApp> John saying hello"
// "Search for messages in <myApp>"
class IntentHandler: INExtension, INSendPaymentIntentHandling {
override func handler(for intent: INIntent) -> Any {
// This is the default implementation. If you want different objects to handle different intents,
// you can override this and return the handler you want for that particular intent.
return self
}
/*!
@brief handling method
@abstract Execute the task represented by the INSendPaymentIntent that's passed in
@discussion This method is called to actually execute the intent. The app must return a response for this intent.
@param sendPaymentIntent The input intent
@param completion The response handling block takes a INSendPaymentIntentResponse containing the details of the result of having executed the intent
@see INSendPaymentIntentResponse
*/
public func handle(sendPayment intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Swift.Void) {
// Implement your application logic for payment here.
var thePhoneNO = "9886957281" //"9711165687" //"9742048795"
let defaults = UserDefaults(suiteName: "group.com.example.ezpay")
if let contactDict = defaults?.object(forKey: contactsSharedKey) as? [String: String] {
if let lowerCaseName = intent.payee?.displayName.lowercased() {
if let phNo = contactDict[lowerCaseName] {
thePhoneNO = phNo
}
}
}
// if(intent.payee?.displayName.caseInsensitiveCompare("Jatin") == .orderedSame) {
// phoneNo = "9711165687"
// }
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendPaymentIntent.self))
var response = INSendPaymentIntentResponse(code: .failure, userActivity: userActivity)
if let intAmount = intent.currencyAmount?.amount?.intValue {
var payInfo = [String:String]()
payInfo["phone"] = thePhoneNO
payInfo["amount"] = String(intAmount)
let defaults = UserDefaults(suiteName: "group.com.example.ezpay")
defaults?.set(payInfo, forKey: payInfoUserDefaultsKey)
defaults?.synchronize()
response = INSendPaymentIntentResponse(code: .success, userActivity: userActivity)
response.paymentRecord = self.makePaymentRecord(for: intent)
}
completion(response)
}
/*!
@brief Confirmation method
@abstract Validate that this intent is ready for the next step (i.e. handling)
@discussion These methods are called prior to asking the app to handle the intent. The app should return a response object that contains additional information about the intent, which may be relevant for the system to show the user prior to handling. If unimplemented, the system will assume the intent is valid following resolution, and will assume there is no additional information relevant to this intent.
@param sendPaymentIntent The input intent
@param completion The response block contains an INSendPaymentIntentResponse containing additional details about the intent that may be relevant for the system to show the user prior to handling.
@see INSendPaymentIntentResponse
*/
public func confirm(sendPayment intent: INSendPaymentIntent, completion: @escaping (INSendPaymentIntentResponse) -> Swift.Void) {
let response = INSendPaymentIntentResponse(code: .success, userActivity: nil)
response.paymentRecord = self.makePaymentRecord(for: intent)
completion(response)
}
func makePaymentRecord(for intent: INSendPaymentIntent, status: INPaymentStatus = .completed) -> INPaymentRecord? {
let paymentMethod = INPaymentMethod(type: .unknown, name: "SimplePay", identificationHint: nil, icon: nil)
let localCurrencyAmmount = INCurrencyAmount(amount: (intent.currencyAmount?.amount)!, currencyCode: "INR")
return INPaymentRecord(
payee: intent.payee,
payer: nil,
currencyAmount: localCurrencyAmmount,
paymentMethod: paymentMethod,
note: intent.note,
status: status
)
}
/*!
@brief Resolution methods
@abstract Determine if this intent is ready for the next step (confirmation)
@discussion These methods are called to make sure the app extension is capable of handling this intent in its current form. This method is for validating if the intent needs any further fleshing out.
@param sendPaymentIntent The input intent
@param completion The response block contains an INIntentResolutionResult for the parameter being resolved
@see INIntentResolutionResult
*/
public func resolvePayee(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INPersonResolutionResult) -> Swift.Void) {
guard let payee = intent.payee else {
completion(INPersonResolutionResult.needsValue())
return
}
// if let type = payee.personHandle?.type {
// if(type == .phoneNumber) {
// completion(INPersonResolutionResult.success(with: payee))
// return
// }
// }
let defaults = UserDefaults(suiteName: "group.com.example.ezpay")
if let contactDict = defaults?.object(forKey: contactsSharedKey) as? [String: String] {
if(contactDict[payee.displayName.lowercased()]?.characters.count == 10) {
completion(INPersonResolutionResult.success(with: payee))
return
}
}
// if (payee.displayName.caseInsensitiveCompare("om") == .orderedSame || payee.displayName.caseInsensitiveCompare("jatin") == .orderedSame) {
// completion(INPersonResolutionResult.success(with: payee))
// }
completion(INPersonResolutionResult.disambiguation(with: [payee]))
}
public func resolveCurrencyAmount(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INCurrencyAmountResolutionResult) -> Swift.Void) {
guard let amount = intent.currencyAmount else {
completion(INCurrencyAmountResolutionResult.needsValue())
return
}
guard amount.amount != nil else {
completion(INCurrencyAmountResolutionResult.needsValue())
return
}
completion(INCurrencyAmountResolutionResult.success(with: amount))
}
// public func resolveNote(forSendPayment intent: INSendPaymentIntent, with completion: @escaping (INStringResolutionResult) -> Swift.Void) {
//
// }
//
}
| 6a9ddd97d8a2b494afd43551d1e99ab0 | 40.527778 | 414 | 0.660602 | false | false | false | false |
kak-ios-codepath/everest | refs/heads/master | Everest/Everest/Controllers/TimeLine/TimelineViewController.swift | apache-2.0 | 1 | //
// TimelineViewController.swift
// Everest
//
// Created by Kavita Gaitonde on 10/13/17.
// Copyright © 2017 Kavita Gaitonde. All rights reserved.
//
import UIKit
class TimelineViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, MomentCellDelegate {
// MARK: -- outlets and properties
@IBOutlet weak var timelineTableView: UITableView!
private var timelineManager: TimeLineManager?
private var moments : [Moment]?
private var isMapView = false
private var mapViewController : TimeLineMapViewController?
private let refreshControl = UIRefreshControl()
// MARK: -- Initialization codes
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
func initialize() -> Void {
timelineManager = TimeLineManager.init()
moments = [Moment]()
}
// MARK: -- View controller lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "MomentCell", bundle: nil)
self.timelineTableView.register(nib, forCellReuseIdentifier: "MomentCell")
self.timelineTableView.estimatedRowHeight = 100//self.timelineTableView.rowHeight
self.timelineTableView.rowHeight = UITableViewAutomaticDimension
refreshControl.backgroundColor = UIColor.clear
refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged)
self.timelineTableView.insertSubview(refreshControl, at: 0)
self.mapViewController = TimeLineMapViewController(nibName: "TimeLineMapViewController", bundle: nil)
self.mapViewController?.navController = self.navigationController
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "MomentCreated"), object: nil, queue: OperationQueue.main, using: {(Notification) -> () in
self.loadData()
})
self.loadData()
//// -- TODO: Remove code after TESTING image uploads
// guard let image = UIImage(named: "password") else { return }
// //guard let imageData = UIImageJPEGRepresentation(image, 0.8) else { return }
//
// FireBaseManager.shared.uploadImage(image: image) { (path, url, error) in
// if url != nil {
// print("Image path: \(path)")
// print("Uploaded image to: \(url!)")
// FireBaseManager.shared.downloadImage(path: path, completion: { (url, error) in
// if url != nil {
// print("Downloaded image to: \(url!)")
// } else {
// print("Error Uploading image ")
// }
// })
// } else {
// print("Error Uploadding image ")
// }
// }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.barTintColor = UIColor(red:0.94, green:0.71, blue:0.25, alpha:1.0)
self.navigationController?.navigationBar.isTranslucent = false
}
@objc func refreshControlAction(_ refreshControl: UIRefreshControl) {
loadData()
}
@IBAction func showMapAction(_ sender: Any) {
if (isMapView) {
self.timelineTableView.frame = self.view.bounds; //grab the view of a separate VC
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1.0)
UIView.setAnimationTransition(.flipFromLeft, for: (self.view)!, cache: true)
self.mapViewController?.view.removeFromSuperview()
self.view.addSubview(self.timelineTableView)
UIView.commitAnimations()
self.navigationItem.rightBarButtonItem?.title = "Map"
} else {
self.mapViewController?.view.frame = self.view.bounds; //grab the view of a separate VC
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1.0)
UIView.setAnimationTransition(.flipFromLeft, for: (self.view)!, cache: true)
self.mapViewController?.view.removeFromSuperview()
self.view.addSubview((self.mapViewController?.view)!)
UIView.commitAnimations()
self.mapViewController?.moments = self.moments
self.navigationItem.rightBarButtonItem?.title = "List"
}
self.isMapView = self.isMapView ? false : true
}
func loadData() {
self.timelineManager?.fetchPublicMomments(completion: { (moments:[Moment]?, error: Error?) in
if((error) != nil) {
// show the alert
return
}
// for moment in moments! {
// print("\(moment.title)")
// }
self.moments = moments?.sorted(by: { $0.timestamp > $1.timestamp })
DispatchQueue.main.async {
self.refreshControl.endRefreshing()
self.timelineTableView.reloadData()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: -- Tableview data source and delegate methods
@available(iOS 2.0, *)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MomentCell", for: indexPath) as! MomentCell
if (self.moments?.count)!>0 {
cell.momentCellDelegate = self
cell.moment = self.moments?[indexPath.row]
}
return cell
}
@available(iOS 2.0, *)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.moments?.count ?? 0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let momentsDetailVC = storyboard.instantiateViewController(withIdentifier: "MomentsViewController") as! MomentsViewController
momentsDetailVC.momentId = self.moments?[indexPath.row].id
momentsDetailVC.isUserMomentDetail = false
self.navigationController?.pushViewController(momentsDetailVC, animated: true)
}
// MARK: -- MomentCell delegate methods
func momentCell(cell: MomentCell, didTapOnUserIconForMoment moment: Moment) {
let userProfileStoryboard = UIStoryboard(name: "UserProfile", bundle: nil)
let userProfileVC = userProfileStoryboard.instantiateViewController(withIdentifier: "UserProfileViewController") as! UserProfileViewController
//TODO: Add the user object property to the userprofile viewcontroller
userProfileVC.userId = moment.userId
self.navigationController?.pushViewController(userProfileVC, animated: true)
}
}
| c37ff12b6975e9b146b3c8323de05aa7 | 37.227723 | 176 | 0.628335 | false | false | false | false |
breadwallet/breadwallet-ios | refs/heads/master | breadwallet/src/ViewControllers/Import/ImportKeyViewController.swift | mit | 1 | //
// StartImportViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-06-13.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
import WalletKit
/**
* Screen that allows the user to scan a QR code corresponding to a private key.
*
* It can be displayed in response to the "Redeem Private Key" menu item under Bitcoin
* preferences or in response to the user scanning a private key using the Scan QR Code
* item in the main menu. In the latter case, an initial QR code is passed to the init() method.
*/
class ImportKeyViewController: UIViewController, Subscriber {
/**
* Initializer
*
* walletManager - Bitcoin wallet manager
* initialQRCode - a QR code that was previously scanned, causing this import view controller to
* be displayed
*/
init(wallet: Wallet, initialQRCode: QRCode? = nil) {
self.wallet = wallet
self.initialQRCode = initialQRCode
assert(wallet.currency.isBitcoin || wallet.currency.isBitcoinCash, "Importing only supports btc or bch")
super.init(nibName: nil, bundle: nil)
}
private let wallet: Wallet
private let header = RadialGradientView(backgroundColor: .blue, offset: 64.0)
private let illustration = UIImageView(image: #imageLiteral(resourceName: "ImportIllustration"))
private let message = UILabel.wrapping(font: .customBody(size: 16.0), color: .white)
private let warning = UILabel.wrapping(font: .customBody(size: 16.0), color: .white)
private let button = BRDButton(title: S.Import.scan, type: .primary)
private let bullet = UIImageView(image: #imageLiteral(resourceName: "deletecircle"))
private let leftCaption = UILabel.wrapping(font: .customMedium(size: 13.0), color: .darkText)
private let rightCaption = UILabel.wrapping(font: .customMedium(size: 13.0), color: .darkText)
private let balanceActivity = BRActivityViewController(message: S.Import.checking)
private let importingActivity = BRActivityViewController(message: S.Import.importing)
private let unlockingActivity = BRActivityViewController(message: S.Import.unlockingActivity)
private var viewModel: TxViewModel?
// Previously scanned QR code passed to init()
private var initialQRCode: QRCode?
override func viewDidLoad() {
super.viewDidLoad()
addSubviews()
addConstraints()
setInitialData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let code = initialQRCode {
handleScanResult(code)
// Set this nil so that if the user tries to can another QR code via the
// Scan Private Key button we don't end up trying to process the initial
// code again. viewWillAppear() will get called again when the scanner/camera
// is dismissed.
initialQRCode = nil
}
}
deinit {
wallet.unsubscribe(self)
}
private func addSubviews() {
view.addSubview(header)
header.addSubview(illustration)
header.addSubview(leftCaption)
header.addSubview(rightCaption)
view.addSubview(message)
view.addSubview(button)
view.addSubview(bullet)
view.addSubview(warning)
}
private func addConstraints() {
header.constrainTopCorners(sidePadding: 0, topPadding: 0)
header.constrain([
header.constraint(.height, constant: E.isIPhoneX ? 250.0 : 220.0) ])
illustration.constrain([
illustration.constraint(.width, constant: 64.0),
illustration.constraint(.height, constant: 84.0),
illustration.constraint(.centerX, toView: header, constant: 0.0),
illustration.constraint(.centerY, toView: header, constant: E.isIPhoneX ? 4.0 : -C.padding[1]) ])
leftCaption.constrain([
leftCaption.topAnchor.constraint(equalTo: illustration.bottomAnchor, constant: C.padding[1]),
leftCaption.trailingAnchor.constraint(equalTo: header.centerXAnchor, constant: -C.padding[2]),
leftCaption.widthAnchor.constraint(equalToConstant: 80.0)])
rightCaption.constrain([
rightCaption.topAnchor.constraint(equalTo: illustration.bottomAnchor, constant: C.padding[1]),
rightCaption.leadingAnchor.constraint(equalTo: header.centerXAnchor, constant: C.padding[2]),
rightCaption.widthAnchor.constraint(equalToConstant: 80.0)])
message.constrain([
message.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[2]),
message.topAnchor.constraint(equalTo: header.bottomAnchor, constant: C.padding[2]),
message.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]) ])
bullet.constrain([
bullet.leadingAnchor.constraint(equalTo: message.leadingAnchor),
bullet.topAnchor.constraint(equalTo: message.bottomAnchor, constant: C.padding[4]),
bullet.widthAnchor.constraint(equalToConstant: 16.0),
bullet.heightAnchor.constraint(equalToConstant: 16.0) ])
warning.constrain([
warning.leadingAnchor.constraint(equalTo: bullet.trailingAnchor, constant: C.padding[2]),
warning.topAnchor.constraint(equalTo: bullet.topAnchor, constant: 0.0),
warning.trailingAnchor.constraint(equalTo: message.trailingAnchor) ])
button.constrain([
button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[3]),
button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -C.padding[4]),
button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[3]),
button.constraint(.height, constant: C.Sizes.buttonHeight) ])
}
private func setInitialData() {
view.backgroundColor = .darkBackground
illustration.contentMode = .scaleAspectFill
message.text = S.Import.importMessage
leftCaption.text = S.Import.leftCaption
leftCaption.textAlignment = .center
rightCaption.text = S.Import.rightCaption
rightCaption.textAlignment = .center
warning.text = S.Import.importWarning
// Set up the tap handler for the "Scan Private Key" button.
button.tap = strongify(self) { myself in
let scan = ScanViewController(forScanningPrivateKeysOnly: true) { result in
guard let result = result else { return }
myself.handleScanResult(result)
}
myself.parent?.present(scan, animated: true, completion: nil)
}
}
private func handleScanResult(_ result: QRCode) {
switch result {
case .privateKey(let key):
didReceiveAddress(key)
case .gift(let key, let model):
didReceiveAddress(key)
self.viewModel = model
default:
break
}
}
private func didReceiveAddress(_ address: String) {
guard !Key.isProtected(asPrivate: address) else {
return unlock(address: address) { self.createTransaction(withPrivKey: $0) }
}
guard let key = Key.createFromString(asPrivate: address) else {
showErrorMessage(S.Import.Error.notValid)
return
}
createTransaction(withPrivKey: key)
}
private func createTransaction(withPrivKey key: Key) {
present(balanceActivity, animated: true, completion: nil)
wallet.createSweeper(forKey: key) { result in
DispatchQueue.main.async {
self.balanceActivity.dismiss(animated: true) {
switch result {
case .success(let sweeper):
self.importFrom(sweeper)
case .failure(let error):
self.handleError(error)
}
}
}
}
}
private func importFrom(_ sweeper: WalletSweeper) {
guard let balance = sweeper.balance else { return self.showErrorMessage(S.Import.Error.empty) }
let balanceAmount = Amount(cryptoAmount: balance, currency: wallet.currency)
guard !balanceAmount.isZero else { return self.showErrorMessage(S.Import.Error.empty) }
sweeper.estimate(fee: wallet.feeForLevel(level: .regular)) { result in
DispatchQueue.main.async {
switch result {
case .success(let feeBasis):
self.confirmImport(fromSweeper: sweeper, fee: feeBasis)
case .failure(let error):
self.handleEstimateFeeError(error)
}
}
}
}
private func confirmImport(fromSweeper sweeper: WalletSweeper, fee: TransferFeeBasis) {
let balanceAmount = Amount(cryptoAmount: sweeper.balance!, currency: wallet.currency)
let feeAmount = Amount(cryptoAmount: fee.fee, currency: wallet.currency)
let balanceText = "\(balanceAmount.fiatDescription) (\(balanceAmount.description))"
let feeText = "\(feeAmount.fiatDescription)"
let message = String(format: S.Import.confirm, balanceText, feeText)
let alert = UIAlertController(title: S.Import.title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: S.Import.importButton, style: .default, handler: { _ in
self.present(self.importingActivity, animated: true)
self.submit(sweeper: sweeper, fee: fee)
}))
present(alert, animated: true)
}
private func submit(sweeper: WalletSweeper, fee: TransferFeeBasis) {
guard let transfer = sweeper.submit(estimatedFeeBasis: fee) else {
importingActivity.dismiss(animated: true)
return showErrorMessage(S.Alerts.sendFailure)
}
wallet.subscribe(self) { event in
guard case .transferSubmitted(let eventTransfer, let success) = event,
eventTransfer.hash == transfer.hash else { return }
DispatchQueue.main.async {
self.importingActivity.dismiss(animated: true) {
guard success else { return self.showErrorMessage(S.Import.Error.failedSubmit) }
self.markAsReclaimed()
self.showSuccess()
}
}
}
}
private func markAsReclaimed() {
guard let kvStore = Backend.kvStore else { return assertionFailure() }
guard let viewModel = viewModel else { return assertionFailure() }
guard let gift = viewModel.gift else { return assertionFailure() }
let newGift = Gift(shared: gift.shared,
claimed: gift.claimed,
reclaimed: true,
txnHash: gift.txnHash,
keyData: gift.keyData,
name: gift.name,
rate: gift.rate,
amount: gift.amount)
viewModel.tx.updateGiftStatus(gift: newGift, kvStore: kvStore)
if let hash = newGift.txnHash {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
Store.trigger(name: .txMetaDataUpdated(hash))
}
}
}
private func handleError(_ error: WalletSweeperError) {
switch error {
case .unsupportedCurrency:
showErrorMessage(S.Import.Error.unsupportedCurrency)
case .invalidKey:
showErrorMessage(S.Send.invalidAddressTitle)
case .invalidSourceWallet:
showErrorMessage(S.Send.invalidAddressTitle)
case .insufficientFunds:
showErrorMessage(S.Send.insufficientFunds)
case .unableToSweep:
showErrorMessage(S.Import.Error.sweepError)
case .noTransfersFound:
showErrorMessage(S.Import.Error.empty)
case .unexpectedError:
showErrorMessage(S.Alert.somethingWentWrong)
case .queryError(let error):
showErrorMessage(error.localizedDescription)
}
}
private func handleEstimateFeeError(_ error: WalletKit.Wallet.FeeEstimationError) {
switch error {
case .InsufficientFunds:
showErrorMessage(S.Send.insufficientFunds)
case .ServiceError:
showErrorMessage(S.Import.Error.serviceError)
case .ServiceUnavailable:
showErrorMessage(S.Import.Error.serviceUnavailable)
}
}
private func unlock(address: String, callback: @escaping (Key) -> Void) {
let alert = UIAlertController(title: S.Import.title, message: S.Import.password, preferredStyle: .alert)
alert.addTextField(configurationHandler: { textField in
textField.placeholder = S.Import.passwordPlaceholder
textField.isSecureTextEntry = true
textField.returnKeyType = .done
})
alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: S.Button.ok, style: .default, handler: { _ in
self.unlock(alert: alert, address: address, callback: callback)
}))
present(alert, animated: true)
}
private func unlock(alert: UIAlertController, address: String, callback: @escaping (Key) -> Void) {
present(self.unlockingActivity, animated: true, completion: {
guard let password = alert.textFields?.first?.text,
let key = Key.createFromString(asPrivate: address, withPassphrase: password) else {
self.unlockingActivity.dismiss(animated: true, completion: {
self.showErrorMessage(S.Import.wrongPassword)
})
return
}
self.unlockingActivity.dismiss(animated: true, completion: {
callback(key)
})
})
}
private func showSuccess() {
Store.perform(action: Alert.Show(.sweepSuccess(callback: { [weak self] in
guard let myself = self else { return }
myself.dismiss(animated: true)
})))
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 667027b1208286ad7f7fb3dc83167458 | 43.293939 | 112 | 0.635425 | false | false | false | false |
KenHeglund/Mustang | refs/heads/master | MustangApp/Mustang/Entity.swift | mit | 1 | /*===========================================================================
Entity.swift
Mustang
Copyright (c) 2020 OrderedBytes. All rights reserved.
===========================================================================*/
import Foundation
enum Entity {
/*==========================================================================*/
enum UsagePage {
static let entityName = "UsagePageEntity"
static let usagePageKey = "usagePage"
static let nameKey = "name"
static let usageNameFormatKey = "usageNameFormat"
static let usagesKey = "usages"
}
/*==========================================================================*/
enum Usage {
static let entityName = "UsageEntity"
static let usageKey = "usage"
static let nameKey = "name"
static let usagePageKey = "usagePage"
static let collectionTypeKey = "collectionType"
}
}
| fa1f17d567a3364484f8154a683b7e93 | 29.75 | 79 | 0.465738 | false | false | false | false |
someoneAnyone/Nightscouter | refs/heads/dev | Common/Views/CompassControl.swift | mit | 1 | //
// CompassView.swift
// Nightscout Watch Face
//
// Created by Peter Ina on 4/30/15.
// Copyright (c) 2015 Peter Ina. All rights reserved.
//
import UIKit
@IBDesignable
public class CompassControl: UIView {
@IBInspectable open var sgvText:String = "---" {
didSet{
setNeedsDisplay()
}
}
@objc var angle: CGFloat = 0
@objc var isUncomputable = false
@objc var isDoubleUp = false
@objc var isArrowVisible = false
@IBInspectable open var color: UIColor = NSAssetKit.predefinedNeutralColor {
didSet {
setNeedsDisplay()
}
}
open override var intrinsicContentSize : CGSize {
super.invalidateIntrinsicContentSize()
let compactSize = CGSize(width: 156, height: 120)
let midSize = CGSize(width: 156, height: 140)
let fullSize = CGSize(width: 156, height: 200)
switch direction {
case .none, .NotComputable, .Not_Computable:
return compactSize
case .FortyFiveUp, .FortyFiveDown, .Flat:
return compactSize
case .SingleUp, .SingleDown:
return midSize
default:
return fullSize
}
}
@objc var animationValue: CGFloat = 0
@IBInspectable open var delta: String = "- --/--" {
didSet{
setNeedsDisplay()
}
}
open var direction: Direction = .none {
didSet {
switch direction {
case .none:
configireDrawRect(isArrowVisible: false)
case .DoubleUp:
configireDrawRect(true)
case .SingleUp:
configireDrawRect()
case .FortyFiveUp:
configireDrawRect(angle:-45)
case .Flat:
configireDrawRect(angle:-90)
case .FortyFiveDown:
configireDrawRect(angle:-120)
case .SingleDown:
configireDrawRect(angle:-180)
case .DoubleDown:
configireDrawRect(true, angle: -180)
case .NotComputable, .Not_Computable:
configireDrawRect(isArrowVisible: false, isUncomputable: true)
case .RateOutOfRange:
configireDrawRect(isArrowVisible: false, isUncomputable: true, sgvText: direction.description)
}
invalidateIntrinsicContentSize()
setNeedsDisplay()
}
}
}
// MARK: - Lifecycle
public extension CompassControl {
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clear
isAccessibilityElement = true
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
NSAssetKit.drawTextBlock(frame: rect, arrowTintColor: self.color, sgvText: self.sgvText, bg_delta: self.delta, textSizeForSgv: 39, textSizeForDelta: 12)
if self.isUncomputable {
NSAssetKit.drawUncomputedCircle(rect, arrowTintColor:self.color, isUncomputable: self.isUncomputable, computeAnimation: self.animationValue)
} else {
NSAssetKit.drawWatchFaceOnly(rect, arrowTintColor: self.color, angle: self.angle, isArrowVisible: self.isArrowVisible, doubleUp: self.isDoubleUp)
}
accessibilityHint = "Glucose Value of \(sgvText) with a delta of \(delta), with the following direction \(direction)"
}
}
// MARK: - Methods
public extension CompassControl {
func configireDrawRect( _ isDoubleUp:Bool = false, isArrowVisible:Bool = true, isUncomputable:Bool = false, angle:CGFloat?=0, sgvText:String?=nil ){
self.isDoubleUp = isDoubleUp
self.isArrowVisible = isArrowVisible
self.isUncomputable = isUncomputable
self.angle = angle!
if (sgvText != nil) {
self.sgvText = sgvText!
}
}
@objc func takeSnapshot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
// MARK: - Delegate Methods
public extension CompassControl {
}
// MARK: - Actions
public extension CompassControl {
}
| 40a65968009cfaf03779ff379155e80d | 29.475862 | 160 | 0.602172 | false | true | false | false |
CodePath2017Group4/travel-app | refs/heads/master | RoadTripPlanner/TripDetailsViewController.swift | mit | 1 | //
// TripsDetailsViewController.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/12/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
import Parse
import ParseUI
import AFNetworking
import MessageUI
import MapKit
class TripDetailsViewController: UIViewController {
@IBOutlet weak var coverPhotoImageView: PFImageView!
@IBOutlet weak var tripNameLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var profileImageView: PFImageView!
@IBOutlet weak var tripDateLabel: UILabel!
@IBOutlet weak var emailGroupImageView: UIImageView!
@IBOutlet weak var editTableButton: UIButton!
@IBOutlet weak var addStopButton: UIButton!
@IBOutlet weak var addFriendsButton: UIButton!
@IBOutlet weak var viewOnMapButton: UIButton!
@IBOutlet weak var tripSettingsImageView: UIImageView!
@IBOutlet weak var albumImageView: UIImageView!
var trip: Trip?
static func storyboardInstance() -> TripDetailsViewController? {
let storyboard = UIStoryboard(name: String(describing: self), bundle: nil)
return storyboard.instantiateInitialViewController() as? TripDetailsViewController
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
tableView.separatorStyle = .none
profileImageView.layer.cornerRadius = profileImageView.frame.size.height / 2
profileImageView.clipsToBounds = true
profileImageView.layer.borderColor = UIColor.white.cgColor
profileImageView.layer.borderWidth = 3.0
// Make the navigation bar completely transparent.
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.tintColor = Constants.Colors.ColorPalette3314Color4
let textAttributes = [NSForegroundColorAttributeName:Constants.Colors.ColorPalette3314Color4]
navigationController?.navigationBar.titleTextAttributes = textAttributes
navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "md_settings"), style: .plain, target: self, action: #selector(tripSettingButtonPressed(_:)))
navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "md_home"), style: .plain, target: self, action: #selector(homeButtonPressed(_:)))
registerForNotifications()
guard let trip = trip else { return }
setUserInterfaceValues(trip: trip)
}
fileprivate func setUserInterfaceValues(trip: Trip) {
let creator = trip.creator
let tripDate = trip.date
tripDateLabel.text = Utils.formatDate(date: tripDate)
let avatarFile = creator.object(forKey: "avatar") as? PFFile
if avatarFile != nil {
profileImageView.file = avatarFile
profileImageView.loadInBackground()
}
tripNameLabel.text = trip.name
if let coverPhotoFile = trip.coverPhoto {
coverPhotoImageView.file = coverPhotoFile
coverPhotoImageView.loadInBackground()
}
tableView.reloadData()
}
fileprivate func registerForNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(TripDetailsViewController.tripWasModified(notification:)),
name: Constants.NotificationNames.TripModifiedNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func tripWasModified(notification: NSNotification) {
let info = notification.userInfo
let trip = info!["trip"] as! Trip
setUserInterfaceValues(trip: trip)
}
fileprivate func loadLandmarkImageFromDesitination(location: CLLocation) {
YelpFusionClient.sharedInstance.search(withLocation: location, term: "landmarks", completion: { (businesses, error) in
if error == nil {
guard let results = businesses else {
return
}
log.verbose("num landmark results: \(results.count)")
let randomIndex = Int(arc4random_uniform(UInt32(results.count)))
let b = results[randomIndex]
if let imageURL = b.imageURL {
log.info(imageURL)
let imageRequest = URLRequest(url: imageURL)
self.coverPhotoImageView.setImageWith(imageRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) in
if imageResponse != nil {
self.coverPhotoImageView.alpha = 0.0
self.coverPhotoImageView.image = image
let coverImageFile = Utils.imageToFile(image: image)!
self.trip?.setCoverPhoto(file: coverImageFile)
self.trip?.saveInBackground()
UIView.animate(withDuration: 0.3, animations: {
self.coverPhotoImageView.alpha = 0.8
})
}
}, failure: { (request, response, error) in
self.coverPhotoImageView.image = #imageLiteral(resourceName: "trip_placeholder")
log.error(error)
})
}
} else {
log.error(error ?? "unknown error occurred")
self.coverPhotoImageView.image = #imageLiteral(resourceName: "trip_placeholder")
}
})
}
fileprivate func setTripCoverPhoto() {
let destination = trip?.segments?.last
destination?.fetchInBackground(block: { (object, error) in
if error == nil {
let location = CLLocation(latitude: (destination?.geoPoint?.latitude)!, longitude: (destination?.geoPoint?.longitude)!)
self.loadLandmarkImageFromDesitination(location: location)
} else {
log.error(error!)
}
})
}
fileprivate func saveChanges() {
guard let trip = self.trip else { return }
trip.saveInBackground(block: { (success, error) in
if error == nil {
log.info("Trip save success: \(success)")
} else {
log.error("Error saving trip: \(error!)")
}
})
}
// MARK: - IBAction methods
@IBAction func editButtonPressed(_ sender: Any) {
if tableView.isEditing {
tableView.setEditing(false, animated: true)
editTableButton.setTitle(" Edit", for: .normal)
editTableButton.setTitleColor(UIColor.white, for: .normal)
saveChanges()
} else {
tableView.setEditing(true, animated: true)
editTableButton.setTitle(" Done", for: .normal)
let doneColor = UIColor(red: 234/255.0, green: 76/255.0, blue: 28/255.0, alpha: 1)
editTableButton.setTitleColor(doneColor, for: .normal)
}
// Disable other buttons if we are editing the table.
addStopButton.isEnabled = !tableView.isEditing
addFriendsButton.isEnabled = !tableView.isEditing
viewOnMapButton.isEnabled = !tableView.isEditing
}
@IBAction func tripSettingButtonPressed(_ sender: Any) {
showAlertController()
}
@IBAction func homeButtonPressed(_ sender: Any) {
// Unwind to the root view controller.
navigationController?.popToRootViewController(animated: true)
}
@IBAction func mapButtonPressed(_ sender: Any) {
// Create a locations array from the trip segments. Locations array consists of tuples of UITextFields and MKMapItem objects.
guard let trip = trip else { return }
var locations: [(textField: UITextField?, mapItem: MKMapItem?)] = []
if let segments = trip.segments {
for segment in segments {
let address = segment.address
let lat = segment.geoPoint?.latitude
let lng = segment.geoPoint?.longitude
let location = CLLocation(latitude: lat!, longitude: lng!)
let placemark = MKPlacemark(coordinate: location.coordinate)
let mapItem = MKMapItem(placemark: placemark) as MKMapItem?
let textField = UITextField(frame: CGRect.zero) as UITextField?
textField?.text = address
let tuple = (textField: textField, mapItem: mapItem)
locations.append(tuple)
}
}
// Launch the map screen.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let routeMapViewController = storyboard.instantiateViewController(withIdentifier: "RouteMapView") as! RouteMapViewController
routeMapViewController.trip = trip
routeMapViewController.locationArray = locations
routeMapViewController.termCategory = ["restaurant" : ["restaurant"]]
routeMapViewController.loadTripOnMap = true
navigationController?.pushViewController(routeMapViewController, animated: true)
}
@IBAction func addFriendsButtonPressed(_ sender: Any) {
guard let friendsVC = FriendsListViewController.storyboardInstance() else { return }
friendsVC.trip = trip
navigationController?.pushViewController(friendsVC, animated: true)
}
@IBAction func addStopButtonPressed(_ sender: Any) {
// Present the AddStopViewController modally.
guard let addStopVC = AddStopViewController.storyboardInstance() else { return }
addStopVC.trip = trip
present(addStopVC, animated: true, completion: nil)
}
func emailImageTapped(_ sender: AnyObject) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.present(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients([])
if #available(iOS 11.0, *) {
let fromEmail = trip?.creator.email != nil ? "\((trip?.creator.email)!)" : ""
mailComposerVC.setPreferredSendingEmailAddress("\(fromEmail)")
}
var emailSubject = User.currentUser?.userName != nil ? "\((User.currentUser?.userName)!)'s" :""
emailSubject += trip?.name != nil ? "\((trip?.name)!)" : "My Road Trip"
mailComposerVC.setSubject("\(emailSubject) !")
mailComposerVC.setMessageBody("\(Constants.PrefabricatedEmailMessage.TripInvitationEmail)", isHTML: true)
return mailComposerVC
}
func showSendMailErrorAlert() {
let alert = UIAlertController(
title: "Could Not Send Email",
message: "Your device could not send Email. Please check Email configuration and try again.",
preferredStyle: .alert
)
let okAction = UIAlertAction(
title: "OK",
style: .default,
handler: nil
)
alert.addAction(okAction)
present(
alert,
animated: true,
completion: nil
)
}
// MARK: - UIAlertController action sheet
func showAlertController() {
let alert = UIAlertController()
alert.addAction(UIAlertAction(title: NSLocalizedString("Trip Settings", comment: "Default action"), style: .`default`, handler: { _ in
log.verbose("Trip Settings selected")
self.showSettings()
}))
// alert.addAction(UIAlertAction(title: "Write a Review", style: .default, handler: { _ in
// log.verbose("Review selected")
// }))
alert.addAction(UIAlertAction(title: "Delete Trip", style: .destructive, handler: { _ in
log.verbose("Delete Trip selected")
self.deleteTrip()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in
log.verbose("Cancel selected")
}))
self.present(alert, animated: true, completion: nil)
}
// MARK: - Action sheet action handlers
func showSettings() {
guard let settingsVC = TripSettingsViewController.storyboardInstance() else { return }
settingsVC.trip = trip
navigationController?.pushViewController(settingsVC, animated: true)
}
func deleteTrip() {
// Confirm they want the trip deleted.
let alert = UIAlertController(title: "Delete Trip?", message: "Are you sure you would like to delete this trip?", preferredStyle: .alert)
let noAction = UIAlertAction(title: "No", style: .default, handler: { _ in
log.verbose("No selected")
})
let confirmAction = UIAlertAction(title: "I'm Sure!", style: .default, handler: { _ in
log.verbose("Delete confirmed")
self.trip?.deleteInBackground(block: { (success, error) in
if error == nil {
log.info("Trip deletion success: \(success)")
if success {
// Post a notification that the trip has been deleted.
NotificationCenter.default.post(name: Constants.NotificationNames.TripDeletedNotification, object: nil, userInfo: ["trip": self.trip!])
// Return to the previous screen.
self.navigationController?.popViewController(animated: true)
}
} else {
log.error("Error deleting trip: \(error!)")
}
})
})
alert.addAction(noAction)
alert.addAction(confirmAction)
alert.preferredAction = noAction
self.present(alert, animated: true, completion: nil)
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension TripDetailsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let trip = self.trip else { return 0 }
guard let segments = trip.segments else { return 0 }
return segments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.ReuseableCellIdentifiers.TripSegmentCell, for: indexPath) as! TripSegmentCell
cell.tripSegment = trip?.segments?[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 68
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Let all cells be reordered.
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard let trip = self.trip else { return }
guard var segments = trip.segments else { return }
let tripSegmentToMove = segments[sourceIndexPath.row]
segments.remove(at: sourceIndexPath.row)
segments.insert(tripSegmentToMove, at: destinationIndexPath.row)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard let trip = self.trip else { return }
if editingStyle == .delete {
tableView.beginUpdates()
// Remove the segment from the segments array.
trip.deleteSegment(atIndex: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
saveChanges()
// Post a notification that the trip has been modified
NotificationCenter.default.post(name: Constants.NotificationNames.TripModifiedNotification, object: nil, userInfo: ["trip": trip])
}
}
}
// MARK: - TripDetailsCellDelegate
extension TripDetailsViewController: TripDetailsCellDelegate {
func tripDetailsCell(tripDetailsCell: TripDetailsCell, didComment tripStopLabel: UILabel) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let compmentsViewController = storyboard.instantiateViewController(withIdentifier: "compose") as! CommentsViewController
self.navigationController?.pushViewController(compmentsViewController, animated: true)
}
}
extension TripDetailsViewController: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
| eff48d263b6f2e843cebee9661dbc6a3 | 38.624724 | 188 | 0.615209 | false | false | false | false |
mercadopago/px-ios | refs/heads/develop | MercadoPagoSDK/MercadoPagoSDK/LaytoutExtension/Dimension/AnchorDimension.swift | mit | 1 | import UIKit
final class AnchorDimension: AnchorDimensionComposing {
let anchor: NSLayoutDimension
let type: AnchorType
let root: AnchoringRoot
init(
anchor: NSLayoutDimension,
root: AnchoringRoot,
type: AnchorType
) {
self.anchor = anchor
self.type = type
self.root = root
self.root.translatesAutoresizingMaskIntoConstraints = false
}
@discardableResult
func equalTo(
_ otherConstraint: AnchorDimension,
multiplier: CGFloat = 1.0,
constant: CGFloat = 0.0,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
let constraint = anchor.constraint(
equalTo: otherConstraint.anchor,
multiplier: multiplier,
constant: constant
)
return prepare(constraint, with: priority)
}
@discardableResult
func lessThanOrEqualTo(
_ otherConstraint: AnchorDimension,
multiplier: CGFloat = 1.0,
constant: CGFloat = 0.0,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
let constraint = anchor.constraint(
lessThanOrEqualTo: otherConstraint.anchor,
multiplier: multiplier,
constant: constant
)
return prepare(constraint, with: priority)
}
@discardableResult
func greaterThanOrEqualTo(
_ otherConstraint: AnchorDimension,
multiplier: CGFloat = 1.0,
constant: CGFloat = 0.0,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
let constraint = anchor.constraint(
greaterThanOrEqualTo: otherConstraint.anchor,
multiplier: multiplier,
constant: constant
)
return prepare(constraint, with: priority)
}
@discardableResult
func equalTo(
constant: CGFloat,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
let constraint = anchor.constraint(equalToConstant: constant)
return prepare(constraint, with: priority)
}
@discardableResult
func lessThanOrEqualTo(
constant: CGFloat,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
let constraint = anchor.constraint(lessThanOrEqualToConstant: constant)
return prepare(constraint, with: priority)
}
@discardableResult
func greaterThanOrEqualTo(
constant: CGFloat,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
let constraint = anchor.constraint(greaterThanOrEqualToConstant: constant)
return prepare(constraint, with: priority)
}
@discardableResult
func equalTo(
_ root: AnchoringRoot,
multiplier: CGFloat = 1.0,
constant: CGFloat = 0.0,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
equalTo(
anchorFor(root: root),
multiplier: multiplier,
constant: constant,
priority: priority
)
}
@discardableResult
func lessThanOrEqualTo(
_ root: AnchoringRoot,
multiplier: CGFloat = 1.0,
constant: CGFloat = 0.0,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
lessThanOrEqualTo(
anchorFor(root: root),
multiplier: multiplier,
constant: constant,
priority: priority
)
}
@discardableResult
func greaterThanOrEqualTo(
_ root: AnchoringRoot,
multiplier: CGFloat = 1.0,
constant: CGFloat = 0.0,
priority: UILayoutPriority = .required
) -> NSLayoutConstraint {
greaterThanOrEqualTo(
anchorFor(root: root),
multiplier: multiplier,
constant: constant,
priority: priority
)
}
}
private extension AnchorDimension {
func anchorFor(root: AnchoringRoot) -> AnchorDimension {
switch type {
case .width:
return root.width
case .height:
return root.height
default:
preconditionFailure("Could not resolve \(type) anchor for this root \(root)")
}
}
func prepare(
_ constraint: NSLayoutConstraint,
with priority: UILayoutPriority
) -> NSLayoutConstraint {
constraint.priority = priority
constraint.isActive = true
return constraint
}
}
| 5cfc4f18fbc0d29e82ee026a6adcd6b3 | 27.55414 | 89 | 0.611421 | false | false | false | false |
JGiola/swift | refs/heads/main | test/SILGen/protocol_class_refinement.swift | apache-2.0 | 9 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
protocol UID {
func uid() -> Int
var clsid: Int { get set }
var iid: Int { get }
}
extension UID {
var nextCLSID: Int {
get { return clsid + 1 }
set { clsid = newValue - 1 }
}
}
protocol ObjectUID : class, UID {}
extension ObjectUID {
var secondNextCLSID: Int {
get { return clsid + 2 }
set { }
}
}
class Base {}
// CHECK-LABEL: sil hidden [ossa] @$s25protocol_class_refinement12getObjectUID{{[_0-9a-zA-Z]*}}F
func getObjectUID<T: ObjectUID>(x: T) -> (Int, Int, Int, Int) {
var x = x
// CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ObjectUID> { var τ_0_0 } <T>
// CHECK: [[XLIFETIME:%[^,]+]] = begin_borrow [lexical] [[XBOX]]
// CHECK: [[PB:%.*]] = project_box [[XLIFETIME]]
// -- call x.uid()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid :
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call set x.clsid
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter
// CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]])
x.clsid = x.uid()
// -- call x.uid()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid :
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call nextCLSID from protocol ext
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @$s25protocol_class_refinement3UIDPAAE9nextCLSIDSivs
// CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]])
x.nextCLSID = x.uid()
// -- call x.uid()
// CHECK: [[READ1:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X1:%.*]] = load [copy] [[READ1]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid :
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call secondNextCLSID from class-constrained protocol ext
// CHECK: [[SET_SECONDNEXT:%.*]] = function_ref @$s25protocol_class_refinement9ObjectUIDPAAE15secondNextCLSIDSivs
// CHECK: apply [[SET_SECONDNEXT]]<T>([[UID]], [[X1]])
// CHECK: destroy_value [[X1]]
x.secondNextCLSID = x.uid()
return (x.iid, x.clsid, x.nextCLSID, x.secondNextCLSID)
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s25protocol_class_refinement16getBaseObjectUID{{[_0-9a-zA-Z]*}}F
func getBaseObjectUID<T: UID>(x: T) -> (Int, Int, Int) where T: Base {
var x = x
// CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Base, τ_0_0 : UID> { var τ_0_0 } <T>
// CHECK: [[XLIFETIME:%[^,]+]] = begin_borrow [lexical] [[XBOX]]
// CHECK: [[PB:%.*]] = project_box [[XLIFETIME]]
// -- call x.uid()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid :
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call set x.clsid
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter
// CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]])
x.clsid = x.uid()
// -- call x.uid()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid :
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call nextCLSID from protocol ext
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @$s25protocol_class_refinement3UIDPAAE9nextCLSIDSivs
// CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]])
x.nextCLSID = x.uid()
return (x.iid, x.clsid, x.nextCLSID)
// CHECK: return
}
| 38f8f790e60aa05045877321ab72aa9a | 38.613445 | 115 | 0.539457 | false | false | false | false |
JeeLiu/Mirror | refs/heads/master | API_Moya/Pods/Nimble/Nimble/Adapters/AssertionRecorder.swift | apache-2.0 | 28 | import Foundation
/// A data structure that stores information about an assertion when
/// AssertionRecorder is set as the Nimble assertion handler.
///
/// @see AssertionRecorder
/// @see AssertionHandler
public struct AssertionRecord: Printable {
/// Whether the assertion succeeded or failed
public let success: Bool
/// The failure message the assertion would display on failure.
public let message: FailureMessage
/// The source location the expectation occurred on.
public let location: SourceLocation
public var description: String {
return "AssertionRecord { success=\(success), message='\(message.stringValue)', location=\(location) }"
}
}
/// An AssertionHandler that silently records assertions that Nimble makes.
/// This is useful for testing failure messages for matchers.
///
/// @see AssertionHandler
public class AssertionRecorder : AssertionHandler {
/// All the assertions that were captured by this recorder
public var assertions = [AssertionRecord]()
public init() {}
public func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) {
assertions.append(
AssertionRecord(
success: assertion,
message: message,
location: location))
}
}
/// Allows you to temporarily replace the current Nimble assertion handler with
/// the one provided for the scope of the closure.
///
/// Once the closure finishes, then the original Nimble assertion handler is restored.
///
/// @see AssertionHandler
public func withAssertionHandler(tempAssertionHandler: AssertionHandler, closure: () -> Void) {
let oldRecorder = NimbleAssertionHandler
let capturer = NMBExceptionCapture(handler: nil, finally: ({
NimbleAssertionHandler = oldRecorder
}))
NimbleAssertionHandler = tempAssertionHandler
capturer.tryBlock {
closure()
}
}
/// Captures expectations that occur in the given closure. Note that all
/// expectations will still go through to the default Nimble handler.
///
/// This can be useful if you want to gather information about expectations
/// that occur within a closure.
///
/// @param silently expectations are no longer send to the default Nimble
/// assertion handler when this is true. Defaults to false.
///
/// @see gatherFailingExpectations
public func gatherExpectations(silently: Bool = false, closure: () -> Void) -> [AssertionRecord] {
let previousRecorder = NimbleAssertionHandler
var recorder = AssertionRecorder()
let handlers: [AssertionHandler]
if silently {
handlers = [recorder]
} else {
handlers = [recorder, previousRecorder]
}
var dispatcher = AssertionDispatcher(handlers: handlers)
withAssertionHandler(dispatcher, closure)
return recorder.assertions
}
/// Captures failed expectations that occur in the given closure. Note that all
/// expectations will still go through to the default Nimble handler.
///
/// This can be useful if you want to gather information about failed
/// expectations that occur within a closure.
///
/// @param silently expectations are no longer send to the default Nimble
/// assertion handler when this is true. Defaults to false.
///
/// @see gatherExpectations
/// @see raiseException source for an example use case.
public func gatherFailingExpectations(silently: Bool = false, closure: () -> Void) -> [AssertionRecord] {
let assertions = gatherExpectations(silently: silently, closure)
return filter(assertions) { assertion in
!assertion.success
}
} | f015455f5d1a3e42be72e4f6613a9d50 | 35.59596 | 111 | 0.713142 | false | false | false | false |
EmberTown/ember-hearth | refs/heads/master | Ember Hearth/Terminal.swift | mit | 1 | //
// Terminal.swift
// Ember Hearth
//
// Created by Thomas Sunde Nielsen on 29.03.15.
// Copyright (c) 2015 Thomas Sunde Nielsen. All rights reserved.
//
import Cocoa
enum InstallMethod: String {
case Hearth = "Hearth"
case NPM = "NPM"
case Bower = "Bower"
case Brew = "Homebrew"
case Unknown = "Unknown"
case NotInstalled = "Not installed"
}
public class Terminal {
private var task: NSTask?
private var output: NSPipe?
public var workingDirectory: String?
public init() { }
func taskForCommand (command: String) -> NSTask {
var task = NSTask()
task.launchPath = "/bin/bash"
task.arguments = ["-l", "-c", command]
return task
}
public func runTerminalCommandSync (command: String) -> String? {
var task = taskForCommand(command)
var findOut = NSPipe()
task.standardOutput = findOut
task.launch()
task.waitUntilExit()
let outData = findOut.fileHandleForReading.readDataToEndOfFile()
let result = NSString(data: outData, encoding: NSASCIIStringEncoding)
if task.terminationStatus == 0 {
return result as? String
}
return nil
}
public func runTerminalCommandAsync (command: String, completion: (result: String?) -> ()) -> NSTask? {
return self.runTerminalCommandAsync(command, showOutput: true, completion: completion)
}
public func runTerminalCommandAsync (command: String, showOutput:Bool, completion: (result: String?) -> ()) -> NSTask? {
self.task = taskForCommand(command)
if self.workingDirectory != nil {
self.task?.currentDirectoryPath = self.workingDirectory!
}
if showOutput {
self.output = NSPipe()
self.task?.standardOutput = self.output!
}
self.task?.terminationHandler = { (task: NSTask!) in
if task.terminationStatus != 0 {
completion(result: nil)
} else {
let outData = self.output?.fileHandleForReading.readDataToEndOfFile()
var result: NSString = ""
if outData != nil {
if let string = NSString(data: outData!, encoding: NSASCIIStringEncoding) {
result = string
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(result: result as String)
})
}
self.task = nil
self.output = nil
}
self.task?.launch()
return self.task
}
public func runTerminalCommandInTerminalApp(command:String, path:String) {
NSAppleScript(source: "tell application \"Terminal\"\n" +
" do script \"cd '\(path)' && \(command)\"\n" +
" activate\n" +
"end tell"
)?.executeAndReturnError(nil)
}
}
| d88880cc6f71907ae7002d2eecd86395 | 30.464646 | 124 | 0.54382 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.