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
phillips07/StudyCast
refs/heads/master
StudyCast/CustomTabBarController.swift
mit
1
// // CustomTabBarController.swift // StudyCast // // Created by Dennis Huebert on 2016-11-11. // Copyright © 2016 Austin Phillips. All rights reserved. // import UIKit class CustomTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() let groupsTableViewContoller = GroupsTableViewController() let groupsNavigationController = UINavigationController(rootViewController: groupsTableViewContoller) groupsNavigationController.title = "Groups" groupsNavigationController.tabBarItem.image = UIImage(named: "GroupsIcon") let castController = CastMapController() let castNavigationController = UINavigationController(rootViewController: castController) castNavigationController.title = "Cast" castNavigationController.tabBarItem.image = UIImage(named: "CastIcon") let homeController = MainScreenController() let homeNavigationController = UINavigationController(rootViewController: homeController) homeNavigationController.title = "Home" homeNavigationController.tabBarItem.image = UIImage(named: "HomeIcon") UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.lightGray], for: .selected) UITabBar.appearance().tintColor = UIColor.lightGray viewControllers = [homeNavigationController, castNavigationController, groupsNavigationController] } }
d12bd437865c0c484f9c3bad93a2c174
40.794872
125
0.734356
false
false
false
false
webventil/OpenSport
refs/heads/master
OpenSport/OpenSport/RecordMapViewController.swift
mit
1
// // RecordMapViewController.swift // OpenSport // // Created by Arne Tempelhof on 19.11.14. // Copyright (c) 2014 Arne Tempelhof. All rights reserved. // import UIKit import MapKit internal class RecordMapViewController: UIViewController, MKMapViewDelegate { @IBOutlet internal weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self mapView.userTrackingMode = MKUserTrackingMode.Follow // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if (overlay is MKPolyline) { var renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.openSportBlue(1) renderer.lineWidth = 5.0 return renderer } if (overlay is MKCircle) { var renderer = MKCircleRenderer(overlay: overlay) renderer.strokeColor = UIColor.redColor() renderer.lineWidth = 5.0 return renderer } return nil } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
dd04d48f857878659049cc8c888fde6f
28.122807
106
0.663253
false
false
false
false
lukecharman/so-many-games
refs/heads/master
SoManyGames/Classes/Cells/GameCell.swift
mit
1
// // GameCell.swift // SoManyGames // // Created by Luke Charman on 21/03/2017. // Copyright © 2017 Luke Charman. All rights reserved. // import UIKit protocol GameCellDelegate: class { func game(_ game: Game, didUpdateProgress progress: Double) } class GameCell: UICollectionViewCell { static let height: CGFloat = iPad ? 90 : 60 static let swipeMultiplier: CGFloat = 1.7 @IBOutlet var label: UILabel! @IBOutlet var platformLabel: UILabel! @IBOutlet var percentageLabel: UILabel! @IBOutlet var progressView: NSLayoutConstraint! @IBOutlet var progressBar: UIView! var longPressRecognizer: UILongPressGestureRecognizer! var panRecognizer: UIPanGestureRecognizer! weak var delegate: GameCellDelegate? let long = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(recognizer:))) let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:))) var game: Game? { didSet { guard let game = game else { return } label.text = game.name platformLabel.text = game.activePlatform?.abbreviation ?? "???" calculateProgress(from: game.completionPercentage) } } override func prepareForReuse() { super.prepareForReuse() isSelected = false backgroundColor = .clear } override func awakeFromNib() { super.awakeFromNib() setUpRecognizers() label.layer.shadowOffset = .zero label.layer.shadowRadius = 2 progressBar.isUserInteractionEnabled = false progressBar.translatesAutoresizingMaskIntoConstraints = false platformLabel.font = platformLabel.font.withSize(Sizes.gameCellSub) percentageLabel.font = percentageLabel.font.withSize(Sizes.gameCellSub) label.font = label.font.withSize(Sizes.gameCellMain) label.numberOfLines = iPad ? 3 : 2 clipsToBounds = false } func setUpRecognizers() { longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(recognizer:))) panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:))) longPressRecognizer.delegate = self panRecognizer.delegate = self addGestureRecognizer(longPressRecognizer) addGestureRecognizer(panRecognizer) } func calculateProgress(from ratio: Double) { let size = bounds.size.width * CGFloat(ratio) progressView.constant = size progressBar.alpha = CGFloat(ratio) percentageLabel.text = String(describing: Int(ratio * 100)) + "%" layoutIfNeeded() } func calculateProgressOnRotation() { let ratio = game!.completionPercentage let size = (UIScreen.main.bounds.size.height / 2) * CGFloat(ratio) progressView.constant = size progressBar.alpha = CGFloat(ratio) percentageLabel.text = String(describing: Int(ratio * 100)) + "%" layoutIfNeeded() } @objc func handleLongPress(recognizer: UILongPressGestureRecognizer) { guard let game = game else { return } UIView.animate(withDuration: 0.3) { if recognizer.state == .began { self.beginLongPress() self.layoutIfNeeded() } else if recognizer.state == .ended || recognizer.state == .cancelled { self.endLongPress() self.calculateProgress(from: game.completionPercentage) self.layoutIfNeeded() } } } override var isSelected: Bool { didSet { guard isSelected != oldValue else { return } updateSelection() } } func updateSelection() { guard let game = game else { return } UIView.animate(withDuration: 0.3) { self.backgroundColor = self.isSelected ? Colors.darkest.withAlphaComponent(0.2) : .clear if self.isSelected { self.progressBar.alpha = 0 } else { self.calculateProgress(from: game.completionPercentage) } } } func beginLongPress() { label.alpha = 0.8 label.transform = CGAffineTransform(scaleX: 1.4, y: 1.4) label.layer.shadowOpacity = 0.2 platformLabel.alpha = 0 platformLabel.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) percentageLabel.alpha = 0 percentageLabel.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) progressBar.alpha = 0 progressView.constant = 0 } func endLongPress() { label.alpha = 1 label.transform = CGAffineTransform(scaleX: 1, y: 1) label.layer.shadowOpacity = 0 platformLabel.alpha = 1 platformLabel.transform = CGAffineTransform(scaleX: 1, y: 1) percentageLabel.alpha = 1 percentageLabel.transform = CGAffineTransform(scaleX: 1, y: 1) progressBar.alpha = 1 } @objc func handlePan(recognizer: UIPanGestureRecognizer) { guard let game = game else { return } guard !isSelected else { return } let originalValue = CGFloat(game.completionPercentage) * bounds.size.width let t = max((recognizer.translation(in: self).x * GameCell.swipeMultiplier) + originalValue, 0) let ratio = min(max(t / bounds.size.width, 0), 1) // Restrict value between 0 and 1. if recognizer.state == .changed { progressView.constant = t progressBar.alpha = ratio * 1.3 percentageLabel.text = "\(String(describing: Int(ratio * 100)))%" layoutIfNeeded() } else if recognizer.state == .ended || recognizer.state == .cancelled { let newRatio = Double(ratio) Backlog.manager.update(game) { game.completionPercentage = newRatio } delegate?.game(game, didUpdateProgress: newRatio) } } } extension GameCell: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return !(gestureRecognizer is UIPanGestureRecognizer) && !(otherGestureRecognizer is UIPanGestureRecognizer) } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer == panRecognizer else { return true } let v = panRecognizer.velocity(in: self) let h = fabs(v.x) > fabs(v.y) return h // Only pan when horizontal. } }
d6081b0a890a5ca6854c3064b7ae083a
32.266332
157
0.646677
false
false
false
false
lixiangzhou/ZZLib
refs/heads/master
Source/ZZCustom/ZZNumberTextField.swift
mit
1
// // ZZNumberTextField.swift // ZZLib // // Created by lixiangzhou on 2018/6/20. // Copyright © 2018年 lixiangzhou. All rights reserved. // import UIKit class ZZNumberTextField: UITextField, UITextFieldDelegate { override init(frame: CGRect) { super.init(frame: frame) self.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Public Prop /// 分隔模式,例如银行卡号[4, 4, 4, 4, 4, 4]; 身份证号[6, 8, 4] var sepMode = [Int]() { didSet { var index = 0 for mode in sepMode { index += mode sepIndex.append(index) index += 1 } } } /// 长度限制,不包含空格的长度 var lengthLimit = Int.max /// 要包含的其他的字符,默认包含 CharacterSet.decimalDigits 和 " " var additionIncludeCharacterSet: CharacterSet? // MARK: - Private Prop private var sepIndex = [Int]() // MARK: - UITextFieldDelegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var text = textField.text ?? "" let emptyCharacter = Character(" ") if range.length > 0 && string.isEmpty { // 删除 if sepMode.count > 0 { if range.length == 1 { // 删除一位 // 光标前第二个字符,如果是空格需要删除 var toDeleteCharacterEmpty: Character? if range.location >= 1 { toDeleteCharacterEmpty = text[text.index(text.startIndex, offsetBy: range.location - 1)] } if range.location == text.count - 1 { // 在最后删除 if toDeleteCharacterEmpty == emptyCharacter { // 有空格,需要再往前删除一个空格 textField.deleteBackward() } return true } else { // 在中间删除 // 删除光标所在位置的字符 textField.deleteBackward() var offset = range.location if toDeleteCharacterEmpty == emptyCharacter { // 如果光标前有空格,删除 textField.deleteBackward() offset -= 1 } textField.text = formatToModeString(textField.text!) resetPosition(offset: offset) return false } } else if range.length > 1 { textField.deleteBackward() textField.text = formatToModeString(textField.text!) var location = range.location var characterBeforeLocation: Character? if location >= 1 { characterBeforeLocation = text[text.index(text.startIndex, offsetBy: location - 1)] if characterBeforeLocation == emptyCharacter { location -= 1 } } if NSMaxRange(range) != text.count { // 光标不是在最后 resetPosition(offset: location) } return false } else { return true } } else { return true } } else if string.count > 0 { // 输入文字 if sepMode.count > 0 { if (text + string).replacingOccurrences(of: " ", with: "").count > lengthLimit { // 超过限制 // 异步主线程是为了避免复制粘贴时光标错位的问题 DispatchQueue.main.async { self.resetPosition(offset: range.location) } return false } var newSet = CharacterSet.decimalDigits.union(CharacterSet(charactersIn: " ")) if let additionIncludeCharacterSet = additionIncludeCharacterSet { newSet = newSet.union(additionIncludeCharacterSet) } if string.trimmingCharacters(in: newSet).count > 0 { // 不是数字 // 异步主线程是为了避免复制粘贴时光标错位的问题 DispatchQueue.main.async { self.resetPosition(offset: range.location) } return false } let stringBeforeCursor = String(text[text.startIndex..<text.index(text.startIndex, offsetBy: range.location)]) textField.insertText(string) textField.text = formatToModeString(textField.text!) let temp = stringBeforeCursor + string let newLocation = formatToModeString(temp).count // 异步主线程是为了避免复制粘贴时光标错位的问题 DispatchQueue.main.async { self.resetPosition(offset: newLocation) } return false } else { text += string if text.replacingOccurrences(of: " ", with: "").count > lengthLimit { return false } } } return true } // MARK: - Private Method private func formatToModeString(_ text: String) -> String { var string = text.replacingOccurrences(of: " ", with: "") for index in sepIndex { if string.count > index { string.insert(" ", at: string.index(string.startIndex, offsetBy: index)) } } return string } private func resetPosition(offset: Int) { let newPosition = self.position(from: self.beginningOfDocument, offset: offset)! self.selectedTextRange = self.textRange(from: newPosition, to: newPosition) } }
a543c345aaff4831d4036f016ad88557
36.728395
129
0.472022
false
false
false
false
jtekenos/ios_schedule
refs/heads/develop
ios_schedule/ClassForum.swift
mit
1
// // ClassForum.swift // ios_schedule // // Created by Jessica Tekenos on 2015-11-27. // Copyright © 2015 Jess. All rights reserved. // import Foundation import RealmSwift import Parse import ParseUI class ClassForum: Object { dynamic var classForumId = 0 dynamic var set = "" dynamic var name = "" dynamic var instructor = "" let posts = List<Post>() // Specify properties to ignore (Realm won't persist these) // override static func ignoredProperties() -> [String] { // return [] // } }
37500a62265bd37c28fa2a229b8aa130
18.928571
63
0.625448
false
false
false
false
austinzheng/swift-compiler-crashes
refs/heads/master
fixed/27135-swift-patternbindingdecl-setpattern.swift
mit
4
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {{{ let : T:a<T where f enum b {struct A enum B}protocol a{ let a=f:A{var" let a { let c{ class d{{ }typealias d {func f g class A { struct d<S where B{ let : N < where h:a var f _}}}} struct S<T where g:d {{{ class B{ var b{ <f {let:d { class b:d{ " { var b{ let : d:A struct d:d { B{ struct B<T where " {{a enum B<T where f: T> : a{var b=Swift.h =1 func f g < where " "" {}struct B<T where f: d< where B : T.h =1 < where h:A func f g:a func let a = " " class d func g a<T {var b { class B<f=1 var b{ var f= let : d:P { class A class A class A{ class A { }}protocol a= func aA} "" class b<f= struct B<T> : { B<T where B{var b:e}}struct S<f:P { let a = " { func foo}typealias d<T where f func aA} struct S<T where " { let : T:e let:d{var" var b { " func a <T {let:d< {func a{{let:A }}} < where h: d B{{ " " " " func a=1 class A var b{ { where =1 class b<T where a = f: a= protocol B:a = " [ 1 {{{ protocol B{ let a func < where h: { class A {}} protocol a{var b {b{{ protocol B:a func struct S<T where =f: { { enum :a<T where g:e let:d struct S<T { func A protocol B{var f= let c{ enum B:P { enum S<T where B : d where a func let a = " {var b:d where g:a<{{var"""" class B<f:A struct S<h {var b {}typealias d< where h: d where f class d<T where g:d<T where g struct B{{ enum b { protocol B{ protocol a class A class B{ class A { { let a<T where B{ let : d:P { struct A enum S<f:d:e}}struct S<T where h:e class d let a func class A<T where f=Swift.E let a = f:d { func g a enum B<T where B : a{ func g a<T where g:d where g:d func a class a<T where " [ 1 class A {var b:d {b<T:a{ }protocol B} class d{} _}}typealias d let a {var f=1 let c{var b { class A { func aA}}}typealias d func f g:a=f:P {{ class A { protocol B} func foo}} let c<f=1 class A class {{ let : T:A{func g a{struct B{ <T { class A { class d<T where g:a var b<T where g func f g:a protocol a<T where g:d<T where h:A class A{ { class d<S where f: {{ protocol a{ class a<T.e}}}} let a{ { enum S<f class a{let:T {b {{ func g a var b:T>: T func foo} let a{ let : d:d enum B{var b{a{struct S<T:A<T <T
fd333d10e1c913ecc9e25fda8f2347c7
13.677632
87
0.619005
false
false
false
false
sopinetchat/SopinetChat-iOS
refs/heads/master
Pod/Models/SImageFile.swift
gpl-3.0
1
// // SImageFile.swift // Pods // // Created by David Moreno Lora on 26/4/16. // // import Foundation import UIKit public class SImageFile { public dynamic var id = -1 public dynamic var path = "" public var message: SMessageImage? init(id: Int, path: String, message: SMessageImage) { self.id = id self.path = path self.message = message } }
53d80e46d178be28950c34ef7719dd60
15.916667
55
0.598522
false
false
false
false
cotkjaer/Silverback
refs/heads/master
Silverback/UIPickerView.swift
mit
1
// // UIPickerView.swift // Silverback // // Created by Christian Otkjær on 08/12/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import UIKit extension UIPickerView { public func maxSizeForRowsInComponent(component: Int) -> CGSize { var size = CGSizeZero if let delegate = self.delegate, let dataSource = self.dataSource, let widthToFit = delegate.pickerView?(self, widthForComponent: component) { let sizeToFit = CGSize(width: widthToFit , height: 10000) for row in 0..<dataSource.pickerView(self, numberOfRowsInComponent: component) { let view = delegate.pickerView!(self, viewForRow: row, forComponent: component, reusingView: nil) let wantedSize = view.sizeThatFits(sizeToFit) size.width = max(size.width, wantedSize.width) size.height = max(size.height, wantedSize.height) } } return size } }
d43c1b12afb5dd41ca441ae4c6e84e7f
29.941176
148
0.596958
false
false
false
false
prachigauriar/MagazineScanCombiner
refs/heads/master
Magazine Scan Combiner/Controllers/ScanCombinerWindowController.swift
mit
1
// // ScanCombinerWindowController.swift // Magazine Scan Combiner // // Created by Prachi Gauriar on 7/3/2016. // Copyright © 2016 Prachi Gauriar. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Cocoa class ScanCombinerWindowController : NSWindowController, FileDropImageAndPathFieldViewDelegate { // MARK: - Outlets and UI-related properties @IBOutlet var frontPagesDropView: FileDropImageAndPathFieldView! @IBOutlet var reversedBackPagesDropView: FileDropImageAndPathFieldView! @IBOutlet var combinePDFsButton: NSButton! // MARK: - User input properties var frontPagesURL: URL? { didSet { updateCombinePDFsButtonEnabledState() } } var reversedBackPagesURL: URL? { didSet { updateCombinePDFsButtonEnabledState() } } // MARK: - Concurrency lazy var operationQueue: OperationQueue = { let operationQueue = OperationQueue() operationQueue.name = "\(type(of: self)).\(Unmanaged.passUnretained(self).toOpaque())" return operationQueue }() // MARK: - NSWindowController subclass overrides override var windowNibName: NSNib.Name? { return .scanCombinerWindow } override func windowDidLoad() { super.windowDidLoad() frontPagesDropView.delegate = self reversedBackPagesDropView.delegate = self updateCombinePDFsButtonEnabledState() } // MARK: - Action methods @IBAction func combinePDFs(_ sender: NSButton) { guard let window = window, let directoryURL = frontPagesURL?.deletingLastPathComponent() else { NSSound.beep() return } let savePanel = NSSavePanel() savePanel.nameFieldStringValue = NSLocalizedString("ScanCombinerWindowController.DefaultOutputFilename", comment: "Default filename for the output PDF") savePanel.directoryURL = directoryURL savePanel.allowedFileTypes = [kUTTypePDF as String] savePanel.canSelectHiddenExtension = true savePanel.beginSheetModal(for: window) { [unowned self] result in guard result == .OK, let outputURL = savePanel.url else { return } self.beginCombiningPDFs(withOutputURL: outputURL) } } private func beginCombiningPDFs(withOutputURL outputURL: URL) { guard let frontPagesURL = frontPagesURL, let reversedBackPagesURL = reversedBackPagesURL, let window = window else { return } // Create the combine scan operation with our input and output PDF URLs let operation = CombineScansOperation(frontPagesPDFURL: frontPagesURL, reversedBackPagesPDFURL: reversedBackPagesURL, outputPDFURL: outputURL) // Set up a progress sheet controller so we can show a progress sheet let progressSheetController = ProgressSheetController() progressSheetController.progress = operation.progress progressSheetController.localizedProgressMesageKey = "CombineProgress.Format" guard let progressSheet = progressSheetController.window else { return } // Add a completion block that hides the progress sheet when the operation finishes operation.completionBlock = { [weak window] in progressSheetController.progress = nil OperationQueue.main.addOperation { [weak window, weak progressSheet] in guard let progressSheet = progressSheet else { return } window?.endSheet(progressSheet) } } // Begin showing the progress sheet. On dismiss, either show an error or show the resultant PDF file window.beginSheet(progressSheet, completionHandler: { [unowned self] _ in if let error = operation.error { // If there was an error, show an alert to the user self.showAlert(for: error) } else if !operation.isCancelled { // Otherwise show the resultant PDF in the Finder if it wasn’t canceled NSWorkspace.shared.activateFileViewerSelecting([outputURL]) } }) operationQueue.addOperation(operation) } // MARK: - Updating the UI based on user input private func updateCombinePDFsButtonEnabledState() { combinePDFsButton.isEnabled = frontPagesURL != nil && reversedBackPagesURL != nil } // MARK: - Showing alerts private func showAlert(for error: CombineScansError) { let alert = NSAlert() alert.addButton(withTitle: NSLocalizedString("OK", comment: "OK button title")) switch error { case let .couldNotOpenFileURL(fileURL): updateAlert(alert, withErrorLocalizedKey: "CouldNotOpenFile", fileURL: fileURL) case let .couldNotCreateOutputPDF(fileURL): updateAlert(alert, withErrorLocalizedKey: "CouldNotCreateFile", fileURL: fileURL) } alert.beginSheetModal(for: self.window!, completionHandler: nil) } private func updateAlert(_ alert: NSAlert, withErrorLocalizedKey key: String, fileURL: URL) { alert.messageText = NSLocalizedString("Error.\(key).MessageText", comment: "") alert.informativeText = String.localizedStringWithFormat(NSLocalizedString("Error.\(key).InformativeText.Format", comment: ""), fileURL.path.abbreviatingWithTildeInPath) } // MARK: - File Drop Image and Path Field View delegate func fileDropImageAndPathFieldView(_ view: FileDropImageAndPathFieldView, shouldAcceptDraggedFileURL fileURL: URL) -> Bool { guard let resourceValues = try? fileURL.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey]), let fileType = resourceValues.typeIdentifier else { return false } return UTTypeConformsTo(fileType as CFString, kUTTypePDF) } func fileDropImageAndPathFieldView(_ view: FileDropImageAndPathFieldView, didReceiveDroppedFileURL fileURL: URL) { if view == frontPagesDropView { frontPagesURL = fileURL } else { reversedBackPagesURL = fileURL } } } private extension NSNib.Name { static let scanCombinerWindow = NSNib.Name("ScanCombinerWindow") }
640df51c7e2abacd7c286526ea0c3bb0
35.807882
150
0.673849
false
false
false
false
gkaimakas/SwiftValidatorsReactiveExtensions
refs/heads/master
Example/SwiftValidatorsReactiveExtensions/Views/TextFieldCollectionViewCell/TextFieldCollectionViewCell.swift
mit
1
// // TextFieldCollectionViewCell.swift // SwiftValidatorsReactiveExtensions_Example // // Created by George Kaimakas on 12/02/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import MagazineLayout import SnapKit import UIKit class TextFieldCollectionViewCell: MagazineLayoutCollectionViewCell { let titleLabel = UILabel(frame: .zero) let textField = UITextField(frame: .zero) let errorLabel = UILabel(frame: .zero) override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { addSubview(titleLabel) addSubview(textField) addSubview(errorLabel) titleLabel.snp.makeConstraints { (make) in make.leading.equalToSuperview() make.trailing.equalToSuperview() make.top.equalToSuperview() make.bottom.equalTo(textField.snp.top) } textField.snp.makeConstraints { (make) in make.leading.equalToSuperview() make.trailing.equalToSuperview() make.bottom.equalTo(errorLabel.snp.top) } errorLabel.snp.makeConstraints { (make) in make.leading.equalToSuperview() make.trailing.equalToSuperview() make.bottom.equalToSuperview() } titleLabel.font = UIFont.preferredFont(forTextStyle: .caption1) errorLabel.font = UIFont.preferredFont(forTextStyle: .caption1) textField.borderStyle = .roundedRect titleLabel.text = "title" textField.placeholder = "text field" errorLabel.text = "error" } }
555ad6c1f5189994bb691cb9a97e1c5e
27.934426
71
0.623229
false
false
false
false
dorentus/bna-swift
refs/heads/master
Padlock/Authenticator/Secret.swift
mit
1
// // Secret.swift // Authenticator // // Created by Rox Dorentus on 14-6-5. // Copyright (c) 2014年 rubyist.today. All rights reserved. // import Foundation public struct Secret: Printable, Equatable { public let text: String public var binary: [UInt8] { return hex2bin(text) } public var description: String { return text } public init?(text: String) { if let secret = Secret.format(secret: text) { self.text = secret } else { return nil } } public init?(binary: [UInt8]) { self.init(text: bin2hex(binary)) } public static func format(#secret: String) -> String? { let text = secret.lowercaseString if text.matches("[0-9a-f]{40}") { return text } return nil } } public func ==(lhs: Secret, rhs: Secret) -> Bool { return lhs.text == rhs.text }
463522e83a88a8b566ce52f76256669b
21.02439
59
0.578073
false
false
false
false
Narsail/relaykit
refs/heads/master
RelayKit/Shared/Relay.swift
mit
1
/// Copyright (c) 2017 David Moeller /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import Foundation import WatchConnectivity public enum RelayError: Error { case moduleIdentNotFound case messageIdentNotFound case noMessageTypeMatchFor(messageIdent: String) case receiverNotFound } open class Relay: NSObject { /// Last initiated Relay public static var shared: Relay? { didSet { debugLog(RelayKitLogCategory.configuration, ["Setting", type(of: shared), "as Relay with", type(of: shared?.core), "."]) } } internal var core: RelayCore internal var sender: [String: (Sender, [Message.Type])] = [:] internal var receiver: [String: (Receiver, [Message.Type])] = [:] public var errorHandler: ((Error) -> Void)? = nil public init(core: RelayCore) { self.core = core super.init() // Attach the receiving end of the core to the receivers self.core.didReceiveMessage = { [weak self] data, method, replyHandler in // Check for the Module Indent do { debugLog(.messageContent, ["Received Message Data", data]) guard let moduleIdent = data["moduleIdent"] as? String else { throw RelayError.moduleIdentNotFound } // Check for the receiver guard let (receiver, messageTypes) = self?.receiver[moduleIdent] else { throw RelayError.receiverNotFound } // Check for the Message Ident guard let messageIdent = data["messageIdent"] as? String else { throw RelayError.messageIdentNotFound } // Get the appropriate Message Type guard let messageType = messageTypes.first(where: { $0.messageIdent == messageIdent }) else { throw RelayError.noMessageTypeMatchFor(messageIdent: messageIdent) } let message = try messageType.decode(data) debugLog(.messages, ["Received", messageType, "with", method]) if let replyHandler = replyHandler { receiver.didReceiveMessage(message, method, { replyMessage in var encodedData = replyMessage.encode() encodedData["moduleIdent"] = moduleIdent encodedData["messageIdent"] = type(of: replyMessage).messageIdent replyHandler(encodedData) }) } else { receiver.didReceiveMessage(message, method, nil) } } catch { debugLog(.messages, ["Receiving message failed with", error, "by", method]) self?.errorHandler?(error) } } Relay.shared = self } /// Registering a Sender can only be done once per object /// /// - note: A followed call with the same sender will overwrite the old one public func register(_ sender: Sender, with messages: Message.Type ...) { self.register(sender, with: messages) } /// Registering a Sender can only be done once per object /// /// - note: A followed call with the same sender will overwrite the old one public func register(_ sender: Sender, with messages: [Message.Type]) { self.sender[sender.moduleIdent] = (sender, messages) // Set the necessary blocks sender.sendMessageBlock = { [weak self] message, method, replyHandler, errorHandler in debugLog(.messages, ["Sending Message", type(of: message), "with", method]) // Error Handling if wrong Method var data = message.encode() data["moduleIdent"] = sender.moduleIdent data["messageIdent"] = type(of: message).messageIdent debugLog(.messageContent, ["Sending Message Data", data]) do { try self?.core.sendMessage(data, method, replyHandler: { replyData in do { debugLog(.messageContent, ["Got Reply Data with", replyData]) // Find Message ident guard let messageIdent = replyData["messageIdent"] as? String else { throw RelayError.messageIdentNotFound } // Find a suitable Message to return guard let messageClass = messages.first(where: { $0.messageIdent == messageIdent }) else { throw RelayError.noMessageTypeMatchFor(messageIdent: messageIdent) } let responseMessage = try messageClass.decode(replyData) debugLog(.messages, ["Got Reply with", type(of: message), "with", method]) replyHandler(responseMessage) } catch { debugLog(.messages, ["Receiving reply failed with", error, "by", method]) errorHandler(error) } }, errorHandler: errorHandler) } catch { debugLog(.messages, ["Sending message failed with", error, "by", method]) errorHandler(error) } } } /// Registering a Receiver can only be done once per object public func register(_ receiver: Receiver, with messages: Message.Type ...) { self.register(receiver, with: messages) } /// Registering a Receiver can only be done once per object public func register(_ receiver: Receiver, with messages: [Message.Type]) { self.receiver[receiver.moduleIdent] = (receiver, messages) } /// Registering a Communicator can only be done once per object public func register(_ allrounder: Allrounder, with messages: Message.Type ...) { self.register(allrounder, with: messages) } public func register(_ allrounder: Allrounder, with messages: [Message.Type]) { self.register(allrounder as Sender, with: messages) self.register(allrounder as Receiver, with: messages) } public func deregister(_ sender: Sender) { // Set the Blocks nil sender.sendMessageBlock = nil self.sender.removeValue(forKey: sender.moduleIdent) } public func deregister(_ receiver: Receiver) { self.receiver.removeValue(forKey: receiver.moduleIdent) } public func deregister(_ allrounder: Allrounder) { self.deregister(allrounder as Sender) self.deregister(allrounder as Receiver) } }
396c745d8b0ab97b7bf566184a5c4bd1
38.191964
178
0.577628
false
false
false
false
avito-tech/Marshroute
refs/heads/master
MarshrouteTests/Sources/Routers/MasterRouterTests/MasterlRouterTests.swift
mit
1
import XCTest @testable import Marshroute final class MasterlRouterTests: XCTestCase { var masterAnimatingTransitionsHandlerSpy: AnimatingTransitionsHandlerSpy! var detailAnimatingTransitionsHandlerSpy: AnimatingTransitionsHandlerSpy! var targetViewController: UIViewController! var router: MasterRouter! override func setUp() { super.setUp() let transitionIdGenerator = TransitionIdGeneratorImpl() let peekAndPopTransitionsCoordinator = PeekAndPopUtilityImpl() let transitionsCoordinator = TransitionsCoordinatorImpl( stackClientProvider: TransitionContextsStackClientProviderImpl(), peekAndPopTransitionsCoordinator: peekAndPopTransitionsCoordinator ) masterAnimatingTransitionsHandlerSpy = AnimatingTransitionsHandlerSpy( transitionsCoordinator: transitionsCoordinator ) detailAnimatingTransitionsHandlerSpy = AnimatingTransitionsHandlerSpy( transitionsCoordinator: transitionsCoordinator ) targetViewController = UIViewController() router = BaseMasterDetailRouter( routerSeed: MasterDetailRouterSeed( masterTransitionsHandlerBox: .init( animatingTransitionsHandler: masterAnimatingTransitionsHandlerSpy ), detailTransitionsHandlerBox: .init( animatingTransitionsHandler: detailAnimatingTransitionsHandlerSpy ), transitionId: transitionIdGenerator.generateNewTransitionId(), presentingTransitionsHandler: nil, transitionsHandlersProvider: transitionsCoordinator, transitionIdGenerator: transitionIdGenerator, controllersProvider: RouterControllersProviderImpl() ) ) } // MARK: - Master Transitions Handler func testThatMasterDetailRouterCallsItsMasterTransitionsHandlerOn_SetMasterViewControllerDerivedFrom_WithCorrectResettingContext() { // Given var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! // When router.setMasterViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(masterAnimatingTransitionsHandlerSpy.resetWithTransitionCalled) let resettingContext = masterAnimatingTransitionsHandlerSpy.resetWithTransitionContextParameter XCTAssertEqual(resettingContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssert(resettingContext?.targetViewController === targetViewController) XCTAssert(resettingContext?.targetTransitionsHandlerBox.unbox() === masterAnimatingTransitionsHandlerSpy) XCTAssertNil(resettingContext?.storableParameters) if case .some(.resettingNavigationRoot(let launchingContext)) = resettingContext?.resettingAnimationLaunchingContextBox { XCTAssert(launchingContext.rootViewController! == targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsMasterTransitionsHandlerOn_SetMasterViewControllerDerivedFrom_WithCorrectResettingContext_IfCustomAnimator() { // Given var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! let resetNavigationTransitionsAnimator = ResetNavigationTransitionsAnimator() // When router.setMasterViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetViewController }, animator: resetNavigationTransitionsAnimator ) // Then XCTAssert(masterAnimatingTransitionsHandlerSpy.resetWithTransitionCalled) let resettingContext = masterAnimatingTransitionsHandlerSpy.resetWithTransitionContextParameter XCTAssertEqual(resettingContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssert(resettingContext?.targetViewController === targetViewController) XCTAssert(resettingContext?.targetTransitionsHandlerBox.unbox() === masterAnimatingTransitionsHandlerSpy) XCTAssertNil(resettingContext?.storableParameters) if case .some(.resettingNavigationRoot(let launchingContext)) = resettingContext?.resettingAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === resetNavigationTransitionsAnimator) XCTAssert(launchingContext.rootViewController! === targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsMasterTransitionsHandlerOn_PushMasterViewControllerDerivedFrom_WithCorrectPresentationContext() { // Given var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! // When router.pushMasterViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(masterAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = masterAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.pendingAnimating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssertNil(presentationContext?.storableParameters) if case .some(.push(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.targetViewController! == targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsMasterTransitionsHandlerOn_PushMasterViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() { // Given var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! let navigationTransitionsAnimator = NavigationTransitionsAnimator() // When router.pushMasterViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetViewController }, animator: navigationTransitionsAnimator ) // Then XCTAssert(masterAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = masterAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.pendingAnimating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssertNil(presentationContext?.storableParameters) if case .some(.push(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === navigationTransitionsAnimator) XCTAssert(launchingContext.targetViewController! === targetViewController) } else { XCTFail() } } // MARK: - Detail Transitions Handler func testThatMasterDetailRouterCallsItsDetailTransitionsHandlerOn_SetDetailViewControllerDerivedFrom_WithCorrectResettingContext() { // Given var nextModuleRouterSeed: RouterSeed! // When router.setDetailViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.resetWithTransitionCalled) let resettingContext = detailAnimatingTransitionsHandlerSpy.resetWithTransitionContextParameter XCTAssertEqual(resettingContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssertEqual(resettingContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(resettingContext?.targetViewController === targetViewController) XCTAssert(resettingContext?.targetTransitionsHandlerBox.unbox() === detailAnimatingTransitionsHandlerSpy) XCTAssertNil(resettingContext?.storableParameters) if case .some(.resettingNavigationRoot(let launchingContext)) = resettingContext?.resettingAnimationLaunchingContextBox { XCTAssert(launchingContext.rootViewController! == targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsDetailTransitionsHandlerOn_SetDetailViewControllerDerivedFrom_WithCorrectResettingContext_IfCustomAnimator() { // Given var nextModuleRouterSeed: RouterSeed! let resetNavigationTransitionsAnimator = ResetNavigationTransitionsAnimator() // When router.setDetailViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController }, animator: resetNavigationTransitionsAnimator ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.resetWithTransitionCalled) let resettingContext = detailAnimatingTransitionsHandlerSpy.resetWithTransitionContextParameter XCTAssertEqual(resettingContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssertEqual(resettingContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(resettingContext?.targetViewController === targetViewController) XCTAssert(resettingContext?.targetTransitionsHandlerBox.unbox() === detailAnimatingTransitionsHandlerSpy) XCTAssertNil(resettingContext?.storableParameters) if case .some(.resettingNavigationRoot(let launchingContext)) = resettingContext?.resettingAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === resetNavigationTransitionsAnimator) XCTAssert(launchingContext.rootViewController! === targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsDetailTransitionsHandlerOn_PushDetailViewControllerDerivedFrom_WithCorrectPresentationContext() { // Given var nextModuleRouterSeed: RouterSeed! // When router.pushDetailViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.pendingAnimating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssertNil(presentationContext?.storableParameters) if case .some(.push(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.targetViewController! == targetViewController) } else { XCTFail() } } func testThatMasterDetailRouterCallsItsDetailTransitionsHandlerOn_PushDetailViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() { // Given var nextModuleRouterSeed: RouterSeed! let navigationTransitionsAnimator = NavigationTransitionsAnimator() // When router.pushDetailViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController }, animator: navigationTransitionsAnimator ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.pendingAnimating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssertNil(presentationContext?.storableParameters) if case .some(.push(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === navigationTransitionsAnimator) XCTAssert(launchingContext.targetViewController! === targetViewController) } else { XCTFail() } } }
b83d21124ec3b0ea628110c0495ba23f
51.517647
157
0.736783
false
false
false
false
PopcornTimeTV/PopcornTimeTV
refs/heads/master
PopcornKit/Managers/NetworkManager.swift
gpl-3.0
1
import Foundation import Alamofire public struct Trakt { static let apiKey = "d3b0811a35719a67187cba2476335b2144d31e5840d02f687fbf84e7eaadc811" static let apiSecret = "f047aa37b81c87a990e210559a797fd4af3b94c16fb6d22b62aa501ca48ea0a4" static let base = "https://api.trakt.tv" static let shows = "/shows" static let movies = "/movies" static let people = "/people" static let person = "/person" static let seasons = "/seasons" static let episodes = "/episodes" static let auth = "/oauth" static let token = "/token" static let sync = "/sync" static let playback = "/playback" static let history = "/history" static let device = "/device" static let code = "/code" static let remove = "/remove" static let related = "/related" static let watched = "/watched" static let watchlist = "/watchlist" static let scrobble = "/scrobble" static let imdb = "/imdb" static let tvdb = "/tvdb" static let search = "/search" static let extended = ["extended": "full"] public struct Headers { static let Default = [ "Content-Type": "application/json", "trakt-api-version": "2", "trakt-api-key": Trakt.apiKey ] static func Authorization(_ token: String) -> [String: String] { var Authorization = Default; Authorization["Authorization"] = "Bearer \(token)" return Authorization } } public enum MediaType: String { case movies = "movies" case shows = "shows" case episodes = "episodes" case people = "people" } /** Watched status of media. - .watching: When the video intially starts playing or is unpaused. - .paused: When the video is paused. - .finished: When the video is stopped or finishes playing on its own. */ public enum WatchedStatus: String { /// When the video intially starts playing or is unpaused. case watching = "start" /// When the video is paused. case paused = "pause" /// When the video is stopped or finishes playing on its own. case finished = "stop" } } public struct PopcornShows { static let base = "https://tv-v2.api-fetch.sh" static let shows = "/shows" static let show = "/show" } public struct PopcornMovies { static let base = "https://movies-v2.api-fetch.sh" static let movies = "/movies" static let movie = "/movie" } public struct TMDB { static let apiKey = "739eed14bc18a1d6f5dacd1ce6c2b29e" static let base = "https://api.themoviedb.org/3" static let tv = "/tv" static let person = "/person" static let images = "/images" static let season = "/season" static let episode = "/episode" public enum MediaType: String { case movies = "movie" case shows = "tv" } static let defaultHeaders = ["api_key": TMDB.apiKey] } public struct Fanart { static let apiKey = "bd2753f04538b01479e39e695308b921" static let base = "http://webservice.fanart.tv/v3" static let tv = "/tv" static let movies = "/movies" static let defaultParameters = ["api_key": Fanart.apiKey] } public struct OpenSubtitles { static let base = "https://rest.opensubtitles.org/" static let userAgent = "Popcorn Time NodeJS" // static let logIn = "LogIn" // static let logOut = "LogOut" static let search = "search/" static let defaultHeaders = ["User-Agent": OpenSubtitles.userAgent] } open class NetworkManager: NSObject { internal let manager: SessionManager = { var configuration = URLSessionConfiguration.default configuration.httpCookieAcceptPolicy = .never configuration.httpShouldSetCookies = false configuration.urlCache = nil configuration.requestCachePolicy = .reloadIgnoringCacheData return Alamofire.SessionManager(configuration: configuration) }() /// Possible orders used in API call. public enum Orders: Int { case ascending = 1 case descending = -1 } /// Possible genres used in API call. public enum Genres: String { case all = "All" case action = "Action" case adventure = "Adventure" case animation = "Animation" case comedy = "Comedy" case crime = "Crime" case disaster = "Disaster" case documentary = "Documentary" case drama = "Drama" case family = "Family" case fanFilm = "Fan Film" case fantasy = "Fantasy" case filmNoir = "Film Noir" case history = "History" case holiday = "Holiday" case horror = "Horror" case indie = "Indie" case music = "Music" case mystery = "Mystery" case road = "Road" case romance = "Romance" case sciFi = "Science Fiction" case short = "Short" case sports = "Sports" case sportingEvent = "Sporting Event" case suspense = "Suspense" case thriller = "Thriller" case war = "War" case western = "Western" public static var array = [all, action, adventure, animation, comedy, crime, disaster, documentary, drama, family, fanFilm, fantasy, filmNoir, history, holiday, horror, indie, music, mystery, road, romance, sciFi, short, sports, sportingEvent, suspense, thriller, war, western] public var string: String { return rawValue.localized } } }
842172af10621e330fe665ac34d0010e
31.770588
285
0.619458
false
false
false
false
stripe/stripe-ios
refs/heads/master
Example/Non-Card Payment Examples/Non-Card Payment Examples/AffirmExampleViewController.swift
mit
1
// // AffirmExampleViewController.swift // Non-Card Payment Examples // // Copyright © 2022 Stripe. All rights reserved. // import Stripe import UIKit class AffirmExampleViewController: UIViewController { @objc weak var delegate: ExampleViewControllerDelegate? var inProgress: Bool = false { didSet { navigationController?.navigationBar.isUserInteractionEnabled = !inProgress payButton.isEnabled = !inProgress inProgress ? activityIndicatorView.startAnimating() : activityIndicatorView.stopAnimating() } } // UI lazy var activityIndicatorView = { return UIActivityIndicatorView(style: .gray) }() lazy var payButton: UIButton = { let button = UIButton(type: .roundedRect) button.setTitle("Pay with Affirm", for: .normal) button.addTarget(self, action: #selector(didTapPayButton), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Affirm" [payButton, activityIndicatorView].forEach { subview in view.addSubview(subview) subview.translatesAutoresizingMaskIntoConstraints = false } let constraints = [ payButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), payButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor), activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor), ] NSLayoutConstraint.activate(constraints) } @objc func didTapPayButton() { guard STPAPIClient.shared.publishableKey != nil else { delegate?.exampleViewController( self, didFinishWithMessage: "Please set a Stripe Publishable Key in Constants.m") return } inProgress = true pay() } } // MARK: - extension AffirmExampleViewController { @objc func pay() { // 1. Create an Affirm PaymentIntent MyAPIClient.shared().createPaymentIntent( completion: { (result, clientSecret, error) in guard let clientSecret = clientSecret else { self.delegate?.exampleViewController(self, didFinishWithError: error) return } // 2. Collect shipping information let shippingAddress = STPPaymentIntentShippingDetailsAddressParams(line1: "55 John St") shippingAddress.line2 = "#3B" shippingAddress.city = "New York" shippingAddress.state = "NY" shippingAddress.postalCode = "10002" shippingAddress.country = "US" let shippingDetailsParam = STPPaymentIntentShippingDetailsParams(address: shippingAddress, name: "TestName") let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret) paymentIntentParams.paymentMethodParams = STPPaymentMethodParams( affirm: STPPaymentMethodAffirmParams(), metadata: [:]) paymentIntentParams.returnURL = "payments-example://safepay/" paymentIntentParams.shipping = shippingDetailsParam // 3. Confirm payment STPPaymentHandler.shared().confirmPayment( paymentIntentParams, with: self ) { (status, intent, error) in switch status { case .canceled: self.delegate?.exampleViewController( self, didFinishWithMessage: "Cancelled") case .failed: self.delegate?.exampleViewController(self, didFinishWithError: error) case .succeeded: self.delegate?.exampleViewController( self, didFinishWithMessage: "Payment successfully created.") @unknown default: fatalError() } } }, additionalParameters: "supported_payment_methods=affirm&products[]=👛") } } extension AffirmExampleViewController: STPAuthenticationContext { func authenticationPresentingViewController() -> UIViewController { self } }
9114b9f09b9078e136f70589e125ccef
38.669565
106
0.596449
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios
refs/heads/develop
Example/SuperAwesomeExampleTests/Common/Mocks/MockFactory.swift
lgpl-3.0
1
// // AdMock.swift // Tests // // Created by Gunhan Sancar on 24/04/2020. // @testable import SuperAwesome class MockFactory { static func makeAdWithTagAndClickUrl(_ tag: String?, _ url: String?) -> Ad { makeAd(.tag, nil, url, tag) } static func makeAdWithImageLink(_ url: String?) -> Ad { makeAd(.imageWithLink, nil, url) } static func makeAd( _ format: CreativeFormatType = .imageWithLink, _ vast: String? = nil, _ clickUrl: String? = nil, _ tag: String? = nil, _ showPadlock: Bool = false, _ ksfRequest: String? = nil, _ bumper: Bool = true ) -> Ad { Ad(advertiserId: 10, publisherId: 20, moat: 0.1, campaignId: 30, campaignType: 40, isVpaid: true, showPadlock: showPadlock, lineItemId: 50, test: false, app: 70, device: "device", creative: Creative( id: 80, name: "name", format: format, clickUrl: clickUrl, details: CreativeDetail( url: "detailurl", image: "image", video: "video", placementFormat: "placement", tag: tag, width: 90, height: 100, duration: 110, vast: vast), bumper: bumper, payload: nil), ksfRequest: ksfRequest) } static func makeError() -> Error { NSError(domain: "", code: 404, userInfo: nil) } static func makeAdRequest() -> AdRequest { AdRequest(test: false, position: .aboveTheFold, skip: .no, playbackMethod: 0, startDelay: AdRequest.StartDelay.midRoll, instl: .off, width: 25, height: 35) } static func makeAdQueryInstance() -> QueryBundle { QueryBundle(parameters: AdQuery( test: true, sdkVersion: "", random: 1, bundle: "", name: "", dauid: 1, connectionType: .wifi, lang: "", device: "", position: 1, skip: 1, playbackMethod: 1, startDelay: 1, instl: 1, width: 1, height: 1), options: nil) } static func makeEventQueryInstance() -> QueryBundle { QueryBundle(parameters: EventQuery( placement: 1, bundle: "", creative: 1, lineItem: 1, connectionType: .wifi, sdkVersion: "", rnd: 1, type: nil, noImage: nil, data: nil), options: nil) } static func makeAdResponse() -> AdResponse { AdResponse(10, makeAd()) } static func makeVastAd(clickThrough: String? = nil) -> VastAd { VastAd(url: nil, type: .inLine, redirect: nil, errorEvents: [], impressions: [], clickThrough: clickThrough, creativeViewEvents: [], startEvents: [], firstQuartileEvents: [], midPointEvents: [], thirdQuartileEvents: [], completeEvents: [], clickTrackingEvents: [], media: []) } }
318c87460142e8222ce1636986793d81
26.092308
86
0.455991
false
false
false
false
sjtu-meow/iOS
refs/heads/master
Meow/UserRecordTableViewCell.swift
apache-2.0
1
// // UserRecordTableViewCell.swift // Meow // // Created by 林武威 on 2017/7/13. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit protocol UnfollowUserDelegate { func didClickUnfollow(profile: Profile) } protocol UserRecordTableViewCellDelegate: UnfollowUserDelegate, AvatarCellDelegate { } class UserRecordTableViewCell: UITableViewCell { var delegate: UserRecordTableViewCellDelegate? var model: Profile? @IBOutlet weak var unfollowButton: UIButton! @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nickNameLabel: UILabel! @IBOutlet weak var bioLabel: UILabel! override func awakeFromNib() { unfollowButton.addTarget(self, action: #selector(didClickUnfollow), for: UIControlEvents.touchUpInside) avatarImageView.isUserInteractionEnabled = true let tapAvatarRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.didTapAvatar(_:))) avatarImageView.addGestureRecognizer(tapAvatarRecognizer) } func configure(model: Profile) { self.model = model if let avatar = model.avatar { avatarImageView.af_setImage(withURL: avatar) } nickNameLabel.text = model.nickname bioLabel.text = model.bio } func didClickUnfollow() { guard let model = self.model else { return } delegate?.didClickUnfollow(profile: model) } func didTapAvatar(_ sender: UITapGestureRecognizer) { guard let model = self.model else { return } //delegate?.didTapAvatar() } }
e88c96451a9e07533fcf343ec9101d7a
26.508475
113
0.683303
false
false
false
false
groue/GRDB.swift
refs/heads/master
GRDB/FTS/FTS5.swift
mit
1
#if SQLITE_ENABLE_FTS5 import Foundation /// FTS5 lets you define "fts5" virtual tables. /// /// // CREATE VIRTUAL TABLE document USING fts5(content) /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// /// See <https://www.sqlite.org/fts5.html> public struct FTS5: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// /// See <https://www.sqlite.org/fts5.html> public enum Diacritics { /// Do not remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=0" tokenizer argument. case keep /// Remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=1" tokenizer argument. case removeLegacy #if GRDBCUSTOMSQLITE /// Remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=2" tokenizer argument, /// available from SQLite 3.27.0 case remove #elseif !GRDBCIPHER /// Remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=2" tokenizer argument, /// available from SQLite 3.27.0 @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) case remove #endif } /// Creates a FTS5 module suitable for the Database /// `create(virtualTable:using:)` method. /// /// // CREATE VIRTUAL TABLE document USING fts5(content) /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// /// See <https://www.sqlite.org/fts5.html> public init() { } // Support for FTS5Pattern initializers. Don't make public. Users tokenize // with `FTS5Tokenizer.tokenize()` methods, which support custom tokenizers, // token flags, and query/document tokenzation. /// Tokenizes the string argument as an FTS5 query. /// /// For example: /// /// try FTS5.tokenize(query: "SQLite database") // ["sqlite", "database"] /// try FTS5.tokenize(query: "Gustave Doré") // ["gustave", "doré"]) /// /// Synonym (colocated) tokens are not present in the returned array. See /// `FTS5_TOKEN_COLOCATED` at <https://www.sqlite.org/fts5.html#custom_tokenizers> /// for more information. /// /// - parameter string: The tokenized string. /// - returns: An array of tokens. /// - throws: An error if tokenization fails. static func tokenize(query string: String) throws -> [String] { try DatabaseQueue().inDatabase { db in try db.makeTokenizer(.ascii()).tokenize(query: string).compactMap { $0.flags.contains(.colocated) ? nil : $0.token } } } // MARK: - VirtualTableModule Adoption /// The virtual table module name public let moduleName = "fts5" /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:using:) public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition { FTS5TableDefinition(configuration: configuration) } /// Don't use this method. public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] { var arguments: [String] = [] if definition.columns.isEmpty { // Programmer error fatalError("FTS5 virtual table requires at least one column.") } for column in definition.columns { if column.isIndexed { arguments.append("\(column.name)") } else { arguments.append("\(column.name) UNINDEXED") } } if let tokenizer = definition.tokenizer { let tokenizerSQL = try tokenizer .components .map { component in try component.sqlExpression.quotedSQL(db) } .joined(separator: " ") .sqlExpression .quotedSQL(db) arguments.append("tokenize=\(tokenizerSQL)") } switch definition.contentMode { case let .raw(content, contentRowID): if let content = content { let quotedContent = try content.sqlExpression.quotedSQL(db) arguments.append("content=\(quotedContent)") } if let contentRowID = contentRowID { let quotedContentRowID = try contentRowID.sqlExpression.quotedSQL(db) arguments.append("content_rowid=\(quotedContentRowID)") } case let .synchronized(contentTable): try arguments.append("content=\(contentTable.sqlExpression.quotedSQL(db))") if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn { let quotedRowID = try rowIDColumn.sqlExpression.quotedSQL(db) arguments.append("content_rowid=\(quotedRowID)") } } if let prefixes = definition.prefixes { let prefix = try prefixes .sorted() .map { "\($0)" } .joined(separator: " ") .sqlExpression .quotedSQL(db) arguments.append("prefix=\(prefix)") } if let columnSize = definition.columnSize { arguments.append("columnSize=\(columnSize)") } if let detail = definition.detail { arguments.append("detail=\(detail)") } return arguments } /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:using:) public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws { switch definition.contentMode { case .raw: break case .synchronized(let contentTable): // https://sqlite.org/fts5.html#external_content_tables let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name let ftsTable = tableName.quotedDatabaseIdentifier let content = contentTable.quotedDatabaseIdentifier let indexedColumns = definition.columns.map(\.name) let ftsColumns = (["rowid"] + indexedColumns) .map(\.quotedDatabaseIdentifier) .joined(separator: ", ") let newContentColumns = ([rowIDColumn] + indexedColumns) .map { "new.\($0.quotedDatabaseIdentifier)" } .joined(separator: ", ") let oldContentColumns = ([rowIDColumn] + indexedColumns) .map { "old.\($0.quotedDatabaseIdentifier)" } .joined(separator: ", ") let ifNotExists = definition.configuration.ifNotExists ? "IF NOT EXISTS " : "" // swiftlint:disable line_length try db.execute(sql: """ CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); END; CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; """) // swiftlint:enable line_length // https://sqlite.org/fts5.html#the_rebuild_command try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')") } } static func api(_ db: Database) -> UnsafePointer<fts5_api> { // Access to FTS5 is one of the rare SQLite api which was broken in // SQLite 3.20.0+, for security reasons: // // Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api. // The previous way to access FTS5 does not work any longer. // // So let's see which SQLite version we are linked against: #if GRDBCUSTOMSQLITE || GRDBCIPHER // GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more. return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) #else // GRDB is linked against the system SQLite. // // Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)? if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) { // SQLite 3.24.0 or more return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) } else { // SQLite 3.19.3 or less return api_v1(db) } #endif } private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> { guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else { fatalError("FTS5 is not available") } return data.withUnsafeBytes { $0.bindMemory(to: UnsafePointer<fts5_api>.self).first! } } // Technique given by Jordan Rose: // https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 private static func api_v2( _ db: Database, // swiftlint:disable:next line_length _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt, // swiftlint:disable:next line_length _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt) -> UnsafePointer<fts5_api> { var statement: SQLiteStatement? = nil var api: UnsafePointer<fts5_api>? = nil let type: StaticString = "fts5_api_ptr" let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil) guard code == SQLITE_OK else { fatalError("FTS5 is not available") } defer { sqlite3_finalize(statement) } type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in _ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil) } sqlite3_step(statement) guard let api else { fatalError("FTS5 is not available") } return api } } /// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table. /// /// You don't create instances of this class. Instead, you use the Database /// `create(virtualTable:using:)` method: /// /// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition /// t.column("content") /// } /// /// See <https://www.sqlite.org/fts5.html> public final class FTS5TableDefinition { enum ContentMode { case raw(content: String?, contentRowID: String?) case synchronized(contentTable: String) } fileprivate let configuration: VirtualTableConfiguration fileprivate var columns: [FTS5ColumnDefinition] = [] fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil) /// The virtual table tokenizer /// /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.tokenizer = .porter() /// } /// /// See <https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization> public var tokenizer: FTS5TokenizerDescriptor? /// The FTS5 `content` option /// /// When you want the full-text table to be synchronized with the /// content of an external table, prefer the `synchronize(withTable:)` /// method. /// /// Setting this property invalidates any synchronization previously /// established with the `synchronize(withTable:)` method. /// /// See <https://www.sqlite.org/fts5.html#external_content_and_contentless_tables> public var content: String? { get { switch contentMode { case .raw(let content, _): return content case .synchronized(let contentTable): return contentTable } } set { switch contentMode { case .raw(_, let contentRowID): contentMode = .raw(content: newValue, contentRowID: contentRowID) case .synchronized: contentMode = .raw(content: newValue, contentRowID: nil) } } } /// The FTS5 `content_rowid` option /// /// When you want the full-text table to be synchronized with the /// content of an external table, prefer the `synchronize(withTable:)` /// method. /// /// Setting this property invalidates any synchronization previously /// established with the `synchronize(withTable:)` method. /// /// See <https://sqlite.org/fts5.html#external_content_tables> public var contentRowID: String? { get { switch contentMode { case .raw(_, let contentRowID): return contentRowID case .synchronized: return nil } } set { switch contentMode { case .raw(let content, _): contentMode = .raw(content: content, contentRowID: newValue) case .synchronized: contentMode = .raw(content: nil, contentRowID: newValue) } } } /// Support for the FTS5 `prefix` option /// /// See <https://www.sqlite.org/fts5.html#prefix_indexes> public var prefixes: Set<Int>? /// Support for the FTS5 `columnsize` option /// /// <https://www.sqlite.org/fts5.html#the_columnsize_option> public var columnSize: Int? /// Support for the FTS5 `detail` option /// /// <https://www.sqlite.org/fts5.html#the_detail_option> public var detail: String? init(configuration: VirtualTableConfiguration) { self.configuration = configuration } /// Appends a table column. /// /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// /// - parameter name: the column name. @discardableResult public func column(_ name: String) -> FTS5ColumnDefinition { let column = FTS5ColumnDefinition(name: name) columns.append(column) return column } /// Synchronizes the full-text table with the content of an external /// table. /// /// The full-text table is initially populated with the existing /// content in the external table. SQL triggers make sure that the /// full-text table is kept up to date with the external table. /// /// See <https://sqlite.org/fts5.html#external_content_tables> public func synchronize(withTable tableName: String) { contentMode = .synchronized(contentTable: tableName) } } /// The FTS5ColumnDefinition class lets you refine a column of an FTS5 /// virtual table. /// /// You get instances of this class when you create an FTS5 table: /// /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") // FTS5ColumnDefinition /// } /// /// See <https://www.sqlite.org/fts5.html> public final class FTS5ColumnDefinition { fileprivate let name: String fileprivate var isIndexed: Bool init(name: String) { self.name = name self.isIndexed = true } /// Excludes the column from the full-text index. /// /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("a") /// t.column("b").notIndexed() /// } /// /// See <https://www.sqlite.org/fts5.html#the_unindexed_column_option> /// /// - returns: Self so that you can further refine the column definition. @discardableResult public func notIndexed() -> Self { self.isIndexed = false return self } } extension Column { /// The FTS5 rank column public static let rank = Column("rank") } extension Database { /// Deletes the synchronization triggers for a synchronized FTS5 table. public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws { try execute(sql: """ DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier); DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier); DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier); """) } } #endif
1ab60198e018aa70eb83ccec031c2c3c
37.539474
196
0.589678
false
false
false
false
derrh/CanvasKit
refs/heads/master
CanvasKitTests/Model Tests/CKIAssignmentTests.swift
mit
3
// // CKIAssignmentTests.swift // CanvasKit // // Created by Nathan Lambson on 7/18/14. // Copyright (c) 2014 Instructure. All rights reserved. // import UIKit import XCTest class CKIAssignmentTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testJSONModelConversion() { let assignmentDictionary = Helpers.loadJSONFixture("assignment") as NSDictionary let assignment = CKIAssignment(fromJSONDictionary: assignmentDictionary) XCTAssertEqual(assignment.id!, "4", "Assignment id did not parse correctly") XCTAssertEqual(assignment.name!, "some assignment", "Assignment name did not parse correctly") XCTAssertEqual(assignment.position, 1, "Assignment position did not parse correctly") XCTAssertEqual(assignment.descriptionHTML!, "<p>Do the following:</p>...", "Assignment descriptionHTML did not parse correctly") let formatter = ISO8601DateFormatter() formatter.includeTime = true var date = formatter.dateFromString("2012-07-01T23:59:00-06:00") XCTAssertEqual(assignment.dueAt!, date, "Assignment dueAt did not parse correctly") XCTAssertEqual(assignment.lockAt!, date, "Assignment lockAt did not descriptionHTML correctly") XCTAssertEqual(assignment.unlockAt!, date, "Assignment unlockAt did not parse correctly") XCTAssertEqual(assignment.courseID!, "123", "Assignment courseID did not parse correctly") var url = NSURL(string:"http://canvas.example.com/courses/123/assignments/4") XCTAssertEqual(assignment.htmlURL!, url!, "Assignment htmlURL did not parse correctly") XCTAssertEqual(assignment.allowedExtensions.count, 2, "Assignment allowedExtensions did not parse correctly") XCTAssertEqual(assignment.assignmentGroupID!, "2", "Assignment assignmentGroupID did not parse correctly") XCTAssertEqual(assignment.groupCategoryID!, "1", "Assignment groupCategoryID did not parse correctly") XCTAssert(assignment.muted, "Assignment muted did not parse correctly") XCTAssert(assignment.published, "Assignment published did not parse correctly") XCTAssertEqual(assignment.pointsPossible, 12, "Assignment pointsPossible did not parse correctly") XCTAssert(assignment.gradeGroupStudentsIndividually, "Assignment gradeGroupStudentsIndividually did not parse correctly") XCTAssertEqual(assignment.gradingType!, "points", "Assignment gradingType did not parse correctly") XCTAssertEqual(assignment.scoringType, CKIAssignmentScoringType.Points, "Assignment scoringType did not parse correctly") XCTAssertEqual(assignment.submissionTypes.count, 1, "Assignment submissionTypes did not parse correctly") XCTAssert(assignment.lockedForUser, "Assignment lockedForUser did not parse correctly") XCTAssertEqual(assignment.needsGradingCount, UInt(17), "Assignment needsGradingCount did not parse correctly") XCTAssertNotNil(assignment.rubric, "Assignment rubric did not parse correctly") XCTAssert(assignment.peerReviewRequired, "Assignment peerReviewRequired did not parse correctly") XCTAssert(assignment.peerReviewsAutomaticallyAssigned, "Assignment peerReviewsAutomaticallyAssigned did not parse correctly") XCTAssertEqual(assignment.peerReviewsAutomaticallyAssignedCount, 2, "Assignment peerReviewsAutomaticallyAssignedCount did not parse correctly") XCTAssertEqual(assignment.peerReviewDueDate!, date, "Assignment peerReviewDueDate did not parse correctly") XCTAssertEqual(assignment.path!, "/api/v1/assignments/4", "Assignment path did not parse correctly") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
d846e2cd9de23f749a2f4cb4f440937c
58.112676
151
0.736717
false
true
false
false
davidozhang/spycodes
refs/heads/master
Spycodes/Views/SCSectionHeaderViewCell.swift
mit
1
import UIKit protocol SCSectionHeaderViewCellDelegate: class { func sectionHeaderViewCell(onButtonTapped sectionHeaderViewCell: SCSectionHeaderViewCell) } class SCSectionHeaderViewCell: SCTableViewCell { weak var delegate: SCSectionHeaderViewCellDelegate? fileprivate var blurView: UIVisualEffectView? @IBOutlet weak var button: SCImageButton! @IBAction func onSectionHeaderButtonTapped(_ sender: Any) { self.delegate?.sectionHeaderViewCell(onButtonTapped: self) } override func awakeFromNib() { super.awakeFromNib() self.primaryLabel.font = SCFonts.regularSizeFont(.bold) } func setButtonImage(name: String) { if let _ = self.button { self.button.setImage(UIImage(named: name), for: UIControlState()) } } func hideButton() { if let _ = self.button { self.button.isHidden = true } } func showButton() { if let _ = self.button { self.button.isHidden = false } } func showBlurBackground() { self.hideBlurBackground() if SCLocalStorageManager.instance.isLocalSettingEnabled(.nightMode) { self.blurView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) } else { self.blurView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) } self.blurView?.frame = self.bounds self.blurView?.clipsToBounds = true self.blurView?.tag = SCConstants.tag.sectionHeaderBlurView.rawValue self.addSubview(self.blurView!) self.sendSubview(toBack: self.blurView!) } func hideBlurBackground() { if let view = self.viewWithTag(SCConstants.tag.sectionHeaderBlurView.rawValue) { view.removeFromSuperview() } } }
9288f2a6b30db851ec6126fa46f85f9a
28.306452
93
0.659329
false
false
false
false
masters3d/xswift
refs/heads/master
exercises/luhn/Sources/LuhnExample.swift
mit
1
import Foundation struct Luhn { var number: Int64 = 0 var addends: [Int] { return addendsFunc(number) } var checksum: Int { return addends.reduce(0, +) } var isValid: Bool { return checksum % 10 == 0 } init(_ num: Int64) { self.number = num } static func create (_ num: Int64) -> Double { func createCheckDigit(_ value: Int) -> Int { let nearestTen = Int(ceil((Double(value) / 10.00)) * 10) return nearestTen - value } let zeroCheckDigitNumber = num * 10 let luhn = Luhn(zeroCheckDigitNumber) if luhn.isValid { return Double(zeroCheckDigitNumber)} return Double((zeroCheckDigitNumber) + createCheckDigit(luhn.checksum)) } func addendsFunc(_ num: Int64) -> [Int] { func oddIndexInt64Minus9( _ input: [Int]) -> [Int] { var input = input input = Array(input.reversed()) var tempArray: [Int] = [] for (inx, each) in input.enumerated() { var tempEach: Int = each if (inx+1) % 2 == 0 { tempEach *= 2 if tempEach > 10 { tempEach -= 9 } tempArray.insert(tempEach, at: 0) } else { tempArray.insert(tempEach, at: 0) } } return tempArray } func char2Int(_ input: Character) -> Int { let tempInt = Int(String(input)) ?? -1 // -1 = error return tempInt } let tempString = "\(num)" return oddIndexInt64Minus9(Array(tempString.characters).map { char2Int($0) }) } }
973eac89ed61d0ca2f5c64c11d78f9eb
27.783333
85
0.501448
false
false
false
false
open-telemetry/opentelemetry-swift
refs/heads/main
Examples/Network Sample/main.swift
apache-2.0
1
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetrySdk import StdoutExporter import URLSessionInstrumentation func simpleNetworkCall() { let url = URL(string: "http://httpbin.org/get")! let request = URLRequest(url: url) let semaphore = DispatchSemaphore(value: 0) let task = URLSession.shared.dataTask(with: request) { data, _, _ in if let data = data { let string = String(decoding: data, as: UTF8.self) print(string) } semaphore.signal() } task.resume() semaphore.wait() } class SessionDelegate: NSObject, URLSessionDataDelegate, URLSessionTaskDelegate { let semaphore = DispatchSemaphore(value: 0) func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { semaphore.signal() } } let delegate = SessionDelegate() func simpleNetworkCallWithDelegate() { let session = URLSession(configuration: .default, delegate: delegate, delegateQueue:nil) let url = URL(string: "http://httpbin.org/get")! let request = URLRequest(url: url) let task = session.dataTask(with: request) task.resume() delegate.semaphore.wait() } let spanProcessor = SimpleSpanProcessor(spanExporter: StdoutExporter(isDebug: true)) OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor) let networkInstrumentation = URLSessionInstrumentation(configuration: URLSessionInstrumentationConfiguration()) simpleNetworkCall() simpleNetworkCallWithDelegate() sleep(1)
5e1b657b7b614a2e5f8b84d28e567185
25.566667
111
0.725847
false
false
false
false
zisko/swift
refs/heads/master
test/Inputs/clang-importer-sdk/swift-modules-without-ns/Foundation.swift
apache-2.0
1
@_exported import ObjectiveC @_exported import CoreGraphics @_exported import Foundation public func == (lhs: NSObject, rhs: NSObject) -> Bool { return lhs.isEqual(rhs) } public let NSUTF8StringEncoding: UInt = 8 extension String : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSString { return NSString() } public static func _forceBridgeFromObjectiveC(_ x: NSString, result: inout String?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSString, result: inout String? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSString? ) -> String { return String() } } extension Int : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> Int { return Int() } } extension Array : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSArray { return NSArray() } public static func _forceBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSArray? ) -> Array { return Array() } } extension Dictionary : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSDictionary { return NSDictionary() } public static func _forceBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSDictionary? ) -> Dictionary { return Dictionary() } } extension Set : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSSet { return NSSet() } public static func _forceBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSSet? ) -> Set { return Set() } } extension CGFloat : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> CGFloat { return CGFloat() } } extension NSRange : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSValue { return NSValue() } public static func _forceBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) { result = x.rangeValue } public static func _conditionallyBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSValue? ) -> NSRange { return NSRange() } } extension NSError : Error { public var _domain: String { return domain } public var _code: Int { return code } } public enum _GenericObjCError : Error { case nilError } public func _convertNSErrorToError(_ error: NSError?) -> Error { if let error = error { return error } return _GenericObjCError.nilError } public func _convertErrorToNSError(_ error: Error) -> NSError { return error as NSError }
417db14962bc2821f4a66b1e26b36cab
21.096774
72
0.666667
false
false
false
false
novi/proconapp
refs/heads/master
ProconApp/ProconApp/Utils.swift
bsd-3-clause
1
// // Utils.swift // ProconApp // // Created by ito on 2015/07/07. // Copyright (c) 2015年 Procon. All rights reserved. // import UIKit import ProconBase import APIKit extension UIApplication { func activatePushNotification() { dispatch_async(dispatch_get_main_queue(), { () -> Void in Logger.debug("activatePushNotification") let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil) self.registerUserNotificationSettings(settings) }) } } extension String { init?(deviceTokenData: NSData?) { if let deviceToken = deviceTokenData { let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) var tokenString = "" for var i = 0; i < deviceToken.length; i++ { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } self = tokenString return } return nil } } extension UIColor { static var appTintColor: UIColor { return UIColor(red:46/255.0,green:63/255.0,blue:126/255.0,alpha:1.0) } } class SafariActivity: UIActivity { var url: NSURL? override class func activityCategory() -> UIActivityCategory { return .Action } override func activityType() -> String? { return "SafariActivity" } override func activityTitle() -> String? { return "Safariで開く" } override func activityImage() -> UIImage? { return UIImage(image: .ActivitySafari) } override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool { for obj in activityItems { if let url = obj as? NSURL { self.url = url return true } } return false } override func prepareWithActivityItems(activityItems: [AnyObject]) { for obj in activityItems { if let url = obj as? NSURL { self.url = url return } } } override func performActivity() { let completed: Bool if let url = self.url { completed = UIApplication.sharedApplication().openURL(url) } else { completed = false } self.activityDidFinish(completed) } }
53b692ee17b44e46e2749971ec80ebf8
23.773196
106
0.565362
false
false
false
false
toggl/superday
refs/heads/develop
teferi/UI/Modules/Goals/NewGoal/Views/CustomCollectionView.swift
bsd-3-clause
1
import UIKit protocol CustomCollectionViewDatasource { var initialIndex: Int { get } func numberOfItems(for collectionView: UICollectionView) -> Int func cell(at row: Int, for collectionView: UICollectionView) -> UICollectionViewCell } protocol CustomCollectionViewDelegate { func itemSelected(for collectionView: UICollectionView, at row: Int) } class CustomCollectionView: UICollectionView { let numberOfLoops: Int = 100 var loops: Bool = false var customDatasource: CustomCollectionViewDatasource? { didSet { delegate = self dataSource = self totalNumberOfItems = customDatasource!.numberOfItems(for: self) } } var customDelegate: CustomCollectionViewDelegate? private var didLayout: Bool = false fileprivate var totalNumberOfItems: Int = 0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) setup() } private func setup() { allowsSelection = false } override func layoutSubviews() { super.layoutSubviews() let layout = collectionViewLayout as! UICollectionViewFlowLayout let inset = frame.width / 2 - layout.itemSize.width / 2 contentInset = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset) firstLayoutIfNeeded() } private func firstLayoutIfNeeded() { guard !didLayout, let customDatasource = customDatasource else { return } didLayout = true let layout = collectionViewLayout as! UICollectionViewFlowLayout let cellWidth = layout.itemSize.width + layout.minimumInteritemSpacing let initialOffset = CGFloat(customDatasource.initialIndex) * cellWidth if loops { contentOffset = CGPoint(x: -contentInset.left + cellWidth * CGFloat(numberOfLoops/2 * totalNumberOfItems) + initialOffset, y: 0) } else { contentOffset = CGPoint(x: -contentInset.left + initialOffset, y: 0) } } } extension CustomCollectionView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return totalNumberOfItems * (loops ? numberOfLoops : 1) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var normalizedIndexPath = indexPath if loops { normalizedIndexPath = IndexPath(row: indexPath.row % totalNumberOfItems, section: 0) } return customDatasource!.cell(at: normalizedIndexPath.row, for: self) } } extension CustomCollectionView: UICollectionViewDelegate { func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let layout = collectionViewLayout as! UICollectionViewFlowLayout let cellWidth = layout.itemSize.width + layout.minimumInteritemSpacing let page: CGFloat let snapDelta: CGFloat = 0.7 let proposedPage = (targetContentOffset.pointee.x + contentInset.left - layout.minimumInteritemSpacing) / cellWidth if floor(proposedPage + snapDelta) == floor(proposedPage) && scrollView.contentOffset.x <= targetContentOffset.pointee.x { page = floor(proposedPage) } else { page = floor(proposedPage + 1) } targetContentOffset.pointee = CGPoint( x: cellWidth * page - contentInset.left, y: targetContentOffset.pointee.y ) } func scrollViewDidScroll(_ scrollView: UIScrollView) { let layout = collectionViewLayout as! UICollectionViewFlowLayout let cellWidth = layout.itemSize.width + layout.minimumInteritemSpacing var page = Int(round((scrollView.contentOffset.x + contentInset.left - layout.minimumInteritemSpacing) / cellWidth)) if loops { page = page % totalNumberOfItems } page = min(max(0, page), totalNumberOfItems - 1) customDelegate?.itemSelected(for: self, at: page) } }
b96d76a35163df416680ac745e1b2368
32.839695
146
0.664336
false
false
false
false
raykle/CustomTransition
refs/heads/master
CircleTransition/ViewControllerTransition/CircleTransitionAnimator.swift
mit
1
// // CircleTransitionAnimator.swift // CircleTransition // // Created by guomin on 16/3/9. // Copyright © 2016年 iBinaryOrg. All rights reserved. // import UIKit class CircleTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning { weak var transitionContext: UIViewControllerContextTransitioning? func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext let containerView = transitionContext.containerView() let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ViewController let button = fromViewController.button containerView?.addSubview(toViewController.view) let circleMaskPathInitial = UIBezierPath(ovalInRect: button.frame) let extremePoint = CGPoint(x: button.center.x - 0, y: button.center.y - CGRectGetHeight(toViewController.view.bounds)) let radius = sqrt((extremePoint.x * extremePoint.x) + (extremePoint.y * extremePoint.y)) let circleMaskPathFinal = UIBezierPath(ovalInRect: CGRectInset(button.frame, -radius, -radius)) let maskLayer = CAShapeLayer() maskLayer.path = circleMaskPathFinal.CGPath toViewController.view.layer.mask = maskLayer let maskLayerAnimation = CABasicAnimation(keyPath: "path") maskLayerAnimation.fromValue = circleMaskPathInitial.CGPath maskLayerAnimation.toValue = circleMaskPathFinal.CGPath maskLayerAnimation.duration = self.transitionDuration(transitionContext) maskLayerAnimation.delegate = self maskLayer.addAnimation(maskLayerAnimation, forKey: "path") } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { self.transitionContext?.completeTransition(!self.transitionContext!.transitionWasCancelled()) self.transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view.layer.mask = nil } }
dff59f852b731a8b90c225bcbf9b6165
45.66
132
0.74282
false
false
false
false
FirasAKAK/FInAppNotifications
refs/heads/master
FNotificationVoicePlayerExtensionView.swift
mit
1
// // FNotificationVoicePlayerExtensionView.swift // FInAppNotification // // Created by Firas Al Khatib Al Khalidi on 7/5/17. // Copyright © 2017 Firas Al Khatib Al Khalidi. All rights reserved. // import UIKit import AVFoundation class FNotificationVoicePlayerExtensionView: FNotificationExtensionView { var audioPlayer : AVPlayer! var timeObserver : Any? var didPlayRecording : (()-> Void)? override var height : CGFloat{ return 100 } var dataUrl: String!{ didSet{ guard dataUrl != nil else { return } audioPlayer = AVPlayer(playerItem: AVPlayerItem(asset: AVAsset(url: URL(fileURLWithPath: dataUrl)))) NotificationCenter.default.addObserver(self, selector: #selector(itemDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: audioPlayer.currentItem!) timeSlider.minimumValue = 0 timeSlider.maximumValue = Float(audioPlayer.currentItem!.asset.duration.seconds) timeSlider.value = Float(audioPlayer.currentTime().seconds) timeSlider.isEnabled = true playPauseButton.isEnabled = true addTimeObserver() timeLabel.text = initialTimeString let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped)) addGestureRecognizer(tapGestureRecognizer) tapGestureRecognizer.delegate = self } } func viewTapped(){ } deinit { NotificationCenter.default.removeObserver(self) } @IBOutlet weak var timeSlider : UISlider! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var timeLabel: UILabel! var didFinishPlaying = false @objc private func itemDidFinishPlaying(){ timeSlider.setValue(0, animated: true) playPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal) audioPlayer.currentItem?.seek(to: CMTime(seconds: 0, preferredTimescale: 1), completionHandler: { (completed) in self.didFinishPlaying = true self.timeLabel.text = self.initialTimeString }) } private var initialTimeString: String{ let time = Int(audioPlayer.currentItem!.asset.duration.seconds) let minutes = time/60 let seconds = time-(minutes*60) var timeString = "" if minutes < 10{ timeString = "0\(minutes)" } else{ timeString = "\(minutes)" } if seconds < 10{ timeString = timeString + ":0\(seconds)" } else{ timeString = timeString + ":\(seconds)" } return timeString } private var currentTimeString: String{ let time = Int(audioPlayer.currentItem!.currentTime().seconds) let minutes = time/60 let seconds = time-(minutes*60) var timeString = "" if minutes < 10{ timeString = "0\(minutes)" } else{ timeString = "\(minutes)" } if seconds < 10{ timeString = timeString + ":0\(seconds)" } else{ timeString = timeString + ":\(seconds)" } if audioPlayer.rate == 0 && seconds == 0{ return initialTimeString } return timeString } override func awakeFromNib() { super.awakeFromNib() addPlayPauseButtonBorder() } private func addPlayPauseButtonBorder(){ playPauseButton.layer.cornerRadius = 5 playPauseButton.layer.masksToBounds = true playPauseButton.layer.borderColor = UIColor.white.cgColor playPauseButton.layer.borderWidth = 1 } private func addTimeObserver(){ timeObserver = audioPlayer.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 1), queue: DispatchQueue.main) { (time) in if !self.timeSlider.isHighlighted{ DispatchQueue.main.async { guard self.audioPlayer != nil else{ return } self.timeSlider.value = Float(self.audioPlayer.currentTime().seconds) self.timeLabel.text = self.currentTimeString } } } } @IBAction func timeSliderValueChanged(_ sender: UISlider) { guard audioPlayer != nil else{ return } var wasPlaying = false if audioPlayer.rate != 0{ audioPlayer.pause() wasPlaying = true } if timeObserver != nil{ audioPlayer.removeTimeObserver(timeObserver!) } audioPlayer.currentItem?.seek(to: CMTime(seconds: Double(sender.value)+0.5, preferredTimescale: 1), completionHandler: { (Bool) in guard self.audioPlayer != nil else{ return } self.addTimeObserver() self.timeLabel.text = self.currentTimeString if wasPlaying{ self.audioPlayer.play() self.playPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal) } }) } @IBAction func playPauseButtonPressed(_ sender: UIButton) { didPlayRecording?() didPlayRecording = nil if audioPlayer.rate != 0{ audioPlayer.pause() playPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal) } else{ audioPlayer.play() playPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal) } } } extension FNotificationVoicePlayerExtensionView: UIGestureRecognizerDelegate{ func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } }
a3e0d4b5706c8020a01becc518d4ca64
36
189
0.602436
false
false
false
false
jiamao130/DouYuSwift
refs/heads/master
DouYuBroad/DouYuBroad/Main/CustomNavigationController.swift
mit
1
// // CustomNavigationController.swift // DouYuBroad // // Created by 贾卯 on 2017/8/14. // Copyright © 2017年 贾卯. All rights reserved. // import UIKit class CustomNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() guard let systemGes = interactivePopGestureRecognizer else {return} guard let gesView = systemGes.view else {return} /* var count: UInt32 = 0 let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)! for i in 0..<count{ let ivar = ivars[Int(i)] let name = ivar_getName(ivar) print(String(cString:name!)) } let targets = systemGes.value(forKey: "_targets") as? [NSObject] guard let targeObjc = targets?.first else {return} guard let target = targeObjc.value(forKey: "target") else { return } let action = Selector(("handleNavigationTransition:")) let panGesure = UIPanGestureRecognizer() gesView.addGestureRecognizer(panGesure) panGesure.addTarget(target as Any, action: action) */ let targets = systemGes.value(forKey: "_targets") as? [NSObject] guard let targetObjc = targets?.first else { return } print(targetObjc) // 3.2.取出target guard let target = targetObjc.value(forKey: "target") else { return } // 3.3.取出Action let action = Selector(("handleNavigationTransition:")) // 4.创建自己的Pan手势 let panGes = UIPanGestureRecognizer() gesView.addGestureRecognizer(panGes) panGes.addTarget(target, action: action) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { viewController.hidesBottomBarWhenPushed = true super.pushViewController(viewController, animated: animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
9ed6f641bd7a3e1fea4764dcccf0c6ec
31.292308
90
0.626965
false
false
false
false
TrustWallet/trust-wallet-ios
refs/heads/master
Trust/Browser/Types/DappCommand.swift
gpl-3.0
1
// Copyright DApps Platform Inc. All rights reserved. import Foundation struct DappCommand: Decodable { let name: Method let id: Int let object: [String: DappCommandObjectValue] } struct DappCallback { let id: Int let value: DappCallbackValue } enum DappCallbackValue { case signTransaction(Data) case sentTransaction(Data) case signMessage(Data) case signPersonalMessage(Data) case signTypedMessage(Data) var object: String { switch self { case .signTransaction(let data): return data.hexEncoded case .sentTransaction(let data): return data.hexEncoded case .signMessage(let data): return data.hexEncoded case .signPersonalMessage(let data): return data.hexEncoded case .signTypedMessage(let data): return data.hexEncoded } } } struct DappCommandObjectValue: Decodable { public var value: String = "" public var array: [EthTypedData] = [] public init(from coder: Decoder) throws { let container = try coder.singleValueContainer() if let intValue = try? container.decode(Int.self) { self.value = String(intValue) } else if let stringValue = try? container.decode(String.self) { self.value = stringValue } else { var arrayContainer = try coder.unkeyedContainer() while !arrayContainer.isAtEnd { self.array.append(try arrayContainer.decode(EthTypedData.self)) } } } }
d391008ec20f50ce2a3cdb768bfdf90f
27.490909
79
0.634971
false
false
false
false
ghysrc/EasyMap
refs/heads/master
EasyMap/BMapManager.swift
mit
1
// // Created by ghysrc on 2016/12/30. // Copyright © 2016年 ghysrc. All rights reserved. // typealias BMapLocateSuccessHandler = ((CLLocation) -> Void) typealias BMapLocateFailHandler = ((Error) -> Void) typealias BMapReGeocoderSuccessHandler = ((BMKReverseGeoCodeResult) -> Void) typealias BMapGeocoderSuccessHandler = ((BMKGeoCodeResult) -> Void) typealias BMapSearchFailHandler = ((BMKSearchErrorCode) -> Void) typealias BMapPoiSearchSuccessHandler = ((BMKPoiResult) -> Void) typealias BMapSuggestionSearchSuccessHandler = ((BMKSuggestionResult) -> Void) let BMap:BMapManager = BMapManager.instance class BMapManager: NSObject, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate, BMKPoiSearchDelegate, BMKSuggestionSearchDelegate { static let instance = BMapManager() private let locationService: BMKLocationService private lazy var searchService = BMKGeoCodeSearch() private lazy var poiSearch = BMKPoiSearch() private lazy var suggestionSearch = BMKSuggestionSearch() private var locateSuccess: BMapLocateSuccessHandler? private var locateFail: BMapLocateFailHandler? private var regeocoderSuccess: BMapReGeocoderSuccessHandler? private var geoCoderSuccess: BMapGeocoderSuccessHandler? private var poiSearchSuccess: BMapPoiSearchSuccessHandler? private var suggestionSearchSuccess: BMapSuggestionSearchSuccessHandler? private var searchFail: BMapSearchFailHandler? override init() { self.locationService = BMKLocationService() super.init() self.locationService.delegate = self } func requestAuthorization(whenInUse:Bool = true) { if !CLLocationManager.locationServicesEnabled() || CLLocationManager.authorizationStatus() == .denied { print("Location Service disabled or authorization denied.") return } let clManager = CLLocationManager() if whenInUse { clManager.requestWhenInUseAuthorization() } else { clManager.requestAlwaysAuthorization() } } /** * Start continuouts locating * Default desiredAccuracy is kCLLocationAccuracyHundredMeters * Default distanceFilter is 200 meters */ func getLocation(withAccuracy: CLLocationAccuracy = kCLLocationAccuracyHundredMeters, distanceFilter: CLLocationDistance = 200, onSuccess: @escaping BMapLocateSuccessHandler, onFail: @escaping BMapLocateFailHandler) { requestAuthorization() locateSuccess = onSuccess locateFail = onFail locationService.desiredAccuracy = withAccuracy locationService.distanceFilter = distanceFilter locationService.startUserLocationService() } func didUpdate(_ userLocation: BMKUserLocation!) { locateSuccess?(userLocation.location) } func didFailToLocateUserWithError(_ error: Error!) { locateFail?(error) } /// coordinate to address func reverseGeocoder(coordinate:CLLocationCoordinate2D, onSuccess:@escaping BMapReGeocoderSuccessHandler, onFail: @escaping BMapSearchFailHandler) { regeocoderSuccess = onSuccess searchFail = onFail searchService.delegate = self let regeo = BMKReverseGeoCodeOption() regeo.reverseGeoPoint = coordinate searchService.reverseGeoCode(regeo) } func onGetReverseGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) { if error == BMK_SEARCH_NO_ERROR { regeocoderSuccess?(result) } else { searchFail?(error) } } /// address to coordinate, city can be empty func geocoder(address:String, city:String, onSuccess: @escaping BMapGeocoderSuccessHandler, onFail: @escaping BMapSearchFailHandler) { geoCoderSuccess = onSuccess searchFail = onFail searchService.delegate = self let geo = BMKGeoCodeSearchOption() geo.city = city geo.address = address searchService.geoCode(geo) } func onGetGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKGeoCodeResult!, errorCode error: BMKSearchErrorCode) { if error == BMK_SEARCH_NO_ERROR { geoCoderSuccess?(result) } else { searchFail?(error) } } /** * Search nearby pois * Note: The keyword can NOT be nil or empty, it's required by SDK. If you want to get all kinds of pois, consider use reverseGeocoder instead. */ func searchPoi(near location:CLLocationCoordinate2D, radius:Int32, keyword:String, pageIndex:Int32 = 1, pageCapacity:Int32 = 20, onSuccess: @escaping BMapPoiSearchSuccessHandler, onFail: @escaping BMapSearchFailHandler) { let option = BMKNearbySearchOption() option.location = location option.radius = radius option.keyword = keyword option.pageIndex = pageIndex option.pageCapacity = pageCapacity poiSearchSuccess = onSuccess searchFail = onFail poiSearch.delegate = self poiSearch.poiSearchNear(by: option) } func onGetPoiResult(_ searcher: BMKPoiSearch!, result poiResult: BMKPoiResult!, errorCode: BMKSearchErrorCode) { if errorCode == BMK_SEARCH_NO_ERROR { poiSearchSuccess?(poiResult) } else { searchFail?(errorCode) } } /// Get suggestions by keyword func searchInputTips(keyword:String, city:String?, onSuccess: @escaping BMapSuggestionSearchSuccessHandler, onFail: @escaping BMapSearchFailHandler) { let option = BMKSuggestionSearchOption() option.cityname = city option.keyword = keyword suggestionSearchSuccess = onSuccess searchFail = onFail suggestionSearch.delegate = self suggestionSearch.suggestionSearch(option) } func onGetSuggestionResult(_ searcher: BMKSuggestionSearch!, result: BMKSuggestionResult!, errorCode error: BMKSearchErrorCode) { if error == BMK_SEARCH_NO_ERROR { suggestionSearchSuccess?(result) } else { searchFail?(error) } } /// Distance between two coordinates func distanceBetween(coordinate1: CLLocationCoordinate2D, coordinate2: CLLocationCoordinate2D ) -> CLLocationDistance { let point1 = BMKMapPointForCoordinate(coordinate1) let point2 = BMKMapPointForCoordinate(coordinate2) return BMKMetersBetweenMapPoints(point1, point2) } }
72403ea764f643907ca4f489edb60246
37.988166
225
0.695098
false
false
false
false
nickqiao/NKBill
refs/heads/master
Carthage/Checkouts/PagingMenuController/Pod/Classes/MenuItemView.swift
apache-2.0
1
// // MenuItemView.swift // PagingMenuController // // Created by Yusuke Kita on 5/9/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit public class MenuItemView: UIView { lazy public var titleLabel: UILabel = { let label = UILabel(frame: .zero) label.numberOfLines = 1 label.textAlignment = .Center label.userInteractionEnabled = true label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy public var menuImageView: UIImageView = { let imageView = UIImageView(frame: .zero) imageView.userInteractionEnabled = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() public internal(set) var selected: Bool = false { didSet { if case .RoundRect = options.menuItemMode { backgroundColor = UIColor.clearColor() } else { backgroundColor = selected ? options.selectedBackgroundColor : options.backgroundColor } switch options.menuItemViewContent { case .Text: titleLabel.textColor = selected ? options.selectedTextColor : options.textColor titleLabel.font = selected ? options.selectedFont : options.font // adjust label width if needed let labelSize = calculateLabelSize() widthConstraint.constant = labelSize.width case .Image: break } } } lazy public private(set) var dividerImageView: UIImageView? = { let imageView = UIImageView(image: self.options.menuItemDividerImage) imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private var options: PagingMenuOptions! private var widthConstraint: NSLayoutConstraint! private var labelSize: CGSize { guard let text = titleLabel.text else { return .zero } return NSString(string: text).boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: titleLabel.font], context: nil).size } private let labelWidth: (CGSize, PagingMenuOptions.MenuItemWidthMode) -> CGFloat = { size, widthMode in switch widthMode { case .Flexible: return ceil(size.width) case .Fixed(let width): return width } } private var horizontalMargin: CGFloat { switch options.menuDisplayMode { case .SegmentedControl: return 0.0 default: return options.menuItemMargin } } // MARK: - Lifecycle internal init(title: String, options: PagingMenuOptions, addDivider: Bool) { super.init(frame: .zero) self.options = options commonInit(addDivider) { self.setupLabel(title) self.layoutLabel() } } internal init(image: UIImage, options: PagingMenuOptions, addDivider: Bool) { super.init(frame: .zero) self.options = options commonInit(addDivider) { self.setupImageView(image) self.layoutImageView() } } private func commonInit(addDivider: Bool, setup: () -> Void) { setupView() setup() if let _ = options.menuItemDividerImage where addDivider { setupDivider() layoutDivider() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } // MARK: - Cleanup internal func cleanup() { switch options.menuItemViewContent { case .Text: titleLabel.removeFromSuperview() case .Image: menuImageView.removeFromSuperview() } dividerImageView?.removeFromSuperview() } // MARK: - Constraints manager internal func updateConstraints(size: CGSize) { // set width manually to support ratotaion switch (options.menuDisplayMode, options.menuItemViewContent) { case (.SegmentedControl, .Text): let labelSize = calculateLabelSize(size) widthConstraint.constant = labelSize.width case (.SegmentedControl, .Image): widthConstraint.constant = size.width / CGFloat(options.menuItemCount) default: break } } // MARK: - Constructor private func setupView() { if case .RoundRect = options.menuItemMode { backgroundColor = UIColor.clearColor() } else { backgroundColor = options.backgroundColor } translatesAutoresizingMaskIntoConstraints = false } private func setupLabel(title: String) { titleLabel.text = title titleLabel.textColor = options.textColor titleLabel.font = options.font addSubview(titleLabel) } private func setupImageView(image: UIImage) { menuImageView.image = image addSubview(menuImageView) } private func setupDivider() { guard let dividerImageView = dividerImageView else { return } addSubview(dividerImageView) } private func layoutLabel() { let viewsDictionary = ["label": titleLabel] let labelSize = calculateLabelSize() let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|", options: [], metrics: nil, views: viewsDictionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) widthConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: labelSize.width) widthConstraint.active = true } private func layoutImageView() { guard let image = menuImageView.image else { return } let width: CGFloat switch options.menuDisplayMode { case .SegmentedControl: width = UIApplication.sharedApplication().keyWindow!.bounds.size.width / CGFloat(options.menuItemCount) default: width = image.size.width + horizontalMargin * 2 } widthConstraint = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: width) NSLayoutConstraint.activateConstraints([ NSLayoutConstraint(item: menuImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: menuImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: menuImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: image.size.width), NSLayoutConstraint(item: menuImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: image.size.height), widthConstraint ]) } private func layoutDivider() { guard let dividerImageView = dividerImageView else { return } let centerYConstraint = NSLayoutConstraint(item: dividerImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 1.0) let rightConstraint = NSLayoutConstraint(item: dividerImageView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: 0.0) NSLayoutConstraint.activateConstraints([centerYConstraint, rightConstraint]) } // MARK: - Size calculator private func calculateLabelSize(size: CGSize = UIApplication.sharedApplication().keyWindow!.bounds.size) -> CGSize { guard let _ = titleLabel.text else { return .zero } let itemWidth: CGFloat switch options.menuDisplayMode { case let .Standard(widthMode, _, _): itemWidth = labelWidth(labelSize, widthMode) case .SegmentedControl: itemWidth = size.width / CGFloat(options.menuItemCount) case let .Infinite(widthMode, _): itemWidth = labelWidth(labelSize, widthMode) } let itemHeight = floor(labelSize.height) return CGSizeMake(itemWidth + horizontalMargin * 2, itemHeight) } }
dfe240d2baf88b44c1f980097b201104
37.421053
201
0.639612
false
false
false
false
brokenhandsio/vapor-oauth
refs/heads/master
Sources/VaporOAuth/Models/OAuthClient.swift
mit
1
import Core public final class OAuthClient: Extendable { public let clientID: String public let redirectURIs: [String]? public let clientSecret: String? public let validScopes: [String]? public let confidentialClient: Bool? public let firstParty: Bool public let allowedGrantType: OAuthFlowType public var extend: [String: Any] = [:] public init(clientID: String, redirectURIs: [String]?, clientSecret: String? = nil, validScopes: [String]? = nil, confidential: Bool? = nil, firstParty: Bool = false, allowedGrantType: OAuthFlowType) { self.clientID = clientID self.redirectURIs = redirectURIs self.clientSecret = clientSecret self.validScopes = validScopes self.confidentialClient = confidential self.firstParty = firstParty self.allowedGrantType = allowedGrantType } func validateRedirectURI(_ redirectURI: String) -> Bool { guard let redirectURIs = redirectURIs else { return false } if redirectURIs.contains(redirectURI) { return true } return false } }
945e21867a1ffe5a2787ff36f2267a66
29.263158
117
0.658261
false
false
false
false
luanlzsn/pos
refs/heads/master
pos/Classes/Ant/AntSingleton.swift
mit
1
// // LeomanSingleton.swift // MoFan // // Created by luan on 2017/1/4. // Copyright © 2017年 luan. All rights reserved. // import UIKit import AFNetworking import MBProgressHUD let kRequestTimeOut = 20.0 let AntManage = AntSingleton.sharedInstance class AntSingleton: NSObject { static let sharedInstance = AntSingleton() var manager = AFHTTPSessionManager() var requestBaseUrl = (UIDevice.current.userInterfaceIdiom == .pad) ? "http://pos.auroraeducationonline.info/api/" : "http://posonline.auroraeducationonline.info/index.php?" var progress : MBProgressHUD? var progressCount = 0//转圈数量 var isLogin = false//是否登录 var userModel: UserModel? var iphoneToken = "" private override init () { if UIDevice.current.userInterfaceIdiom == .phone { manager.requestSerializer = AFJSONRequestSerializer() manager.requestSerializer.httpMethodsEncodingParametersInURI = Set.init(arrayLiteral: "GET", "HEAD") } manager.responseSerializer.acceptableContentTypes = Set(arrayLiteral: "application/json","text/json","text/javascript","text/html") manager.requestSerializer.timeoutInterval = kRequestTimeOut } //MARK: - post请求 func postRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) { AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))") showMessage(message: "") weak var weakSelf = self manager.post(requestBaseUrl + path, parameters: params, progress: nil, success: { (task, response) in weakSelf?.requestSuccess(response: response, successResult: successResult, failureResult: failureResult) }) { (task, error) in weakSelf?.hideMessage() weakSelf?.showDelayToast(message: "未知错误,请重试!") failureResult() } } //MARK: - get请求 func getRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) { AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))") showMessage(message: "") weak var weakSelf = self manager.get(requestBaseUrl + path, parameters: params, progress: nil, success: { (task, response) in weakSelf?.requestSuccess(response: response, successResult: successResult, failureResult: failureResult) }) { (task, error) in weakSelf?.hideMessage() weakSelf?.showDelayToast(message: "未知错误,请重试!") failureResult() } } //MARK: - 请求成功回调 func requestSuccess(response: Any?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) { AntLog(message: "接口返回数据:\(String(describing: response))") hideMessage() if let data = response as? [String : Any] { if let status = data["status"] { if status as! String == "success" { if let success = data["data"] as? [String : Any] { successResult(success) } else { successResult(data) } } else { if let error = data["data"] as? [String : Any] { if let message = error["message"] as? String { showDelayToast(message: message) } } else if let message = data["message"] as? String { showDelayToast(message: message) } failureResult() } } else { failureResult() } } else { failureResult() } } //MARK: - iphone post请求 func iphonePostRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) { AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))") if path != "route=feed/rest_api/gettoken&grant_type=client_credentials" { showMessage(message: "") } weak var weakSelf = self if iphoneToken.isEmpty { manager.requestSerializer.setValue("Basic cG9zb25saW5lOlBvTCMxMjA5", forHTTPHeaderField: "Authorization") } else { manager.requestSerializer.setValue("BEARER \(iphoneToken)", forHTTPHeaderField: "Authorization") } manager.requestSerializer.setValue((LanguageManager.currentLanguageString() == "en") ? "en" : "zh", forHTTPHeaderField: "Accept-Language") manager.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") manager.requestSerializer.httpShouldHandleCookies = false manager.post(requestBaseUrl + path, parameters: params, progress: nil, success: { (task, response) in weakSelf?.iphoneRequestSuccess(response: response, successResult: successResult, failureResult: failureResult) }) { (task, error) in if path != "route=feed/rest_api/gettoken&grant_type=client_credentials" { weakSelf?.iphoneRequestFail(error: error, failureResult: failureResult) } } } //MARK: - iphone get请求 func iphoneGetRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) { AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))") showMessage(message: "") weak var weakSelf = self if iphoneToken.isEmpty { manager.requestSerializer.setValue("Basic cG9zb25saW5lOlBvTCMxMjA5", forHTTPHeaderField: "Authorization") } else { manager.requestSerializer.setValue("BEARER \(iphoneToken)", forHTTPHeaderField: "Authorization") } manager.requestSerializer.setValue((LanguageManager.currentLanguageString() == "en") ? "en" : "zh", forHTTPHeaderField: "Accept-Language") manager.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") manager.requestSerializer.httpShouldHandleCookies = false manager.get(requestBaseUrl + path, parameters: params, progress: nil, success: { (task, response) in weakSelf?.iphoneRequestSuccess(response: response, successResult: successResult, failureResult: failureResult) }) { (task, error) in weakSelf?.iphoneRequestFail(error: error, failureResult: failureResult) } } //MARK: - iphone get请求 func iphoneDeleteRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) { AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))") showMessage(message: "") weak var weakSelf = self if iphoneToken.isEmpty { manager.requestSerializer.setValue("Basic cG9zb25saW5lOlBvTCMxMjA5", forHTTPHeaderField: "Authorization") } else { manager.requestSerializer.setValue("BEARER \(iphoneToken)", forHTTPHeaderField: "Authorization") } manager.requestSerializer.setValue((LanguageManager.currentLanguageString() == "en") ? "en" : "zh", forHTTPHeaderField: "Accept-Language") manager.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") manager.requestSerializer.httpShouldHandleCookies = false manager.delete(requestBaseUrl + path, parameters: params, success: { (task, response) in weakSelf?.iphoneRequestSuccess(response: response, successResult: successResult, failureResult: failureResult) }) { (task, error) in weakSelf?.iphoneRequestFail(error: error, failureResult: failureResult) } } //MARK: - 请求成功回调 func iphoneRequestSuccess(response: Any?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) { AntLog(message: "接口返回数据:\(String(describing: response))") hideMessage() if let data = response as? [String : Any] { if let success = data["success"] as? Bool { if success { successResult(data) } else { failureResult() if let error = data["error"] as? [String : Any] { for value in error.values { if let message = value as? String { showDelayToast(message: message) } } } else if let error = data["error"] as? String { showDelayToast(message: error) } } } else { successResult(data) } } else { failureResult() } } // MARK: - iPhone请求错误回调 func iphoneRequestFail(error: Error, failureResult:@escaping () -> Void) { hideMessage() failureResult() if let responseData = (error as NSError).userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? Data { if let responseDict = try! JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String : Any] { if let errorArray = responseDict["error"] as? [String] { if let errorStr = errorArray.first { showDelayToast(message: errorStr) return } } } } AntManage.showDelayToast(message: NSLocalizedString("未知错误,请重试!", comment: "")) } // MARK: - 显示提示 func showMessage(message : String) { if progress == nil { progressCount = 0 progress = MBProgressHUD.showAdded(to: kWindow!, animated: true) progress?.label.text = message } progressCount += 1 } // MARK: - 隐藏提示 func hideMessage() { progressCount -= 1 if progressCount < 0 { progressCount = 0 } if (progress != nil) && progressCount == 0 { progress?.hide(animated: true) progress?.removeFromSuperview() progress = nil } } // MARK: - 显示固定时间的提示 func showDelayToast(message : String) { let hud = MBProgressHUD.showAdded(to: kWindow!, animated: true) hud.detailsLabel.text = message hud.mode = .text hud.hide(animated: true, afterDelay: 2) } // MARK: - 校验默认请求地址 func checkBaseRequestAddress(isStartUp: Bool) { let baseRequestAddress = UserDefaults.standard.object(forKey: "BaseRequestAddress") AntLog(message: baseRequestAddress) let beforeUrl = requestBaseUrl if let address = baseRequestAddress as? String { if Common.isValidateURL(urlStr: address) { if address.hasSuffix("/") { requestBaseUrl = address + "api/" } else { requestBaseUrl = address + "/api/" } } } if beforeUrl != requestBaseUrl, !isStartUp { NotificationCenter.default.post(name: NSNotification.Name("RequestAddressUpdate"), object: nil) } } }
7d322b7d8a86aa6182b118f40f950182
43.34749
176
0.59394
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/MediaStoreData/MediaStoreData_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for MediaStoreData public struct MediaStoreDataErrorType: AWSErrorType { enum Code: String { case containerNotFoundException = "ContainerNotFoundException" case internalServerError = "InternalServerError" case objectNotFoundException = "ObjectNotFoundException" case requestedRangeNotSatisfiableException = "RequestedRangeNotSatisfiableException" } private let error: Code public let context: AWSErrorContext? /// initialize MediaStoreData public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The specified container was not found for the specified account. public static var containerNotFoundException: Self { .init(.containerNotFoundException) } /// The service is temporarily unavailable. public static var internalServerError: Self { .init(.internalServerError) } /// Could not perform an operation on an object that does not exist. public static var objectNotFoundException: Self { .init(.objectNotFoundException) } /// The requested content range is not valid. public static var requestedRangeNotSatisfiableException: Self { .init(.requestedRangeNotSatisfiableException) } } extension MediaStoreDataErrorType: Equatable { public static func == (lhs: MediaStoreDataErrorType, rhs: MediaStoreDataErrorType) -> Bool { lhs.error == rhs.error } } extension MediaStoreDataErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
aeb94a7edf7196c560d4da2bf73ac0c5
36.727273
117
0.675502
false
false
false
false
D8Ge/Jchat
refs/heads/master
Jchat/Pods/SwiftProtobuf/Sources/SwiftProtobuf/ProtobufRawMessage.swift
mit
1
// ProtobufRuntime/Sources/Protobuf/ProtobufRawMessage.swift - Raw message decoding // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// A "RawMessage" is a tool for parsing proto binary messages without /// using a schema of any sort. This is slow, inconvenient, and unsafe. /// Despite these drawbacks, it is occasionally quite useful... /// // ----------------------------------------------------------------------------- import Swift // TODO: This is a tentative sketch; needs tests and plenty of more stuff filled in. public struct ProtobufRawMessage { public private(set) var fieldWireType = [Int: Int]() public private(set) var fieldData = [Int: Any]() public init(protobuf: [UInt8]) throws { try protobuf.withUnsafeBufferPointer { (bp) throws in var protobufDecoder = ProtobufBinaryDecoder(protobufPointer: bp) while let tagType = try protobufDecoder.getTagType() { let protoFieldNumber = tagType / 8 let wireType = tagType % 8 fieldWireType[protoFieldNumber] = wireType switch wireType { case 0: if let v = try protobufDecoder.decodeUInt64() { fieldData[protoFieldNumber] = v } else { throw ProtobufDecodingError.malformedProtobuf } case 1: if let v = try protobufDecoder.decodeFixed64() { fieldData[protoFieldNumber] = v } else { throw ProtobufDecodingError.malformedProtobuf } case 2: if let v = try protobufDecoder.decodeBytes() { fieldData[protoFieldNumber] = v } else { throw ProtobufDecodingError.malformedProtobuf } case 3: // TODO: Find a useful way to deal with groups try protobufDecoder.skip() case 5: if let v = try protobufDecoder.decodeFixed32() { fieldData[protoFieldNumber] = v } else { throw ProtobufDecodingError.malformedProtobuf } default: throw ProtobufDecodingError.malformedProtobuf } } } } // TODO: serializeProtobuf(), serializeProtobufBytes() /// Get the contents of this field as a UInt64 /// Returns nil if the field doesn't exist or it's contents cannot be expressed as a UInt64 public func getUInt64(protoFieldNumber: Int) -> UInt64? { return fieldData[protoFieldNumber] as? UInt64 } public func getString(protoFieldNumber: Int) -> String? { if let bytes = fieldData[protoFieldNumber] as? [UInt8] { return bytes.withUnsafeBufferPointer {(buffer) -> String? in buffer.baseAddress?.withMemoryRebound(to: CChar.self, capacity: buffer.count) { (cp) -> String? in // cp is not null-terminated! var chars = [CChar](UnsafeBufferPointer<CChar>(start: cp, count: buffer.count)) chars.append(0) return String(validatingUTF8: chars) } } } else { return nil } } // TODO: More getters... // TODO: Setters... }
3fd9f0cb0150b7e315118b4ad08eedfc
39.936842
114
0.541013
false
false
false
false
uShip/iOSIdeaFlow
refs/heads/master
IdeaFlow/ChartViewController.swift
gpl-3.0
1
// // ChartViewController.swift // IdeaFlow // // Created by Matt Hayes on 8/14/15. // Copyright (c) 2015 uShip. All rights reserved. // import UIKit class ChartViewController: UIViewController { @IBOutlet weak var previousDate: UIButton! @IBOutlet weak var currentDate: UILabel! @IBOutlet weak var nextDate: UIButton! override func viewDidLoad() { super.viewDidLoad() refreshDateLabel() let longPresser = UILongPressGestureRecognizer(target: self, action: Selector("onLongPress:")) self.view.addGestureRecognizer(longPresser) let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("onLeftSwipe:")) leftSwipe.direction = .Left self.view.addGestureRecognizer(leftSwipe) let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("onRightSwipe:")) rightSwipe.direction = .Right self.view.addGestureRecognizer(rightSwipe) } func onLeftSwipe(gestureRecognizer: UISwipeGestureRecognizer) { goToNextDay(gestureRecognizer) } func onRightSwipe(gestureRecognizer: UISwipeGestureRecognizer) { goToPreviousDay(gestureRecognizer) } func onLongPress(gestureRecognizer: UILongPressGestureRecognizer) { print("\(__FUNCTION__)") } @IBAction func goToNextDay(sender: AnyObject) { IdeaFlowEvent.setSelectedDayWithOffset(1) refreshDateLabel() } @IBAction func goToPreviousDay(sender: AnyObject) { IdeaFlowEvent.setSelectedDayWithOffset(-1) refreshDateLabel() } func refreshDateLabel() { let selectedDate = IdeaFlowEvent.getSelectedDate() let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .ShortStyle dateFormatter.timeStyle = .NoStyle currentDate.text = dateFormatter.stringFromDate(selectedDate) } }
09ed8540c39bb38cb1448554874cc4d3
26.638889
102
0.664656
false
false
false
false
onevcat/CotEditor
refs/heads/develop
CotEditor/Sources/FilePermissions.swift
apache-2.0
1
// // FilePermissions.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-02-16. // // --------------------------------------------------------------------------- // // © 2018 1024jp // // 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 // // https://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. // struct FilePermissions { var user: Permission var group: Permission var others: Permission struct Permission: OptionSet { let rawValue: UInt16 static let read = Permission(rawValue: 0b100) static let write = Permission(rawValue: 0b010) static let execute = Permission(rawValue: 0b001) var humanReadable: String { return (self.contains(.read) ? "r" : "-") + (self.contains(.write) ? "w" : "-") + (self.contains(.execute) ? "x" : "-") } } init(mask: UInt16) { self.user = Permission(rawValue: (mask & 0b111 << 6) >> 6) self.group = Permission(rawValue: (mask & 0b111 << 3) >> 3) self.others = Permission(rawValue: (mask & 0b111)) } var mask: UInt16 { let userMask = self.user.rawValue << 6 let groupMask = self.group.rawValue << 3 let othersMask = self.others.rawValue return userMask + groupMask + othersMask } /// human-readable permission expression like "rwxr--r--" var humanReadable: String { return self.user.humanReadable + self.group.humanReadable + self.others.humanReadable } } extension FilePermissions: CustomStringConvertible { var description: String { return self.humanReadable } }
253767a7793899224edf1218574095f7
25.395349
93
0.571366
false
false
false
false
leo150/Pelican
refs/heads/develop
Sources/Pelican/API/Types/Game/GameHighScore.swift
mit
1
// // GameHighScore.swift // Pelican // // Created by Ido Constantine on 31/08/2017. // import Foundation import Vapor import FluentProvider /** This object represents one row of the high scores table for a game. */ final public class GameHighScore: Model { public var storage = Storage() var position: Int // Position in the high score table for the game var user: User // User who made the score entry var score: Int // The score the user set // NodeRepresentable conforming methods required public init(row: Row) throws { position = try row.get("position") user = try row.get("user") score = try row.get("score") } public func makeRow() throws -> Row { var row = Row() try row.set("position", position) try row.set("user", user) try row.set("score", score) return row } }
fa7a0924e5ada69ac34fd54a464c60cc
21.540541
71
0.672662
false
false
false
false
CCRogerWang/ReactiveWeatherExample
refs/heads/master
10-combining-operators-in-practice/final/OurPlanet/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift
apache-2.0
11
// // Take.swift // RxSwift // // Created by Krunoslav Zaher on 6/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // count version class TakeCountSink<O: ObserverType> : Sink<O>, ObserverType { typealias E = O.E typealias Parent = TakeCount<E> private let _parent: Parent private var _remaining: Int init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent _remaining = parent._count super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { switch event { case .next(let value): if _remaining > 0 { _remaining -= 1 forwardOn(.next(value)) if _remaining == 0 { forwardOn(.completed) dispose() } } case .error: forwardOn(event) dispose() case .completed: forwardOn(event) dispose() } } } class TakeCount<Element>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _count: Int init(source: Observable<Element>, count: Int) { if count < 0 { rxFatalError("count can't be negative") } _source = source _count = count } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } } // time version class TakeTimeSink<ElementType, O: ObserverType> : Sink<O> , LockOwnerType , ObserverType , SynchronizedOnType where O.E == ElementType { typealias Parent = TakeTime<ElementType> typealias E = ElementType fileprivate let _parent: Parent let _lock = NSRecursiveLock() init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next(let value): forwardOn(.next(value)) case .error: forwardOn(event) dispose() case .completed: forwardOn(event) dispose() } } func tick() { _lock.lock(); defer { _lock.unlock() } forwardOn(.completed) dispose() } func run() -> Disposable { let disposeTimer = _parent._scheduler.scheduleRelative((), dueTime: _parent._duration) { self.tick() return Disposables.create() } let disposeSubscription = _parent._source.subscribe(self) return Disposables.create(disposeTimer, disposeSubscription) } } class TakeTime<Element> : Producer<Element> { typealias TimeInterval = RxTimeInterval fileprivate let _source: Observable<Element> fileprivate let _duration: TimeInterval fileprivate let _scheduler: SchedulerType init(source: Observable<Element>, duration: TimeInterval, scheduler: SchedulerType) { _source = source _scheduler = scheduler _duration = duration } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
df982f4669201a4ea207bcd281fd8a54
25.944444
145
0.576031
false
false
false
false
DrabWeb/Keijiban
refs/heads/master
Keijiban/Keijiban/KJPostViewerViewController.swift
gpl-3.0
1
// // KJBrowserWindowPostViewerViewController.swift // Keijiban // // Created by Seth on 2016-05-27. // import Cocoa import Alamofire /// The view controller for the posts viewer view(Can show catalog, index or a thread) class KJPostViewerViewController: NSViewController { /// The collection view for this post viewer for if it is in the catalog @IBOutlet var catalogCollectionView: NSCollectionView! /// The scroll view for catalogCollectionView @IBOutlet var catalogCollectionViewScrollView: NSScrollView! /// The NSArrayController for catalogCollectionView @IBOutlet weak var catalogCollectionViewArrayController: NSArrayController! /// The array of items in catalogCollectionViewArrayController var catalogCollectionViewItems : NSMutableArray = NSMutableArray(); /// The stack view for showing the posts in the posts viewer stack view @IBOutlet var postsViewerStackView: NSStackView! /// The scroll view for postsViewerStackView @IBOutlet var postsViewerStackViewScrollView: NSScrollView! /// The current mode that this post viewer is in var currentMode : KJPostViewerMode = KJPostViewerMode.None; /// The current board this post viewer is showing something for var currentBoard : KJ4CBoard? = nil; /// The current thread we are displaying(If any) var currentThread : KJ4CThread? = nil; /// The last requests for downloading thumbnails in this view var lastThumbnailDownloadRequests : [Request] = []; /// Displays the given thread in the posts stack view. Returns the title that should be used in tabs func displayThread(thread : KJ4CThread, completionHandler: (() -> ())?) -> String { // Set the current mode, board and thread currentMode = .Thread; currentBoard = thread.board!; currentThread = thread; // Print what thread we are displaying print("KJPostViewerViewController: Displaying thread /\(currentBoard!.code)/\(currentThread!.opPost!.postNumber) - \(currentThread!.displayTitle!)"); // Remove all the current post items clearPostsViewerStackView(); // For every post in the given thread... for(_, currentThreadPost) in currentThread!.allPosts.enumerate() { // Add the current post to postsViewerStackView addPostToPostsViewerStackView(currentThreadPost, displayImage: true); } // Scroll to the top of postsViewerStackViewScrollView scrollToTopOfPostsViewerStackViewScrollView(); // Hide all the other views catalogCollectionViewScrollView.hidden = true; // Show the posts view postsViewerStackViewScrollView.hidden = false; // Return the title return "/\(currentBoard!.code)/ - \(currentThread!.displayTitle!)"; } /// Displays the catalog for the given board. Only shows the amount of pages given(Minimum 0, maximum 9). Calls the given completion handler when done(If any). Returns the title that should be used in tabs func displayCatalog(forBoard : KJ4CBoard, maxPages : Int, completionHandler: (() -> ())?) -> String { // Set the current mode, board and thread currentMode = .Catalog; currentBoard = forBoard; currentThread = nil; // Print what catalog we are displaying print("KJPostViewerViewController: Displaying \(maxPages + 1) catalog pages for /\(currentBoard!.code)/"); // Clear all the current items catalogCollectionViewArrayController.removeObjects(catalogCollectionViewArrayController.arrangedObjects as! [AnyObject]); // Make the request to get the catalog Alamofire.request(.GET, "https://a.4cdn.org/\(currentBoard!.code)/catalog.json", encoding: .JSON).responseJSON { (responseData) -> Void in /// The string of JSON that will be returned when the GET request finishes let responseJsonString : NSString = NSString(data: responseData.data!, encoding: NSUTF8StringEncoding)!; // If the the response data isnt nil... if let dataFromResponseJsonString = responseJsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { /// The JSON from the response string let responseJson = JSON(data: dataFromResponseJsonString); // For every page up till the given page limit... for currentPageIndex in 0...maxPages { // For every thread in the current page... for(_, currentThread) in responseJson[currentPageIndex]["threads"].enumerate() { /// The new OP post to add to the catalog collection view let newOpPost : KJ4COPPost = KJ4COPPost(json: currentThread.1, board: self.currentBoard!); // Load the thumbnail image self.lastThumbnailDownloadRequests.append(Alamofire.request(.GET, newOpPost.fileThumbnailUrl).response { (request, response, data, error) in // If data isnt nil... if(data != nil) { /// The downloaded image let image : NSImage? = NSImage(data: data!); // If image isnt nil... if(image != nil) { // If there are any items in catalogCollectionViewArrayController... if((self.catalogCollectionViewArrayController.arrangedObjects as! [AnyObject]).count > 0) { // For ever item in the catalog collection view... for currentIndex in 0...(self.catalogCollectionViewArrayController.arrangedObjects as! [AnyObject]).count - 1 { // If the current item's represented object is equal to the item we downloaded the thumbnail for... if(((self.catalogCollectionView.itemAtIndex(currentIndex)! as! KJPostViewerCatalogCollectionViewItem).representedObject as! KJ4COPPost) == newOpPost) { // Update the image view of the item self.catalogCollectionView.itemAtIndex(currentIndex)!.imageView?.image = image!; // Set the item's model's thumbnail image ((self.catalogCollectionView.itemAtIndex(currentIndex)! as! KJPostViewerCatalogCollectionViewItem).representedObject as! KJ4COPPost).thumbnailImage = image!; } } } } } }); // Add the OP post to the catalog collection view self.catalogCollectionViewArrayController.addObject(newOpPost); } } // Call the completion handler completionHandler?(); } } // Hide all the other views postsViewerStackViewScrollView.hidden = true; // Show the catalog collection view catalogCollectionViewScrollView.hidden = false; // Return the title return "/\(currentBoard!.code)/ - Catalog"; } /// Displays the index for the given board. Only shows the amount of pages given(Minimum 0, maximum 9). Calls the given completion handler when done(If any). Returns the title that should be used in tabs func displayIndex(forBoard : KJ4CBoard, maxPages : Int, completionHandler: (() -> ())?) -> String { // Set the current mode, board and thread currentMode = .Index; currentBoard = forBoard; currentThread = nil; // Print what catalog we are displayinga print("KJPostViewerViewController: Displaying \(maxPages + 1) index pages for /\(currentBoard!.code)/"); // Clear all the current items clearPostsViewerStackView(); // Make the request to get the catalog Alamofire.request(.GET, "https://a.4cdn.org/\(currentBoard!.code)/catalog.json", encoding: .JSON).responseJSON { (responseData) -> Void in /// The string of JSON that will be returned when the GET request finishes let responseJsonString : NSString = NSString(data: responseData.data!, encoding: NSUTF8StringEncoding)!; // If the the response data isnt nil... if let dataFromResponseJsonString = responseJsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { /// The JSON from the response string let responseJson = JSON(data: dataFromResponseJsonString); // For every page up till the given page limit... for currentPageIndex in 0...maxPages { // For every thread in the current page... for(_, currentThread) in responseJson[currentPageIndex]["threads"].enumerate() { /// The new OP post to add to the catalog collection view let newOpPost : KJ4COPPost = KJ4COPPost(json: currentThread.1, board: self.currentBoard!); // Load the thumbnail image newOpPost.thumbnailImage = NSImage(contentsOfURL: NSURL(string: newOpPost.fileThumbnailUrl)!); // Add the OP post to the posts view self.addPostToPostsViewerStackView(newOpPost, displayImage: true); // For every reply in the OP post's recent replies... for(_, currentRecentReply) in newOpPost.recentReplies.enumerate() { // Add the current post to the posts view self.addPostToPostsViewerStackView(currentRecentReply, displayImage: false); } } } // Call the completion handler completionHandler?(); } } // Scroll to the top of postsViewerStackViewScrollView scrollToTopOfPostsViewerStackViewScrollView(); // Hide all the other views catalogCollectionViewScrollView.hidden = true; // Show the posts view postsViewerStackViewScrollView.hidden = false; // Return the title return "/\(currentBoard!.code)/ - Index"; } /// Scrolls to the top of postsViewerStackViewScrollView func scrollToTopOfPostsViewerStackViewScrollView() { // Scroll to the top of postsViewerStackViewScrollView postsViewerStackViewScrollView.contentView.scrollToPoint(NSPoint(x: 0, y: postsViewerStackView.subviews.count * 100000)); } /// Clears all the items in postsViewerStackView func clearPostsViewerStackView() { // Remove all the subviews from postsViewerStackView postsViewerStackView.subviews.removeAll(); } /// Adds the given post to postsViewerStackView. ALso only shows the thumbnail if displayImage is true func addPostToPostsViewerStackView(post : KJ4CPost, displayImage : Bool) { /// The new post view item for the stack view let newPostView : KJPostView = KJPostView(); // Display the post's info in the new post view newPostView.displayPost(post, displayImage: displayImage); // Set newPostView's repliesViewerViewContainer newPostView.repliesViewerViewContainer = self.view; // Set newPostView's thumbnail clicked target and action newPostView.thumbnailClickedTarget = self; newPostView.thumbnailClickedAction = Selector("postThumbnailImageClicked:"); // Add the post view to postsViewerStackView postsViewerStackView.addView(newPostView, inGravity: NSStackViewGravity.Top); // Add the leading and trailing constraints /// The constraint for the trailing edge of newPostView let newPostViewTrailingConstraint = NSLayoutConstraint(item: newPostView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: postsViewerStackViewScrollView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -50); // Add the constraint postsViewerStackViewScrollView.addConstraint(newPostViewTrailingConstraint); /// The constraint for the leading edge of newPostView let newPostViewLeadingConstraint = NSLayoutConstraint(item: newPostView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: postsViewerStackViewScrollView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: -50); // Add the constraint postsViewerStackViewScrollView.addConstraint(newPostViewLeadingConstraint); } /// The current image browser for this posts viewer var currentImageBrowser : KJPostsImageViewer? = nil; /// Called when the user presses a post's thumbnail image func postThumbnailImageClicked(post : KJ4CPost) { // Print what post we are displaying the file of print("KJPostViewerViewController: Displaying the file for \(post)"); // If the current image browser is nil... if(currentImageBrowser?.superview == nil) { // Create a new KJPostsImageViewer currentImageBrowser = KJPostsImageViewer(); // Move it into this view self.view.addSubview(currentImageBrowser!); // Disable translating autoresizing masks into constraints currentImageBrowser!.translatesAutoresizingMaskIntoConstraints = false; // Add the outer constraints currentImageBrowser!.addOuterConstraints(0); // Load in the current posts currentImageBrowser!.showImagesForPosts(self.currentThread!.allPosts, displayFirstPost: false); } // Jump to the clicked image in the current image browser currentImageBrowser!.displayPostAtIndex(NSMutableArray(array: currentImageBrowser!.currentBrowsingPosts).indexOfObject(post)); } override func viewWillAppear() { // Theme the view self.view.layer?.backgroundColor = KJThemingEngine().defaultEngine().backgroundColor.CGColor; } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // Set postsViewerStackViewScrollView's document view postsViewerStackViewScrollView.documentView = postsViewerStackView; // Set the catalog collection view's item prototype catalogCollectionView.itemPrototype = storyboard!.instantiateControllerWithIdentifier("catalogCollectionViewItem") as? NSCollectionViewItem; // Set the minimum and maximum item sizes catalogCollectionView.minItemSize = NSSize(width: 150, height: 200); catalogCollectionView.maxItemSize = NSSize(width: 250, height: 250); } } /// The different modes KJPostViewerViewController can be in enum KJPostViewerMode { /// Not set case None /// The catalog collection view case Catalog /// The index where you see the most recent posts case Index /// A thread case Thread }
f7e4411065a4fd7533466fbc8115899e
48.77709
265
0.614877
false
false
false
false
cfilipov/MuscleBook
refs/heads/master
MuscleBook/DB+Exercises.swift
gpl-3.0
1
/* Muscle Book Copyright (C) 2016 Cristian Filipov This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import SQLite extension Exercise { enum SortType: Int { case Alphabetical = 0 case Count private func column(scope scope: SchemaType) -> Expressible { typealias E = Exercise.Schema typealias W = Workset.Schema switch self { case .Alphabetical: return scope[E.name] case .Count: return W.workoutID.distinct.count.desc } } } } extension DB { func all(type: Exercise.Type) throws -> AnySequence<Exercise> { return try db.prepare(Exercise.Schema.table) } func all(type: Exercise.Type, sort: Exercise.SortType) throws -> [ExerciseReference] { typealias R = ExerciseReference.Schema typealias E = Exercise.Schema typealias W = Workset.Schema let rows = try db.prepare(E.table .select(E.table[E.exerciseID], E.table[E.name], W.workoutID.distinct.count) .join(.LeftOuter, W.table, on: W.table[W.exerciseID] == E.table[E.exerciseID]) .group(E.table[E.exerciseID]) .order(sort.column(scope: E.table))) return rows.map { return ExerciseReference( exerciseID: $0[R.exerciseID], name: $0[R.name], count: $0[W.workoutID.distinct.count]) }.filter { guard sort == .Count else { return true } return $0.count > 0 } } func count(type: Exercise.Type) -> Int { return db.scalar(Exercise.Schema.table.count) } func count(type: Exercise.Type, exerciseID: Int64) -> Int { typealias WS = Workset.Schema return db.scalar(WS.table.select(WS.exerciseID.count).filter(WS.exerciseID == exerciseID)) } func dereference(ref: ExerciseReference) -> Exercise? { guard let exerciseID = ref.exerciseID else { return nil } typealias S = Exercise.Schema let query = S.table.filter(S.exerciseID == exerciseID) return db.pluck(query) } func find(exactName name: String) -> ExerciseReference? { typealias E = Exercise.Schema return db.pluck(E.search .select(E.exerciseID, E.name) .filter(E.name == name)) } func find(exerciseID exerciseID: Int64) throws -> AnySequence<MuscleMovement> { return try db.prepare( MuscleMovement.Schema.table.filter( MuscleMovement.Schema.exerciseID == exerciseID)) } func findUnknownExercises() throws -> AnySequence<ExerciseReference> { let query = Workset.Schema.table .select(Workset.Schema.exerciseName) .filter(Workset.Schema.exerciseID == nil) .group(Workset.Schema.exerciseName) return try db.prepare(query) } func get(type: ExerciseReference.Type, date: NSDate) throws -> AnySequence<ExerciseReference> { typealias WS = Workset.Schema return try db.prepare(WS.table .select(WS.exerciseID, WS.exerciseName) .filter(WS.startTime.localDay == date.localDay) .group(WS.exerciseID)) } func match(name name: String, sort: Exercise.SortType) throws -> [ExerciseReference] { typealias E = Exercise.Schema typealias W = Workset.Schema let rows = try db.prepare(E.search .select(E.search[E.exerciseID], E.search[E.name], W.workoutID.distinct.count) .join(.LeftOuter, W.table, on: W.table[W.exerciseID] == E.search[E.exerciseID]) .group(E.search[E.exerciseID]) .match("*"+name+"*") .order(sort.column(scope: E.search))) return rows.map { return ExerciseReference( exerciseID: $0[E.search[E.exerciseID]], name: $0[E.name], count: $0[W.workoutID.distinct.count]) }.filter { guard sort == .Count else { return true } return $0.count > 0 } } func save(exercise: Exercise) throws { try db.transaction { [unowned self] in try self.db.run(Exercise.Schema.table.insert(or: .Replace, exercise)) for movement in exercise.muscles! { try self.db.run(MuscleMovement.Schema.table.insert(movement)) } try self.db.run(Exercise.Schema.search.insert(or: .Replace, exercise.exerciseReference)) } } func totalExercisesPerformed(sinceDate date: NSDate) -> Int { typealias W = Workset.Schema return db.scalar(W.table .select(W.exerciseID.distinct.count) .filter(W.startTime.localDay >= date)) } }
cbee248f082b05bb3ce214552ab36006
35.380952
100
0.61773
false
false
false
false
alexwinston/UIViewprint
refs/heads/master
UIViewprint/Examples/Padding/PaddingExamplesController.swift
mit
1
// // UILabelExamples.swift // Blueprint // // Created by Alex Winston on 3/9/16. // Copyright © 2016 Alex Winston. All rights reserved. // import Foundation import UIKit // TODO? Create UITableViewableStyleController that only requires a cell style and a datasource class PaddingExamplesController: UITableViewableController { let examples: [ExampleControllerDetails] = [ ExampleControllerDetails(name:"UIView basic padding example", controller:UIViewPaddingController.self), ] override func viewDidLoad() { super.viewDidLoad() self.title = "UIView padding examples" self.edgesForExtendedLayout = UIRectEdge.None; self.table( sections: [ section(selectExample, foreach:examples) { (example:AnyObject) in let example = example as! ExampleControllerDetails return self.defaultTableViewCell(example.name) } ] ) } func selectExample(indexPath:NSIndexPath) { let controller:UIViewController = self.examples[indexPath.row].controller.init() controller.view.frame = view.bounds controller.view.backgroundColor = .whiteColor() controller.view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] self.navigationController?.pushViewController(controller, animated: true) } }
9e25694d004a99a720a2e083f2e58dc1
32.363636
112
0.664622
false
false
false
false
ReactiveCocoa/ReactiveSwift
refs/heads/master
Sources/Observers/CollectEvery.swift
mit
1
import Dispatch extension Operators { internal final class CollectEvery<Value, Error: Swift.Error>: UnaryAsyncOperator<Value, [Value], Error> { let interval: DispatchTimeInterval let discardWhenCompleted: Bool let targetWithClock: DateScheduler private let state: Atomic<CollectEveryState<Value>> private let timerDisposable = SerialDisposable() init( downstream: Observer<[Value], Error>, downstreamLifetime: Lifetime, target: DateScheduler, interval: DispatchTimeInterval, skipEmpty: Bool, discardWhenCompleted: Bool ) { self.interval = interval self.discardWhenCompleted = discardWhenCompleted self.targetWithClock = target self.state = Atomic(CollectEveryState(skipEmpty: skipEmpty)) super.init(downstream: downstream, downstreamLifetime: downstreamLifetime, target: target) downstreamLifetime += timerDisposable let initialDate = targetWithClock.currentDate.addingTimeInterval(interval) timerDisposable.inner = targetWithClock.schedule(after: initialDate, interval: interval, leeway: interval * 0.1) { let (currentValues, isCompleted) = self.state.modify { ($0.collect(), $0.isCompleted) } if let currentValues = currentValues { self.unscheduledSend(currentValues) } if isCompleted { self.unscheduledTerminate(.completed) } } } override func receive(_ value: Value) { state.modify { $0.values.append(value) } } override func terminate(_ termination: Termination<Error>) { guard isActive else { return } if case .completed = termination, !discardWhenCompleted { state.modify { $0.isCompleted = true } } else { timerDisposable.dispose() super.terminate(termination) } } } } private struct CollectEveryState<Value> { let skipEmpty: Bool var values: [Value] = [] var isCompleted: Bool = false init(skipEmpty: Bool) { self.skipEmpty = skipEmpty } var hasValues: Bool { return !values.isEmpty || !skipEmpty } mutating func collect() -> [Value]? { guard hasValues else { return nil } defer { values.removeAll() } return values } }
16fc4f03637dc3f9d2b2cfda83cd2d47
25.807692
117
0.724055
false
false
false
false
tinypass/piano-sdk-for-ios
refs/heads/master
PianoAPI/API/SubscriptionAPI.swift
apache-2.0
1
import Foundation @objc(PianoAPISubscriptionAPI) public class SubscriptionAPI: NSObject { /// Lists a user&#39;s subscription /// - Parameters: /// - aid: Application aid /// - userToken: User token /// - userProvider: User token provider /// - userRef: Encrypted user reference /// - callback: Operation callback @objc public func list( aid: String, userToken: String? = nil, userProvider: String? = nil, userRef: String? = nil, completion: @escaping ([UserSubscription]?, Error?) -> Void) { guard let client = PianoAPI.shared.client else { completion(nil, PianoAPIError("PianoAPI not initialized")) return } var params = [String:String]() params["aid"] = aid if let v = userToken { params["user_token"] = v } if let v = userProvider { params["user_provider"] = v } if let v = userRef { params["user_ref"] = v } client.request( path: "/api/v3/subscription/list", method: PianoAPI.HttpMethod.from("POST"), params: params, completion: completion ) } }
c498dd63e1fc044f89807c680dfa94db
31.888889
70
0.571791
false
false
false
false
DianQK/Flix
refs/heads/master
Example/Example/Tutorial/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // Example // // Created by DianQK on 02/11/2017. // Copyright © 2017 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa import Flix class SettingsViewController: TableViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .automatic title = "Settings" let profileProvider = ProfileProvider(avatar: #imageLiteral(resourceName: "Flix Icon"), name: "Flix") let profileSectionProvider = SpacingSectionProvider(providers: [profileProvider], headerHeight: 35, footerHeight: 0) let airplaneModeProvider = SwitchTableViewCellProvider(title: "Airplane Mode", icon: #imageLiteral(resourceName: "Airplane Icon"), isOn: false) let wifiProvider = DescriptionTableViewCellProvider(title: "Wi-Fi", icon: #imageLiteral(resourceName: "Wifi Icon"), description: "Flix_5G") let bluetoothProvider = DescriptionTableViewCellProvider(title: "Bluetooth", icon: #imageLiteral(resourceName: "Bluetooth Icon"), description: "On") let cellularProvider = DescriptionTableViewCellProvider(title: "Cellular", icon: #imageLiteral(resourceName: "Cellular Icon")) let personalHotspotProvider = DescriptionTableViewCellProvider(title: "Personal Hotspot", icon: #imageLiteral(resourceName: "Personal Hotspot Icon"), description: "Off") let carrierProvider = DescriptionTableViewCellProvider(title: "Carrier", icon: #imageLiteral(resourceName: "Carrier Icon"), description: "AT&T") let networkSectionProvider = SpacingSectionProvider( providers: [ airplaneModeProvider, wifiProvider, bluetoothProvider, cellularProvider, personalHotspotProvider, carrierProvider ], headerHeight: 35, footerHeight: 0 ) let appSectionProvider = SpacingSectionProvider( providers: [AppsProvider(apps: [ App(icon: #imageLiteral(resourceName: "Wallet App Icon"), title: "Wallet"), App(icon: #imageLiteral(resourceName: "Music App Icon"), title: "Music"), App(icon: #imageLiteral(resourceName: "Safari App Icon"), title: "Safari"), App(icon: #imageLiteral(resourceName: "News App Icon"), title: "News"), App(icon: #imageLiteral(resourceName: "Camera App Icon"), title: "Camera"), App(icon: #imageLiteral(resourceName: "Photos App Icon"), title: "Photo") ])], headerHeight: 35, footerHeight: 35 ) self.tableView.flix.build([profileSectionProvider, networkSectionProvider, appSectionProvider]) } }
b218d04bf01550372c5cefcc7e2503a7
43.31746
177
0.663682
false
false
false
false
d4rkl0rd3r3b05/Data_Structure_And_Algorithm
refs/heads/master
LeetCode_LongestPalindromicSubString.swift
mit
1
/* * Given a string s, find the longest palindromic substring in s. */ func checkPalindromicString(input : String) -> Bool{ guard input.characters.count > 0 else { return false } if input.characters.count == 1 { return true } for index in 0 ..< input.characters.count/2 { if input[index] != input[input.characters.count - index - 1] { return false } } return true } public func getLongestPalindromicSubString(input : String) -> String?{ var maxLength = 0 var palindromicSubString = "" for index in 0 ..< input.characters.count { for innerIndex in ((index + 1) ..< input.characters.count).reversed() { if input[index] == input[innerIndex] { if checkPalindromicString(input: input[(index + 1) ..< innerIndex]) && maxLength < input[(index + 1) ..< innerIndex].characters.count{ maxLength = input[(index + 1) ..< innerIndex].characters.count palindromicSubString = input[index ..< innerIndex + 1] } } } } return maxLength != 0 ? palindromicSubString : nil }
2182b9c254cd1cdfa4cc940d2125b232
30.105263
150
0.576142
false
false
false
false
Yummypets/YPImagePicker
refs/heads/master
Source/Filters/Video/YPVideoFiltersVC.swift
mit
1
// // VideoFiltersVC.swift // YPImagePicker // // Created by Nik Kov || nik-kov.com on 18.04.2018. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import Photos import PryntTrimmerView import Stevia public final class YPVideoFiltersVC: UIViewController, IsMediaFilterVC { /// Designated initializer public class func initWith(video: YPMediaVideo, isFromSelectionVC: Bool) -> YPVideoFiltersVC { let vc = YPVideoFiltersVC() vc.inputVideo = video vc.isFromSelectionVC = isFromSelectionVC return vc } // MARK: - Public vars public var inputVideo: YPMediaVideo! public var inputAsset: AVAsset { return AVAsset(url: inputVideo.url) } public var didSave: ((YPMediaItem) -> Void)? public var didCancel: (() -> Void)? // MARK: - Private vars private var playbackTimeCheckerTimer: Timer? private var imageGenerator: AVAssetImageGenerator? private var isFromSelectionVC = false private let trimmerContainerView: UIView = { let v = UIView() return v }() private let trimmerView: TrimmerView = { let v = TrimmerView() v.mainColor = YPConfig.colors.trimmerMainColor v.handleColor = YPConfig.colors.trimmerHandleColor v.positionBarColor = YPConfig.colors.positionLineColor v.maxDuration = YPConfig.video.trimmerMaxDuration v.minDuration = YPConfig.video.trimmerMinDuration return v }() private let coverThumbSelectorView: ThumbSelectorView = { let v = ThumbSelectorView() v.thumbBorderColor = YPConfig.colors.coverSelectorBorderColor v.isHidden = true return v }() private lazy var trimBottomItem: YPMenuItem = { let v = YPMenuItem() v.textLabel.text = YPConfig.wordings.trim v.button.addTarget(self, action: #selector(selectTrim), for: .touchUpInside) return v }() private lazy var coverBottomItem: YPMenuItem = { let v = YPMenuItem() v.textLabel.text = YPConfig.wordings.cover v.button.addTarget(self, action: #selector(selectCover), for: .touchUpInside) return v }() private let videoView: YPVideoView = { let v = YPVideoView() return v }() private let coverImageView: UIImageView = { let v = UIImageView() v.contentMode = .scaleAspectFit v.isHidden = true return v }() // MARK: - Live cycle override public func viewDidLoad() { super.viewDidLoad() setupLayout() title = YPConfig.wordings.trim view.backgroundColor = YPConfig.colors.filterBackgroundColor setupNavigationBar(isFromSelectionVC: self.isFromSelectionVC) // Remove the default and add a notification to repeat playback from the start videoView.removeReachEndObserver() NotificationCenter.default .addObserver(self, selector: #selector(itemDidFinishPlaying(_:)), name: .AVPlayerItemDidPlayToEndTime, object: videoView.player.currentItem) // Set initial video cover imageGenerator = AVAssetImageGenerator(asset: self.inputAsset) imageGenerator?.appliesPreferredTrackTransform = true didChangeThumbPosition(CMTime(seconds: 1, preferredTimescale: 1)) } override public func viewDidAppear(_ animated: Bool) { trimmerView.asset = inputAsset trimmerView.delegate = self coverThumbSelectorView.asset = inputAsset coverThumbSelectorView.delegate = self selectTrim() videoView.loadVideo(inputVideo) videoView.showPlayImage(show: true) startPlaybackTimeChecker() super.viewDidAppear(animated) } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopPlaybackTimeChecker() videoView.stop() } // MARK: - Setup private func setupNavigationBar(isFromSelectionVC: Bool) { if isFromSelectionVC { navigationItem.leftBarButtonItem = UIBarButtonItem(title: YPConfig.wordings.cancel, style: .plain, target: self, action: #selector(cancel)) navigationItem.leftBarButtonItem?.setFont(font: YPConfig.fonts.leftBarButtonFont, forState: .normal) } setupRightBarButtonItem() } private func setupRightBarButtonItem() { let rightBarButtonTitle = isFromSelectionVC ? YPConfig.wordings.done : YPConfig.wordings.next navigationItem.rightBarButtonItem = UIBarButtonItem(title: rightBarButtonTitle, style: .done, target: self, action: #selector(save)) navigationItem.rightBarButtonItem?.tintColor = YPConfig.colors.tintColor navigationItem.rightBarButtonItem?.setFont(font: YPConfig.fonts.rightBarButtonFont, forState: .normal) } private func setupLayout() { view.subviews( trimBottomItem, coverBottomItem, videoView, coverImageView, trimmerContainerView.subviews( trimmerView, coverThumbSelectorView ) ) trimBottomItem.leading(0).height(40) trimBottomItem.Bottom == view.safeAreaLayoutGuide.Bottom trimBottomItem.Trailing == coverBottomItem.Leading coverBottomItem.Bottom == view.safeAreaLayoutGuide.Bottom coverBottomItem.trailing(0) equal(sizes: trimBottomItem, coverBottomItem) videoView.heightEqualsWidth().fillHorizontally().top(0) videoView.Bottom == trimmerContainerView.Top coverImageView.followEdges(videoView) trimmerContainerView.fillHorizontally() trimmerContainerView.Top == videoView.Bottom trimmerContainerView.Bottom == trimBottomItem.Top trimmerView.fillHorizontally(padding: 30).centerVertically() trimmerView.Height == trimmerContainerView.Height / 3 coverThumbSelectorView.followEdges(trimmerView) } // MARK: - Actions @objc private func save() { guard let didSave = didSave else { return ypLog("Don't have saveCallback") } navigationItem.rightBarButtonItem = YPLoaders.defaultLoader do { let asset = AVURLAsset(url: inputVideo.url) let trimmedAsset = try asset .assetByTrimming(startTime: trimmerView.startTime ?? CMTime.zero, endTime: trimmerView.endTime ?? inputAsset.duration) // Looks like file:///private/var/mobile/Containers/Data/Application // /FAD486B4-784D-4397-B00C-AD0EFFB45F52/tmp/8A2B410A-BD34-4E3F-8CB5-A548A946C1F1.mov let destinationURL = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingUniquePathComponent(pathExtension: YPConfig.video.fileType.fileExtension) _ = trimmedAsset.export(to: destinationURL) { [weak self] session in switch session.status { case .completed: DispatchQueue.main.async { if let coverImage = self?.coverImageView.image { let resultVideo = YPMediaVideo(thumbnail: coverImage, videoURL: destinationURL, asset: self?.inputVideo.asset) didSave(YPMediaItem.video(v: resultVideo)) self?.setupRightBarButtonItem() } else { ypLog("Don't have coverImage.") } } case .failed: ypLog("Export of the video failed. Reason: \(String(describing: session.error))") default: ypLog("Export session completed with \(session.status) status. Not handled") } } } catch let error { ypLog("Error: \(error)") } } @objc private func cancel() { didCancel?() } // MARK: - Bottom buttons @objc private func selectTrim() { title = YPConfig.wordings.trim trimBottomItem.select() coverBottomItem.deselect() trimmerView.isHidden = false videoView.isHidden = false coverImageView.isHidden = true coverThumbSelectorView.isHidden = true } @objc private func selectCover() { title = YPConfig.wordings.cover trimBottomItem.deselect() coverBottomItem.select() trimmerView.isHidden = true videoView.isHidden = true coverImageView.isHidden = false coverThumbSelectorView.isHidden = false stopPlaybackTimeChecker() videoView.stop() } // MARK: - Various Methods // Updates the bounds of the cover picker if the video is trimmed // TODO: Now the trimmer framework doesn't support an easy way to do this. // Need to rethink a flow or search other ways. private func updateCoverPickerBounds() { if let startTime = trimmerView.startTime, let endTime = trimmerView.endTime { if let selectedCoverTime = coverThumbSelectorView.selectedTime { let range = CMTimeRange(start: startTime, end: endTime) if !range.containsTime(selectedCoverTime) { // If the selected before cover range is not in new trimeed range, // than reset the cover to start time of the trimmed video } } else { // If none cover time selected yet, than set the cover to the start time of the trimmed video } } } // MARK: - Trimmer playback @objc private func itemDidFinishPlaying(_ notification: Notification) { if let startTime = trimmerView.startTime { videoView.player.seek(to: startTime) } } private func startPlaybackTimeChecker() { stopPlaybackTimeChecker() playbackTimeCheckerTimer = Timer .scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(onPlaybackTimeChecker), userInfo: nil, repeats: true) } private func stopPlaybackTimeChecker() { playbackTimeCheckerTimer?.invalidate() playbackTimeCheckerTimer = nil } @objc private func onPlaybackTimeChecker() { guard let startTime = trimmerView.startTime, let endTime = trimmerView.endTime else { return } let playBackTime = videoView.player.currentTime() trimmerView.seek(to: playBackTime) if playBackTime >= endTime { videoView.player.seek(to: startTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero) trimmerView.seek(to: startTime) } } } // MARK: - TrimmerViewDelegate extension YPVideoFiltersVC: TrimmerViewDelegate { public func positionBarStoppedMoving(_ playerTime: CMTime) { videoView.player.seek(to: playerTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero) videoView.play() startPlaybackTimeChecker() updateCoverPickerBounds() } public func didChangePositionBar(_ playerTime: CMTime) { stopPlaybackTimeChecker() videoView.pause() videoView.player.seek(to: playerTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero) } } // MARK: - ThumbSelectorViewDelegate extension YPVideoFiltersVC: ThumbSelectorViewDelegate { public func didChangeThumbPosition(_ imageTime: CMTime) { if let imageGenerator = imageGenerator, let imageRef = try? imageGenerator.copyCGImage(at: imageTime, actualTime: nil) { coverImageView.image = UIImage(cgImage: imageRef) } } }
4a28f96c2aaa990570c2838be1155f9f
35.188406
112
0.605046
false
true
false
false
giangbvnbgit128/AnViet
refs/heads/master
AnViet/Class/Models/NewsItem.swift
apache-2.0
1
// // NewsItem.swift // AnViet // // Created by Bui Giang on 6/6/17. // Copyright © 2017 Bui Giang. All rights reserved. // import Foundation import ObjectMapper class NewsItem: Mappable { var error:String = "FALSE" var host:String = "" var message:String = "" var data:[DataForItem] = [] init() {} required init(map: Map) { } func mapping(map: Map) { error <- map["error"] host <- map["host"] message <- map["mess"] data <- map["data"] } } class DataForItem: Mappable { var post:PostOfData = PostOfData() var user:UserNewsPost = UserNewsPost() init() {} required init(map: Map) { } func mapping(map: Map) { post <- map["Post"] user <- map["User"] } } class PostOfData: Mappable { var id:String = "" var title:String = "" var avatar:String = "" var userId:String = "" var content:String = "" private var strImage:String = "" var image:[ImageItem] = [] var userLike:String = "" var userView:String = "" var activate:String = "0" var status:String = "0" var createdDate:String = "2017" init() {} required init(map: Map) { } func mapping(map: Map) { id <- map["id"] title <- map["title"] avatar <- map["avatar"] userId <- map["user_id"] content <- map["content"] strImage <- map["image"] userLike <- map["user_like"] userView <- map["user_view"] activate <- map["active"] status <- map["status"] createdDate <- map["created_date"] image = self.getArrayLinkImage(strListImage: strImage) } func getArrayLinkImage(strListImage: String) -> [ImageItem] { var arrayImage:[ImageItem] = [] let data: Data? = strListImage.data(using: String.Encoding.utf8) guard data != nil else { return [] } let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? [String : AnyObject] guard json != nil else { return [] } for item in json!! { print(item.value) print(item.key) let itemImage:ImageItem = ImageItem(id: item.key, urlImage: item.value as! String) arrayImage.append(itemImage) } return arrayImage } } class UserNewsPost: Mappable { var id:String = "" var username:String = "" var avartar:String = "" init() {} required init(map: Map) { } func mapping(map: Map) { id <- map["id"] username <- map["username"] avartar <- map["avatar"] } } class ImageItem: AnyObject { var id:String = "" var urlImage = "" init() { } init(id:String , urlImage:String) { self.id = id self.urlImage = urlImage } }
b0de7c539771145b7268b49b5816b64f
20.232394
115
0.519403
false
false
false
false
grandiere/box
refs/heads/master
box/View/GridHarvest/VGridHarvestBarCollect.swift
mit
1
import UIKit class VGridHarvestBarCollect:UIButton { private weak var controller:CGridHarvest! private weak var labelScore:UILabel! private weak var labelKills:UILabel! private weak var labelGet:UILabel! private weak var viewGet:UIView! private let kLabelsHeight:CGFloat = 26 private let kTitlesHeigth:CGFloat = 18 private let KBorderWidth:CGFloat = 1 private let kCornerRadius:CGFloat = 6 private let kGetWidth:CGFloat = 50 private let kScoreMultiplier:CGFloat = 0.6 private let kKillsMultiplier:CGFloat = 0.4 init(controller:CGridHarvest) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false layer.cornerRadius = kCornerRadius layer.borderWidth = KBorderWidth isUserInteractionEnabled = false addTarget( self, action:#selector(actionCollect(sender:)), for:UIControlEvents.touchUpInside) self.controller = controller let viewGet:UIView = UIView() viewGet.translatesAutoresizingMaskIntoConstraints = false viewGet.isUserInteractionEnabled = false viewGet.clipsToBounds = true self.viewGet = viewGet let viewLabels:UIView = UIView() viewLabels.isUserInteractionEnabled = false viewLabels.translatesAutoresizingMaskIntoConstraints = false viewLabels.clipsToBounds = true viewLabels.backgroundColor = UIColor.clear let labelGet:UILabel = UILabel() labelGet.isUserInteractionEnabled = false labelGet.backgroundColor = UIColor.clear labelGet.translatesAutoresizingMaskIntoConstraints = false labelGet.textAlignment = NSTextAlignment.center labelGet.font = UIFont.bold(size:14) labelGet.text = NSLocalizedString("VGridHarvestBarCollect_labelGet", comment:"") self.labelGet = labelGet let labelScore:UILabel = UILabel() labelScore.translatesAutoresizingMaskIntoConstraints = false labelScore.isUserInteractionEnabled = false labelScore.backgroundColor = UIColor.clear labelScore.textAlignment = NSTextAlignment.center labelScore.font = UIFont.numeric(size:15) self.labelScore = labelScore let labelKills:UILabel = UILabel() labelKills.translatesAutoresizingMaskIntoConstraints = false labelKills.isUserInteractionEnabled = false labelKills.backgroundColor = UIColor.clear labelKills.textAlignment = NSTextAlignment.center labelKills.font = UIFont.numeric(size:15) self.labelKills = labelKills let labelScoreTitle:UILabel = UILabel() labelScoreTitle.isUserInteractionEnabled = false labelScoreTitle.translatesAutoresizingMaskIntoConstraints = false labelScoreTitle.backgroundColor = UIColor.clear labelScoreTitle.textAlignment = NSTextAlignment.center labelScoreTitle.font = UIFont.regular(size:10) labelScoreTitle.textColor = UIColor.white labelScoreTitle.text = NSLocalizedString("VGridHarvestBarCollect_labelScoreTitle", comment:"") let labelKillsTitle:UILabel = UILabel() labelKillsTitle.isUserInteractionEnabled = false labelKillsTitle.translatesAutoresizingMaskIntoConstraints = false labelKillsTitle.backgroundColor = UIColor.clear labelKillsTitle.textAlignment = NSTextAlignment.center labelKillsTitle.font = UIFont.regular(size:10) labelKillsTitle.textColor = UIColor.white labelKillsTitle.text = NSLocalizedString("VGridHarvestBarCollect_labelKillsTitle", comment:"") viewGet.addSubview(labelGet) viewLabels.addSubview(labelScore) viewLabels.addSubview(labelKills) viewLabels.addSubview(labelScoreTitle) viewLabels.addSubview(labelKillsTitle) addSubview(viewLabels) addSubview(viewGet) NSLayoutConstraint.equals( view:labelGet, toView:viewGet) NSLayoutConstraint.equalsVertical( view:viewLabels, toView:self) NSLayoutConstraint.rightToLeft( view:viewLabels, toView:viewGet) NSLayoutConstraint.leftToLeft( view:viewLabels, toView:self) NSLayoutConstraint.equalsVertical( view:viewGet, toView:self) NSLayoutConstraint.rightToRight( view:viewGet, toView:self) NSLayoutConstraint.width( view:viewGet, constant:kGetWidth) NSLayoutConstraint.topToTop( view:labelScore, toView:viewLabels) NSLayoutConstraint.height( view:labelScore, constant:kLabelsHeight) NSLayoutConstraint.width( view:labelScore, toView:viewLabels, multiplier:kScoreMultiplier) NSLayoutConstraint.rightToRight( view:labelScore, toView:viewLabels) NSLayoutConstraint.topToTop( view:labelKills, toView:viewLabels) NSLayoutConstraint.height( view:labelKills, constant:kLabelsHeight) NSLayoutConstraint.leftToLeft( view:labelKills, toView:viewLabels) NSLayoutConstraint.width( view:labelKills, toView:viewLabels, multiplier:kKillsMultiplier) NSLayoutConstraint.bottomToBottom( view:labelScoreTitle, toView:viewLabels) NSLayoutConstraint.height( view:labelScoreTitle, constant:kTitlesHeigth) NSLayoutConstraint.equalsHorizontal( view:labelScore, toView:labelScoreTitle) NSLayoutConstraint.bottomToBottom( view:labelKillsTitle, toView:viewLabels) NSLayoutConstraint.height( view:labelKillsTitle, constant:kTitlesHeigth) NSLayoutConstraint.equalsHorizontal( view:labelKillsTitle, toView:labelKills) hover() } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: actions func actionCollect(sender button:UIButton) { button.isUserInteractionEnabled = false controller.collect() } //MARK: private private func hover() { if isUserInteractionEnabled { if isSelected || isHighlighted { layer.borderColor = UIColor.gridOrange.cgColor viewGet.backgroundColor = UIColor.gridOrange labelGet.textColor = UIColor.white labelScore.textColor = UIColor.gridOrange labelKills.textColor = UIColor.gridOrange } else { layer.borderColor = UIColor.gridBlue.cgColor viewGet.backgroundColor = UIColor.gridBlue labelGet.textColor = UIColor.black labelScore.textColor = UIColor.white labelKills.textColor = UIColor.white } } else { layer.borderColor = UIColor(white:1, alpha:0.2).cgColor viewGet.backgroundColor = UIColor(white:1, alpha:0.2) labelGet.textColor = UIColor(white:1, alpha:0.4) labelScore.textColor = UIColor(white:1, alpha:0.4) labelKills.textColor = UIColor(white:1, alpha:0.4) } } //MARK: public func displayHarvest() { labelScore.text = "\(controller.model.harvestScore)" labelKills.text = "\(controller.model.harvestKills)" if controller.model.harvestScore > 0 { isUserInteractionEnabled = true } else { isUserInteractionEnabled = false } hover() } }
74225d66144996e41215be54b1feb69a
32.167331
102
0.624144
false
false
false
false
netyouli/SexyJson
refs/heads/master
SexyJsonKit/SexyJsonOperation.swift
mit
1
// // SexyJsonOperation.swift // SexyJson // // Created by WHC on 17/5/14. // Copyright © 2017年 WHC. All rights reserved. // // Github <https://github.com/netyouli/SexyJson> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation infix operator <<< //MARK: - SexyJsonBasicType - #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) public func <<< <T: _SexyJsonBasicType>(left: inout T!, right: Any?) -> Void { left = T.sexyTransform(right) } #endif public func <<< <T: _SexyJsonBasicType>(left: inout T?, right: Any?) -> Void { left = T.sexyTransform(right) } public func <<< <T: _SexyJsonBasicType>(left: inout T, right: Any?) -> Void { if let value = T.sexyTransform(right) { left = value } } //MARK: - SexyJsonEnumType - #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) public func <<< <T: SexyJsonEnumType> (left: inout T!, right: Any?) -> Void { left = T.sexyTransform(right) } #endif public func <<< <T: SexyJsonEnumType>(left: inout T?, right: Any?) -> Void { left = T.sexyTransform(right) } public func <<< <T: SexyJsonEnumType>(left: inout T, right: Any?) -> Void { if let value = T.sexyTransform(right) { left = value } } //MARK: - SexyJsonObjectType - #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) public func <<< <T: SexyJsonObjectType>(left: inout T!, right: Any?) -> Void { left = T._sexyTransform(right) as? T } #endif public func <<< <T: SexyJsonObjectType>(left: inout T?, right: Any?) -> Void { left = T._sexyTransform(right) as? T } public func <<< <T: SexyJsonObjectType>(left: inout T, right: Any?) -> Void { if let value = T._sexyTransform(right) as? T { left = value } } //MARK: - SexyJson - public func <<< <T: SexyJson>(left: inout T?, right: Any?) -> Void { if let rightMap = right as? [String: Any] { left = T.init() left!.sexyMap(rightMap) } } #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) public func <<< <T: SexyJson>(left: inout T!, right: Any?) -> Void { if let rightMap = right as? [String: Any] { left = T.init() left.sexyMap(rightMap) } } #endif public func <<< <T: SexyJson>(left: inout T, right: Any?) -> Void { if let rightMap = right as? [String: Any] { left.sexyMap(rightMap) } } //MARK: - [SexyJsonBasicType] - public func <<< <T: _SexyJsonBasicType>(left: inout [T]?, right: Any?) -> Void { if right != nil { left = [T].init() left! <<< right } } #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) public func <<< <T: _SexyJsonBasicType>(left: inout [T]!, right: Any?) -> Void { if right != nil { left = [T].init() left! <<< right } } #endif public func <<< <T: _SexyJsonBasicType>(left: inout [T], right: Any?) -> Void { if let rightMap = right as? [Any] { rightMap.forEach({ (map) in left.append(T.sexyTransform(map)!) }) } } //MARK: - [SexyJsonEnumType] - #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) public func <<< <T: SexyJsonEnumType> (left: inout [T]!, right: Any?) -> Void { if right != nil { left = [T].init() left! <<< right } } #endif public func <<< <T: SexyJsonEnumType>(left: inout [T]?, right: Any?) -> Void { if right != nil { left = [T].init() left! <<< right } } public func <<< <T: SexyJsonEnumType>(left: inout [T], right: Any?) -> Void { if let rightMap = right as? [Any] { rightMap.forEach({ (map) in left.append(T.sexyTransform(map)!) }) } } //MARK: - [SexyJsonObjectType] - #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) public func <<< <T: SexyJsonObjectType>(left: inout [T]!, right: Any?) -> Void { if right != nil { left = [T].init() left! <<< right } } #endif public func <<< <T: SexyJsonObjectType>(left: inout [T]?, right: Any?) -> Void { if right != nil { left = [T].init() left! <<< right } } public func <<< <T: SexyJsonObjectType>(left: inout [T], right: Any?) -> Void { if let rightMap = right as? [Any] { rightMap.forEach({ (map) in if let value = T._sexyTransform(map) as? T { left.append(value) } }) } } //MARK: - [SexyJson] - public func <<< <T: SexyJson>(left: inout [T]?, right: Any?) -> Void { if right != nil { left = [T].init() left! <<< right } } #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) public func <<< <T: SexyJson>(left: inout [T]!, right: Any?) -> Void { if right != nil { left = [T].init() left! <<< right } } #endif public func <<< <T: SexyJson>(left: inout [T], right: Any?) -> Void { if let rightMap = right as? [Any] { rightMap.forEach({ (map) in if let elementMap = map as? [String : Any] { var element = T.init() element.sexyMap(elementMap) left.append(element) } }) } }
720780e941a0fb48064985ed0687f692
26.7
80
0.576469
false
false
false
false
CODE4APPLE/PKHUD
refs/heads/master
Demo/DemoViewController.swift
mit
2
// // DemoViewController.swift // PKHUD Demo // // Created by Philip Kluz on 6/18/14. // Copyright (c) 2014 NSExceptional. All rights reserved. // import UIKit import PKHUD class DemoViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() PKHUD.sharedHUD.dimsBackground = false PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = false } @IBAction func showAnimatedSuccessHUD(sender: AnyObject) { PKHUD.sharedHUD.contentView = PKHUDSuccessView() PKHUD.sharedHUD.show() PKHUD.sharedHUD.hide(afterDelay: 2.0); } @IBAction func showAnimatedErrorHUD(sender: AnyObject) { PKHUD.sharedHUD.contentView = PKHUDErrorView() PKHUD.sharedHUD.show() PKHUD.sharedHUD.hide(afterDelay: 2.0); } @IBAction func showAnimatedProgressHUD(sender: AnyObject) { PKHUD.sharedHUD.contentView = PKHUDProgressView() PKHUD.sharedHUD.show() let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { PKHUD.sharedHUD.contentView = PKHUDSuccessView() PKHUD.sharedHUD.hide(afterDelay: 2.0) } } @IBAction func showTextHUD(sender: AnyObject) { PKHUD.sharedHUD.contentView = PKHUDTextView(text: "Requesting Licence…") PKHUD.sharedHUD.show() PKHUD.sharedHUD.hide(afterDelay: 2.0) } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.AllButUpsideDown; } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
fd0b5302a69451e8b84080dc9d26d41d
30.392857
91
0.671217
false
false
false
false
vsubrahmanian/iRemind
refs/heads/master
iRemind/ReminderInfoModel.swift
apache-2.0
2
// // ReminderInfoModel.swift // iRemind // // Created by Vijay Subrahmanian on 03/06/15. // Copyright (c) 2015 Vijay Subrahmanian. All rights reserved. // import Foundation class ReminderInfoModel: NSObject, NSCoding { var name = "" var details = "" var time: NSDate? override init() { super.init() } required convenience init(coder aDecoder: NSCoder) { self.init() self.name = aDecoder.decodeObjectForKey("nameKey") as! String self.details = aDecoder.decodeObjectForKey("detailsKey") as! String self.time = aDecoder.decodeObjectForKey("timeKey") as? NSDate } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "nameKey") aCoder.encodeObject(self.details, forKey: "detailsKey") aCoder.encodeObject(self.time, forKey: "timeKey") } }
5ac761ab2e9415dbe21aa5b60bf9164d
25.757576
75
0.651927
false
false
false
false
wireapp/wire-ios-sync-engine
refs/heads/develop
Tests/Source/Synchronization/Strategies/UserImageAssetUpdateStrategyTests.swift
gpl-3.0
1
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import XCTest @testable import WireSyncEngine typealias ProfileImageSize = WireSyncEngine.ProfileImageSize class MockImageUpdateStatus: WireSyncEngine.UserProfileImageUploadStatusProtocol { var allSizes: [ProfileImageSize] { return [.preview, .complete] } var assetIdsToDelete = Set<String>() func hasAssetToDelete() -> Bool { return !assetIdsToDelete.isEmpty } func consumeAssetToDelete() -> String? { return assetIdsToDelete.removeFirst() } var dataToConsume = [ProfileImageSize: Data]() func consumeImage(for size: ProfileImageSize) -> Data? { return dataToConsume[size] } func hasImageToUpload(for size: ProfileImageSize) -> Bool { return dataToConsume[size] != nil } var uploadDoneForSize: ProfileImageSize? var uploadDoneWithAssetId: String? func uploadingDone(imageSize: ProfileImageSize, assetId: String) { uploadDoneForSize = imageSize uploadDoneWithAssetId = assetId } var uploadFailedForSize: ProfileImageSize? var uploadFailedWithError: Error? func uploadingFailed(imageSize: ProfileImageSize, error: Error) { uploadFailedForSize = imageSize uploadFailedWithError = error } } class UserImageAssetUpdateStrategyTests: MessagingTest { var sut: WireSyncEngine.UserImageAssetUpdateStrategy! var mockApplicationStatus: MockApplicationStatus! var updateStatus: MockImageUpdateStatus! override func setUp() { super.setUp() self.mockApplicationStatus = MockApplicationStatus() self.mockApplicationStatus.mockSynchronizationState = .online self.updateStatus = MockImageUpdateStatus() sut = UserImageAssetUpdateStrategy(managedObjectContext: syncMOC, applicationStatus: mockApplicationStatus, imageUploadStatus: updateStatus) self.syncMOC.zm_userImageCache = UserImageLocalCache(location: nil) self.uiMOC.zm_userImageCache = self.syncMOC.zm_userImageCache } override func tearDown() { self.mockApplicationStatus = nil self.updateStatus = nil self.sut = nil self.syncMOC.zm_userImageCache = nil BackendInfo.domain = nil super.tearDown() } } // MARK: - Profile image upload extension UserImageAssetUpdateStrategyTests { func testThatItDoesNotReturnARequestWhenThereIsNoImageToUpload() { // WHEN updateStatus.dataToConsume.removeAll() // THEN XCTAssertNil(sut.nextRequest(for: .v0)) } func testThatItDoesNotReturnARequestWhenUserIsNotLoggedIn() { // WHEN updateStatus.dataToConsume[.preview] = Data() updateStatus.dataToConsume[.complete] = Data() mockApplicationStatus.mockSynchronizationState = .unauthenticated // THEN XCTAssertNil(sut.nextRequest(for: .v0)) } func testThatItCreatesRequestSyncs() { XCTAssertNotNil(sut.upstreamRequestSyncs[.preview]) XCTAssertNotNil(sut.upstreamRequestSyncs[.complete]) } func testThatItReturnsCorrectSizeFromRequestSync() { // WHEN let previewSync = sut.upstreamRequestSyncs[.preview]! let completeSync = sut.upstreamRequestSyncs[.complete]! // THEN XCTAssertEqual(sut.size(for: previewSync), .preview) XCTAssertEqual(sut.size(for: completeSync), .complete) } func testThatItCreatesRequestWhenThereIsData() { // WHEN updateStatus.dataToConsume.removeAll() updateStatus.dataToConsume[.preview] = "Some".data(using: .utf8) // THEN let previewRequest = sut.nextRequest(for: .v0) XCTAssertNotNil(previewRequest) XCTAssertEqual(previewRequest?.path, "/assets/v3") XCTAssertEqual(previewRequest?.method, .methodPOST) // WHEN updateStatus.dataToConsume.removeAll() updateStatus.dataToConsume[.complete] = "Other".data(using: .utf8) // THEN let completeRequest = sut.nextRequest(for: .v0) XCTAssertNotNil(completeRequest) XCTAssertEqual(completeRequest?.path, "/assets/v3") XCTAssertEqual(completeRequest?.method, .methodPOST) } func testThatItCreatesRequestWithExpectedData() { // GIVEN let previewData = "--1--".data(using: .utf8) let previewRequest = sut.requestFactory.upstreamRequestForAsset(withData: previewData!, shareable: true, retention: .eternal, apiVersion: .v0) let completeData = "1111111".data(using: .utf8) let completeRequest = sut.requestFactory.upstreamRequestForAsset(withData: completeData!, shareable: true, retention: .eternal, apiVersion: .v0) // WHEN updateStatus.dataToConsume.removeAll() updateStatus.dataToConsume[.preview] = previewData // THEN XCTAssertEqual(sut.nextRequest(for: .v0)?.binaryData, previewRequest?.binaryData) // WHEN updateStatus.dataToConsume.removeAll() updateStatus.dataToConsume[.complete] = completeData // THEN XCTAssertEqual(sut.nextRequest(for: .v0)?.binaryData, completeRequest?.binaryData) } func testThatItCreatesDeleteRequestIfThereAreAssetsToDelete() { // GIVEN let assetId = "12344" let deleteRequest = ZMTransportRequest(path: "/assets/v3/\(assetId)", method: .methodDELETE, payload: nil, apiVersion: APIVersion.v0.rawValue) // WHEN updateStatus.assetIdsToDelete = [assetId] // THEN XCTAssertEqual(sut.nextRequest(for: .v0), deleteRequest) XCTAssert(updateStatus.assetIdsToDelete.isEmpty) } func testThatUploadMarkedAsFailedOnUnsuccessfulResponse() { // GIVEN let size = ProfileImageSize.preview let sync = sut.upstreamRequestSyncs[size] let failedResponse = ZMTransportResponse(payload: nil, httpStatus: 500, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue) // WHEN sut.didReceive(failedResponse, forSingleRequest: sync!) // THEN XCTAssertEqual(updateStatus.uploadFailedForSize, size) } func testThatUploadIsMarkedAsDoneAfterSuccessfulResponse() { // GIVEN let size = ProfileImageSize.preview let sync = sut.upstreamRequestSyncs[size] let assetId = "123123" let payload: [String: String] = ["key": assetId] let successResponse = ZMTransportResponse(payload: payload as NSDictionary, httpStatus: 200, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue) // WHEN sut.didReceive(successResponse, forSingleRequest: sync!) // THEN XCTAssertEqual(updateStatus.uploadDoneForSize, size) XCTAssertEqual(updateStatus.uploadDoneWithAssetId, assetId) } } // MARK: - Profile image download extension UserImageAssetUpdateStrategyTests { func testThatItCreatesDownstreamRequestSyncs() { XCTAssertNotNil(sut.downstreamRequestSyncs[.preview]) XCTAssertNotNil(sut.downstreamRequestSyncs[.complete]) } func testThatItReturnsCorrectSizeFromDownstreamRequestSync() { // WHEN let previewSync = sut.downstreamRequestSyncs[.preview]! let completeSync = sut.downstreamRequestSyncs[.complete]! // THEN XCTAssertEqual(sut.size(for: previewSync), .preview) XCTAssertEqual(sut.size(for: completeSync), .complete) } func testThatItWhitelistsUserOnPreviewSyncForPreviewImageNotification() { // GIVEN let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC) user.previewProfileAssetIdentifier = "fooo" let sync = self.sut.downstreamRequestSyncs[.preview]! XCTAssertFalse(sync.hasOutstandingItems) syncMOC.saveOrRollback() // WHEN uiMOC.performGroupedBlock { (self.uiMOC.object(with: user.objectID) as? ZMUser)?.requestPreviewProfileImage() } XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // THEN XCTAssertTrue(sync.hasOutstandingItems) } func testThatItWhitelistsUserOnPreviewSyncForCompleteImageNotification() { // GIVEN let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC) user.completeProfileAssetIdentifier = "fooo" let sync = self.sut.downstreamRequestSyncs[.complete]! XCTAssertFalse(sync.hasOutstandingItems) syncMOC.saveOrRollback() // WHEN uiMOC.performGroupedBlock { (self.uiMOC.object(with: user.objectID) as? ZMUser)?.requestCompleteProfileImage() } XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // THEN XCTAssertTrue(sync.hasOutstandingItems) } func testThatItCreatesRequestForCorrectAssetIdentifier(for size: ProfileImageSize, apiVersion: APIVersion) { // GIVEN let domain = "example.domain.com" BackendInfo.domain = domain let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC) let assetId = "foo-bar" switch size { case .preview: user.previewProfileAssetIdentifier = assetId case .complete: user.completeProfileAssetIdentifier = assetId } syncMOC.saveOrRollback() // WHEN uiMOC.performGroupedBlock { let user = self.uiMOC.object(with: user.objectID) as? ZMUser switch size { case .preview: user?.requestPreviewProfileImage() case .complete: user?.requestCompleteProfileImage() } } XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // THEN let expectedPath: String switch apiVersion { case .v0: expectedPath = "/assets/v3/\(assetId)" case .v1: expectedPath = "/v1/assets/v4/\(domain)/\(assetId)" case .v2: expectedPath = "/v2/assets/\(domain)/\(assetId)" } let request = self.sut.downstreamRequestSyncs[size]?.nextRequest(for: apiVersion) XCTAssertNotNil(request) XCTAssertEqual(request?.path, expectedPath) XCTAssertEqual(request?.method, .methodGET) } func testThatItCreatesRequestForCorrectAssetIdentifierForPreviewImage() { testThatItCreatesRequestForCorrectAssetIdentifier(for: .preview, apiVersion: .v0) testThatItCreatesRequestForCorrectAssetIdentifier(for: .preview, apiVersion: .v1) testThatItCreatesRequestForCorrectAssetIdentifier(for: .preview, apiVersion: .v2) } func testThatItCreatesRequestForCorrectAssetIdentifierForCompleteImage() { testThatItCreatesRequestForCorrectAssetIdentifier(for: .complete, apiVersion: .v0) testThatItCreatesRequestForCorrectAssetIdentifier(for: .complete, apiVersion: .v1) testThatItCreatesRequestForCorrectAssetIdentifier(for: .complete, apiVersion: .v2) } func testThatItUpdatesCorrectUserImageDataForPreviewImage() { // GIVEN let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC) let imageData = "image".data(using: .utf8)! let sync = self.sut.downstreamRequestSyncs[.preview]! user.previewProfileAssetIdentifier = "foo" let response = ZMTransportResponse(imageData: imageData, httpStatus: 200, transportSessionError: nil, headers: nil, apiVersion: APIVersion.v0.rawValue) // WHEN self.sut.update(user, with: response, downstreamSync: sync) // THEN XCTAssertEqual(user.imageSmallProfileData, imageData) } func testThatItUpdatesCorrectUserImageDataForCompleteImage() { // GIVEN let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC) let imageData = "image".data(using: .utf8)! let sync = self.sut.downstreamRequestSyncs[.complete]! user.completeProfileAssetIdentifier = "foo" let response = ZMTransportResponse(imageData: imageData, httpStatus: 200, transportSessionError: nil, headers: nil, apiVersion: APIVersion.v0.rawValue) // WHEN self.sut.update(user, with: response, downstreamSync: sync) // THEN XCTAssertEqual(user.imageMediumData, imageData) } func testThatItDeletesPreviewProfileAssetIdentifierWhenReceivingAPermanentErrorForPreviewImage() { // Given let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC) let assetId = UUID.create().transportString() user.previewProfileAssetIdentifier = assetId syncMOC.saveOrRollback() // When uiMOC.performGroupedBlock { (self.uiMOC.object(with: user.objectID) as? ZMUser)?.requestPreviewProfileImage() } XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) guard let request = sut.nextRequestIfAllowed(for: .v0) else { return XCTFail("nil request generated") } XCTAssertEqual(request.path, "/assets/v3/\(assetId)") XCTAssertEqual(request.method, .methodGET) // Given let response = ZMTransportResponse(payload: nil, httpStatus: 404, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue) request.complete(with: response) // THEN user.requestPreviewProfileImage() XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) XCTAssertNil(user.previewProfileAssetIdentifier) XCTAssertNil(sut.nextRequestIfAllowed(for: .v0)) } func testThatItDeletesCompleteProfileAssetIdentifierWhenReceivingAPermanentErrorForCompleteImage() { // Given let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC) let assetId = UUID.create().transportString() user.completeProfileAssetIdentifier = assetId syncMOC.saveOrRollback() // When uiMOC.performGroupedBlock { (self.uiMOC.object(with: user.objectID) as? ZMUser)?.requestCompleteProfileImage() } XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) guard let request = sut.nextRequestIfAllowed(for: .v0) else { return XCTFail("nil request generated") } XCTAssertEqual(request.path, "/assets/v3/\(assetId)") XCTAssertEqual(request.method, .methodGET) // Given let response = ZMTransportResponse(payload: nil, httpStatus: 404, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue) request.complete(with: response) // THEN user.requestCompleteProfileImage() XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) XCTAssertNil(user.completeProfileAssetIdentifier) XCTAssertNil(sut.nextRequestIfAllowed(for: .v0)) } }
cc172d8f9f93e5e88c1a5d33c6fa5c3e
36.924574
164
0.685251
false
true
false
false
NickEntin/SimPermissions
refs/heads/master
Pods/SwiftFSWatcher/src/SwiftFSWatcher/SwiftFSWatcher/SwiftFSWatcher.swift
mit
1
// // SwiftFSWatcher.swift // SwiftFSWatcher // // Created by Gurinder Hans on 4/9/16. // Copyright © 2016 Gurinder Hans. All rights reserved. // @objc public class SwiftFSWatcher : NSObject { var isRunning = false var stream: FSEventStreamRef? var onChangeCallback: ([FileEvent] -> Void)? public var watchingPaths: [String]? // MARK: - Init methods public override init() { // Default init super.init() } public convenience init(_ paths: [String]) { self.init() self.watchingPaths = paths } // MARK: - API public methods public func watch(changeCb: ([FileEvent] -> Void)?) { guard let paths = watchingPaths else { return } guard stream == nil else { return } onChangeCallback = changeCb var context = FSEventStreamContext(version: 0, info: UnsafeMutablePointer<Void>(unsafeAddressOf(self)), retain: nil, release: nil, copyDescription: nil) stream = FSEventStreamCreate(kCFAllocatorDefault, innerEventCallback, &context, paths, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0, UInt32(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents)) FSEventStreamScheduleWithRunLoop(stream!, NSRunLoop.currentRunLoop().getCFRunLoop(), kCFRunLoopDefaultMode) FSEventStreamStart(stream!) isRunning = true } public func resume() { guard stream != nil else { return } FSEventStreamStart(stream!) } public func pause() { guard stream != nil else { return } FSEventStreamStop(stream!) } // MARK: - [Private] Closure passed into `FSEventStream` and is called on new file event private let innerEventCallback: FSEventStreamCallback = { (stream: ConstFSEventStreamRef, contextInfo: UnsafeMutablePointer<Void>, numEvents: Int, eventPaths: UnsafeMutablePointer<Void>, eventFlags: UnsafePointer<FSEventStreamEventFlags>, eventIds: UnsafePointer<FSEventStreamEventId>) in let fsWatcher: SwiftFSWatcher = unsafeBitCast(contextInfo, SwiftFSWatcher.self) let paths = unsafeBitCast(eventPaths, NSArray.self) as! [String] var fileEvents = [FileEvent]() for i in 0..<numEvents { let event = FileEvent(path: paths[i], flag: eventFlags[i], id: eventIds[i]) fileEvents.append(event) } fsWatcher.onChangeCallback?(fileEvents) } } @objc public class FileEvent : NSObject { public var eventPath: String! public var eventFlag: NSNumber! public var eventId: NSNumber! public init(path: String!, flag: UInt32!, id: UInt64!) { eventPath = path eventFlag = NSNumber(unsignedInt: flag) eventId = NSNumber(unsignedLongLong: id) } }
cff30cde8e86824e372c0ca4675d0468
28.317308
292
0.614173
false
false
false
false
henriquecfreitas/diretop
refs/heads/master
Diretop/SimpleDataSource.swift
gpl-3.0
1
// // SimpleDataSource.swift // Diretop // // Created by Henrique on 22/04/17. // Copyright © 2017 Henrique. All rights reserved. // import UIKit class SimpleDataSource: NSObject { var data = Array<String>() public func addItenToDts(iten: String){ data.append(iten) } public func removeItenFromDts(index: Int){ data.remove(at: index) } public func setData(dataToSet: Array<String>){ data = dataToSet } } class SimpleTableViewDataSource: SimpleDataSource, UITableViewDataSource { var tableKey: String! init(tableKey: String) { super.init() self.tableKey = tableKey self.setData(dataToSet: getPersistedData()) } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let index = indexPath.item cell.textLabel?.text = data[index] return cell } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCellEditingStyle.delete) { let index = indexPath.item self.removeItenFromDts(index: index) tableView.reloadData() } } override func addItenToDts(iten: String) { super.addItenToDts(iten: iten) persistData() } override func removeItenFromDts(index: Int) { super.removeItenFromDts(index: index) persistData() } public func persistData() { UserDefaults.standard.set(data, forKey: tableKey) } public func getPersistedData() -> Array<String> { let data = UserDefaults.standard.array(forKey: tableKey) as! Array<String> return data } } class SimplePickerViewDataSource: SimpleDataSource, UIPickerViewDataSource, UIPickerViewDelegate { func onRowSelected() {/* override this method if you need to execute any actions after selecting another row ps: 9x2 eterno */} public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return data.count } public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return data.count > 0 && data.count > row ? data[row] : "" } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { onRowSelected() } }
1819af8c0ec497a90e4875eed787f6a3
28.43
134
0.648318
false
false
false
false
yanif/circator
refs/heads/master
MetabolicCompass/View Controller/Charts/ChartsViewController.swift
apache-2.0
1
// // ChartsViewController.swift // MetabolicCompass // // Created by Artem Usachov on 6/9/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import UIKit import Charts import HealthKit import MetabolicCompassKit import MCCircadianQueries import SwiftDate import Crashlytics enum DataRangeType : Int { case Week = 0 case Month case Year } class ChartsViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! private var rangeType = DataRangeType.Week private let barChartCellIdentifier = "BarChartCollectionCell" private let lineChartCellIdentifier = "LineChartCollectionCell" private let scatterChartCellIdentifier = "ScatterChartCollectionCell" private let chartCollectionDataSource = ChartCollectionDataSource() private let chartCollectionDelegate = ChartCollectionDelegate() private let chartsModel = BarChartModel() private var segmentControl: UISegmentedControl? = nil // MARK :- View life cycle override func viewDidLoad() { super.viewDidLoad() updateNavigationBar() registerCells() chartCollectionDataSource.model = chartsModel collectionView.delegate = chartCollectionDelegate collectionView.dataSource = chartCollectionDataSource } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateChartDataWithClean), name: UIApplicationWillEnterForegroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateChartsData), name: HMDidUpdatedChartsData, object: nil) chartCollectionDataSource.updateData() updateChartsData() logContentView() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) logContentView(false) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func logContentView(asAppear: Bool = true) { Answers.logContentViewWithName("Charts", contentType: asAppear ? "Appear" : "Disappear", contentId: NSDate().toString(DateFormat.Custom("YYYY-MM-dd:HH")), customAttributes: ["range": rangeType.rawValue]) } // MARK :- Base preparation func updateChartDataWithClean() { chartsModel.typesChartData = [:] IOSHealthManager.sharedManager.cleanCache() IOSHealthManager.sharedManager.collectDataForCharts() activityIndicator.startAnimating() } func updateChartsData () { if !activityIndicator.isAnimating() { activityIndicator.startAnimating() } chartsModel.getAllDataForCurrentPeriod({ self.activityIndicator.stopAnimating() self.collectionView.reloadData() }) } func registerCells () { let barChartCellNib = UINib(nibName: "BarChartCollectionCell", bundle: nil) collectionView?.registerNib(barChartCellNib, forCellWithReuseIdentifier: barChartCellIdentifier) let lineChartCellNib = UINib(nibName: "LineChartCollectionCell", bundle: nil) collectionView?.registerNib(lineChartCellNib, forCellWithReuseIdentifier: lineChartCellIdentifier) let scatterChartCellNib = UINib(nibName: "ScatterChartCollectionCell", bundle: nil) collectionView.registerNib(scatterChartCellNib, forCellWithReuseIdentifier: scatterChartCellIdentifier) } func updateNavigationBar () { let manageButton = ScreenManager.sharedInstance.appNavButtonWithTitle("Manage") manageButton.addTarget(self, action: #selector(manageCharts), forControlEvents: .TouchUpInside) let manageBarButton = UIBarButtonItem(customView: manageButton) self.navigationItem.leftBarButtonItem = manageBarButton self.navigationItem.title = NSLocalizedString("CHART", comment: "chart screen title") // let correlateButton = ScreenManager.sharedInstance.appNavButtonWithTitle("Correlate") // correlateButton.addTarget(self, action: #selector(correlateChart), forControlEvents: .TouchUpInside) // let corrButton = UIBarButtonItem(customView: correlateButton) // self.navigationItem.rightBarButtonItem = corrButton } @IBAction func rangeChanged(sender: UISegmentedControl) { self.segmentControl = sender // var showCorrelate = false // let correlateSegment = sender.numberOfSegments-1 switch sender.selectedSegmentIndex { case HealthManagerStatisticsRangeType.Month.rawValue: chartsModel.rangeType = .Month case HealthManagerStatisticsRangeType.Year.rawValue: chartsModel.rangeType = .Year break default: chartsModel.rangeType = .Week } logContentView() updateChartsData() } func manageCharts () { let manageController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("manageCharts") self.presentViewController(manageController, animated: true) {} } // func correlateChart () { // if let correlateController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("correlatePlaceholder") as? UIViewController { // let leftButton = UIBarButtonItem(image: UIImage(named: "close-button"), style: .Plain, target: self, action: #selector(dismissCorrelateChart)) // // self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) // self.navigationController?.pushViewController(correlateController, animated: true) // // } // } // // func dismissCorrelateChart() { // dismissViewControllerAnimated(true) { _ in // if let sc = self.segmentControl { // sc.selectedSegmentIndex = 0 // self.rangeChanged(sc) // } // } // } }
3118ec787f7fd0101e5101579bff37b3
39.877419
174
0.693971
false
false
false
false
GuiBayma/PasswordVault
refs/heads/develop
PasswordVault/Scenes/Groups/GroupsTableViewDataSource.swift
mit
1
// // GroupsTableViewDataSource.swift // PasswordVault // // Created by Guilherme Bayma on 7/26/17. // Copyright © 2017 Bayma. All rights reserved. // import UIKit import CoreData class GroupsTableViewDataSource: NSObject, UITableViewDataSource { // MARK: - Variables fileprivate var data: [NSManagedObject] = [] weak var tableView: UITableView? // MARK: - Set Data func setData(_ data: [NSManagedObject]) { self.data = data tableView?.reloadData() } // MARK: - Return data func getData(at index: Int) -> Group? { if let group = data[index] as? Group { return group } return nil } // MARK: - Add data func addData(_ group: Group) { data.append(group) tableView?.reloadData() } // MARK: - Delete data fileprivate func removeDataAt(_ indexPath: IndexPath) { if let group = data[indexPath.item] as? Group { if GroupManager.sharedInstance.delete(object: group) { data.remove(at: indexPath.item) tableView?.deleteRows(at: [indexPath], with: .automatic) } } } // MARK: - Data Source func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(for:indexPath) as GroupTableViewCell if let group = data[indexPath.item] as? Group { cell.configure(group) } return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { removeDataAt(indexPath) } } }
62dedde0729c8071e4537b43bea2eeda
24.419753
127
0.617776
false
false
false
false
akupara/Vishnu
refs/heads/master
Vishnu/Matsya/MatsyaContainerViewController.swift
mit
1
// // MatsyaContainerViewController.swift // Vishnu // // Created by Daniel Lu on 3/9/16. // Copyright © 2016 Daniel Lu. All rights reserved. // import UIKit public class MatsyaContainerViewController: UIViewController { enum PanelStatus { case RightExpaned case LeftExpanded case BothCollapsed } private var mainNavigationController:UINavigationController! private var rightPanel:UIViewController? private var leftPanel:UIViewController? private var mainViewGestures:[UISwipeGestureRecognizer] = [] private var leftViewGesture:UISwipeGestureRecognizer? private var rightViewGesture:UISwipeGestureRecognizer? private var currentPanelStatus:PanelStatus = .BothCollapsed internal var targetPosRate:CGFloat = 0.7 internal var targetSizeScaleRate:CGFloat = 1 public var positionRate:CGFloat { get { return targetPosRate } set { if newValue > 1 || newValue < 0 { targetPosRate = 0.7 } else { targetPosRate = newValue } } } public var mainViewScaleRate:CGFloat { get { return targetSizeScaleRate } set { if newValue > 1 || newValue < 0 { targetSizeScaleRate = 1 } else { targetSizeScaleRate = newValue } } } public var backgroundImage:UIImage! = nil public var backgroundView:UIView! = nil static let animationDuration:NSTimeInterval = 0.5 static let springWithDamping:CGFloat = 0.8 override public func viewDidLoad() { super.viewDidLoad() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MAKR: - MainViewController public func setMainViewController(viewController:UIViewController) { if mainNavigationController != nil { if mainViewGestures.count > 0 { for gesture in mainViewGestures { mainNavigationController.view.removeGestureRecognizer(gesture) } } mainNavigationController.view.removeFromSuperview() mainNavigationController.removeFromParentViewController() mainNavigationController = nil } if let navigation = viewController as? UINavigationController { mainNavigationController = navigation if let viewController = navigation.topViewController as? MatsyaContainerContent { viewController.delegate = self } } else { let navigation = UINavigationController(rootViewController: viewController) mainNavigationController = navigation if let mainController = viewController as? MatsyaContainerContent { mainController.delegate = self } } let index = view.subviews.count let leftGesture = setupSwipeGestureRecognizerViewController(viewController, direction: .Left) let rightGesture = setupSwipeGestureRecognizerViewController(viewController, direction: .Right) mainViewGestures.append(leftGesture) mainViewGestures.append(rightGesture) view.insertSubview(viewController.view, atIndex: index) addChildViewController(viewController) viewController.didMoveToParentViewController(self) } public func setMainViewControllerInStoryboard(storyboard:UIStoryboard, withIdentifier identifier:String, params: [String:AnyObject]! = nil) { let viewController = storyboard.instantiateViewControllerWithIdentifier(identifier) setupParams(viewController, params: params) setMainViewController(viewController) } public func setMainViewControllerWithStoryboardInitialController(storyboard: UIStoryboard, params:[String:AnyObject]! = nil) { if let viewController = storyboard.instantiateInitialViewController() { setupParams(viewController, params: params) setMainViewController(viewController) } } // MARK: - Panel update public func setLeftPanel<T: UIViewController where T:MatsyaContainerContent> (panel: T) { if currentPanelStatus == .LeftExpanded { hidePanel(leftPanel) if let gesture = leftViewGesture { leftPanel?.view.removeGestureRecognizer(gesture) leftViewGesture = nil } leftPanel = nil } leftPanel = panel leftViewGesture = setupSwipeGestureRecognizerViewController(panel, direction: .Left) panel.delegate = self } public func setRightPanen<T: UIViewController where T:MatsyaContainerContent> (panel: T) { if currentPanelStatus == .RightExpaned { hidePanel(rightPanel) if let gesture = rightViewGesture { rightPanel?.view.removeGestureRecognizer(gesture) } rightPanel = nil } rightPanel = panel rightViewGesture = setupSwipeGestureRecognizerViewController(panel, direction: .Right) panel.delegate = self } //MARK: - panel toggle and main view navigation public func toggleRightPanel() { if currentPanelStatus == .RightExpaned { hidePanel(rightPanel) } else if let _ = rightPanel { currentPanelStatus = .RightExpaned let targetPosition = (0 - (view.frame.size.width * targetPosRate)) showPanel(rightPanel, mainViewPosition: targetPosition) } } public func toggleLeftPanel() { if currentPanelStatus == .LeftExpanded { hidePanel(leftPanel) } else if let _ = leftPanel { let targetPosition = view.frame.size.width * targetPosRate showPanel(leftPanel, mainViewPosition: targetPosition) } } public func collapsePanels(completion:((Bool) -> Void)! = nil) { if currentPanelStatus == .LeftExpanded { hidePanel(leftPanel, completion: completion) } else if currentPanelStatus == .RightExpaned { hidePanel(rightPanel, completion: completion) } } public func presentViewController(viewController: UIViewController, animated:Bool, params:[String:AnyObject]! = nil) { super.presentViewController(viewController, animated: animated, withParams: params, inViewController: mainNavigationController) } public func presentViewControllerInStoryboard(storyboard:UIStoryboard, withIdentifier identifier:String, animated:Bool, params: [String: AnyObject]! = nil) { let viewController = storyboard.instantiateViewControllerWithIdentifier(identifier) presentViewController(viewController, animated: animated, params: params) } public func presentInitialViewControllerInStoryboard(storyboard:UIStoryboard, animated:Bool, params:[String:AnyObject]! = nil) { if let viewController = storyboard.instantiateInitialViewController() { presentViewController(viewController, animated: animated, params: params) } } // MARK: - internal messages internal func animateMainView(targetPosition:CGFloat, newSize: CGSize! = nil, completion: ((Bool) -> Void)! = nil) { UIView.animateWithDuration(MatsyaContainerViewController.animationDuration, delay: 0.0, usingSpringWithDamping: MatsyaContainerViewController.springWithDamping, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: { [unowned self] in self.mainNavigationController.view.frame.origin.x = targetPosition if newSize != nil { self.mainNavigationController.view.frame.size = newSize self.mainNavigationController.view.layoutIfNeeded() } }, completion: completion) } internal func hidePanel(panel:UIViewController?, completion: ((Bool) -> Void)! = nil) { currentPanelStatus = .BothCollapsed if let viewController = panel { animateMainView(0.0, newSize: view.frame.size) { [unowned self] (finished:Bool) in self.showShadowForMainViewController(false) viewController.view.removeFromSuperview() viewController.removeFromParentViewController() if completion != nil { completion(finished) } } } } internal func showPanel(panel:UIViewController?, mainViewPosition position:CGFloat) { if let viewController = panel { view.insertSubview(viewController.view, belowSubview: mainNavigationController.view) addChildViewController(viewController) viewController.didMoveToParentViewController(self) let newSize:CGSize! if targetSizeScaleRate < 1 { let newWidth = mainNavigationController.view.frame.width * targetSizeScaleRate let newHeight = mainNavigationController.view.frame.height * targetSizeScaleRate newSize = CGSizeMake(newWidth, newHeight) } else { newSize = nil } showShadowForMainViewController(true) layoutPanelForPosition(position, panel: panel) animateMainView(position, newSize: newSize) } } internal func showShadowForMainViewController(showShadow:Bool = true) { if (showShadow) { mainNavigationController.view.layer.shadowOpacity = 0.8 } else { mainNavigationController.view.layer.shadowOpacity = 0.0 } } internal func layoutPanelForPosition(position:CGFloat, panel:UIViewController?) { if position == 0.0 { return } if let viewController = panel { let maxWidth = view.frame.width let height = view.frame.height let width = abs(position) let xPos:CGFloat! if position > 0 { xPos = 0.0 } else { xPos = maxWidth - width } let targetFrame = CGRectMake(xPos, 0.0, width, height) viewController.view.frame = targetFrame viewController.view.layoutIfNeeded() } } internal func setupSwipeGestureRecognizerViewController(viewController:UIViewController, direction:UISwipeGestureRecognizerDirection) -> UISwipeGestureRecognizer { let gesture = UISwipeGestureRecognizer(target: self, action: #selector(MatsyaContainerViewController.gestureSwipeHandler(_:))) gesture.numberOfTouchesRequired = 1 gesture.direction = direction viewController.view.addGestureRecognizer(gesture) return gesture } // MARK: - Gesture Recogniser Handlers public func gestureSwipeHandler(sender:UISwipeGestureRecognizer) { if sender.view == leftPanel?.view { leftPanelSwiped(sender) } else if sender.view == rightPanel?.view { rightPanelSwiped(sender) } else if sender.view == mainNavigationController.view { mainViewSwiped(sender) } } internal func leftPanelSwiped(gesture:UISwipeGestureRecognizer) { if currentPanelStatus == .LeftExpanded && gesture.direction == .Left { hidePanel(leftPanel) } } internal func rightPanelSwiped(gesture:UISwipeGestureRecognizer) { if currentPanelStatus == .RightExpaned && gesture.direction == .Right { hidePanel(rightPanel) } } internal func mainViewSwiped(gesture:UISwipeGestureRecognizer) { if gesture.direction == .Right { if currentPanelStatus == .BothCollapsed { toggleLeftPanel() } else if currentPanelStatus == .RightExpaned { hidePanel(rightPanel) } } else if gesture.direction == .Left { if currentPanelStatus == .BothCollapsed { toggleRightPanel() } else if currentPanelStatus == .LeftExpanded { hidePanel(leftPanel) } } } //MARK: - Background private func setupBackgroundImage() { if backgroundImage != nil { //Remove previous background view if backgroundView != nil { backgroundView.removeFromSuperview() backgroundView = nil } let imageView = UIImageView(image: backgroundImage) imageView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(imageView, atIndex: 0) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[imageView]|", options: [NSLayoutFormatOptions.AlignAllCenterX, NSLayoutFormatOptions.AlignAllCenterY], metrics: nil, views: ["imageView": imageView])) imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: imageView, attribute: .Width, multiplier: backgroundImage.size.height/backgroundImage.size.width, constant: 0)) // let rate = backgroundImage.size.width } } } @objc public protocol MatsyaContainerContent { weak var delegate:MatsyaContainerViewController? { get set } }
656dc24d398a8498ac217135c4d5641b
38.64723
232
0.640462
false
false
false
false
adobe-behancemobile/PeekPan
refs/heads/master
PeekPan/Demo/DemoViewController.swift
apache-2.0
1
/****************************************************************************** * * ADOBE CONFIDENTIAL * ___________________ * * Copyright 2016 Adobe Systems Incorporated * All Rights Reserved. * * This file is licensed to you 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. ******************************************************************************/ import UIKit import Foundation class DemoViewController : UIViewController, UIViewControllerPreviewingDelegate, PeekPanCoordinatorDelegate, PeekPanCoordinatorDataSource { var peekPanCoordinator: PeekPanCoordinator! @IBOutlet var percentageLabel: UILabel! @IBOutlet var redView: UIView! @IBOutlet var greenView: UIView! @IBOutlet var yellowView: UIView! override func viewDidLoad() { super.viewDidLoad() redView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.bounds.width, height: view.bounds.height)) greenView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: view.bounds.height)) yellowView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: view.bounds.height)) redView.backgroundColor = .red greenView.backgroundColor = .green yellowView.backgroundColor = .yellow view.addSubview(redView) view.addSubview(greenView) view.addSubview(yellowView) yellowView.addSubview(percentageLabel) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 9.0, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: view) peekPanCoordinator = PeekPanCoordinator(sourceView: view) peekPanCoordinator.delegate = self peekPanCoordinator.dataSource = self } } } // MARK: PeekPanCoordinatorDataSource func maximumIndex(for peekPanCoordinator: PeekPanCoordinator) -> Int { return 0 } func shouldStartFromMinimumIndex(for peekPanCoordinator: PeekPanCoordinator) -> Bool { return true } // MARK: PeekPanCoordinatorDelegate func peekPanCoordinatorBegan(_ peekPanCoordinator: PeekPanCoordinator) { greenView.frame.origin.x = peekPanCoordinator.startingPoint.x greenView.frame.size.width = peekPanCoordinator.sourceView.bounds.width - peekPanCoordinator.startingPoint.x yellowView.frame.origin.x = peekPanCoordinator.startingPoint.x } func peekPanCoordinatorEnded(_ peekPanCoordinator: PeekPanCoordinator) { greenView.frame.size.width = 0.0 yellowView.frame.size.width = 0.0 percentageLabel.text = "" } func peekPanCoordinatorUpdated(_ peekPanCoordinator: PeekPanCoordinator) { greenView.frame.origin.x = peekPanCoordinator.minimumPoint.x greenView.frame.size.width = peekPanCoordinator.maximumPoint.x - peekPanCoordinator.minimumPoint.x yellowView.frame.origin.x = peekPanCoordinator.minimumPoint.x yellowView.frame.size.width = peekPanCoordinator.percentage * (peekPanCoordinator.maximumPoint.x - peekPanCoordinator.minimumPoint.x); percentageLabel.text = String(format: "%.2f", Double(peekPanCoordinator.percentage)) percentageLabel.sizeToFit() percentageLabel.frame.origin = CGPoint(x: 0.0, y: yellowView.bounds.height/2) } // MARK: UIViewControllerPreviewingDelegate func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { peekPanCoordinator.setup() return nil } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { peekPanCoordinator.end(true) } }
ef62c5f2f2e0f963ca06c019654f09da
41.913462
143
0.678467
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
Objects/struct tables/ItemsTable.swift
gpl-2.0
1
// // ItemsTable.swift // GoD Tool // // Created by Stars Momodu on 24/03/2021. // import Foundation let itemsStruct = GoDStruct(name: "Item", format: [ .byte(name: "Pocket", description: "Which pocket in the bag the item goes in", type: .itemPocket), .byte(name: "Is Locked", description: "Can't be held or tossed", type: .bool), .byte(name: "Padding", description: "", type: .null), .byte(name: "Unknown Flag", description: "", type: .bool), .byte(name: "Battle Item ID", description: "Referred to by the ASM to determine item effect when used in battle", type: .uintHex), .short(name: "Price", description: "", type: .uint), .short(name: "Coupon Price", description: "", type: .uint), .short(name: "Hold Item ID", description: "Referred to by the ASM to determine item effect when held in battle", type: .uint), .word(name: "Padding 2", description: "", type: .null), .word(name: "Name ID", description: "", type: .msgID(file: .common_rel)), .word(name: "Description ID", description: "", type: .msgID(file: .typeAndFsysName(.msg, "pocket_menu"))), .word(name: "Parameter", description: "Determines effectiveness of item", type: .uint), .word(name: "Function Pointer", description: "Offset of ASM function the item triggers. This is set at run time but if you set it in the game file for an item that doesn't normally get set then it will keep that value.", type: .uintHex), .word(name: "Function Pointer 2", description: "Offset of ASM function the item triggers. This is set at run time but if you set it in the game file for an item that doesn't normally get set then it will keep that value.", type: .uintHex), .array(name: "Happiness effects", description: "Determines how much a pokemon's happiness changes when consuming this item. The amount varies based on the current happiness in 2 tiers.", property: .byte(name: "Happiness Effect", description: "", type: .int), count: 3) ]) let validItemStruct = GoDStruct(name: "Valid Item", format: [ .short(name: "Item ID", description: "", type: .itemID) ]) #if GAME_XD let itemsTable = CommonStructTable(index: .Items, properties: itemsStruct, documentByIndex: false) let validItemsTable = CommonStructTable(index: .ValidItems, properties: validItemStruct) #else let itemsTable = GoDStructTable(file: .dol, properties: itemsStruct, documentByIndex: false) { (file) -> Int in kFirstItemOffset } numberOfEntriesInFile: { (file) -> Int in kNumberOfItems } let validItemsTable = GoDStructTable(file: .dol, properties: validItemStruct) { (file) -> Int in return kFirstValidItemOffset } numberOfEntriesInFile: { (file) -> Int in return 1220 } let validItemStruct2 = GoDStruct(name: "Valid Item 2", format: [ .short(name: "Item ID", description: "", type: .itemID) ]) let validItemsTable2 = GoDStructTable(file: .dol, properties: validItemStruct2) { (file) -> Int in return kFirstValidItem2Offset } numberOfEntriesInFile: { (file) -> Int in return 1220 } #endif
cf84c9198391ed54021dc49283a1f501
50.614035
269
0.717539
false
false
false
false
eneko/SourceDocs
refs/heads/main
Sources/SourceDocsLib/PackageProcessor/PackageProcessor.swift
mit
1
// // PackageProcessor.swift // // // Created by Eneko Alonso on 5/1/20. // import Foundation import Rainbow import ProcessRunner import MarkdownGenerator public final class PackageProcessor { public let inputPath: URL public let outputPath: URL public let reproducibleDocs: Bool public var clustersEnabled: Bool = true let canRenderDOT: Bool let packageDump: PackageDump let packageDependencyTree: PackageDependency public enum Error: Swift.Error { case invalidInput } static var canRenderDOT: Bool { let result = try? system(command: "which dot", captureOutput: true) return result?.standardOutput.isEmpty == false } public init(inputPath: String, outputPath: String, reproducibleDocs: Bool) throws { self.inputPath = URL(fileURLWithPath: inputPath) self.outputPath = URL(fileURLWithPath: outputPath) self.reproducibleDocs = reproducibleDocs canRenderDOT = Self.canRenderDOT let path = self.inputPath.appendingPathComponent("Package.swift").path guard FileManager.default.fileExists(atPath: path) else { throw Error.invalidInput } try PackageLoader.resolveDependencies(at: inputPath) packageDump = try PackageLoader.loadPackageDump(from: inputPath) packageDependencyTree = try PackageLoader.loadPackageDependencies(from: inputPath) } public func run() throws { fputs("Processing package...\n".green, stdout) try createOutputFolderIfNeeded() try generateGraphs() let content: [MarkdownConvertible] = [ MarkdownHeader(title: "Package: **\(packageDump.name)**"), renderProductsSection(), renderModulesSection(), renderExternalDependenciesSection(), renderRequirementsSection(), DocumentationGenerator.generateFooter(reproducibleDocs: reproducibleDocs) ] let file = MarkdownFile(filename: "Package", basePath: outputPath.path, content: content) fputs(" Writing \(file.filePath)", stdout) try file.write() fputs(" ✔\n".green, stdout) fputs("Done 🎉\n".green, stdout) } func generateGraphs() throws { let modules = ModuleGraphGenerator(basePath: outputPath, packageDump: packageDump) modules.canRenderDOT = canRenderDOT modules.clustersEnabled = clustersEnabled try modules.run() let dependencies = DependencyGraphGenerator(basePath: outputPath, dependencyTree: packageDependencyTree) dependencies.canRenderDOT = canRenderDOT dependencies.clustersEnabled = clustersEnabled try dependencies.run() } func createOutputFolderIfNeeded() throws { if FileManager.default.fileExists(atPath: outputPath.path) { return } try FileManager.default.createDirectory(at: outputPath, withIntermediateDirectories: true, attributes: nil) } func renderProductsSection() -> MarkdownConvertible { if packageDump.products.isEmpty { return "" } let rows = packageDump.products.map { productDescription -> [String] in let name = productDescription.name let type = productDescription.type.label let targets = productDescription.targets return [name, type, targets.joined(separator: ", ")] } return [ MarkdownHeader(title: "Products", level: .h2), "List of products in this package:", MarkdownTable(headers: ["Product", "Type", "Targets"], data: rows), "_Libraries denoted 'automatic' can be both static or dynamic._" ] } func renderModulesSection() -> MarkdownConvertible { return [ MarkdownHeader(title: "Modules", level: .h2), renderTargets(), renderModuleGraph() ] } func renderModuleGraph() -> MarkdownConvertible { let url = outputPath.appendingPathComponent("PackageModules.png") guard FileManager.default.fileExists(atPath: url.path) else { return "" } return [ MarkdownHeader(title: "Module Dependency Graph", level: .h3), "[![Module Dependency Graph](PackageModules.png)](PackageModules.png)" ] } func renderTargets() -> MarkdownConvertible { let rows = packageDump.targets.map { targetDescription -> [String] in let name = targetDescription.name let type = targetDescription.type.rawValue.capitalized let dependencies = targetDescription.dependencies.map { $0.label }.sorted() return [name, type, dependencies.joined(separator: ", ")] } let regularRows = rows.filter { $0[1] != "Test" } let testRows = rows.filter { $0[1] == "Test" } return [ MarkdownHeader(title: "Program Modules", level: .h3), MarkdownTable(headers: ["Module", "Type", "Dependencies"], data: regularRows), MarkdownHeader(title: "Test Modules", level: .h3), MarkdownTable(headers: ["Module", "Type", "Dependencies"], data: testRows) ] } func renderExternalDependenciesSection() -> MarkdownConvertible { let title = MarkdownHeader(title: "External Dependencies", level: .h2) if packageDump.dependencies.isEmpty { return [ title, "This package has zero dependencies 🎉" ] } return [ title, MarkdownHeader(title: "Direct Dependencies", level: .h3), renderDependenciesTable(), MarkdownHeader(title: "Resolved Dependencies", level: .h3), renderDependencyTree(dependency: packageDependencyTree), renderExternalDependenciesGraph() ] } func renderDependenciesTable() -> MarkdownConvertible { let sortedDependencies = packageDump.dependencies.sorted { $0.label < $1.label } let rows = sortedDependencies.map { dependency -> [String] in let name = MarkdownLink(text: dependency.label, url: dependency.url).markdown let versions = dependency.requirementDescription return [name, versions] } return MarkdownTable(headers: ["Package", "Versions"], data: rows) } func renderDependencyTree(dependency: PackageDependency) -> MarkdownConvertible { let versionedName = "\(dependency.name) (\(dependency.version))" let link: MarkdownConvertible = dependency.url.hasPrefix("http") ? MarkdownLink(text: versionedName, url: dependency.url) : versionedName let items = [link] + dependency.dependencies.map(renderDependencyTree) return MarkdownList(items: items) } func renderExternalDependenciesGraph() -> MarkdownConvertible { guard canRenderDOT else { return "" } return [ MarkdownHeader(title: "Package Dependency Graph", level: .h3), "[![Package Dependency Graph](PackageDependencies.png)](PackageDependencies.png)" ] } func renderRequirementsSection() -> MarkdownConvertible { return [ MarkdownHeader(title: "Requirements", level: .h2), renderPlatforms() ] } func renderPlatforms() -> MarkdownConvertible { if packageDump.platforms.isEmpty { return "" } let rows = packageDump.platforms.map { platform -> [String] in let name = platform.platformName.replacingOccurrences(of: "os", with: "OS") let version = platform.version ?? "" return [name, version] } return [ MarkdownHeader(title: "Minimum Required Versions", level: .h3), MarkdownTable(headers: ["Platform", "Version"], data: rows) ] } }
147c0a5e44d22ada19c9e4b65ec8f946
36.820755
112
0.624345
false
false
false
false
TableBooking/ios-client
refs/heads/master
TableBooking/HistoryViewController.swift
mit
1
// // HistoryViewController.swift // TableBooking // // Created by Nikita Kirichek on 11/30/16. // Copyright © 2016 Nikita Kirichek. All rights reserved. // import UIKit class HistoryViewController: UIViewController { let numberOfSectionsForTable = 2 let heightForCell = 130 @IBOutlet weak var orderHistory: UITableView! override func viewDidLoad() { super.viewDidLoad() orderHistory.backgroundColor = Color.TBBackground navigationController?.navigationBar.barTintColor = Color.TBGreen navigationController?.navigationBar.barStyle = .black; navigationItem.title = "History" // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension HistoryViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(heightForCell) } func numberOfSections(in tableView: UITableView) -> Int { return numberOfSectionsForTable } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "historyItemCell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! HistoryItemTableViewCell return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Active" case 1: return "Previous" default: return "" } } }
b39111edd492d51cbfb0bfbb2aaa5fc4
25.05618
125
0.658473
false
false
false
false
kyleYang/KYNavigationFadeManager
refs/heads/master
KYNavigationFadeManager/TableViewController.swift
mit
1
// // TableViewController.swift // KYNavigationFadeManager // // Created by Kyle on 2017/5/8. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit open class TableViewController: UIViewController { let tableView = UITableView(frame: .zero, style: .plain) var fadeManager : KYNavigationFadeManager! var shareButton : UIButton! var backButton : UIButton! var backBarItem : UIBarButtonItem! public var shouldeHiddenTitle : Bool = true override open func viewDidLoad() { super.viewDidLoad() self.extendedLayoutIncludesOpaqueBars = true; self.automaticallyAdjustsScrollViewInsets = false if #available(iOS 11.0, *) { self.tableView.contentInsetAdjustmentBehavior = .never } else { // Fallback on earlier versions } self.tableView.dataSource = self self.tableView.delegate = self self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "tablecell") self.view.addSubview(self.tableView); self.tableView.translatesAutoresizingMaskIntoConstraints = false self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[table]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["table":self.tableView])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[table]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["table":self.tableView])) let headerView = UIImageView(frame: CGRect(x:0,y:0,width:0,height:200)) headerView.image = UIImage(named:"header") headerView.contentMode = .scaleAspectFill self.tableView.tableHeaderView = headerView self.backButton = UIButton() self.backButton.setImage(UIImage(named:"navigationBar_back"), for: .normal) self.backButton.frame = CGRect(x: 0, y: 0, width: 64, height: 64) self.backButton.addTarget(self, action: #selector(TableViewController.buttonTapped(sender:)), for: .touchUpInside) self.backBarItem = UIBarButtonItem(customView: self.backButton); self.navigationItem.leftBarButtonItem = self.backBarItem self.shareButton = UIButton() self.shareButton.setImage(UIImage(named:"navi_collect"), for: .normal) self.shareButton.frame = CGRect(x: 0, y: 0, width: 64, height: 64) let shareBarItem = UIBarButtonItem(customView: self.shareButton); self.navigationItem.rightBarButtonItems = [shareBarItem] self.fadeManager = KYNavigationFadeManager(viewController: self, scollView: self.tableView) self.fadeManager.allowTitleHidden = shouldeHiddenTitle self.fadeManager.zeroAlphaOffset = 0; self.fadeManager.fullAlphaOffset = 200; } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.fadeManager.viewWillAppear(animated) } open override func viewWillDisappear(_ animated: Bool) { self.fadeManager.viewWillDisappear(animated) super .viewWillDisappear(animated) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func buttonTapped(sender: UIButton) { self.navigationController?.popViewController(animated: true) } deinit { print("TableViewController deinit") } open override var preferredStatusBarStyle: UIStatusBarStyle { if (self.fadeManager != nil && self.fadeManager.state == .faded) { return .lightContent; } return .default; } } extension TableViewController : UITableViewDelegate,UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell") cell?.textLabel?.text = String(format: "%ld", arguments: [indexPath.row]) return cell! } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = AfterTableViewController(nibName: nil, bundle: nil); vc.title = "下一个" self.navigationController?.pushViewController(vc, animated: true) } } extension TableViewController : KYNavigationFadeManagerDelegate { public func fadeManagerBarItemColorChange(_ manager: KYNavigationFadeManager, barItem: UIBarButtonItem, alpha: CGFloat) -> Bool { if (barItem == self.backBarItem) { return false } if (alpha > 0.3) { self.shareButton.setImage(UIImage(named:"navi_collect"), for: .normal) }else { self.shareButton.setImage(UIImage(named:"navi_collect_fade"), for: .normal) } return true } public func fadeManager(_ manager: KYNavigationFadeManager, changeState: KYNavigationFadeState) { self.setNeedsStatusBarAppearanceUpdate() } }
78b01c3eb100221f552866bd8d780414
34.360544
189
0.683147
false
false
false
false
gkaimakas/ReactiveBluetooth
refs/heads/master
Example/ReactiveBluetooth/Views/ActionButton.swift
mit
1
// // ActionButton.swift // ReactiveBluetooth_Example // // Created by George Kaimakas on 06/03/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import Foundation import ReactiveCocoa import ReactiveSwift import Result import UIKit public class ActionButton: UIButton { fileprivate let activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) override public init(frame: CGRect) { super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } private func configure() { addSubview(activityIndicator) activityIndicator.activityIndicatorViewStyle = .gray activityIndicator.hidesWhenStopped = true activityIndicator.color = tintColor bringSubview(toFront: activityIndicator) layer.borderColor = tintColor.cgColor layer.borderWidth = 0.5 contentEdgeInsets = UIEdgeInsets(top: 8, left: 32, bottom: 8, right: 32) } override public func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = self.frame.height/2 activityIndicator.frame = CGRect(x: frame.width-28, y: (frame.height - 24)/2, width: 24, height: 24) } } extension Reactive where Base: ActionButton { public var action: CocoaAction<Base>? { get { return self.pressed } nonmutating set { self.pressed = newValue if let _action = newValue { base.activityIndicator.reactive.isAnimating <~ _action.isExecuting.producer } } } }
d1f66a9b4f4de941f5cec265d776267c
24.984615
113
0.646536
false
false
false
false
rringham/webviewqueue
refs/heads/master
src/WebViewQueue/WebViewQueue/ViewController.swift
mit
1
// // ViewController.swift // WebViewQueue // // Created by Robert Ringham on 10/10/16. // import Foundation import UIKit import WebKit import JavaScriptCore class RequestOperation { var operationId: Int init(_ operationId: Int) { self.operationId = operationId } } class ViewController: UIViewController, WKScriptMessageHandler, WKUIDelegate { var webView: WKWebView? var contentController: WKUserContentController? var requestQueue: [RequestOperation] = [RequestOperation]() var operationsQueued = 0 var operationsStarted = 0 var operationsCompleted = 0 override func viewDidLoad() { super.viewDidLoad() contentController = WKUserContentController() contentController?.addScriptMessageHandler(self, name: "continueHandler") let config = WKWebViewConfiguration() config.userContentController = contentController! webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), configuration: config) webView?.UIDelegate = self webView?.loadHTMLString(getHtml(), baseURL: nil) // view.addSubview(webView!) } func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { let alert = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.Alert); alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel) { _ in completionHandler()}); self.presentViewController(alert, animated: true, completion: {}); } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { var queued = false if let queuedParam = message.body["queued"] as? Bool { queued = queuedParam } if let dataRequestProcessId = message.body["dataRequestProcessId"] as? Int { print("requested data for process id \(dataRequestProcessId)") self.webView?.evaluateJavaScript("continueLongRunningProcess(\(dataRequestProcessId), \(queued));", completionHandler: { (result, error) in print("evaluateJavaScript completion handler for \(queued ? "queued" : "unqueued") DATA REQUEST for js operation \(dataRequestProcessId) done") }) } if let networkRequestProcessId = message.body["networkRequestProcessId"] as? Int { print("requested data for process id \(networkRequestProcessId)") self.webView?.evaluateJavaScript("finishLongRunningProcess(\(networkRequestProcessId), \(queued));", completionHandler: { (result, error) in print("evaluateJavaScript completion handler for \(queued ? "queued" : "unqueued") NETWORK REQUEST for js operation \(networkRequestProcessId) done") }) } if let completedProcessId = message.body["completedProcessId"] as? Int { print("completed process id \(completedProcessId)") self.operationsCompleted += 1 if queued { dequeueAndSubmitNextRequest() } } if let pongId = message.body["pongId"] as? Int { print("pong <- JS \(pongId)") } } @IBAction func startWithNoProcessQueuing(sender: AnyObject) { operationsQueued = 0 operationsStarted = 0 operationsCompleted = 0 for operationId in 1...10 { print("started process \(operationId)") self.operationsQueued += 1 self.operationsStarted += 1 self.webView?.evaluateJavaScript("someLongRunningProcess(\(operationId), false);", completionHandler: { (result, error) in print("evaluateJavaScript completion handler for unqueued START js operation \(operationId) done") }) } // startPings() } @IBAction func startWithProcessQueuing(sender: AnyObject) { operationsStarted = 0 operationsCompleted = 0 for operationId in 1...10 { self.operationsQueued += 1 requestQueue.append(RequestOperation(operationId)) } dequeueAndSubmitNextRequest() // startPings() } @IBAction func printStats(sender: AnyObject) { print("") print("operations queued: \(operationsQueued)") print("operations started: \(operationsStarted)") print("operations completed: \(operationsCompleted)") print("") } func dequeueAndSubmitNextRequest() { if let requestOperation = self.requestQueue.first { self.requestQueue.removeFirst() print("started process \(requestOperation.operationId)") self.operationsStarted += 1 self.webView?.evaluateJavaScript("someLongRunningProcess(\(requestOperation.operationId), true);", completionHandler: { (result, error) in print("evaluateJavaScript completion handler for queued START js operation \(requestOperation.operationId) done") }) } } func startPings() { dispatch_async(dispatch_get_main_queue()) { for pingId in 1...100 { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(pingId * 1000) * NSEC_PER_MSEC)), dispatch_get_main_queue(), { () -> Void in print("ping -> JS \(pingId)") self.webView?.evaluateJavaScript("ping(\(pingId));", completionHandler: nil) }) } } } func getHtml() -> String { let fileLocation = NSBundle.mainBundle().pathForResource("poc", ofType: "html")! do { return try String(contentsOfFile: fileLocation) } catch { return "" } } }
be76cf749bcb5aa4623c1ef22aec1136
37.371795
165
0.624123
false
false
false
false
Rapid-SDK/ios
refs/heads/master
Examples/RapiDO - ToDo list/RapiDO macOS/AppDelegate.swift
mit
1
// // AppDelegate.swift // ExampleMacOSApp // // Created by Jan on 15/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import Cocoa import Rapid @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var newTaskWindows: [NSWindow] = [] func applicationDidFinishLaunching(_ aNotification: Notification) { } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } @IBAction func newDocument(_ sender: Any) { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) let window = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "AddTaskWindow")) as! NSWindowController window.showWindow(self) if let window = window.window { newTaskWindows.append(window) } } func updateTask(_ task: Task) { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) let window = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "AddTaskWindow")) as! NSWindowController (window.contentViewController as? TaskViewController)?.task = task window.showWindow(self) if let window = window.window { newTaskWindows.append(window) } } class func closeWindow(_ window: NSWindow) { window.close() windowClosed(window) } class func windowClosed(_ window: NSWindow) { let delegate = NSApplication.shared.delegate as? AppDelegate if let index = delegate?.newTaskWindows.index(of: window) { delegate?.newTaskWindows.remove(at: index) } } }
23e361915f72c6288f59df415fd87aca
30.964286
149
0.669832
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
iOS/Inspector/AccountInspectorViewController.swift
mit
1
// // AccountInspectorViewController.swift // NetNewsWire-iOS // // Created by Maurice Parker on 5/17/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import UIKit import Account class AccountInspectorViewController: UITableViewController { static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0) @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var activeSwitch: UISwitch! @IBOutlet weak var deleteAccountButton: VibrantButton! var isModal = false weak var account: Account? override func viewDidLoad() { super.viewDidLoad() guard let account = account else { return } nameTextField.placeholder = account.defaultName nameTextField.text = account.name nameTextField.delegate = self activeSwitch.isOn = account.isActive navigationItem.title = account.nameForDisplay if account.type != .onMyMac { deleteAccountButton.setTitle(NSLocalizedString("Remove Account", comment: "Remove Account"), for: .normal) } if isModal { let doneBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done)) navigationItem.leftBarButtonItem = doneBarButtonItem } tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") } override func viewWillDisappear(_ animated: Bool) { account?.name = nameTextField.text account?.isActive = activeSwitch.isOn } @objc func done() { dismiss(animated: true) } @IBAction func credentials(_ sender: Any) { guard let account = account else { return } switch account.type { case .feedbin: let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "FeedbinAccountNavigationViewController") as! UINavigationController let addViewController = navController.topViewController as! FeedbinAccountViewController addViewController.account = account navController.modalPresentationStyle = .currentContext present(navController, animated: true) case .feedWrangler: let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "FeedWranglerAccountNavigationViewController") as! UINavigationController let addViewController = navController.topViewController as! FeedWranglerAccountViewController addViewController.account = account navController.modalPresentationStyle = .currentContext present(navController, animated: true) case .newsBlur: let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "NewsBlurAccountNavigationViewController") as! UINavigationController let addViewController = navController.topViewController as! NewsBlurAccountViewController addViewController.account = account navController.modalPresentationStyle = .currentContext present(navController, animated: true) case .inoreader, .bazQux, .theOldReader, .freshRSS: let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "ReaderAPIAccountNavigationViewController") as! UINavigationController let addViewController = navController.topViewController as! ReaderAPIAccountViewController addViewController.accountType = account.type addViewController.account = account navController.modalPresentationStyle = .currentContext present(navController, animated: true) default: break } } @IBAction func deleteAccount(_ sender: Any) { guard let account = account else { return } let title = NSLocalizedString("Remove Account", comment: "Remove Account") let message: String = { switch account.type { case .feedly: return NSLocalizedString("Are you sure you want to remove this account? NetNewsWire will no longer be able to access articles and feeds unless the account is added again.", comment: "Log Out and Remove Account") default: return NSLocalizedString("Are you sure you want to remove this account? This cannot be undone.", comment: "Remove Account") } }() let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel") let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) alertController.addAction(cancelAction) let markTitle = NSLocalizedString("Remove", comment: "Remove") let markAction = UIAlertAction(title: markTitle, style: .default) { [weak self] (action) in guard let self = self, let account = self.account else { return } AccountManager.shared.deleteAccount(account) if self.isModal { self.dismiss(animated: true) } else { self.navigationController?.popViewController(animated: true) } } alertController.addAction(markAction) alertController.preferredAction = markAction present(alertController, animated: true) } } // MARK: Table View extension AccountInspectorViewController { var hidesCredentialsSection: Bool { guard let account = account else { return true } switch account.type { case .onMyMac, .cloudKit, .feedly: return true default: return false } } override func numberOfSections(in tableView: UITableView) -> Int { guard let account = account else { return 0 } if account == AccountManager.shared.defaultAccount { return 1 } else if hidesCredentialsSection { return 2 } else { return super.numberOfSections(in: tableView) } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let account = account else { return nil } if section == 0 { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView headerView.imageView.image = AppAssets.image(for: account.type) return headerView } else { return super.tableView(tableView, viewForHeaderInSection: section) } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell if indexPath.section == 1, hidesCredentialsSection { cell = super.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 2)) } else { cell = super.tableView(tableView, cellForRowAt: indexPath) } return cell } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { if indexPath.section > 0 { return true } return false } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.selectRow(at: nil, animated: true, scrollPosition: .none) } } // MARK: UITextFieldDelegate extension AccountInspectorViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
338d30d0d4a291c41ec2ebfc2b6df91b
33.362745
215
0.763481
false
false
false
false
ndevenish/KerbalHUD
refs/heads/master
KerbalHUD/RPMTextFile.swift
mit
1
// // RPMTextFile.swift // KerbalHUD // // Created by Nicholas Devenish on 03/09/2015. // Copyright © 2015 Nicholas Devenish. All rights reserved. // import Foundation class RPMTextFileWidget : Widget { private(set) var bounds : Bounds private(set) var variables : [String] private let drawing : DrawingTools private let rpm : RPMTextFile private var data : [String : Any]? = nil init(tools : DrawingTools, bounds : Bounds) { self.bounds = bounds self.drawing = tools let url = NSBundle.mainBundle().URLForResource("RPMHUD", withExtension: "txt") let rpm = RPMTextFile(file: url!) rpm.prepareTextFor(1.0/20, screenHeight: 1, font: self.drawing.defaultTextRenderer, tools: tools) self.rpm = rpm self.variables = rpm.variables } func update(data : [String : JSON]) { var c : [String : Any] = [:] for (x, y) in data { c[x] = y } self.data = c } func draw() { if let data = self.data { self.rpm.draw(data) } } } struct TextDrawInfo { var position : Point2D var color : Color4 var size : Float var string : String } protocol PageEntry { /// Is this entry dynamic, or can it's behaviour change? var isDynamic : Bool { get } /// Is this entry always the same length? var isFixedLength : Bool { get } /// Can, or does this entry, affect state? var affectsState : Bool { get } var affectsOffset : Bool { get } var affectsTextScale : Bool { get } var affectsColor : Bool { get } var affectsFont : Bool { get } /// What is the length, or at least, current length var length : Int { get } var state : FormatState? { get set } // Position, in lines, where we would expect to start var position : Point2D? { get set } var variables : [String] { get } func process(data : [String : Any]) -> TextDrawInfo } class FixedLengthEntry : PageEntry { private(set) var length : Int init(length : Int) { self.length = length } var isDynamic : Bool { return false } var isFixedLength : Bool { return true } var affectsState : Bool { return false } var affectsOffset : Bool { return false } var affectsTextScale : Bool { return false } var affectsColor : Bool { return false } var affectsFont : Bool { return false } var state : FormatState? var position : Point2D? = nil let variables : [String] = [] func process(data : [String : Any]) -> TextDrawInfo { fatalError() } } class EmptyString : FixedLengthEntry { } class FixedString : FixedLengthEntry { private(set) var text : String init(text: String) { self.text = text super.init(length: text.characters.count) } override func process(data : [String : Any]) -> TextDrawInfo { return TextDrawInfo(position: position!+state!.offset, color: state!.color, size: 1, string: text) } } class FormatEntry : PageEntry { var variable : String var alignment : Int var format : String var variables : [String] { return variable.isEmpty ? [] : [variable] } private(set) var length : Int var isDynamic : Bool { return true } var isFixedLength : Bool { return stringFormatter.fixedLength } var affectsState : Bool { return affectsOffset || affectsTextScale || affectsColor || affectsFont } private(set) var affectsOffset : Bool private(set) var affectsTextScale : Bool private(set) var affectsColor : Bool private(set) var affectsFont : Bool var state : FormatState? var position : Point2D? = nil var stringFormatter : StringFormatter init(variable: String, alignment: Int, format: String) { self.variable = variable self.alignment = alignment self.format = format self.length = 0 stringFormatter = getFormatterForString(format) if (stringFormatter.fixedLength) { self.length = stringFormatter.length } affectsColor = false affectsTextScale = false affectsFont = false affectsOffset = false } func process(data : [String : Any]) -> TextDrawInfo { let dataVar = "rpm." + variable return TextDrawInfo(position: position!+state!.offset, color: state!.color, size: 1, string: stringFormatter.format(data[dataVar])) } } class Tag : FixedLengthEntry { func changeState(from: FormatState) -> FormatState { fatalError() } // var affectsOffset : Bool { return false } // var affectsTextScale : Bool { return false } // var affectsColor : Bool { return false } // var affectsFont : Bool { return false } // override var affectsState : Bool { return true } init() { super.init(length: 0) } } class ColorTag : Tag { var text : String override var affectsColor : Bool { return true } init(value : String) { text = value } override func changeState(from: FormatState) -> FormatState { fatalError() } } class NudgeTag : Tag { var value : Float var x : Bool init(value : Float, x : Bool) { self.value = value self.x = x } override var affectsOffset : Bool { return true } override func changeState(from: FormatState) -> FormatState { if x { return FormatState(prior: from, offset: Point2D(value, from.offset.y)) } else { return FormatState(prior: from, offset: Point2D(from.offset.x, value)) } } } class WidthTag : Tag { enum WidthType { case Normal case Half case Double } var type : WidthType = .Normal init(type : WidthType) { self.type = type } override var affectsTextScale : Bool { return true } override func changeState(from: FormatState) -> FormatState { return FormatState(prior: from, textSize: type) } } struct FormatState { var offset : Point2D var textSize : WidthTag.WidthType var color : Color4 var font : String init(prior: FormatState) { self.offset = prior.offset self.textSize = prior.textSize self.color = prior.color self.font = prior.font } init(prior: FormatState, offset: Point2D) { self.init(prior: prior) self.offset = offset } init(prior: FormatState, textSize: WidthTag.WidthType) { self.init(prior: prior) self.textSize = textSize } init() { self.offset = Point2D(0,0) self.textSize = .Normal self.color = Color4.White self.font = "" } } class RPMTextFile { private(set) var lineHeight : Float = 0 private(set) var screenHeight : Float = 0 var fixedEntries : [PageEntry] = [] var dynamicEntries : [PageEntry] = [] var dynamicLines : [[PageEntry]] = [] let textFileData : String var text : TextRenderer? = nil var drawing : DrawingTools? = nil private(set) var variables : [String] = [] convenience init(file : NSURL) { let data = NSData(contentsOfURL: file) let s = NSString(bytes: data!.bytes, length: data!.length, encoding: NSUTF8StringEncoding)! as String self.init(data: s) } init(data : String) { textFileData = data } func prepareTextFor(lineHeight : Float, screenHeight : Float, font : TextRenderer, tools: DrawingTools) { self.lineHeight = lineHeight self.screenHeight = screenHeight let fW : Float = 16//lineHeight * font.aspect * 0.5 text = font drawing = tools let reSplit = try! NSRegularExpression(pattern: "^(.+?)(?:\\$&\\$\\s*(.+))?$", options: NSRegularExpressionOptions()) var allLines : [[PageEntry]] = [] // for line in data.s let lines = textFileData.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) for (i, line) in lines.enumerate() { var lineEntries : [PageEntry] = [] if let match = reSplit.firstMatchInString(line, options: NSMatchingOptions(), range: NSRange(location: 0, length: line.characters.count)) { let nss = line as NSString let formatString = nss.substringWithRange(match.rangeAtIndex(1)) let variables : [String] if match.rangeAtIndex(2).location != NSNotFound { variables = nss.substringWithRange(match.rangeAtIndex(2)) .componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } else { variables = [] } self.variables.appendContentsOf(variables) print ("\(i) Vars: ", variables) lineEntries.appendContentsOf(parseWholeFormattingLine(formatString, variables: variables)) // } else { // // No formatting variables. pass the whole thing // lineEntries.appendContentsOf(parseWholeFormattingLine(line, variables: [])) } print ("Processed line: ", lineEntries) allLines.append(lineEntries) } print("Done") // Now, go over each line, and reduce down to dynamic entries only var fixedEntries : [PageEntry] = [] // Lines with only dynamic entries remaining var dynamicLines : [[PageEntry]] = [] // Dynamic entries that do not affect state var dynamicEntries : [PageEntry] = [] // var dynamicEntries : [PageEntry] = [] for (lineNum, entries) in allLines.enumerate() { var state : FormatState = FormatState() var position : Point2D = Point2D(0,Float(lineNum)) var lineDynamics : [PageEntry] = [] for (j, var entry) in entries.enumerate() { // Assign the current position and state // entry.position = position entry.state = state entry.position = Point2D(x: position.x*fW, y: screenHeight-(0.5+Float(lineNum))*lineHeight) + state.offset // If we have a text scale, calculate this now for width calculations let scale : Float = state.textSize == .Normal ? 1 : (state.textSize == .Half ? 0.5 : 2.0) position.x += Float(entry.length) * scale if entry is EmptyString { // position.x += Float(entry.length) * scale } else if entry is Tag { // We have something that can change state state = (entry as! Tag).changeState(state) } else if !entry.isDynamic && entry.isFixedLength { fixedEntries.append(entry) } else if entry.isFixedLength && !entry.affectsState { // We are dynamic, but not in a way that affects other items. dynamicEntries.append(entry) // position.x += Float(entry.length) * scale } else { // We are dynamic, or not fixed length. Skip the rest for iEntry in j..<entries.count { lineDynamics.append(entries[iEntry]) } break } } if !lineDynamics.isEmpty { // Strip any empty strings off of the end while lineDynamics.last is EmptyString { lineDynamics.removeLast() } // If a single entry, just shove onto the dynamic pile if lineDynamics.count == 1 { dynamicEntries.append(lineDynamics.first!) } else { dynamicLines.append(lineDynamics) } } } self.fixedEntries = fixedEntries self.dynamicEntries = dynamicEntries self.dynamicLines = dynamicLines // Deduplicate the variables self.variables = Array(Set(self.variables.map({"rpm."+$0}))) } func parseWholeFormattingLine(line : String, variables : [String]) -> [PageEntry] { let nss = line as NSString var entries : [PageEntry] = [] let formatRE = try! NSRegularExpression(pattern: "\\{([^\\}]+)\\}", options: NSRegularExpressionOptions()) // Split all formatting out of this, iteratively var position = 0 for match in formatRE.matchesInString(line, options: NSMatchingOptions(), range: NSRange(location: 0, length: nss.length)) { if match.range.location > position { let s = nss.substringWithRange(NSRange(location: position, length: match.range.location-position)) // Process anything between the position and this match entries.appendContentsOf(parsePotentiallyTaggedString(s as String)) position = match.range.location } // Append an entry for this variable entries.append(parseFormatString(nss.substringWithRange(match.rangeAtIndex(1)), variables: variables)) position = match.range.location + match.range.length } if position != nss.length { let remaining = nss.substringFromIndex(position) entries.appendContentsOf(parsePotentiallyTaggedString(remaining)) } return entries } func parseFormatString(fragment : String, variables : [String]) -> PageEntry { let fmtRE = Regex(pattern: "(\\d+)(?:,(\\d+))?(?::(.+))?") let info = fmtRE.firstMatchInString(fragment)!.groups let variable = variables[Int(info[0])!] let alignment = Int(info[1] ?? "0") ?? 0 let format = info[2] ?? "" return FormatEntry(variable: variable, alignment: alignment, format: format) } /// Parse a string that contains no variables {} but may contain tags func parsePotentiallyTaggedString(fragment : String) -> [PageEntry] { var entries : [PageEntry] = [] // Handle square bracket escaping let fragment = fragment.stringByReplacingOccurrencesOfString("[[", withString: "[") let tagRE = try! NSRegularExpression(pattern: "\\[([@\\#hs\\/].+?)\\]", options: NSRegularExpressionOptions()) let matches = tagRE.matchesInString(fragment, options: NSMatchingOptions(), range: NSRange(location: 0, length: fragment.characters.count)) var position = 0 for match in matches { // Handle any intermediate text if match.range.location > position { let subS = (fragment as NSString).substringWithRange(NSRange(location: position, length: match.range.location-position)) entries.appendContentsOf(processStringEntry(subS)) position = match.range.location } // Handle the tag type entries.append(processTag((fragment as NSString).substringWithRange(match.rangeAtIndex(1)))) position += match.range.length } if position < fragment.characters.count { let subS = (fragment as NSString).substringFromIndex(position) entries.appendContentsOf(processStringEntry(subS)) } return entries } func lengthOfSpacesAtFrontOf(string : String) -> UInt { var charCount : UInt = 0 var idx = string.startIndex while string[idx] == " " as Character { charCount += 1 if idx == string.endIndex { break } idx = idx.advancedBy(1) } return charCount } /// Takes a plain string entry, and splits into an array of potential /// [Whitespace] [String] [Whitespace] entries func processStringEntry(var fragment : String) -> [PageEntry] { if fragment.isWhitespace() { return [EmptyString(length: fragment.characters.count)] } var entries : [PageEntry] = [] let startWhite = lengthOfSpacesAtFrontOf(fragment) if startWhite > 0 { entries.append(EmptyString(length: Int(startWhite))) fragment = fragment.substringFromIndex(fragment.startIndex.advancedBy(Int(startWhite))) } let reversed = fragment.characters.reverse().reduce("", combine: { (str : String, ch : Character) -> String in var news = str news.append(ch) return news }) let endWhite = lengthOfSpacesAtFrontOf(reversed) if endWhite > 0 { fragment = fragment.substringToIndex(fragment.endIndex.advancedBy(-Int(endWhite))) } entries.append(FixedString(text: fragment)) if endWhite > 0 { entries.append(EmptyString(length: Int(endWhite))) } return entries } /// Processes the inner contents of a tag, and returns the page entry func processTag(fragment : String) -> Tag { let offsetRE = Regex(pattern: "@([xy])(-?\\d+)") if let nudge = offsetRE.firstMatchInString(fragment) { let res = nudge.groups return NudgeTag(value: Float(res[1])!, x: res[0] == "x") } else if fragment == "hw" { return WidthTag(type: .Half) } else if fragment == "/hw" || fragment == "/dw"{ return WidthTag(type: .Normal) } else if fragment == "dw" { return WidthTag(type: .Double) } fatalError() } func draw(data : [String : Any]) { // Draw all the fixed positions for entry in fixedEntries { let txt = entry.process(data) drawing!.program.setColor(txt.color) text?.draw(txt.string, size: lineHeight*txt.size, position: txt.position) } } } extension String { func isWhitespace() -> Bool { let trim = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) return trim.characters.count == 0 } } //private let sipRE = Regex(pattern: "SIP(_?)(0?)(\\d+)(?:\\.(\\d+))?") // protocol StringFormatter { func format<T>(item : T) -> String var fixedLength : Bool { get } var length : Int { get } } // //class SIFormatter : StringFormatter { // var spaced : Bool // var zeroPadded : Bool // var length : Int // var precision : Int? // // var fixedLength : Bool { return true } // // init(format: String) { // guard let match = sipRE.firstMatchInString(format) else { // fatalError() // } // // We have an SI processing entry. // var parts = match.groups // spaced = parts[0] != "" // zeroPadded = parts[1] == "0" // length = Int(parts[2])! // precision = parts[3] == "" ? nil : Int(parts[3])! // } // //// var length : Int { return length } // // func format<T>(item : T) -> String { // fatalError() // } //} // class DefaultStringFormatter : StringFormatter { var fixedLength : Bool { return false } var length : Int { return 0 } func format<T>(item: T) -> String { return String(item) } } // func getFormatterForString(format: String) -> StringFormatter { // if let _ = sipRE.firstMatchInString(format) { // return SIFormatter(format: format) // } return DefaultStringFormatter() }
e16ef68a3b84a04c4e9f7b2e4bb976f1
30.154657
145
0.646339
false
false
false
false
YouareMylovelyGirl/Sina-Weibo
refs/heads/Develop
新浪微博/新浪微博/Classes/Tools(工具)/NetManager/NetManager+Extension.swift
apache-2.0
1
// // NetManager+Extension.swift // 新浪微博 // // Created by 阳光 on 2017/6/7. // Copyright © 2017年 YG. All rights reserved. // import Foundation //封装新浪微博的网络请求方法 extension NetManager { /// 加载微博字典数据 /// - since_id: 则返回ID比since_id大的微博(即比since_id时间晚的微博),默认为0。 /// - max_id: 则返回ID小于或等于max_id的微博,默认为0。 /// - Parameter completionHandler: 完成回调 [list: 微博字典数组/错误信息] func stausList( since_id: Int64 = 0, max_id: Int64 = 0, completionHandler: @escaping (_ list: [[String: AnyObject]]?, _ error : NSError? ) -> ()) { //用AFN加载网络数据 let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" // let params = ["access_token": "2.00UCb9cD0VJ8eC0a8a9bbdf5S6IHwC"] //Swift 中 Int 可以转换成AnyObject / 但是Int64 不行, 但是可以将Int64 装换成字符串 let params = ["since_id": "\(since_id)", "max_id": "\(max_id > 0 ?max_id - 1 : 0)"] //提示: 服务器返回的字典, 就是按照时间倒序排序的 tokenRequest(url: urlString, params: params) { (json, error) in let result = json?["statuses"] as? [[String: AnyObject]] completionHandler(result, error as NSError?) } } //定时刷新不需要提示失败 ///返回微博的未读数量 func unreadCount(completionHandler:@escaping (_ count: Int)->()) { guard let uid = userAccount.uid else { return } let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json" let params = ["uid": uid] tokenRequest(url: urlString, params: params) { (data, error) in let dic = data as [String: AnyObject]? let count = dic?["status"] as? Int completionHandler(count ?? 0) } } } //MARK: - OAuth相关方法 extension NetManager { //加载accessToken /// 加载AccessToken /// /// - Parameters: /// - code: 授权码 /// - completionHandler: 完成回调 func loadAccessToken(code: String, completionHandler:@escaping (_ isSuccess: Bool)->()) { let urlString = "https://api.weibo.com/oauth2/access_token" let params = ["client_id": APPKey, "client_secret": APPSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": RedirectURI] //发起网络请求 request(requestType: .POST, url: urlString, params: params) { (data, error) in //直接用字典设置 userAccount属性 self.userAccount.yy_modelSet(with: (data as [String: AnyObject]?) ?? [:]) print(self.userAccount) //加载用户信息 self.loadUserInfo(completionHandler: { (dict) in //使用用户信息字典设置用户账户信息, 设置昵称和头像地址 self.userAccount.yy_modelSet(with: dict) //保存模型 self.userAccount.saceAccount() print(self.userAccount) //等用户信息加载完成后再 完成回调 if error == nil { completionHandler(true) } else { completionHandler(false) } }) } } } extension NetManager { ///加载当前用户信息 - 用户登录后立即执行 func loadUserInfo(completionHandler:@escaping (_ dict: [String: AnyObject])->()) { guard let uid = userAccount.uid else { return } let urlString = "https://api.weibo.com/2/users/show.json" let params = ["uid": uid] //发起网络请求 tokenRequest(url: urlString, params: params) { (data, error) in completionHandler(data as [String : AnyObject]? ?? [:]) } } }
3c1cdf4f9274ec4fe3a19b00aa1eee60
29.747967
151
0.513749
false
false
false
false
BeanstalkData/beanstalk-ios-sdk
refs/heads/master
Example/BeanstalkEngageiOSSDK/ProfileViewController.swift
mit
1
// // ProfileViewController.swift // BeanstalkEngageiOSSDK // // 2016 Heartland Commerce, Inc. All rights reserved. // import UIKit import BeanstalkEngageiOSSDK class ProfileViewController: BaseViewController, CoreProtocol, EditProfileProtocol { var contact: ContactModel? var updateContactRequest: UpdateContactRequest? @IBOutlet var nameLabel: UILabel! @IBOutlet var emailLabel: UILabel! @IBOutlet var genderSegment: UISegmentedControl! override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if self.contact == nil { self.loadProfile() } else { self.updateProfile() } } //MARK: - Private func loadProfile() { self.coreService?.getContact(self, handler: { (contact) in if contact != nil { self.contact = contact as? ContactModel self.updateProfile() } }) } func updateProfile() { let updateRequest = UpdateContactRequest(contact: self.contact) self.updateContactRequest = updateRequest self.nameLabel.text = self.contact?.getFullName() self.emailLabel.text = updateRequest.email if self.updateContactRequest?.gender == "Male" { self.genderSegment.selectedSegmentIndex = 0 } else if self.updateContactRequest?.gender == "Female" { self.genderSegment.selectedSegmentIndex = 1 } else { self.genderSegment.selectedSegmentIndex = 2 } } //MARK: - Actions @IBAction func genderAction() { switch self.genderSegment.selectedSegmentIndex { case 0: self.updateContactRequest?.gender = "Male" case 1: self.updateContactRequest?.gender = "Female" default: self.updateContactRequest?.gender = "Unknown" } } @IBAction func saveContactAction() { if let cont = self.contact { if let upd = self.updateContactRequest { self.coreService?.updateContact(self, original: cont, request: upd, handler: { (success) in if success { self.loadProfile() } }) } } } }
a2ac0a19edebd382924492bf554913a4
22.75
99
0.653589
false
false
false
false
EGF2/ios-client
refs/heads/master
EGF2/EGF2/Graph/EGF2Graph+WebSocket.swift
mit
1
// // EGF2Graph+WebSocket.swift // EGF2 // // Created by LuzanovRoman on 12.01.17. // Copyright © 2017 EigenGraph. All rights reserved. // import Foundation class EGF2Subscription { var isSent = false var observerPointers = [UnsafeRawPointer]() var isNoObservers: Bool { return observerPointers.isEmpty } static func pointer(forObserver observer: NSObject) -> UnsafeRawPointer { return UnsafeRawPointer(Unmanaged.passUnretained(observer).toOpaque()) } static func observer(fromPointer pointer: UnsafeRawPointer) -> NSObject { return Unmanaged<NSObject>.fromOpaque(pointer).takeUnretainedValue() } init(isSent: Bool, observers: [NSObject]) { self.isSent = isSent self.observerPointers = observers.map( {EGF2Subscription.pointer(forObserver: $0)} ) } func add(_ observer: NSObject) { let pointer = EGF2Subscription.pointer(forObserver: observer) if let _ = observerPointers.first(where: {$0 == pointer}) { return } observerPointers.append(EGF2Subscription.pointer(forObserver: observer)) } func remove(_ observer: NSObject) { let pointer = EGF2Subscription.pointer(forObserver: observer) guard let ptr = observerPointers.first(where: {$0 == pointer}) else { return } observerPointers.remove(ptr) } func contains(_ observer: NSObject) -> Bool { let pointer = EGF2Subscription.pointer(forObserver: observer) return observerPointers.first(where: {$0 == pointer}) != nil } } extension EGF2Graph: WebSocketDelegate { // MARK: - Private methods fileprivate func startPing() { if let timer = webSocketPingTimer { timer.invalidate() } webSocketPingTimer = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self] (timer) in guard let socket = self?.webSocket else { return } socket.write(ping: Data()) } } fileprivate func stopPing() { webSocketPingTimer?.invalidate() webSocketPingTimer = nil } // Send JSON for subscribe/unsubscribe a specific object // Returns false if subscription wasn't sent fileprivate func updateSubscription(subscribe: Bool, forObjecWithId id: String) -> Bool { guard let socket = webSocket, socket.isConnected else { return false } let action = subscribe ? "subscribe" : "unsubscribe" guard let data = Data(jsonObject:[action:[["object_id":id]]]) else { return false } guard let string = String(data: data, encoding: .utf8) else { return false } socket.write(string: string) if showLogs { print("EGF2Graph. Sent json: \(string).") } return true } // Send JSON for subscribe/unsubscribe a specific edge // Returns false if subscription wasn't sent fileprivate func updateSubscription(subscribe: Bool, forSourceWithId id: String, andEdge edge: String) -> Bool { guard let socket = webSocket, socket.isConnected else { return false} let action = subscribe ? "subscribe" : "unsubscribe" guard let data = Data(jsonObject:[action:[["edge":["source":id,"name":edge]]]]) else { return false } guard let string = String(data: data, encoding: .utf8) else { return false } socket.write(string: string) if showLogs { print("EGF2Graph. Sent json: \(string).") } return true } fileprivate func subscribe(observer: NSObject, key: String, subscribe: () -> Bool) { guard let subscription = subscriptions[key] else { subscriptions[key] = EGF2Subscription(isSent: subscribe(), observers: [observer]) return } // Add new observer (if needed) subscription.add(observer) } fileprivate func unsubscribe(observer: NSObject, key: String, unsubscribe: () -> () ) { guard let subscription = subscriptions[key] else { return } subscription.remove(observer) if subscription.isNoObservers { if subscription.isSent { unsubscribe() } subscriptions[key] = nil } } // MARK: - Internal methods func subscribe(observer: NSObject, forObjectWithId id: String) { subscribe(observer: observer, key: id) { () -> Bool in updateSubscription(subscribe: true, forObjecWithId: id) } } func subscribe(observer: NSObject, forSourceWithId id: String, andEdge edge: String) { subscribe(observer: observer, key: "\(id)|\(edge)") { () -> Bool in updateSubscription(subscribe: true, forSourceWithId: id, andEdge: edge) } } func unsubscribe(observer: NSObject, fromObjectWithId id: String) { unsubscribe(observer: observer, key: id) { _ = updateSubscription(subscribe: false, forObjecWithId: id) } } func unsubscribe(observer: NSObject, fromSourceWithId id: String, andEdge edge: String) { unsubscribe(observer: observer, key: "\(id)|\(edge)") { _ = updateSubscription(subscribe: false, forSourceWithId: id, andEdge: edge) } } func subscribe(observer: NSObject, forObjectsWithIds ids: [String]) { var subscribe = [[String: Any]]() let isConnected = webSocket?.isConnected ?? false for id in ids { // If there is a subscription just add new observer (if needed) if let subscription = subscriptions[id] { subscription.add(observer) } else { // Add a new subscription subscriptions[id] = EGF2Subscription(isSent: isConnected, observers: [observer]) subscribe.append(["object_id":id]) } } // If we need to subscribe for the new objects if subscribe.count > 0 && isConnected { if let data = Data(jsonObject:["subscribe":subscribe]), let string = String(data: data, encoding: .utf8) { webSocket?.write(string: string) if showLogs { print("EGF2Graph. Sent json: \(string).") } } } } // Unsubscribe observer from all subscriptions // Send unsubscribe message via websocket if needed func unsubscribe(observer: NSObject) { var unsubscribe = [[String: Any]]() for (key, subscription) in subscriptions { if !subscription.contains(observer) { continue } subscription.remove(observer) if !subscription.isNoObservers { continue } if subscription.isSent { let components = key.components(separatedBy: "|") // Just object id if components.count == 1 { guard let id = components.first else { return } unsubscribe.append(["object_id":id]) // Object id and edge } else { guard let id = components.first, let edge = components.last else { return } unsubscribe.append(["edge":["source":id,"name":edge]]) } } subscriptions[key] = nil } if unsubscribe.count > 0 { if let data = Data(jsonObject:["unsubscribe":unsubscribe]), let string = String(data: data, encoding: .utf8) { webSocket?.write(string: string) if showLogs { print("EGF2Graph. Sent json: \(string).") } } } } // MARK: - func webSocketConnect() { guard let url = webSocketURL, let token = account.userToken else { return } // Is already have a connected socket? if let socket = webSocket, socket.isConnected { return } // Is already connecting? if webSocketIsConnecting { return } // Create a new socket and connect it webSocketIsConnecting = true webSocket = WebSocket(url: url) webSocket?.headers["Authorization"] = token webSocket?.delegate = self webSocket?.connect() } func webSocketDisonnect() { webSocket?.disconnect() } // MARK:- WebSocketDelegate public func websocketDidConnect(socket: WebSocket) { webSocketIsConnecting = false var subscribe = [[String: Any]]() for (key, subscription) in subscriptions { if !subscription.isSent { let components = key.components(separatedBy: "|") // Just object id if components.count == 1 { guard let id = components.first else { return } subscribe.append(["object_id":id]) // Object id and edge } else { guard let id = components.first, let edge = components.last else { return } subscribe.append(["edge":["source":id,"name":edge]]) } subscription.isSent = true } } if subscribe.count > 0 { if let data = Data(jsonObject:["subscribe":subscribe]), let string = String(data: data, encoding: .utf8) { socket.write(string: string) if showLogs { print("EGF2Graph. Sent json: \(string).") } } } startPing() if showLogs { print("EGF2Graph. Websocket connected to \(socket.currentURL.absoluteString).") } } public func websocketDidDisconnect(socket: WebSocket, error: NSError?) { webSocketIsConnecting = false for (_, subscription) in subscriptions { subscription.isSent = false } stopPing() if showLogs { print("EGF2Graph. Websocket disconnected from \(socket.currentURL.absoluteString).") } } public func websocketDidReceiveMessage(socket: WebSocket, text: String) { guard let json = text.data(using: .utf8)?.jsonObject() as? [String: Any] else { return } guard let method = json["method"] as? String else { return } if let objectId = json["object"] as? String { if method == "PUT" { guard let dictionary = json["current"] as? [String: Any] else { return } self.internalUpdateObject(withId: objectId, dictionary: dictionary, completion: nil) } else if method == "DELETE" { self.internalDeleteObject(withId: objectId, completion: nil) } } else if let edge = json["edge"] as? [String: String], let src = edge["src"], let dst = edge["dst"], let name = edge["name"] { if method == "POST" { self.internalAddObject(withId: dst, forSource: src, toEdge: name, completion: nil) } else if method == "DELETE" { self.internalDeleteObject(withId: dst, forSource: src, fromEdge: name, completion: nil) } } } public func websocketDidReceiveData(socket: WebSocket, data: Data) { // Nothing here } }
448b05c192f855b5e7d3e0c20c09b2e9
36.766447
135
0.570769
false
false
false
false
Ben-G/Argo
refs/heads/master
ArgoTests/Tests/SwiftDictionaryDecodingTests.swift
mit
10
import XCTest import Argo class SwiftDictionaryDecodingTests: XCTestCase { func testDecodingAllTypesFromSwiftDictionary() { let typesDict = [ "numerics": [ "int": 5, "int64": 9007199254740992, "double": 3.4, "float": 1.1, "int_opt": 4 ], "bool": false, "string_array": ["hello", "world"], "embedded": [ "string_array": ["hello", "world"], "string_array_opt": [] ], "user_opt": [ "id": 6, "name": "Cooler User" ] ] let model: TestModel? = decode(typesDict) XCTAssert(model != nil) XCTAssert(model?.numerics.int == 5) XCTAssert(model?.numerics.int64 == 9007199254740992) XCTAssert(model?.numerics.double == 3.4) XCTAssert(model?.numerics.float == 1.1) XCTAssert(model?.numerics.intOpt != nil) XCTAssert(model?.numerics.intOpt! == 4) XCTAssert(model?.string == "Cooler User") XCTAssert(model?.bool == false) XCTAssert(model?.stringArray.count == 2) XCTAssert(model?.stringArrayOpt == nil) XCTAssert(model?.eStringArray.count == 2) XCTAssert(model?.eStringArrayOpt != nil) XCTAssert(model?.eStringArrayOpt?.count == 0) XCTAssert(model?.userOpt != nil) XCTAssert(model?.userOpt?.id == 6) } }
dd3949cc2758324e12e1b577c7f4ef79
27.688889
56
0.597211
false
true
false
false
cubixlabs/GIST-Framework
refs/heads/master
GISTFramework/Classes/BaseClasses/BaseUINavigationItem.swift
agpl-3.0
1
// // BaseUINavigationItem.swift // GISTFramework // // Created by Shoaib Abdul on 14/07/2016. // Copyright © 2016 Social Cubix. All rights reserved. // import UIKit /// BaseUINavigationItem is a subclass of UINavigationItem and implements BaseView. It has some extra proporties and support for SyncEngine. open class BaseUINavigationItem: UINavigationItem, BaseView { //MARK: - Properties /// Overriden title property to set title from SyncEngine (Hint '#' prefix). override open var title: String? { get { return super.title; } set { if let key:String = newValue , key.hasPrefix("#") == true { super.title = SyncedText.text(forKey: key); } else { super.title = newValue; } } } //P.E. //MARK: - Constructors /// Overridden constructor to setup/ initialize components. /// /// - Parameter title: Title of Navigation Item public override init(title: String) { super.init(title: title); } //F.E. /// Required constructor implemented. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } //F.E. //MARK: - Overridden Methods /// Overridden method to setup/ initialize components. open override func awakeFromNib() { super.awakeFromNib(); self.commontInit(); } //F.E. /// Common initazier for setting up items. private func commontInit() { if let txt:String = self.title , txt.hasPrefix("#") == true { self.title = txt; // Assigning again to set value from synced data } } //F.E. } //CLS END
e935eb7870e9ed06e6ffddee9dd6bdeb
27.377049
140
0.589832
false
false
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/MaxWidthSelectionTableViewCell.swift
apache-2.0
3
// // MaxWidthSelectionTableViewCell.swift // SwiftEntryKit_Example // // Created by Daniel Huri on 4/26/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit class MaxWidthSelectionTableViewCell: SelectionTableViewCell { override func configure(attributesWrapper: EntryAttributeWrapper) { super.configure(attributesWrapper: attributesWrapper) titleValue = "Max Width" descriptionValue = "Describes the entry's maximum width limitation. It can stretch to the width of the screen, get screen edge less 40pts, or be 90% of the screen width" insertSegments(by: ["Stretch", "Min Edge", "90% Screen"]) selectSegment() } private func selectSegment() { switch attributesWrapper.attributes.positionConstraints.maxSize.width { case .offset(value: _): segmentedControl.selectedSegmentIndex = 0 case .constant(value: _): segmentedControl.selectedSegmentIndex = 1 case .ratio(value: 0.9): segmentedControl.selectedSegmentIndex = 2 default: break } } @objc override func segmentChanged() { switch segmentedControl.selectedSegmentIndex { case 0: attributesWrapper.attributes.positionConstraints.maxSize.width = .offset(value: 0) case 1: attributesWrapper.attributes.positionConstraints.maxSize.width = .constant(value: UIScreen.main.minEdge - 40) case 2: attributesWrapper.attributes.positionConstraints.maxSize.width = .ratio(value: 0.9) default: break } } }
8443c8a214cfb0f27dde4841fd31b899
35.577778
177
0.664642
false
false
false
false
josve05a/wikipedia-ios
refs/heads/develop
Wikipedia/Code/WelcomeContainerViewController.swift
mit
4
import UIKit protocol WelcomeContainerViewControllerDataSource: AnyObject { var animationView: WelcomeAnimationView { get } var panelViewController: WelcomePanelViewController { get } var isFirst: Bool { get } } extension WelcomeContainerViewControllerDataSource { var isFirst: Bool { return false } } class WelcomeContainerViewController: UIViewController { weak var dataSource: WelcomeContainerViewControllerDataSource? @IBOutlet private weak var topContainerView: UIView! @IBOutlet private weak var bottomContainerView: UIView! private var theme = Theme.standard init(dataSource: WelcomeContainerViewControllerDataSource) { self.dataSource = dataSource super.init(nibName: "WelcomeContainerViewController", bundle: Bundle.main) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() guard let dataSource = dataSource else { assertionFailure("dataSource should be set by now") apply(theme: theme) return } addChild(WelcomeAnimationViewController(animationView: dataSource.animationView, waitsForAnimationTrigger: dataSource.isFirst), to: topContainerView) addChild(dataSource.panelViewController, to: bottomContainerView) apply(theme: theme) } private func addChild(_ viewController: UIViewController?, to view: UIView) { guard let viewController = viewController, viewController.parent == nil, viewIfLoaded != nil else { return } addChild(viewController) viewController.view.translatesAutoresizingMaskIntoConstraints = false view.wmf_addSubviewWithConstraintsToEdges(viewController.view) viewController.didMove(toParent: self) (viewController as? Themeable)?.apply(theme: theme) } } extension WelcomeContainerViewController: Themeable { func apply(theme: Theme) { guard viewIfLoaded != nil else { self.theme = theme return } children.forEach { ($0 as? Themeable)?.apply(theme: theme) } topContainerView.backgroundColor = theme.colors.midBackground bottomContainerView.backgroundColor = theme.colors.midBackground } } extension WelcomeContainerViewController: PageViewControllerViewLifecycleDelegate { func pageViewControllerDidAppear(_ pageViewController: UIPageViewController) { dataSource?.animationView.animate() } }
f17b75cb175c6eb56180076b617a0a04
33.513158
157
0.698437
false
false
false
false
githubError/KaraNotes
refs/heads/master
KaraNotes/KaraNotes/WriteArticle/View/CPFPreviewHeaderView.swift
apache-2.0
1
// // CPFHeaderView.swift // KaraNotes // // Created by 崔鹏飞 on 2017/4/16. // Copyright © 2017年 崔鹏飞. All rights reserved. // import UIKit protocol CPFPreviewHeaderViewDelegate { func headerView(headerView: UIView, didClickDismissBtn dismissBtn: UIButton) func headerView(headerView: UIView, didClickExportBtn dismissBtn: UIButton) } class CPFPreviewHeaderView: UIView { fileprivate var titleLabel:UILabel! fileprivate var dismissBtn:UIButton! fileprivate var exportBtn:UIButton! var delegate:CPFPreviewHeaderViewDelegate? override init(frame: CGRect) { super.init(frame: frame) setupSubviews(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } extension CPFPreviewHeaderView { fileprivate func setupSubviews(frame: CGRect) -> Void { backgroundColor = CPFNavColor dismissBtn = UIButton(type: .custom) dismissBtn.setImage(UIImage.init(named: "dismissBtn"), for: .normal) dismissBtn.addTarget(self, action: #selector(dismissBtnClick), for: .touchUpInside) addSubview(dismissBtn) dismissBtn.snp.makeConstraints { (mark) in mark.width.height.equalTo(30) mark.centerY.equalTo(self.snp.centerY).offset(10) mark.left.equalTo(15) } titleLabel = UILabel() addSubview(titleLabel) titleLabel.text = CPFLocalizableTitle("previewArticle_title") titleLabel.font = CPFPingFangSC(weight: .semibold, size: 18) titleLabel.textColor = UIColor.white titleLabel.textAlignment = .center titleLabel.snp.makeConstraints { (make) in make.centerY.equalTo(dismissBtn.snp.centerY) make.width.equalTo(60) make.height.equalTo(35) make.centerX.equalToSuperview() } exportBtn = UIButton(type: .custom) addSubview(exportBtn) exportBtn.titleLabel?.font = CPFPingFangSC(weight: .regular, size: 14) exportBtn.setTitle(CPFLocalizableTitle("previewArticle_export"), for: .normal) exportBtn.setTitleColor(UIColor.white, for: .normal) exportBtn.addTarget(self, action: #selector(exportBtnClick), for: .touchUpInside) exportBtn.snp.makeConstraints { (make) in make.centerY.equalTo(dismissBtn.snp.centerY) make.width.equalTo(40) make.height.equalTo(25) make.right.equalToSuperview().offset(-10) } } } extension CPFPreviewHeaderView { @objc fileprivate func dismissBtnClick() -> Void { delegate?.headerView(headerView: self, didClickDismissBtn: dismissBtn) } @objc fileprivate func exportBtnClick() -> Void { delegate?.headerView(headerView: self, didClickExportBtn: exportBtn) } }
4fcb2efa398b7a48587fcf471b0fa57a
31.908046
91
0.661893
false
false
false
false
antonio081014/LeetCode-CodeBase
refs/heads/main
Swift/baseball-game.swift
mit
1
/** * https://leetcode.com/problems/baseball-game/ * * */ // Date: Sat Apr 9 23:27:59 PDT 2022 class Solution { func calPoints(_ ops: [String]) -> Int { var result = [Int]() for op in ops { if op == "+" { let n = result.count let sum = result[n - 1] + result[n - 2] result.append(sum) } else if op == "D" { let d = result[result.count - 1] * 2 result.append(d) } else if op == "C" { result.removeLast() } else { result.append(Int(op)!) } // print(result) } return result.reduce(0) { $0 + $1 } } }
e796149d157edd16aff34a037a166623
26
55
0.410714
false
false
false
false
hetefe/HTF_sina_swift
refs/heads/master
sina_htf/sina_htf/Classes/Module/Home/StatusCell/StatusCellBottomView.swift
mit
1
// // StatusCellBottomView.swift // sina_htf // // Created by 赫腾飞 on 15/12/18. // Copyright © 2015年 hetefe. All rights reserved. // import UIKit class StatusCellBottomView: UIView { override init(frame:CGRect) { super.init(frame: frame) // backgroundColor = UIColor(white: 0.3, alpha: 1) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ addSubview(retweetedBtn) addSubview(composeBtn) addSubview(likeBtn) //MARK:- 设置约束 retweetedBtn.snp_makeConstraints { (make) -> Void in make.top.left.bottom.equalTo(self) } composeBtn.snp_makeConstraints { (make) -> Void in make.left.equalTo(retweetedBtn.snp_right) make.top.bottom.equalTo(self) make.width.equalTo(retweetedBtn.snp_width) } likeBtn.snp_makeConstraints { (make) -> Void in make.left.equalTo(composeBtn.snp_right) make.right.equalTo(self.snp_right) make.top.bottom.equalTo(self) make.width.equalTo(composeBtn.snp_width) } let sepView1 = sepView() let sepView2 = sepView() //添加 addSubview(sepView1) addSubview(sepView2) //设置约束 let w = 0.5 let scale = 0.4 sepView1.snp_makeConstraints { (make) -> Void in make.left.equalTo(retweetedBtn.snp_right) make.height.equalTo(self.snp_height).multipliedBy(scale) make.centerY.equalTo(self.snp_centerY) make.width.equalTo(w) } sepView2.snp_makeConstraints { (make) -> Void in make.left.equalTo(composeBtn.snp_right) make.height.equalTo(self.snp_height).multipliedBy(scale) make.centerY.equalTo(self.snp_centerY) make.width.equalTo(w) } } //MARK:- 生成分割线的方法 private func sepView() -> UIView{ let v = UIView() v.backgroundColor = UIColor.darkGrayColor() return v } //MARK:- 懒加载视图 private lazy var retweetedBtn: UIButton = UIButton(backImageNameN: nil, backImageNameH: nil, color: UIColor.darkGrayColor(), title: "转发", fontOfSize: 10, imageName: "timeline_icon_retweet") private lazy var composeBtn: UIButton = UIButton(backImageNameN: nil, backImageNameH: nil, color: UIColor.darkGrayColor(), title: "评论", fontOfSize: 10, imageName: "timeline_icon_comment") private lazy var likeBtn: UIButton = UIButton(backImageNameN: nil, backImageNameH: nil, color: UIColor.darkGrayColor(), title: "赞", fontOfSize: 10, imageName: "timeline_icon_unlike") }
0cebbfae992da3d5e582e61a060de0a0
29.630435
193
0.598297
false
false
false
false
istyle-inc/LoadMoreTableViewController
refs/heads/master
Pod/Classes/FooterCell.swift
mit
1
import UIKit public class FooterCell: UITableViewCell { @IBOutlet private weak var activityIndecator: UIActivityIndicatorView! @IBOutlet weak var retryButton: UIButton! var showsRetryButton = false { didSet { if showsRetryButton { activityIndecator.isHidden = true retryButton.isHidden = false } else { activityIndecator.isHidden = false retryButton.isHidden = true } } } var retryButtonTapped: (() -> ())? public override func awakeFromNib() { super.awakeFromNib() showsRetryButton = false } override public func layoutSubviews() { super.layoutSubviews() activityIndecator.startAnimating() } @IBAction func retryButtonTapped(_ sender: UIButton) { retryButtonTapped?() } }
607b877cff49bdcfc5f7c5a6b0c13ddd
22.837838
74
0.602041
false
false
false
false
jcfausto/transit-app
refs/heads/master
TransitApp/TransitApp/RouteSegmentsDetailViewController.swift
mit
1
// // RouteSegmentsDetailViewController.swift // TransitApp // // Created by Julio Cesar Fausto on 26/02/16. // Copyright © 2016 Julio Cesar Fausto. All rights reserved. // import UIKit import GoogleMaps import Polyline import CoreLocation class RouteSegmentsDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: Properties var route: Route? @IBOutlet weak var mapViewContainer: GMSMapView! // MARK: properties @IBOutlet weak var routeSegmentsView: RouteSegmentsView! @IBOutlet weak var routeDurationLabel: UILabel! @IBOutlet weak var routeSummaryLabel: UILabel! @IBOutlet weak var segmentsTableView: UITableView! // MARK: Initialization override func viewDidLoad() { super.viewDidLoad() doFillRouteInformation(self) initMapView(self) // Observers NSNotificationCenter.defaultCenter().addObserver(self, selector:"performSegmentSelection:", name: "RSVButtonTapped", object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Deinitialization deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: TableView protocols compliance func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let route = self.route { return route.segments.count } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "RouteSegmentsDetailTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RouteSegmentsDetailTableViewCell doInitializeCell(cell, indexPath: indexPath) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { doPlotSegmentOnTheMap(indexPath) } } // MARK: Custom functions extension RouteSegmentsDetailViewController { /** Fill the view with the route information */ func doFillRouteInformation(rsViewController: RouteSegmentsDetailViewController) { if let route = rsViewController.route { rsViewController.navigationItem.title = route.provider rsViewController.routeSegmentsView.segments = route.segments rsViewController.routeSummaryLabel.text = route.summary rsViewController.routeDurationLabel.text = route.duration.stringValueInMinutes } } // MARK: Cell initialization func doInitializeCell(cell: RouteSegmentsDetailTableViewCell, indexPath: NSIndexPath) { if let route = self.route { let segment = route.segments[indexPath.row] let firstStop = route.segments[indexPath.row].stops.first let lastStop = route.segments[indexPath.row].stops.last //Segment vertical line color cell.segmentDetailVerticalLineView.fillColor = segment.color //Segment duration in minutes if let firstStop = firstStop, lastStop = lastStop { cell.segmentEstimatedDurationLabel.text = lastStop.time.timeIntervalSinceDate(firstStop.time).stringValueInMinutes } //Departure and arrival information if let firstStop = firstStop { cell.segmentTimeLabel.text = "Departure at \(firstStop.time.stringValueWithHourAndMinute)" if let name = firstStop.name { if (!name.isEmpty) { cell.segmentNameLabel.text = "starting at \(name)" } } var destinationSummary: String = "" if (!segment.travelMode.isEmpty) { destinationSummary = destinationSummary + "\(segment.travelMode)" } if let lastStop = lastStop { if let name = lastStop.name { if (!name.isEmpty) { var prepString = "to" if segment.isSetupStop() { prepString = "at" } destinationSummary = destinationSummary + " \(prepString) \(name)" } } } cell.segmentTravelModeLabel.text = destinationSummary } //Last segment additional information if indexPath.row == route.segments.count-1 { if let lastStop = lastStop { cell.segmentFinishTimeLabel.text = "Estimated arrival at \(lastStop.time.stringValueWithHourAndMinute)" cell.segmentDetailVerticalLineView.lastSegment = true } } } } // MARK: Map initialization, centered initially for the purpose of this application in Berlin func initMapView(rsViewController: RouteSegmentsDetailViewController) { //This initial center position could come from a .plist config file. let camera = GMSCameraPosition.cameraWithLatitude(52.524370, longitude: 13.410530, zoom: 15) rsViewController.mapViewContainer.camera = camera rsViewController.mapViewContainer.myLocationEnabled = true } /** Plot a segment on the map */ func doPlotSegmentOnTheMap(indexPath: NSIndexPath) { if let route = self.route { let selectedSegment: Segment = route.segments[indexPath.row] //If the segment doesn't have a polyline, means that is a stop in the same place //for some acton (bike or car returnin, car setup, etc) if (!selectedSegment.polyline.isEmpty) { let decodePolyline = Polyline(encodedPolyline: selectedSegment.polyline) let decodedPath: [CLLocationCoordinate2D]? = decodePolyline.coordinates let path = GMSMutablePath() if let decodedPath = decodedPath { for location in decodedPath { path.addCoordinate(location) } } let polyline = GMSPolyline(path: path) polyline.strokeColor = selectedSegment.color polyline.strokeWidth = 2.0 var locationPosition = path.coordinateAtIndex(0) //First location switch indexPath.row { case 0: let marker = GMSMarker(position: locationPosition) marker.icon = GMSMarker.markerImageWithColor(selectedSegment.color) marker.title = selectedSegment.name marker.map = self.mapViewContainer //When there's only one segment, the index row 0 represents both the starting //and stopping positions. if route.segments.count == 1 { let finalPosition = path.coordinateAtIndex(path.count()-1) //Last location let finalMarker = GMSMarker(position: finalPosition) finalMarker.icon = GMSMarker.markerImageWithColor(selectedSegment.color) finalMarker.map = self.mapViewContainer } case route.segments.count-1: locationPosition = path.coordinateAtIndex(path.count()-1) //Last location let marker = GMSMarker(position: locationPosition) marker.icon = GMSMarker.markerImageWithColor(selectedSegment.color) marker.title = selectedSegment.name marker.map = self.mapViewContainer default: break } polyline.map = self.mapViewContainer self.mapViewContainer.animateToLocation(locationPosition) } } } /** This method will be invoked every time that the RouteSegmentsView notify for an RSVButtonTapped event */ func performSegmentSelection(notification: NSNotification) { let userInfo = notification.userInfo as! [String: AnyObject] let button = userInfo["button"] as! RouteSegmentButton? if let button = button { let indexPath = NSIndexPath(forRow: button.index, inSection: 0) self.segmentsTableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Middle) self.tableView(self.segmentsTableView, didSelectRowAtIndexPath: indexPath) } } }
036430c051fa715f0c9de8863c81baad
35.393701
140
0.586651
false
false
false
false
JGiola/swift
refs/heads/main
validation-test/compiler_crashers_2_fixed/sr11639.swift
apache-2.0
4
// RUN: %target-swift-frontend -emit-ir -primary-file %s -debug-generic-signatures 2>&1 | %FileCheck %s public protocol FooProtocol { associatedtype Bar } public struct Foo<Bar>: FooProtocol { public var bar: Bar } public protocol BazProtocol: FooProtocol { associatedtype Foo1: FooProtocol where Foo1.Bar == Foo2.Bar associatedtype Foo2Bar typealias Foo2 = Foo<Foo2Bar> } // CHECK-LABEL: sr11639.(file).BazProtocol@ // CHECK-NEXT: Requirement signature: <Self where Self : FooProtocol, Self.[BazProtocol]Foo1 : FooProtocol, Self.[BazProtocol]Foo2Bar == Self.[BazProtocol]Foo1.[FooProtocol]Bar>
d95cb61722ea2a71109cf90ae1b8ed7e
32.833333
177
0.752053
false
false
false
false
BluefinSolutions/ODataParser
refs/heads/master
ODataParser/ODataServiceManager.swift
apache-2.0
1
// // ODataServiceManager.swift // Demo Jam // // Created by Brenton O'Callaghan on 09/10/2014. // Completely open source without any warranty to do with what you like :-) // import Foundation class ODataServiceManager: NSObject, ODataCollectionDelegate{ internal var _entitiesAvailable: NSMutableArray = NSMutableArray() internal var _collectionListLoaded: Bool = false; // The local oData requestor. internal var _oDataRequester: ODataCollectionManager? // Callsback to the passed in function with a list of the available collections in the oData service. class func getCollectionList() -> NSMutableArray{ // This would be so much better as a class variable with async calls but Swift does not // support class variables yet :-( /*var serviceManager: ODataServiceManager = ODataServiceManager() serviceManager._oDataRequester?.makeRequestToCollection(OdataFilter()) while (!serviceManager._collectionListLoaded){ sleep(1) } return serviceManager._entitiesAvailable*/ return NSMutableArray() } // Create a collection manager object used to make all the requests to a particular collection. class func createCollectionManagerForCollection(collectionName:NSString, andDelegate:ODataCollectionDelegate) -> ODataCollectionManager{ // New instance of a collection. var newCollectionManager: ODataCollectionManager = ODataCollectionManager(); // Set the delegate and the collection name. newCollectionManager.setDelegate(andDelegate) newCollectionManager.setCollectionName(collectionName) // Return to the user :-) return newCollectionManager } // ====================================================================== // MARK: - Internal Private instance methods. // ====================================================================== override init() { // Always do the super. super.init() // Create an odata request to the service with no specific collection. self._oDataRequester = ODataServiceManager.createCollectionManagerForCollection("", andDelegate: self) } func didRecieveResponse(results: NSDictionary){ let queryDictionary = results.objectForKey("d") as NSMutableDictionary let queryResults = queryDictionary.objectForKey("EntitySets") as NSMutableArray for singleResult in queryResults{ // Create and initialise the new entity object. self._entitiesAvailable.addObject(singleResult as NSString) } // Very important if we want to exit the infinite loop above! // There has to be a better way to do this!!! :) self._collectionListLoaded = true } func requestFailedWithError(error: NSString){ println("=== ERROR ERROR ERROR ===") println("Unable to request entity listing from OData service - is it an odata server??") println("Error: " + error) } }
6077b41715c584f28e7266ca463a32ac
35.505747
140
0.630866
false
false
false
false
cbaker6/qismartcity_netatmo
refs/heads/master
QiSmartCity/NetatmoModuleProvider.swift
apache-2.0
1
// // NetadmoModuleProvider.swift // netatmoclient // // Created by Corey Baker on 5/10/16. // Copyright © 2016 University of California San Diego. All rights reserved. // // Original code by: Thomas Kluge, https://github.com/thkl/NetatmoSwift import Foundation import CoreData //Currently not using anything in this class struct NetatmoModule: Equatable { var id: String var moduleName: String var type: String //Might need to make an enum for types var stationid : String } func ==(lhs: NetatmoModule, rhs: NetatmoModule) -> Bool { return lhs.id == rhs.id } extension NetatmoModule { init(managedObject : NSManagedObject) { self.id = managedObject.valueForKey(kQSModuleId) as! String self.moduleName = managedObject.valueForKey(kQSModuleName) as! String self.type = managedObject.valueForKey(kQSModuleType) as! String self.stationid = managedObject.valueForKey(kQSParentStationId) as! String } var measurementTypes : [NetatmoMeasureType] { switch self.type { case "NAMain": return [.Temperature,.CO2,.Humidity,.Pressure,.Noise] case "NAModule1","NAModule4": return [.Temperature,.Humidity] case "NAModule3": return [.Rain] case "NAModule2": return [.WindStrength,.WindAngle] default: return [] } } } class NetadmoModuleProvider { private let coreDataStore: CoreDataStore! init(coreDataStore : CoreDataStore?) { if (coreDataStore != nil) { self.coreDataStore = coreDataStore } else { self.coreDataStore = CoreDataStore() } } func save() { try! coreDataStore.managedObjectContext.save() } func modules()->Array<NetatmoModule> { let fetchRequest = NSFetchRequest(entityName: kQSModule) fetchRequest.fetchLimit = 1 let results = try! coreDataStore.managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject] return results.map{NetatmoModule(managedObject: $0 )} } func createModule(id: String, name: String, type : String, stationId : String)->NSManagedObject { let newModule = NSManagedObject(entity: coreDataStore.managedObjectContext.persistentStoreCoordinator!.managedObjectModel.entitiesByName[kQSModule]!, insertIntoManagedObjectContext: coreDataStore.managedObjectContext) newModule.setValue(id, forKey: kQSModuleId) newModule.setValue(name, forKey: kQSModuleName) newModule.setValue(type, forKey: kQSModuleType) newModule.setValue(stationId, forKey: kQSParentStationId) try! coreDataStore.managedObjectContext.save() return newModule } func getModuleWithId(id: String)->NSManagedObject? { let fetchRequest = NSFetchRequest(entityName: kQSModule) fetchRequest.predicate = NSPredicate(format: "\(kQSModuleId) == %@", argumentArray: [id]) fetchRequest.fetchLimit = 1 let results = try! coreDataStore.managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject] return results.first } }
602c7382a99e1a6e1a56604ee262a3ed
29.670103
221
0.726967
false
false
false
false
acastano/swift-bootstrap
refs/heads/master
foundationkit/Sources/Classes/Extensions/Primitives/String+Crypto.swift
apache-2.0
1
import Foundation import CommonCrypto public extension String { public func sha1() -> String? { var output: NSMutableString? if let data = dataUsingEncoding(NSUTF8StringEncoding) { var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue:0) CC_SHA1(data.bytes, CC_LONG(data.length), &digest) output = NSMutableString(capacity:Int(CC_SHA1_DIGEST_LENGTH)) for byte in digest { output?.appendFormat("%02x", byte) } } var string: String? if let output = output { string = String(output) } return string } public func applyHmac(key: String) -> String? { return "" } public func hmac(key: String) -> String? { var hmac: String? if let cData = cStringUsingEncoding(NSUTF8StringEncoding), let cKey = key.cStringUsingEncoding(NSUTF8StringEncoding) { let digestLenght = Int(CC_SHA1_DIGEST_LENGTH) let cHMAC = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLenght) CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), cKey, Int(strlen(cKey)), cData, Int(strlen(cData)), cHMAC) let hash = NSMutableString() for i in 0..<digestLenght { hash.appendFormat("%02x", cHMAC[i]) } hmac = String(hash) } return hmac } }
533b844de6ec5aa8fe4fcc98a9c43902
23.150685
126
0.470788
false
false
false
false
AndersHqst/SwiftRestFramework
refs/heads/master
SwiftServer/main.swift
mit
1
// // main.swift // SwiftServer // // Created by Anders Høst Kjærgaard on 15/08/2015. // Copyright (c) 2015 hqst IT. All rights reserved. // import Foundation let server = HttpServer() // Custom endpoint server["endpoint"] = { request in return HttpResponse(text: "Hello world") } // Custom endpoint server["json"] = { request in switch request.method { case .POST: // Do something with the body return Created(json: request.body) case .GET: return OK(json: ["foo": "bar"]) default: return MethodNotAllowed() } } // POST and GET /users. No validation. Subject to a "users" collection server["/users"] = Create(resource: "users").handler // GET /readonly-users. Returns the "users" collection server["/readonly-users"] = Read(resource: "users").handler server.run()
ec0c59dff6ddc0d8437af264a4a5dab5
19.023256
70
0.632985
false
false
false
false
MadAppGang/refresher
refs/heads/master
Refresher/ConnectionLostExtension.swift
mit
1
// // ConnectionLostExtension.swift // Pods // // Created by Ievgen Rudenko on 21/10/15. // // import Foundation import ReachabilitySwift private let сonnectionLostTag = 1326 private let ConnectionLostViewDefaultHeight: CGFloat = 24 extension UIScrollView { // View on top that shows "connection lost" public var сonnectionLostView: ConnectionLostView? { get { let theView = viewWithTag(сonnectionLostTag) as? ConnectionLostView return theView } } // If you want to connection lost functionality to your UIScrollView just call this method and pass action closure you want to execute when Reachabikity changed. If you want to stop showing reachability view you must do that manually calling hideReachabilityView methods on your scroll view public func addReachability(action:(newStatus: Reachability.NetworkStatus) -> ()) { let frame = CGRectMake(0, -ConnectionLostViewDefaultHeight, self.frame.size.width, ConnectionLostViewDefaultHeight) let defaultView = ConnectionLostDefaultSubview(frame: frame) let reachabilityView = ConnectionLostView(view:defaultView, action:action) reachabilityView.tag = сonnectionLostTag reachabilityView.hidden = true addSubview(reachabilityView) } public func addReachabilityView(view:UIView, action:(newStatus: Reachability.NetworkStatus) -> ()) { let reachabilityView = ConnectionLostView(view:view, action:action) reachabilityView.tag = сonnectionLostTag reachabilityView.hidden = true addSubview(reachabilityView) } // Manually start pull to refresh public func showReachabilityView() { сonnectionLostView?.becomeUnreachable() } // Manually stop pull to refresh public func hideReachabilityView() { сonnectionLostView?.becomeReachable() } }
01f4bde6b5885308672feb18a20bbcb2
33.654545
294
0.717585
false
false
false
false
ainopara/Stage1st-Reader
refs/heads/master
Stage1st/Manager/DiscuzClient/Utilities/Transformers/StringDateTransformer.swift
bsd-3-clause
1
// // StringDateTransformer.swift // Stage1st // // Created by Zheng Li on 2018/11/3. // Copyright © 2018 Renaissance. All rights reserved. // import CodableExtensions struct StringDateTransformer: DecodingContainerTransformer { typealias Input = String typealias Output = Date enum DateType { case secondSince1970 } let dateType: DateType init(dateType: DateType) { self.dateType = dateType } func transform(_ decoded: String) throws -> Date { switch self.dateType { case .secondSince1970: guard let intValue = Int(decoded) else { throw "Failed to transform \(decoded) to Int." } guard intValue >= 0 else { throw "Invalid time interval \(intValue)." } return Date(timeIntervalSince1970: TimeInterval(intValue)) } } }
a1cf8145cb96d556846829de334259be
21.475
70
0.606229
false
false
false
false
biohazardlover/NintendoEverything
refs/heads/master
Pods/SwiftSoup/Sources/TreeBuilder.swift
mit
5
// // TreeBuilder.swift // SwiftSoup // // Created by Nabil Chatbi on 24/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation public class TreeBuilder { public var reader: CharacterReader var tokeniser: Tokeniser public var doc: Document // current doc we are building into public var stack: Array<Element> // the stack of open elements public var baseUri: String // current base uri, for creating new elements public var currentToken: Token? // currentToken is used only for error tracking. public var errors: ParseErrorList // null when not tracking errors public var settings: ParseSettings private let start: Token.StartTag = Token.StartTag() // start tag to process private let end: Token.EndTag = Token.EndTag() public func defaultSettings() -> ParseSettings {preconditionFailure("This method must be overridden")} public init() { doc = Document("") reader = CharacterReader("") tokeniser = Tokeniser(reader, nil) stack = Array<Element>() baseUri = "" errors = ParseErrorList(0, 0) settings = ParseSettings(false, false) } public func initialiseParse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings) { doc = Document(baseUri) self.settings = settings reader = CharacterReader(input) self.errors = errors tokeniser = Tokeniser(reader, errors) stack = Array<Element>() self.baseUri = baseUri } func parse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Document { initialiseParse(input, baseUri, errors, settings) try runParser() return doc } public func runParser()throws { while (true) { let token: Token = try tokeniser.read() try process(token) token.reset() if (token.type == Token.TokenType.EOF) { break } } } @discardableResult public func process(_ token: Token)throws->Bool {preconditionFailure("This method must be overridden")} @discardableResult public func processStartTag(_ name: String)throws->Bool { if (currentToken === start) { // don't recycle an in-use token return try process(Token.StartTag().name(name)) } return try process(start.reset().name(name)) } @discardableResult public func processStartTag(_ name: String, _ attrs: Attributes)throws->Bool { if (currentToken === start) { // don't recycle an in-use token return try process(Token.StartTag().nameAttr(name, attrs)) } start.reset() start.nameAttr(name, attrs) return try process(start) } @discardableResult public func processEndTag(_ name: String)throws->Bool { if (currentToken === end) { // don't recycle an in-use token return try process(Token.EndTag().name(name)) } return try process(end.reset().name(name)) } public func currentElement() -> Element? { let size: Int = stack.count return size > 0 ? stack[size-1] : nil } }
a1ce8932645de45779972f5bfcd7cc1b
31.897959
122
0.634615
false
false
false
false
firebase/FirebaseUI-iOS
refs/heads/master
samples/swift/FirebaseUI-demo-swift/Samples/Auth/FUIAuthViewController.swift
apache-2.0
1
// // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import FirebaseAuth import FirebaseEmailAuthUI import FirebaseFacebookAuthUI import FirebaseAnonymousAuthUI import FirebasePhoneAuthUI import FirebaseOAuthUI import FirebaseGoogleAuthUI let kFirebaseTermsOfService = URL(string: "https://firebase.google.com/terms/")! let kFirebasePrivacyPolicy = URL(string: "https://firebase.google.com/support/privacy/")! enum UISections: Int, RawRepresentable { case Settings = 0 case Providers case AnonymousSignIn case Name case Email case UID case Phone case AccessToken case IDToken } enum Providers: Int, RawRepresentable { case Email = 0 case Google case Facebook case Twitter case Apple case Phone } /// A view controller displaying a basic sign-in flow using FUIAuth. class FUIAuthViewController: UITableViewController { // Before running this sample, make sure you've correctly configured // the appropriate authentication methods in Firebase console. For more // info, see the Auth README at ../../FirebaseAuthUI/README.md // and https://firebase.google.com/docs/auth/ fileprivate var authStateDidChangeHandle: AuthStateDidChangeListenerHandle? fileprivate(set) var auth: Auth? = Auth.auth() fileprivate(set) var authUI: FUIAuth? = FUIAuth.defaultAuthUI() fileprivate(set) var customAuthUIDelegate: FUIAuthDelegate = FUICustomAuthDelegate() @IBOutlet weak var cellSignedIn: UITableViewCell! @IBOutlet weak var cellName: UITableViewCell! @IBOutlet weak var cellEmail: UITableViewCell! @IBOutlet weak var cellUid: UITableViewCell! @IBOutlet weak var cellPhone: UITableViewCell! @IBOutlet weak var cellAccessToken: UITableViewCell! @IBOutlet weak var cellIdToken: UITableViewCell! @IBOutlet weak var cellAnonymousSignIn: UITableViewCell! @IBOutlet weak var authorizationButton: UIBarButtonItem! @IBOutlet weak var customAuthorizationSwitch: UISwitch! @IBOutlet weak var customScopesSwitch: UISwitch! @IBOutlet weak var facebookSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() self.authUI?.tosurl = kFirebaseTermsOfService self.authUI?.privacyPolicyURL = kFirebasePrivacyPolicy self.tableView.selectRow(at: IndexPath(row: Providers.Email.rawValue, section: UISections.Providers.rawValue), animated: false, scrollPosition: .none) self.tableView.selectRow(at: IndexPath(row: Providers.Google.rawValue, section: UISections.Providers.rawValue), animated: false, scrollPosition: .none) self.tableView.selectRow(at: IndexPath(row: Providers.Facebook.rawValue, section: UISections.Providers.rawValue), animated: false, scrollPosition: .none) self.tableView.selectRow(at: IndexPath(row: Providers.Twitter.rawValue, section: UISections.Providers.rawValue), animated: false, scrollPosition: .none) self.tableView.selectRow(at: IndexPath(row: Providers.Apple.rawValue, section: UISections.Providers.rawValue), animated: false, scrollPosition: .none) self.tableView.selectRow(at: IndexPath(row: Providers.Phone.rawValue, section: UISections.Providers.rawValue), animated: false, scrollPosition: .none) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.rowHeight = UITableView.automaticDimension; self.tableView.estimatedRowHeight = 240; self.authStateDidChangeHandle = self.auth?.addStateDidChangeListener(self.updateUI(auth:user:)) self.navigationController?.isToolbarHidden = false; } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let handle = self.authStateDidChangeHandle { self.auth?.removeStateDidChangeListener(handle) } self.navigationController?.isToolbarHidden = true; } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath.section == UISections.AnonymousSignIn.rawValue && indexPath.row == 0) { if (auth?.currentUser?.isAnonymous ?? false) { tableView.deselectRow(at: indexPath, animated: false) return; } do { try self.authUI?.signOut() } catch let error { self.ifNoError(error) {} } auth?.signInAnonymously() { authReuslt, error in self.ifNoError(error) { self.showAlert(title: "Signed In Anonymously") } } tableView.deselectRow(at: indexPath, animated: false) } } fileprivate func showAlert(title: String, message: String? = "") { if #available(iOS 8.0, *) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (UIAlertAction) in alertController.dismiss(animated: true, completion: nil) })) self.present(alertController, animated: true, completion: nil) } else { UIAlertView(title: title, message: message ?? "", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "OK").show() } } private func ifNoError(_ error: Error?, execute: () -> Void) { guard error == nil else { showAlert(title: "Error", message: error!.localizedDescription) return } execute() } @IBAction func onAuthorize(_ sender: AnyObject) { if (self.auth?.currentUser) != nil { if (auth?.currentUser?.isAnonymous != false) { auth?.currentUser?.delete() { error in self.ifNoError(error) { self.showAlert(title: "", message:"The user was properly deleted.") } } } else { do { try self.authUI?.signOut() } catch let error { self.ifNoError(error) { self.showAlert(title: "Error", message:"The user was properly signed out.") } } } } else { self.authUI?.delegate = self.customAuthorizationSwitch.isOn ? self.customAuthUIDelegate : nil; // If you haven't set up your authentications correctly these buttons // will still appear in the UI, but they'll crash the app when tapped. self.authUI?.providers = self.getListOfIDPs() let providerID = self.authUI?.providers.first?.providerID; let isPhoneAuth = providerID == PhoneAuthProviderID; let isEmailAuth = providerID == EmailAuthProviderID; let shouldSkipAuthPicker = self.authUI?.providers.count == 1 && (isPhoneAuth || isEmailAuth); if (shouldSkipAuthPicker) { if (isPhoneAuth) { let provider = self.authUI?.providers.first as! FUIPhoneAuth; provider.signIn(withPresenting: self, phoneNumber: nil); } else if (isEmailAuth) { let provider = self.authUI?.providers.first as! FUIEmailAuth; provider.signIn(withPresenting: self, email: nil); } } else { let controller = self.authUI!.authViewController() controller.navigationBar.isHidden = self.customAuthorizationSwitch.isOn self.present(controller, animated: true, completion: nil) } } } // Boilerplate func updateUI(auth: Auth, user: User?) { if let user = self.auth?.currentUser { self.cellSignedIn.textLabel?.text = "Signed in" self.cellName.textLabel?.text = user.displayName ?? "(null)" self.cellEmail.textLabel?.text = user.email ?? "(null)" self.cellUid.textLabel?.text = user.uid self.cellPhone.textLabel?.text = user.phoneNumber if (auth.currentUser?.isAnonymous != false) { self.authorizationButton.title = "Delete Anonymous User"; } else { self.authorizationButton.title = "Sign Out"; } } else { self.cellSignedIn.textLabel?.text = "Not signed in" self.cellName.textLabel?.text = "null" self.cellEmail.textLabel?.text = "null" self.cellUid.textLabel?.text = "null" self.cellPhone.textLabel?.text = "null" self.authorizationButton.title = "Sign In"; } self.cellAccessToken.textLabel?.text = getAllAccessTokens() self.cellIdToken.textLabel?.text = getAllIdTokens() let selectedRows = self.tableView.indexPathsForSelectedRows self.tableView.reloadData() if let rows = selectedRows { for path in rows { self.tableView.selectRow(at: path, animated: false, scrollPosition: .none) } } } func getAllAccessTokens() -> String { var result = "" for provider in self.authUI!.providers { result += (provider.shortName + ": " + (provider.accessToken ?? "null") + "\n") } return result } func getAllIdTokens() -> String { var result = "" for provider in self.authUI!.providers { result += (provider.shortName + ": " + (provider.idToken! ?? "null") + "\n") } return result } func getListOfIDPs() -> [FUIAuthProvider] { var providers = [FUIAuthProvider]() if let selectedRows = self.tableView.indexPathsForSelectedRows { for indexPath in selectedRows { if indexPath.section == UISections.Providers.rawValue { let provider:FUIAuthProvider? switch indexPath.row { case Providers.Email.rawValue: provider = FUIEmailAuth() case Providers.Google.rawValue: provider = self.customScopesSwitch.isOn ? FUIGoogleAuth(authUI: self.authUI!, scopes: [kGoogleGamesScope, kGooglePlusMeScope, kGoogleUserInfoEmailScope, kGoogleUserInfoProfileScope]) : FUIGoogleAuth(authUI: self.authUI!) case Providers.Twitter.rawValue: let buttonColor = UIColor(red: 71.0/255.0, green: 154.0/255.0, blue: 234.0/255.0, alpha: 1.0) guard let iconPath = Bundle.main.path(forResource: "twtrsymbol", ofType: "png") else { NSLog("Warning: Unable to find Twitter icon") continue } provider = FUIOAuth(authUI: self.authUI!, providerID: "twitter.com", buttonLabelText: "Sign in with Twitter", shortName: "Twitter", buttonColor: buttonColor, iconImage: UIImage(contentsOfFile: iconPath)!, scopes: ["user.readwrite"], customParameters: ["prompt" : "consent"], loginHintKey: nil) case Providers.Facebook.rawValue: provider = self.customScopesSwitch.isOn ? FUIFacebookAuth(authUI: self.authUI!, permissions: ["email", "user_friends", "ads_read"]) : FUIFacebookAuth(authUI: self.authUI!) let facebookProvider = provider as! FUIFacebookAuth facebookProvider.useLimitedLogin = self.facebookSwitch.isOn case Providers.Apple.rawValue: if #available(iOS 13.0, *) { provider = FUIOAuth.appleAuthProvider() } else { provider = nil } case Providers.Phone.rawValue: provider = FUIPhoneAuth(authUI: self.authUI!) default: provider = nil } guard provider != nil else { continue } providers.append(provider!) } } } return providers } }
94013ad8a266e6bed8e6e23ba74cdb4f
37.114035
117
0.614653
false
false
false
false
Bartlebys/Bartleby
refs/heads/master
Bartleby.xOS/bsfs/BSFS.swift
apache-2.0
1
// // BSFS.swift // BartlebyKit // // Created by Benoit Pereira da silva on 02/11/2016. // // import Foundation /// The BSFS is set per document. /// File level operations are done on GCD global utility queue. public final class BSFS:TriggerHook{ // MARK: - // If set to false we use the sandBoxing Context // else we use the `exportPath` (CLI context) static var useExportPath = false static var exportPath:String = Bartleby.getSearchPath(.desktopDirectory) ?? Default.NO_PATH // Document fileprivate var _document:BartlebyDocument /// The File manager used to perform all the BSFS operation on GCD global utility queue. /// Note that we also use specific FileHandle at chunk level fileprivate let _fileManager:FileManager=FileManager() /// Chunk level operations fileprivate let _chunker:Chunker // The box Delegate fileprivate var _boxDelegate:BoxDelegate? // The current accessors key:node.UID, value:Array of Accessors fileprivate var _accessors=[String:[NodeAccessor]]() /// Store the blocks UIDs that need to be uploaded fileprivate var _toBeUploadedBlocksUIDS=[String]() // Store the blocks UIDs that need to be downloaded fileprivate var _toBeDownloadedBlocksUIDS=[String]() /// The downloads operations in progrees fileprivate var _downloadsInProgress=[DownloadBlock]() /// The uploads operations in progrees fileprivate var _uploadsInProgress=[UploadBlock]() /// Max Simultaneous operations ( per operation type and per bsfs instance. ) fileprivate var _maxSimultaneousOperations=1 // MARK: - initialization /// Each document has it own BSFS /// /// - Parameter document: the document instance required public init(in document:BartlebyDocument){ self._document=document self._chunker=Chunker(fileManager: FileManager.default, mode:.digestAndProcessing, embeddedIn:document) self._boxDelegate=document } // MARK: - Persistency /// Serialize the local state of the BSFS /// /// - Returns: the serialized data public func saveState()->Data{ let state=["toBeUploaded":self._toBeUploadedBlocksUIDS, "toBeDownloaded":self._toBeDownloadedBlocksUIDS] if let data = try? JSONSerialization.data(withJSONObject: state){ return data } return Data() } /// Restore the state /// /// - Parameter data: from the serialized state data public func restoreStateFrom(data:Data)throws->(){ if let state = try? JSONSerialization.jsonObject(with: data) as? [String:[String]]{ self._toBeDownloadedBlocksUIDS=state?["toBeDownloaded"] ?? [String]() self._toBeUploadedBlocksUIDS=state?["toBeUploaded"] ?? [String]() } } // MARK: - Paths /// The BSFS base folder path /// --- /// baseFolder/ /// - boxes/<boxUID>/[files] /// - downloads/[files] tmp download files public var baseFolderPath:String{ if BSFS.useExportPath{ return BSFS.exportPath } if self._document.metadata.appGroup != ""{ if let url=self._fileManager.containerURL(forSecurityApplicationGroupIdentifier: self._document.metadata.appGroup){ return url.path+"/\(_document.UID)" } } return Bartleby.getSearchPath(.documentDirectory)!+"/\(_document.UID)" } /// Downloads folder public var downloadFolderPath:String{ return baseFolderPath+"/downloads" } /// Boxes folder public var boxesFolderPath:String{ return baseFolderPath+"/boxes" } //MARK: - Box Level /// Mounts the current local box == Assemble all its assemblable nodes /// There is no guarantee that the box is not fully up to date /// /// - Parameters: /// - boxUID: the Box UID /// - progressed: a closure to relay the Progression State /// - completed: a closure called on completion with Completion State. /// the box UID is stored in the completion.getResultExternalReference() public func mount( boxUID:String, progressed:@escaping (Progression)->(), completed:@escaping (Completion)->()){ do { let box = try Bartleby.registredObjectByUID(boxUID) as Box self._document.send(BoxStates.isMounting(box: box)) if box.assemblyInProgress || box.isMounted { throw BSFSError.attemptToMountBoxMultipleTime(boxUID: boxUID) } var concernedNodes=[Node]() let group=AsyncGroup() group.utility{ try? self._fileManager.createDirectory(atPath: box.nodesFolderPath, withIntermediateDirectories: true, attributes: nil) } group.wait() // Let's try to assemble as much nodes as we can. let nodes=box.nodes for node in nodes{ let isNotAssembled = !self.isAssembled(node) let isAssemblable = node.isAssemblable if node.isAssemblable && isNotAssembled{ concernedNodes.append(node) } } box.quietChanges{ box.assemblyProgression.totalTaskCount=concernedNodes.count box.assemblyProgression.currentTaskIndex=0 box.assemblyProgression.currentPercentProgress=0 } // We want to assemble the node sequentially. // So we will use a recursive pop method func __popNode(){ if let node=concernedNodes.popLast(){ node.assemblyInProgress=true do{ try self._assemble(node: node, progressed: { (progression) in progressed(progression) }, completed: { (completion) in node.assemblyInProgress=false box.assemblyProgression.currentTaskIndex += 1 box.assemblyProgression.currentPercentProgress=Double(box.assemblyProgression.currentTaskIndex)*Double(100)/Double(box.assemblyProgression.totalTaskCount) __popNode() }) }catch{ self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false) completed(Completion.failureStateFromError(error)) } }else{ box.assemblyInProgress=false box.isMounted=true let completionState=Completion.successState() completionState.setExternalReferenceResult(from:box) completed(completionState) self._document.send(BoxStates.hasBeenMounted(box: box)) } } // Call the first pop. __popNode() } catch { let resolvedBox:Box? = try? Bartleby.registredObjectByUID(boxUID) resolvedBox?.assemblyInProgress = false completed(Completion.failureStateFromError(error)) self._document.send(BoxStates.mountingHasFailed(boxUID:boxUID,message: "\(error)")) } } public func unMountAllBoxes(){ self._document.boxes.forEach { (box) in self.unMount(box: box) } let group=AsyncGroup() group.utility{ try? self._fileManager.removeItem(atPath: self.boxesFolderPath) } group.wait() } /// Un mounts the Box == deletes all the assembled files /// /// - Parameters: /// - boxUID: the Box UID /// - completed: a closure called on completion with Completion State. public func unMount( boxUID:String, completed:@escaping (Completion)->()){ do { let box = try Bartleby.registredObjectByUID(boxUID) as Box self.unMount(box: box) completed(Completion.successState()) }catch{ completed(Completion.failureStateFromError(error)) } } public func unMount(box:Box)->(){ for node in box.nodes{ if let accessors=self._accessors[node.UID]{ for accessor in accessors{ accessor.willBecomeUnusable(node: node) } } let assembledPath=self.assemblyPath(for:node) let group=AsyncGroup() group.utility{ try? self._fileManager.removeItem(atPath: assembledPath) } group.wait() } let group=AsyncGroup() group.utility{ try? self._fileManager.removeItem(atPath: box.nodesFolderPath) } group.wait() box.isMounted=false box.assemblyInProgress=false } /// /// - Parameter node: the node /// - Returns: the assembled path (created if there no public func assemblyPath(for node:Node)->String{ if let box=node.box{ return self.assemblyPath(for: box)+node.relativePath } return Default.NO_PATH } public func assemblyPath(for box:Box)->String{ return box.nodesFolderPath } /// Return is the node file has been assembled /// /// - Parameter node: the node /// - Returns: true if the file is available and the node not marked assemblyInProgress public func isAssembled(_ node:Node)->Bool{ if node.assemblyInProgress { // Return false if the assembly is in progress return false } let group=AsyncGroup() var isAssembled=false group.utility{ let path=self.assemblyPath(for: node) isAssembled=self._fileManager.fileExists(atPath: path) if isAssembled{ if let attributes = try? self._fileManager.attributesOfItem(atPath: path){ if let size:Int=attributes[FileAttributeKey.size] as? Int{ if size != node.size{ self._document.log("Divergent size node Size:\(node.size) fs.size: \(size) ", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false) isAssembled=false } } } } } group.wait() return isAssembled } /// Creates a file from the node blocks. /// IMPORTANT: this method requires a response from the BoxDelegate /// /// - Parameters: /// - node: the node /// - progressed: a closure to relay the Progression State /// - completed: a closure called on completion with Completion State. /// the node UID is stored in the completion.getResultExternalReference() internal func _assemble(node:Node, progressed:@escaping (Progression)->(), completed:@escaping (Completion)->()) throws->(){ do { if node.isAssemblable == false{ throw BSFSError.nodeIsNotAssemblable } if let delegate = self._boxDelegate{ delegate.nodeIsReady(node: node, proceed: { let path=self.assemblyPath(for: node) let blocks=node.blocks.sorted(by: { (rblock, lblock) -> Bool in return rblock.rank < lblock.rank }) if node.nature == .file || node.nature == .flock { var blockPaths=[String]() for block in blocks{ // The blocks are embedded in a document // So we use the relative path blockPaths.append(block.blockRelativePath()) } self._chunker.joinChunksToFile(from: blockPaths, to: path, decompress: node.compressedBlocks, decrypt: node.cryptedBlocks, externalId:node.UID, progression: { (progression) in progressed(progression) }, success: { path in if node.nature == .flock{ //TODO // FLOCK path == path let completionState=Completion.successState() completionState.setExternalReferenceResult(from:node) completed(completionState) }else{ // The file has been assembled let completionState=Completion.successState() completionState.setExternalReferenceResult(from:node) completed(completionState) } }, failure: { (message) in let completion=Completion() completion.message=message completion.success=false completion.externalIdentifier=node.UID completed(completion) }) }else if node.nature == .alias{ Async.utility{ do{ if let rNodeUID=node.referentNodeUID{ if let rNode = try? Bartleby.registredObjectByUID(rNodeUID) as Node{ let destination=self.assemblyPath(for: rNode) try self._fileManager.createSymbolicLink(atPath: path, withDestinationPath:destination) let completionState=Completion.successState() completionState.setExternalReferenceResult(from:node) completed(completionState) }else{ completed(Completion.failureState("Unable to find Alias referent node", statusCode:.expectation_Failed)) } }else{ completed(Completion.failureState("Unable to find Alias destination", statusCode:.expectation_Failed)) } }catch{ completed(Completion.failureStateFromError(error)) } } }else if node.nature == .folder{ Async.utility{ do{ try self._fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) let completionState=Completion.successState() completionState.setExternalReferenceResult(from:node) completed(completionState) }catch{ completed(Completion.failureStateFromError(error)) } } } }) }else{ throw BSFSError.boxDelegateIsNotAvailable } } catch{ completed(Completion.failureStateFromError(error)) } } //MARK: - File Level /// Adds a file or all the file from o folder into the box /// Flocks may be supported soon /// /// + generate the blocks in background. /// + adds the node(s) /// + the first node UID is stored in the Completion (use completion.getResultExternalReference()) /// /// - Parameters: /// - FileReference: the file reference (Nature == file or flock) /// - box: the box /// - relativePath: the relative Path of the Node in the box /// - deleteOriginal: should we delete the original? /// - progressed: a closure to relay the Progression State /// - completed: a closure called on completion with Completion State /// the node UID is stored in the completion.getResultExternalReference() public func add( reference:FileReference, in box:Box, to relativePath:String, deleteOriginal:Bool=false, progressed:@escaping (Progression)->(), completed:@escaping (Completion)->()){ var fileExistsAtPath = false let group=AsyncGroup() group.utility{ fileExistsAtPath = self._fileManager.fileExists(atPath: reference.absolutePath) } group.wait() if fileExistsAtPath{ var firstNode:Node? func __chunksHaveBeenCreated(chunks:[Chunk]){ // Successful operation // Let's Upsert the distant models. // AND the local nodes let groupedChunks=Chunk.groupByNodePath(chunks: chunks) for (nodeRelativePath,groupOfChunks) in groupedChunks{ // Create the new node. // And add its blocks let node=self._document.newManagedModel() as Node if firstNode==nil{ firstNode=node } node.quietChanges{ node.nature=reference.nodeNature.forNode node.relativePath=relativePath/// node.priority=reference.priority // Set up the node relative path node.relativePath=nodeRelativePath var cumulatedDigests="" var cumulatedSize=0 box.quietChanges { box.declaresOwnership(of: node) } // Let's add the blocks for chunk in groupOfChunks{ let block=self._document.newManagedModel() as Block block.quietChanges{ block.rank=chunk.rank block.digest=chunk.sha1 block.startsAt=chunk.startsAt block.size=chunk.originalSize block.priority=reference.priority } cumulatedSize += chunk.originalSize cumulatedDigests += chunk.sha1 node.addBlock(block) self._toBeUploadedBlocksUIDS.append(block.UID) } // Store the digest of the cumulated digests. node.digest=cumulatedDigests.sha1 // And the node original size node.size=cumulatedSize } // Add the file in the box if it is mounted. if box.isMounted{ let nodeAssemblyPath = self.assemblyPath(for:node) do { try self._fileManager.copyItem(atPath: reference.absolutePath, toPath: nodeAssemblyPath) }catch{ self._document.log("Original Copy has failed. \nReferencePath:\( reference.absolutePath) \nassemblyPath:\(nodeAssemblyPath)",category: Default.LOG_BSFS) } } } // Delete the original if deleteOriginal{ // We consider deletion as non mandatory. // So we produce only a log. do { try self._fileManager.removeItem(atPath: reference.absolutePath) } catch { self._document.log("Deletion has failed. Path:\( reference.absolutePath)",file: Default.LOG_BSFS) } } let finalState=Completion.successState() if let node=firstNode{ finalState.setExternalReferenceResult(from:node) } completed(finalState) // Call the centralized upload mechanism self._uploadNext() } Async.utility{ if reference.nodeNature == .file{ var isDirectory:ObjCBool=false if self._fileManager.fileExists(atPath: reference.absolutePath, isDirectory: &isDirectory){ if isDirectory.boolValue{ self._chunker.breakFolderIntoChunk(filesIn: reference.absolutePath, chunksFolderPath: box.nodesFolderPath, progression: { (progression) in progressed(progression) }, success: { (chunks) in __chunksHaveBeenCreated(chunks: chunks) }, failure: { (chunks, message) in completed(Completion.failureState(message, statusCode: .expectation_Failed)) }) }else{ /// Let's break the file into chunk. self._chunker.breakIntoChunk( fileAt: reference.absolutePath, relativePath:relativePath, chunksFolderPath: box.nodesFolderPath, chunkMaxSize:reference.chunkMaxSize, compress: reference.compressed, encrypt: reference.crypted, progression: { (progression) in progressed(progression) } , success: { (chunks) in __chunksHaveBeenCreated(chunks: chunks) }, failure: { (message) in completed(Completion.failureState(message, statusCode: .expectation_Failed)) }) } }else{ let message=NSLocalizedString("Unexisting path: ", tableName:"system", comment: "Unexisting path: ")+reference.absolutePath completed(Completion.failureState(message, statusCode: .expectation_Failed)) } } if reference.nodeNature == .flock{ // @TODO } } }else{ completed(Completion.failureState(NSLocalizedString("Reference Not Found!", tableName:"system", comment: "Reference Not Found!")+" \(reference.absolutePath)", statusCode: .not_Found)) } } /// Call to replace the content of a file node with a given file. (alias, flocks, folders are not supported) /// This action may be refused by the BoxDelegate (check the completion state) /// /// Delta Optimization: /// We first compute the `deltaChunks` to determine if some Blocks can be preserved /// Then we `breakIntoChunk` the chunks that need to be chunked. /// /// /// - Parameters: /// - node: the concerned node /// - path: the file path /// - deleteOriginal: should we destroy the original file /// - accessor: the accessor that ask for replacement /// - progressed: a closure to relay the Progression State /// - completed: a closure called on completion with Completion State. /// the node UID is stored in the completion.getResultExternalReference() func replaceContent(of node:Node, withContentAt path:String, deleteOriginal:Bool, accessor:NodeAccessor, progressed:@escaping (Progression)->(), completed:@escaping (Completion)->()){ if node.nature == .file{ if node.authorized.contains(self._document.currentUser.UID) || node.authorized.contains("*"){ var isDirectory:ObjCBool=false var fileExistsAtPath = false let group=AsyncGroup() group.utility{ fileExistsAtPath = self._fileManager.fileExists(atPath:path, isDirectory: &isDirectory) } group.wait() if fileExistsAtPath{ if isDirectory.boolValue{ completed(Completion.failureState(NSLocalizedString("Forbidden! Replacement is restricted to single files not folder", tableName:"system", comment: "Forbidden! Replacement is restricted to single files not folder"), statusCode: .forbidden)) }else{ if let box=node.box{ let analyzer=DeltaAnalyzer(embeddedIn: self._document) ////////////////////////////// // #1 We first compute the `deltaChunks` to determine if some Blocks can be preserved ////////////////////////////// analyzer.deltaChunks(fromFileAt: path, to: node, using: self._fileManager, completed: { (toBePreserved, toBeDeleted) in /// delete the blocks to be deleted for chunk in toBeDeleted{ if let block=self._findBlockMatching(chunk: chunk){ self.deleteBlockFile(block) } } ///////////////////////////////// // #2 Then we `breakIntoChunk` the chunks that need to be chunked. ///////////////////////////////// self._chunker.breakIntoChunk(fileAt: path, relativePath: node.relativePath, chunksFolderPath: box.nodesFolderPath, compress: node.compressedBlocks, encrypt: node.cryptedBlocks, excludeChunks:toBePreserved, progression: { (progression) in progressed(progression) } , success: { (chunks) in // Successful operation // Let's Upsert the node. // AND create the local node node.quietChanges{ var cumulatedDigests="" var cumulatedSize=0 // Let's add the blocks for chunk in chunks{ var block:Block? if let b=self._findBlockMatching(chunk: chunk){ block=b block?.needsToBeCommitted() }else{ block=self._document.newManagedModel() as Block node.quietChanges { block!.quietChanges { node.addBlock(block!) } } } block!.quietChanges{ block!.rank=chunk.rank block!.digest=chunk.sha1 block!.startsAt=chunk.startsAt block!.size=chunk.originalSize block!.priority=node.priority } cumulatedDigests += chunk.sha1 cumulatedSize += chunk.originalSize } // Store the digest of the cumulated digests. node.digest=cumulatedDigests.sha1 // And the node original size node.size=cumulatedSize } // Mark the node to be committed node.needsToBeCommitted() // Delete the original Async.utility{ if deleteOriginal{ // We consider deletion as non mandatory. // So we produce only a log. do { try self._fileManager.removeItem(atPath: path) } catch { self._document.log("Deletion has failed. Path:\( path)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false) } } } let finalState=Completion.successState() finalState.setExternalReferenceResult(from:node) completed(finalState) // Call the centralized upload mechanism self._uploadNext() }, failure: { (message) in completed(Completion.failureState(message, statusCode: .expectation_Failed)) }) }, failure: { (message) in completed(Completion.failureState(message, statusCode: .expectation_Failed)) }) }else{ completed(Completion.failureState(NSLocalizedString("Forbidden! Box not found", tableName:"system", comment: "Forbidden! Box not found"), statusCode: .forbidden)) } } } }else{ completed(Completion.failureState(NSLocalizedString("Forbidden! Replacement refused", tableName:"system", comment: "Forbidden! Replacement refused"), statusCode: .forbidden)) } }else{ completed(Completion.failureState("\(node.nature)", statusCode: .precondition_Failed)) } } //MARK: - Node Level //MARK: Access /// Any accessor to obtain access to the resource (file) of a node need to call this method. /// The nodeIsUsable() will be called when the file will be usable. /// /// WHY? /// Because there is no guarantee that the node is locally available. /// The application may work with a file that is available or another computer, with pending synchro. /// /// By registering as accessor, the caller will be notified as soon as possible. /// /// /// - Parameters: /// - node: the node /// - accessor: the accessor public func wantsAccess(to node:Node,accessor:NodeAccessor){ // The nodeIsUsable() will be called when the file will be usable. if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){ if self._accessors[node.UID] != nil { self._accessors[node.UID]=[NodeAccessor]() } if !self._accessors[node.UID]!.contains(where: {$0.UID==accessor.UID}){ self._accessors[node.UID]!.append(accessor) } if self.isAssembled(node){ self._grantAccess(to: node, accessor: accessor) } }else{ accessor.accessRefused(to:node, explanations: NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed")) } } /// Should be called when the accessor does not need any more the node resource. /// /// - Parameters: /// - node: the node /// - accessor: the accessor public func stopsAccessing(to node:Node,accessor:NodeAccessor){ if let idx=self._accessors[node.UID]?.index(where: {$0.UID==accessor.UID}){ self._accessors[node.UID]!.remove(at: idx) } } /// Grants the access /// /// - Parameters: /// - node: to the node /// - accessor: for an Accessor fileprivate func _grantAccess(to node:Node,accessor:NodeAccessor){ accessor.fileIsAvailable(for:node, at: self.assemblyPath(for:node)) } //MARK: Logical actions /// Moves a node to another destination in the box. /// IMPORTANT: this method requires a response from the BoxDelegate /// The completion occurs when the BoxDelegate invokes `applyPendingChanges` on the concerned node /// /// - Parameters: /// - node: the node /// - relativePath: the relative path /// - completed: a closure called on completion with Completion State. /// the copied node UID is stored in the completion.getResultExternalReference() public func copy(node:Node,to relativePath:String,completed:@escaping (Completion)->())->(){ // The nodeIsUsable() will be called when the file will be usable. if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){ self._boxDelegate?.copyIsReady(node: node, to: relativePath, proceed: { if let box=node.box{ Async.utility{ do{ try self._fileManager.copyItem(atPath: self.assemblyPath(for: node), toPath:box.nodesFolderPath+relativePath) // Create the copiedNode let copiedNode=self._document.newManagedModel() as Node copiedNode.quietChanges{ box.declaresOwnership(of: copiedNode) try? copiedNode.mergeWith(node)// merge copiedNode.relativePath=relativePath // Thats it! } let finalState=Completion.successState() finalState.setExternalReferenceResult(from:copiedNode) completed(finalState) }catch{ completed(Completion.failureStateFromError(error)) } } }else{ completed(Completion.failureState(NSLocalizedString("Forbidden! Box not found", tableName:"system", comment: "Forbidden! Box not found"), statusCode: .forbidden)) } }) }else{ completed(Completion.failureState(NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"), statusCode: .unauthorized)) } } /// Moves a node to another destination in the box. /// IMPORTANT: this method requires a response from the BoxDelegate /// The completion occurs when the BoxDelegate invokes `applyPendingChanges` on the concerned node /// /// - Parameters: /// - node: the node /// - relativePath: the relative path /// - completed: a closure called on completion with Completion State. /// the copied node UID is stored in the completion.getResultExternalReference() public func move(node:Node,to relativePath:String,completed:@escaping (Completion)->())->(){ // The nodeIsUsable() will be called when the file will be usable. if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){ self._boxDelegate?.moveIsReady(node: node, to: relativePath, proceed: { node.relativePath=relativePath let finalState=Completion.successState() finalState.setExternalReferenceResult(from:node) completed(finalState) }) }else{ completed(Completion.failureState(NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"), statusCode: .unauthorized)) } } /// Deletes a node /// IMPORTANT: this method requires a response from the BoxDelegate /// The completion occurs when the BoxDelegate invokes `applyPendingChanges` on the concerned node /// /// - Parameters: /// - node: the node /// - completed: a closure called on completion with Completion State. public func delete(node:Node,completed:@escaping (Completion)->())->(){ // The nodeIsUsable() will be called when the file will be usable. if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){ self._boxDelegate?.deletionIsReady(node: node, proceed: { /// TODO implement the deletion /// Delete the node /// Delete the files if necessary /// Refuse to delete folder containing nodes completed(Completion.successState()) }) }else{ completed(Completion.failureState(NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"), statusCode: .unauthorized)) } } /// Create Folders /// - Parameters: /// - relativePath: the relative Path /// - completed: a closure called on completion with Completion State. public func createFolder(in box:Box,at relativePath:String,completed:@escaping (Completion)->())->(){ /// TODO implement /// TEST IF THERE IS A LOCAL FOLDER /// Create the folder /// Create the NODE completed(Completion.successState()) } /// Creates the Alias /// - Parameters: /// - node: the node to be aliased /// - relativePath: the destination relativePath /// - completed: a closure called on completion with Completion State. public func createAlias(of node:Node,to relativePath:String, completed:@escaping (Completion)->())->(){ // The nodeIsUsable() will be called when the file will be usable. if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){ // TODO /// Create the Alias /// Create the NODE }else{ completed(Completion.failureState(NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"), statusCode: .unauthorized)) } } // MARK: - TriggerHook /// Called by the Document before trigger integration /// /// - Parameter trigger: the trigger public func triggerWillBeIntegrated(trigger:Trigger){ // We have nothing to do. } /// Called by the Document after trigger integration /// /// - Parameter trigger: the trigger public func triggerHasBeenIntegrated(trigger:Trigger){ // CHECK if there are Blocks, Node actions. // UploadBlock -> download if allowed triggered_download // DeleteBlock, DeleteBlocks -> delete the block immediately // UpsertBlock, UpsertBlocks -> nothing to do // On Nodes or Blocks check if we are concerned / allowed. } //MARK: - Triggered Block Level Action /// Downloads a Block. /// This occurs before triggered_create on each successfull upload. /// /// - Parameters: /// - node: the node internal func triggered_download(block:Block){ if let node=block.node{ if node.authorized.contains(self._document.currentUser.UID) || node.authorized.contains("*"){ self._toBeDownloadedBlocksUIDS.append(block.UID) self._downloadNext() } } } //MARK: - Block Level /// Will upload the next block if possible /// Respecting the priorities internal func _uploadNext()->(){ if self._uploadsInProgress.count<_maxSimultaneousOperations{ do{ let uploadableBlocks = try self._toBeUploadedBlocksUIDS.map({ (UID) -> Block in return try Bartleby.registredObjectByUID(UID) as Block }) let priorizedBlocks=uploadableBlocks.sorted { (l, r) -> Bool in return l.priority>r.priority } var toBeUploaded:Block? for candidate in priorizedBlocks{ if self._toBeUploadedBlocksUIDS.contains(candidate.UID) && candidate.uploadInProgress==false { toBeUploaded=candidate break } } func __removeBlockFromList(_ block:Block){ block.uploadInProgress=false if let idx=self._toBeUploadedBlocksUIDS.index(where:{ $0 == block.UID}){ self._toBeUploadedBlocksUIDS.remove(at: idx) } if let idx=self._uploadsInProgress.index(where:{ $0.blockUID == block.UID}){ self._uploadsInProgress.remove(at: idx) } } if toBeUploaded != nil{ if let block = try? Bartleby.registredObjectByUID(toBeUploaded!.UID) as Block { block.uploadInProgress=true let uploadOperation=UploadBlock(block: block, documentUID: self._document.UID, sucessHandler: { (context) in __removeBlockFromList(block) self._uploadNext() }, failureHandler: { (context) in __removeBlockFromList(block) }, cancelationHandler: { __removeBlockFromList(block) }) self._uploadsInProgress.append(uploadOperation) }else{ self._document.log("Block not found \(toBeUploaded!.UID)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false) } } } catch{ self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false) } } } /// Will download the next block if possible /// Respecting the priorities internal func _downloadNext()->(){ if self._downloadsInProgress.count<self._maxSimultaneousOperations{ do{ let downloadableBlocks = try self._toBeDownloadedBlocksUIDS.map({ (UID) -> Block in return try Bartleby.registredObjectByUID(UID) as Block }) let priorizedBlocks=downloadableBlocks.sorted { (l, r) -> Bool in return l.priority>r.priority } var toBeDownloaded:Block? for candidate in priorizedBlocks{ if self._toBeDownloadedBlocksUIDS.contains(candidate.UID) && candidate.downloadInProgress==false { toBeDownloaded=candidate break } } func __removeBlockFromList(_ block:Block){ block.downloadInProgress=false if let idx=self._toBeDownloadedBlocksUIDS.index(where:{ $0 == block.UID }){ self._toBeDownloadedBlocksUIDS.remove(at: idx) } if let idx=self._downloadsInProgress.index(where:{ $0.blockUID == block.UID }){ self._downloadsInProgress.remove(at: idx) } } if toBeDownloaded != nil{ if let block = try? Bartleby.registredObjectByUID(toBeDownloaded!.UID) as Block { block.downloadInProgress=true let downLoadOperation=DownloadBlock(block: block, documentUID: self._document.UID, sucessHandler: { (tempURL) in var data:Data? var sha1="" Async.utility{ do{ data=try Data(contentsOf:tempURL) sha1=data!.sha1 }catch{ self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false) } }.main{ do{ if sha1==block.digest{ try self._document.put(data: data!, identifiedBy:sha1) __removeBlockFromList(block) self._uploadNext() }else{ self._document.log("Digest of the block is not matching", file: #file, function: #function, line: #line, category: Default.LOG_SECURITY, decorative: false) } }catch{ self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false) } } }, failureHandler: { (context) in __removeBlockFromList(block) }, cancelationHandler: { __removeBlockFromList(block) }) self._downloadsInProgress.append(downLoadOperation) }else{ self._document.log("Block not found \(toBeDownloaded!.UID)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false) } } }catch{ self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false) } } } /// Return the block matching the Chunk if found /// /// - Parameter chunk: the chunk /// - Returns: the block. internal func _findBlockMatching(chunk:Chunk) -> Block? { if let idx=self._document.blocks.index(where: { (block) -> Bool in return block.digest==chunk.sha1 }){ return self._document.blocks[idx] } return nil } /// /// /// - Parameter block: the block or the Block reference /// Delete a Block its Block, raw file /// /// - Parameters: /// - block: the block or the Block open func deleteBlockFile(_ block:Block) { if let node:Node = block.firstRelation(Relationship.ownedBy){ node.removeRelation(Relationship.owns, to: block) node.numberOfBlocks -= 1 }else{ self._document.log("Block's node not found (block.UID:\(block.UID)", file: #file, function: #function, line: #line, category: Default.LOG_FAULT, decorative: false) } self._document.blocks.removeObject(block) do{ try self._document.removeBlock(with: block.digest) }catch{ self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false) } } }
f86f31dc2a2568d3a55662ddb64ceb14
41.687606
264
0.499781
false
false
false
false
lelandjansen/fatigue
refs/heads/master
ios/fatigue/Result.swift
apache-2.0
1
import Foundation class Result: QuestionnaireItem { enum QualitativeRisk { case low, medium, high, veryHigh } static func getQualitativeRisk(forRiskScore riskScore: Int32) -> QualitativeRisk { if riskScore < 6 { return .low } else if riskScore < 15 { return .medium } else if riskScore < 18 { return .high } else { return .veryHigh } } static func getRemark(forRiskScore riskScore: Int32, role: Role) -> String { let qualitativeRisk = getQualitativeRisk(forRiskScore: riskScore) return getRemark(forQualitativeRisk: qualitativeRisk, role: role) } static func getRemark(forQualitativeRisk qualitativeRisk: QualitativeRisk, role: Role) -> String { switch (role, qualitativeRisk) { case (.none, _): fatalError("Role cannot be none") case (_, .low): return "Continue as normal." case (.pilot, .medium): return "Reduce flight time and if possible reduce duty period." case (.engineer, .medium): return "Reduce duty day and defer all non-essential tasks." case (.pilot, .high): return "Proceed upon approval from your supervisor." case (.engineer, .high): return "Proceed upon approval from your supervisor." case (.pilot, .veryHigh): return "Stay on the ground." case (.engineer, .veryHigh): return "Defer all maintenance." default: fatalError("No remark for qualitative risk and occupation (\(qualitativeRisk), \(role))") } } var riskScore: Int32 = 0 { didSet { qualitativeRisk = Result.getQualitativeRisk(forRiskScore: riskScore) remark = Result.getRemark(forQualitativeRisk: qualitativeRisk!, role: UserDefaults.standard.role) } } var remark: String = String() var nextItem: QuestionnaireItem? var qualitativeRisk: QualitativeRisk? }
777b6622c0b89baf62598efeaaac57f0
34.482759
109
0.604956
false
false
false
false
younata/RSSClient
refs/heads/master
Tethys/Generic/CoreGraphicsLinearAlgebra.swift
mit
1
import CoreGraphics extension CGPoint { static func - (lhs: CGPoint, rhs: CGPoint) -> CGVector { return CGVector(dx: lhs.x - rhs.x, dy: lhs.y - rhs.y) } static func + (lhs: CGPoint, rhs: CGVector) -> CGPoint { return CGPoint(x: lhs.x + rhs.dx, y: lhs.y + rhs.dy) } static func += (lhs: inout CGPoint, rhs: CGVector) { lhs = lhs + rhs // swiftlint:disable:this shorthand_operator } } extension CGVector { func magnitudeSquared() -> CGFloat { return pow(self.dx, 2) + pow(self.dy, 2) } func normalized() -> CGVector { let x2 = pow(dx, 2) let y2 = pow(dy, 2) let mag = sqrt(x2 + y2) return CGVector(dx: self.dx / mag, dy: self.dy / mag) } }
ac4feeb6761f17bccaf0b59a27f175d8
24.793103
68
0.565508
false
false
false
false
csnu17/My-Swift-learning
refs/heads/master
collection-data-structures-swift/DataStructures/NSDictionaryManipulator.swift
mit
1
// // NSDictionaryManipulator.swift // DataStructures // // Created by Ellen Shapiro on 8/3/14. // Copyright (c) 2014 Ray Wenderlich Tutorial Team. All rights reserved. // import Foundation class NSDictionaryManipulator: DictionaryManipulator { var intDictionary = NSMutableDictionary() func dictHasEntries() -> Bool { if (intDictionary.count == 0) { return false } else { return true } } //MARK: Setup func setupWithEntryCount(_ count: Int) -> TimeInterval { return Profiler.runClosureForTime() { for i in 0 ..< count { self.intDictionary.setObject(i, forKey: i as NSCopying) } } } fileprivate func nextElement() -> Int { return self.intDictionary.count + 1 } //MARK: Adding entries func addEntries(_ count: Int) -> TimeInterval { var dictionary = [Int: Int]() let next = nextElement() for i in 0 ..< count { let plusI = next + i dictionary[plusI] = plusI } let time = Profiler.runClosureForTime() { self.intDictionary.addEntries(from: dictionary) } //Restore to original state let keys = Array(dictionary.keys) self.intDictionary.removeObjects(forKeys: keys) return time } func add1Entry() -> TimeInterval { return addEntries(1) } func add5Entries() -> TimeInterval { return addEntries(5) } func add10Entries() -> TimeInterval { return addEntries(10) } //MARK: Removing entries func removeEntries(_ count: Int) -> TimeInterval { var dictionary = [Int: Int]() let next = nextElement() for i in 0 ..< count { let plusI = next + i dictionary[plusI] = plusI } self.intDictionary.addEntries(from: dictionary) //Restore to original state let keys = Array(dictionary.keys) return Profiler.runClosureForTime() { self.intDictionary.removeObjects(forKeys: keys) } } func remove1Entry() -> TimeInterval { return removeEntries(1) } func remove5Entries() -> TimeInterval { return removeEntries(5) } func remove10Entries() -> TimeInterval { return removeEntries(10) } //MARK: Looking up entries func lookupEntries(_ count: Int) -> TimeInterval { var dictionary = [Int: Int]() let next = nextElement() for i in 0 ..< count { let plusI = next + i dictionary[plusI] = plusI } self.intDictionary.addEntries(from: dictionary) let keys = Array(dictionary.keys) let time = Profiler.runClosureForTime() { for key in keys { self.intDictionary.object(forKey: key) } } //Restore to original state self.intDictionary.removeObjects(forKeys: keys) return time } func lookup1EntryTime() -> TimeInterval { return lookupEntries(1) } func lookup10EntriesTime() -> TimeInterval { return lookupEntries(10) } }
a4724cc67f4c084aca515e5d1efa94b3
21.007463
73
0.62394
false
false
false
false
duming91/Hear-You
refs/heads/master
Hear You/Services/Request.swift
gpl-3.0
1
// // Request.swift // Hear You // // Created by 董亚珣 on 16/5/12. // Copyright © 2016年 snow. All rights reserved. // import Foundation import Alamofire /// api根路径 let baseURL = NSURL(string: "http://api.dongting.com/")! let searchBaseURL = NSURL(string: "http://search.dongting.com/")! let lricdBaseURL = NSURL(string: "http://lp.music.ttpod.com/")! typealias NetworkSucceed = (result: JSONDictionary) -> () typealias NetworkFailed = (reason: NSError) -> () /** post请求 - parameter URLString: 接口url - parameter parameters: 参数 - parameter finished: 回调 */ func apiRequest(apiName apiName: String, URLString: String, headers: [String : String]?, parameters: JSONDictionary?, encoding: ParameterEncoding, failed: NetworkFailed?, succeed: NetworkSucceed) { println("\n***************************** Networking Request *****************************") println("\nAPI: \(apiName)") println("\nURL: \(URLString)") println("\nParameters: \(parameters)") println("\n******************************************************************************") Alamofire.request(.GET, URLString, parameters: parameters, encoding: encoding, headers: headers).responseJSON { (response) in println("\n***************************** Networking Response *****************************") println("\nAPI: \(apiName)") println("\nResponse:\n\(response.result.value)") println("\n*******************************************************************************") if let JSON = response.result.value { if let dict = JSON as? JSONDictionary { succeed(result: dict) } else { println("\nNetworking Failed: resopnse data is not a JSONDictionary") } } else { println("\nNetworking Failed: \(response.result.error)") if let failed = failed { failed(reason: response.result.error!) } } } } // MARK: - 搜索歌曲 func searchSongWithName(name: String, page: String, size: String, failed: NetworkFailed?, succeed: [Song] -> Void) { let parameters: JSONDictionary = [ "q": name, "page": page, "size": size, ] apiRequest(apiName: "搜索歌曲", URLString: "http://search.dongting.com/song/search", headers: nil, parameters: parameters, encoding: .URL, failed: failed) { (result) in if let data = result["data"] as? [JSONDictionary] { var searchSongList = [Song]() for songInfo in data { guard let song = Song.fromJSONDictionary(songInfo) else { continue } searchSongList.append(song) } succeed(searchSongList) } } } // MARK: - 歌曲列表 func searchSongList(albumID: String, failed: NetworkFailed?, succeed: SongList -> Void) { apiRequest(apiName: "搜索歌曲", URLString: "http://api.songlist.ttpod.com/songlists/" + albumID, headers: nil, parameters: nil, encoding: .URL, failed: failed) { (result) in let songlist = SongList.fromJSONDictionary(result) succeed(songlist) } } // MARK: - 首页展示 func getFrontpageInformation(failed: NetworkFailed?, succeed: [FrontpageElement] -> Void) { apiRequest(apiName: "首页展示", URLString: "http://api.dongting.com/frontpage/frontpage", headers: nil, parameters: nil, encoding: .URL, failed: failed) { (result) in if let data = result["data"] as? [JSONDictionary] { let frontpageElements = FrontpageElement.frmeJSONArray(data) println(frontpageElements) succeed(frontpageElements) } } }
4679e95778514b16fa00dfc1ef2b29e5
32.539823
197
0.552243
false
false
false
false
dataich/TypetalkSwift
refs/heads/master
TypetalkSwift/Client.swift
mit
1
// // Client.swift // TypetalkSwift // // Created by Taichiro Yoshida on 2017/10/15. // Copyright © 2017 Nulab Inc. All rights reserved. // import Alamofire import OAuth2 public class Client { static let shared: Client = Client() static let ErrorDomain = "TypetalkSwift.err" var oauth2: OAuth2! var manager: SessionManager! let decoder = JSONDecoder() static var baseUrl: String = "https://typetalk.com" private init() { } public class func setAPISettings( baseUrl: String? = nil, clientId: String, clientSecret: String, scopes: [OAuth2Scope], redirectUri: String, authorizeContext: Any) { if let baseUrl = baseUrl { Client.baseUrl = baseUrl } let settings = [ "client_id": clientId, "client_secret": clientSecret, "authorize_uri": "\(Client.baseUrl)/oauth2/authorize", "token_uri": "\(Client.baseUrl)/oauth2/access_token", "scope": scopes.map{$0.rawValue}.joined(separator: ","), "redirect_uris": [redirectUri], "keychain": true, "verbose": true ] as OAuth2JSON let oauth2 = CustomOAuth2CodeGrant(settings: settings) oauth2.authConfig.authorizeEmbedded = true oauth2.authConfig.authorizeContext = authorizeContext as AnyObject oauth2.logger = OAuth2DebugLogger(.trace) shared.oauth2 = oauth2 let manager = SessionManager() let retrier = OAuth2RetryHandler(oauth2: oauth2) manager.adapter = retrier manager.retrier = retrier shared.manager = manager shared.decoder.dateDecodingStrategy = .iso8601 } private func responseDecodableObject<T: Request>(_ request:T, dataRequest: DataRequest, completionHandler:@escaping ((Result<T.Response>) -> Void)) -> Void { let statusCode = 200..<300 dataRequest .validate(statusCode: statusCode) .responseDecodableObject(decoder: decoder) { (response: DataResponse<T.Response>) in let result: Result<T.Response> if let value = response.value { result = Result.success(value) } else { result = Result.failure(response.error ?? APIError.unknown) } completionHandler(result) } } public class func send<T: Request>(_ request:T, completionHandler:@escaping ((Result<T.Response>) -> Void)) -> Void { shared.oauth2.authorize { (authParameters, error) in if let _ = authParameters { guard let urlRequest = try? request.asURLRequest(Client.baseUrl) else { return } if let bodyParameter = request.bodyParameter { shared.manager.upload(multipartFormData: { (multipartFormData) in multipartFormData.append(bodyParameter.data, withName: bodyParameter.withName, fileName: bodyParameter.fileName, mimeType: bodyParameter.mimeType) }, with: urlRequest, encodingCompletion: { (encodingResult) in switch encodingResult { case .success(let dataRequest, _, _): shared.responseDecodableObject(request, dataRequest: dataRequest, completionHandler: completionHandler) case .failure(let error): print(error) } }) } else { shared.responseDecodableObject(request, dataRequest: shared.manager.request(urlRequest), completionHandler: completionHandler) } } else { print("Authorization was canceled or went wrong: \(error.debugDescription)") // error will not be nil } } } public class func handleRedirectURL(url: URL) throws -> Void { try shared.oauth2.handleRedirectURL(url) } }
6e2e4568251859e8f6540ff09975cb2e
32.398148
159
0.659274
false
false
false
false
MagicianDL/Shark
refs/heads/master
Shark/Utils/SKUtils.swift
mit
1
// // SKUtils.swift // Shark // // Created by Dalang on 2017/3/3. // Copyright © 2017年 青岛鲨鱼汇信息技术有限公司. All rights reserved. // /// 常用方法 import UIKit class SKUtils: NSObject { class func initializeAppDefaultSetting() { initializeNavigationBar() initializeTabbar() } /// tabbar 设置 class func initializeTabbar() { let normalAttributes: Dictionary = [ NSForegroundColorAttributeName: UIColor(hexString: "#A9A8A8") ] let selectedAttribute: Dictionary = [ NSForegroundColorAttributeName: UIColor.mainBlue ] UITabBarItem.appearance().setTitleTextAttributes(normalAttributes, for: UIControlState.normal) UITabBarItem.appearance().setTitleTextAttributes(selectedAttribute, for: UIControlState.selected) UITabBar.appearance().tintColor = UIColor.mainBlue } /// 导航栏设置 class func initializeNavigationBar() { let attributes = [ NSForegroundColorAttributeName: UIColor.mainBlue, NSFontAttributeName: UIFont.systemFont(ofSize: 20) ] UINavigationBar.appearance().titleTextAttributes = attributes UINavigationBar.appearance().tintColor = UIColor.mainBlue } }
901c74edd7e7c18dfff4be427ca2ba03
25.571429
105
0.641321
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Mac/MainWindow/AddFeed/FolderTreeMenu.swift
mit
1
// // FolderTreeMenu.swift // NetNewsWire // // Created by Maurice Parker on 9/12/18. // Copyright © 2018 Ranchero Software, LLC. All rights reserved. // import AppKit import RSCore import RSTree import Account class FolderTreeMenu { static func createFolderPopupMenu(with rootNode: Node, restrictToSpecialAccounts: Bool = false) -> NSMenu { let menu = NSMenu(title: "Folders") menu.autoenablesItems = false for childNode in rootNode.childNodes { guard let account = childNode.representedObject as? Account else { continue } if restrictToSpecialAccounts && !(account.type == .onMyMac || account.type == .cloudKit) { continue } let menuItem = NSMenuItem(title: account.nameForDisplay, action: nil, keyEquivalent: "") menuItem.representedObject = childNode.representedObject if account.behaviors.contains(.disallowFeedInRootFolder) { menuItem.isEnabled = false } menu.addItem(menuItem) let childNodes = childNode.childNodes addFolderItemsToMenuWithNodes(menu: menu, nodes: childNodes, indentationLevel: 1) } return menu } static func select(account: Account, folder: Folder?, in popupButton: NSPopUpButton) { for menuItem in popupButton.itemArray { if let oneAccount = menuItem.representedObject as? Account, oneAccount == account && folder == nil { popupButton.select(menuItem) return } if let oneFolder = menuItem.representedObject as? Folder, oneFolder == folder { if oneFolder.account == account { popupButton.select(menuItem) return } } } } private static func addFolderItemsToMenuWithNodes(menu: NSMenu, nodes: [Node], indentationLevel: Int) { nodes.forEach { (oneNode) in if let nameProvider = oneNode.representedObject as? DisplayNameProvider { let menuItem = NSMenuItem(title: nameProvider.nameForDisplay, action: nil, keyEquivalent: "") menuItem.indentationLevel = indentationLevel menuItem.representedObject = oneNode.representedObject menu.addItem(menuItem) if oneNode.numberOfChildNodes > 0 { addFolderItemsToMenuWithNodes(menu: menu, nodes: oneNode.childNodes, indentationLevel: indentationLevel + 1) } } } } }
4117730f3efd60697f9f03bc038bd590
26.493827
113
0.71621
false
false
false
false
blstream/TOZ_iOS
refs/heads/master
TOZ_iOS/OrganizationInfoResponseMapper.swift
apache-2.0
1
// // OrganizationInfoResponseMapper.swift // TOZ_iOS // // Copyright © 2017 intive. All rights reserved. // import Foundation /** Parses response from OrganizationInfo operation. Inherits from generic ResponseMapper class. */ final class OrganizationInfoResponseMapper: ResponseMapper<OrganizationInfoItem>, ResponseMapperProtocol { // swiftlint:disable cyclomatic_complexity static func process(_ obj: AnyObject?) throws -> OrganizationInfoItem { // swiftlint:enable cyclomatic_complexity return try process(obj, parse: { json in guard let name = json["name"] as? String else { return nil } guard let invitationText = json["invitationText"] as? String? else { return nil } guard let volunteerText = json["volunteerText"] as? String? else { return nil } guard let address = json["address"] as? [String: Any] else { return nil } guard let street = address["street"] as? String? else { return nil } guard let houseNumber = address["houseNumber"] as? String? else { return nil } guard let apartmentNumber = address["apartmentNumber"] as? String? else { return nil } var adressApartmentNumber: String? = nil if let apartmentNumber = apartmentNumber { adressApartmentNumber = "/" + apartmentNumber } guard let postcode = address["postCode"] as? String? else { return nil } guard let city = address["city"] as? String? else { return nil } guard let country = address["country"] as? String? else { return nil } guard let contact = json["contact"] as? [String: Any] else { return nil } guard let email = contact["email"] as? String? else { return nil } guard let phone = contact["phone"] as? String? else { return nil } guard let fax = contact["fax"] as? String? else { return nil } guard let website = contact["website"] as? String? else { return nil } guard let bankAccount = json["bankAccount"] as? [String: Any] else { return nil } guard let accountNumber = bankAccount["number"] as? String else { return nil } guard let bankName = bankAccount["bankName"] as? String? else { return nil } return OrganizationInfoItem(name: name, invitationText: invitationText, volunteerText: volunteerText, street: street, houseNumber: houseNumber, apartmentNumber: adressApartmentNumber, postCode: postcode, city: city, country: country, email: email, phone: phone, fax: fax, website: website, accountNumber: accountNumber, bankName: bankName) }) } }
2446ed6b12690b149eedaa7357de0bc4
59.272727
351
0.657617
false
false
false
false
gavrix/AnyAnimation
refs/heads/master
Examples/AnyAnimationTestbed/ManualAnimatorViewController.swift
mit
1
// // ManualAnimatorViewController.swift // AnyAnimationTestbed // // Created by Sergey Gavrilyuk on 2017-09-05. // Copyright © 2017 Gavrix. All rights reserved. // import Foundation import UIKit import AnyAnimation class ManualAnimatorViewController: UIViewController { @IBOutlet weak var movingViewXConstraint: NSLayoutConstraint! @IBOutlet weak var containerView: UIView! @IBOutlet weak var movingView: UIView! var animator = ManualAnimator() lazy var xProperty: AnimatableProperty<CGFloat> = { return AnimatableProperty(self.movingViewXConstraint.constant) { [unowned self] in self.movingViewXConstraint.constant = $0 } }() lazy var rotationProperty: AnimatableProperty<CGFloat> = { return AnimatableProperty(0) { [unowned self] in self.movingView.transform = CGAffineTransform(rotationAngle: $0) } }() @IBAction func sliderValueChanged(_ slider: UISlider) { self.animator.time = RelativeTimeInterval(interval: TimeInterval(slider.value), maxInterval: TimeInterval(slider.maximumValue)) } override func viewDidLoad() { super.viewDidLoad() let animation = AnimationGroup([ BasicAnimation(from: xProperty.value, to: containerView.frame.width - movingView.frame.width * CGFloat(0.5), on: self.xProperty, duration: 1), BasicAnimation(from: 0, to: CGFloat.pi, on: self.rotationProperty, duration: 1) ]) self.animator.run(animation: animation) } }
4ceac4c22d6a8d3a6d318426b71856d4
28.529412
131
0.707835
false
false
false
false
shyn/cs193p
refs/heads/master
Happiness/Happiness/FaceView.swift
mit
2
// // FaceView.swift // Happiness // // Created by deepwind on 4/29/17. // Copyright © 2017 deepwind. All rights reserved. // import UIKit protocol FaceViewDataSource: class { // var happiness: Int { get set} func smilinessForFaceView(sender: FaceView) -> Double? } @IBDesignable class FaceView: UIView { @IBInspectable var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } } @IBInspectable var scale:CGFloat = 0.9 { didSet { setNeedsDisplay() } } @IBInspectable var color:UIColor = UIColor.blue { didSet { setNeedsDisplay() } } var faceCenter: CGPoint { return convert(center, from: superview) } var faceRadius: CGFloat { return min(bounds.height, bounds.width)/2 * scale } // do not keep this pointer in memory to avoid cycle reference // but weak can not decorate protocol.. so we make our protocol a 'class':) weak var dataSource: FaceViewDataSource? func pinch(_ gesture: UIPinchGestureRecognizer) { if gesture.state == .changed { scale *= gesture.scale gesture.scale = 1 } } override func draw(_ rect: CGRect) { let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true) facePath.lineWidth = lineWidth color.set() facePath.stroke() let smiliness = dataSource?.smilinessForFaceView(sender: self) ?? 0.5 bezierPathForEye(whichEye: .Left).stroke() bezierPathForEye(whichEye: .Right).stroke() bezierPathForSmile(fractionOfMaxSmile: smiliness).stroke() } private struct Scaling { static let FaceRadiusToEyeRadiusRatio: CGFloat = 10 static let FaceRadiusToEyeOffsetRatio: CGFloat = 3 static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5 static let FaceRadiusToMouthWidthRatio: CGFloat = 1 static let FaceRadiusToMouthHeightRatio: CGFloat = 3 static let FaceRadiusToMouthOffsetRatio: CGFloat = 3 } private enum Eye { case Left, Right } private func bezierPathForSmile(fractionOfMaxSmile: Double) -> UIBezierPath { let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio let mouthVerticleOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio let smileHeight = CGFloat(max(min(fractionOfMaxSmile, 1), -1)) * mouthHeight let start = CGPoint(x: faceCenter.x - mouthWidth/2, y: faceCenter.y + mouthVerticleOffset) let end = CGPoint(x: start.x + mouthWidth, y: start.y) let cp1 = CGPoint(x: start.x + mouthWidth/3, y: start.y + smileHeight) let cp2 = CGPoint(x: end.x - mouthWidth/3, y: cp1.y) let path = UIBezierPath() path.move(to: start) path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = lineWidth return path } private func bezierPathForEye(whichEye: Eye) -> UIBezierPath { let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio var eyeCenter = faceCenter eyeCenter.y -= eyeVerticalOffset switch whichEye { case .Left: eyeCenter.x -= eyeHorizontalSeparation / 2 case .Right: eyeCenter.x += eyeHorizontalSeparation / 2 } let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true) path.lineWidth = lineWidth return path } }
0195fc43877e16befc84d5186e1792bf
35.638095
142
0.656875
false
false
false
false