repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
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
ITzTravelInTime/TINU
refs/heads/development
TINU/IconsManager.swift
gpl-2.0
1
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Cocoa import TINURecovery import SwiftPackagesBase public struct SFSymbol: Hashable, Codable, Copying, Equatable{ private let name: String public var description: String? = nil @available(macOS 11.0, *) public static var defaultWeight: NSFont.Weight = .light public init(name: String, description: String? = nil){ self.name = name self.description = description } public init(symbol: SFSymbol){ self.name = symbol.name self.description = symbol.description } public func copy() -> SFSymbol { return SFSymbol(symbol: self) } public func adding(attribute: String) -> SFSymbol?{ if #available(macOS 11.0, *){ if name.contains(".\(attribute)"){ return copy() } let segmented = self.name.split(separator: ".") for i in (0...segmented.count).reversed(){ var str = "" for k in 0..<i{ str += ".\(segmented[k])" } if !str.isEmpty{ str.removeFirst() } str += ".\(attribute)" if i <= segmented.count{ for k in i..<segmented.count{ str += ".\(segmented[k])" } } //Really unefficient way of checking if a symbol exists if NSImage(systemSymbolName: str, accessibilityDescription: nil) != nil{ return SFSymbol(name: str, description: description) } } } return nil } public func fill() -> SFSymbol?{ return adding(attribute: "fill") } public func circular() -> SFSymbol?{ return adding(attribute: "circle") } public func triangular() -> SFSymbol?{ return adding(attribute: "triangle") } public func octagonal() -> SFSymbol?{ return adding(attribute: "octagon") } public func duplicated() -> SFSymbol?{ return adding(attribute: "2") } public func image(accessibilityDescription: String? = nil) -> NSImage?{ if #available(macOS 11.0, *) { return NSImage(systemSymbolName: self.name, accessibilityDescription: accessibilityDescription)?.withSymbolWeight(Self.defaultWeight) } else { return nil } } public func imageWithSystemDefaultWeight(accessibilityDescription: String? = nil) -> NSImage?{ if #available(macOS 11.0, *) { return NSImage(systemSymbolName: self.name, accessibilityDescription: accessibilityDescription) } else { return nil } } } public struct Icon: Hashable, Codable, Equatable{ public init(path: String? = nil, symbol: SFSymbol? = nil, imageName: String? = nil, alternativeImage: Data? = nil) { assert(imageName != nil || path != nil || alternativeImage != nil || symbol != nil, "This is not a valid configuration for an icon") self.path = path self.symbol = symbol self.imageName = imageName self.alternativeImage = alternativeImage } public init(path: String?, symbol: SFSymbol?, imageName: String?, alternative: NSImage?) { assert(imageName != nil || path != nil || alternative != nil || symbol != nil, "This is not a valid configuration for an icon") self.path = path self.symbol = symbol self.imageName = imageName self.alternativeImage = alternative?.tiffRepresentation } public init(symbol: SFSymbol) { self.symbol = symbol } public init(symbolName: String) { self.symbol = SFSymbol(name: symbolName) } public init(imageName: String) { self.imageName = imageName } public init(alternativeImage: Data?) { self.alternativeImage = alternativeImage } private var path: String? = nil private var symbol: SFSymbol? = nil private var imageName: String? = nil private var alternativeImage: Data? = nil private var alternative: NSImage?{ get{ guard let alt = alternativeImage else { return nil } return NSImage(data: alt) } set{ alternativeImage = newValue?.tiffRepresentation } } public var sfSymbol: SFSymbol?{ return symbol } public func normalImage() -> NSImage?{ assert(imageName != nil || path != nil || alternativeImage != nil) var image: NSImage? if imageName != nil{ assert(imageName != "", "The image name must be a valid image name") image = NSImage(named: imageName!) } if image == nil && path != nil{ assert(path != "", "The path must be a valid path") //Commented this to allow for testing if an image exists and then if not use the alternate image //assert(FileManager.default.fileExists(atPath: path!), "The specified path must be the one of a file that exists") image = NSImage(contentsOfFile: path!) } if image == nil && alternativeImage != nil{ image = alternative } return image } public func sFSymbolImage() -> NSImage?{ return symbol?.image() } public func themedImage() -> NSImage?{ if #available(macOS 11.0, *),symbol != nil && look.usesSFSymbols(){ if look.usesFilledSFSymbols(){ return symbol?.fill()?.image() ?? normalImage() } return sFSymbolImage() ?? normalImage() } return normalImage() } } public final class IconsManager{ public static let shared = IconsManager() //warning icon used by the app public var warningIcon: Icon{ //return getIconFor(path: "", symbol: "exclamationmark.triangle", name: NSImage.cautionName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "exclamationmark.triangle"), imageName: NSImage.cautionName) } return Mem.icon! } public var roundWarningIcon: Icon{ //return getIconFor(path: "", symbol: "exclamationmark.circle", name: NSImage.cautionName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "exclamationmark").circular(), imageName: NSImage.cautionName) } return Mem.icon! } //stop icon used by the app public var stopIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns", symbol: "xmark.octagon", name: "uncheck") struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns", symbol: SFSymbol(name: "xmark").octagonal(), imageName: "uncheck") } return Mem.icon! } public var roundStopIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns", symbol: "xmark.circle", name: "uncheck") struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns", symbol: SFSymbol(name: "xmark").circular(), imageName: "uncheck") } return Mem.icon! } public var checkIcon: Icon{ //return getIconFor(path: "", symbol: "checkmark.circle", name: "checkVector") struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "checkmark").circular(), imageName: "checkVector") } return Mem.icon! } public var copyIcon: Icon{ //return getIconFor(path: "", symbol: "doc.on.doc", name: NSImage.multipleDocumentsName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "doc.on.doc"), imageName: NSImage.multipleDocumentsName) } return Mem.icon! } public var saveIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocumentIcon.icns", symbol: "tray.and.arrow.down", name: NSImage.multipleDocumentsName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocumentIcon.icns", symbol: SFSymbol(name: "tray.and.arrow.down"), imageName: NSImage.multipleDocumentsName) } return Mem.icon! } public var removableDiskIcon: Icon{ //return getIconFor(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/Removable.icns", symbol: "externaldrive", name: "Removable") struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/Removable.icns", symbol: SFSymbol(name: "externaldrive"), imageName: "Removable") } return Mem.icon! } public var externalDiskIcon: Icon{ //return getIconFor(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/External.icns", symbol: "externaldrive", alternate: removableDiskIcon) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/External.icns", symbol: SFSymbol(name: "externaldrive"), imageName: nil, alternative: removableDiskIcon.normalImage()) } return Mem.icon! } public var internalDiskIcon: Icon{ //return getIconFor(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/Internal.icns", symbol: "internaldrive", alternate: removableDiskIcon) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/Internal.icns", symbol: SFSymbol(name: "internaldrive"), imageName: "internaldrive", alternative: removableDiskIcon.normalImage()) } return Mem.icon! } public var timeMachineDiskIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericTimeMachineDiskIcon.icns", symbol: "externaldrive.badge.timemachine", alternate: removableDiskIcon) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericTimeMachineDiskIcon.icns", symbol: SFSymbol(name: "externaldrive.badge.timemachine"), imageName: nil, alternative: removableDiskIcon.normalImage()) } return Mem.icon! } public var genericInstallerAppIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericApplicationIcon.icns", symbol: "square.and.arrow.down", name: "InstallApp", alternateFirst: true) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericApplicationIcon.icns", symbol: SFSymbol(name: "square.and.arrow.down"), imageName: "InstallApp") } return Mem.icon! } public var optionsIcon: Icon{ //return getIconFor(path: "", symbol: "gearshape", name: NSImage.preferencesGeneralName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "gearshape"), imageName: NSImage.preferencesGeneralName) } return Mem.icon! } public var advancedOptionsIcon: Icon{ //return getIconFor(path: "", symbol: "gearshape.2", name: NSImage.advancedName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "gearshape").duplicated(), imageName: NSImage.advancedName) } return Mem.icon! } public var folderIcon: Icon{ //return getIconFor(path: "", symbol: "folder", name: NSImage.folderName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "folder"), imageName: NSImage.folderName) } return Mem.icon! } //return the icon of thespecified installer app func getInstallerAppIconFrom(path app: String) ->NSImage{ let iconp = app + "/Contents/Resources/InstallAssistant.icns" if FileManager.default.fileExists(atPath: iconp){ if let i = NSImage(contentsOfFile: iconp){ return i } } return NSWorkspace.shared.icon(forFile: app) } /* //gets an icon from a file, if the file do not exists, it uses an icon from the assets public func getIconFor(path: String, symbol: String, name: String, alternateFirst: Bool = false) -> NSImage!{ return getIconFor(path: path, symbol: symbol, alternate: NSImage(named: name), alternateFirst: alternateFirst) } //TODO: caching for icons from the file system public func getIconFor(path: String, symbol: String, alternate: NSImage! = nil, alternateFirst: Bool = false) -> NSImage!{ if #available(macOS 11.0, *), look.usesSFSymbols() && !symbol.isEmpty{ var ret = NSImage(systemSymbolName: symbol + (look.usesFilledSFSymbols() && !symbol.contains(".fill") ? ".fill" : ""), accessibilityDescription: nil) if ret == nil{ ret = NSImage(systemSymbolName: symbol, accessibilityDescription: nil) } ret?.isTemplate = true return ret } if path.isEmpty{ return alternate } if FileManager.default.fileExists(atPath: path) && !(alternate != nil && alternateFirst){ return NSImage(contentsOfFile: path) }else{ return alternate } } */ public func getCorrectDiskIcon(_ id: BSDID) -> NSImage{ if id.isVolume{ if let mount = id.mountPoint(){ if !(mount.isEmpty){ if FileManager.default.directoryExists(atPath: mount + "/Backups.backupdb"){ return timeMachineDiskIcon.themedImage()! }else{ if FileManager.default.fileExists(atPath: mount + "/.VolumeIcon.icns"){ return NSWorkspace.shared.icon(forFile: mount) } } } } } var image = IconsManager.shared.removableDiskIcon if let i = id.isRemovable(){ if !i{ image = IconsManager.shared.internalDiskIcon }else if let i = id.isExternalHardDrive(){ if !i{ image = IconsManager.shared.externalDiskIcon } } } return image.themedImage()! } }
466a585b0ee691f6b212595a20d306d9
27.693069
245
0.695514
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/Notice.swift
mit
1
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** A notice produced for the collection. */ public struct Notice: Decodable { /// Severity level of the notice. public enum Severity: String { case warning = "warning" case error = "error" } /// Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. public var noticeID: String? /// The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. public var created: String? /// Unique identifier of the document. public var documentID: String? /// Unique identifier of the query used for relevance training. public var queryID: String? /// Severity level of the notice. public var severity: String? /// Ingestion or training step in which the notice occurred. public var step: String? /// The description of the notice. public var description: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case noticeID = "notice_id" case created = "created" case documentID = "document_id" case queryID = "query_id" case severity = "severity" case step = "step" case description = "description" } }
48651151f7e9fa5b551bcc2b0aaac8b3
32.216667
188
0.69142
false
false
false
false
alirsamar/BiOS
refs/heads/master
RobotMaze2/Maze/MazeActor.swift
mit
1
// // MovingObject.swift // Maze // // Created by Jarrod Parkes on 8/14/15. // Copyright © 2015 Udacity, Inc. All rights reserved. // import UIKit // MARK: - MazeActor class MazeActor: MazeObject { // MARK: Properities var location: MazeLocation var direction: MazeDirection var view: UIView var mazeController: MazeController? let objectSize = CGSize(width: 50, height: 50) let queueManager = QueueManager.sharedManager // MARK: Initializers init(location: MazeLocation, direction: MazeDirection) { self.location = location self.direction = direction self.view = SimpleRobotView() self.view.opaque = false if self.direction != MazeDirection.Up { self.view.transform = CGAffineTransformRotate(self.view.transform, CGFloat(M_PI_2) * CGFloat(self.direction.rawValue)) } } init(location: MazeLocation, direction: MazeDirection, imagePath: String) { self.location = location self.direction = direction self.view = UIView(frame: CGRectMake(0, 0, objectSize.width, objectSize.height)) self.view.opaque = false if let image = UIImage(named: imagePath) { let imageView = UIImageView(image: image) imageView.frame = self.view.frame self.view.addSubview(imageView) } if self.direction != MazeDirection.Up { self.view.transform = CGAffineTransformRotate(self.view.transform, CGFloat(M_PI_2) * CGFloat(self.direction.rawValue)) } } // MARK: Enqueue MazeMovesOperation (NSOperation) func rotate(rotateDirection: RotateDirection, completionHandler: (() -> Void)? = nil) { if rotateDirection == RotateDirection.Left { if direction.rawValue > 0 { direction = MazeDirection(rawValue: direction.rawValue - 1)! } else { direction = MazeDirection.Left } } else if rotateDirection == RotateDirection.Right { if direction.rawValue < 3 { direction = MazeDirection(rawValue: direction.rawValue + 1)! } else { direction = MazeDirection.Up } } let move = MazeMove(coords: Move(dx: 0, dy: 0), rotateDirection: rotateDirection) enqueueMove(move, completionHandler: completionHandler) } func move(moveDirection: MazeDirection, moves: Int, completionHandler: (() -> Void)? = nil) { if moveDirection != self.direction { var movesToRotate = moveDirection.rawValue - self.direction.rawValue if movesToRotate == 3 { movesToRotate = -1 } else if movesToRotate == -3 { movesToRotate = 1 } for _ in 0..<abs(movesToRotate) { rotate((movesToRotate > 0) ? RotateDirection.Right : RotateDirection.Left, completionHandler: completionHandler) } } let dx = (moveDirection == MazeDirection.Right) ? 1 : ((moveDirection == MazeDirection.Left) ? -1 : 0) let dy = (moveDirection == MazeDirection.Up) ? -1 : ((moveDirection == MazeDirection.Down) ? 1 : 0) for var i = 0; i < moves; ++i { let move = MazeMove(coords: Move(dx: dx, dy: dy), rotateDirection: .None) enqueueMove(move, completionHandler: completionHandler) } } func enqueueMove(move: MazeMove, completionHandler: (() -> Void)? = nil) { guard let mazeController = mazeController else { return } let operation = MazeMoveOperation(object: self, move: move, mazeController: mazeController) queueManager.addDependentMove(operation) if let completionHandler = completionHandler { completionHandler() } } } extension MazeActor: Hashable { var hashValue: Int { return self.view.hashValue } }
b9159856c65e093f14ca4a96450cf8bd
35.745283
130
0.619928
false
false
false
false
andr3a88/TryNetworkLayer
refs/heads/master
TryNetworkLayer/Controllers/Users/UsersCoordinator.swift
mit
1
// // UsersCoordinator.swift // TryNetworkLayer // // Created by Andrea Stevanato on 13/03/2020. // Copyright © 2020 Andrea Stevanato. All rights reserved. // import UIKit final class UsersCoordinator: Coordinator { var window: UIWindow var navigationController: UINavigationController! var userDetailCoordinator: UserDetailCoordinator? init(window: UIWindow) { self.window = window } func start() { let usersViewController = Storyboard.main.instantiate(UsersViewController.self) usersViewController.viewModel = UsersViewModel() usersViewController.viewModel.coordinatorDelegate = self self.navigationController = UINavigationController(rootViewController: usersViewController) self.window.rootViewController = navigationController } } extension UsersCoordinator: UsersViewModelCoordinatorDelegate { func usersViewModelPresent(user: GHUser) { userDetailCoordinator = UserDetailCoordinator(navigationController: navigationController, user: user) userDetailCoordinator?.start() } }
e07e18b44832933b9fa156deef29d75b
28.72973
109
0.741818
false
false
false
false
alobanov/ALFormBuilder
refs/heads/master
Sources/FormBuilder/FormItemsComposite/sections/SectionFormComposite.swift
mit
1
// // SectionFormItemComposite.swift // ALFormBuilder // // Created by Lobanov Aleksey on 26/10/2017. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import Foundation public protocol SectionFormCompositeOutput { var header: String? {get} var footer: String? {get} } public class SectionFormComposite: FormItemCompositeProtocol, SectionFormCompositeOutput { // MARK: - SectionFormCompositeOutput public var header: String? public var footer: String? // MARK: - Provate propery private let decoratedComposite: FormItemCompositeProtocol // MARK: - FormItemCompositeProtocol properties public var identifier: String { return self.decoratedComposite.identifier } public var children: [FormItemCompositeProtocol] { return self.decoratedComposite.children } public var datasource: [FormItemCompositeProtocol] { return self.decoratedComposite.children.flatMap { $0.datasource } } public var leaves: [FormItemCompositeProtocol] { return self.decoratedComposite.leaves.flatMap { $0.leaves } } public var level: ALFB.FormModelLevel = .section public init(composite: FormItemCompositeProtocol, header: String?, footer: String?) { self.decoratedComposite = composite self.header = header self.footer = footer } // MARK :- FormItemCompositeProtocol methods public func add(_ model: FormItemCompositeProtocol...) { for item in model { if item.level != .section { self.decoratedComposite.add(item) } else { print("You can`t add section in other section") } } } public func remove(_ model: FormItemCompositeProtocol) { self.decoratedComposite.remove(model) } }
8c620e36e8f3638979acdafd5c656cdc
25.828125
90
0.716948
false
false
false
false
efremidze/NumPad
refs/heads/master
Example/ViewController.swift
mit
1
// // ViewController.swift // Example // // Created by Lasha Efremidze on 5/27/16. // Copyright © 2016 Lasha Efremidze. All rights reserved. // import UIKit import NumPad class ViewController: UIViewController { lazy var containerView: UIView = { [unowned self] in let containerView = UIView() containerView.layer.borderColor = self.borderColor.cgColor containerView.layer.borderWidth = 1 self.view.addSubview(containerView) containerView.constrainToEdges() return containerView }() lazy var textField: UITextField = { [unowned self] in let textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.textAlignment = .right textField.textColor = UIColor(white: 0.3, alpha: 1) textField.font = .systemFont(ofSize: 40) textField.placeholder = "0".currency() textField.isEnabled = false self.containerView.addSubview(textField) return textField }() lazy var numPad: NumPad = { [unowned self] in let numPad = DefaultNumPad() numPad.delegate = self numPad.translatesAutoresizingMaskIntoConstraints = false numPad.backgroundColor = self.borderColor self.containerView.addSubview(numPad) return numPad }() let borderColor = UIColor(white: 0.9, alpha: 1) override func viewDidLoad() { super.viewDidLoad() let views: [String : Any] = ["textField": textField, "numPad": numPad] containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[textField]-20-|", options: [], metrics: nil, views: views)) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[numPad]|", options: [], metrics: nil, views: views)) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[textField(==120)][numPad]|", options: [], metrics: nil, views: views)) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() numPad.invalidateLayout() } } extension ViewController: NumPadDelegate { func numPad(_ numPad: NumPad, itemTapped item: Item, atPosition position: Position) { switch (position.row, position.column) { case (3, 0): textField.text = nil default: let item = numPad.item(for: position)! let string = textField.text!.sanitized() + item.title! if Int(string) == 0 { textField.text = nil } else { textField.text = string.currency() } } } }
211fbf0a282f4fe07b91f92a4501aa0c
33.1375
165
0.633834
false
false
false
false
borisyurkevich/Wallet
refs/heads/master
Wallet/Currency Converter/Converter.swift
gpl-3.0
1
// // Converter.swift // Wallet // // Created by Boris Yurkevich on 30/09/2017. // Copyright © 2017 Boris Yurkevich. All rights reserved. // import Foundation struct Converter { private var rates: [Currency] init(rates: [Currency]) { self.rates = rates } func convert(fromCurrency: CurrencyType, toCurrency: CurrencyType, amount: Double) -> (sucess: Bool, error: String?, amount: Double?) { if fromCurrency == toCurrency { return (true, nil, amount) } var euroRateRelativeToGivenCurrency: Double? = nil var rateFromEuroToNeededCurrency: Double? = nil for rate in rates { if rate.type == fromCurrency { euroRateRelativeToGivenCurrency = rate.valueInEuro } else if rate.type == toCurrency { rateFromEuroToNeededCurrency = rate.valueInEuro } } if toCurrency == .eur { rateFromEuroToNeededCurrency = 1.0 } if fromCurrency == .eur { euroRateRelativeToGivenCurrency = 1.0 } if euroRateRelativeToGivenCurrency == nil { return (false, "Couldn't find EUR rate to \(fromCurrency.rawValue).", nil) } if rateFromEuroToNeededCurrency == nil { return (false, "Couldn't find EUR rate to \(toCurrency.rawValue).", nil) } // Because our rates are relative to € we need to convert to € first. let inEuro = amount / euroRateRelativeToGivenCurrency! let result = inEuro * rateFromEuroToNeededCurrency! return (true, nil, result) } }
85f7e19d4f1d41af45401f14ac9839c6
30.811321
86
0.585409
false
false
false
false
jfosterdavis/FlashcardHero
refs/heads/master
FlashcardHero/CommandCenterViewController.swift
apache-2.0
1
// // FirstViewController.swift // FlashcardHero // // Created by Jacob Foster Davis on 10/24/16. // Copyright © 2016 Zero Mu, LLC. All rights reserved. // import UIKit import CoreData //import Charts class CommandCenterViewController: CoreDataQuizletCollectionViewController, UICollectionViewDataSource, GameCaller { @IBOutlet weak var missionsCollectionView: UICollectionView! @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var essenceLabel: UILabel! @IBOutlet weak var termsLoadedLabel: UILabel! var keyGameLevel = "GameLevel" var keySets = "Sets" override func viewDidLoad() { super.viewDidLoad() //link the collection view to the coredata class self.collectionView = self.missionsCollectionView collectionView.delegate = self collectionView.dataSource = self _ = setupFetchedResultsController(frcKey: keyGameLevel, entityName: "GameLevel", sortDescriptors: [NSSortDescriptor(key: "level", ascending: false)], predicate: nil) //create FRC for sets _ = setupFetchedResultsController(frcKey: keySets, entityName: "QuizletSet", sortDescriptors: [NSSortDescriptor(key: "title", ascending: false),NSSortDescriptor(key: "id", ascending: true)], predicate: NSPredicate(format: "isActive = %@", argumentArray: [true])) //set up the status bar refreshStatusBar() // Do any additional setup after loading the view, typically from a nib. showMissionsSegment() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refreshStatusBar() } //adapted from http://stackoverflow.com/questions/28347878/ios8-swift-buttons-inside-uicollectionview-cell @IBAction func startMissionButtonPressed(_ sender: UIButton) { let touchPoint = collectionView.convert(CGPoint.zero, from: sender) if let indexPath = collectionView.indexPathForItem(at: touchPoint) { // now you know indexPath. You can get data or cell from here. let gameVariant = GameDirectory.activeGameVariants[indexPath.row] let game = gameVariant.game let gameId = game.name print("You pushed button for game \(gameId)") let vc = storyboard?.instantiateViewController(withIdentifier: game.storyboardId) if let trueFalseVc = vc as? GameTrueFalseViewController { //if it is a true false game //set the level //let objective = //check for the variant if let objective = getGameObjective(gameVariant: gameVariant) as? GameObjectiveMaxPoints { present(trueFalseVc, animated: true, completion: {trueFalseVc.playGameUntil(playerScoreIs: objective.maxPoints, unlessPlayerScoreReaches: objective.minPoints, sender: self)}) } else if let objective = getGameObjective(gameVariant: gameVariant) as? GameObjectivePerfectScore { present(trueFalseVc, animated: true, completion: {trueFalseVc.playGameUntil(playerReaches: objective.maxPoints, unlessPlayerMisses: objective.missedPoints, sender: self)}) } } } } /******************************************************/ /*******************///MARK: Segmented Control /******************************************************/ @IBAction func indexChanged(_ sender: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: showMissionsSegment() case 1: showGoalsSegment() default: break; } } func showMissionsSegment() { print("Showing the missions segment") UIView.animate(withDuration: 0.1, animations: { self.missionsCollectionView.alpha = 1.0 self.missionsCollectionView.isHidden = false }) } func showGoalsSegment() { UIView.animate(withDuration: 0.1, animations: { self.missionsCollectionView.alpha = 0.0 self.missionsCollectionView.isHidden = true }) } /******************************************************/ /*******************///MARK: Status Bar /******************************************************/ func refreshStatusBar() { termsLoadedLabel.text = String(describing: getNumTermsLoaded()) } /******************************************************/ /*******************///MARK: Model Operations /******************************************************/ /** Returns number of terms whose sets are in an active state (selected by user switch) */ func getNumTermsLoaded() -> Int { var count: Int = 0 guard let sets = frcDict[keySets]?.fetchedObjects as? [QuizletSet] else { return 0 } for set in sets { count += Int(set.termCount) } return count } /******************************************************/ /*******************///MARK: GameCaller /******************************************************/ func gameFinished(_ wasObjectiveAchieved: Bool, forGame sender: Game) { print("Game finished. Player success? \(wasObjectiveAchieved)") //if they succeeded award reward and increase level. If they lost, decrease by 2 if wasObjectiveAchieved { //increase level increaseGameLevel(of: sender) } else { decreaseGameLevel(of: sender) } collectionView.reloadData() } /******************************************************/ /*******************///MARK: UICollectionViewDataSource /******************************************************/ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { print("The are \(GameDirectory.activeGames.count) active games that will be displayed") return GameDirectory.activeGameVariants.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MissionCell", for: indexPath as IndexPath) as! CustomMissionCollectionViewCell let gameVariant = GameDirectory.activeGameVariants[indexPath.row] let game = gameVariant.game print("Showing mission for game: \(game.name)") //associate the photo with this cell, which will set all parts of image view cell.gameVariant = gameVariant //set the level let level = getGameLevel(game: game) let objective = getGameObjective(gameVariant: gameVariant) cell.level.text = String(describing: level) cell.objective.text = objective.description if objective.reward < 1 { cell.reward.text = "Unlockable at higher level!" } else { cell.reward.text = "\(objective.reward) Essence" } //if numTermsLoaded is zero, make start mission button disabled cell.startMissionButton.setTitleColor(UIColor.white, for: .normal) cell.startMissionButton.setTitleColor(UIColor.gray, for: .disabled) cell.startMissionButton.setTitle("Start Mission", for: .normal) cell.startMissionButton.setTitle("Load Terms to Enable Mission", for: .disabled) //this formatting approach adapted from http://stackoverflow.com/questions/6178545/adjust-uibutton-font-size-to-width cell.startMissionButton.titleLabel?.numberOfLines = 2 cell.startMissionButton.titleLabel?.adjustsFontSizeToFitWidth = true cell.startMissionButton.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping cell.startMissionButton.titleLabel?.textAlignment = NSTextAlignment.center if getNumTermsLoaded() < 1 { cell.startMissionButton.isEnabled = false cell.startMissionButton.alpha = 0.7 } else { cell.startMissionButton.isEnabled = true cell.startMissionButton.alpha = 1.0 } return cell } //When a user selects an item from the collection override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { return } override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { return } /******************************************************/ /*******************///MARK: Game level and objectives /******************************************************/ func increaseGameLevel(of game: Game) { if let fc = frcDict[keyGameLevel] { if (fc.sections?.count)! > 0, let gameLevels = fc.fetchedObjects as? [GameLevel]{ for gameLevel in gameLevels { if gameLevel.gameId == Int64(game.id) { //update this record to the next game level and return gameLevel.level += 1 return } } //if didn't find at end of loop, must not be an entry, so create one at level 1 _ = GameLevel(gameId: game.id, level: 1, context: fc.managedObjectContext) return } else { return } } else { return } } func decreaseGameLevel(of game: Game) { if let fc = frcDict[keyGameLevel] { if (fc.sections?.count)! > 0, let gameLevels = fc.fetchedObjects as? [GameLevel]{ for gameLevel in gameLevels { if gameLevel.gameId == Int64(game.id) { //update this record to the next game level and return gameLevel.level -= 2 //don't let level go below 0 if gameLevel.level < 0 { gameLevel.level = 0 } return } } //if didn't find at end of loop, must not be an entry, so create one at level 0 _ = GameLevel(gameId: game.id, level: 0, context: fc.managedObjectContext) return } else { return } } else { return } } /** check records to see if this game has an indicated level and return it or 0 */ func getGameLevel(game: Game) -> Int { if let fc = frcDict[keyGameLevel] { if (fc.sections?.count)! > 0, let gameLevels = fc.fetchedObjects as? [GameLevel]{ for gameLevel in gameLevels { if gameLevel.gameId == Int64(game.id) { return Int(gameLevel.level) } } //if didn't find at end of loop, must not be an entry, so level 0 return 0 } else { return 0 } } else { return 0 } } //TODO: make following function return something that conforms with GameObjective protocol func getGameObjective(gameVariant: GameVariant) -> GameObjective { //check for the variant switch gameVariant.gameProtocol { case GameVariantProtocols.MaxPoints: return getGameObjectiveMaxPoints(game: gameVariant.game) case GameVariantProtocols.PerfectGame: return getGameObjectivePerfectScore(game: gameVariant.game) default: fatalError("Asked for a game variant that doesn't exist") } } /** Based on the level of the game, develop some objectives and return */ func getGameObjectiveMaxPoints(game: Game) -> GameObjectiveMaxPoints { //TODO: Impliment fibonnaci method let gameLevel = getGameLevel(game: game) let maxPoints = gameLevel + 5 let minPoints = -5 let description = "Achieve a score of \(maxPoints) points!" let reward = 0 let objective = GameObjectiveMaxPoints() objective.maxPoints = maxPoints objective.minPoints = minPoints objective.description = description objective.reward = reward return objective } func getGameObjectivePerfectScore(game: Game) -> GameObjectivePerfectScore { //TODO: Impliment fibonnaci method let gameLevel = getGameLevel(game: game) let maxPoints = gameLevel + 5 var missedPointsAllowed = 15 - gameLevel if missedPointsAllowed < 1 { missedPointsAllowed = 1 } //make sure missed points is greater than 1 let description = "Achieve a score of \(maxPoints) points... but don't get \(missedPointsAllowed) wrong!" let reward = 0 let objective = GameObjectivePerfectScore() objective.maxPoints = maxPoints objective.missedPoints = missedPointsAllowed objective.description = description objective.reward = reward return objective } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } protocol GameObjectiveProtocol: class { var maxPoints: Int {get set} var description: String {get set} var reward: Int {get set} } class GameObjective: GameObjectiveProtocol { var maxPoints: Int = 0 var description: String = "" var reward: Int = 0 } class GameObjectiveMaxPoints: GameObjective { //var maxPoints: Int = 0 var minPoints: Int = -1 //var description: String = "" //var reward: Int = 0 } class GameObjectivePerfectScore: GameObjective { //var maxPoints: Int = 0 var missedPoints: Int = -1 //var description: String = "" //var reward: Int = 0 }
cb3a0de08edd8cc071b5b38366f3a1d0
34.525301
198
0.559655
false
false
false
false
JGiola/swift
refs/heads/main
validation-test/stdlib/ArrayTrapsObjC.swift
apache-2.0
9
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out_Debug -Onone -swift-version 4.2 && %target-codesign %t/a.out_Debug && %target-run %t/a.out_Debug // RUN: %target-build-swift %s -o %t/a.out_Release -O -swift-version 4.2 && %target-codesign %t/a.out_Release && %target-run %t/a.out_Release // REQUIRES: executable_test // REQUIRES: objc_interop // Temporarily disable for backdeployment (rdar://89821303) // UNSUPPORTED: use_os_stdlib import StdlibUnittest import Foundation let testSuiteSuffix = _isDebugAssertConfiguration() ? "_debug" : "_release" var ArrayTraps = TestSuite("ArrayTraps" + testSuiteSuffix) class Base { } class Derived : Base { } class Derived2 : Derived { } ArrayTraps.test("downcast1") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { let ba: [Base] = [ Derived(), Base() ] let da = ba as! [Derived] _ = da[0] expectCrashLater() _ = da[1] } ArrayTraps.test("downcast2") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { let a: [AnyObject] = ["String" as NSString, 1 as NSNumber] let sa = a as! [NSString] _ = sa[0] expectCrashLater() _ = sa[1] } ArrayTraps.test("downcast3") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { let ba: [Base] = [ Derived2(), Derived(), Base() ] let d2a = ba as! [Derived2] _ = d2a[0] let d1a = d2a as [Derived] _ = d1a[0] _ = d1a[1] expectCrashLater() _ = d1a[2] } @objc protocol ObjCProto { } class ObjCBase : NSObject, ObjCProto { } class ObjCDerived : ObjCBase { } ArrayTraps.test("downcast4") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { let ba: [ObjCProto] = [ ObjCDerived(), ObjCBase() ] let da = ba as! [ObjCDerived] _ = da[0] expectCrashLater() _ = da[1] } ArrayTraps.test("bounds_with_downcast") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .crashOutputMatches(_isDebugAssertConfiguration() ? "Fatal error: Index out of range" : "") .code { let ba: [Base] = [ Derived(), Base() ] let da = ba as! [Derived] expectCrashLater() _ = da[2] } func hasBackdeployedConcurrencyRuntime() -> Bool { // If the stdlib we've loaded predates Swift 5.5, then we're running on a back // deployed concurrency runtime, which has the side effect of disabling // regular runtime exclusivity checks. // // This makes the two tests below fall back to older, higher-level exclusivity // checks in the stdlib, which will still trap, but with a different message. if #available(SwiftStdlib 5.5, *) { return false } // recent enough production stdlib if #available(SwiftStdlib 9999, *) { return false } // dev stdlib return true } var ArraySemanticOptzns = TestSuite("ArraySemanticOptzns" + testSuiteSuffix) class BaseClass { } class ElementClass : BaseClass { var val: String init(_ x: String) { val = x } } class ViolateInoutSafetySwitchToObjcBuffer { final var anArray: [ElementClass] = [] let nsArray = NSArray( objects: ElementClass("a"), ElementClass("b"), ElementClass("c")) @inline(never) func accessArrayViaInoutViolation() { anArray = nsArray as! [ElementClass] } @inline(never) func runLoop(_ A: inout [ElementClass]) { // Simulate what happens if we hoist array properties out of a loop and the // loop calls a function that violates inout safety and overrides the array. let isNativeTypeChecked = A._hoistableIsNativeTypeChecked() for i in 0..<A.count { // Note: the compiler is sometimes able to eliminate this // `_checkSubscript` call when optimizations are enabled, skipping the // exclusivity check contained within. let t = A._checkSubscript( i, wasNativeTypeChecked: isNativeTypeChecked) _ = A._getElement( i, wasNativeTypeChecked: isNativeTypeChecked, matchingSubscriptCheck: t) accessArrayViaInoutViolation() } } @inline(never) func inoutViolation() { anArray = [ ElementClass("1"), ElementClass("2"), ElementClass("3") ] runLoop(&anArray) } } ArraySemanticOptzns.test("inout_rule_violated_isNativeBuffer") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -O or -Ounchecked")) .crashOutputMatches( hasBackdeployedConcurrencyRuntime() ? "inout rules were violated" : "Fatal access conflict detected." ) .code { let v = ViolateInoutSafetySwitchToObjcBuffer() expectCrashLater() v.inoutViolation() } class ViolateInoutSafetyNeedElementTypeCheck { final var anArray : [ElementClass] = [] @inline(never) func accessArrayViaInoutViolation() { // Overwrite the array with one that needs an element type check. let ba: [BaseClass] = [ BaseClass(), BaseClass() ] anArray = ba as! [ElementClass] } @inline(never) func runLoop(_ A: inout [ElementClass]) { // Simulate what happens if we hoist array properties out of a loop and the // loop calls a function that violates inout safety and overrides the array. let isNativeTypeChecked = A._hoistableIsNativeTypeChecked() for i in 0..<A.count { // Note: the compiler is sometimes able to eliminate this // `_checkSubscript` call when optimizations are enabled, skipping the // exclusivity check contained within. let t = A._checkSubscript( i, wasNativeTypeChecked: isNativeTypeChecked) _ = A._getElement( i, wasNativeTypeChecked: isNativeTypeChecked, matchingSubscriptCheck: t) accessArrayViaInoutViolation() } } @inline(never) func inoutViolation() { anArray = [ ElementClass("1"), ElementClass("2"), ElementClass("3")] runLoop(&anArray) } } ArraySemanticOptzns.test("inout_rule_violated_needsElementTypeCheck") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -O or -Ounchecked")) .crashOutputMatches( hasBackdeployedConcurrencyRuntime() ? "inout rules were violated" : "Fatal access conflict detected." ) .code { let v = ViolateInoutSafetyNeedElementTypeCheck() expectCrashLater() v.inoutViolation() } runAllTests()
50f3ebc05dfcb7eb6fee484a389eea1e
29.495283
141
0.683217
false
true
false
false
sanekgusev/xkcd-swift
refs/heads/master
src/Services/Implementations/ImageNetworkingServiceImpl.swift
mit
1
// // ComicImageNetworkingServiceImpl.swift // xkcd-swift // // Created by Aleksandr Gusev on 2/17/15. // // import Foundation import ReactiveCocoa final class ImageNetworkingServiceImpl: NSObject, ImageNetworkingService { private let URLSessionConfiguration: NSURLSessionConfiguration private let completionQueueQualityOfService: NSQualityOfService private lazy var URLSession: NSURLSession = { let completionQueue = NSOperationQueue() completionQueue.qualityOfService = self.completionQueueQualityOfService completionQueue.name = "com.sanekgusev.xkcd.ComicImageNetworkingServiceImpl.completionQueue" return NSURLSession(configuration: self.URLSessionConfiguration, delegate: nil, delegateQueue: completionQueue) }() init(URLSessionConfiguration: NSURLSessionConfiguration, completionQueueQualityOfService: NSQualityOfService) { self.URLSessionConfiguration = URLSessionConfiguration self.completionQueueQualityOfService = completionQueueQualityOfService } func downloadImageForURL(imageURL: NSURL) -> SignalProducer<FileURL, ImageNetworkingServiceError> { let URLRequest = NSURLRequest(URL:imageURL) return SignalProducer { observer, disposable in let downloadTask = self.URLSession.downloadTaskWithRequest(URLRequest, completionHandler: { url, response, error in guard !disposable.disposed else { return } switch (url, response, error) { case (let url?, _, _): observer.sendNext(url) observer.sendCompleted() case (_, _?, let error): observer.sendFailed(.ServerError(underlyingError:error)) case (_, _, let error): observer.sendFailed(.NetworkError(underlyingError:error)) } }) disposable += ActionDisposable { [weak downloadTask] in downloadTask?.cancel() } downloadTask.resume() } } }
2228e113837181a0dc4de20f461c7053
40.196429
103
0.602775
false
true
false
false
maxbritto/cours-ios11-swift4
refs/heads/master
Apprendre/Objectif 3/LifeGoals/LifeGoals/GoalManager.swift
apache-2.0
1
// // GoalManager.swift // LifeGoals // // Created by Maxime Britto on 31/07/2017. // Copyright © 2017 Purple Giraffe. All rights reserved. // import Foundation class GoalManager { private let GOAL_LIST_KEY = "GoalList" private var _goalList:[String] init() { if let loadedGoalList = UserDefaults.standard.array(forKey: GOAL_LIST_KEY) as? [String] { _goalList = loadedGoalList } else { _goalList = [] } } func getGoalCount() -> Int { return _goalList.count } func getGoal(atIndex index:Int) -> String { return _goalList[index] } func addGoal(withText text:String) -> Int? { let newIndex:Int? if text.count > 0 { _goalList.append(text) newIndex = _goalList.count - 1 UserDefaults.standard.set(_goalList, forKey: GOAL_LIST_KEY) } else { newIndex = nil } return newIndex } func removeGoal(atIndex index:Int) { _goalList.remove(at: index) UserDefaults.standard.set(_goalList, forKey: GOAL_LIST_KEY) } }
9259ffc6c88ff124ea65484d9e5d9708
23.891304
97
0.570306
false
false
false
false
DrabWeb/Komikan
refs/heads/master
Komikan/Komikan/KMAddMangaViewController.swift
gpl-3.0
1
// // KMAddMangaViewController.swift // Komikan // // Created by Seth on 2016-01-03. // import Cocoa class KMAddMangaViewController: NSViewController { // The visual effect view for the background of the window @IBOutlet weak var backgroundVisualEffectView: NSVisualEffectView! // The manga we will send back var newManga : KMManga = KMManga(); // An array to store all the manga we want to batch open, if thats what we are doing var newMangaMultiple : [KMManga] = [KMManga()]; // The NSTimer to update if we can add the manga with our given values var addButtonUpdateLoop : Timer = Timer(); // Does the user want to batch add them? var addingMultiple : Bool = false; /// The image view for the cover image @IBOutlet weak var coverImageView: NSImageView! /// The token text field for the mangas title @IBOutlet weak var titleTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas series @IBOutlet weak var seriesTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas artist @IBOutlet weak var artistTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas writer @IBOutlet weak var writerTokenTextField: KMSuggestionTokenField! /// The text field for the mangas tags @IBOutlet weak var tagsTextField: KMAlwaysActiveTextField! /// The token text field for the mangas group @IBOutlet weak var groupTokenTextField: KMSuggestionTokenField! /// The text field for setting the manga's release date(s) @IBOutlet var releaseDateTextField: KMAlwaysActiveTextField! /// The date formatter for releaseDateTextField @IBOutlet var releaseDateTextFieldDateFormatter: DateFormatter! /// The checkbox to say if this manga is l-lewd... @IBOutlet weak var llewdCheckBox: NSButton! /// The button to say if the manga we add should be favourited @IBOutlet weak var favouriteButton: KMFavouriteButton! /// The open panel to let the user choose the mangas directory var chooseDirectoryOpenPanel : NSOpenPanel = NSOpenPanel(); /// The "Choose Directory" button @IBOutlet weak var chooseDirectoryButton: NSButton! /// When we click chooseDirectoryButton... @IBAction func chooseDirectoryButtonPressed(_ sender: AnyObject) { // Run he choose directory open panel chooseDirectoryOpenPanel.runModal(); } /// The add button @IBOutlet weak var addButton: NSButton! /// When we click the add button... @IBAction func addButtonPressed(_ sender: AnyObject) { // Dismiss the popver self.dismiss(self); // Add the manga we described in the open panel addSelf(); } /// The URLs of the files we are adding var addingMangaURLs : [URL] = []; /// The local key down monitor var keyDownMonitor : AnyObject?; override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // Style the window styleWindow(); // Update the favourite button favouriteButton.updateButton(); // Setup the choose directory open panel // Allow multiple files chooseDirectoryOpenPanel.allowsMultipleSelection = true; // Only allow CBZ, CBR, ZIP, RAR and Folders chooseDirectoryOpenPanel.allowedFileTypes = ["cbz", "cbr", "zip", "rar"]; chooseDirectoryOpenPanel.canChooseDirectories = true; // Set the Open button to say choose chooseDirectoryOpenPanel.prompt = "Choose"; // Setup all the suggestions for the property text fields seriesTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allSeries(); artistTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allArtists(); writerTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allWriters(); groupTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allGroups(); // Start a 0.1 second loop that will set if we can add this manga or not addButtonUpdateLoop = Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(KMAddMangaViewController.updateAddButton), userInfo: nil, repeats: true); // Prompt for a manga startPrompt(); } func addSelf() { // If we are only adding one... if(!addingMultiple) { // Set the new mangas cover image newManga.coverImage = coverImageView.image!; // Resize the cover image to be compressed for faster loading newManga.coverImage = newManga.coverImage.resizeToHeight(400); // Set the new mangas title newManga.title = titleTokenTextField.stringValue; // Set the new mangas series newManga.series = seriesTokenTextField.stringValue; // Set the new mangas artist newManga.artist = artistTokenTextField.stringValue; // If the release date field isnt blank... if(releaseDateTextField.stringValue != "") { // Set the release date newManga.releaseDate = releaseDateTextFieldDateFormatter.date(from: releaseDateTextField.stringValue)!; } // Set if the manga is l-lewd... newManga.lewd = Bool(llewdCheckBox.state as NSNumber); // Set the new mangas directory newManga.directory = (addingMangaURLs[0].absoluteString.removingPercentEncoding!).replacingOccurrences(of: "file://", with: ""); // Set the new mangas writer newManga.writer = writerTokenTextField.stringValue; // For every part of the tags text field's string value split at every ", "... for (_, currentTag) in tagsTextField.stringValue.components(separatedBy: ", ").enumerated() { // Print to the log what tag we are adding and what manga we are adding it to print("KMAddMangaViewController: Adding tag \"" + currentTag + "\" to \"" + newManga.title + "\""); // Append the current tags to the mangas tags newManga.tags.append(currentTag); } // Set the new manga's group newManga.group = groupTokenTextField.stringValue; // Set if the manga is a favourite newManga.favourite = Bool(favouriteButton.state as NSNumber); // Post the notification saying we are done and sending back the manga NotificationCenter.default.post(name: Notification.Name(rawValue: "KMAddMangaViewController.Finished"), object: newManga); } else { for (_, currentMangaURL) in addingMangaURLs.enumerated() { // A temporary variable for storing the manga we are currently working on var currentManga : KMManga = KMManga(); // Set the new mangas directory currentManga.directory = (currentMangaURL.absoluteString).removingPercentEncoding!.replacingOccurrences(of: "file://", with: ""); // Get the information of the manga(Cover image, title, ETC.)(Change this function to be in KMManga) currentManga = getMangaInfo(currentManga); // Set the manga's series currentManga.series = seriesTokenTextField.stringValue; // Set the manga's artist currentManga.artist = artistTokenTextField.stringValue; // Set the manga's writer currentManga.writer = writerTokenTextField.stringValue; // If the release date field isnt blank... if(releaseDateTextField.stringValue != "") { // Set the release date currentManga.releaseDate = releaseDateTextFieldDateFormatter.date(from: releaseDateTextField.stringValue)!; } // Set if the manga is l-lewd... currentManga.lewd = Bool(llewdCheckBox.state as NSNumber); // For every part of the tags text field's string value split at every ", "... for (_, currentTag) in tagsTextField.stringValue.components(separatedBy: ", ").enumerated() { // Print to the log what tag we are adding and what manga we are adding it to print("KMAddMangaViewController: Adding tag \"" + currentTag + "\" to \"" + newManga.title + "\""); // Append the current tags to the mangas tags currentManga.tags.append(currentTag); } // Set the manga's group currentManga.group = groupTokenTextField.stringValue; // Set if the manga is a favourite currentManga.favourite = Bool(favouriteButton.state as NSNumber); // Add curentManga to the newMangaMultiple array newMangaMultiple.append(currentManga); } // Remove the first element in newMangaMultiple, for some reason its always empty newMangaMultiple.remove(at: 0); // Post the notification saying we are done and sending back the manga NotificationCenter.default.post(name: Notification.Name(rawValue: "KMAddMangaViewController.Finished"), object: newMangaMultiple); } } /// DId the user specify a custom title in the JSON? var gotTitleFromJSON : Bool = false; /// Did the user specify a custom cover image in the JSON? var gotCoverImageFromJSON : Bool = false; /// Gets the data from the optional JSON file that contains metadata info func fetchJsonData() { // If we actually selected anything... if(addingMangaURLs != []) { // Print to the log that we are fetching the JSON data print("KMAddMangaViewController: Fetching JSON data..."); /// The selected Mangas folder it is in var folderURLString : String = (addingMangaURLs.first?.absoluteString)!; // Remove everything after the last "/" in the string so we can get the folder folderURLString = folderURLString.substring(to: folderURLString.range(of: "/", options: NSString.CompareOptions.backwards, range: nil, locale: nil)!.lowerBound); // Append a slash to the end because it removes it folderURLString += "/"; // Remove the file:// from the folder URL string folderURLString = folderURLString.replacingOccurrences(of: "file://", with: ""); // Remove the percent encoding from the folder URL string folderURLString = folderURLString.removingPercentEncoding!; // Add the "Komikan" folder to the end of it folderURLString += "Komikan/" // If we chose multiple manga... if(addingMangaURLs.count > 1) { /// The URL of the multiple Manga's possible JSON file let mangaJsonURL : String = folderURLString + "series.json"; // If there is a "series.json" file in the Manga's folder... if(FileManager.default.fileExists(atPath: mangaJsonURL)) { // Print to the log that we found the JSON file for the selected manga print("KMAddMangaViewController: Found a series.json file for the selected Manga at \"" + mangaJsonURL + "\""); /// The SwiftyJSON object for the Manga's JSON info let mangaJson = JSON(data: FileManager.default.contents(atPath: mangaJsonURL)!); // Set the series text field's value to the series value seriesTokenTextField.stringValue = mangaJson["series"].stringValue; // Set the series text field's value to the artist value artistTokenTextField.stringValue = mangaJson["artist"].stringValue; // Set the series text field's value to the writer value writerTokenTextField.stringValue = mangaJson["writer"].stringValue; // If there is a released value... if(mangaJson["published"].exists()) { // If there is a release date listed... if(mangaJson["published"].stringValue.lowercased() != "unknown" && mangaJson["published"].stringValue != "") { // If the release date is valid... if(releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue) != nil) { // Set the release date text field's value to the release date value releaseDateTextField.stringValue = releaseDateTextFieldDateFormatter.string(from: (releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue)!)); } } } // For every item in the tags value of the JSON... for(_, currentTag) in mangaJson["tags"].arrayValue.enumerated() { // Print the current tag print("KMAddMangaViewController: Found tag \"" + currentTag.stringValue + "\""); // Add the current item to the tag text field tagsTextField.stringValue += currentTag.stringValue + ", "; } // If the tags text field is not still blank... if(tagsTextField.stringValue != "") { // Remove the extra ", " from the tags text field tagsTextField.stringValue = tagsTextField.stringValue.substring(to: tagsTextField.stringValue.index(before: tagsTextField.stringValue.characters.index(before: tagsTextField.stringValue.endIndex))); } // Set the group text field's value to the group value groupTokenTextField.stringValue = mangaJson["group"].stringValue; // Set the favourites buttons value to the favourites value of the JSON favouriteButton.state = Int.fromBool(bool: mangaJson["favourite"].boolValue); // Update the favourites button favouriteButton.updateButton(); // Set the l-lewd... checkboxes state to the lewd value of the JSON llewdCheckBox.state = Int.fromBool(bool: mangaJson["lewd"].boolValue); } } // If we chose 1 manga... else if(addingMangaURLs.count == 1) { /// The URL to the single Manga's possible JSON file let mangaJsonURL : String = folderURLString + (addingMangaURLs.first?.lastPathComponent.removingPercentEncoding!)! + ".json"; // If there is a file that has the same name but with a .json on the end... if(FileManager.default.fileExists(atPath: mangaJsonURL)) { // Print to the log that we found the JSON file for the single manga print("KMAddMangaViewController: Found single Manga's JSON file at \"" + mangaJsonURL + "\""); /// The SwiftyJSON object for the Manga's JSON info let mangaJson = JSON(data: FileManager.default.contents(atPath: mangaJsonURL)!); // If the title value from the JSON is not "auto" or blank... if(mangaJson["title"].stringValue != "auto" && mangaJson["title"].stringValue != "") { // Set the title text fields value to the title value from the JSON titleTokenTextField.stringValue = mangaJson["title"].stringValue; // Say we got a title from the JSON gotTitleFromJSON = true; } // If the cover image value from the JSON is not "auto" or blank... if(mangaJson["cover-image"].stringValue != "auto" && mangaJson["cover-image"].stringValue != "") { // If the first character is not a "/"... if(mangaJson["cover-image"].stringValue.substring(to: mangaJson["cover-image"].stringValue.characters.index(after: mangaJson["cover-image"].stringValue.startIndex)) == "/") { // Set the cover image views image to an NSImage at the path specified in the JSON coverImageView.image = NSImage(contentsOf: URL(fileURLWithPath: mangaJson["cover-image"].stringValue)); // Say we got a cover image from the JSON gotCoverImageFromJSON = true; } else { // Get the relative image coverImageView.image = NSImage(contentsOf: URL(fileURLWithPath: folderURLString + mangaJson["cover-image"].stringValue)); // Say we got a cover image from the JSON gotCoverImageFromJSON = true; } } // Set the series text field's value to the series value seriesTokenTextField.stringValue = mangaJson["series"].stringValue; // Set the series text field's value to the artist value artistTokenTextField.stringValue = mangaJson["artist"].stringValue; // Set the series text field's value to the writer value writerTokenTextField.stringValue = mangaJson["writer"].stringValue; // If there is a released value... if(mangaJson["published"].exists()) { // If there is a release date listed... if(mangaJson["published"].stringValue.lowercased() != "unknown" && mangaJson["published"].stringValue != "") { // If the release date is valid... if(releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue) != nil) { // Set the release date text field's value to the release date value releaseDateTextField.stringValue = releaseDateTextFieldDateFormatter.string(from: (releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue)!)); } } } // For every item in the tags value of the JSON... for(_, currentTag) in mangaJson["tags"].arrayValue.enumerated() { // Print the current tag print("KMAddMangaViewController: Found tag \"" + currentTag.stringValue + "\""); // Add the current item to the tag text field tagsTextField.stringValue += currentTag.stringValue + ", "; } // If the tags text field is not still blank... if(tagsTextField.stringValue != "") { // Remove the extra ", " from the tags text field tagsTextField.stringValue = tagsTextField.stringValue.substring(to: tagsTextField.stringValue.index(before: tagsTextField.stringValue.characters.index(before: tagsTextField.stringValue.endIndex))); } // Set the group text field's value to the group value groupTokenTextField.stringValue = mangaJson["group"].stringValue; // Set the favourites buttons value to the favourites value of the JSON favouriteButton.state = Int.fromBool(bool: mangaJson["favourite"].boolValue); // Update the favourites button favouriteButton.updateButton(); // Set the l-lewd... checkboxes state to the lewd value of the JSON llewdCheckBox.state = Int.fromBool(bool: mangaJson["lewd"].boolValue); } } } } // Updates the add buttons enabled state func updateAddButton() { // A variable to say if we can add the manga with the given values var canAdd : Bool = false; // If we are only adding one... if(!addingMultiple) { // If the cover image selected is not the default one... if(coverImageView.image != NSImage(named: "NSRevealFreestandingTemplate")) { // If the title is not nothing... if(titleTokenTextField.stringValue != "") { // If the directory is not nothing... if(addingMangaURLs != []) { // Say we can add with these variables canAdd = true; } } } } else { // Say we can add canAdd = true; } // If we can add with these variables... if(canAdd) { // Enable the add button addButton.isEnabled = true; } else { // Disable the add button addButton.isEnabled = false; } } func getMangaInfo(_ manga : KMManga) -> KMManga { // Set the mangas title to the mangas archive name manga.title = KMFileUtilities().getFileNameWithoutExtension(manga.directory); // Delete /tmp/komikan/addmanga, if it exists do { // Remove /tmp/komikan/addmanga try FileManager().removeItem(atPath: "/tmp/komikan/addmanga"); // Print to the log that we deleted it print("KMAddMangaViewController: Deleted /tmp/komikan/addmanga folder for \"" + manga.title + "\""); // If there is an error... } catch _ as NSError { // Print to the log that there is no /tmp/komikan/addmanga folder to delete print("KMAddMangaViewController: No /tmp/komikan/addmanga to delete for \"" + manga.title + "\""); } // If the manga's file isnt a folder... if(!KMFileUtilities().isFolder(manga.directory.replacingOccurrences(of: "file://", with: ""))) { // Extract the passed manga to /tmp/komikan/addmanga KMFileUtilities().extractArchive(manga.directory.replacingOccurrences(of: "file://", with: ""), toDirectory: "/tmp/komikan/addmanga"); } // If the manga's file is a folder... else { // Copy the folder to /tmp/komikan/addmanga do { try FileManager.default.copyItem(atPath: manga.directory.replacingOccurrences(of: "file://", with: ""), toPath: "/tmp/komikan/addmanga"); } catch _ as NSError { } } // Clean up the directory print("KMAddMangaViewController: \(KMCommandUtilities().runCommand(Bundle.main.bundlePath + "/Contents/Resources/cleanmangadir", arguments: ["/tmp/komikan/addmanga"], waitUntilExit: true))"); /// All the files in /tmp/komikan/addmanga var addMangaFolderContents : [String] = []; // Get the contents of /tmp/komikan/addmanga do { // Set addMangaFolderContents to all the files in /tmp/komikan/addmanga addMangaFolderContents = try FileManager().contentsOfDirectory(atPath: "/tmp/komikan/addmanga"); // Sort the files by their integer values addMangaFolderContents = (addMangaFolderContents as NSArray).sortedArray(using: [NSSortDescriptor(key: "integerValue", ascending: true)]) as! [String]; } catch _ as NSError { // Do nothing } // Get the first image in the folder, and set the cover image selection views image to it // The first item in /tmp/komikan/addmanga var firstImage : NSImage = NSImage(); // For every item in the addmanga folder... for(_, currentFile) in addMangaFolderContents.enumerated() { // If this file is an image and not a dot file... if(KMFileUtilities().isImage("/tmp/komikan/addmanga/" + (currentFile )) && ((currentFile).substring(to: (currentFile).characters.index(after: (currentFile).startIndex))) != ".") { // If the first image isnt already set... if(firstImage.size == NSSize.zero) { // Set the first image to the current image file firstImage = NSImage(contentsOfFile: "/tmp/komikan/addmanga/\(currentFile)")!; } } } // Set the cover image selecting views image to firstImage manga.coverImage = firstImage; // Resize the cover image to be compressed for faster loading manga.coverImage = manga.coverImage.resizeToHeight(400); // Print the image to the log(It for some reason needs this print or it wont work) print("KMAddMangaViewController: \(firstImage)"); // Return the changed manga return manga; } // Asks for a manga, and deletes the old ones tmp folder func promptForManga() { // Delete /tmp/komikan/addmanga do { // Remove /tmp/komikan/addmanga try FileManager().removeItem(atPath: "/tmp/komikan/addmanga"); // If there is an error... } catch _ as NSError { // Do nothing } // Ask for the manga's directory, and if we clicked "Choose"... if(Bool(chooseDirectoryOpenPanel.runModal() as NSNumber)) { // Set the adding manga URLs to the choose directory open panels URLs addingMangaURLs = chooseDirectoryOpenPanel.urls; } } // The prompt you get when you open this view with the open panel func startPrompt() { // If addingMangaURLs is []... if(addingMangaURLs == []) { // Prompt for a file promptForManga(); } // Fetch the JSON data fetchJsonData(); // Subscribe to the key down event keyDownMonitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.keyDown, handler: keyHandler) as AnyObject?; // If we selected multiple files... if(addingMangaURLs.count > 1) { // Say we are adding multiple addingMultiple = true; // Say we cant edit the image view coverImageView.isEditable = false; // Dont allow us to set the title titleTokenTextField.isEnabled = false; // Dont allow us to change the directory chooseDirectoryButton.isEnabled = false; // Set the cover image image views image to NSFlowViewTemplate coverImageView.image = NSImage(named: "NSFlowViewTemplate"); } else { // If the directory is not nothing... if(addingMangaURLs != []) { // Set the new mangas directory newManga.directory = addingMangaURLs[0].absoluteString.removingPercentEncoding!; // Get the information of the manga(Cover image, title, ETC.)(Change this function to be in KMManga) newManga = getMangaInfo(newManga); // If we didnt get a cover image from the JSON... if(!gotCoverImageFromJSON) { // Set the cover image views cover image coverImageView.image = newManga.coverImage; } // If we didnt get a title from the JSON... if(!gotTitleFromJSON) { // Set the title text fields value to the mangas title titleTokenTextField.stringValue = newManga.title; } } } } func keyHandler(_ event : NSEvent) -> NSEvent { // If we pressed enter... if(event.keyCode == 36 || event.keyCode == 76) { // If the add button is enabled... if(addButton.isEnabled) { // Hide the popover self.dismiss(self); // Add the chosen manga addSelf(); } } // Return the event return event; } override func viewWillDisappear() { // Unsubscribe from key down NSEvent.removeMonitor(keyDownMonitor!); // Stop the add button update loop addButtonUpdateLoop.invalidate(); } func styleWindow() { // Set the background effect view to be dark backgroundVisualEffectView.material = NSVisualEffectMaterial.dark; } }
7d18839ce2521f72f5ba3e4a7f749108
47.162717
221
0.560272
false
false
false
false
krimpedance/KRActivityIndicator
refs/heads/master
KRActivityIndicatorView/Classes/KRActivityIndicatorView.swift
mit
2
// // KRActivityIndicatorView.swift // KRActivityIndicatorView // // Copyright © 2016 Krimpedance. All rights reserved. // import UIKit /// KRActivityIndicatorView is a simple and customizable activity indicator @IBDesignable public final class KRActivityIndicatorView: UIView { private let animationKey = "KRActivityIndicatorViewAnimationKey" private var animationLayer = CALayer() /// Activity indicator's head color (read-only). /// You can set head color from IB. /// If you want to change color from code, use colors property. @IBInspectable public fileprivate(set) var headColor: UIColor { get { return colors.first ?? .black } set { colors = [newValue, tailColor] } } /// Activity indicator's tail color (read-only). /// You can set tail color from IB. /// If you want to change color from code, use colors property. @IBInspectable public fileprivate(set) var tailColor: UIColor { get { return colors.last ?? .black } set { colors = [headColor, newValue] } } /// Number of dots @IBInspectable public var numberOfDots: Int = 8 { didSet { drawIndicatorPath() } } // Duration for one rotation @IBInspectable public var duration: Double = 1.0 { didSet { guard isAnimating else { return } stopAnimating() startAnimating() } } /// Animation of activity indicator when it's shown. @IBInspectable public var animating: Bool = true { didSet { animating ? startAnimating() : stopAnimating() } } /// set `true` to `isHidden` when call `stopAnimating()` @IBInspectable public var hidesWhenStopped: Bool = false { didSet { animationLayer.isHidden = !isAnimating && hidesWhenStopped } } /// Activity indicator gradient colors. public var colors: [UIColor] = [.black, .lightGray] { didSet { drawIndicatorPath() } } /// Whether view performs animation public var isAnimating: Bool { return animationLayer.animation(forKey: animationKey) != nil } // Initializer ---------- public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.addSublayer(animationLayer) } public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear layer.addSublayer(animationLayer) } /// Initializer public convenience init() { self.init(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) } /// Initializer with colors /// /// - Parameter colors: Activity indicator gradient colors. public convenience init(colors: [UIColor]) { self.init(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) self.colors = colors } // Deprecated ---------- /// Activity indicator color style. @available(*, deprecated) public var style = KRActivityIndicatorViewStyle.gradationColor(head: .black, tail: .lightGray) { didSet { colors = [style.headColor, style.tailColor] } } /// Initialize with style. /// - Parameter style: Activity indicator default color use of KRActivityIndicatorViewStyle @available(*, deprecated) public convenience init(style: KRActivityIndicatorViewStyle) { self.init(colors: [style.headColor, style.tailColor]) } // Lyfecycle ---------- public override func layoutSubviews() { super.layoutSubviews() viewResized() } } // MARK: - Private actions ------------ private extension KRActivityIndicatorView { func viewResized() { animationLayer.frame = layer.bounds animationLayer.isHidden = !isAnimating && hidesWhenStopped drawIndicatorPath() if animating { startAnimating() } } func drawIndicatorPath() { animationLayer.sublayers?.forEach { $0.removeFromSuperlayer() } let width = Double(min(animationLayer.bounds.width, animationLayer.bounds.height)) // 各ドットの直径を求めるためのベースとなる比率 let diff = 0.6 / Double(numberOfDots-1) let baseRatio = 100 / (1.8 * Double(numberOfDots) - Double(numberOfDots * (numberOfDots - 1)) * diff) // ベースとなる円の直径(レイヤー内にドットが収まるように調整する) var diameter = width while true { let circumference = diameter * Double.pi let dotDiameter = baseRatio * 0.9 * circumference / 100 let space = width - diameter - dotDiameter if space > 0 { break } diameter -= 2 } let colors = getGradientColors(dividedIn: numberOfDots) let circumference = diameter * Double.pi let spaceRatio = 50 / Double(numberOfDots) / 100 var degree = Double(20) // 全体を 20° 傾ける (0..<numberOfDots).forEach { let number = Double($0) let ratio = (0.9 - diff * number) * baseRatio / 100 let dotDiameter = circumference * ratio let rect = CGRect( x: (width - dotDiameter) / 2, y: (width - diameter - dotDiameter) / 2, width: dotDiameter, height: dotDiameter ) if number != 0 { let preRatio = (0.9 - diff * (number - 1)) * baseRatio / 100 let arc = (preRatio / 2 + spaceRatio + ratio / 2) * circumference degree += 360 * arc / circumference } let pathLayer = CAShapeLayer() pathLayer.frame.size = CGSize(width: width, height: width) pathLayer.position = animationLayer.position pathLayer.fillColor = colors[$0].cgColor pathLayer.lineWidth = 0 pathLayer.path = UIBezierPath(ovalIn: rect).cgPath pathLayer.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(-degree) * CGFloat.pi / 180)) animationLayer.addSublayer(pathLayer) } } func getGradientColors(dividedIn num: Int) -> [UIColor] { let gradient = CAGradientLayer() gradient.frame = CGRect(x: 0, y: 0, width: 2, height: (num-1) * 10 + 1) switch colors.count { case 0: gradient.colors = [UIColor.black.cgColor, UIColor.lightGray.cgColor] case 1: gradient.colors = [colors.first!.cgColor, colors.first!.cgColor] default: gradient.colors = colors.map { $0.cgColor } } return (0..<num).map { let point = CGPoint(x: 1, y: 10*CGFloat($0)) return gradient.color(point: point) } } } // MARK: - Public actions ------------------ public extension KRActivityIndicatorView { /// Start animating. func startAnimating() { if animationLayer.animation(forKey: animationKey) != nil { return } let animation = CABasicAnimation(keyPath: "transform.rotation") animation.fromValue = 0 animation.toValue = Double.pi * 2 animation.duration = duration animation.timingFunction = CAMediaTimingFunction(name: .linear) animation.isRemovedOnCompletion = false animation.repeatCount = Float(NSIntegerMax) animation.fillMode = .forwards animation.autoreverses = false animationLayer.isHidden = false animationLayer.add(animation, forKey: animationKey) } /// Stop animating. func stopAnimating() { animationLayer.removeAllAnimations() animationLayer.isHidden = hidesWhenStopped } }
790821c09f43b1503f6e632734ddf967
32.714932
111
0.619514
false
false
false
false
pushtechnology/diffusion-examples
refs/heads/6.8
apple/ConsumingRecordV2TopicsExample.swift
apache-2.0
1
// Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // // Copyright (C) 2017, 2020 Push Technology Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Diffusion /** This example demonstrates a client consuming RecordV2 topics. It has been contrived to demonstrate the various techniques for Diffusion record topics and is not necessarily realistic or efficient in its processing. It can be run using a schema or not using a schema and demonstrates how the processing could be done in both cases. This makes use of the 'Topics' feature only. To subscribe to a topic, the client session must have the 'select_topic' and 'read_topic' permissions for that branch of the topic tree. This example receives updates to currency conversion rates via a branch of the topic tree where the root topic is called "FX" which under it has a topic for each base currency and under each of those is a topic for each target currency which contains the bid and ask rates. So a topic FX/GBP/USD would contain the rates for GBP to USD. This example maintains a local map of the rates and also notifies a listener of any rates changes. */ public class ClientConsumingRecordV2Topics { private static let rootTopic = "FX" private var subscriber: Subscriber? /** Constructor. @param serverUrl For example "ws://diffusion.example.com" @param listener An object that will be notified of rates and rate changes. @param withSchema Whether schema processing should be used or not. */ init(serverUrl: URL, listener: RatesListener, withSchema: Bool) { let schema = withSchema ? ClientConsumingRecordV2Topics.createSchema() : nil let configuration = PTDiffusionSessionConfiguration( principal: "client", credentials: PTDiffusionCredentials(password: "password")) PTDiffusionSession.open(with: serverUrl, configuration: configuration) { (session, error) in if let connectedSession = session { self.subscriber = Subscriber(connectedSession, listener: listener, schema: schema) } else { print(error!) } } } private class Subscriber { let session: PTDiffusionSession let valueStreamDelegate: ValueStreamDelegate init(_ session: PTDiffusionSession, listener: RatesListener, schema: PTDiffusionRecordV2Schema?) { self.session = session // Use the Topics feature to add a record value stream and subscribe // to all topics under the root. valueStreamDelegate = ValueStreamDelegate( listener: listener, schema: schema) let valueStream = PTDiffusionRecordV2.valueStream( with: valueStreamDelegate) let topics = session.topics let topicSelector = "?" + rootTopic + "//" do { try topics.add(valueStream, withSelectorExpression: topicSelector, error:()) } catch { print("Error while adding stream with selector expression") } topics.subscribe(withTopicSelectorExpression: topicSelector) { (error) in if let subscriptionError = error { print(subscriptionError) } } } } private class ValueStreamDelegate: PTDiffusionRecordV2ValueStreamDelegate { let listener: RatesListener let schema: PTDiffusionRecordV2Schema? var currencies = [String: Currency]() init(listener: RatesListener, schema: PTDiffusionRecordV2Schema?) { self.listener = listener self.schema = schema } func diffusionStream(_ stream: PTDiffusionStream, didSubscribeToTopicPath topicPath: String, specification: PTDiffusionTopicSpecification) { print("Value stream subscribed to topic path: \(topicPath)") } func diffusionStream(_ stream: PTDiffusionValueStream, didUpdateTopicPath topicPath: String, specification: PTDiffusionTopicSpecification, oldRecord: PTDiffusionRecordV2?, newRecord: PTDiffusionRecordV2) { let topicElements = elements(topicPath) // It is only a rate update if topic has 2 elements below root path if topicElements.count == 2 { applyUpdate( currencyCode: topicElements[0], targetCurrencyCode: topicElements[1], oldValue: oldRecord, newValue: newRecord) } } func diffusionStream(_ stream: PTDiffusionStream, didUnsubscribeFromTopicPath topicPath: String, specification: PTDiffusionTopicSpecification, reason: PTDiffusionTopicUnsubscriptionReason) { let topicElements = elements(topicPath) if topicElements.count == 2 { removeRate( currencyCode: topicElements[0], targetCurrencyCode: topicElements[1]) } else if topicElements.count == 1 { removeCurrency(code: topicElements[0]) } } func diffusionDidClose( _ stream: PTDiffusionStream) { print("Value stream closed.") } func diffusionStream( _ stream: PTDiffusionStream, didFailWithError error: Error) { print("Value stream failed: \(error)") } func elements(_ topicPath: String) -> [String] { let prefix = rootTopic + "/" if let prefixRange = topicPath.range(of: prefix) { var subPath = topicPath subPath.removeSubrange(prefixRange) return subPath.components(separatedBy: "/") } return [] } func applyUpdate( currencyCode: String, targetCurrencyCode: String, oldValue: PTDiffusionRecordV2?, newValue: PTDiffusionRecordV2) { let currency = currencies[currencyCode] ?? Currency() currencies[currencyCode] = currency if let schema = self.schema { // Update using Schema. applyUpdate( currencyCode: currencyCode, targetCurrencyCode: targetCurrencyCode, oldValue: oldValue, newValue: newValue, currency: currency, schema: schema) return; } // Update without using Schema. let fields = try! newValue.fields() let bid = fields[0] let ask = fields[1] currency.setRatesForTargetCurrency( code: targetCurrencyCode, bid: bid, ask: ask) if let previousValue = oldValue { // Compare fields individually in order to determine what has // changed. let oldFields = try! previousValue.fields() let oldBid = oldFields[0] let oldAsk = oldFields[1] if bid != oldBid { listener.onRateChange( currency: currencyCode, targetCurrency: targetCurrencyCode, bidOrAsk: "Bid", rate: bid) } if ask != oldAsk { listener.onRateChange( currency: currencyCode, targetCurrency: targetCurrencyCode, bidOrAsk: "Ask", rate: ask) } } else { listener.onNewRate( currency: currencyCode, targetCurrency: targetCurrencyCode, bid: bid, ask: ask) } } func applyUpdate( currencyCode: String, targetCurrencyCode: String, oldValue: PTDiffusionRecordV2?, newValue: PTDiffusionRecordV2, currency: Currency, schema: PTDiffusionRecordV2Schema) { let model = try! newValue.model(with: schema) let bid = try! model.fieldValue(forKey: "Bid") let ask = try! model.fieldValue(forKey: "Ask") currency.setRatesForTargetCurrency( code: targetCurrencyCode, bid: bid, ask: ask) if let previousValue = oldValue { // Generate a structural delta to determine what has changed. let delta = newValue.diff(fromOriginalRecord: previousValue) for change in try! delta.changes(with: schema) { let fieldName = change.fieldName listener.onRateChange( currency: currencyCode, targetCurrency: targetCurrencyCode, bidOrAsk: fieldName, rate: try! model.fieldValue(forKey: fieldName)) } } else { listener.onNewRate( currency: currencyCode, targetCurrency: targetCurrencyCode, bid: bid, ask: ask) } } func removeCurrency(code: String) { if let oldCurrency = currencies.removeValue(forKey: code) { for targetCurrencyCode in oldCurrency.targetCurrencyCodes() { listener.onRateRemoved( currency: code, targetCurrency: targetCurrencyCode) } } } func removeRate(currencyCode: String, targetCurrencyCode: String) { if let currency = currencies.removeValue(forKey: currencyCode) { if currency.removeTargetCurrency(code: targetCurrencyCode) { listener.onRateRemoved( currency: currencyCode, targetCurrency: targetCurrencyCode) } } } } /** Encapsulates a base currency and all of its known rates. */ private class Currency { var rates = [String: (bid: String, ask: String)]() func targetCurrencyCodes() -> [String] { return Array(rates.keys) } func removeTargetCurrency(code: String) -> Bool { return nil != rates.removeValue(forKey: code) } func setRatesForTargetCurrency(code: String, bid: String, ask: String) { rates[code] = (bid: bid, ask: ask) } } /** Create the record schema for the rates topic, with two decimal fields which are maintained to 5 decimal places */ private static func createSchema() -> PTDiffusionRecordV2Schema { return PTDiffusionRecordV2SchemaBuilder() .addRecord(withName: "Rates") .addDecimal(withName: "Bid", scale: 5) .addDecimal(withName: "Ask", scale: 5) .build() } } /** A listener for rates updates. */ public protocol RatesListener { /** Notification of a new rate or rate update. @param currency The base currency. @param targetCurrency The target currency. @param bid Rate. @param ask Rate. */ func onNewRate(currency: String, targetCurrency: String, bid: String, ask: String) /** Notification of a change to the bid or ask value for a rate. @param currency the base currency. @param targetCurrency The target currency. @param bidOrAsk Either "Bid" or "Ask". @param rate The new rate. */ func onRateChange(currency: String, targetCurrency: String, bidOrAsk: String, rate: String) /** Notification of a rate being removed. @param currency The base currency. @param targetCurrency The target currency. */ func onRateRemoved(currency: String, targetCurrency: String) }
2f82205f79da35d79f488efca3d574ac
35.146479
95
0.577307
false
false
false
false
hikelee/hotel
refs/heads/master
Sources/Common/Controllers/HostController.swift
mit
1
import Vapor import HTTP import Foundation final class HostAdminController : HotelBasedController<Host> { typealias M = Host override var path:String {return "/admin/common/host"} override func preSave(request:Request,model:M) throws{ if let hotelId = model.hotelId?.int, let hotel = try Hotel.load(id:hotelId){ model.channelId = hotel.channelId } } override func preUpdate(request:Request,new:M,old:M) throws{ new.ids = old.ids new.lastSyncTime = old.lastSyncTime } override func getModel(request:Request) throws -> M{ let model = try super.getModel(request:request) model.macAddress = model.macAddress?.uppercased() return model } } class HostApiController: Controller { override func makeRouter(){ routerGroup.get("/api/common/ip/sync/"){return try self.sync($0)} routerGroup.post("/api/common/ip/sync/"){return try self.sync($0)} } func sync(_ request: Request) throws -> String { guard let ip = request.data["ip"]?.string else { return "no ip\n" } guard let mac = request.data["mac"]?.string else{ return "no mac address\n" } if try Host.load(macAddress: mac) == nil { return "no host found" } //if host.ipAddress == ip { // return "ok,on-change" //} try Host.sync(macAddress:mac,ipAddress:ip) return "ok\n" } }
ce623b4939e19cd7c8e06f927409bf53
28.88
74
0.60241
false
false
false
false
saurabytes/JSQCoreDataKit
refs/heads/develop
Source/StackResult.swift
mit
1
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://www.jessesquires.com/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import CoreData import Foundation /** A result object representing the result of creating a `CoreDataStack` via a `CoreDataStackFactory`. */ public enum StackResult: CustomStringConvertible, Equatable { /// The success result, containing the successfully initialized `CoreDataStack`. case success(CoreDataStack) /// The failure result, containing an `NSError` instance that describes the error. case failure(NSError) // MARK: Methods /** - returns: The result's `CoreDataStack` if `.Success`, otherwise `nil`. */ public func stack() -> CoreDataStack? { if case .success(let stack) = self { return stack } return nil } /** - returns: The result's `NSError` if `.Failure`, otherwise `nil`. */ public func error() -> NSError? { if case .failure(let error) = self { return error } return nil } // MARK: CustomStringConvertible /// :nodoc: public var description: String { get { var str = "<\(StackResult.self): " switch self { case .success(let s): str += ".success(\(s)" case .failure(let e): str += ".failure(\(e))" } return str + ">" } } }
8f7a497cd6658b383f811840265f1b82
21.657534
100
0.579807
false
false
false
false
xNekOIx/StoryboardStyles
refs/heads/master
MyPlayground.playground/Pages/Untitled Page 3.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation let storyboardData = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + "<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"9059\" systemVersion=\"15B42\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" useTraitCollections=\"YES\">" + "<dependencies>" + "<plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"9049\"/>" + "</dependencies>" + "<scenes>" + "<!--View Controller-->" + "<scene sceneID=\"X5B-PV-zIh\">" + "<objects>" + "<viewController id=\"iHD-XU-1t3\" sceneMemberID=\"viewController\">" + "<layoutGuides>" + "<viewControllerLayoutGuide type=\"top\" id=\"vBi-pL-j8v\"/>" + "<viewControllerLayoutGuide type=\"bottom\" id=\"YIc-tN-jzC\"/>" + "</layoutGuides>" + "<view key=\"view\" contentMode=\"scaleToFill\" id=\"D67-Go-AuY\">" + "<rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"600\" height=\"600\"/>" + "<autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>" + "<animations/>" + "<color key=\"backgroundColor\" white=\"1\" alpha=\"1\" colorSpace=\"calibratedWhite\"/>" + "<userDefinedRuntimeAttributes>" + "<userDefinedRuntimeAttribute type=\"string\" keyPath=\"styleClass\" value=\"PewPew\"/>" + "</userDefinedRuntimeAttributes>" + "</view>" + "</viewController>" + "<placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"wG4-Wr-g0G\" userLabel=\"First Responder\" sceneMemberID=\"firstResponder\"/>" + "</objects>" + "<point key=\"canvasLocation\" x=\"977\" y=\"394\"/>" + "</scene>" + "</scenes>" + "</document>").dataUsingEncoding(NSUTF8StringEncoding)! let stylesheetData = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + "<xsl:template match=\"//userDefinedRuntimeAttribute[@keyPath='styleClass' and @value='PewPew']\">" + // "<xsl:template match=\"@* | node()\">" + "<xsl:copy-of select=\".\"/>" + // "<color></color>" + // "<xsl:copy>" + // "<color></color>" + // "<xsl:apply-templates select=\"@* | node()\"/>" + // "</xsl:copy>" + "</xsl:template>" + "</xsl:stylesheet>").dataUsingEncoding(NSUTF8StringEncoding)! let doc = try! NSXMLDocument(data: storyboardData, options: Int(NSXMLDocumentContentKind.XMLKind.rawValue)) let xslt = try! doc.objectByApplyingXSLT(stylesheetData, arguments: nil) print(xslt) //: [Next](@next)
4dd1c8c4cadec776c4ba241e7ecfb6a1
46.636364
257
0.621374
false
false
false
false
KoCMoHaBTa/MHAppKit
refs/heads/master
MHAppKit/Extensions/UIKit/UIControl+Action.swift
mit
1
// // UIControl+Action.swift // MHAppKit // // Created by Milen Halachev on 5/30/16. // Copyright © 2016 Milen Halachev. All rights reserved. // #if canImport(UIKit) && !os(watchOS) import Foundation import UIKit extension UIControl { public typealias Action = (_ sender: UIControl) -> Void ///Adds an action handler to the receiver for the given `UIControlEvents` (default to `.touchUpInside`) public func addAction(forEvents events: UIControl.Event = [.touchUpInside], action: @escaping Action) { //the action should be called for every event let handler = ActionHandler(control: self, events: events, action: action) self.actionHandlers.append(handler) } ///Returns an array of actions added to the receiver for the given control events public func actions(forEvents events: UIControl.Event) -> [Action] { return self.actionHandlers.filter({ $0.events.contains(events) }).map({ $0.action }) } ///removes all actions from the receiver for the given control events public func removeActions(forEvents events: UIControl.Event) { self.actionHandlers = self.actionHandlers.filter({ !$0.events.contains(events) }) } } extension UIControl { private static var actionHandlersKey = "" fileprivate var actionHandlers: [ActionHandler] { get { let result = objc_getAssociatedObject(self, &UIControl.actionHandlersKey) as? [ActionHandler] ?? [] return result } set { let newValue = newValue.filter({ $0.control != nil }) objc_setAssociatedObject(self, &UIControl.actionHandlersKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } extension UIControl { fileprivate class ActionHandler { weak var control: UIControl? let events: UIControl.Event let action: Action deinit { self.control?.removeTarget(self, action: #selector(handleAction(_:)), for: self.events) } init(control: UIControl, events: UIControl.Event, action: @escaping Action) { self.control = control self.events = events self.action = action control.addTarget(self, action: #selector(handleAction(_:)), for: events) } @objc dynamic func handleAction(_ sender: UIControl) { self.action(sender) } } } #endif
769d46c9dc71c859b54750ea5b1a0c90
29.247059
118
0.60949
false
false
false
false
SnipDog/ETV
refs/heads/master
ETV/Moudel/Home/HomeViewController.swift
mit
1
// // HomeViewController.swift // ETV // // Created by Heisenbean on 16/9/29. // Copyright © 2016年 Heisenbean. All rights reserved. // import UIKit import Alamofire import Then import SwiftyJSON class HomeViewController: UIViewController { // MARK: Init Properties var titleView = TitleView().then { $0.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40) } @IBOutlet weak var tableview: UITableView! let kBannerReqeutUrl = "http://api.m.panda.tv/ajax_rmd_ads_get?__version=1.1.4.1261&__plat=ios&__channel=appstore&pt_sign=ef767d23f0a6ccd476b738c0b91c4109&pt_time=1475204481" let kDataReqeutUrl = "http://api.m.panda.tv/ajax_get_live_list_by_multicate?pagenum=4&hotroom=1&__version=1.1.4.1261&__plat=ios&__channel=appstore&pt_sign=ef767d23f0a6ccd476b738c0b91c4109&pt_time=1475204481" var banners = [[String:AnyObject]]() var datas = [JSON]() // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() configUI() loadBanner() loadData() loadTitleView() // Do any additional setup after loading the view. } func configUI(){ self.title = nil self.navigationController?.tabBarItem.title = "首页" let navView = UIImageView().then { let img = UIImage(named: "slogon") $0.image = img $0.sizeToFit() } self.navigationItem.titleView = navView } func loadBanner() { let banner = tableview.dequeueReusableCell(withIdentifier: "header") as! HomeHeaderCell tableview.tableHeaderView = banner Alamofire.request(kBannerReqeutUrl).responseJSON { response in if let json = response.result.value { self.banners.removeAll() let jsonData = json as! [String:AnyObject] for data in jsonData["data"] as! [[String : AnyObject]]{ self.banners.append(data) } banner.banners = self.banners } } } func loadTitleView() { view.addSubview(titleView) // load data from service titleView.titles = ["精彩推荐","全部直播","DOTA2"] } func loadData() { Alamofire.request(kDataReqeutUrl).responseJSON { response in if let json = response.data { let jsonData = JSON(data: json) let jsons = jsonData["data"].arrayValue for j in jsons{ self.datas.append(j) } self.tableview.reloadData() } } } // MARK: Actions @IBAction func search(_ sender: UIBarButtonItem) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension HomeViewController:UITableViewDataSource,UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datas.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeCell cell.data = datas[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 321 } }
f8f2fb4b7645375d8cd1a87003cfaaf1
29.637931
211
0.599043
false
false
false
false
Morkrom/googlyeyes
refs/heads/master
googlyeyes/Classes/GooglyEye.swift
mit
1
// // GooglyEye.swift // googlyeyes // // Created by Michael Mork on 10/24/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import UIKit class GooglyEye: UIView { var pupilDiameterPercentageWidth: CGFloat = 0.62 { didSet { updateDimensions() } } var pupil = Pupil() private class func grayColor() -> UIColor { return GooglyEye.paperGray(alpha: 1.0) } private class func paperGray(alpha: CGFloat) -> UIColor {return UIColor(red: 0.99, green: 0.99, blue: 0.99, alpha: alpha)} private class func cutoutRadius(dimension: CGFloat) -> CGFloat {return dimension/2 * 0.97} private class func diameterFromFrame(rectSize: CGSize) -> CGFloat {return rectSize.width > rectSize.height ? rectSize.height : rectSize.width} private var displayLink: CADisplayLink! private var animation: PupilBehaviorManager? private var diameter: CGFloat = 0 private var orientation = UIApplication.shared.statusBarOrientation private var baseCutout = Sclera() private let innerStamp = HeatStamp() class func autoLayout() -> GooglyEye { let gEye = GooglyEye(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 100))) gEye.translatesAutoresizingMaskIntoConstraints = false return gEye } override init(frame: CGRect) { super.init(frame: frame) displayLink = CADisplayLink(target: self, selector: #selector(GooglyEye.link)) //initialization displayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.default) //properties displayLink.frameInterval = 2 addSubview(pupil) layer.addSublayer(baseCutout) layer.addSublayer(innerStamp) layer.insertSublayer(pupil.layer, below: innerStamp) if frame.size != .zero { animation = PupilBehaviorManager(googlyEye: self, center: baseCutout.startCenter, travelRadius: diameter) } updateDimensions() } private func updateDimensions() { guard animation != nil else { return } diameter = GooglyEye.diameterFromFrame(rectSize: frame.size) baseCutout.frame = CGRect(x: 0, y: 0, width: diameter, height: diameter) innerStamp.startCenter = baseCutout.startCenter innerStamp.frame = baseCutout.bounds if orientation == UIApplication.shared.statusBarOrientation { // Avoid changing the pupil frame if there's a status bar animation happening - doing so compromises an otherwise concentric pupil. adjustPupilForNewWidth() pupil.layer.setNeedsDisplay() } innerStamp.update() baseCutout.setNeedsDisplay() innerStamp.setNeedsDisplay() animation?.updateBehaviors(googlyEye: self, center: baseCutout.startCenter, travelRadius: GooglyEye.cutoutRadius(dimension: diameter)) } private func adjustPupilForNewWidth() { if pupilDiameterPercentageWidth > 1.0 { pupilDiameterPercentageWidth = 1.0 } else if pupilDiameterPercentageWidth < 0 { pupilDiameterPercentageWidth = 0.01 } pupil.frame = CGRect(x: pupil.frame.minX - (pupil.frame.width - diameter*pupilDiameterPercentageWidth)/2, y: pupil.frame.minY - (pupil.frame.height - diameter*pupilDiameterPercentageWidth)/2, width: diameter*pupilDiameterPercentageWidth, height: diameter*pupilDiameterPercentageWidth) } let motionManager = MotionProvider.shared.motionManager() @objc func link(link: CADisplayLink) { // motionManager.deviceMotion?.rotationRate guard let motion = motionManager.deviceMotion else {return} // print("\(motion.rotationRate)") animation?.update(gravity: motion.gravity, acceleration: motion.userAcceleration) } override var frame: CGRect { didSet { updateDimensions() } } override func setNeedsLayout() { super.setNeedsLayout() animation = PupilBehaviorManager(googlyEye: self, center: baseCutout.startCenter, travelRadius: diameter) updateDimensions() } override func layoutIfNeeded() { super.layoutIfNeeded() animation = PupilBehaviorManager(googlyEye: self, center: baseCutout.startCenter, travelRadius: diameter) updateDimensions() } override func layoutSubviews() { super.layoutSubviews() let currentOrientation = UIApplication.shared.statusBarOrientation if orientation != currentOrientation { orientation = currentOrientation switch orientation { case .landscapeLeft: layer.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))) case .landscapeRight: layer.setAffineTransform(CGAffineTransform(rotationAngle: -CGFloat(Double.pi/2))) case .portraitUpsideDown: layer.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(Double.pi))) default: layer.setAffineTransform(.identity) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class HeatStamp: CALayer { var endCenter: CGPoint = .zero var startCenter: CGPoint = .zero let edgeShadowGradient = CGGradient(colorsSpace: nil, colors: [UIColor(red: 0.2, green: 0.1, blue: 0.2, alpha: 0.01).cgColor, UIColor(red: 0.1, green: 0.1, blue: 0.2, alpha: 0.6).cgColor, UIColor.clear.cgColor] as CFArray, locations: [0.78, 0.95, 0.999] as [CGFloat]) let innerShadowGradient = CGGradient(colorsSpace: nil, colors: [GooglyEye.paperGray(alpha: 0.2).cgColor, UIColor.clear.cgColor] as CFArray, locations: nil) func update() { endCenter = CGPoint(x: startCenter.x, y: startCenter.y) } override init(layer: Any) { super.init(layer: layer) contentsScale = UIScreen.main.scale } override init() { super.init() contentsScale = UIScreen.main.scale } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(in ctx: CGContext) { super.draw(in: ctx) let radius = GooglyEye.cutoutRadius(dimension: bounds.width) ctx.drawRadialGradient(edgeShadowGradient!, startCenter: endCenter, startRadius: radius - (bounds.width*0.5), endCenter: startCenter, endRadius: radius, options: .drawsBeforeStartLocation) ctx.drawRadialGradient(innerShadowGradient!, startCenter: endCenter, startRadius: 1, endCenter: endCenter, endRadius: radius*0.4, options: .drawsBeforeStartLocation) } } class Pupil: UIView { let diameter: CGFloat = 11.0 override var collisionBoundsType: UIDynamicItemCollisionBoundsType { get { return .ellipse } } override class var layerClass: Swift.AnyClass { return PupilLayer.self } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class PupilLayer: CAShapeLayer { override init(layer: Any) { super.init(layer: layer) contentsScale = UIScreen.main.scale fillColor = UIColor.black.cgColor } override init() { super.init() contentsScale = UIScreen.main.scale fillColor = UIColor.black.cgColor } override func setNeedsDisplay() { super.setNeedsDisplay() path = CGPath(ellipseIn: bounds, transform: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } } class Sclera: CAShapeLayer { let stampPercentSizeDifference: CGFloat = 0.1 let baseStampGradient = CGGradient(colorsSpace: nil, colors: [GooglyEye.grayColor().cgColor, UIColor.clear.cgColor] as CFArray, locations: nil) var startCenter: CGPoint = .zero var diameter: CGFloat = 0 override init(layer: Any) { super.init(layer: layer) contentsScale = UIScreen.main.scale // this one is key fillColor = GooglyEye.grayColor().cgColor } override init() { super.init() contentsScale = UIScreen.main.scale // this one is key fillColor = GooglyEye.grayColor().cgColor } override var bounds: CGRect { didSet { diameter = GooglyEye.diameterFromFrame(rectSize: bounds.size) startCenter = CGPoint(x: diameter/2, y: diameter/2) } } override func setNeedsDisplay() { super.setNeedsDisplay() path = CGPath(ellipseIn: bounds, transform: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(in ctx: CGContext) { super.draw(in: ctx) ctx.setShouldAntialias(true) ctx.setAllowsAntialiasing(true) ctx.setFillColor(GooglyEye.grayColor().cgColor) let path = CGPath(ellipseIn: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: diameter, height: diameter)), transform: nil) ctx.addPath(path) ctx.fillPath() let radius = GooglyEye.cutoutRadius(dimension: diameter) ctx.drawRadialGradient(baseStampGradient!, startCenter: startCenter, startRadius: radius - (diameter*0.05), endCenter: startCenter, endRadius: radius + (diameter*0.02), options: .drawsAfterEndLocation) } } }
0466b09080811e876a3f6e45a1098b55
37.372263
292
0.606144
false
false
false
false
Kukiwon/rfduino-swift
refs/heads/master
Pod/Classes/RFDuino.swift
mit
1
// // RFDuino.swift // Pods // // Created by Jordy van Kuijk on 27/01/16. // // import Foundation import CoreBluetooth @objc public protocol RFDuinoDelegate { @objc optional func rfDuinoDidTimeout(rfDuino: RFDuino) @objc optional func rfDuinoDidDisconnect(rfDuino: RFDuino) @objc optional func rfDuinoDidDiscover(rfDuino: RFDuino) @objc optional func rfDuinoDidDiscoverServices(rfDuino: RFDuino) @objc optional func rfDuinoDidDiscoverCharacteristics(rfDuino: RFDuino) @objc optional func rfDuinoDidSendData(rfDuino: RFDuino, forCharacteristic: CBCharacteristic, error: Error?) @objc optional func rfDuinoDidReceiveData(rfDuino: RFDuino, data: Data?) } public class RFDuino: NSObject { public var isTimedOut = false public var isConnected = false public var didDiscoverCharacteristics = false public var delegate: RFDuinoDelegate? public static let timeoutThreshold = 5.0 public var RSSI: NSNumber? var whenDoneBlock: (() -> ())? var peripheral: CBPeripheral var timeoutTimer: Timer? init(peripheral: CBPeripheral) { self.peripheral = peripheral super.init() self.peripheral.delegate = self } } /* Internal methods */ internal extension RFDuino { func confirmAndTimeout() { isTimedOut = false delegate?.rfDuinoDidDiscover?(rfDuino: self) timeoutTimer?.invalidate() timeoutTimer = nil timeoutTimer = Timer.scheduledTimer(timeInterval: RFDuino.timeoutThreshold, target: self, selector: #selector(RFDuino.didTimeout), userInfo: nil, repeats: false) } @objc func didTimeout() { isTimedOut = true isConnected = false delegate?.rfDuinoDidTimeout?(rfDuino: self) } func didConnect() { timeoutTimer?.invalidate() timeoutTimer = nil isConnected = true isTimedOut = false } func didDisconnect() { isConnected = false confirmAndTimeout() delegate?.rfDuinoDidDisconnect?(rfDuino: self) } func findCharacteristic(characteristicUUID: RFDuinoUUID, forServiceWithUUID serviceUUID: RFDuinoUUID) -> CBCharacteristic? { if let discoveredServices = peripheral.services, let service = (discoveredServices.filter { return $0.uuid == serviceUUID.id }).first, let characteristics = service.characteristics { return (characteristics.filter { return $0.uuid == characteristicUUID.id}).first } return nil } } /* Public methods */ public extension RFDuino { func discoverServices() { "Going to discover services for peripheral".log() peripheral.discoverServices([RFDuinoUUID.Discover.id]) } func sendDisconnectCommand(whenDone: @escaping () -> ()) { self.whenDoneBlock = whenDone // if no services were discovered, imediately invoke done block if peripheral.services == nil { whenDone() return } if let characteristic = findCharacteristic(characteristicUUID: RFDuinoUUID.Disconnect, forServiceWithUUID: RFDuinoUUID.Discover) { var byte = UInt8(1) let data = NSData(bytes: &byte, length: 1) peripheral.writeValue(data as Data, for: characteristic, type: .withResponse) } } func send(data: Data) { if let characteristic = findCharacteristic(characteristicUUID: RFDuinoUUID.Send, forServiceWithUUID: RFDuinoUUID.Discover) { peripheral.writeValue(data, for: characteristic, type: .withResponse) } } } /* Calculated vars */ public extension RFDuino { var name: String { get { return peripheral.name ?? "Unknown device" } } } extension RFDuino: CBPeripheralDelegate { public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { "Did send data to peripheral".log() if characteristic.uuid == RFDuinoUUID.Disconnect.id { if let doneBlock = whenDoneBlock { doneBlock() } } else { delegate?.rfDuinoDidSendData?(rfDuino: self, forCharacteristic: self.findCharacteristic(characteristicUUID: RFDuinoUUID.Send, forServiceWithUUID: RFDuinoUUID.Discover)!, error: error) } } public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { "Did discover services".log() if let discoveredServices = peripheral.services { for service in discoveredServices { if service.uuid == RFDuinoUUID.Discover.id { peripheral.discoverCharacteristics(nil, for: service) } } } delegate?.rfDuinoDidDiscoverServices?(rfDuino: self) } public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { for characteristic in service.characteristics! { ("did discover characteristic with UUID: " + characteristic.uuid.description).log() if characteristic.uuid == RFDuinoUUID.Receive.id { peripheral.setNotifyValue(true, for: characteristic) } else if characteristic.uuid == RFDuinoUUID.Send.id { peripheral.setNotifyValue(true, for: characteristic) } } "Did discover characteristics for service".log() delegate?.rfDuinoDidDiscoverCharacteristics?(rfDuino: self) } public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { "Did receive data for rfDuino".log() delegate?.rfDuinoDidReceiveData?(rfDuino: self, data: characteristic.value) } }
0840dd543cc7db4f6b1764916e7f3cd0
34.385542
195
0.655941
false
false
false
false
f2m2/f2m2-swift-forms
refs/heads/master
Cartography/Compound.swift
mit
5
// // Compound.swift // Cartography // // Created by Robert Böhnke on 18/06/14. // Copyright (c) 2014 Robert Böhnke. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif protocol Compound { var properties: [Property] { get } } func apply(from: Compound, coefficients: [Coefficients]? = nil, to: Compound? = nil, relation: NSLayoutRelation = NSLayoutRelation.Equal) -> [NSLayoutConstraint] { var results: [NSLayoutConstraint] = [] for i in 0..<from.properties.count { let n: Coefficients = coefficients?[i] ?? Coefficients() results.append(apply(from.properties[i], coefficients: n, to: to?.properties[i], relation: relation)) } return results }
f944429904f3449ada266166b17c8f83
23.62069
163
0.677871
false
false
false
false
lingyijie/DYZB
refs/heads/master
DYZB/DYZB/Class/Home/Controller/RecommendViewController.swift
mit
1
// // RecommendViewController.swift // DYZB // // Created by ling yijie on 2017/8/31. // Copyright © 2017年 ling yijie. All rights reserved. // import UIKit fileprivate let kPrettyCell = "kPrettyCell" fileprivate let kMargin : CGFloat = 10 fileprivate let kNormalItemW : CGFloat = (kScreenW - 3 * kMargin) / 2 fileprivate let kNormalItemH : CGFloat = 3 * kNormalItemW / 4 fileprivate let kPrettyItemH : CGFloat = 4 * kNormalItemW / 3 fileprivate let kCycleViewH : CGFloat = 150 fileprivate let kGameViewH : CGFloat = 90 class RecommendViewController: BaseAnchorViewController { // 数据模型 fileprivate lazy var recommendVM : RecommentVM = RecommentVM() // 推荐view fileprivate lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() // 无线循环view fileprivate lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() } extension RecommendViewController { override func setupUI() { super.setupUI() //设置上边距以显示cycleview&gameview collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) // 设置代理遵循UICollectionViewDelegateFlowLayout collectionView.delegate = self collectionView.addSubview(cycleView) collectionView.addSubview(gameView) } } extension RecommendViewController { override func loadData() { // 请求主播数据 recommendVM.requestData(){ self.baseVM = self.recommendVM self.collectionView.reloadData() self.gameView.groups = self.recommendVM.anchorGroups } // 请求无限轮播数据 recommendVM.requestCycleData { self.cycleView.cycleModelGroup = self.recommendVM.cycleGroup } //停止动画 super.stopAnimation() } } extension RecommendViewController: UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let group = recommendVM.anchorGroups[indexPath.section] let anchor = group.anchors[indexPath.item] if indexPath.section == 1 { let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCell, for: indexPath) as! CollectionPrettyCell prettyCell.anchor = anchor return prettyCell } else { return super.collectionView(collectionView, cellForItemAt: indexPath) } } // 根据section返回不同尺寸的cell func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kNormalItemW, height: kPrettyItemH) } return CGSize(width: kNormalItemW, height: kNormalItemH) } }
0589870eff04d50b67331068fbdf4d7c
34.88764
160
0.6866
false
false
false
false
iOSDevLog/iOSDevLog
refs/heads/master
Checklists/Checklists/Checklist.swift
mit
1
// // Checklist.swift // Checklists // // Created by iosdevlog on 16/1/3. // Copyright © 2016年 iosdevlog. All rights reserved. // import UIKit class Checklist: NSObject, NSCoding { var name = "" var iconName = "No Icon" var items = [ChecklistItem]() convenience init(name: String) { self.init(name: name, iconName: "No Icon") } init(name: String, iconName: String) { self.name = name self.iconName = iconName super.init() } // MARK: - protocol NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "Name") aCoder.encodeObject(iconName, forKey: "IconName") aCoder.encodeObject(items, forKey: "Items") } required init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey("Name") as! String iconName = aDecoder.decodeObjectForKey("IconName") as! String items = aDecoder.decodeObjectForKey("Items") as! [ChecklistItem] super.init() } // MARK: - Helper func countUncheckedItems() -> Int { var count = 0 for item in items where !item.checked { count += 1 } return count } }
ea90c100f3541711471aa39436fa1557
22.981132
72
0.575924
false
false
false
false
Hussain-it/Onboard-Walkthrough
refs/heads/master
Onboard-Walkthrough/Onboard-Walkthrough/MainNavigationController.swift
mit
1
// // MainNavigationController.swift // Onboard-Walkthrough // // Created by Khan Hussain on 19/10/17. // Copyright © 2017 kb. All rights reserved. // import UIKit class MainNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white //Login Controller || Home Controller based on user loggedin status if isLoggedin(){ let hvc = HomeViewController() viewControllers = [hvc] }else{ perform(#selector(showLoginController), with: nil, afterDelay: 0.001) } } fileprivate func isLoggedin() -> Bool{ return true } @objc func showLoginController(){ let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 let cv = LoginViewController(collectionViewLayout: layout) present(cv, animated: true, completion: nil) } @objc func showHomeController(){ let hvc = HomeViewController() present(hvc, animated: true, completion: nil) } }
3f201f5e5cad5f35be5221f461c7c8dc
25.133333
81
0.622449
false
false
false
false
Mayfleet/SimpleChat
refs/heads/master
Frontend/iOS/SimpleChat/Simple Chat Screenshots/Simple_Chat_Screenshots.swift
mit
1
// // Simple_Chat_Screenshots.swift // Simple Chat Screenshots // // Created by Maxim Pervushin on 18/03/16. // Copyright © 2016 Maxim Pervushin. All rights reserved. // import XCTest class Simple_Chat_Screenshots: XCTestCase { override func setUp() { super.setUp() let app = XCUIApplication() setupSnapshot(app) app.launch() } override func tearDown() { super.tearDown() } func testExample() { let app = XCUIApplication() snapshot("01ChatsListScreen") app.tables.cells.staticTexts.elementBoundByIndex(0).tap() snapshot("02ChatScreen") let collectionView = app.otherElements.containingType(.NavigationBar, identifier:"Local:3000").childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.CollectionView).element collectionView.twoFingerTap() collectionView.twoFingerTap() snapshot("03LogInScreen") app.buttons["SignUpButton"].tap() snapshot("04SignUpScreen") /* let app = XCUIApplication() snapshot("01ChatsListScreen") app.tables.cells.staticTexts["Local:3000"].tap() snapshot("02ChatScreen") let local3000NavigationBar = app.navigationBars["Local:3000"] local3000NavigationBar.buttons["Authentication"].tap() snapshot("02LogInScreen") app.buttons["Sign Up"].tap() snapshot("02SignUpScreen") let closeButton = app.buttons["Close"] closeButton.tap() closeButton.tap() local3000NavigationBar.buttons["Chats"].tap() */ /* let app = XCUIApplication() snapshot("01ChatsListScreen") app.tables.cells.staticTexts.elementBoundByIndex(0).tap() snapshot("02ChatScreen") let collectionView = app.otherElements.containingType(.NavigationBar, identifier:"Local:3000").childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.CollectionView).element // let collectionView = app.otherElements.childrenMatchingType(.CollectionView).element collectionView.twoFingerTap() collectionView.twoFingerTap() snapshot("03LogInScreen") app.buttons["SignUpButton"].tap() snapshot("04SignUpScreen") */ } }
54634aacdc5770195cfbeba10ffbc873
31.4
370
0.658315
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureForm/Sources/FeatureFormUI/Form.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import FeatureFormDomain import SwiftUI public struct PrimaryForm: View { @Binding private var form: FeatureFormDomain.Form private let submitActionTitle: String private let submitActionLoading: Bool private let submitAction: () -> Void public init( form: Binding<FeatureFormDomain.Form>, submitActionTitle: String, submitActionLoading: Bool, submitAction: @escaping () -> Void ) { _form = form self.submitActionTitle = submitActionTitle self.submitActionLoading = submitActionLoading self.submitAction = submitAction } public var body: some View { ScrollView { LazyVStack(spacing: Spacing.padding4) { if let header = form.header { VStack { Icon.user .frame(width: 32.pt, height: 32.pt) Text(header.title) .typography(.title2) Text(header.description) .typography(.paragraph1) } .multilineTextAlignment(.center) .foregroundColor(.semantic.title) } ForEach($form.nodes) { question in FormQuestionView(question: question) } PrimaryButton( title: submitActionTitle, isLoading: submitActionLoading, action: submitAction ) .disabled(!form.nodes.isValidForm) } .padding(Spacing.padding3) .background(Color.semantic.background) } } } struct PrimaryForm_Previews: PreviewProvider { static var previews: some View { let jsonData = formPreviewJSON.data(using: .utf8)! // swiftlint:disable:next force_try let formRawData = try! JSONDecoder().decode(FeatureFormDomain.Form.self, from: jsonData) PreviewHelper(form: formRawData) } struct PreviewHelper: View { @State var form: FeatureFormDomain.Form var body: some View { PrimaryForm( form: $form, submitActionTitle: "Next", submitActionLoading: false, submitAction: {} ) } } }
4c34c464d0b8e067333c0fe36df4ea8d
29.207317
96
0.547033
false
false
false
false
iNoles/NolesFootball
refs/heads/master
NolesFootball.iOS/Noles Football/DemandViewController.swift
gpl-3.0
1
// // DemandViewController.swift // Noles Football // // Created by Jonathan Steele on 5/6/16. // Copyright © 2016 Jonathan Steele. All rights reserved. // import UIKit import AVKit import AVFoundation class DemandViewController: UITableViewController { private var list = [Demand]() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() let format = DateUtils(format: "yyyy-MM-dd'T'HH:mm:ss'Z'", isGMTWithLocale: true) let dateFormatter = DateUtils(format: "EEE, MMM d, yyyy h:mm a") parseXML(withURL: "http://www.seminoles.com/XML/services/v2/onDemand.v2.dbml?DB_OEM_ID=32900&maxrows=10&start=0&spid=157113", query: "//clip", callback: { [unowned self] childNode in var demand = Demand() childNode.forEach { nodes in if nodes.tagName == "short_description" { demand.description = nodes.firstChild?.content } if nodes.tagName == "start_date" { let date = format.dateFromString(string: nodes.firstChild?.content) demand.date = dateFormatter.stringFromDate(date: date!) } if nodes.tagName == "external_m3u8" { demand.link = nodes.firstChild?.content } } self.list.append(demand) }, deferCallback: tableView.reloadData) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in _: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { // Return the number of rows in the section. return list.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "OnDemand", for: indexPath) // Configure the cell... let demand = list[indexPath.row] cell.textLabel?.text = demand.description cell.detailTextLabel?.text = demand.date return cell } // 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?) { guard let int = tableView.indexPathForSelectedRow?.row else { assertionFailure("Couldn't get TableView Selected Row") return } if let url = URL(string: list[int].link!) { let destination = segue.destination as! AVPlayerViewController destination.player = AVPlayer(url: url) } } }
489887102dcb70f78b589511fc80eda5
34.597701
190
0.627058
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Models/Map/MapLocationPoint.swift
mit
1
// // MapLocationPoint.swift // MEGameTracker // // Created by Emily Ivie on 9/26/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import UIKit public typealias MapLocationPointKey = Duplet<CGFloat, CGFloat> /// Defines a scalable location marker on a map, either square or circular. public struct MapLocationPoint: Codable { enum CodingKeys: String, CodingKey { case x case y case radius case width case height } // MARK: Properties public var x: CGFloat public var y: CGFloat public var radius: CGFloat? public var width: CGFloat public var height: CGFloat // x, y is altered for rectangles to locate center, so keep original values for encode: private var _x: CGFloat? private var _y: CGFloat? // MARK: Computed Properties public var cgRect: CGRect { return CGRect(x: x, y: y, width: width, height: height) } public var cgPoint: CGPoint { return CGPoint(x: x, y: y) } public var key: MapLocationPointKey { return MapLocationPointKey(x, y) } // MARK: Initialization public init(x: CGFloat, y: CGFloat, radius: CGFloat) { self.x = x self.y = y self.radius = radius self.width = radius * 2 self.height = radius * 2 } public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { self.x = x self.y = y self.radius = nil self.width = width self.height = height } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let x = try container.decode(CGFloat.self, forKey: .x) let y = try container.decode(CGFloat.self, forKey: .y) if let radius = try container.decodeIfPresent(CGFloat.self, forKey: .radius) { self.init(x: x, y: y, radius: radius) } else { let width = try container.decode(CGFloat.self, forKey: .width) let height = try container.decode(CGFloat.self, forKey: .height) self.init(x: x + width/2, y: y + height/2, width: width, height: height) self._x = x self._y = y } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(_x ?? x, forKey: .x) try container.encode(_y ?? y, forKey: .y) if let radius = self.radius { try container.encode(radius, forKey: .radius) } else { try container.encode(width, forKey: .width) try container.encode(height, forKey: .height) } } } // MARK: Basic Actions extension MapLocationPoint { /// Converts a map location point from where it is on a base size map to where it is on an adjusted size map. public func fromSize(_ oldSize: CGSize, toSize newSize: CGSize) -> MapLocationPoint { let ratio = newSize.width / oldSize.width let x = self.x * ratio let y = self.y * ratio if let radius = radius { let r = radius * ratio return MapLocationPoint(x: x, y: y, radius: r) } else { let w = width * ratio let h = height * ratio return MapLocationPoint(x: x, y: y, width: w, height: h) } } } //// MARK: SerializedDataStorable //extension MapLocationPoint: SerializedDataStorable { // // public func getData() -> SerializableData { // var list: [String: SerializedDataStorable?] = [:] // if let radius = self.radius { // list["x"] = "\(x)" // list["y"] = "\(y)" // list["radius"] = "\(radius)" // } else { // // rect uses top left; convert from center // list["x"] = "\(x - (width / 2))" // list["y"] = "\(y - (height / 2))" // list["width"] = "\(width)" // list["height"] = "\(height)" // } // return SerializableData.safeInit(list) // } // //} // //// MARK: SerializedDataRetrievable //extension MapLocationPoint: SerializedDataRetrievable { // // public init?(data: SerializableData?) { // guard let data = data, // var x = data["x"]?.cgFloat, // var y = data["y"]?.cgFloat // else { // return nil // } // // if let width = data["width"]?.cgFloat, let height = data["height"]?.cgFloat { // // rect uses top left; convert to center // x += (width / 2) // y += (height / 2) // self.init(x: x, y: y, width: width, height: height) // } else { // self.init(x: x, y: y, radius: data["radius"]?.cgFloat ?? 0) // } // } // // public mutating func setData(_ data: SerializableData) {} //} // MARK: Equatable extension MapLocationPoint: Equatable { public static func == ( _ lhs: MapLocationPoint, _ rhs: MapLocationPoint ) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } }
23980eb247d631ac574911ad15c28377
29.528662
110
0.592739
false
false
false
false
catalanjrj/BarMate
refs/heads/master
BarMateCustomer/BarMateCustomer/barMenuViewViewController.swift
cc0-1.0
1
// // barMenuViewViewController.swift // BarMateCustomer // // Created by Jorge Catalan on 6/23/16. // Copyright © 2016 Jorge Catalan. All rights reserved. // import UIKit import Firebase import FirebaseDatabase class barMenuViewViewController:UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var barMenuTableView: UITableView! @IBOutlet weak var barNameLabel: UILabel! var ref : FIRDatabaseReference = FIRDatabase.database().reference() var barMenuArray = [String]() var barMenuDict = [String:Drink]() override func viewDidLoad() { super.viewDidLoad() //present drinkReady Alert drinkReadyPopUp() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // remove observers when user leaves view self.ref.removeAllObservers() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) bars() } // retrive barMenus func bars(){ self.ref.child("Bars").child("aowifjeafasg").observeEventType(FIRDataEventType.Value, withBlock: {(snapshot) in guard snapshot.value != nil else{ return } self.barMenuArray = [String]() self.barMenuDict = [String:Drink]() for (key,value)in snapshot.value!["barMenu"] as! [String:AnyObject]{ self.barMenuArray.append(key) self.barMenuDict[key] = Drink(data: value as! [String:AnyObject]) } dispatch_async(dispatch_get_main_queue(), {self.barMenuTableView.reloadData()}) }) } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return barMenuArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("drinkMenuTableCell", forIndexPath: indexPath)as! drinkMenuTableCell let label = barMenuArray[indexPath.row] let bar = barMenuDict[label] cell.configurMenuCell(bar!) return cell } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "drinkDetailView"{ if let indexPath = self.barMenuTableView.indexPathForSelectedRow{ let object = barMenuArray[indexPath.row] let destinationViewController = segue.destinationViewController as! confirmOrderViewController destinationViewController.drink = barMenuDict[object] } } // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } func barNameLabel(bar:Bar){ barNameLabel.text = bar.barName } func drinkReadyPopUp(){ _ = self.ref.child("Orders/completed/").queryOrderedByChild("bar").queryEqualToValue("aowifjeafasg").observeEventType(FIRDataEventType.ChildAdded, withBlock: {(snapshot) in if snapshot.value != nil{ let drinkReadyAlert = UIAlertController(title:"Order Status", message: "Your order is ready for pick up!", preferredStyle: .Alert) let okAction = UIAlertAction(title:"Ok",style: .Default){(action) in } drinkReadyAlert.addAction(okAction) self.presentViewController(drinkReadyAlert, animated:true){} }else{ return } }) } }
92baa548751251095d79efe181494f53
30.376812
180
0.604157
false
false
false
false
RevenueCat/purchases-ios
refs/heads/main
Tests/UnitTests/Purchasing/PurchasesDeprecation.swift
mit
1
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // PurchasesDeprecation.swift // // Created by Joshua Liebowitz on 10/18/21. import Foundation import RevenueCat // Protocol that enables us to call deprecated methods without triggering warnings. protocol PurchasesDeprecatable { var allowSharingAppStoreAccount: Bool { get set } static func addAttributionData(_ data: [String: Any], fromNetwork network: AttributionNetwork) static func addAttributionData(_ data: [String: Any], from network: AttributionNetwork, forNetworkUserId networkUserId: String?) static var automaticAppleSearchAdsAttributionCollection: Bool { get set } } class PurchasesDeprecation: PurchasesDeprecatable { let purchases: Purchases init(purchases: Purchases) { self.purchases = purchases } @available(*, deprecated) var allowSharingAppStoreAccount: Bool { get { return purchases.allowSharingAppStoreAccount } set { purchases.allowSharingAppStoreAccount = newValue } } @available(*, deprecated) static func addAttributionData(_ data: [String: Any], fromNetwork network: AttributionNetwork) { Purchases.addAttributionData(data, fromNetwork: network) } @available(*, deprecated) static func addAttributionData(_ data: [String: Any], from network: AttributionNetwork, forNetworkUserId networkUserId: String?) { Purchases.addAttributionData(data, from: network, forNetworkUserId: networkUserId) } @available(*, deprecated) static var automaticAppleSearchAdsAttributionCollection: Bool { get { return Purchases.automaticAppleSearchAdsAttributionCollection } set { Purchases.automaticAppleSearchAdsAttributionCollection = newValue } } } extension Purchases { /** * Computed property you should use if you receive deprecation warnings. This is a proxy for a Purchases object. * By calling `.deprecated` you will have access to the same API, but it won't trigger a deprecation. * If you need to set a property that is deprecated, you'll need to create a var in your test to hold a copy of * the `deprecated` object. This is because the `deprecated` property is computed and so you cannot mutate it. * e.g.: * var deprecatedVarObject = purchases.deprecated * deprecatedVarObject.allowSharingAppStoreAccount = true */ var deprecated: PurchasesDeprecatable { return PurchasesDeprecation(purchases: self) } /** * Computed property you should use if you receive deprecation warnings. This is a proxy for the Purchases class. * By calling `.deprecated` you will have access to the same API, but it won't trigger a deprecation. */ static var deprecated: PurchasesDeprecatable.Type { return PurchasesDeprecation.self } }
0c363119ea2b56ddaf1e918dfbd4896d
34.086957
117
0.686493
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/BlockchainNamespace/Sources/BlockchainNamespace/Session/Session+Event.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation extension Session { public typealias Events = PassthroughSubject<Session.Event, Never> public struct Event: Identifiable, Hashable { public let id: UInt public let date: Date public let origin: Tag.Event public let reference: Tag.Reference public let context: Tag.Context public let source: (file: String, line: Int) public var tag: Tag { reference.tag } init( date: Date = Date(), origin: Tag.Event, reference: Tag.Reference, context: Tag.Context = [:], file: String = #fileID, line: Int = #line ) { id = Self.id self.date = date self.origin = origin self.reference = reference self.context = context source = (file, line) } public func hash(into hasher: inout Hasher) { hasher.combine(id) } public static func == (lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id } } } extension Session.Event: CustomStringConvertible { public var description: String { String(describing: origin) } } extension Session.Event { private static var count: UInt = 0 private static let lock = NSLock() private static var id: UInt { lock.lock() defer { lock.unlock() } count += 1 return count } } extension Publisher where Output == Session.Event { public func filter(_ type: L) -> Publishers.Filter<Self> { filter(type[]) } public func filter(_ type: Tag) -> Publishers.Filter<Self> { filter([type]) } public func filter(_ type: Tag.Reference) -> Publishers.Filter<Self> { filter([type]) } public func filter<S: Sequence>(_ types: S) -> Publishers.Filter<Self> where S.Element == Tag { filter { $0.tag.is(types) } } public func filter<S: Sequence>(_ types: S) -> Publishers.Filter<Self> where S.Element == Tag.Reference { filter { event in types.contains { type in event.reference == type || (event.tag.is(type.tag) && type.indices.allSatisfy { event.reference.indices[$0] == $1 }) } } } } extension AppProtocol { @inlinable public func on( _ first: Tag.Event, _ rest: Tag.Event..., file: String = #fileID, line: Int = #line, action: @escaping (Session.Event) throws -> Void ) -> BlockchainEventSubscription { on([first] + rest, file: file, line: line, action: action) } @inlinable public func on( _ first: Tag.Event, _ rest: Tag.Event..., file: String = #fileID, line: Int = #line, priority: TaskPriority? = nil, action: @escaping (Session.Event) async throws -> Void ) -> BlockchainEventSubscription { on([first] + rest, file: file, line: line, priority: priority, action: action) } @inlinable public func on<Events>( _ events: Events, file: String = #fileID, line: Int = #line, action: @escaping (Session.Event) throws -> Void ) -> BlockchainEventSubscription where Events: Sequence, Events.Element: Tag.Event { on(events.map { $0 as Tag.Event }, file: file, line: line, action: action) } @inlinable public func on<Events>( _ events: Events, file: String = #fileID, line: Int = #line, priority: TaskPriority? = nil, action: @escaping (Session.Event) async throws -> Void ) -> BlockchainEventSubscription where Events: Sequence, Events.Element: Tag.Event { on(events.map { $0 as Tag.Event }, file: file, line: line, priority: priority, action: action) } @inlinable public func on<Events>( _ events: Events, file: String = #fileID, line: Int = #line, action: @escaping (Session.Event) throws -> Void ) -> BlockchainEventSubscription where Events: Sequence, Events.Element == Tag.Event { BlockchainEventSubscription( app: self, events: Array(events), file: file, line: line, action: action ) } @inlinable public func on<Events>( _ events: Events, file: String = #fileID, line: Int = #line, priority: TaskPriority? = nil, action: @escaping (Session.Event) async throws -> Void ) -> BlockchainEventSubscription where Events: Sequence, Events.Element == Tag.Event { BlockchainEventSubscription( app: self, events: Array(events), file: file, line: line, priority: priority, action: action ) } } public final class BlockchainEventSubscription: Hashable { enum Action { case sync((Session.Event) throws -> Void) case async((Session.Event) async throws -> Void) } let id: UInt let app: AppProtocol let events: [Tag.Event] let action: Action let priority: TaskPriority? let file: String, line: Int deinit { stop() } @usableFromInline init( app: AppProtocol, events: [Tag.Event], file: String, line: Int, action: @escaping (Session.Event) throws -> Void ) { id = Self.id self.app = app self.events = events self.file = file self.line = line priority = nil self.action = .sync(action) } @usableFromInline init( app: AppProtocol, events: [Tag.Event], file: String, line: Int, priority: TaskPriority? = nil, action: @escaping (Session.Event) async throws -> Void ) { id = Self.id self.app = app self.events = events self.file = file self.line = line self.priority = priority self.action = .async(action) } private var subscription: AnyCancellable? @discardableResult public func start() -> Self { guard subscription == nil else { return self } subscription = app.on(events).sink( receiveValue: { [weak self] event in guard let self = self else { return } switch self.action { case .sync(let action): do { try action(event) } catch { self.app.post(error: error, file: self.file, line: self.line) } case .async(let action): Task(priority: self.priority) { do { try await action(event) } catch { self.app.post(error: error, file: self.file, line: self.line) } } } } ) return self } public func cancel() { stop() } @discardableResult public func stop() -> Self { subscription?.cancel() subscription = nil return self } } extension BlockchainEventSubscription { @inlinable public func subscribe() -> AnyCancellable { start() return AnyCancellable { [self] in stop() } } private static var count: UInt = 0 private static let lock = NSLock() private static var id: UInt { lock.lock() defer { lock.unlock() } count += 1 return count } public static func == (lhs: BlockchainEventSubscription, rhs: BlockchainEventSubscription) -> Bool { lhs.id == rhs.id } public func hash(into hasher: inout Hasher) { hasher.combine(id) } }
13dbe8099f948d21af0b8364fae9fb2d
27.117857
109
0.546806
false
false
false
false
kamawshuang/iOS---Animation
refs/heads/master
Spring(一)/iOS Animation(一)--First:Spring/Animation-First/ViewController.swift
apache-2.0
1
// // ViewController.swift // Animation-First // // Created by 51Testing on 15/11/26. // Copyright © 2015年 HHW. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tilteLab: UILabel! @IBOutlet weak var userTF: UITextField! @IBOutlet weak var passwordTF: UITextField! @IBOutlet weak var loginbutton: UIButton! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var rightImageView: UIImageView! @IBOutlet weak var tomImageView: UIImageView! //在视图将要出现的时候改变坐标 override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) tilteLab.frame.origin.x -= view.frame.width userTF.frame.origin.x -= view.frame.width passwordTF.frame.origin.x -= view.frame.width rightImageView.frame.origin.x -= view.frame.width tomImageView.frame.origin.x -= view.frame.width } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(0.5) { () -> Void in self.tilteLab.frame.origin.x += self.view.frame.width } UIView.animateWithDuration(0.5, delay: 0.2, options: [], animations: { self.userTF.frame.origin.x += self.view.frame.width }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.6, options: [], animations: { self.passwordTF.frame.origin.x += self.view.frame.width }, completion: nil) //旋转角度,顺时针转 /// 创建了一个旋转的结构,参数是一个CGFloat类型的角度,这里我们使用预定义好的常量比如M_PI代表3.14...,也就是旋转一周、M_PI_2代表1.57...,也就是旋转半周等 let rotation = CGAffineTransformMakeRotation(CGFloat(M_PI)) UIView.animateWithDuration(1, animations: { self.loginbutton.transform = rotation }) //缩放 /// 首先创建了一个缩放的结构,第一个参数是x轴的缩放比例,第二个参数是y轴的缩放比例。 let scale = CGAffineTransformMakeScale(0.5, 0.5) UIView.animateWithDuration(0.5, animations: { self.imageView.transform = scale }) // animationWithDuration(_:delay:options:animations:completion:)方法,其中的options当时没有详细的讲述,这节会向大家说明该属性。options选项可以使你自定义让UIKit如何创建你的动画。该属性需要一个或多个UIAnimationOptions枚举类型,让我们来看看都有哪些动画选项吧。 /** 重复类 .Repeat:该属性可以使你的动画永远重复的运行。 .Autoreverse:该属性可以使你的动画当运行结束后按照相反的行为继续运行回去。该属性只能和.Repeat属性组合使用。 */ UIView.animateWithDuration(2, delay: 0.5, options: [.Repeat, .Autoreverse], animations: { self.rightImageView.center.x += self.view.bounds.width }, completion: nil) /** 动画缓冲 */ /** .CurveLinear :该属性既不会使动画加速也不会使动画减速,只是做以线性运动。 .CurveEaseIn:该属性使动画在开始时加速运行。 .CurveEaseOut:该属性使动画在结束时减速运行。 .CurveEaseInOut:该属性结合了上述两种情况,使动画在开始时加速,在结束时减速。 */ UIView.animateWithDuration(2, delay: 1, options: [.Repeat, .Autoreverse, .CurveEaseOut], animations: { self.tomImageView.frame.origin.x += self.view.frame.width }, completion: nil) } /** usingSpringWithDamping:弹簧动画的阻尼值,也就是相当于摩擦力的大小,该属性的值从0.0到1.0之间,越靠近0,阻尼越小,弹动的幅度越大,反之阻尼越大,弹动的幅度越小,如果大道一定程度,会出现弹不动的情况。 initialSpringVelocity:弹簧动画的速率,或者说是动力。值越小弹簧的动力越小,弹簧拉伸的幅度越小,反之动力越大,弹簧拉伸的幅度越大。这里需要注意的是,如果设置为0,表示忽略该属性,由动画持续时间和阻尼计算动画的效果。 */ /** 以下为设置同样的时间,不同的阻尼系数,不同的动力的效果;并在动画中增大宽和高 */ @IBAction func doClickloginButton(sender: AnyObject) { UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 30, options: .AllowUserInteraction, animations: { self.loginbutton.center.y += 30; }, completion: nil) } @IBAction func doClickRegister(sender: UIButton) { UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .AllowAnimatedContent, animations: { sender.center.y += 30 sender.bounds.size.width += 10 }, completion: nil) } @IBAction func doClickExit(sender: UIButton) { UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 10, options: .AllowAnimatedContent, animations: { sender.center.y += 30 sender.bounds.size.height += 10 }, completion: nil) } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
f1a1f8abbc4cdaf8a3c81952d71128a5
25.719577
189
0.586733
false
false
false
false
TZLike/GiftShow
refs/heads/master
GiftShow/GiftShow/Classes/CategoryPage/Controller/LeeCategoryViewController.swift
apache-2.0
1
// // LeeCategoryViewController.swift // GiftShow // // Created by admin on 16/10/27. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit //import SnapKit private let titleHeight:CGFloat = 44 class LeeCategoryViewController: UIViewController { //底部的数据控件 fileprivate lazy var bottomView:LeeHotBottomView = { var arr:[UIViewController] = [UIViewController]() arr.append(LeeRaidersViewController()) arr.append(LeeSingleProductViewController()) let view = LeeHotBottomView(frame:CGRect(x: 0, y: 35, width: WIDTH, height: HEIGHT - 35),vcs:arr,parent:self) view.delegate = self return view }() //搜索 fileprivate lazy var search:LeeHomeSearchView = { let view = LeeHomeSearchView.getInfo() view.backgroundColor = UIColor.colorWithHexString("FDF5F3") view.layer.cornerRadius = 12.5 view.delegate = self view.clipsToBounds = true return view }() //头部banner fileprivate lazy var topBanner:LeeCategoryNavView = {[weak self] in let topBanner = LeeCategoryNavView(frame:CGRect(x: 0, y: 0, width: WIDTH / 3 - 20 ,height: titleHeight),arrs:["攻略","单品"]) topBanner.delegate = self topBanner.backgroundColor = UIColor.white return topBanner }() override func viewDidLoad() { super.viewDidLoad() setNav() view.backgroundColor = UIColor.white navigationController?.navigationBar.shadowImage = UIImage() } } extension LeeCategoryViewController { fileprivate func setNav(){ navigationItem.titleView = topBanner view.addSubview(search) view.addSubview(bottomView) search.snp.makeConstraints { (make) in make.left.equalTo(view).offset(15) make.right.equalTo(view).offset(-15) make.top.equalTo(view).offset(5) make.height.equalTo(25) } // showAge(age: 10) } } extension LeeCategoryViewController :LeeCategoryNavViewDelegate { func categoryTopTitleClick(_ hot: LeeCategoryNavView, index: Int) { self.bottomView.changePageControler(index) } // func showAge(age:Int){ // print(age) // } } extension LeeCategoryViewController :LeeHomeSearchViewDelegate { func searchBtnClick() { print("aaa") } } //MARK:改变collectionView的页码 extension LeeCategoryViewController :LeePageContentViewDelegate { func scrollContentIndex(_ pageContent: LeeHotBottomView, progress: CGFloat, targetIndex: Int, sourceIndex: Int) { topBanner.showProgress(progress, targetInex: targetIndex, sourceIndex: sourceIndex) } }
89e45c8225b037151c4e70e38ac32c87
26.712871
129
0.637728
false
false
false
false
giangbvnbgit128/AnViet
refs/heads/master
AnViet/Class/Helpers/Network/AVUploadRouter.swift
apache-2.0
1
// // File.swift // AnViet // // Created by Bui Giang on 6/11/17. // Copyright © 2017 Bui Giang. All rights reserved. // import UIKit import Alamofire enum PostEndPoint { case UploadImage case PostNews(userId:String,token:String,image:String,content:String) } class AVUploadRouter : AVBaseRouter { var endpoint: PostEndPoint var UrlConfig:URL? init(endpoint: PostEndPoint) { self.endpoint = endpoint } func getUrl() -> String { return self.baseUrl + "api/upload_image" } override var path: String { switch endpoint { case .PostNews(let userId,let token,let image,let content): return "api/create_post?user_id=\(userId)&token=\(token)&image=\(image)&content=\(content)" case .UploadImage: return "api/upload_image" default: break } } override var parameters: APIParams { return nil } override var encoding: Alamofire.ParameterEncoding? { return URLEncoding() } }
0501c80405f3722548fb85bad154482d
21.434783
159
0.627907
false
false
false
false
ushios/SwifTumb
refs/heads/master
Sources/SwifTumb/SwifTumb.swift
mit
1
// // SwifTumb.swift // SwifTumb // // Created by Ushio Shugo on 2016/12/11. // // import Foundation /// Tumblr client written by Swift open class SwifTumb { static let EnvConsumerKey: String = "SWIFTUMB_CONSUMER_KEY" static let EnvConsumerSecret: String = "SWIFTUMB_CONSUMER_SECRET" static let EnvOAuthToken: String = "SWIFTUMB_OAUTH_TOKEN" static let EnvOAuthTokenSecret: String = "SWIFTUMB_OAUTH_TOKEN_SECRET" /// Post types /// /// - Text: text post type /// - Quote: quote post type /// - Link: link post type /// - Answer: answer post type /// - Video: video post type /// - Audio: audio post type /// - Photo: photo post type /// - Chat: chat post type public enum PostType: String { case Text = "text" case Quote = "quote" case Link = "link" case Answer = "answer" case Video = "video" case Audio = "audio" case Photo = "photo" case Chat = "chat" } public static let DefaultProtocol: String = "https" public static let DefaultHost: String = "api.tumblr.com" public static let DefaultVersion: String = "v2" public static let RequestTokenUrl: String = "https://www.tumblr.com/oauth/request_token" public static let AuthorizeUrl: String = "https://www.tumblr.com/oauth/authorize" public static let AccessTokenUrl: String = "https://www.tumblr.com/oauth/access_token" /// OAuth adapter private var adapter: SwifTumbOAuthAdapter /// Make base url /// /// - Returns: url open static func baseUrl() -> String { return "\(SwifTumb.DefaultProtocol)://\(SwifTumb.DefaultHost)/\(SwifTumb.DefaultVersion)" } /// Make endpoint url /// /// - Parameter path: path string without prefix slash /// - Returns: endpoint url open static func url(_ path: String) -> String { return "\(SwifTumb.baseUrl())/\(path)" } /// init /// /// - Parameter adapter: oauth adapter public init(adapter: SwifTumbOAuthAdapter) { self.adapter = adapter } /// init /// /// - Parameters: /// - consumerKey: consumer key /// - consumerSecret: consumer secret /// - oauthToken: oauth token /// - oauthTokenSecret: oauth token secret public convenience init( consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String ) { let adapter = OAuthSwiftAdapter( consumerKey: consumerKey, consumerSecret: consumerSecret, oauthToken: oauthToken, oauthTokenSecret: oauthTokenSecret ) self.init(adapter: adapter) } /// init from environments public convenience init?() { guard let consumerKey = getenv(SwifTumb.EnvConsumerKey), let consumerSecret = getenv(SwifTumb.EnvConsumerSecret), let oauthToken = getenv(SwifTumb.EnvOAuthToken), let oauthTokenSecret = getenv(SwifTumb.EnvOAuthTokenSecret) else { return nil } self.init( consumerKey: String(utf8String: consumerKey) ?? "", consumerSecret: String(utf8String: consumerSecret) ?? "", oauthToken: String(utf8String: oauthToken) ?? "", oauthTokenSecret: String(utf8String: oauthTokenSecret) ?? "" ) } /// Request to tumblr api /// /// - Parameters: /// - urlString: path /// - method: HTTP method /// - paramHolder: parameter struct /// - headers: HTTP headers /// - body: request body /// - checkTokenExpiration: <#checkTokenExpiration description#> /// - success: success handler /// - failure: failure handler /// - Returns: request handle private func request( _ urlString: String, method: SwifTumbHttpRequest.Method, paramHolder: SwifTumbParameterHolder? = nil, headers: SwifTumb.Headers? = nil, body: Data? = nil, checkTokenExpiration: Bool = true, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) -> SwifTumbRequestHandle? { var params: [String: Any] if paramHolder == nil { params = [:] } else { params = paramHolder!.parameters() } return self.adapter.request(urlString, method: method, parameters: params, headers: headers, body: body, checkTokenExpiration: checkTokenExpiration, success: success, failure: failure) } /// Request user/info api /// /// - Parameters: /// - success: success handler /// - failure: failure handler /// - Returns: request handle /// - Throws: request exceptions open func userInfo( success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { let handle = self.request( SwifTumb.url("user/info"), method: SwifTumbHttpRequest.Method.GET, success: success, failure: failure ) return handle } /// Request parameters for user/dashboard public struct UserDashboardParameters: SwifTumbParameterHolder { var limit: Int? var offset: Int? var type: SwifTumb.PostType? var sinceId: Int? var reblogInfo: Bool? var notesInfo: Bool? } /// Request user/dashboard api /// /// - Parameters: /// - params: user/dashboard parameter /// - success: sucess handler /// - failure: failure handler /// - Returns: request handle /// - Throws: request exceptions open func userDashboard( params: UserDashboardParameters? = nil, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { let handle = self.request( SwifTumb.url("user/dashboard"), method: SwifTumbHttpRequest.Method.GET, paramHolder: params, success: success, failure: failure ) return handle } /// Request parameters for user/likes public struct UserLikesParameters: SwifTumbParameterHolder { var limit: Int? var offset: Int? var before: Int? var after: Int? } /// Request user/likes api /// /// - Parameters: /// - params: user/likes parameter /// - success: success handler /// - failure: failure handler /// - Returns: request handle /// - Throws: request exceptions open func userLikes( params: UserLikesParameters? = nil, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { let handle = self.request( SwifTumb.url("user/likes"), method: SwifTumbHttpRequest.Method.GET, paramHolder: params, success: success, failure: failure ) return handle } /// Request parameters for posts public struct PostsParameters: SwifTumbParameterHolder { var blogIdentifier: String var type: PostType? var id: Int? var tag: String? var limit: Int? var offset: Int? var reblogInfo: Bool? var notesInfo: Bool? var filter: String? } /// Request /blog/xxxx/posts api /// /// - Parameters: /// - params: posts parameters /// - success: success handler /// - failure: failure handler /// - Returns: request handle /// - Throws: request exceptions open func posts( params: PostsParameters, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { var url: String if params.type != nil { url = SwifTumb.url("blog/\(params.blogIdentifier)/posts/\(params.type!.rawValue)") } else { url = SwifTumb.url("blog/\(params.blogIdentifier)/posts") } let handle = self.request( url, method: SwifTumbHttpRequest.Method.GET, paramHolder: params, success: success, failure: failure ) return handle } /// Request parameters for post/reblog public struct PostReblogParameters: SwifTumbParameterHolder { var blogIdentifier: String var id: Int? var reblogKey: String? var comment: String? var nativeInlineImages: Bool? } open func postReblog( params: PostReblogParameters, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { let handle = self.request( SwifTumb.url("blog/\(params.blogIdentifier)/post/reblog"), method: SwifTumbHttpRequest.Method.POST, paramHolder: params, success: success, failure: failure ) return handle } } extension SwifTumb { public typealias Parameters = [String : Any] public typealias Headers = [String : String] } extension SwifTumb.UserDashboardParameters { public func parameters() -> [String : Any] { var param: [String: Any] = [:] if self.limit != nil { param["limit"] = self.limit! } if self.offset != nil { param["offset"] = self.offset! } if self.type != nil { param["type"] = self.type!.rawValue } if self.sinceId != nil { param["since_id"] = self.sinceId! } if self.reblogInfo != nil { param["reblog_info"] = self.reblogInfo! } if self.notesInfo != nil { param["notes_info"] = self.notesInfo! } return param } } extension SwifTumb.PostsParameters { public init(_ blogIdentifier: String) { self.blogIdentifier = blogIdentifier } public func parameters() -> [String : Any] { var param: [String: Any] = [:] if self.id != nil { param["id"] = self.id! } if self.tag != nil { param["tag"] = self.tag! } if self.limit != nil { param["limit"] = self.limit! } if self.offset != nil { param["offset"] = self.offset! } if self.reblogInfo != nil { param["reblog_info"] = self.reblogInfo! } if self.notesInfo != nil { param["notes_info"] = self.notesInfo! } if self.filter != nil { param["filter"] = self.filter! } return param } } extension SwifTumb.PostReblogParameters { public init( _ blogIdentifier: String, id: Int? = nil, reblogKey: String? = nil, comment: String? = nil, nativeInlineImages: Bool? = nil ) { self.blogIdentifier = blogIdentifier self.id = id ?? nil self.reblogKey = reblogKey ?? nil self.comment = comment self.nativeInlineImages = nativeInlineImages } public func parameters() -> [String: Any] { var param: [String: Any] = [:] param["id"] = self.id param["reblog_key"] = self.reblogKey if self.comment != nil { param["comment"] = self.comment } if self.nativeInlineImages != nil { param["native_inline_images"] = self.nativeInlineImages } return param } } extension SwifTumb.UserLikesParameters { public func parameters() -> [String: Any] { var param: [String: Any] = [:] if self.limit != nil { param["limit"] = self.limit! } if self.offset != nil { param["offset"] = self.offset } if self.after != nil { param["after"] = self.after } if self.before != nil { param["before"] = self.before } return param } } /// Parameters protocol public protocol SwifTumbParameterHolder { /// Get request parameters map /// /// - Returns: parameters func parameters() -> [String: Any] }
9116e4dc330b62daf4d9ab507dbc2d1f
27.48
192
0.560003
false
false
false
false
olejnjak/KartingCoach
refs/heads/development
KartingCoach/Model/LapTime.swift
gpl-3.0
1
// // LapTime.swift // KartingCoach // // Created by Jakub Olejník on 01/09/2017. // import Foundation struct LapTime: Codable { static var zero: LapTime { return LapTime(duration: 0) } var minutes: Int { return duration / 1000 / 60 } var seconds: Int { return duration / 1000 % 60 } var miliseconds: Int { return duration % 1000 } let duration: Int } extension LapTime { init(minutes: Int, seconds: Int, miliseconds: Int) { self.init(duration: minutes * 60 * 1000 + seconds * 1000 + miliseconds) } init?(string: String) { if let int = Int(string) { self.init(duration: int) } else { var components = string.trimmingCharacters(in: .whitespacesAndNewlines) .components(separatedBy: CharacterSet(charactersIn: ".:")) .compactMap { Int($0) } if components.isEmpty { return nil } var duration = components.last ?? 0 components.removeLast() if components.isEmpty { self.init(duration: duration) return } duration += components.last.flatMap { $0 * 1000 } ?? 0 components.removeLast() if components.isEmpty { self.init(duration: duration) return } duration += components.last.flatMap { $0 * 1000 * 60 } ?? 0 if duration > 0 { self.init(duration: duration) } else { return nil } } } } extension LapTime: CustomStringConvertible { var description: String { let secondsAndMiliseconds = String(format: "%02d", seconds) + "." + String(format: "%03d", miliseconds) return minutes > 0 ? String(minutes) + ":" + secondsAndMiliseconds : secondsAndMiliseconds } } extension LapTime: CustomDebugStringConvertible { var debugDescription: String { return "\(self)" } } extension LapTime: Comparable { static func < (lhs: LapTime, rhs: LapTime) -> Bool { return lhs.duration < rhs.duration } static func == (lhs: LapTime, rhs: LapTime) -> Bool { return lhs.duration == rhs.duration } } func + (lhs: LapTime, rhs: LapTime) -> LapTime { return LapTime(duration: lhs.duration + rhs.duration) } func / (lhs: LapTime, rhs: Int) -> LapTime { return LapTime(duration: lhs.duration / rhs) } extension Collection where Iterator.Element == LapTime { func average() -> Iterator.Element? { if isEmpty { return nil } return reduce(.zero, +) / Int(count) } }
a8aa945d3672816116ec743534a6efde
26.555556
111
0.557185
false
false
false
false
alexmiragall/Gourmet-iOS
refs/heads/master
gourmet/gourmet/viewcontrollers/FirstViewController.swift
mit
1
// // FirstViewController.swift // gourmet // // Created by Alejandro Miragall Arnal on 15/3/16. // Copyright © 2016 Alejandro Miragall Arnal. All rights reserved. // import UIKit import MapKit import Firebase import AlamofireImage class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MKMapViewDelegate, CLLocationManagerDelegate, GIDSignInUIDelegate { @IBOutlet var mapView: MKMapView! @IBOutlet var tableView: UITableView! let locationManager = CLLocationManager() var restaurantRepository: RestaurantsRepository! var items: [Restaurant] = [] var userManager = UserManager.instance @IBAction func viewChanged(sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { tableView.hidden = true mapView.hidden = false } else { tableView.hidden = false mapView.hidden = true } } override func viewDidLoad() { super.viewDidLoad() userManager.signIn(self, callback: { (error, errorType) in if (error) { print("Error login: \(errorType)") } else { print("Success login") } }) restaurantRepository = RestaurantsRepository() let nib = UINib(nibName: "RestaurantTableViewCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: RestaurantTableViewCell.name) locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() mapView.delegate = self getRestaurants() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueToRestaurantDetail" { let viewController = segue.destinationViewController as! RestaurantDetailViewController viewController.hidesBottomBarWhenPushed = true viewController.restaurant = sender as? Restaurant } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .Authorized, .AuthorizedWhenInUse: manager.startUpdatingLocation() self.mapView.showsUserLocation = true default: break } } func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { let region = MKCoordinateRegionMakeWithDistance ( userLocation.location!.coordinate, 10000, 10000) mapView.setRegion(region, animated: true) } override func viewDidAppear(animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:RestaurantTableViewCell = self.tableView.dequeueReusableCellWithIdentifier(RestaurantTableViewCell.name) as! RestaurantTableViewCell let restaurant:Restaurant = self.items[indexPath.row] cell.loadItem(title: restaurant.name, image: restaurant.photo, completion: { cell.setNeedsLayout() }) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) performSegueWithIdentifier("segueToRestaurantDetail", sender: self.items[indexPath.row]) print("You selected cell #\(indexPath.row)!") } func getRestaurants() { restaurantRepository.getItems({ self.items.appendContentsOf($0) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() self.updateMap() }) }) } func updateMap() { for rest in items { mapView.addAnnotation(RestaurantItem(title: rest.name, coordinate: CLLocationCoordinate2D(latitude: rest.lat!, longitude: rest.lon!), info: rest.description)) } } }
1e28f56db5b0d9345391da4d6f5062b0
33.677419
170
0.665116
false
false
false
false
kinetic-fit/sensors-swift
refs/heads/master
SwiftySensorsExample/ServiceDetailsViewController.swift
mit
1
// // ServiceDetailsViewController.swift // SwiftySensors // // https://github.com/kinetic-fit/sensors-swift // // Copyright © 2017 Kinetic. All rights reserved. // import UIKit import SwiftySensors class ServiceDetailsViewController: UIViewController { var service: Service! @IBOutlet var nameLabel: UILabel! @IBOutlet var tableView: UITableView! fileprivate var characteristics: [Characteristic] = [] override func viewDidLoad() { super.viewDidLoad() service.sensor.onCharacteristicDiscovered.subscribe(with: self) { [weak self] sensor, characteristic in self?.rebuildData() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) nameLabel.text = "\(service!)".components(separatedBy: ".").last rebuildData() } fileprivate func rebuildData() { characteristics = Array(service.characteristics.values) tableView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let charViewController = segue.destination as? CharacteristicViewController { guard let indexPath = tableView.indexPathForSelectedRow else { return } if indexPath.row >= characteristics.count { return } charViewController.characteristic = characteristics[indexPath.row] } } } extension ServiceDetailsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let charCell = tableView.dequeueReusableCell(withIdentifier: "CharCell")! let characteristic = characteristics[indexPath.row] charCell.textLabel?.text = "\(characteristic)".components(separatedBy: ".").last return charCell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return characteristics.count } }
ed040f85c4378e3e54084248cbb80cc1
28.214286
111
0.664059
false
false
false
false
czerenkow/LublinWeather
refs/heads/master
App/Dashboard/DashboardInteractor.swift
mit
1
// // DashboardInteractor.swift // LublinWeather // // Created by Damian Rzeszot on 24/04/2018. // Copyright © 2018 Damian Rzeszot. All rights reserved. // import Foundation final class DashboardInteractor: Interactor { weak var router: DashboardRouter! weak var presentable: DashboardPresentable! // MARK: - var fetch: WeatherFetchService! var provider: StationsListProvider! var selected: SelectedStationWorker! var tracker: Tracker<DashboardEvent>! // MARK: - var station: Station! var measurements: [DashboardViewModel.Measurement: String]! var obsolete: Bool! // MARK: - override func activate() { super.activate() tracker.track(.activate) } override func deactivate() { super.deactivate() tracker.track(.deactivate) } // MARK: - Helpers private func reload() { let active = selected.load() let stations = provider.load().flatMap { $0.stations } station = stations.first(where: { $0.identifier == active }) ?? stations.first refresh() } private func update(loading: Bool = false) { let model = DashboardViewModel(station: station?.name ?? "???", loading: loading, obsolete: obsolete ?? false, measurements: self.measurements ?? [:]) presentable.configure(with: model) } } extension DashboardInteractor: DashboardOutput { func appearing() { reload() } func stations() { tracker.track(.stations) router.stations() } func settings() { tracker.track(.settings) router.settings() } func refresh() { tracker.track(.refresh(station?.source ?? "nil")) update(loading: true) fetch.fetch(identifier: station.identifier) { result in if let value = result.value { let measurements: [DashboardViewModel.Measurement: String?] = [ .date: self.format(date: value.date), .temperatureAir: self.format(number: value.temperatureAir), .temperatureGround: self.format(number: value.temperatureGround), .temperaturePerceptible: self.format(number: value.temperaturePerceptible), .pressure: self.format(number: value.pressure), .rain: self.format(number: value.rain), .windSpeed: self.format(number: value.windSpeed), .windDirection: self.format(direction: value.windDirection), .humidity: self.format(number: value.humidity) ] self.obsolete = value.obsolete self.measurements = measurements.filter { $0.value != nil }.mapValues { $0! } } else if let error = result.error { print("error \(error)") } self.update() } } private func format(date: Date?) -> String? { guard let date = date else { return nil } let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm" return formatter.string(from: date) } private func format(number: Double?) -> String? { guard let number = number else { return nil } let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.usesGroupingSeparator = true formatter.minimumFractionDigits = 1 formatter.maximumFractionDigits = 1 return formatter.string(from: NSNumber(value: number)) } private func format(direction: WeatherResult.Direction?) -> String? { guard let direction = direction else { return nil } return String(direction) } }
850994b8688c9ad46de025d74c959429
27.212121
158
0.603921
false
false
false
false
IvanVorobei/RequestPermission
refs/heads/master
Example/SPPermission/SPPermission/Frameworks/SPPermission/SPPermissionType.swift
mit
2
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @objc public enum SPPermissionType: Int { case camera = 0 case photoLibrary = 1 case notification = 2 case microphone = 3 case calendar = 4 case contacts = 5 case reminders = 6 case speech = 7 case locationWhenInUse = 9 case locationAlwaysAndWhenInUse = 10 case motion = 11 case mediaLibrary = 12 var name: String { switch self { case .camera: return "Camera" case .photoLibrary: return "Photo Library" case .notification: return "Notification" case .microphone: return "Microphone" case .calendar: return "Calendar" case .contacts: return "Contacts" case .reminders: return "Reminders" case .speech: return "Speech" case .locationWhenInUse, .locationAlwaysAndWhenInUse: return "Location" case .motion: return "Motion" case .mediaLibrary: return "Media Library" } } var usageDescriptionKey: String? { switch self { case .camera: return "NSCameraUsageDescription" case .photoLibrary: return "NSPhotoLibraryUsageDescription" case .notification: return nil case .microphone: return "NSMicrophoneUsageDescription" case .calendar: return "NSCalendarsUsageDescription" case .contacts: return "NSContactsUsageDescription" case .reminders: return "NSRemindersUsageDescription" case .speech: return "NSSpeechRecognitionUsageDescription" case .locationWhenInUse: return "NSLocationWhenInUseUsageDescription" case .locationAlwaysAndWhenInUse: return "NSLocationAlwaysAndWhenInUseUsageDescription" case .motion: return "NSMotionUsageDescription" case .mediaLibrary: return "NSAppleMusicUsageDescription" } } }
e56f9f8a00af707323b8139f484a06c8
33.468085
81
0.65
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/stdlib/Accelerate_vDSPClippingLimitThreshold.swift
apache-2.0
8
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: rdar50301438 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Accelerate var Accelerate_vDSPClippingLimitThresholdTests = TestSuite("Accelerate_vDSPClippingLimitThreshold") //===----------------------------------------------------------------------===// // // vDSP clipping, limit, and threshold tests; single-precision. // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { let count = 256 let n = vDSP_Length(256) let bounds = Float(-0.5) ... Float(0.5) let outputConstant: Float = 99 let source: [Float] = (0 ..< 256).map { i in return sin(Float(i) * 0.05) + sin(Float(i) * 0.025) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionClipping") { var result = [Float](repeating: 0, count: count) vDSP.clip(source, to: bounds, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vclip(source, 1, [bounds.lowerBound], [bounds.upperBound], &legacyResult, 1, n) let returnedResult = vDSP.clip(source, to: bounds) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionInvertedClipping") { var result = [Float](repeating: 0, count: count) vDSP.invertedClip(source, to: bounds, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_viclip(source, 1, [bounds.lowerBound], [bounds.upperBound], &legacyResult, 1, n) let returnedResult = vDSP.invertedClip(source, to: bounds) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThreshold") { var result = [Float](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .clampToThreshold, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vthr(source, 1, [bounds.lowerBound], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .clampToThreshold) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThresholdWithConstant") { var result = [Float](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .signedConstant(outputConstant), result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vthrsc(source, 1, [bounds.lowerBound], [outputConstant], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .signedConstant(outputConstant)) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThresholdWithZeroFill") { var result = [Float](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .zeroFill, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vthres(source, 1, [bounds.lowerBound], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .zeroFill) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionLimit") { var result = [Float](repeating: 0, count: count) vDSP.limit(source, limit: bounds.upperBound, withOutputConstant: outputConstant, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vlim(source, 1, [bounds.upperBound], [outputConstant], &legacyResult, 1, n) let returnedResult = vDSP.limit(source, limit: bounds.upperBound, withOutputConstant: outputConstant) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } } //===----------------------------------------------------------------------===// // // vDSP clipping, limit, and threshold tests; double-precision. // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { let count = 256 let n = vDSP_Length(256) let bounds = Double(-0.5) ... Double(0.5) let outputConstant: Double = 99 let source: [Double] = (0 ..< 256).map { i in return sin(Double(i) * 0.05) + sin(Double(i) * 0.025) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionClipping") { var result = [Double](repeating: 0, count: count) vDSP.clip(source, to: bounds, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vclipD(source, 1, [bounds.lowerBound], [bounds.upperBound], &legacyResult, 1, n) let returnedResult = vDSP.clip(source, to: bounds) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionInvertedClipping") { var result = [Double](repeating: 0, count: count) vDSP.invertedClip(source, to: bounds, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_viclipD(source, 1, [bounds.lowerBound], [bounds.upperBound], &legacyResult, 1, n) let returnedResult = vDSP.invertedClip(source, to: bounds) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThreshold") { var result = [Double](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .clampToThreshold, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vthrD(source, 1, [bounds.lowerBound], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .clampToThreshold) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThresholdWithConstant") { var result = [Double](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .signedConstant(outputConstant), result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vthrscD(source, 1, [bounds.lowerBound], [outputConstant], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .signedConstant(outputConstant)) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThresholdWithZeroFill") { var result = [Double](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .zeroFill, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vthresD(source, 1, [bounds.lowerBound], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .zeroFill) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionLimit") { var result = [Double](repeating: 0, count: count) vDSP.limit(source, limit: bounds.upperBound, withOutputConstant: outputConstant, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vlimD(source, 1, [bounds.upperBound], [outputConstant], &legacyResult, 1, n) let returnedResult = vDSP.limit(source, limit: bounds.upperBound, withOutputConstant: outputConstant) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } } runAllTests()
5dead1d7ac556724025568a1c5bd3ac7
34.431818
99
0.466325
false
true
false
false
Rapid-SDK/ios
refs/heads/master
Examples/RapiDO - ToDo list/RapiDO tvOS/FilterViewController.swift
mit
1
// // FilterViewController.swift // ExampleApp // // Created by Jan on 05/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import UIKit import Rapid protocol FilterViewControllerDelegate: class { func filterViewControllerDidCancel(_ controller: FilterViewController) func filterViewControllerDidFinish(_ controller: FilterViewController, withFilter filter: RapidFilter?) } class FilterViewController: UIViewController { weak var delegate: FilterViewControllerDelegate? var filter: RapidFilter? @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var tagsTableView: TagsTableView! @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var cancelButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setupUI() } // MARK: Actions @IBAction func cancel(_ sender: Any) { delegate?.filterViewControllerDidCancel(self) } @IBAction func done(_ sender: Any) { var operands = [RapidFilter]() // Segmented control selected index equal to 1 means "show all tasks regardless completion state", so no filter is needed // Otherwise, create filter for either completed or incompleted tasks if segmentedControl.selectedSegmentIndex != 1 { let completed = segmentedControl.selectedSegmentIndex == 0 operands.append(RapidFilter.equal(keyPath: Task.completedAttributeName, value: completed)) } // Create filter for selected tags let selectedTags = tagsTableView.selectedTags if selectedTags.count > 0 { var tagFilters = [RapidFilter]() for tag in selectedTags { tagFilters.append(RapidFilter.arrayContains(keyPath: Task.tagsAttributeName, value: tag.rawValue)) } // Combine single tag filters with logical "OR" operator operands.append(RapidFilter.or(tagFilters)) } // If there are any filters combine them with logical "AND" let filter: RapidFilter? if operands.count > 0 { filter = RapidFilter.and(operands) } else { filter = nil } delegate?.filterViewControllerDidFinish(self, withFilter: filter) } } fileprivate extension FilterViewController { func setupUI() { if let expression = filter?.expression, case .compound(_, let operands) = expression { var tagsSet = false var completionSet = false for operand in operands { switch operand { case .simple(_, _, let value): completionSet = true let done = value as? Bool ?? false let index = done ? 0 : 2 segmentedControl.selectedSegmentIndex = index case .compound(_, let operands): tagsSet = true var tags = [Tag]() for case .simple(_, _, let value) in operands { switch value as? String { case .some(Tag.home.rawValue): tags.append(.home) case .some(Tag.work.rawValue): tags.append(.work) case .some(Tag.other.rawValue): tags.append(.other) default: break } } tagsTableView.selectTags(tags) } } if !tagsSet { tagsTableView.selectTags([]) } if !completionSet { segmentedControl.selectedSegmentIndex = 1 } } else { segmentedControl.selectedSegmentIndex = 1 tagsTableView.selectTags([]) } setupFocusGuide() } func setupFocusGuide() { let doneGuide = UIFocusGuide() doneGuide.preferredFocusEnvironments = [doneButton] view.addLayoutGuide(doneGuide) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .bottom, relatedBy: .equal, toItem: doneButton, attribute: .top, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .right, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .left, multiplier: 1, constant: 0)) let segmentGuide = UIFocusGuide() segmentGuide.preferredFocusEnvironments = [segmentedControl] view.addLayoutGuide(segmentGuide) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .centerY, relatedBy: .equal, toItem: segmentedControl, attribute: .centerY, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .left, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .right, multiplier: 1, constant: 0)) } }
d719d8fb9350feb78a30240fb3652c4d
38.973154
181
0.588146
false
false
false
false
asynchrony/Re-Lax
refs/heads/master
ReLaxExample/StaticTextViewController.swift
mit
1
import UIKit import ReLax class StaticTextViewController: UIViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) tabBarItem = UITabBarItem(title: "Static Text", image: nil, tag: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { guard let image = UIImage(contentsOfFile: Bundle.main.path(forResource: "monstersinc", ofType: "lcr")!) else { fatalError("monstersinc LCR missing") } let example = StaticTextExampleView(layerContainer: DefaultContainer(views: [UIImageView(image: image)])) let parallaxParent = StaticTextParentButton(standardLCR: image, exampleView: example) view = parallaxParent view.backgroundColor = .darkGray } private var images: [UIImage] { return (1...5) .map { "\($0)" } .map { UIImage(contentsOfFile: Bundle.main.path(forResource: $0, ofType: "png")!)! } } private func generateLCR() -> UIImage? { let parallaxImage = ParallaxImage(images: Array(images.reversed())) return parallaxImage.image() } } class StaticTextExampleView: ParallaxView<DefaultContainer> { private let label = UILabel() override init(layerContainer: DefaultContainer, effectMultiplier: CGFloat = 1.0, sheenContainer: UIView? = nil) { super.init(layerContainer: layerContainer, effectMultiplier: effectMultiplier, sheenContainer: sheenContainer) label.text = "Release Date: 11/2/2001\nRunning Time: 1h 32m" label.numberOfLines = 0 label.font = UIFont.boldSystemFont(ofSize: 30) label.textAlignment = .center label.textColor = .white label.shadowColor = UIColor(white: 0.0, alpha: 0.5) addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() label.frame = bounds.divided(atDistance: 150, from: .maxYEdge).slice } }
7d95fbb9ceb595d7c3f530490e428c75
32.779661
152
0.736076
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/Model/Sfo/MSfoHeaderFactory.swift
mit
1
import Foundation extension MSfoHeader { static let kBytes:Int = 20 private static let kElements:Int = 5 //MARK: internal static func factoryHeader( data:Data) -> MSfoHeader? { guard let array:[UInt32] = data.arrayFromBytes( elements:kElements) else { return nil } let rawMagic:UInt32 = array[0] let rawVersion:UInt32 = array[1] let rawKeysOffset:UInt32 = array[2] let rawValuesOffset:UInt32 = array[3] let rawCount:UInt32 = array[4] let magic:Int = Int(rawMagic) let version:Int = Int(rawVersion) let keysOffset:Int = Int(rawKeysOffset) let valuesOffset:Int = Int(rawValuesOffset) let count:Int = Int(rawCount) let header:MSfoHeader = MSfoHeader( magic:magic, version:version, keysOffset:keysOffset, valuesOffset:valuesOffset, count:count) return header } }
598fcaceeabf74fac429498199ee7f0c
23.636364
53
0.54428
false
false
false
false
OrielBelzer/StepCoin
refs/heads/master
Models/User.swift
mit
1
// // User.swift // StepCoin // // Created by Oriel Belzer on 12/22/16. // import ObjectMapper import Haneke class User: NSObject, NSCoding, Mappable { var id: Int? var email: String? var password: String? var phoneNumber: String? var notificationId: String? var credits: String? var createTime: String? var coins: [Coin2]? required init?(map: Map) { } func mapping(map: Map) { id <- map["id"] email <- map["email"] password <- map["password"] phoneNumber <- map["phoneNumber"] notificationId <- map["notificationId"] credits <- map["credits"] createTime <- map["createTime"] coins <- map["coins"] } //MARK: NSCoding required init(coder aDecoder: NSCoder) { self.id = aDecoder.decodeObject(forKey: "id") as? Int self.email = aDecoder.decodeObject(forKey: "email") as? String self.password = aDecoder.decodeObject(forKey: "password") as? String self.phoneNumber = aDecoder.decodeObject(forKey: "phoneNumber") as? String self.notificationId = aDecoder.decodeObject(forKey: "notificationId") as? String self.credits = aDecoder.decodeObject(forKey: "credits") as? String self.createTime = aDecoder.decodeObject(forKey: "createTime") as? String self.coins = aDecoder.decodeObject(forKey: "coins") as? [Coin2] } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(email, forKey: "email") aCoder.encode(password, forKey: "password") aCoder.encode(phoneNumber, forKey: "phoneNumber") aCoder.encode(notificationId, forKey: "notificationId") aCoder.encode(credits, forKey: "credits") aCoder.encode(createTime, forKey: "createTime") aCoder.encode(coins, forKey: "coins") } } extension User : DataConvertible, DataRepresentable { public typealias Result = User public class func convertFromData(_ data:Data) -> Result? { return NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? User } public func asData() -> Data! { return (NSKeyedArchiver.archivedData(withRootObject: self) as NSData!) as Data! } }
b3a6c21346a16f09aa9c9c2e115a7186
31.027397
88
0.616339
false
false
false
false
DrabWeb/Azusa
refs/heads/master
Source/Azusa/Azusa/View Controllers/MusicPlayerController.swift
gpl-3.0
1
// // MusicPlayerController.swift // Azusa // // Created by Ushio on 2/10/17. // import Cocoa import Yui class MusicPlayerController: NSViewController { // MARK: - Properties // MARK: Public Properties var splitViewController : MusicPlayerSplitViewController! { return childViewControllers[0] as? MusicPlayerSplitViewController } var playerBarController : PlayerBarController! { return childViewControllers[1] as? PlayerBarController; } // MARK: Private Properties private var musicSource : MusicSource! { didSet { musicSource.eventManager.add(subscriber: EventSubscriber(events: [.connect, .player, .queue, .options, .database], performer: { event in self.musicSource.getPlayerStatus({ status, _ in self.playerBarController.display(status: status); self.playerBarController.canSkipPrevious = status.currentSongPosition != 0; if status.playingState == .stopped || status.currentSong.isEmpty { self.popOutPlayerBar(); } else { self.popInPlayerBar(); } }); // Keep the mini queue updated if self.playerBarController.isQueueOpen { self.playerBarController.onQueueOpen?(); } })); musicSource.connect(nil); } } private var window : NSWindow! private weak var playerBarBottomConstraint : NSLayoutConstraint! // MARK: - Methods // MARK: Public Methods override func viewDidLoad() { super.viewDidLoad(); initialize(); // I don't even // Maybe temporary? Creating an IBOutlet to the constraint(or even the player bar) makes the window not appear view.constraints.forEach { c in if c.identifier == "playerBarBottomConstraint" { self.playerBarBottomConstraint = c; return; } } NotificationCenter.default.addObserver(forName: PreferencesNotification.loaded, object: nil, queue: nil, using: { _ in let d = PluginManager.global.defaultPlugin!; self.musicSource = d.getPlugin!.getMusicSource(settings: d.settings); }); } func sourceMenuItemPressed(_ sender : NSMenuItem) { let p = (sender.representedObject as! PluginInfo); musicSource = p.getPlugin!.getMusicSource(settings: p.settings); } func popInPlayerBar(animate : Bool = true) { NSAnimationContext.runAnimationGroup({ (context) in context.duration = animate ? 0.2 : 0; context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn); playerBarBottomConstraint.animator().constant = 0; }, completionHandler: nil); } func popOutPlayerBar(animate : Bool = true) { NSAnimationContext.runAnimationGroup({ (context) in context.duration = animate ? 0.2 : 0; context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn); playerBarBottomConstraint.animator().constant = -62; }, completionHandler: nil); } // MARK: Private methods private func initialize() { window = NSApp.windows.last!; window.appearance = NSAppearance(named: NSAppearanceNameVibrantLight); window.styleMask.insert(NSWindowStyleMask.fullSizeContentView); window.titleVisibility = .hidden; // Set up all the player bar actions playerBarController.onSeek = { time in self.musicSource.seek(to: time, completionHandler: nil); }; self.playerBarController.onRepeat = { mode in self.musicSource.setRepeatMode(to: mode.next(), completionHandler: nil); }; self.playerBarController.onPrevious = { playingState in self.musicSource.skipPrevious(completionHandler: nil); }; self.playerBarController.onPausePlay = { _ in // TODO: Make MusicSource use playing states instead of bools self.musicSource.togglePaused(completionHandler: { state, _ in self.playerBarController.display(playingState: state ? .playing : .paused); }); }; self.playerBarController.onNext = { playingState in self.musicSource.skipNext(completionHandler: nil); }; self.playerBarController.onShuffle = { self.musicSource.shuffleQueue(completionHandler: nil); }; self.playerBarController.onVolumeChanged = { volume in self.musicSource.setVolume(to: volume, completionHandler: nil); }; self.playerBarController.onQueueOpen = { self.musicSource.getQueue(completionHandler: { songs, currentPos, _ in // Drop the songs before and the current song so only up next songs are shown self.playerBarController.display(queue: Array(songs.dropFirst(currentPos + 1))); }); }; self.playerBarController.onClear = { self.musicSource.clearQueue(completionHandler: nil); }; Timer.scheduledTimer(timeInterval: TimeInterval(0.25), target: self, selector: #selector(MusicPlayerController.updateProgress), userInfo: nil, repeats: true); } internal func updateProgress() { self.musicSource.getElapsed({ elapsed, _ in self.playerBarController.display(progress: elapsed); }); } }
7e3a2ae5c0cc5c6fdbc8d042c7ddd494
35.31677
166
0.598084
false
false
false
false
getsocial-im/getsocial-ios-sdk
refs/heads/master
example/GetSocialDemo/Views/Communities/Groups/CreateGroups/CreateGroupViewController.swift
apache-2.0
1
// // CreateGroupsViewController.swift // GetSocialInternalDemo // // Created by Gábor Vass on 09/10/2020. // Copyright © 2020 GrambleWorld. All rights reserved. // import Foundation import UIKit class CreateGroupViewController: UIViewController { var oldGroup: Group? var model: CreateGroupModel private let scrollView = UIScrollView() private let idLabel = UILabel() private let idText = UITextFieldWithCopyPaste() private let titleLabel = UILabel() private let titleText = UITextFieldWithCopyPaste() private let descriptionLabel = UILabel() private let descriptionText = UITextFieldWithCopyPaste() private let avatarImageUrlLabel = UILabel() private let avatarImageUrlText = UITextFieldWithCopyPaste() private let avatarImage = UIImageView() private var avatarImageHeightConstraint: NSLayoutConstraint? private let avatarAddImageButton = UIButton(type: .roundedRect) private let avatarClearImageButton = UIButton(type: .roundedRect) private let allowPostLabel = UILabel() private let allowPostSegmentedControl = UISegmentedControl() private let allowInteractLabel = UILabel() private let allowInteractSegmentedControl = UISegmentedControl() private let property1KeyLabel = UILabel() private let property1KeyText = UITextFieldWithCopyPaste() private let property1ValueLabel = UILabel() private let property1ValueText = UITextFieldWithCopyPaste() private let isDiscoverableLabel = UILabel() private let isDiscoverableSwitch = UISwitch() private let isPrivateLabel = UILabel() private let isPrivateSwitch = UISwitch() private let labelsLabel = UILabel() private let labelsValueText = UITextFieldWithCopyPaste() private let createButton = UIButton(type: .roundedRect) private var isKeyboardShown = false private let imagePicker = UIImagePickerController() required init(_ groupToEdit: Group? = nil) { self.oldGroup = groupToEdit self.model = CreateGroupModel(oldGroupId: groupToEdit?.id) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { setup() setupModel() } private func setupModel() { self.model.onGroupCreated = { [weak self] group in self?.hideActivityIndicatorView() self?.showAlert(withTitle: "Group created", andText: group.description) } self.model.onGroupUpdated = { [weak self] group in self?.hideActivityIndicatorView() self?.showAlert(withTitle: "Group updated", andText: group.description) } self.model.onError = { [weak self] error in self?.hideActivityIndicatorView() self?.showAlert(withTitle: "Error", andText: "Failed to create group, error: \(error)") } } private func setup() { // setup keyboard observers NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) self.view.backgroundColor = UIDesign.Colors.viewBackground self.scrollView.translatesAutoresizingMaskIntoConstraints = false self.scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height + 300) self.view.addSubview(self.scrollView) NSLayoutConstraint.activate([ self.scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.scrollView.topAnchor.constraint(equalTo: self.view.topAnchor), self.scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), ]) setupIdRow() setupTitleRow() setupDescriptionRow() setupAvatarImageUrlRow() setupAvatarImageRow() setupAllowPostRow() setupAllowInteractRow() setupProperty1KeyRow() setupProperty1ValueRow() setupIsDiscoverableRow() setupIsPrivateRow() setupLabelsRow() setupCreateButton() } private func setupIdRow() { self.idLabel.translatesAutoresizingMaskIntoConstraints = false self.idLabel.text = "Group ID" self.idLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.idLabel) NSLayoutConstraint.activate([ self.idLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.idLabel.trailingAnchor.constraint(equalTo: self.scrollView.trailingAnchor, constant: -8), self.idLabel.topAnchor.constraint(equalTo: self.scrollView.topAnchor, constant: 8), self.idLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.idText.translatesAutoresizingMaskIntoConstraints = false self.idText.borderStyle = .roundedRect self.idText.isEnabled = true if let oldGroup = self.oldGroup { self.idText.text = oldGroup.id self.idText.isEnabled = false } self.scrollView.addSubview(self.idText) NSLayoutConstraint.activate([ self.idText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.idText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.idText.topAnchor.constraint(equalTo: self.idLabel.bottomAnchor, constant: 4), self.idText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupTitleRow() { self.titleLabel.translatesAutoresizingMaskIntoConstraints = false self.titleLabel.text = "Name" self.titleLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.titleLabel) NSLayoutConstraint.activate([ self.titleLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.titleLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.titleLabel.topAnchor.constraint(equalTo: self.idText.bottomAnchor, constant: 8), self.titleLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.titleText.translatesAutoresizingMaskIntoConstraints = false self.titleText.borderStyle = .roundedRect self.titleText.text = self.oldGroup?.title self.scrollView.addSubview(self.titleText) NSLayoutConstraint.activate([ self.titleText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.titleText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.titleText.topAnchor.constraint(equalTo: self.titleLabel.bottomAnchor, constant: 4), self.titleText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupDescriptionRow() { self.descriptionLabel.translatesAutoresizingMaskIntoConstraints = false self.descriptionLabel.text = "Description" self.descriptionLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.descriptionLabel) NSLayoutConstraint.activate([ self.descriptionLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.descriptionLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.descriptionLabel.topAnchor.constraint(equalTo: self.titleText.bottomAnchor, constant: 8), self.descriptionLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.descriptionText.translatesAutoresizingMaskIntoConstraints = false self.descriptionText.borderStyle = .roundedRect self.descriptionText.text = self.oldGroup?.groupDescription self.scrollView.addSubview(self.descriptionText) NSLayoutConstraint.activate([ self.descriptionText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.descriptionText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.descriptionText.topAnchor.constraint(equalTo: self.descriptionLabel.bottomAnchor, constant: 4), self.descriptionText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupAvatarImageUrlRow() { self.avatarImageUrlLabel.translatesAutoresizingMaskIntoConstraints = false self.avatarImageUrlLabel.text = "Avatar URL" self.avatarImageUrlLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.avatarImageUrlLabel) NSLayoutConstraint.activate([ self.avatarImageUrlLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.avatarImageUrlLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.avatarImageUrlLabel.topAnchor.constraint(equalTo: self.descriptionText.bottomAnchor, constant: 8), self.avatarImageUrlLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.avatarImageUrlText.translatesAutoresizingMaskIntoConstraints = false self.avatarImageUrlText.borderStyle = .roundedRect self.avatarImageUrlText.text = self.oldGroup?.avatarUrl self.scrollView.addSubview(self.avatarImageUrlText) NSLayoutConstraint.activate([ self.avatarImageUrlText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.avatarImageUrlText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.avatarImageUrlText.topAnchor.constraint(equalTo: self.avatarImageUrlLabel.bottomAnchor, constant: 4), self.avatarImageUrlText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupAvatarImageRow() { self.avatarImage.translatesAutoresizingMaskIntoConstraints = false self.avatarImage.isHidden = true self.scrollView.addSubview(self.avatarImage) self.avatarAddImageButton.translatesAutoresizingMaskIntoConstraints = false self.avatarAddImageButton.isHidden = false self.avatarAddImageButton.setTitle("Select", for: .normal) self.avatarAddImageButton.addTarget(self, action: #selector(selectImage), for: .touchUpInside) self.scrollView.addSubview(self.avatarAddImageButton) self.avatarClearImageButton.translatesAutoresizingMaskIntoConstraints = false self.avatarClearImageButton.isHidden = true self.avatarClearImageButton.setTitle("Clear", for: .normal) self.avatarClearImageButton.addTarget(self, action: #selector(clearImage), for: .touchUpInside) self.scrollView.addSubview(self.avatarClearImageButton) self.avatarImageHeightConstraint = self.avatarImage.heightAnchor.constraint(equalToConstant: 0) NSLayoutConstraint.activate([ self.avatarImage.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.avatarImage.topAnchor.constraint(equalTo: self.avatarImageUrlText.bottomAnchor, constant: 8), self.avatarImage.widthAnchor.constraint(equalToConstant: 200), self.avatarImageHeightConstraint!, ]) NSLayoutConstraint.activate([ self.avatarAddImageButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.avatarAddImageButton.topAnchor.constraint(equalTo: self.avatarImage.bottomAnchor, constant: 8), self.avatarAddImageButton.heightAnchor.constraint(equalToConstant: 30), self.avatarAddImageButton.widthAnchor.constraint(equalToConstant: 100) ]) NSLayoutConstraint.activate([ self.avatarClearImageButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 8), self.avatarClearImageButton.topAnchor.constraint(equalTo: self.avatarImage.bottomAnchor, constant: 8), self.avatarClearImageButton.heightAnchor.constraint(equalToConstant: 30), self.avatarClearImageButton.widthAnchor.constraint(equalToConstant: 100) ]) } private func setupAllowPostRow() { self.allowPostLabel.translatesAutoresizingMaskIntoConstraints = false self.allowPostLabel.text = "Allow Post" self.allowPostLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.allowPostLabel) NSLayoutConstraint.activate([ self.allowPostLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.allowPostLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.allowPostLabel.topAnchor.constraint(equalTo: self.avatarAddImageButton.bottomAnchor, constant: 8), self.allowPostLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.allowPostSegmentedControl.translatesAutoresizingMaskIntoConstraints = false self.allowPostSegmentedControl.insertSegment(withTitle: "Owner", at: 0, animated: false) self.allowPostSegmentedControl.insertSegment(withTitle: "Admin", at: 1, animated: false) self.allowPostSegmentedControl.insertSegment(withTitle: "Member", at: 2, animated: false) self.allowPostSegmentedControl.selectedSegmentIndex = 0 if let oldGroup = self.oldGroup { let oldValue = oldGroup.settings.permissions[CommunitiesAction.post]?.rawValue ?? 0 if oldValue == 3 { self.allowPostSegmentedControl.selectedSegmentIndex = 2 } else { self.allowPostSegmentedControl.selectedSegmentIndex = oldValue } } self.scrollView.addSubview(self.allowPostSegmentedControl) NSLayoutConstraint.activate([ self.allowPostSegmentedControl.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.allowPostSegmentedControl.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.allowPostSegmentedControl.topAnchor.constraint(equalTo: self.allowPostLabel.bottomAnchor, constant: 8), self.allowPostSegmentedControl.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupAllowInteractRow() { self.allowInteractLabel.translatesAutoresizingMaskIntoConstraints = false self.allowInteractLabel.text = "Allow Interact" self.allowInteractLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.allowInteractLabel) NSLayoutConstraint.activate([ self.allowInteractLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.allowInteractLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.allowInteractLabel.topAnchor.constraint(equalTo: self.allowPostSegmentedControl.bottomAnchor, constant: 8), self.allowInteractLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.allowInteractSegmentedControl.translatesAutoresizingMaskIntoConstraints = false self.allowInteractSegmentedControl.insertSegment(withTitle: "Owner", at: 0, animated: false) self.allowInteractSegmentedControl.insertSegment(withTitle: "Admin", at: 1, animated: false) self.allowInteractSegmentedControl.insertSegment(withTitle: "Member", at: 2, animated: false) self.allowInteractSegmentedControl.selectedSegmentIndex = 0 if let oldGroup = self.oldGroup { let oldValue = oldGroup.settings.permissions[CommunitiesAction.comment]?.rawValue ?? 0 if oldValue == 3 { self.allowInteractSegmentedControl.selectedSegmentIndex = 2 } else { self.allowInteractSegmentedControl.selectedSegmentIndex = oldValue } } self.scrollView.addSubview(self.allowInteractSegmentedControl) NSLayoutConstraint.activate([ self.allowInteractSegmentedControl.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.allowInteractSegmentedControl.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.allowInteractSegmentedControl.topAnchor.constraint(equalTo: self.allowInteractLabel.bottomAnchor, constant: 8), self.allowInteractSegmentedControl.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupProperty1KeyRow() { self.property1KeyLabel.translatesAutoresizingMaskIntoConstraints = false self.property1KeyLabel.text = "Property key" self.property1KeyLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.property1KeyLabel) NSLayoutConstraint.activate([ self.property1KeyLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.property1KeyLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.property1KeyLabel.topAnchor.constraint(equalTo: self.allowInteractSegmentedControl.bottomAnchor, constant: 8), self.property1KeyLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.property1KeyText.translatesAutoresizingMaskIntoConstraints = false self.property1KeyText.borderStyle = .roundedRect self.property1KeyText.text = self.oldGroup?.settings.properties.first?.key self.scrollView.addSubview(self.property1KeyText) NSLayoutConstraint.activate([ self.property1KeyText.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.property1KeyText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.property1KeyText.topAnchor.constraint(equalTo: self.property1KeyLabel.bottomAnchor, constant: 4), self.property1KeyText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupProperty1ValueRow() { self.property1ValueLabel.translatesAutoresizingMaskIntoConstraints = false self.property1ValueLabel.text = "Property value" self.property1ValueLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.property1ValueLabel) NSLayoutConstraint.activate([ self.property1ValueLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.property1ValueLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.property1ValueLabel.topAnchor.constraint(equalTo: self.property1KeyText.bottomAnchor, constant: 8), self.property1ValueLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.property1ValueText.translatesAutoresizingMaskIntoConstraints = false self.property1ValueText.borderStyle = .roundedRect self.property1ValueText.text = self.oldGroup?.settings.properties.first?.value self.scrollView.addSubview(self.property1ValueText) NSLayoutConstraint.activate([ self.property1ValueText.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.property1ValueText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.property1ValueText.topAnchor.constraint(equalTo: self.property1ValueLabel.bottomAnchor, constant: 4), self.property1ValueText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupIsDiscoverableRow() { self.isDiscoverableLabel.translatesAutoresizingMaskIntoConstraints = false self.isDiscoverableLabel.text = "Discoverable?" self.isDiscoverableLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.isDiscoverableLabel) NSLayoutConstraint.activate([ self.isDiscoverableLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.isDiscoverableLabel.topAnchor.constraint(equalTo: self.property1ValueText.bottomAnchor, constant: 8), self.isDiscoverableLabel.widthAnchor.constraint(equalToConstant: 200), self.isDiscoverableLabel.heightAnchor.constraint(equalToConstant: 30) ]) self.isDiscoverableSwitch.translatesAutoresizingMaskIntoConstraints = false if let oldGroup = self.oldGroup { self.isDiscoverableSwitch.isOn = oldGroup.settings.isDiscovarable } self.scrollView.addSubview(self.isDiscoverableSwitch) NSLayoutConstraint.activate([ self.isDiscoverableSwitch.leadingAnchor.constraint(equalTo: self.isDiscoverableLabel.trailingAnchor, constant: 8), self.isDiscoverableSwitch.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.isDiscoverableSwitch.centerYAnchor.constraint(equalTo: self.isDiscoverableLabel.centerYAnchor), self.isDiscoverableSwitch.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupIsPrivateRow() { self.isPrivateLabel.translatesAutoresizingMaskIntoConstraints = false self.isPrivateLabel.text = "Private?" self.isPrivateLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.isPrivateLabel) NSLayoutConstraint.activate([ self.isPrivateLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.isPrivateLabel.topAnchor.constraint(equalTo: self.isDiscoverableSwitch.bottomAnchor, constant: 8), self.isPrivateLabel.widthAnchor.constraint(equalToConstant: 200), self.isPrivateLabel.heightAnchor.constraint(equalToConstant: 40) ]) self.isPrivateSwitch.translatesAutoresizingMaskIntoConstraints = false if let oldGroup = self.oldGroup { self.isPrivateSwitch.isOn = oldGroup.settings.isPrivate } self.scrollView.addSubview(self.isPrivateSwitch) NSLayoutConstraint.activate([ self.isPrivateSwitch.leadingAnchor.constraint(equalTo: self.isPrivateLabel.trailingAnchor, constant: 8), self.isPrivateSwitch.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.isPrivateSwitch.centerYAnchor.constraint(equalTo: self.isPrivateLabel.centerYAnchor), self.isPrivateSwitch.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupLabelsRow() { self.labelsLabel.translatesAutoresizingMaskIntoConstraints = false self.labelsLabel.text = "Labels" self.labelsLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.labelsLabel) NSLayoutConstraint.activate([ self.labelsLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.labelsLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.labelsLabel.topAnchor.constraint(equalTo: self.isPrivateLabel.bottomAnchor, constant: 8), self.labelsLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.labelsValueText.translatesAutoresizingMaskIntoConstraints = false self.labelsValueText.borderStyle = .roundedRect self.labelsValueText.text = self.oldGroup?.settings.labels.joined(separator: ",") self.labelsValueText.placeholder = "label1,label2" self.scrollView.addSubview(self.labelsValueText) NSLayoutConstraint.activate([ self.labelsValueText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.labelsValueText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.labelsValueText.topAnchor.constraint(equalTo: self.labelsLabel.bottomAnchor, constant: 4), self.labelsValueText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupCreateButton() { self.createButton.translatesAutoresizingMaskIntoConstraints = false self.createButton.setTitle(self.oldGroup == nil ? "Create": "Update", for: .normal) self.createButton.addTarget(self, action: #selector(executeCreate(sender:)), for: .touchUpInside) self.scrollView.addSubview(self.createButton) NSLayoutConstraint.activate([ self.createButton.topAnchor.constraint(equalTo: self.labelsValueText.bottomAnchor, constant: 8), self.createButton.heightAnchor.constraint(equalToConstant: 40), self.createButton.widthAnchor.constraint(equalToConstant: 100), self.createButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), self.createButton.bottomAnchor.constraint(equalTo: self.scrollView.bottomAnchor, constant: -8) ]) } @objc private func executeCreate(sender: UIView) { UIApplication.shared.sendAction(#selector(UIApplication.resignFirstResponder), to: nil, from: nil, for: nil) guard let groupId = self.idText.text, groupId.count > 0 else { showAlert(withText: "Group ID is mandatory!") return } if self.oldGroup == nil { guard let groupTitle = self.titleText.text, groupTitle.count > 0 else { showAlert(withText: "Name is mandatory!") return } } let groupContent = GroupContent(groupId: groupId) groupContent.title = self.titleText.text?.count == 0 ? nil : self.titleText.text groupContent.groupDescription = self.descriptionText.text if let avatarImage = self.avatarImage.image { groupContent.avatar = MediaAttachment.image(avatarImage) } else if let avatarUrl = self.avatarImageUrlText.text { groupContent.avatar = MediaAttachment.imageUrl(avatarUrl) } if let propertyKey = self.property1KeyText.text, let propertyValue = self.property1ValueText.text, propertyKey.count > 0, propertyValue.count > 0 { groupContent.properties = [propertyKey: propertyValue] } switch(self.allowPostSegmentedControl.selectedSegmentIndex) { case 0: groupContent.permissions[.post] = .owner break case 1: groupContent.permissions[.post] = .admin break case 2: groupContent.permissions[.post] = .member break default: groupContent.permissions[.post] = .member break } switch(self.allowInteractSegmentedControl.selectedSegmentIndex) { case 0: groupContent.permissions[.react] = .owner groupContent.permissions[.comment] = .owner break case 1: groupContent.permissions[.react] = .admin groupContent.permissions[.comment] = .admin break case 2: groupContent.permissions[.react] = .member groupContent.permissions[.comment] = .member break default: groupContent.permissions[.react] = .member groupContent.permissions[.comment] = .member break } groupContent.isDiscoverable = self.isDiscoverableSwitch.isOn groupContent.isPrivate = self.isPrivateSwitch.isOn if let labelsText = self.labelsValueText.text { groupContent.labels = labelsText.components(separatedBy: ",") } self.showActivityIndicatorView() self.model.createGroup(groupContent) } // MARK: Handle keyboard @objc private func keyboardWillShow(notification: NSNotification) { let userInfo = notification.userInfo if let keyboardSize = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { self.scrollView.contentInset = UIEdgeInsets.init(top: self.scrollView.contentInset.top, left: self.scrollView.contentInset.left, bottom: keyboardSize.height, right: self.scrollView.contentInset.right) } } @objc private func keyboardWillHide(notification: NSNotification) { self.scrollView.contentInset = UIEdgeInsets.init(top: self.scrollView.contentInset.top, left: self.scrollView.contentInset.left, bottom: 0, right: self.scrollView.contentInset.right) } @objc func selectImage() { self.imagePicker.sourceType = .photoLibrary self.imagePicker.delegate = self self .present(self.imagePicker, animated: true, completion: nil) } @objc func clearImage() { self.avatarImage.image = nil self.avatarImage.isHidden = true self.avatarImageHeightConstraint?.constant = 0 self.avatarClearImageButton.isHidden = true } } extension CreateGroupViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let uiImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { self.avatarImage.image = uiImage self.avatarImage.isHidden = false self.avatarClearImageButton.isHidden = false self.avatarImageHeightConstraint?.constant = 100.0 } self.imagePicker.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.imagePicker.dismiss(animated: true, completion: nil) } }
27d8f745e5ac03351fa5a1fef5366049
49.178037
212
0.713533
false
false
false
false
rockgarden/swift_language
refs/heads/swift3
Playground/FibonacciSequence-original.playground/section-1.swift
mit
2
// Thinkful Playground // Thinkful.com // Fibonacci Sequence // By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two. class FibonacciSequence { let includesZero: Bool let values: [UInt] init(maxNumber: UInt, includesZero: Bool) { self.includesZero = includesZero if maxNumber == 0 && includesZero == false { values = [] } else if maxNumber == 0 { values = [0] } else { var sequence: [UInt] = [0,1,1] var nextNumber: UInt = 2 while nextNumber <= maxNumber { sequence.append(nextNumber) let lastNumber = sequence.last! let secondToLastNumber = sequence[sequence.count-2] let (sum, didOverflow) = UInt.addWithOverflow(lastNumber, secondToLastNumber) if didOverflow == true { print("Overflow! The next number is too big to store in a UInt!") break } nextNumber = sum } if includesZero == false { sequence.remove(at: 0) } values = sequence } } init(numberOfItemsInSequence: UInt, includesZero: Bool) { self.includesZero = includesZero if numberOfItemsInSequence == 0 { values = [] } else if numberOfItemsInSequence == 1 { if includesZero == true { values = [0] } else { values = [1] } } else { var sequence: [UInt] if includesZero == true { sequence = [0,1] } else { sequence = [1,1] } for _ in 2 ..< Int(numberOfItemsInSequence) { let lastNumber = sequence.last! let secondToLastNumber = sequence[sequence.count-2] let (nextNumber, didOverflow) = UInt.addWithOverflow(lastNumber, secondToLastNumber) if didOverflow == true { print("Overflow! The next number is too big to store in a UInt!") break } sequence.append(nextNumber) } values = sequence } } } let fibonacciSequence = FibonacciSequence(maxNumber:12345, includesZero: true) print(fibonacciSequence.values) let anotherSequence = FibonacciSequence(numberOfItemsInSequence: 113, includesZero: true) print(anotherSequence.values) UInt.max
83fb0e19f8ecb66b758bd00b15ac3023
32.4125
205
0.542462
false
false
false
false
pvieito/PythonKit
refs/heads/master
Tests/PythonKitTests/PythonFunctionTests.swift
apache-2.0
1
import XCTest import PythonKit class PythonFunctionTests: XCTestCase { private var canUsePythonFunction: Bool { let versionMajor = Python.versionInfo.major let versionMinor = Python.versionInfo.minor return (versionMajor == 3 && versionMinor >= 1) || versionMajor > 3 } func testPythonFunction() { guard canUsePythonFunction else { return } let pythonAdd = PythonFunction { args in let lhs = args[0] let rhs = args[1] return lhs + rhs }.pythonObject let pythonSum = pythonAdd(2, 3) XCTAssertNotNil(Double(pythonSum)) XCTAssertEqual(pythonSum, 5) // Test function with keyword arguments // Since there is no alternative function signature, `args` and `kwargs` // can be used without manually stating their type. This differs from // the behavior when there are no keywords. let pythonSelect = PythonFunction { args, kwargs in // NOTE: This may fail on Python versions before 3.6 because they do // not preserve order of keyword arguments XCTAssertEqual(args[0], true) XCTAssertEqual(kwargs[0].key, "y") XCTAssertEqual(kwargs[0].value, 2) XCTAssertEqual(kwargs[1].key, "x") XCTAssertEqual(kwargs[1].value, 3) let conditional = Bool(args[0])! let xIndex = kwargs.firstIndex(where: { $0.key == "x" })! let yIndex = kwargs.firstIndex(where: { $0.key == "y" })! return kwargs[conditional ? xIndex : yIndex].value }.pythonObject let pythonSelectOutput = pythonSelect(true, y: 2, x: 3) XCTAssertEqual(pythonSelectOutput, 3) } // From https://www.geeksforgeeks.org/create-classes-dynamically-in-python func testPythonClassConstruction() { guard canUsePythonFunction else { return } let constructor = PythonInstanceMethod { args in let `self` = args[0] `self`.constructor_arg = args[1] return Python.None } // Instead of calling `print`, use this to test what would be output. var printOutput: String? // Example of function using an alternative syntax for `args`. let displayMethod = PythonInstanceMethod { (args: [PythonObject]) in // let `self` = args[0] printOutput = String(args[1]) return Python.None } let classMethodOriginal = PythonInstanceMethod { args in // let cls = args[0] printOutput = String(args[1]) return Python.None } // Did not explicitly convert `constructor` or `displayMethod` to // PythonObject. This is intentional, as the `PythonClass` initializer // should take any `PythonConvertible` and not just `PythonObject`. let classMethod = Python.classmethod(classMethodOriginal.pythonObject) let Geeks = PythonClass("Geeks", members: [ // Constructor "__init__": constructor, // Data members "string_attribute": "Geeks 4 geeks!", "int_attribute": 1706256, // Member functions "func_arg": displayMethod, "class_func": classMethod, ]).pythonObject let obj = Geeks("constructor argument") XCTAssertEqual(obj.constructor_arg, "constructor argument") XCTAssertEqual(obj.string_attribute, "Geeks 4 geeks!") XCTAssertEqual(obj.int_attribute, 1706256) obj.func_arg("Geeks for Geeks") XCTAssertEqual(printOutput, "Geeks for Geeks") Geeks.class_func("Class Dynamically Created!") XCTAssertEqual(printOutput, "Class Dynamically Created!") } // Previously, there was a build error where passing a simple // `PythonClass.Members` literal made the literal's type ambiguous. It was // confused with `[String: PythonObject]`. The solution was adding a // `@_disfavoredOverload` attribute to the more specific initializer. func testPythonClassInitializer() { guard canUsePythonFunction else { return } let MyClass = PythonClass( "MyClass", superclasses: [Python.object], members: [ "memberName": "memberValue", ] ).pythonObject let memberValue = MyClass().memberName XCTAssertEqual(String(memberValue), "memberValue") } func testPythonClassInheritance() { guard canUsePythonFunction else { return } var helloOutput: String? var helloWorldOutput: String? // Declare subclasses of `Python.Exception` let HelloException = PythonClass( "HelloException", superclasses: [Python.Exception], members: [ "str_prefix": "HelloException-prefix ", "__init__": PythonInstanceMethod { args in let `self` = args[0] let message = "hello \(args[1])" helloOutput = String(message) // Conventional `super` syntax does not work; use this instead. Python.Exception.__init__(`self`, message) return Python.None }, // Example of function using the `self` convention instead of `args`. "__str__": PythonInstanceMethod { (`self`: PythonObject) in return `self`.str_prefix + Python.repr(`self`) } ] ).pythonObject let HelloWorldException = PythonClass( "HelloWorldException", superclasses: [HelloException], members: [ "str_prefix": "HelloWorldException-prefix ", "__init__": PythonInstanceMethod { args in let `self` = args[0] let message = "world \(args[1])" helloWorldOutput = String(message) `self`.int_param = args[2] // Conventional `super` syntax does not work; use this instead. HelloException.__init__(`self`, message) return Python.None }, // Example of function using the `self` convention instead of `args`. "custom_method": PythonInstanceMethod { (`self`: PythonObject) in return `self`.int_param } ] ).pythonObject // Test that inheritance works as expected let error1 = HelloException("test 1") XCTAssertEqual(helloOutput, "hello test 1") XCTAssertEqual(Python.str(error1), "HelloException-prefix HelloException('hello test 1')") XCTAssertEqual(Python.repr(error1), "HelloException('hello test 1')") let error2 = HelloWorldException("test 1", 123) XCTAssertEqual(helloOutput, "hello world test 1") XCTAssertEqual(helloWorldOutput, "world test 1") XCTAssertEqual(Python.str(error2), "HelloWorldException-prefix HelloWorldException('hello world test 1')") XCTAssertEqual(Python.repr(error2), "HelloWorldException('hello world test 1')") XCTAssertEqual(error2.custom_method(), 123) XCTAssertNotEqual(error2.custom_method(), "123") // Test that subclasses behave like Python exceptions // Example of function with no named parameters, which can be stated // ergonomically using an underscore. The ignored input is a [PythonObject]. let testFunction = PythonFunction { _ in throw HelloWorldException("EXAMPLE ERROR MESSAGE", 2) }.pythonObject do { try testFunction.throwing.dynamicallyCall(withArguments: []) XCTFail("testFunction did not throw an error.") } catch PythonError.exception(let error, _) { guard let description = String(error) else { XCTFail("A string could not be created from a HelloWorldException.") return } XCTAssertTrue(description.contains("EXAMPLE ERROR MESSAGE")) XCTAssertTrue(description.contains("HelloWorldException")) } catch { XCTFail("Got error that was not a Python exception: \(error.localizedDescription)") } } // Tests the ability to dynamically construct an argument list with keywords // and instantiate a `PythonInstanceMethod` with keywords. func testPythonClassInheritanceWithKeywords() { guard canUsePythonFunction else { return } func getValue(key: String, kwargs: [(String, PythonObject)]) -> PythonObject { let index = kwargs.firstIndex(where: { $0.0 == key })! return kwargs[index].1 } // Base class has the following arguments: // __init__(): // - 1 unnamed argument // - param1 // - param2 // // test_method(): // - param1 // - param2 let BaseClass = PythonClass( "BaseClass", superclasses: [], members: [ "__init__": PythonInstanceMethod { args, kwargs in let `self` = args[0] `self`.arg1 = args[1] `self`.param1 = getValue(key: "param1", kwargs: kwargs) `self`.param2 = getValue(key: "param2", kwargs: kwargs) return Python.None }, "test_method": PythonInstanceMethod { args, kwargs in let `self` = args[0] `self`.param1 += getValue(key: "param1", kwargs: kwargs) `self`.param2 += getValue(key: "param2", kwargs: kwargs) return Python.None } ] ).pythonObject // Derived class accepts the following arguments: // __init__(): // - param2 // - param3 // // test_method(): // - param1 // - param2 // - param3 let DerivedClass = PythonClass( "DerivedClass", superclasses: [], members: [ "__init__": PythonInstanceMethod { args, kwargs in let `self` = args[0] `self`.param3 = getValue(key: "param3", kwargs: kwargs) // Lists the arguments in an order different than they are // specified (self, param2, param3, param1, arg1). The // correct order is (self, arg1, param1, param2, param3). let newKeywordArguments = args.map { ("", $0) } + kwargs + [ ("param1", 1), ("", 0) ] BaseClass.__init__.dynamicallyCall( withKeywordArguments: newKeywordArguments) return Python.None }, "test_method": PythonInstanceMethod { args, kwargs in let `self` = args[0] `self`.param3 += getValue(key: "param3", kwargs: kwargs) BaseClass.test_method.dynamicallyCall( withKeywordArguments: args.map { ("", $0) } + kwargs) return Python.None } ] ).pythonObject let derivedInstance = DerivedClass(param2: 2, param3: 3) XCTAssertEqual(derivedInstance.arg1, 0) XCTAssertEqual(derivedInstance.param1, 1) XCTAssertEqual(derivedInstance.param2, 2) XCTAssertEqual(derivedInstance.checking.param3, 3) derivedInstance.test_method(param1: 1, param2: 2, param3: 3) XCTAssertEqual(derivedInstance.arg1, 0) XCTAssertEqual(derivedInstance.param1, 2) XCTAssertEqual(derivedInstance.param2, 4) XCTAssertEqual(derivedInstance.checking.param3, 6) // Validate that subclassing and instantiating the derived class does // not affect behavior of the parent class. let baseInstance = BaseClass(0, param1: 10, param2: 20) XCTAssertEqual(baseInstance.arg1, 0) XCTAssertEqual(baseInstance.param1, 10) XCTAssertEqual(baseInstance.param2, 20) XCTAssertEqual(baseInstance.checking.param3, nil) baseInstance.test_method(param1: 10, param2: 20) XCTAssertEqual(baseInstance.arg1, 0) XCTAssertEqual(baseInstance.param1, 20) XCTAssertEqual(baseInstance.param2, 40) XCTAssertEqual(baseInstance.checking.param3, nil) } }
8495db2129024084ea4d8d35e36d6d9e
38.167155
114
0.542078
false
true
false
false
Estimote/iOS-SDK
refs/heads/master
Examples/swift/LoyaltyStore/LoyaltyStore/Controllers/OffersViewController.swift
mit
1
// // Please report any problems with this app template to [email protected] // import UIKit class OffersViewController: UIViewController { @IBOutlet var collectionView: UICollectionView! var customer: Customer! @objc var offers = [Any]() fileprivate let itemsPerRow: CGFloat = 3 override func viewDidLoad() { super.viewDidLoad() // register header self.registerHeader() self.offers = exampleOffers() // register cell in table view self.addCustomerObserver() } // observe for selected customer @objc func addCustomerObserver() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(setNewlySelectedCustomer), name: NSNotification.Name(rawValue: "customer selected"), object: nil) } @objc func setNewlySelectedCustomer(_ notification: Notification) { guard let newCustomer = notification.object as? Customer else { if notification.object == nil { self.customer = nil } return } self.customer = newCustomer } } // MARK: Table View extension OffersViewController: UICollectionViewDataSource, UICollectionViewDelegate { // MARK: Cell config func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "offerCell", for: indexPath) as! OfferCell let offer = self.offers[indexPath.item] as! Offer cell.imageView.image = offer.image cell.nameLabel.text = offer.name cell.costLabel.text = "\(offer.cost)" return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.offers.count } // MARK: Header func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! HeaderView return header } @objc func registerHeader() { let headerNib = UINib.init(nibName: "HeaderView", bundle: Bundle.main) self.collectionView.register(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header") } // Substract points func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let offer = offers[indexPath.item] as! Offer AlertHelper.displayValidationAlert("Redeem \(offer.name) for \(emojiPoints[offer.cost]!)⭐️?", subtitle: nil, viewController: self) { _ in if (self.customer) != nil { self.customer.substractPoints(offer.cost) } else { let notEnoughPointsPopup = UIAlertController(title: "Detected customers", message: "Redeeming products is only available once there is a customer nearby 💁‍♂️", preferredStyle: UIAlertControllerStyle.alert) let understandAction = UIAlertAction(title: "Sure", style: UIAlertActionStyle.default, handler: nil) notEnoughPointsPopup.addAction(understandAction) self.present(notEnoughPointsPopup, animated: true, completion: nil) } } } }
f93164f3302ebab356eb6cf5bfd5a615
33.787879
217
0.714866
false
false
false
false
macemmi/HBCI4Swift
refs/heads/master
HBCI4Swift/HBCI4Swift/Source/Sepa/HBCISepaUtility.swift
gpl-2.0
1
// // HBCISepaUtility.swift // HBCI4Swift // // Created by Frank Emminghaus on 03.07.20. // Copyright © 2020 Frank Emminghaus. All rights reserved. // import Foundation class HBCISepaUtility { let numberFormatter = NumberFormatter(); let dateFormatter = DateFormatter(); init() { initFormatters(); } fileprivate func initFormatters() { numberFormatter.decimalSeparator = "."; numberFormatter.alwaysShowsDecimalSeparator = true; numberFormatter.minimumFractionDigits = 2; numberFormatter.maximumFractionDigits = 2; numberFormatter.generatesDecimalNumbers = true; dateFormatter.dateFormat = "yyyy-MM-dd"; } func stringToNumber(_ s:String) ->NSDecimalNumber? { if let number = numberFormatter.number(from: s) as? NSDecimalNumber { return number; } else { logInfo("Sepa document parser: not able to convert \(s) to a value"); return nil; } } func stringToDate(_ s:String) ->Date? { if let date = dateFormatter.date(from: s) { return date; } else { logInfo("Sepa document parser: not able to convert \(s) to a date"); return nil; } } }
85e3705bad336c23a8c4f7d8d7e1212e
25.957447
81
0.611681
false
false
false
false
andreamazz/Tropos
refs/heads/master
Sources/TroposCore/Formatters/TemperatureFormatter.swift
mit
3
public struct TemperatureFormatter { public var unitSystem: UnitSystem public init(unitSystem: UnitSystem = SettingsController().unitSystem) { self.unitSystem = unitSystem } public func stringFromTemperature(_ temperature: Temperature) -> String { let usesMetricSystem = unitSystem == .metric let rawTemperature = usesMetricSystem ? temperature.celsiusValue : temperature.fahrenheitValue return String(format: "%.f°", Double(rawTemperature)) } }
2bdcacea5b32e6a8370e038f4591c8fa
37.461538
102
0.716
false
false
false
false
benbahrenburg/BucketList
refs/heads/master
BucketList/Classes/Converters.swift
mit
1
// // BucketList - Just another cache provider with security built in // Converters.swift // // Created by Ben Bahrenburg on 3/23/16. // Copyright © 2016 bencoding.com. All rights reserved. // import Foundation import ImageIO import MobileCoreServices /** Internal Helper functions to convert formats */ internal struct Converters { static func convertImage(_ image: UIImage, option: CacheOptions.imageConverter) -> Data? { if option == .imageIO { return UIImageToDataIO(image) } return image.jpegData(compressionQuality: 0.9) } fileprivate static func UIImageToDataIO(_ image: UIImage) -> Data? { return autoreleasepool(invoking: { () -> Data in let data = NSMutableData() let options: NSDictionary = [ kCGImagePropertyOrientation: 1, // Top left kCGImagePropertyHasAlpha: true, kCGImageDestinationLossyCompressionQuality: 0.9 ] let imageDestinationRef = CGImageDestinationCreateWithData(data as CFMutableData, kUTTypeJPEG, 1, nil)! CGImageDestinationAddImage(imageDestinationRef, image.cgImage!, options) CGImageDestinationFinalize(imageDestinationRef) return data as Data }) } }
521696cc7c01fffbdbb4c371969ccfa1
28.777778
115
0.637313
false
false
false
false
AnirudhDas/ADEmailAndPassword
refs/heads/master
Classes/ADEmailAndPassword.swift
mit
1
import Foundation enum PasswordStrength { case None case Weak case Moderate case Strong } public class ADEmailAndPassword { public static func validateEmail(emailId: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: emailId) } public static func validatePassword(password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool { if (password.characters.count < length) { return false } if caseSensitivty { let hasUpperCase = self.matchesForRegexInText(regex: "[A-Z]", text: password).count > 0 if !hasUpperCase { return false } let hasLowerCase = self.matchesForRegexInText(regex: "[a-z]", text: password).count > 0 if !hasLowerCase { return false } } if numericDigits { let hasNumbers = self.matchesForRegexInText(regex: "\\d", text: password).count > 0 if !hasNumbers { return false } } if patternsToEscape.count > 0 { let passwordLowerCase = password.lowercased() for pattern in patternsToEscape { let hasMatchesWithPattern = self.matchesForRegexInText(regex: pattern, text: passwordLowerCase).count > 0 if hasMatchesWithPattern { return false } } } return true } public static func matchesForRegexInText(regex: String, text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex, options: []) let nsString = text as NSString let results = regex.matches(in: text, options: [], range: NSMakeRange(0, nsString.length)) return results.map { nsString.substring(with: $0.range)} } catch let error as NSError { print("invalid regex: \(error.localizedDescription)") return [] } } public static func checkPasswordStrength(password: String) -> String { let len: Int = password.characters.count var strength: Int = 0 switch len { case 0: return "None" case 1...4: strength += 1 case 5...8: strength += 2 default: strength += 3 } // Upper case, Lower case, Number & Symbols let patterns = ["^(?=.*[A-Z]).*$", "^(?=.*[a-z]).*$", "^(?=.*[0-9]).*$", "^(?=.*[!@#%&-_=:;\"'<>,`~\\*\\?\\+\\[\\]\\(\\)\\{\\}\\^\\$\\|\\\\\\.\\/]).*$"] for pattern in patterns { if (password.range(of: pattern, options: .regularExpression) != nil) { strength += 1 } } switch strength { case 0: return "None" case 1...3: return "Weak" case 4...6: return "Moderate" default: return "Strong" } } }
03d7cf67958f0d0a003b1b5375c8fdbc
31.846939
160
0.504505
false
false
false
false
softman123g/SMImagesShower
refs/heads/master
SMImagesShower/SMImageShowerViewController.swift
mit
1
// // SMImageBrowerViewController.swift // TakePictureAndRecordVideo // // Created by softman on 16/1/25. // Copyright © 2016年 softman. All rights reserved. // // Contact me: [email protected] // Or Star me: https://github.com/softman123g/SMImagesShower // // 原理: // 在一个大ScrollView中,嵌入两个小ScrollView,以达到复用的目的。小ScrollView负责从网络加载图片。 // 并且小ScrollView负责图片的点击放大等的处理,而大ScrollView负责翻页等的效果。 // // 优势: // 1.支持横屏竖屏 // 2.存储空间小。使用复用ScrollView,当图片很多时,依旧不耗费存储空间 // 3.支持底部页码显示 // 4.支持双击图片放大/缩小 // 5.支持双指放大/缩小图片 // 6.支持长按保存图片到相册 // 7.支持单击隐藏图片 // // 使用方法: // let imageUrls = ["http://image.photophoto.cn/m-6/Animal/Amimal%20illustration/0180300271.jpg", // "http://img4.3lian.com/sucai/img6/230/29.jpg", // "http://img.taopic.com/uploads/allimg/130501/240451-13050106450911.jpg", // "http://pic1.nipic.com/2008-08-12/200881211331729_2.jpg", // "http://a2.att.hudong.com/38/59/300001054794129041591416974.jpg"] // let imagesShowViewController = SMImagesShowerViewController() // do { // try imagesShowViewController.prepareDatas(imageUrls, currentDisplayIndex: 0) // } catch { // print("图片显示出错:第一个图片指定索引错误") // return // } // presentViewController(imagesShowViewController, animated: true, completion: nil) import UIKit public class SMImagesShowerViewController: UIViewController, UIScrollViewDelegate, LongPressGestureRecognizerDelegate{ // MARK: Properties private let pageScaleRadio = CGFloat(9.8/10)//页码位置垂直比例 private let pageLabelHeight = CGFloat(15.0)//页码高度 var currentImageIndex:Int = 0 //当前图片索引,从0开始 pre var currentPageNumber:Int = 0 //当前页码,从0开始,真正滑动后展现的页码 after var prePointX:Float = 0.0 //scrollview 滑过的上一个点x坐标 var currentSubScrollView:SMImageScrollView?//当前滑动的子ScrollView var imageModels:[SMImageModel] = [] //所有图片信息的model数组 var imageScrollViews:[SMImageScrollView] = [] //用于复用的子ScrollView var scrollView:UIScrollView!//大ScrollView var pageLabel:UILabel = UILabel()//页码 // MARK: Super override public func viewDidLoad() { super.viewDidLoad() self.scrollView = UIScrollView(frame: self.view.bounds) self.scrollView.backgroundColor = UIColor.blackColor() self.scrollView.showsHorizontalScrollIndicator = false self.scrollView.showsVerticalScrollIndicator = false self.scrollView.alwaysBounceVertical = false self.scrollView.pagingEnabled = true //翻页效果,一页显示一个子内容 self.scrollView.delegate = self self.addSubScrollView()//增加子ScrollView self.view.addSubview(self.scrollView) self.pageLabel.textAlignment = .Center self.pageLabel.font = UIFont.systemFontOfSize(12) self.pageLabel.textColor = UIColor.whiteColor() self.pageLabel.text = self.pageText() self.view.addSubview(self.pageLabel) self.addGesture() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.All //支持横竖屏 } //第一次调用,以及横竖屏切换的时候,将重新布局 override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.scrollView.frame = self.view.bounds var size = self.scrollView.bounds.size size.width *= CGFloat(self.imageModels.count) self.scrollView.contentSize = size var frame = self.view.bounds frame.origin.y = frame.size.height * pageScaleRadio - pageLabelHeight frame.size.height = pageLabelHeight self.pageLabel.frame = frame //布局scrollview内部的控件 for imageScrollView in self.imageScrollViews { if let _imageModel = imageScrollView.imageModel { var frame = self.scrollView.bounds frame.origin.x = CGFloat(_imageModel.index) * frame.size.width imageScrollView.frame = frame imageScrollView.refleshSubview() } } currentSubScrollView?.resetScale(true) self.scrollView.setContentOffset((currentSubScrollView?.frame.origin)!, animated: true) } // MARK: Self Functions //准备数据相关,应该在展现前调用 currentDisplayIndex,从0开始 public func prepareDatas(imageUrls:[String], currentDisplayIndex:Int) throws { guard currentDisplayIndex >= 0 && currentDisplayIndex < imageUrls.count else { throw SMImageShowerError.ArrayOutOfBounds } imageModels.appendContentsOf(SMImageModel.initImages([], imageURLs: imageUrls)) currentPageNumber = currentDisplayIndex currentImageIndex = -1 //表示之前还没有显示 } func addSubScrollView(){ //当图片数大于2张时,使用2个UIScrollView重用。之所以用2个,因为翻页的时候用页面上只会存在2个页面 for _ in 0 ..< min(2, self.imageModels.count) { let imageScrollView = SMImageScrollView(frame: self.scrollView.bounds) imageScrollView.longpressGrstureRecorgnizerDelegate = self self.scrollView.addSubview(imageScrollView) self.imageScrollViews.append(imageScrollView) } self.setCurrentPage(currentPageNumber) } func pageText()->String{ return String(format: "%d/%d", currentPageNumber+1, self.imageModels.count) } //设置指定索引位置的图片页 func setCurrentPage(index:Int){ if currentImageIndex == index || index >= self.imageModels.count || index < 0{ return } //重置某一页,实现翻页后的效果 currentImageIndex = index let imageScrollView = dequeueScrollViewForResuable() if let _imageScrollView = imageScrollView { currentSubScrollView = _imageScrollView if _imageScrollView.tag == index { return } currentSubScrollView?.resetScale(true) var frame = self.scrollView.bounds frame.origin.x = CGFloat(index) * (frame.size.width)//frame的x坐标为当前scrollview的index倍,此时刚好是每一张图对应的在父ScrollView中的位置 currentSubScrollView?.frame = frame currentSubScrollView?.tag = index currentSubScrollView?.imageModel = self.imageModels[index] } } //重用SMImageScrollView。当前界面显示页为第1个ScrollView,下1个页面(左滑或者右滑产生的下一个页面)则始终是第2个Scrollview func dequeueScrollViewForResuable() -> SMImageScrollView?{ let imageScrollView = self.imageScrollViews.last if let _imageScrollView = imageScrollView { self.imageScrollViews.removeLast() self.imageScrollViews.insert(_imageScrollView, atIndex: 0) } return imageScrollView } func addGesture(){ //添加单击返回手势 let tap = UITapGestureRecognizer(target: self, action: "tapAction:") self.view.addGestureRecognizer(tap) //添加双击缩放手势 let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTapAction:") doubleTap.numberOfTapsRequired = 2 self.view.addGestureRecognizer(doubleTap) //双击优先级比单击高 tap.requireGestureRecognizerToFail(doubleTap) } //单击 func tapAction(tap:UITapGestureRecognizer){ self.dismissViewControllerAnimated(true, completion: nil) } //双击 func doubleTapAction(doubleTap:UITapGestureRecognizer){ self.currentSubScrollView?.responseDoubleTapAction() } //该方法在滑动结束时(或滑动减速结束)调用,触发重置当前应该显示哪个子ScrollView。参数scrollView是父ScrollView func pageDragOperate(scrollView:UIScrollView){ let pointX = scrollView.contentOffset.x / scrollView.bounds.width //通过向上或向下取整,使得在滑动相对距离 超过一半 时才可以滑向下一页。也就是说什么时候滑动到下一页,是由自己决定的,而不是由别人决定的。 if Float(scrollView.contentOffset.x) > prePointX {//手向左滑 self.setCurrentPage(Int(ceil(pointX)))//取上整,取到下一个要显示的index值 } else {//手向右滑 self.setCurrentPage(Int(floor(pointX)))//取下整,取到上一个已显示的index值 } prePointX = Float(scrollView.contentOffset.x) //显示图片的页码,这里实时显示,是用于在用户滑动的时候,能够实时的展现,而不像用户翻页图片的时候只有超过0.5的大小才翻页 let int = Int(Float(pointX) + 0.5) if int != currentPageNumber { currentPageNumber = int self.pageLabel.text = self.pageText() } } // MARK: Delegate //会调用多次 public func scrollViewDidScroll(scrollView: UIScrollView) { if !self.scrollView.dragging { return } pageDragOperate(scrollView) } //会调用多次 public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { pageDragOperate(scrollView) //将所有的子ScrollView都全部设置成原始的大小。因为可能用户当前界面中的子ScrollView放大了,所以滑动结束后,需要设置回原来的大小。也可以不设置,就看是不是需要这样的设置回原来大小的需求了。 for imgsc in self.imageScrollViews{ if imgsc != currentSubScrollView { imgsc.resetScale(true) } } } func longPressPresentAlertController(alertController: UIAlertController) { self.presentViewController(alertController, animated: true, completion: nil) } } enum SMImageShowerError:ErrorType { case ArrayOutOfBounds }
7c0e4a8a28cbd8b7bd9012a5b7518fb9
36.958159
124
0.674383
false
false
false
false
schrockblock/gtfs-stations
refs/heads/develop
Example/GTFS StationsTests/PredictionSpec.swift
mit
1
// // PredictionSpec.swift // GTFS Stations // // Created by Elliot Schrock on 7/30/15. // Copyright (c) 2015 Elliot Schrock. All rights reserved. // import GTFSStations import Quick import Nimble import SubwayStations class PredictionSpec: QuickSpec { override func spec() { describe("Prediction", { () -> Void in it("is equal when everything matches") { let route = NYCRoute(objectId: "1") let time = NSDate() let first = Prediction(time: time as Date) let second = Prediction(time: time as Date) first.route = route first.direction = .downtown second.route = route second.direction = .downtown expect([first].contains(where: {second == $0})).to(beTruthy()) } }) } }
1f95cf6de3a2ddf408b8c674d11bb3ad
26.085714
78
0.509494
false
false
false
false
mitochrome/complex-gestures-demo
refs/heads/master
apps/GestureRecognizer/Source/RootViewController.swift
mit
1
import UIKit import RxSwift extension GestureModel { static var shared = GestureModel() } class RootViewController: UIViewController { var disposeBag = DisposeBag() let complexGestureInput = ComplexGestureInput() @objc private func showInstructions() { let gestureList = GestureList() present(gestureList, animated: true, completion: nil) } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() let canvas = UIView() view.addSubview(canvas) canvas.snp.makeConstraints { (make) in make.size.equalToSuperview() make.center.equalToSuperview() } complexGestureInput.view = canvas complexGestureInput.switchStatesOnFlatTap = false complexGestureInput.isGesturing.value = true let instructions = InstructionsView() instructions.button.addTarget(self, action: #selector(showInstructions), for: .touchUpInside) view.addSubview(instructions) instructions.snp.makeConstraints { (make) in make.top.equalTo(view.safeAreaLayoutGuide.snp.topMargin).inset(20) make.centerX.equalToSuperview() } let notification = NotificationPopover() notification.isUserInteractionEnabled = false view.addSubview(notification) notification.makeSizeConstraints() notification.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.bottom.equalToSuperview().inset(30) } view.addSubview(complexGestureInput.previewView) complexGestureInput.previewView.snp.makeConstraints { (make) in make.size.equalToSuperview() make.center.equalToSuperview() } let drawingLabelValues = complexGestureInput .currentDrawing .filter({ $0.strokes.count > 0 }) .distinctUntilChanged() .throttle(0.1, scheduler: MainScheduler.instance) .flatMap({ drawing -> Observable<(Drawing, [Double])> in guard let labelValues = predictLabel(drawing: drawing) else { return Observable.empty() } print("labelValues", labelValues) return Observable.just((drawing, labelValues)) }) .share() let immediateRecognition: Observable<Touches_Label> = drawingLabelValues .flatMap { (drawing: Drawing, labelValues: [Double]) -> Observable<Touches_Label> in // labelValues are the softmax outputs ("probabilities") // for each label in Touches_Label.all, in the the order // that they're present there. let max = labelValues.max()! if max < 0.8 { return Observable.empty() } let argMax = labelValues.index(where: { $0 == max })! let prediction = Touches_Label.all[argMax] if drawing.strokes.count < requiredNumberOfStrokes(label: prediction) { return Observable.empty() } return Observable.just(prediction) } let delayedRecognition = immediateRecognition .flatMapLatest { label -> Observable<Touches_Label> in if shouldDelayRecognition(of: label) { return Observable.just(label) .delay(0.5, scheduler: MainScheduler.instance) } return Observable.just(label) } delayedRecognition .subscribe(onNext: { label in notification.show(label: label) }) .disposed(by: disposeBag) let clearTimeout = Observable<Observable<Observable<()>>>.of( // Don't clear while the user is stroking. complexGestureInput .didStartStroke .map({ Observable.never() }), // After the user finishes a stroke, clear slowly (time out). complexGestureInput .currentDrawing .map({ _ in Observable.just(()) .delay(1, scheduler: MainScheduler.instance) }), // After the gesture is recognized, clear quickly unless the // user continues drawing. delayedRecognition .map({ _ in Observable.just(()) .delay(0.5, scheduler: MainScheduler.instance) }) ) .merge() .flatMapLatest({ $0 }) clearTimeout .subscribe(onNext: { [weak self] _ in self?.complexGestureInput.clear() }) .disposed(by: disposeBag) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } fileprivate class InstructionsView: UIView { private let label = UILabel() let button = UIButton() init() { super.init(frame: .zero) label.isUserInteractionEnabled = false label.font = UIFont.systemFont(ofSize: 18) label.textColor = UIColor(white: 0.2, alpha: 1) label.textAlignment = .center label.text = "Make a gesture below." addSubview(label) label.snp.makeConstraints { (make) in make.top.equalToSuperview() make.left.equalToSuperview() make.right.equalToSuperview() } button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) button.titleLabel?.textAlignment = .center button.setTitleColor(UIColor("#37A0F4"), for: .normal) button.setTitle("See available gestures.", for: .normal) addSubview(button) button.snp.makeConstraints { (make) in make.top.equalTo(label.snp.bottom) make.left.equalToSuperview() make.right.equalToSuperview() make.bottom.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
95333371717bff2ecfd9115074d989c7
34.849462
101
0.544841
false
false
false
false
24/ios-o2o-c
refs/heads/master
gxc/Order/SendOrderViewController.swift
mit
1
// // SendOrderViewController.swift // gxc // // Created by gx on 14/12/8. // Copyright (c) 2014年 zheng. All rights reserved. // import Foundation class SendOrderViewController: UIViewController ,UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate { var timerTxt = UITextField() var dataTxt = UITextField() var datePicker:UIPickerView = UIPickerView() var pickerView:UIPickerView = UIPickerView() var orderDetail = GXViewState.OrderDetail var messagetxt = UITextField() var shopOrder:GX_ShopNewOrder! var shopOrderTimes = Dictionary<String,([String])>() var elements:[String] = [String]() var loginBtn = UIButton() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_back.png"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("NavigationControllerBack")) /*navigation 不遮住View*/ self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = UIRectEdge() /*self view*/ self.view.backgroundColor = UIColor.whiteColor() //superview let superview: UIView = self.view /* navigation titleView */ self.navigationController?.navigationBar.barTintColor = UIColor(fromHexString: "#008FD7") var navigationBar = self.navigationController?.navigationBar navigationBar?.tintColor = UIColor.whiteColor() self.navigationItem.title = "预约送衣" let iconWidth = 30 let iconHeight = 30 let txtHeight = 40 var elements:[String] = [String]() var shopId = orderDetail.shopDetail?.ShopMini?.ShopId GxApiCall().ShopOrder(GXViewState.userInfo.Token!, shopId: String(shopId!)) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("Set_View_Value:"), name: GXNotifaction_Shop_NewOrder, object: nil) MBProgressHUD.showHUDAddedTo(self.view, animated: true) //日期 var dataView = UIView() self.view.addSubview(dataView) dataView.snp_makeConstraints { make in make.left.equalTo(CGPointZero) make.top.equalTo(superview).offset(20) make.width.equalTo(superview) make.height.equalTo(45) } var dataImageView = UIImageView(image: UIImage(named: "order_date.png")) dataView.addSubview(dataImageView) dataView.addSubview(dataTxt) dataImageView.snp_makeConstraints { make in make.left.equalTo(CGPointZero).offset(3) make.centerY.equalTo(dataView.snp_centerY) make.width.equalTo(iconWidth) make.height.equalTo(iconHeight) } dataTxt.snp_makeConstraints { make in make.left.equalTo(dataImageView.snp_right).offset(5) make.centerY.equalTo(dataView.snp_centerY) make.right.equalTo(dataView.snp_right).offset(-5) make.height.equalTo(txtHeight) } dataTxt.placeholder = "设置日期" dataTxt.adjustsFontSizeToFitWidth = true dataTxt.clearButtonMode = UITextFieldViewMode.WhileEditing dataTxt.borderStyle = UITextBorderStyle.RoundedRect dataTxt.keyboardAppearance = UIKeyboardAppearance.Dark dataTxt.delegate = self //timer var timeView = UIView() self.view.addSubview(timeView) timeView.snp_makeConstraints { make in make.left.equalTo(CGPointZero) make.top.equalTo(dataView.snp_bottom) make.width.equalTo(superview) make.height.equalTo(45) } var timerImageView = UIImageView(image: UIImage(named: "order_time.png")) timeView.addSubview(timerImageView) timeView.addSubview(timerTxt) timerImageView.snp_makeConstraints { make in make.left.equalTo(CGPointZero).offset(3) make.centerY.equalTo(timeView.snp_centerY) make.width.equalTo(iconWidth) make.height.equalTo(iconHeight) } timerTxt.delegate = self timerTxt.snp_makeConstraints { make in make.left.equalTo(timerImageView.snp_right).offset(5) make.centerY.equalTo(timeView.snp_centerY) make.right.equalTo(timeView.snp_right).offset(-5) make.height.equalTo(txtHeight) } timerTxt.placeholder = "设置时间" timerTxt.adjustsFontSizeToFitWidth = true timerTxt.clearButtonMode = UITextFieldViewMode.WhileEditing timerTxt.borderStyle = UITextBorderStyle.RoundedRect timerTxt.keyboardAppearance = UIKeyboardAppearance.Dark //message var messageView = UIView() self.view.addSubview(messageView) messageView.snp_makeConstraints { make in make.left.equalTo(CGPointZero) make.top.equalTo(timeView.snp_bottom) make.width.equalTo(superview) make.height.equalTo(45) } var messageImageView = UIImageView(image: UIImage(named: "order_message.png")) messageView.addSubview(messageImageView) messageView.addSubview(messagetxt) messagetxt.placeholder = "给饲料厂留言" messagetxt.adjustsFontSizeToFitWidth = true messagetxt.clearButtonMode = UITextFieldViewMode.WhileEditing messagetxt.borderStyle = UITextBorderStyle.RoundedRect messagetxt.keyboardAppearance = UIKeyboardAppearance.Dark messagetxt.delegate = self messageImageView.snp_makeConstraints { make in make.left.equalTo(CGPointZero).offset(5) make.centerY.equalTo(messageView.snp_centerY) make.width.equalTo(iconWidth) make.height.equalTo(iconHeight) } messagetxt.snp_makeConstraints { make in make.left.equalTo(messageImageView.snp_right).offset(5) make.centerY.equalTo(messageView.snp_centerY) make.right.equalTo(messageView.snp_right).offset(-5) make.height.equalTo(txtHeight) } dataTxt.inputView = datePicker datePicker.tag = 12 pickerView.tag = 23 timerTxt.inputView = pickerView pickerView.delegate = self // pickerView.dataSource = self datePicker.delegate = self // datePicker.dataSource = self loginBtn.backgroundColor = UIColor(fromHexString: "#E61D4C") loginBtn.addTarget(self, action: Selector("SetSendOrder"), forControlEvents: .TouchUpInside) loginBtn.setTitle("立即预约", forState: UIControlState.Normal) self.view.addSubview(loginBtn) loginBtn.snp_makeConstraints { make in make.top.equalTo(self.messagetxt.snp_bottom).offset(15) make.left.equalTo(CGPointZero).offset(5) make.right.equalTo(superview).offset(-5) // make.width.equalTo(superview) make.height.equalTo(40) } } func Set_View_Value(notif :NSNotification) { shopOrder = notif.userInfo?["GXNotifaction_Shop_NewOrder"] as GX_ShopNewOrder var messagetxt = "" //拼假时间 for time in shopOrder.shopOrderdata!.orderTimes! { var tip = "\(time.Tip!)" var k = time.Date! var newArray = [String]() if let kd = shopOrderTimes[k] { newArray = kd newArray.append(tip) }else { newArray = [tip] } shopOrderTimes.updateValue(newArray, forKey: k) } elements = [String](shopOrderTimes.keys) elements.sort { $0 < $1 } var key = elements[0] dataTxt.text = key timerTxt.text = shopOrderTimes[key]![0] MBProgressHUD.hideAllHUDsForView(self.view, animated: true) } func SetSendOrder() { MBProgressHUD.showHUDAddedTo(self.view, animated: true) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("OrderSendSuccess:"), name: GXNotifaction_User_Order_Send, object: nil) //无地址 var orderId = NSString(format: "%.0f", orderDetail.shopDetail!.OrderId!) var content = messagetxt.text! var token = GXViewState.userInfo.Token! var getTime = dataTxt.text + " " + timerTxt.text GxApiCall().OrderSend(orderId, remark: content, token: token, sendTime: getTime) } func OrderSendSuccess(notif :NSNotification) { MBProgressHUD.hideHUDForView(self.view, animated: true) SweetAlert().showAlert("", subTitle: "预约送衣成功!", style: AlertStyle.Success) self.navigationController?.popViewControllerAnimated(true) } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if(pickerView.tag == 12) { return elements.count } else { var key = dataTxt.text! var c = shopOrderTimes[key]!.count println(c) return c } } func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String { if(pickerView.tag == 12) { return elements[row] } else { var key = dataTxt.text! var lx = shopOrderTimes[key]![row] println(lx) return lx } } func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { if(pickerView.tag == 12) { dataTxt.text = elements[row] } else { var key = dataTxt.text! timerTxt.text = shopOrderTimes[key]![row] } } func NavigationControllerBack() { self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
f22e517fed13583ed3d2f5c5093ed924
31.767584
204
0.59832
false
false
false
false
xhjkl/rayban
refs/heads/master
Rayban/GLESRenderer.swift
mit
1
// // OpenGL renderer // import Cocoa import OpenGL.GL3 fileprivate let passThroughVertSrc = "#version 100\n" + "attribute vec2 attr;" + "varying vec2 position;" + "void main() {" + "gl_Position = vec4((position = attr), 0.0, 1.0);" + "}" fileprivate let passThroughFragSrc = "#version 100\n" + "uniform sampler2D texture;" + "uniform vec2 density;" + "void main() {" + "gl_FragColor = texture2D(texture, gl_FragCoord.xy * density);" + "}" fileprivate let unitQuadVertices = Array<GLfloat>([ GLfloat(+1.0), GLfloat(-1.0), GLfloat(-1.0), GLfloat(-1.0), GLfloat(+1.0), GLfloat(+1.0), GLfloat(-1.0), GLfloat(+1.0), ]) // OpenGL ES 2 // class GLESRenderer: Renderer { private var progId = GLuint(0) private var vertexArrayId = GLuint(0) private var unitQuadBufferId = GLuint(0) private var timeUniform: GLint? = nil private var densityUniform: GLint? = nil private var resolutionUniform: GLint? = nil var logListener: RenderLogListener? = nil func prepare() { glClearColor(1.0, 0.33, 0.77, 1.0) glGenVertexArrays(1, &vertexArrayId) glBindVertexArray(vertexArrayId) let size = unitQuadVertices.count * MemoryLayout<GLfloat>.size glGenBuffers(1, &unitQuadBufferId) glBindBuffer(GLenum(GL_ARRAY_BUFFER), unitQuadBufferId) unitQuadVertices.withUnsafeBufferPointer { bytes in glBufferData(GLenum(GL_ARRAY_BUFFER), size, bytes.baseAddress, GLenum(GL_STATIC_DRAW)) } glVertexAttribPointer(0, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(0), UnsafeRawPointer(bitPattern: 0)) glEnableVertexAttribArray(0) } func setSource(_ source: String) { if glIsProgram(progId) == GLboolean(GL_TRUE) { glDeleteProgram(progId) } let newProgId = makeShader(vertSource: passThroughVertSrc, fragSource: source) guard newProgId != nil else { return } progId = newProgId! glUseProgram(progId) } func yieldFrame(size: (width: Float64, height: Float64), time: Float64) { glUniform1f(timeUniform ?? -1, GLfloat(time)) glUniform2f(densityUniform ?? -1, GLfloat(1.0 / size.width), GLfloat(1.0 / size.height)) glUniform2f(resolutionUniform ?? -1, GLfloat(size.width), GLfloat(size.height)) let _ = glGetError() glClear(GLbitfield(GL_COLOR_BUFFER_BIT)) glViewport(0, 0, GLsizei(size.width), GLsizei(size.height)) glDrawArrays(GLenum(GL_TRIANGLE_STRIP), 0, 4) } private func retrieveCompilationLog(id: GLuint) -> String { let oughtToBeEnough = 1024 var storage = ContiguousArray<CChar>(repeating: 0, count: oughtToBeEnough) var log: String! = nil storage.withUnsafeMutableBufferPointer { mutableBytes in glGetShaderInfoLog(id, GLsizei(oughtToBeEnough), nil, mutableBytes.baseAddress!) log = String(cString: mutableBytes.baseAddress!) } return log } private func retrieveLinkageLog(id: GLuint) -> String { let oughtToBeEnough = 1024 var storage = ContiguousArray<CChar>(repeating: 0, count: oughtToBeEnough) var log: String! = nil storage.withUnsafeMutableBufferPointer { mutableBytes in glGetProgramInfoLog(id, GLsizei(oughtToBeEnough), nil, mutableBytes.baseAddress!) log = String(cString: mutableBytes.baseAddress!) } return log } private func makeShader(vertSource: String, fragSource: String) -> GLuint? { var status: GLint = 0 let progId = glCreateProgram() let vertId = glCreateShader(GLenum(GL_VERTEX_SHADER)) defer { glDeleteShader(vertId) } vertSource.withCString { bytes in glShaderSource(vertId, 1, [bytes], nil) } glCompileShader(vertId) glGetShaderiv(vertId, GLenum(GL_COMPILE_STATUS), &status) guard status == GL_TRUE else { let log = retrieveCompilationLog(id: vertId) emitReports(per: log) return nil } let fragId = glCreateShader(GLenum(GL_FRAGMENT_SHADER)) defer { glDeleteShader(fragId) } fragSource.withCString { bytes in glShaderSource(fragId, 1, [bytes], nil) } glCompileShader(fragId) glGetShaderiv(fragId, GLenum(GL_COMPILE_STATUS), &status) guard status == GL_TRUE else { let log = retrieveCompilationLog(id: fragId) emitReports(per: log) return nil } glBindAttribLocation(progId, 0, "attr") glAttachShader(progId, vertId) glAttachShader(progId, fragId) glLinkProgram(progId) defer { glDetachShader(progId, vertId) glDetachShader(progId, fragId) } glGetProgramiv(progId, GLenum(GL_LINK_STATUS), &status) guard status == GL_TRUE else { let log = retrieveLinkageLog(id: progId) emitReports(per: log) return nil } timeUniform = glGetUniformLocation(progId, "time") densityUniform = glGetUniformLocation(progId, "density") resolutionUniform = glGetUniformLocation(progId, "resolution") return progId } private func emitReports(per log: String) { guard logListener != nil else { return } let reports = parseLog(log) for report in reports { logListener!.onReport(report) } } }
00eae86fb614296484ced617d971229f
28.074286
115
0.684945
false
false
false
false
a497500306/MLSideslipView
refs/heads/master
MLSideslipViewDome/MLSideslipViewDome/ViewController.swift
apache-2.0
1
// // ViewController.swift // MLSideslipViewDome // // Created by 洛耳 on 16/1/5. // Copyright © 2016年 workorz. All rights reserved. import UIKit //第一步继承--MLViewController class ViewController: MLViewController , UITableViewDelegate , UITableViewDataSource { /// 侧滑栏图片数组 var images : NSArray! /// 侧滑栏文字数组 var texts : NSArray! override func viewDidLoad() { super.viewDidLoad() //设置左上角的放回按钮 let righBtn = UIButton(frame: CGRectMake(0, 0, 24, 24)) righBtn.setBackgroundImage(UIImage(named: "椭圆-19"), forState: UIControlState.Normal) righBtn.setBackgroundImage(UIImage(named: "椭圆-19" ), forState: UIControlState.Highlighted) righBtn.addTarget(self, action: "dianjiNavZuoshangjiao", forControlEvents: UIControlEvents.TouchUpInside) let rightBarItem = UIBarButtonItem(customView: righBtn) self.navigationItem.leftBarButtonItem = rightBarItem //第二步创建侧滑栏中需要添加的控件 添加控件() } func 添加控件(){ self.images = ["二维码","手势密码","指纹图标","我的收藏","设置"] self.texts = ["我的二维码","手势解锁","指纹解锁","我的收藏","设置"] let imageView = UIImageView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width * 2 / 3 , UIScreen.mainScreen().bounds.height)) imageView.userInteractionEnabled = true imageView.image = UIImage(named: "我的—背景图") let table = UITableView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width * 2 / 3 , UIScreen.mainScreen().bounds.height)) table.backgroundColor = UIColor.clearColor() table.tag = 1000 table.separatorStyle = UITableViewCellSeparatorStyle.None //1添加头部控件 let touView : UIView = UIView() //1.1头像 let btn : UIButton = UIButton() let w : CGFloat = 75 btn.frame = CGRectMake(((UIScreen.mainScreen().bounds.width * 2 / 3)-w)/2, w/2, w, w) //圆角 btn.layer.cornerRadius = 10 btn.layer.masksToBounds = true btn.setImage(UIImage(named: "IMG_1251.JPG"), forState: UIControlState.Normal) touView.addSubview(btn) //1.2名字 let nameText : UILabel = UILabel() let WH : CGSize = MLGongju().计算文字宽高("2131231", sizeMake: CGSizeMake(10000, 10000), font: UIFont.systemFontOfSize(15)) nameText.frame = CGRectMake(0, btn.frame.height + btn.frame.origin.y+10, table.frame.width, WH.height) nameText.font = UIFont.systemFontOfSize(15) nameText.textAlignment = NSTextAlignment.Center nameText.text = "毛哥哥是神" touView.addSubview(nameText) //1.3线 let xian : UIView = UIView() xian.frame = CGRectMake(25, nameText.frame.height + nameText.frame.origin.y + 10, table.frame.width - 50, 0.5) xian.backgroundColor = UIColor(red: 149/255.0, green: 149/255.0, blue: 149/255.0, alpha: 1) touView.addSubview(xian) touView.frame = CGRectMake(0, 0, table.frame.width, xian.frame.origin.y + xian.frame.height + 10) table.tableHeaderView = touView //设置代理数据源 table.dataSource = self table.delegate = self super.sideslipView.contentView.addSubview(imageView) super.sideslipView.contentView.addSubview(table) }//MARK: - tableView代理和数据源方法 //多少行 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.images.count } //点击每行做什么 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //取消选择 tableView.deselectRowAtIndexPath(indexPath, animated: true) //关闭侧滑栏 super.down() print("在这里做跳转") } //MARK: - tableView代理数据源 //每行cell张什么样子 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let ID = "cell" var cell : UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(ID) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: ID) } cell.backgroundColor = UIColor.clearColor() cell.textLabel?.text = self.texts[indexPath.row] as? String cell.imageView?.image = UIImage(named: (self.images[indexPath.row] as? String)!) return cell } //cell的高度 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 55 } //MARK: - 点击左上角按钮 func dianjiNavZuoshangjiao(){ super.show() } }
30629a059b2b2342aebb7a06b3c02b87
41.396226
144
0.654651
false
false
false
false
gyro-n/PaymentsIos
refs/heads/master
GyronPayments/Classes/Models/Webhook.swift
mit
1
// // Webhook.swift // GyronPayments // // Created by Ye David on 11/1/16. // Copyright © 2016 gyron. All rights reserved. // import Foundation /** The Webhook class stores information about webhooks. A webhook is a URL that can be used as a callback to receive information when an event is triggered in the Gopay system. Payloads for a webhook are delivered via a POST request. The body of the request will contain a JSON object with pertinent data. Webhooks can be created via the merchant console. The following table displays all events you can register a webhook, their payload, and a short description of the triggering event. */ open class Webhook: BaseModel { /** The unique identifier for the webhook. */ public var id: String /** The unique identifier for the merchant. */ public var merchantId: String /** The unique identifier for the store. */ public var storeId: String /** The triggers that fire the webhook request. */ public var triggers: [String] /** The url of the webhook. */ public var url: String /** Whether or not the webhook is active. */ public var active: Bool /** The date the webhook was created. */ public var createdOn: String /** The date the webhook was updated. */ public var updatedOn: String /** Initializes the Webhook object */ override init() { id = "" merchantId = "" storeId = "" triggers = [] url = "" active = false createdOn = "" updatedOn = "" } /** Maps the values from a hash map object into the Webhook. */ override open func mapFromObject(map: ResponseData) { id = map["id"] as? String ?? "" merchantId = map["merchant_id"] as? String ?? "" storeId = map["store_id"] as? String ?? "" triggers = map["triggers"] as? [String] ?? [] url = map["url"] as? String ?? "" active = map["active"] as? Bool ?? false createdOn = map["created_on"] as? String ?? "" updatedOn = map["updated_on"] as? String ?? "" } }
35f6648b0975de3b8c0deafed7d43f14
26.746835
300
0.597172
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/PullReqeustReviews/PullRequestReviewCommentsViewController.swift
mit
1
// // PullRequestReviewCommentsViewController.swift // Freetime // // Created by Ryan Nystrom on 11/4/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit final class PullRequestReviewCommentsViewController: BaseListViewController<NSNumber>, BaseListViewControllerDataSource { private let model: IssueDetailsModel private let client: GithubClient private var models = [ListDiffable]() init(model: IssueDetailsModel, client: GithubClient) { self.model = model self.client = client super.init( emptyErrorMessage: NSLocalizedString("Error loading review comments.", comment: ""), dataSource: self ) title = NSLocalizedString("Review Comments", comment: "") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Overrides override func fetch(page: NSNumber?) { client.fetchPRComments( owner: model.owner, repo: model.repo, number: model.number, width: view.bounds.width ) { [weak self] (result) in switch result { case .error: ToastManager.showGenericError() case .success(let models, let page): self?.models = models self?.update(page: page as NSNumber?, animated: trueUnlessReduceMotionEnabled) } } } // MARK: BaseListViewControllerDataSource func headModels(listAdapter: ListAdapter) -> [ListDiffable] { return [] } func models(listAdapter: ListAdapter) -> [ListDiffable] { return models } func sectionController(model: Any, listAdapter: ListAdapter) -> ListSectionController { switch model { case is NSAttributedStringSizing: return IssueTitleSectionController() case is IssueCommentModel: return IssueCommentSectionController(model: self.model, client: client) case is IssueDiffHunkModel: return IssueDiffHunkSectionController() default: fatalError("Unhandled object: \(model)") } } func emptySectionController(listAdapter: ListAdapter) -> ListSectionController { return ListSingleSectionController(cellClass: LabelCell.self, configureBlock: { (_, cell: UICollectionViewCell) in guard let cell = cell as? LabelCell else { return } cell.label.text = NSLocalizedString("No review comments found.", comment: "") }, sizeBlock: { [weak self] (_, context: ListCollectionContext?) -> CGSize in guard let context = context, let strongSelf = self else { return .zero } return CGSize( width: context.containerSize.width, height: context.containerSize.height - strongSelf.topLayoutGuide.length - strongSelf.bottomLayoutGuide.length ) }) } // MARK: IssueCommentSectionControllerDelegate }
64cba61d371971fc75f7cbf97921d783
33.298851
125
0.650469
false
false
false
false
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
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
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
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
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
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
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
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
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
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