repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
futurist/cutecmd-mac
cutecmd-mac/AppDelegate.swift
1
16831
// // AppDelegate.swift // cutecmd-mac // // Created by pro on 16/11/17. // Copyright © 2016年 wuniu. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSTextViewDelegate, AutoCompleteTableViewDelegate { @IBOutlet weak var window: NSWindow! var input: AutoCompleteTextField! // Cmd-S to switch between sapce mode var isSpaceMode = false var popupTimer:Timer? // suggestion dropDown is showing? var isCompleting = false let wordRegEx = "[0-9a-zA-Z_]+$" let directoryURL = try? FileManager.default.url(for: .applicationScriptsDirectory, in: .userDomainMask, appropriateFor: nil, create: true) static var isWindowShow = false var AppList:[String] = [] func loadAppList () { AppList = AppDelegate.getAppsInFolders(["/Applications", "/Applications/Utilities"]) } func openUserScriptsFolder (){ if let folder = directoryURL { NSWorkspace.shared().open(folder) } } func runScript(filename: String){ let surl = directoryURL!.appendingPathComponent(filename + ".scpt") hideApp() do { if try surl.checkResourceIsReachable() { _ = try? NSUserAppleScriptTask(url: surl).execute(withAppleEvent: nil, completionHandler: nil) } } catch { print("script not found") let args = splitCommandLine(str: filename, by:[" "]) // first try run as a Applicaiton if( runShell(["open \'\(filename)\'"]) > 0 && runShell(["open -a \'\(filename)\'"]) > 0 // && runShell( args ) > 0 ) { print("Command execute error", args, input.string!) } } } @discardableResult func runShell(_ args: [String], raw rawString: String = "") -> Int32 { let task = Process() task.launchPath = "/bin/bash" task.arguments = ["-c"] + args task.launch() task.waitUntilExit() // print(task.terminationStatus, task.terminationReason.rawValue) return task.terminationStatus } func showApp (){ AppDelegate.isWindowShow = true updateSize() if(NSApp.isHidden) { NSApp.unhide(self) } window.center() window.makeKeyAndOrderFront(self) NSApp.activate(ignoringOtherApps: true) window.makeFirstResponder(input) } func hideApp (){ input.autoCompletePopover?.close() stopPopupTimer() // window.orderOut(self) NSApp.hide(self) isSpaceMode = false updateInputMode() AppDelegate.isWindowShow = false HookKeyEvent.shared.resetState() HookKeyEvent.shared.isControlDown = false } func quitApp(){ exit(0) } // split command line with space, regard Quote // The result don't contain Quote at first/end func splitCommandLine(str: String, by characterSet: CharacterSet) -> [String] { let quoteStr = "\'\"" let quoteSet = CharacterSet.init(charactersIn: quoteStr) var apperQuote = false let result = str.utf16.split(maxSplits: Int.max, omittingEmptySubsequences: true) { x in if quoteSet.contains(UnicodeScalar(x)!) { apperQuote = !apperQuote } if apperQuote { return false } else { return characterSet.contains(UnicodeScalar(x)!) } }.flatMap(String.init) return result.map({x in var isQuoted = false var unQuoted = x for (_, quote) in str.characters.enumerated() { isQuoted = x.hasPrefix(String(quote)) && x.hasSuffix(String(quote)) if isQuoted && x.characters.count > 1 { // when only one char in x, below will throw error unQuoted = x[x.index(x.startIndex, offsetBy: 1)..<x.index(x.endIndex, offsetBy: -1) ] break } } // x.characters.dropLast().dropLast() return unQuoted }) } func updateInputMode() { window.backgroundColor = isSpaceMode ? NSColor.darkGray : NSColor.init(hue: 0, saturation: 0, brightness: 0.85, alpha: 1) try input.textColor = isSpaceMode ? NSColor.blue : NSColor.textColor try input.backgroundColor = isSpaceMode ? NSColor.lightGray : NSColor.controlBackgroundColor } func ExecuteCommand (key: String) { if(key == "") { return } switch (key) { case ":quit": quitApp() case ":reload": loadAppList() case ":setup": openUserScriptsFolder() default: runScript(filename: key) } self.input.string!.removeAll() } /* Delegate methods */ func applicationWillResignActive(_ notification: Notification) { hideApp() } func applicationWillFinishLaunching(_ notification: Notification) { checkSingleton() } func applicationDidFinishLaunching(_ aNotification: Notification) { loadAppList() window.isMovableByWindowBackground = true window.titleVisibility = NSWindowTitleVisibility.hidden window.styleMask.insert(.fullSizeContentView) window.styleMask.remove(.closable) window.styleMask.remove(.resizable) window.styleMask.remove(.miniaturizable) window.titlebarAppearsTransparent = true window.level = Int(CGWindowLevelKey.maximumWindow.rawValue) window.collectionBehavior = [.stationary, .canJoinAllSpaces, .fullScreenAuxiliary] let top = (window.frame.height - 48)/2 input = AutoCompleteTextField(frame: NSMakeRect(20, top, window.frame.width-40, 48)) input.textContainerInset = NSSize(width: 10, height: 10) input.font = NSFont(name:"Helvetica", size:24) input.isEditable = true input.isSelectable = true // prevent quote etc. be replaced input.enabledTextCheckingTypes = 0 input.tableViewDelegate = self input.delegate = self window.contentView!.addSubview(input) // wait for the event loop to activate DispatchQueue.main.async { self.showApp() self.updateInputMode() HookKeyEvent.setupHook(trigger: self.showApp) } NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler:localEventMonitor ) } func localEventMonitor(event: NSEvent) -> NSEvent? { // print(event.keyCode, UnicodeScalar(event.characters!), event.charactersIgnoringModifiers ) let autoCompleteView = input.autoCompleteTableView! let row:Int = autoCompleteView.selectedRow let isShow = input.autoCompletePopover!.isShown let keyCode = event.keyCode // CTRL-n if(isShow && event.modifierFlags.contains(.control) && keyCode==45 || keyCode == 125 ){ autoCompleteView.selectRowIndexes(IndexSet(integer: row + 1), byExtendingSelection: false) autoCompleteView.scrollRowToVisible((autoCompleteView.selectedRow)) return nil } // CTRL-p if(isShow && event.modifierFlags.contains(.control) && keyCode==35 || keyCode == 126){ autoCompleteView.selectRowIndexes(IndexSet(integer: row - 1), byExtendingSelection: false) autoCompleteView.scrollRowToVisible((autoCompleteView.selectedRow)) return nil } // CTRL+TAB will switch SpaceMode if(keyCode == 48 && event.modifierFlags.contains(.control)){ self.isSpaceMode = !self.isSpaceMode self.updateInputMode() return nil } // TAB if(keyCode == 48){ self.input.insert(input) self.ExecuteCommand(key: self.input.string!) return nil } // CMD-Space will insert SPACE if(keyCode == 49 && event.modifierFlags.contains(.command)){ self.input.string! += " " return nil } if(!self.isSpaceMode && keyCode == 49 || keyCode == 36) { // SPACE or Enter self.ExecuteCommand(key: self.input.string!) return nil } if(keyCode == 53 //ESC or Ctrl-G || event.charactersIgnoringModifiers == "g" && event.modifierFlags.contains(.control)) { self.input.string!.removeAll() self.hideApp() return nil } return event } } extension AppDelegate { /* --- Some util func --- */ func setTimeout(delay:TimeInterval, block:@escaping ()->Void) -> Timer { return Timer.scheduledTimer(timeInterval: delay, target: BlockOperation(block: block), selector: #selector(Operation.main), userInfo: nil, repeats: false) } /* Application Singleton */ func checkSingleton (){ // Check if another instance of this app is running let bundleID = Bundle.main.bundleIdentifier! let apps = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) if apps.count > 1 { // Activate the other instance and terminate this instance for app in apps { if app != NSRunningApplication.current() { app.activate(options: [.activateIgnoringOtherApps]) break } } NSApp.terminate(nil) } } func matches(for regex: String, in text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex) let nsString = text as NSString let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length)) return results.map { nsString.substring(with: $0.range)} } catch let error { print("invalid regex: \(error.localizedDescription)") return [] } } static func getAppsInFolders (_ folders: [String]) -> [String] { let filemanager:FileManager = FileManager() var apps = [String]() for folder in folders { let files = try? filemanager.contentsOfDirectory(atPath: folder) if let filesArr = files { apps.append(contentsOf: filesArr.filter{ // only .app folders $0.hasSuffix(".app") }.map{ x in // without .app extension x[x.startIndex..<x.index(x.endIndex, offsetBy: -4) ] } ) } } return apps } } extension AppDelegate { /* NSTextView Delegate part */ func stopPopupTimer (){ if let timer = popupTimer { if(timer.isValid) { timer.invalidate() } popupTimer = nil } } // when text changed, frames may enlarge to multiline func textDidChange(_ notification: Notification) { updateSize() stopPopupTimer() popupTimer = setTimeout(delay: 0.2, block: { () -> Void in // delay popup completion window if (!self.isCompleting) { // to prevent infinite loop self.isCompleting = true self.input.complete(self.input) self.isCompleting = false } }) } func textView(_ textView: NSTextView, completions words: [String], forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer<Int>?) -> [String] { let str = input.string! let range = input.selectedRange() if(str.isEmpty) { return [] } let strOfCaret = str.substring(to: str.index(str.startIndex, offsetBy: range.location)) let word = self.matches(for: wordRegEx, in: strOfCaret).last ?? "" let retArr = word.isEmpty ? [] : [] + AppList return retArr.filter({x in x.score(str)>0}).sorted(by: { (a, b) in a.score(str) > b.score(str) }) } func updateSize(){ var frame = window.frame var inputOrigin = input.frame.origin let oldHeight = frame.size.height let inputHeight = input.frame.height let winHeight = inputHeight + 40 inputOrigin.y = (winHeight - inputHeight)/2 frame.size.height = winHeight frame.origin.y -= (winHeight - oldHeight) window.setFrame(frame, display: true) input.setFrameOrigin(inputOrigin) } } private class HookKeyEvent { /* Hook key in global */ public static let shared = HookKeyEvent() var delayTime = 0.5 * 1e9 // 0.5 sec var prevTime:UInt64 = 0 var isTriggered = false var isControlDown = false var count = 0 static var handler:(()->Void)? static func setupHook(trigger: @escaping (()->Void)){ handler = trigger // keyDown && keyUp event have to use root privilege // ADD this APP to System->Security->Privacy list let eventMask = CGEventMask(( 1 << CGEventType.flagsChanged.rawValue | 1 << CGEventType.keyDown.rawValue | 1 << CGEventType.keyUp.rawValue)) guard let eventTap = CGEvent.tapCreate(tap: .cghidEventTap, place: .headInsertEventTap, options: .listenOnly, eventsOfInterest: eventMask, callback: { (_,_,event,_) in return HookKeyEvent.shared.checkEvent(event) }, userInfo: nil) else { print("failed to create event tap") exit(1) } let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0) CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes) CGEvent.tapEnable(tap: eventTap, enable: true) CFRunLoopRun() } func checkEvent(_ event: CGEvent) -> Unmanaged<CGEvent>? { let flags = event.flags let commandTapped = flags.contains(.maskCommand) let shiftTapped = flags.contains(.maskShift) let controlTapped = flags.contains(.maskControl) let altTapped = flags.contains(.maskAlternate) // Make sure only one modifier key let totalHash = commandTapped.hashValue + altTapped.hashValue + shiftTapped.hashValue + controlTapped.hashValue // totalHash==0 equal to isKeyUp ?? let isKeyUp = totalHash==0 || event.flags.rawValue <= 256 // multiple key changed or window already shown if totalHash > 1 || AppDelegate.isWindowShow || event.type.rawValue != CGEventType.flagsChanged.rawValue { // any keyDown/keyUp will let control reset isControlDown = false resetState() return Unmanaged.passRetained(event) } if(!isKeyUp){ isControlDown = controlTapped return Unmanaged.passRetained(event) } if(isControlDown) { isTriggered = DispatchTime.now().rawValue - prevTime < UInt64(delayTime) prevTime = DispatchTime.now().rawValue } else { resetState() } if isTriggered { doubleTapped() resetState() } return Unmanaged.passRetained(event) } func resetState(){ prevTime = 0 isTriggered = false } func doubleTapped() { count += 1 print("triggered", count) HookKeyEvent.handler?() } }
mit
2f6ad45b7d803d6b450e7cd219b30c4c
29.877064
179
0.547243
5.12112
false
false
false
false
ltcarbonell/deckstravaganza
Deckstravaganza/RummyAI.swift
1
5970
// // RummyAI.swift // Deckstravaganza // // Created by Luis Carbonell on 11/23/15. // Copyright © 2015 University of Florida. All rights reserved. // import Foundation import GameplayKit class RummyAI { let difficulty: Difficulty let game: Rummy let player: Player var neededCards = Pile() var discardedCards = Pile() var currentHand = Pile() var countedRanks = [Int](repeating: 0, count: 13) var countedSuits = [Int](repeating: 0, count: 4) init(difficulty: Difficulty, game: Rummy, player: Player) { self.difficulty = difficulty self.game = game self.player = player self.game.playersHands[player.playerNumber].sortByRank(true) } func countHands() { self.countedRanks = [Int](repeating: 0, count: 13) self.countedSuits = [Int](repeating: 0, count: 4) for cardIndex in 0..<self.game.playersHands[player.playerNumber].numberOfCards() { self.countedRanks[self.game.playersHands[player.playerNumber].cardAt(cardIndex)!.getRank().rawValue-1] += 1 self.countedSuits[self.game.playersHands[player.playerNumber].cardAt(cardIndex)!.getSuit().rawValue-1] += 1 } } // MARK: Test for AI by only drawing from waste pile if it is a red card func shouldDrawCardFromWaste() -> Bool { let wasteTop = self.game.wastePile.topCard()! if difficulty == .easy { if wasteTop.getColor() == Card.CardColor.red { return true } else { return false } } else if difficulty == .hard { if self.countedRanks[wasteTop.getRank().rawValue-1] >= 2 || self.countedSuits[wasteTop.getSuit().rawValue-1] >= 4 { return true } else { return false } } else { return false } } func shouldMeldCards() -> Bool { for rank in 0..<self.countedRanks.count { if countedRanks[rank] >= 3 { for cardIndex in 0..<self.game.playersHands[player.playerNumber].numberOfCards() { if self.game.playersHands[player.playerNumber].cardAt(cardIndex)!.getRank().rawValue-1 == rank { self.game.addSelectedCard(self.game.playersHands[player.playerNumber].cardAt(cardIndex)!) } } return true } } for suit in 0..<self.countedSuits.count { if countedSuits[suit] >= 3 { for cardIndex in 0..<self.game.playersHands[player.playerNumber].numberOfCards() { if self.game.playersHands[player.playerNumber].cardAt(cardIndex)!.getSuit().rawValue-1 == suit { self.game.addSelectedCard(self.game.playersHands[player.playerNumber].cardAt(cardIndex)!) } } while self.game.selectedCards.numberOfCards() >= 3 { // MARK: DEBUG print("Check for run", self.game.checkForRun()) print(self.game.selectedCards.numberOfCards()) for cardIndex in 0..<self.game.selectedCards.numberOfCards() { print(self.game.selectedCards.cardAt(cardIndex)!.getRank(),self.game.selectedCards.cardAt(cardIndex)!.getSuit()) } if self.game.checkForRun() { return true } else { let numberOfCardsSelected = self.game.selectedCards.numberOfCards() let distribution = GKRandomDistribution(lowestValue: 0, highestValue: numberOfCardsSelected-1) let randIndex = distribution.nextInt() self.game.selectedCards.removeCardAt(randIndex) } } self.game.selectedCards.removeAllCards() } } return false } func shouldLayOffCards() -> Bool { let numberOfCardsInHand = self.game.playersHands[player.playerNumber].numberOfCards() for cardIndex in 0..<numberOfCardsInHand { self.game.addSelectedCard(self.game.playersHands[player.playerNumber].cardAt(cardIndex)!) if self.game.isSelectedCardsValidLayOff() { return true } } self.game.selectedCards.removeAllCards() return false } func getDiscardCardIndex(_ drawnCard: Card) -> Int { let numberOfCardsInHand = self.game.playersHands[player.playerNumber].numberOfCards() let distribution = GKRandomDistribution(lowestValue: 0, highestValue: numberOfCardsInHand-1) let checkedFirst = distribution.nextInt() let goRight = distribution.nextBool() var discardedIndex = checkedFirst if difficulty == .hard { for _ in 0..<numberOfCardsInHand { let cardBeingChecked = self.game.playersHands[player.playerNumber].cardAt(discardedIndex) if self.countedRanks[cardBeingChecked!.getRank().rawValue-1] < 2 && self.countedSuits[cardBeingChecked!.getSuit().rawValue-1] < 4 && !cardBeingChecked!.isEqualTo(drawnCard, ignoreSuit: false) { return discardedIndex } else { if goRight { discardedIndex += 1 } else { discardedIndex -= 1 } if discardedIndex == numberOfCardsInHand { discardedIndex = 0 } if discardedIndex == -1 { discardedIndex = numberOfCardsInHand-1 } } } } return discardedIndex } }
mit
63945ee8b927e94531e65e9a1c735f20
38.529801
210
0.552689
4.666927
false
false
false
false
dangdangfeng/BOOKS
Swift 4/Swift Standard Library.playground/Sources/TimelineVisualizations.swift
1
4964
import UIKit public func loadElements() -> [(date: Date, image: UIImage)] { let plistElements = NSArray(contentsOf: Bundle.main.url(forResource: "Timeline", withExtension: "plist")!)! as! [[String: AnyObject]] return plistElements.map { elem in return (date: elem["date"] as! Date, image: UIImage(named: elem["image"] as! String)!) } } fileprivate final class TimelineCollectionCell: UICollectionViewCell { let photoView = UIImageView() let dateLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white photoView.contentMode = .scaleAspectFit photoView.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(photoView) dateLabel.font = UIFont.systemFont(ofSize: 12) dateLabel.textAlignment = .right dateLabel.numberOfLines = 1 dateLabel.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(dateLabel) let hPhotoConstraints = NSLayoutConstraint.constraints( withVisualFormat: "|[photoView]|", options: [], metrics: nil, views: ["photoView": photoView]) let hDateConstraints = NSLayoutConstraint.constraints( withVisualFormat: "|[dateLabel]|", options: [], metrics: nil, views: ["dateLabel": dateLabel]) let vConstraints = NSLayoutConstraint.constraints( withVisualFormat: "V:|[dateLabel(<=14)]-3-[photoView(134)]|", options: [], metrics: nil, views: ["photoView": photoView, "dateLabel": dateLabel]) self.contentView.addConstraints(hPhotoConstraints + hDateConstraints + vConstraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } fileprivate final class TimelineCollectionController: UICollectionViewController { let timelineCellIdentifier = "TimelineCellIdentifier" var elements = [(date: String, image: UIImage?)]() override func viewDidLoad() { self.collectionView!.backgroundColor = .white collectionView!.register(TimelineCollectionCell.self, forCellWithReuseIdentifier: timelineCellIdentifier) self.view.frame.size = CGSize(width: 1180, height: 160) collectionView!.contentInset = UIEdgeInsetsMake(5, 5, 5, 5) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return elements.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: timelineCellIdentifier, for: indexPath) as! TimelineCollectionCell let (date, image) = elements[indexPath.row] cell.photoView.image = image ?? UIImage(named: "NoImage.jpg") cell.dateLabel.text = date return cell } } // UICollectionViewControllers are deallocated before their collection view is rendered unless you store them somewhere. fileprivate var timelines = [TimelineCollectionController]() fileprivate final class BorderView: UIView { fileprivate override func draw(_ rect: CGRect) { UIColor(white: CGFloat(0.75), alpha: 1.0).set() UIRectFill(rect) } } fileprivate func showTimelineCollection(_ elements: [(date: String, image: UIImage?)]) -> UIView { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 7 layout.itemSize = CGSize(width: 134, height: 150) let timeline = TimelineCollectionController(collectionViewLayout: layout) timeline.elements = elements timelines.append(timeline) let topBorder = BorderView(frame: CGRect(x: 0, y: 0, width: 1180, height: 1)) let bottomBorder = BorderView(frame: CGRect(x: 0, y: 161, width: 1180, height: 1)) let view = UIView(frame: CGRect(x: 0, y: 0, width: 1180, height: 162)) view.addSubview(topBorder) timeline.view.frame.origin.y = 1 view.addSubview(timeline.view) view.addSubview(bottomBorder) return view } public let mayFirst = Date(timeIntervalSince1970: 1.4305e9) public let maySeventh = Date(timeIntervalSince1970: 1.431e9) public func visualize<C: Collection>(_ collection: C) -> UIView where C.Iterator.Element == UIImage? { let elements = zip(collection.indices, collection).map { (x: (C.Index, UIImage?)) -> (date: String, image: UIImage?) in let (date, image) = x return (date: String(reflecting: date), image: image) } return showTimelineCollection(elements) }
mit
697e3d11dcc0ff1bcbada71f77f227cd
38.086614
141
0.679291
4.895464
false
false
false
false
Brandon-J-Campbell/codemash
AutoLayoutSession/demos/demo9/codemash/ContainerViewController.swift
10
6401
// // ContainerViewController.swift // codemash // // Created by Brandon Campbell on 12/5/16. // Copyright © 2016 Brandon Campbell. All rights reserved. // import Foundation import UIKit class ContainerRow { var tabName : String? var items = Array<ContainerRow>() convenience init(withTabName: String) { self.init() self.tabName = withTabName } convenience init(items: Array<ContainerRow>) { self.init() self.items = items } } class ContainerCell : UICollectionViewCell { var viewController : ScheduleCollectionViewController? static func cellIdentifier() -> String { return "ContainerCell" } static func cell(forCollectionView collectionView: UICollectionView, indexPath: IndexPath, tabName: String) -> ContainerCell { let cell : ContainerCell = collectionView.dequeueReusableCell(withReuseIdentifier: ContainerCell.cellIdentifier(), for: indexPath) as! ContainerCell return cell } } class ContainerViewController : UICollectionViewController { var data = Dictionary<String, Array<Session>>() var sessions : Array<Session> = Array<Session>.init() var sections = Array<ContainerRow>() override func viewDidLoad() { super.viewDidLoad() /* let urlSession = URLSession.shared urlSession.dataTask(with: URL.init(string: "https://speakers.codemash.org/api/SessionsData/")!, completionHandler: { (data, response, error) -> Void in if let HTTPResponse = response as? HTTPURLResponse { let statusCode = HTTPResponse.statusCode if(data == nil || error != nil || statusCode != 200) { print(error.debugDescription) } else { do { let convertedString = String(data: data!, encoding: String.Encoding.utf8) // the data will be converted to the string print(convertedString!) let array : Array<Any?> = try JSONSerialization.jsonObject(with: data!, options: [.allowFragments]) as! Array<Any?> for dict : Dictionary<String, Any> in array as! Array<Dictionary<String, Any>> { let session = Session.parse(fromDictionary: dict) self.sessions.append(session) } } catch { print(error.localizedDescription) } DispatchQueue.main.async { self.setupSections() } } } }).resume() */ var rawSessions = Array<Session>.init() if let url = Bundle.main.url(forResource: "SessionsData", withExtension: "json") { if let data = NSData(contentsOf: url) { do { let array : Array<Any?> = try JSONSerialization.jsonObject(with: data as Data, options: [.allowFragments]) as! Array<Any?> for dict : Dictionary<String, Any> in array as! Array<Dictionary<String, Any>> { let session = Session.parse(fromDictionary: dict) rawSessions.append(session) } } catch { print("Error!! Unable to parse SessionsData.json") } } print("Error!! Unable to load SessionsData.json") } self.sessions = rawSessions.sorted() self.setupSections() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil, completion: { _ in DispatchQueue.main.async { self.collectionView?.reloadData() } }) } func setupSections() { var sections : Array<ContainerRow> = [] var rows : Array<ContainerRow> = [] let dayFormatter = DateFormatter.init() dayFormatter.dateFormat = "EEEE" for session in self.sessions { let day = dayFormatter.string(from: session.startTime) if data[day] == nil { data[day] = Array<Session>() rows.append(ContainerRow.init(withTabName: day)) } data[day]?.append(session) } sections.append(ContainerRow.init(items: rows)) self.sections = sections self.collectionView?.reloadData() } } extension ContainerViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return self.sections.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let section = self.sections[section] return section.items.count } } extension ContainerViewController { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let section = self.sections[indexPath.section] let row = section.items[indexPath.row] let cell = ContainerCell.cell(forCollectionView: collectionView, indexPath: indexPath, tabName: row.tabName!) if (cell.viewController == nil) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "ScheduleCollectionViewController") as! ScheduleCollectionViewController cell.viewController = vc self.addChildViewController(vc) cell.addSubview((vc.view)!) vc.view.frame = cell.bounds vc.view.autoresizingMask = [ .flexibleWidth, .flexibleHeight ] } cell.viewController?.sessions = data[row.tabName!]! return cell } } extension ContainerViewController : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return collectionView.bounds.size } }
mit
f9ab0b1f11fab7a18a77038b53df8c5c
35.571429
160
0.589063
5.414552
false
false
false
false
elkanaoptimove/OptimoveSDK
OptimoveSDK/Optimove Components/OptiPush/Registrar/RegistrationRequestComposer.swift
1
3806
// // JSONComposer.swift // OptimoveSDK // // Created by Mobile Developer Optimove on 26/09/2017. // Copyright © 2017 Optimove. All rights reserved. // import Foundation struct RegistrationRequestBuilder { func buildOptRequest(state: State.Opt) -> Data? { var requestJsonData = [String: Any]() if let bundleID = Bundle.main.bundleIdentifier?.replacingOccurrences(of: ".", with: "_") { let iOSToken = [Keys.Registration.bundleID.rawValue : bundleID, Keys.Registration.deviceID.rawValue : DeviceID ] requestJsonData[Keys.Registration.iOSToken.rawValue] = iOSToken requestJsonData[Keys.Registration.tenantID.rawValue] = TenantID if let customerId = UserInSession.shared.customerID { requestJsonData[Keys.Registration.customerID.rawValue] = customerId } else { requestJsonData[Keys.Registration.visitorID.rawValue] = VisitorID } let dictionary = state == .optIn ? [Keys.Registration.optIn.rawValue : requestJsonData] : [Keys.Registration.optOut.rawValue: requestJsonData] return try! JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) } return nil } func buildRegisterRequest() -> Data? { guard let bundleID = Bundle.main.bundleIdentifier?.replacingOccurrences(of: ".", with: "_") else { return nil } var requestJsonData = [String: Any]() var bundle = [String:Any]() bundle[Keys.Registration.optIn.rawValue] = UserInSession.shared.isMbaasOptIn bundle[Keys.Registration.token.rawValue] = UserInSession.shared.fcmToken let app = [bundleID: bundle] var device: [String: Any] = [Keys.Registration.apps.rawValue: app] device[Keys.Registration.osVersion.rawValue] = OSVersion let ios = [DeviceID: device] requestJsonData[Keys.Registration.iOSToken.rawValue] = ios requestJsonData[Keys.Registration.tenantID.rawValue] = UserInSession.shared.siteID if let customerId = UserInSession.shared.customerID { requestJsonData[Keys.Registration.origVisitorID.rawValue] = UserInSession.shared.visitorID requestJsonData[Keys.Registration.isConversion.rawValue] = UserInSession.shared.isFirstConversion requestJsonData[Keys.Registration.customerID.rawValue] = customerId } else { requestJsonData[Keys.Registration.visitorID.rawValue] = UserInSession.shared.visitorID } let dictionary = [Keys.Registration.registrationData.rawValue : requestJsonData] return try! JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) } func buildUnregisterRequest() -> Data? { guard let bundleID = Bundle.main.bundleIdentifier?.replacingOccurrences(of: ".", with: "_") else {return nil} var requestJsonData = [String: Any]() let iOSToken = [Keys.Registration.bundleID.rawValue : bundleID, Keys.Registration.deviceID.rawValue : DeviceID ] requestJsonData[Keys.Registration.iOSToken.rawValue] = iOSToken requestJsonData[Keys.Registration.tenantID.rawValue] = TenantID if let customerId = UserInSession.shared.customerID { requestJsonData[Keys.Registration.customerID.rawValue] = customerId } else { requestJsonData[Keys.Registration.visitorID.rawValue] = VisitorID } let dictionary = [Keys.Registration.unregistrationData.rawValue : requestJsonData] return try! JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) } }
mit
b56ddb5c5c195c5aa78d4b768dfdc145
47.782051
154
0.663338
4.680197
false
false
false
false
gmontalvoriv/mongod-starter
mongod-starter/AppDelegate.swift
1
12444
// // AppDelegate.swift // mongod-starter // // Created by Gabriel Montalvo on 1/4/16. // Copyright © 2016 Gabriel Montalvo. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { /* OUTLETS */ @IBOutlet weak var statusMenu: NSMenu! @IBOutlet weak var serverStatusMenuItem: NSMenuItem! @IBOutlet weak var startServerMenuItem: NSMenuItem! @IBOutlet weak var stopServerMenuItem: NSMenuItem! @IBOutlet weak var preferencesWindow: NSWindow! @IBOutlet weak var binPathTextfield: NSTextField! @IBOutlet weak var dataStoreTextfield: NSTextField! @IBOutlet weak var configFileTextfield: NSTextField! @IBOutlet weak var configFileCheckBox: NSButton! let statusItem = NSStatusBar.system().statusItem(withLength: -1) let defBinDir = UserDefaults.standard let defDataDir = UserDefaults.standard let configFileDir = UserDefaults.standard let useConfigFile = UserDefaults.standard var dataPath: String var binPath: String var configPath: String var task: Process = Process() var pipe: Pipe = Pipe() var file: FileHandle let mongodFile: String = "/mongod" override init() { self.file = self.pipe.fileHandleForReading if defDataDir.string(forKey: "defDataDir") != nil { self.dataPath = defDataDir.string(forKey: "defDataDir")! } else { self.dataPath = "" } if defBinDir.string(forKey: "defBinDir") != nil { self.binPath = defBinDir.string(forKey: "defBinDir")! + mongodFile } else { self.binPath = "" } if configFileDir.string(forKey: "configFileDir") != nil { self.configPath = configFileDir.string(forKey: "configFileDir")! } else { self.configPath = "" } super.init() } func startMongod() { self.task = Process() self.pipe = Pipe() self.file = self.pipe.fileHandleForReading if ((!FileManager.default.fileExists(atPath: self.binPath)) || (!FileManager.default.fileExists(atPath: self.dataPath))) { print("--> ERROR: Invalid path in UserDefaults") alert("Error: Invalid path", information: "MongoDB server and data storage locations are required. Go to Preferences.") return } else { let path = self.binPath self.task.launchPath = path if configFileCheckBox.state == NSOnState { if (FileManager.default.fileExists(atPath: self.configPath)) { self.task.arguments = ["--dbpath", self.dataPath, "--nounixsocket", "--config", self.configPath] if let port = getPort() { self.serverStatusMenuItem.title = "Running on Port \(port)" } else { self.serverStatusMenuItem.title = "Running on Port 27017" } } } else { self.task.arguments = ["--dbpath", self.dataPath, "--nounixsocket"] self.serverStatusMenuItem.title = "Running on Port 27017" } // Update status icon to active let icon = NSImage(named: "statusIconActive") icon?.isTemplate = false icon!.size = NSSize(width: 13.3, height: 18.3) statusItem.image = icon self.task.standardOutput = self.pipe self.serverStatusMenuItem.isHidden = false self.task.launch() print("-> MONGOD IS RUNNING...") self.startServerMenuItem.isHidden = true self.stopServerMenuItem.isHidden = false } } func stopMongod() { print("-> SHUTTING DOWN MONGOD") task.terminate() // Update status icon to inactive let appearance = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Light" var icon = NSImage(named: "statusIcon") if appearance == "Dark" { icon = NSImage(named: "statusIconDark") } icon?.isTemplate = false icon!.size = NSSize(width: 13.3, height: 18.3) statusItem.image = icon self.serverStatusMenuItem.isHidden = true self.startServerMenuItem.isHidden = false self.stopServerMenuItem.isHidden = true let data: Data = self.file.readDataToEndOfFile() self.file.closeFile() let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String print(output) } // returns the path to be stored in the UserDefaults database func getDir(_ canChooseFiles: Bool, canChooseDirectories: Bool) -> String { let browser: NSOpenPanel = NSOpenPanel() browser.allowsMultipleSelection = false browser.canChooseFiles = canChooseFiles browser.canChooseDirectories = canChooseDirectories let i = browser.runModal() let url = browser.url let path: String if (url != nil) { path = url!.path } else { path = "" } if (i == NSModalResponseOK) { return path } else { return "" } } // scans the user's mongod configuration file for port changes func getPort() -> String? { let configPath = self.configPath do { let content = try String(contentsOfFile: configPath, encoding: String.Encoding.utf8) let contentArray = content.components(separatedBy: "\n") for (_, element) in contentArray.enumerated() { let lineContent = element.trimmingCharacters(in: CharacterSet.whitespaces) if ((lineContent.range(of: "port") != nil) || (lineContent.range(of: "Port") != nil)) { if let port = lineContent.components(separatedBy: ":").last { return port.trimmingCharacters(in: CharacterSet.whitespaces) } } } } catch _ as NSError { return nil } return nil } // wraps NSAlert() methods func alert(_ message: String, information: String) { let alert = NSAlert() alert.messageText = message alert.informativeText = information alert.runModal() } /* ITEM ACTIONS */ @IBAction func startServer(_ sender: NSMenuItem) { startMongod() } @IBAction func stopServer(_ sender: NSMenuItem) { stopMongod() } @IBAction func openPreferences(_ sender: NSMenuItem) { self.preferencesWindow!.orderFront(self) NSApplication.shared().activate(ignoringOtherApps: true) } @IBAction func browseBinDir(_ sender: NSButton) { binPathTextfield.stringValue = getDir(false, canChooseDirectories: true) defBinDir.set(binPathTextfield.stringValue, forKey: "defBinDir") self.binPath = defBinDir.string(forKey: "defBinDir")! + mongodFile } @IBAction func browseDataDir(_ sender: NSButton) { dataStoreTextfield.stringValue = getDir(false, canChooseDirectories: true) defDataDir.set(dataStoreTextfield.stringValue, forKey: "defDataDir") self.dataPath = defDataDir.string(forKey: "defDataDir")! } @IBAction func browseConfigDir(_ sender: NSButton) { configFileTextfield.stringValue = getDir(true, canChooseDirectories: false) configFileDir.set(configFileTextfield.stringValue, forKey: "configFileDir") self.configPath = configFileDir.string(forKey: "configFileDir")! configFileCheckBox.isEnabled = true } @IBAction func useConfigurationFile(_ sender: NSButton) { if configFileCheckBox.state == NSOnState { useConfigFile.set(true, forKey: "useConfigFile") } else if (configFileCheckBox.state == NSOffState) { useConfigFile.set(false, forKey: "useConfigFile") } useConfigFile.synchronize() } @IBAction func resetPreferences(_ sender: NSButton) { UserDefaults.standard.removeObject(forKey: "defDataDir") UserDefaults.standard.removeObject(forKey: "defBinDir") UserDefaults.standard.removeObject(forKey: "configFileDir") UserDefaults.standard.removeObject(forKey: "useConfigFile") dataStoreTextfield.stringValue = "" binPathTextfield.stringValue = "" configFileTextfield.stringValue = "" configFileCheckBox.isEnabled = false UserDefaults.standard.synchronize() } @IBAction func openAbout(_ sender: NSMenuItem) { NSApplication.shared().orderFrontStandardAboutPanel(sender) NSApplication.shared().activate(ignoringOtherApps: true) } @IBAction func openDoc(_ sender: NSMenuItem) { if let url: URL = URL(string: "https://github.com/gmontalvoriv/mongod-starter") { NSWorkspace.shared().open(url) } } @IBAction func openIssues(_ sender: NSMenuItem) { if let url: URL = URL(string: "https://github.com/gmontalvoriv/mongod-starter/issues") { NSWorkspace.shared().open(url) } } @IBAction func quit(_ sender: NSMenuItem) { NSApplication.shared().terminate(sender) } /* LAUNCH AND TERMINATION EVENTS */ func applicationDidFinishLaunching(_ aNotification: Notification) { self.preferencesWindow!.orderOut(self) if self.useConfigFile.bool(forKey: "useConfigFile") == true { configFileCheckBox.state = NSOnState } else { configFileCheckBox.state = NSOffState } if defDataDir.string(forKey: "defDataDir") != nil { let customDataDirectory = defDataDir.string(forKey: "defDataDir")! dataStoreTextfield.stringValue = customDataDirectory } if defBinDir.string(forKey: "defBinDir") != nil { let customBinDirectory = defBinDir.string(forKey: "defBinDir")! binPathTextfield.stringValue = customBinDirectory } if configFileDir.string(forKey: "configFileDir") != nil { let configFileDirectory = configFileDir.string(forKey: "configFileDir")! configFileTextfield.stringValue = configFileDirectory configFileCheckBox.isEnabled = true } let appearance = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Light" var icon = NSImage(named: "statusIcon") if appearance == "Dark" { icon = NSImage(named: "statusIconDark") } icon?.isTemplate = false icon!.size = NSSize(width: 13.3, height: 18.3) if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String? { statusItem.toolTip = "mongod-starter \(version)" } statusItem.length = 27 statusItem.image = icon statusItem.menu = statusMenu DistributedNotificationCenter.default.addObserver(self, selector: #selector(interfaceModeChanged(sender:)), name: NSNotification.Name(rawValue: "AppleInterfaceThemeChangedNotification"), object: nil) } func applicationWillTerminate(_ notification: Notification) { if (self.startServerMenuItem.isHidden == false) { return } stopMongod() // makes sure the server shuts down before quitting the application } func interfaceModeChanged(sender: NSNotification) { if(!self.startServerMenuItem.isHidden) { let appearance = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Light" var icon = NSImage(named: "statusIcon") if appearance == "Dark" { icon = NSImage(named: "statusIconDark") } icon?.isTemplate = false icon!.size = NSSize(width: 13.3, height: 18.3) statusItem.image = icon } } }
mit
50a30a7da731c02fbfa5bb6a44102969
34.85879
207
0.596962
4.896891
false
true
false
false
fxwx23/Volumizer
Volumizer/Volumizer.swift
1
12337
// // Volumizer.swift // Volumizer // // Created by Fumitaka Watanabe on 2017/03/16. // Copyright © 2017年 Fumitaka Watanabe. All rights reserved. // import Foundation import AVFoundation import MediaPlayer fileprivate let AVAudioSessionOutputVolumeKey = "outputVolume" /** Errors being thrown by `VolumizerError`. - disableToChangeVolumeLevel: `Volumizer` was unable to change audio level */ public enum VolumizerError: Error { case disableToChangeVolumeLevel } /** VolumizerAppearanceOption */ public enum VolumizerAppearanceOption { case overlayIsTranslucent(Bool) case overlayBackgroundBlurEffectStyle(UIBlurEffect.Style) case overlayBackgroundColor(UIColor) case sliderProgressTintColor(UIColor) case sliderTrackTintColor(UIColor) } /** - Volumizer Replace default `MPVolumeView` by volumizer. */ open class Volumizer: UIView { // MARK: Properties // current volume value. public fileprivate(set) var volume: Float = 0 private let session = AVAudioSession.sharedInstance() private let volumeView = MPVolumeView(frame: CGRect.zero) private let overlay = UIView() private var overlayBlur = UIVisualEffectView() private var slider = UIProgressView() private var base: UIWindow? private var isAppActive = false private var isAlreadyWindowLevelAboveNormal = false // MARK: Initializations public convenience init(options: [VolumizerAppearanceOption], base: UIWindow) { /// default width self.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.height, height: UIApplication.shared.statusBarFrame.height)) self.base = base isAppActive = true setupSession(options) } override private init(frame: CGRect) { super.init(frame: frame) overlay.frame = frame } required public init() { fatalError("Please use the convenience initializer `init(options:_, base:_)` instead.") } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented.") } deinit { session.removeObserver(self, forKeyPath: AVAudioSessionOutputVolumeKey, context: nil) NotificationCenter.default.removeObserver(self) } // MARK: Layout open override func layoutSubviews() { super.layoutSubviews() let statusBarHeight: CGFloat = UIApplication.shared.statusBarFrame.height overlay.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: statusBarHeight) overlayBlur.frame = overlay.bounds // Progress view frame is defined based on the device model. // Slider view style would be like Instagram's way (of course iPhoneX too). let deviceHasNotch = UIDevice.current.hasNotch let marginLeft = deviceHasNotch ? (layoutMargins.left * 2) : layoutMargins.left let top: CGFloat = (overlay.frame.height - slider.frame.height) / 2 let width: CGFloat = deviceHasNotch ? (marginLeft * 2 + statusBarHeight) - marginLeft : overlay.frame.width - (marginLeft * 2) slider.frame = CGRect(x: marginLeft, y: top, width: width, height: slider.frame.height) slider.layer.cornerRadius = slider.bounds.height / 2 slider.clipsToBounds = true } // MARK: Convenience @discardableResult open class func configure(_ options: [VolumizerAppearanceOption] = []) -> Volumizer { let base = UIWindow(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.height, height: UIApplication.shared.statusBarFrame.height)) base.windowLevel = UIWindow.Level.statusBar + 1.0 let instance = Volumizer(options: options, base: base) base.addSubview(instance) base.makeKeyAndVisible() return instance } open func change(options: [VolumizerAppearanceOption]) { options.forEach { switch $0 { case .overlayIsTranslucent(let isTranslucent): if isTranslucent { overlayBlur.isHidden = false } else { overlayBlur.isHidden = true } case .overlayBackgroundBlurEffectStyle(let style): overlayBlur.effect = UIBlurEffect(style: style) case .overlayBackgroundColor(let color): overlay.backgroundColor = color backgroundColor = color case .sliderProgressTintColor(let color): slider.progressTintColor = color case .sliderTrackTintColor(let color): slider.trackTintColor = color } } } open func resign() { base?.resignKey() base = nil } // MARK: Private private func setupSession(_ options: [VolumizerAppearanceOption]) { do { try session.setCategory( .playback, mode: .default, options: .mixWithOthers) } catch { print("Unable to set audio session category.") } do { try session.setActive(true) } catch { print("Unable to initialize AVAudioSession.") } volumeView.setVolumeThumbImage(UIImage(), for: UIControl.State()) volumeView.isUserInteractionEnabled = false volumeView.showsRouteButton = false addSubview(volumeView) /// overlay's `backgroundColor` is white by default. overlay.backgroundColor = .white addSubview(overlay) overlayBlur = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) overlayBlur.frame = overlay.bounds overlay.addSubview(overlayBlur) /// slider's `thumbTintColor` is black by default. slider.backgroundColor = .white slider.progressTintColor = .black slider.trackTintColor = UIColor.lightGray.withAlphaComponent(0.5) addSubview(slider) change(options: options) update(volume: session.outputVolume, animated: false) /// add observers. session.addObserver(self, forKeyPath: AVAudioSessionOutputVolumeKey, options: .new, context: nil) NotificationCenter.default.addObserver(self, selector: #selector(audioSessionInterrupted(_:)), name: AVAudioSession.interruptionNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(audioSessionRouteChanged(_:)), name: AVAudioSession.routeChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidChangeActive(_:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidChangeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) } private func update(volume value: Float, animated: Bool) { volume = value slider.setProgress(volume, animated: true) do { try setSystem(volume: value) } catch { print("unable to change system volume level.") } let deviceHasNotch = UIDevice.current.hasNotch let animationDuration = deviceHasNotch ? 1.0 : 2.0 let showRelativeDuration = deviceHasNotch ? 0.05 : 0.1 let hideRelativeDuration = deviceHasNotch ? 0.3 : 0.1 UIView.animateKeyframes(withDuration: animated ? animationDuration : 0, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: showRelativeDuration, animations: { self.animateProgressView(showing: true) }) UIView.addKeyframe(withRelativeStartTime: 0.8, relativeDuration: hideRelativeDuration, animations: { () -> Void in self.animateProgressView(showing: false) }) }) { _ in } } private func setSystem(volume value: Float) throws { guard let systemSlider = volumeView.subviews.compactMap({ $0 as? UISlider }).first else { throw VolumizerError.disableToChangeVolumeLevel } systemSlider.value = max(0, min(1, value)) } private func animateProgressView(showing: Bool) { if showing { self.alpha = 1 self.base?.transform = CGAffineTransform.identity } else { self.alpha = 0.0001 self.base?.transform = UIDevice.current.hasNotch ? CGAffineTransform.identity : CGAffineTransform(translationX: 0, y: -self.frame.height) } } // MARK: Notification @objc private func audioSessionInterrupted(_ notification: Notification) { guard let interruptionInfo = notification.userInfo, let rawValue = interruptionInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let interruptionType = AVAudioSession.InterruptionType(rawValue: rawValue) else { return } switch interruptionType { case .began: print("Audio Session Interruption: began.") break case .ended: print("Audio Session Interruption: ended.") do { try session.setActive(true) } catch { print("Unable to initialize AVAudioSession.") } @unknown default: fatalError("unknown AVAudioSessio.InterruptionType is addded.") } } @objc private func audioSessionRouteChanged(_ notification: Notification) { guard let interruptionInfo = notification.userInfo, let rawValue = interruptionInfo[AVAudioSessionRouteChangeReasonKey] as? UInt, let reason = AVAudioSession.RouteChangeReason(rawValue: rawValue) else { return } switch reason { case .newDeviceAvailable: print("Audio seesion route changed: new device available.") break case .oldDeviceUnavailable: print("Audio seesion route changed: old device unavailable.") break default: print("Audio seesion route changed: \(reason.rawValue)") break } } @objc private func applicationDidChangeActive(_ notification: Notification) { isAppActive = notification.name == UIApplication.didBecomeActiveNotification if isAppActive { update(volume: session.outputVolume, animated: false) } } @objc private func orientationDidChange(_ notification: Notification) { // TODO: [wip] support landscape mode. // print("orientation changed.") /** let currentOrientation = UIDevice.current.orientation switch currentOrientation { case .landscapeLeft: base?.transform = CGAffineTransform(rotationAngle: -CGFloat(90 * M_PI / 180.0)) case .landscapeRight: base?.transform = CGAffineTransform(rotationAngle: CGFloat(90 * M_PI / 180.0)) case .portraitUpsideDown: base?.transform = CGAffineTransform(rotationAngle: CGFloat(180.0 * M_PI / 180.0)) default: base?.transform = CGAffineTransform(rotationAngle: CGFloat(0.0 * M_PI / 180.0)) } */ } // MARK: KVO open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let change = change, let value = change[.newKey] as? Float , keyPath == AVAudioSessionOutputVolumeKey else { return } update(volume: value, animated: UIDevice.current.orientation.isPortrait) } } extension UIDevice { fileprivate var hasNotch: Bool { guard let window = UIApplication.shared.keyWindow else { return false } if #available(iOS 11.0, *) { return window.safeAreaInsets.bottom > 0.0 && UIDevice.current.userInterfaceIdiom == .phone } else { return false } } }
mit
74bf385748ec92e14c9de50d8d5e02bf
38.155556
168
0.641884
5.092486
false
false
false
false
koher/CGPoint-Vector
Sources/CGPointVector/CGSize.swift
2
4038
import CoreGraphics extension CGSize { public func isNearlyEqual(to point: CGSize, epsilon: CGFloat) -> Bool { let difference = self - point return abs(difference.width) < epsilon && abs(difference.height) < epsilon } public var length: CGFloat { return hypot(width, height) } public var squareLength: CGFloat { return width * width + height * height } public var unit: CGSize { return self * (1.0 / length) } public var phase: CGFloat { return atan2(height, width) } public func distance(from point: CGSize) -> CGFloat { return (self - point).length } public func squareDistance(from point: CGSize) -> CGFloat { return (self - point).squareLength } public func angle(from point: CGSize) -> CGFloat { return acos(cos(from: point)) } public func cos(from point: CGSize) -> CGFloat { let squareLength1 = self.squareLength guard squareLength1 > 0.0 else { return 1.0 } let squareLength2 = point.squareLength guard squareLength2 > 0.0 else { return 1.0 } return Swift.min(Swift.max(self.dot(point) / sqrt(squareLength1 * squareLength2), -1.0), 1.0) } public func dot(_ other: CGSize) -> CGFloat { return self.width * other.width + self.height * other.height } } extension CGSize: CustomStringConvertible { public var description: String { return "(\(width), \(height))" } } extension CGSize { public static prefix func + (value: CGSize) -> CGSize { return value } public static prefix func - (value: CGSize) -> CGSize { return CGSize(width: -value.width, height: -value.height) } public static func + (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height) } public static func - (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width - rhs.width, height: lhs.height - rhs.height) } public static func * (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width * rhs.width, height: lhs.height * rhs.height) } public static func * (lhs: CGSize, rhs: CGFloat) -> CGSize { return CGSize(width: lhs.width * rhs, height: lhs.height * rhs) } public static func * (lhs: CGFloat, rhs: CGSize) -> CGSize { return CGSize(width: rhs.width * lhs, height: rhs.height * lhs) } public static func / (lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width / rhs.width, height: lhs.height / rhs.height) } public static func / (lhs: CGSize, rhs: CGFloat) -> CGSize { return CGSize(width: lhs.width / rhs, height: lhs.height / rhs) } public static func += (lhs: inout CGSize, rhs: CGSize) { lhs = lhs + rhs } public static func -= (lhs: inout CGSize, rhs: CGSize) { lhs = lhs - rhs } public static func *= (lhs: inout CGSize, rhs: CGSize) { lhs = lhs * rhs } public static func *= (lhs: inout CGSize, rhs: CGFloat) { lhs = lhs * rhs } public static func /= (lhs: inout CGSize, rhs: CGSize) { lhs = lhs / rhs } public static func /= (lhs: inout CGSize, rhs: CGFloat) { lhs = lhs / rhs } } extension CGSize { public static func + (lhs: CGSize, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.width + rhs.x, y: lhs.height + rhs.y) } public static func - (lhs: CGSize, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.width - rhs.x, y: lhs.height - rhs.y) } public static func * (lhs: CGSize, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.width * rhs.x, y: lhs.height * rhs.y) } public static func / (lhs: CGSize, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.width / rhs.x, y: lhs.height / rhs.y) } }
mit
72bb780e685482759c8e9496f368b257
29.134328
101
0.5842
3.897683
false
false
false
false
darina/omim
iphone/Maps/Classes/Widgets/DownloadBanner/MultiPartnerBannerViewController.swift
4
753
final class MultiPartnerBannerViewController: DownloadBannerViewController { @IBOutlet var icons: [UIImageView]! @IBOutlet var message: UILabel! @IBOutlet var button: UIButton! private let model: PartnerBannerViewModel init(model: PartnerBannerViewModel, tapHandler: @escaping MWMVoidBlock) { self.model = model super.init(tapHandler: tapHandler) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() for (iconView, imageName) in zip(icons, model.images) { iconView.image = UIImage(named: imageName) } message.text = model.message button.localizedText = model.button button.styleName = model.style } }
apache-2.0
29bda7a4b6cf0a822a6df9f6a64a795c
27.961538
76
0.722444
4.429412
false
false
false
false
jcheng77/missfit-ios
missfit/missfit/MyClassTableViewCell.swift
1
1150
// // MyClassTableViewCell.swift // missfit // // Created by Hank Liang on 5/5/15. // Copyright (c) 2015 Hank Liang. All rights reserved. // import UIKit class MyClassTableViewCell: ClassTableViewCell { @IBOutlet weak var startDate: UILabel! override func setData(missfitClass: MissFitClass) { let dateString = missfitClass.schedule.date let startIndex = advance(dateString.startIndex, 5) startDate.text = dateString.substringFromIndex(startIndex) startTime.text = missfitClass.schedule.startTime name.text = missfitClass.name duration.text = String("\(missfitClass.schedule.duration)分钟") address.text = missfitClass.location.address area.text = missfitClass.location.area teacherAvatar.image = nil if let avatarUrl = missfitClass.teacher.avatarUrl { teacherAvatar.setImageWithURL(NSURL(string: avatarUrl), placeholderImage: UIImage(named: "default-teacher-avatar")) teacherAvatar.hidden = false } else { teacherAvatar.hidden = true } teacherName.text = missfitClass.teacher.name } }
mit
662ca2c0eb5f18fdd07099cfb6fb4cca
34.8125
127
0.684991
4.407692
false
true
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Services/APIs/OrganizationsService.swift
2
2473
// // OrgranizationsService.swift // SmartReceipts // // Created by Bogdan Evsenev on 24/07/2019. // Copyright © 2019 Will Baumann. All rights reserved. // import RxSwift import RxCocoa import Alamofire import Moya private let SYNC_ID = "sync.id" protocol OrganizationsServiceInterface { func getOrganizations() -> Single<[OrganizationModel]> func saveOrganization(_ organization: OrganizationModel) -> Single<OrganizationModel> func sync(organization: OrganizationModel) func startSync() var currentOrganiztionId: String? { get } } class OrganizationsService: OrganizationsServiceInterface { private let api: APIProvider<SmartReceiptsAPI> private let bag = DisposeBag() init(api: APIProvider<SmartReceiptsAPI> = .init()) { self.api = api } func getOrganizations() -> Single<[OrganizationModel]> { return api.request(.organizations) .mapModel(OrganizationsResponse.self) .map { $0.organizations } } var currentOrganiztionId: String? { return UserDefaults.standard.string(forKey: SYNC_ID) } func saveOrganization(_ organization: OrganizationModel) -> Single<OrganizationModel> { return api.request(.saveOrganization(organization)) .mapModel(OrganizationModel.self) } func sync(organization: OrganizationModel) { UserDefaults.standard.set(organization.id, forKey: SYNC_ID) WBPreferences.importModel(settings: organization.appSettings.settings) Database.sharedInstance().importSettings(models: organization.appSettings.models) } func startSync() { AuthService.shared.loggedInObservable .filter { $0 } .flatMap { _ -> Observable<(String, [OrganizationModel])> in let organizationService = ServiceFactory.shared.organizationService let idObservable = Observable.just(organizationService.currentOrganiztionId).filterNil().asObservable() let organizationsObservable = organizationService.getOrganizations().asObservable() return Observable.zip(idObservable, organizationsObservable) }.map { id, organizations in return organizations.first(where: { $0.id == id }) }.filterNil() .subscribe(onNext: { ServiceFactory.shared.organizationService.sync(organization: $0) }).disposed(by: bag) } }
agpl-3.0
253f14c7422a2c7c8ab20cfae48e9a5f
34.826087
119
0.673544
4.763006
false
false
false
false
bogosmer/UnitKit
UnitKit/Source/Protocols/Unit.swift
1
3370
// // Unit.swift // UnitKit // // Created by Bo Gosmer on 09/02/2016. // Copyright © 2016 Deadlock Baby. All rights reserved. // import Foundation public protocol Unit: CustomStringConvertible { typealias T: UnitType static var sharedDecimalNumberHandler: NSDecimalNumberHandler? { get set } // get segmentation fault 11 when building module if the static and instance variable have same name var decimalNumberHandler: NSDecimalNumberHandler? { get set } // get segmentation fault 11 when building module if the static and instance variable have same name var baseUnitTypeValue: NSDecimal { get } var unitType: T { get } init(value: NSDecimalNumber, type: T) init(value: Double, type: T) init(value: Int, type: T) func valueForUnitType(unitType: T) -> NSDecimalNumber func localizedNameOfUnitType(locale: NSLocale?) -> String func localizedAbbreviationOfUnitType(locale: NSLocale?) -> String } public extension Unit { public var description: String { return "\(valueForUnitType(unitType)) \(localizedNameOfUnitType(NSLocale(localeIdentifier: "en")))" } func localizedNameOfUnitType(locale: NSLocale?) -> String { if NSDecimalNumber.one().compare(valueForUnitType(unitType).absoluteValue) == .OrderedAscending { return Localize.localize(String(self.dynamicType) + ".name.plural." + unitType.description, locale: locale) } else { return Localize.localize(String(self.dynamicType) + ".name.single." + unitType.description, locale: locale) } } func localizedAbbreviationOfUnitType(locale: NSLocale?) -> String { if NSDecimalNumber.one().compare(valueForUnitType(unitType).absoluteValue) == .OrderedAscending { return Localize.localize(String(self.dynamicType) + ".abbreviation.plural." + unitType.description, locale: locale) } else { return Localize.localize(String(self.dynamicType) + ".abbreviation.single." + unitType.description, locale: locale) } } } internal protocol _Unit: Unit { func convertToBaseUnitType(value: NSDecimalNumber, fromType: T) -> NSDecimalNumber func convertFromBaseUnitTypeTo(unitType: T) -> NSDecimalNumber } internal extension _Unit { internal func convertToBaseUnitType(value: NSDecimalNumber, fromType: T) -> NSDecimalNumber { let handler = decimalNumberHandler ?? self.dynamicType.sharedDecimalNumberHandler let result: NSDecimalNumber if handler != nil { result = value.decimalNumberByMultiplyingBy(fromType.baseUnitTypePerUnit(), withBehavior: handler) } else { result = value.decimalNumberByMultiplyingBy(fromType.baseUnitTypePerUnit()) } return result } internal func convertFromBaseUnitTypeTo(unitType: T) -> NSDecimalNumber { let handler = decimalNumberHandler ?? self.dynamicType.sharedDecimalNumberHandler let result: NSDecimalNumber if handler != nil { result = NSDecimalNumber(decimal: baseUnitTypeValue).decimalNumberByDividingBy(unitType.baseUnitTypePerUnit(), withBehavior: handler) } else { result = NSDecimalNumber(decimal: baseUnitTypeValue).decimalNumberByDividingBy(unitType.baseUnitTypePerUnit()) } return result } }
mit
b44e171060b8aa4743e8c8f6a1b24732
39.590361
179
0.699911
4.998516
false
false
false
false
aslanyanhaik/Quick-Chat
QuickChat/Presenter/UIObjects/UILabelGradient.swift
1
2298
// MIT License // Copyright (c) 2019 Haik Aslanyan // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class UILabelGradient: UILabel { @IBInspectable var leftColor: UIColor = ThemeService.purpleColor { didSet { applyGradient() } } @IBInspectable var rightColor: UIColor = ThemeService.blueColor { didSet { applyGradient() } } override var text: String? { didSet { applyGradient() } } func applyGradient() { let gradientLayer = CAGradientLayer() gradientLayer.colors = [leftColor.cgColor, rightColor.cgColor] gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) let textSize = NSAttributedString(string: text ?? "", attributes: [.font: font!]).size() gradientLayer.bounds = CGRect(origin: .zero, size: textSize) UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, true, 0.0) let context = UIGraphicsGetCurrentContext() gradientLayer.render(in: context!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() textColor = UIColor(patternImage: image!) } override func awakeFromNib() { super.awakeFromNib() applyGradient() } }
mit
cecc3435802eba6c9308aac5a1494cbf
34.90625
92
0.721497
4.523622
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/DetailsMainVC.swift
1
3991
// // DetailsMainVC.swift // RealmModelGenerator // // Created by Zhaolong Zhong on 3/28/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Cocoa class DetailsMainVC: NSViewController { static let TAG = NSStringFromClass(DetailsMainVC.self) let ENTITYDETAILVC: NSStoryboard.SceneIdentifier = NSStoryboard.SceneIdentifier(rawValue: "EntityDetailVC") let ATTRIBUTEDETAILVC: NSStoryboard.SceneIdentifier = NSStoryboard.SceneIdentifier(rawValue: "AttributeDetailVC") let RELATIONSHIPDETAILVC: NSStoryboard.SceneIdentifier = NSStoryboard.SceneIdentifier(rawValue: "RelationshipDetailVC") private var entityDetailVC: EntityDetailVC! = nil private var attributeDetailVC: AttributeDetailVC! = nil private var relationshipDetailVC: RelationshipDetailVC! = nil @IBOutlet weak var detailsContainerView: NSView! @IBOutlet weak var emptyTextField: NSTextField! var isAttributeSelected = false weak var selectedEntity:Entity? { didSet { if self.selectedEntity === oldValue { return } self.selectedAttribute = nil self.selectedRelationship = nil self.invalidateViews() } } weak var selectedAttribute: Attribute? { didSet { if self.selectedAttribute === oldValue { return } self.isAttributeSelected = true self.invalidateViews() } } weak var selectedRelationship: Relationship? { didSet { if self.selectedRelationship === oldValue { return } self.isAttributeSelected = false self.invalidateViews() } } var detailType: DetailType { if selectedEntity != nil { if selectedAttribute != nil && (self.isAttributeSelected || selectedRelationship == nil) { return .Attribute } if selectedRelationship != nil { return .Relationship } return .Entity } return .Empty } override func viewDidLoad() { super.viewDidLoad() entityDetailVC = self.storyboard!.instantiateController(withIdentifier: ENTITYDETAILVC) as! EntityDetailVC attributeDetailVC = self.storyboard!.instantiateController(withIdentifier: ATTRIBUTEDETAILVC) as! AttributeDetailVC relationshipDetailVC = self.storyboard!.instantiateController(withIdentifier: RELATIONSHIPDETAILVC) as! RelationshipDetailVC self.addChildViewController(entityDetailVC) self.addChildViewController(attributeDetailVC) self.addChildViewController(relationshipDetailVC) detailsContainerView.addSubview(entityDetailVC.view) detailsContainerView.addSubview(attributeDetailVC.view) detailsContainerView.addSubview(relationshipDetailVC.view) self.emptyTextField.isHidden = false self.entityDetailVC.view.isHidden = true self.attributeDetailVC.view.isHidden = true self.relationshipDetailVC.view.isHidden = true } override func viewWillAppear() { super.viewWillAppear() invalidateViews() } func invalidateViews() { entityDetailVC.entity = self.selectedEntity attributeDetailVC.attribute = self.selectedAttribute relationshipDetailVC.relationship = self.selectedRelationship self.emptyTextField.isHidden = true self.entityDetailVC.view.isHidden = true self.attributeDetailVC.view.isHidden = true self.relationshipDetailVC.view.isHidden = true switch self.detailType { case .Entity: self.entityDetailVC.view.isHidden = false case .Attribute: self.attributeDetailVC.view.isHidden = false case .Relationship: self.relationshipDetailVC.view.isHidden = false case .Empty: self.emptyTextField.isHidden = false } } }
mit
7dda2832126eb6bd31e9ab0935fcf70f
35.605505
132
0.668672
5.384615
false
false
false
false
wokalski/Diff.swift
PerfTests/Utils/Resources/Diff-old.swift
5
5076
public struct Diff { let elements: [DiffElement] } public enum DiffElement { case Insert(from: Int, at: Int) case Delete(at: Int) case Equal(aIndex: Int, bIndex: Int) } extension DiffElement { init(trace: Trace) { if trace.from.x + 1 == trace.to.x && trace.from.y + 1 == trace.to.y { self = .Equal(aIndex: trace.to.x, bIndex: trace.to.y) } else if trace.from.y < trace.to.y { self = .Insert(from: trace.from.y, at: trace.from.x) } else { self = .Delete(at: trace.from.x) } } } struct Point { let x: Int let y: Int } struct Trace { let from: Point let to: Point } public extension RangeReplaceableCollectionType where Self.Generator.Element: Equatable, Self.Index: SignedIntegerType { public func apply(patch: Patch<Generator.Element, Index>) -> Self { var mutableSelf = self for insertion in patch.insertions { mutableSelf.insert(insertion.element, atIndex: insertion.index) } for deletion in patch.deletions { mutableSelf.removeAtIndex(deletion) } return mutableSelf } public func apply(patch: [PatchElement<Generator.Element, Index>]) -> Self { var mutableSelf = self for change in patch { switch change { case let .Insertion(index, element): mutableSelf.insert(element, atIndex: index) case let .Deletion(index): mutableSelf.removeAtIndex(index) } } return mutableSelf } } public extension CollectionType where Generator.Element: Equatable, Index: SignedIntegerType { public func diff(b: Self) -> Diff { let N = Int(self.count.toIntMax()) let M = Int(b.count.toIntMax()) var traces = Array<Trace>() let max = N + M // this is arbitrary, maximum difference between a and b. N+M assures that this algorithm always finds a diff var V = Array(count: 2 * Int(max) + 1, repeatedValue: -1) // from [0...2*max], it is -max...max in the whitepaper V[max + 1] = 0 for D in 0 ... max { for k in (-D).stride(through: D, by: 2) { let index = k + max // if x value for bigger (x-y) V[index-1] is smaller than x value for smaller (x-y) V[index+1] // then return smaller (x-y) // well, why?? // It means that y = x - k will be bigger // otherwise y = x - k will be smaller // What is the conclusion? Hell knows. /* case 1: k == -D: take the furthest going k+1 trace and go greedly down. We take x of the furthest going k+1 path and go greedly down. case 2: k == D: take the furthest going k-d trace and go right. Again, k+1 is unknown so we have to take k-1. What's more k-1 is right most one trace. We add 1 so that we go 1 to the right direction and stay on the same y case 3: -D<k<D: take the rightmost one (biggest x) and if it the previous trace went right go down, otherwise (if it the trace went down) go right */ var x = { _ -> Int in if k == -D || (k != D && V[index - 1] < V[index + 1]) { // V[index-1] - y is bigger V[index+1] - y is smaller let x = V[index + 1] traces.append(Trace(from: Point(x: x, y: x - k - 1), to: Point(x: x, y: x - k))) return x // go down AKA insert } else { let x = V[index - 1] + 1 traces.append(Trace(from: Point(x: x - 1, y: x - k), to: Point(x: x, y: x - k))) return x // go right AKA delete } }() var y = x - k // keep going as long as they match on diagonal k while x < N && y < M && self[Self.Index(x.toIntMax())] == b[Self.Index(y.toIntMax())] { x += 1 y += 1 traces.append(Trace(from: Point(x: x - 1, y: y - 1), to: Point(x: x, y: y))) } V[index] = x if x >= N && y >= M { return findPath(traces, n: N, m: M) } } } return Diff(elements: []) } private func findPath(traces: Array<Trace>, n: Int, m: Int) -> Diff { guard traces.count > 0 else { return Diff(elements: []) } var array = Array<Trace>() var item = traces.last! array.append(item) for trace in traces.reverse() { if trace.to.x == item.from.x && trace.to.y == item.from.y { array.append(trace) item = trace } if trace.from.x == 0 && trace.from.y == 0 { break } } return Diff(elements: array.reverse().map { DiffElement(trace: $0) }) } }
mit
02c15df4076e78f499a0e2dd5d0f8efa
33.067114
238
0.507683
3.931836
false
false
false
false
mesosfer/Mesosfer-iOS
Sample-Swift/07-add-n-delete-data/Mesosfer-Swift/FormDataViewController.swift
1
1812
/** * Copyright (c) 2016, Mesosfer * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ import Foundation import UIKit import Mesosfer protocol FormDataViewControllerDelegate { func onSavedData(beacon: MFData, isNewData: Bool) } class FormDataViewController: UITableViewController { @IBOutlet weak var textUUID: UITextField! @IBOutlet weak var textMajor: UITextField! @IBOutlet weak var textMinor: UITextField! @IBOutlet weak var switchIsActive: UISwitch! var delegate: FormDataViewControllerDelegate? = nil @IBAction func saveSelector(_ sender: UIBarButtonItem) { let bucket = "Beacon" let proximityUUID = self.textUUID.text let major = Int(self.textMajor.text!) let minor = Int(self.textMinor.text!) let isActive = self.switchIsActive.isOn let timestamp = NSDate() let beacon = MFData(withBucket: bucket) beacon["proximityUUID"] = proximityUUID beacon["major"] = major beacon["minor"] = minor beacon["isActive"] = isActive beacon["timestamp"] = timestamp beacon.saveAsync { (succeeded, error) in if succeeded { self.showAlert(message: "Data beacon saved", handler: { (action) in guard let delegate = self.delegate else { return } delegate.onSavedData(beacon: beacon, isNewData: true) _ = self.navigationController?.popViewController(animated: true) }) } else { self.showError(title: "Failed to save data", error: error as! NSError) } } } }
bsd-3-clause
22dd07cc1080dcdad7199351a10fb689
32.555556
86
0.616446
4.870968
false
false
false
false
TotalDigital/People-iOS
People at Total/Contact.swift
1
2181
// // Contact.swift // justOne // // Created by Florian Letellier on 29/01/2017. // Copyright © 2017 Florian Letellier. All rights reserved. // import Foundation class Contact: NSObject, NSCoding { var email: String? var phone_number: String? var linkedin_profile:String? var twitter_profile:String? var agil_profile:String? var wat_profile: String? var skipe: String? override init() { } init(email: String?, phone_number: String?, linkedin_profile: String?,twitter_profile: String?,agil_profile: String?,wat_profile: String?,skipe: String?) { self.email = email self.phone_number = phone_number self.linkedin_profile = linkedin_profile self.twitter_profile = twitter_profile self.agil_profile = agil_profile self.wat_profile = wat_profile self.skipe = skipe } required convenience init(coder aDecoder: NSCoder) { let email = aDecoder.decodeObject(forKey: "email") as? String let phone_number = aDecoder.decodeObject(forKey: "phone_number") as? String let linkedin_profile = aDecoder.decodeObject(forKey: "linkedin_profile") as? String let twitter_profile = aDecoder.decodeObject(forKey: "twitter_profile") as? String let agil_profile = aDecoder.decodeObject(forKey: "agil_profile") as? String let wat_profile = aDecoder.decodeObject(forKey: "wat_profile") as? String let skipe = aDecoder.decodeObject(forKey: "skipe") as? String self.init(email: email, phone_number: phone_number, linkedin_profile: linkedin_profile,twitter_profile:twitter_profile,agil_profile: agil_profile,wat_profile: wat_profile,skipe: skipe) } func encode(with aCoder: NSCoder) { aCoder.encode(email, forKey: "email") aCoder.encode(phone_number, forKey: "phone_number") aCoder.encode(linkedin_profile, forKey: "linkedin_profile") aCoder.encode(twitter_profile, forKey: "twitter_profile") aCoder.encode(agil_profile, forKey: "agil_profile") aCoder.encode(wat_profile, forKey: "wat_profile") aCoder.encode(skipe, forKey: "skipe") } }
apache-2.0
7fbacc5f2f3769a7ee56e80ba51f9546
38.636364
192
0.672477
3.858407
false
false
false
false
skutnii/4swivl
TestApp/TestApp/PeopleViewController+Github.swift
1
1098
// // VieController+Github.swift // TestApp // // Created by Serge Kutny on 9/17/15. // Copyright © 2015 skutnii. All rights reserved. // import UIKit extension PeopleViewController : GithubDataConsumer { func receiveUsers(newPeople: [Person]) { let start = people.count let end = start + newPeople.count people.appendContentsOf(newPeople) tableView?.reloadData() } func requestUsers(start start: Int, count: Int) { let taskId = "LoadUsers(\(start),\(count))" //No need to add a new task if one is already present, just sit and wait guard nil == taskCache[taskId] else { return } let loader = Github.getUsers(forConsumer: self, from: start, count: count) taskCache[taskId] = loader } func requestNextUsers() { let count = PeopleViewController.USER_CHUNK_SIZE let addPoint = people.count maxCells = max(maxCells, addPoint) + count requestUsers(start: addPoint, count: count) tableView?.reloadData() } }
mit
c5e9187d65b5f7b239015c53ddc97c2f
26.45
82
0.616226
4.171103
false
false
false
false
db42/SidePanel
Example/Source/AppDelegate.swift
1
3186
// // AppDelegate.swift // SidePanel // // Created by Dushyant Bansal on 25/06/16. // Copyright © 2016 Dushyant Bansal. All rights reserved. // import UIKit import SidePanel @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var sidePanelController: SidePanelController? var vc1: UINavigationController? var vc2: UINavigationController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let sb = UIStoryboard(name: "Main", bundle: nil) vc1 = UINavigationController(rootViewController: sb.instantiateViewController(withIdentifier: "ViewController")) vc2 = UINavigationController(rootViewController: sb.instantiateViewController(withIdentifier: "ViewController2")) let sc = sb.instantiateViewController(withIdentifier: "SideViewController") let svc = MySidePanelController(sideController: sc) svc.selectedViewController = vc1 self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = svc self.window?.makeKeyAndVisible() self.sidePanelController = svc return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } class MySidePanelController: SidePanelController { override func leftButton() -> UIButton { let frame = CGRect(x: 0, y: 0, width: 20, height: 20) let button = UIButton(frame: frame) button.setImage(UIImage(named: "menu"), for: UIControlState()) return button } }
mit
eb9b4047b4235c17bb2b1b306bcfa2bd
43.859155
281
0.764835
5.195759
false
false
false
false
mityung/XERUNG
IOS/Xerung/Xerung/CityViewController.swift
1
8448
// // CityViewController.swift // Xerung // // Created by mityung on 20/03/17. // Copyright © 2017 mityung. All rights reserved. // import UIKit import XLPagerTabStrip class CityViewController: UIViewController , UITableViewDelegate , UITableViewDataSource , IndicatorInfoProvider { public func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: "City") } @IBOutlet weak var tableView: UITableView! // var groupId:String! var data = [String]() var groupType = [String]() var groupCount = [String]() override func viewDidLoad() { super.viewDidLoad() // self.getOffLineData() // print(data) // self.saveData() self.findBloodGroup() //tableView.backgroundView = UIImageView(image: UIImage(named: "backScreen.png")) // tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.separatorStyle = .none self.tableView.estimatedRowHeight = 170; self.tableView.rowHeight = UITableViewAutomaticDimension; /* let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell cell.directoryMoto.text = selectedGroupAbout cell.dirtectoryType.text = selectedGroupCalled cell.directoryImage.layer.cornerRadius = cell.directoryImage.frame.width/2 cell.directoryImage.layer.masksToBounds = true cell.directoryImage.layer.borderWidth = 1 cell.directoryImage.layer.borderColor = themeColor.cgColor if selectedGroupPhoto != "" && selectedGroupPhoto != "0" { if let imageData = Data(base64Encoded: selectedGroupPhoto , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) { let DecodedImage = UIImage(data: imageData) cell.directoryImage.image = DecodedImage } }else{ cell.directoryImage.image = UIImage(named: "user.png") } tableView.tableHeaderView = cell*/ // Do any additional setup after loading the view. self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) } // set tab title func indicatorInfoForPagerTabStrip(_ pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: "City") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groupCount.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BloodCell", for: indexPath) as! BloodCell cell.bloodGroup.text = groupType[indexPath.row].uppercaseFirst cell.groupCount.text = groupCount[indexPath.row] cell.selectionStyle = .none cell.backgroundColor = UIColor.clear return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } /* func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell cell.directoryMoto.text = selectedGroupAbout cell.dirtectoryType.text = selectedGroupCalled cell.directoryImage.layer.cornerRadius = cell.directoryImage.frame.width/2 cell.directoryImage.layer.masksToBounds = true cell.directoryImage.layer.borderWidth = 1 cell.directoryImage.layer.borderColor = themeColor.cgColor if selectedGroupPhoto != "" && selectedGroupPhoto != "0" { if let imageData = Data(base64Encoded: selectedGroupPhoto , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) { let DecodedImage = UIImage(data: imageData) cell.directoryImage.image = DecodedImage } }else{ cell.directoryImage.image = UIImage(named: "user.png") } return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 88 }*/ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "MemberDetailViewController") as! MemberDetailViewController viewController.type = "city" if groupType[indexPath.row] == "Unknown" { viewController.query = "-1" }else{ viewController.query = groupType[indexPath.row] } self.navigationController?.pushViewController(viewController, animated: true) } /* func getOffLineData(){ let databasePath = NSUserDefaults.standardUserDefaults().URLForKey("DataBasePath")! let contactDB = FMDatabase(path: String(databasePath)) if contactDB.open() { let querySQL = "SELECT * FROM DirectoryMember where groupId = '\(groupId)'" let results:FMResultSet? = contactDB.executeQuery(querySQL,withArgumentsInArray: nil) while((results?.next()) == true){ self.data.append(results!.stringForColumn("GroupData")!) } contactDB.close() } else { print("Error: \(contactDB.lastErrorMessage())") } }*/ func findBloodGroup(){ let databasePath = UserDefaults.standard.url(forKey: "DataBasePath")! let contactDB = FMDatabase(path: String(describing: databasePath)) if (contactDB?.open())! { let querySQL = "SELECT count(*) as Num_row , city FROM GroupData GROUP BY city " let results:FMResultSet? = contactDB?.executeQuery(querySQL,withArgumentsIn: nil) while((results?.next()) == true){ print(results!.string(forColumn: "city")!) if results!.string(forColumn: "city")! == "-1" { groupType.append("Unknown") }else{ groupType.append(results!.string(forColumn: "city")!) } groupCount.append(results!.string(forColumn: "Num_row")!) } tableView.reloadData() contactDB?.close() } else { print("Error: \(contactDB?.lastErrorMessage())") } } /*func saveData(){ let databasePath = NSUserDefaults.standardUserDefaults().URLForKey("DataBasePath")! let contactDB = FMDatabase(path: String(databasePath)) if contactDB.open() { let querySQL = "DELETE FROM GroupData " _ = contactDB!.executeUpdate(querySQL, withArgumentsInArray: nil) for i in 0 ..< data.count { var info = data[i].componentsSeparatedByString("|") var city = "-1" if info[6] != "" && info[6] != " "{ city = info[6] } let insertSQL = "INSERT INTO GroupData (name,number,flag,address,UID,bloodGroup,city,profession,Date) VALUES ('\(info[0])', '\(info[1])','\(info[2])', '\(info[3])', '\(info[4])','\(info[5])', '\(city)', '\(info[7])', '\(info[8])')" let result = contactDB.executeUpdate(insertSQL , withArgumentsInArray: nil) if !result { print("Error: \(contactDB.lastErrorMessage())") } } } else { print("Error: \(contactDB.lastErrorMessage())") } }*/ /* // 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. } */ }
apache-2.0
19ad154793490871906c0d582ad8d645
38.288372
247
0.611696
5.223871
false
false
false
false
aolan/Cattle
CattleKit/Alamofire+CAExtension.swift
1
1582
// // Alamofire+CAExtension.swift // cattle // // Created by lawn on 15/11/10. // Copyright © 2015年 zodiac. All rights reserved. // import Alamofire public protocol ResponseObjectSerializable { init?(response: NSHTTPURLResponse, representation: AnyObject) } extension Request { public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self { let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in guard error == nil else { return .Failure(error!) } let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let result = JSONResponseSerializer.serializeResponse(request, response, data, error) switch result { case .Success(let value): if let response = response, responseObject = T(response: response, representation: value){ return .Success(responseObject) }else { let failureReason = "JSON could not be serialized into response object: \(value)" let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) return .Failure(error) } case .Failure(let error): return .Failure(error) } } return response(responseSerializer: responseSerializer, completionHandler: completionHandler) } }
mit
8023f7def0e0b5d21252d594edd35d03
35.744186
120
0.61368
5.679856
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 1.playgroundbook/Contents/Chapters/Document1.playgroundchapter/Pages/Exercise1.playgroundpage/Sources/Assessments.swift
1
2331
// // Assessments.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // let solution = "```swift\nmoveForward()\nmoveForward()\nmoveForward()\ncollectGem()\n```" var success = "### Congratulations! \nYou’ve written your first lines of [Swift](glossary://Swift) code. \n\nByte performed the commands you wrote and did exactly what you asked, in exactly the order that you specified. \n\n[**Next Page**](@next)" import PlaygroundSupport public func assessmentPoint() -> AssessmentResults { let checker = ContentsChecker(contents: PlaygroundPage.current.text) var hints = [ "Remember, you need to make Byte move forward and collect the gem, using commands in the shortcut bar.", "First tap `moveForward()` three times, and then tap `collectGem()`. If you have problems with your code, you can start over by tapping the three-dot icon at the top of the page and then tapping Reset." ] if checker.numberOfStatements == 0 { hints[0] = "You need to enter some commands. First tap the area that says \"Tap to enter code\" then use `moveForward()` and `collectGem()` to solve the puzzle." } else if checker.numberOfStatements < 3 { hints[0] = "Oops! Every `moveForward()` command moves Byte forward only one tile. To move forward three tiles, you need **three** `moveForward()` commands." } else if checker.functionCallCount(forName: "collectGem") == 0 { hints[0] = "You forgot to collect the gem. When you're on the tile with the gem, use `collectGem()`." } if world.commandQueue.containsIncorrectCollectGemCommand() { hints[0] = "For the `collectGem()` command to work, Byte needs to be on the tile with the gem." } if world.commandQueue.containsIncorrectMoveForwardCommand() { success = "### Great work! \nYou’ve written your first lines of [Swift](glossary://Swift) code. \n\nDid you notice how Byte performed all the commands you wrote, even though the `moveForward()` command almost made Byte fall off the world? \n\nEven though you had extra commands in your solution, Byte still solved the puzzle correctly. Next time, try using only the commands you need. \n\n[**Next Page**](@next)" } return updateAssessment(successMessage: success, failureHints: hints, solution: solution) }
mit
77b31cfd4aaf03c5cad31713507745ea
54.404762
421
0.702192
4.207957
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCNotificationManager.swift
2
12677
// // NCNotificationManager.swift // Neocom // // Created by Artem Shimanski on 31.08.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import Foundation import UserNotifications import EVEAPI import CoreData import Futures private protocol NotificationRequest { var identifier: String {get} var accountUUID: String? {get} } @available(iOS 10.0, *) extension UNNotificationRequest: NotificationRequest { var accountUUID: String? { return content.userInfo["accountUUID"] as? String } } extension UILocalNotification: NotificationRequest { var accountUUID: String? { return userInfo?["accountUUID"] as? String } var identifier: String { return userInfo?["identifier"] as? String ?? "" } } class NCNotificationManager: NSObject { struct SkillQueueNotificationOptions: OptionSet { var rawValue: Int static let inactive = SkillQueueNotificationOptions(rawValue: 1 << 0) static let oneHour = SkillQueueNotificationOptions(rawValue: 1 << 1) static let fourHours = SkillQueueNotificationOptions(rawValue: 1 << 2) static let oneDay = SkillQueueNotificationOptions(rawValue: 1 << 3) static let skillTrainingComplete = SkillQueueNotificationOptions(rawValue: 1 << 4) static let `default`: SkillQueueNotificationOptions = [.inactive, .oneHour, .fourHours, .oneDay, .skillTrainingComplete] } lazy var skillQueueNotificationOptions: SkillQueueNotificationOptions = { if let setting = (NCSetting.setting(key: NCSetting.Key.skillQueueNotifications)?.value as? NSNumber)?.intValue { return SkillQueueNotificationOptions(rawValue: setting) } else { return .default } }() static let sharedManager = NCNotificationManager() override private init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(managedObjectContextDidSave(_:)), name: .NSManagedObjectContextDidSave, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } private var lastScheduleDate: Date? func setNeedsUpdate() { lastScheduleDate = nil } func schedule(completionHandler: ((Bool) -> Void)? = nil) { guard let storage = NCStorage.sharedStorage else { completionHandler?(false) return } guard (lastScheduleDate ?? Date.distantPast).timeIntervalSinceNow < -600 else { completionHandler?(false) return } pendingNotificationRequests { requests in let dispatchGroup = DispatchGroup() dispatchGroup.enter() var pending = requests var queue: [(Int64, String, [ESI.Skills.SkillQueueItem], Date, String)] = [] storage.performBackgroundTask { managedObjectContext in defer {dispatchGroup.leave()} guard let accounts: [NCAccount] = managedObjectContext.fetch("Account") else { return } accounts.forEach { account in let uuid = account.uuid let i = pending.partition {$0.accountUUID == uuid} let requests = Array(pending[0..<i]) pending.removeSubrange(0..<i) let dataManager = NCDataManager(account: account) let characterID = account.characterID let characterName = account.characterName ?? "" let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(characterID)_64.png") // let lifeTime = NCExtendedLifeTime(managedObjectContext) if let value = (try? dataManager.skillQueue().get())?.value { if let uuid = uuid { queue.append((characterID, characterName, value, value.compactMap{$0.finishDate}.max() ?? Date.distantFuture, uuid)) } dispatchGroup.enter() if let image = (try? dataManager.image(characterID: characterID, dimension: 64).get())?.value { try? UIImagePNGRepresentation(image)?.write(to: url) } self.schedule(skillQueue: value, account: account, requests: requests, imageURL: url).wait() } } self.remove(requests: pending) NCDatabase.sharedDatabase?.performTaskAndWait { context in if let url = WidgetData.url { let date = Date() let invTypes = NCDBInvType.invTypes(managedObjectContext: context) let accounts = Array(queue.filter{!$0.2.isEmpty}.sorted{$0.3 < $1.3}.prefix(4)) .map { i -> WidgetData.Account in let skills = i.2.compactMap { j-> WidgetData.Account.SkillQueueItem? in guard let type = invTypes[j.skillID], let skill = NCSkill(type: type, skill: j), let startDate = j.startDate, let finishDate = j.finishDate, let skillName = type.typeName, finishDate > date else {return nil} return WidgetData.Account.SkillQueueItem(skillName: skillName, startDate: startDate, finishDate: finishDate, level: j.finishedLevel - 1, rank: skill.rank, startSP: j.levelStartSP, endSP: j.levelEndSP) } return WidgetData.Account(characterID: i.0, characterName: i.1, uuid: i.4, skillQueue: skills) } let dispatchGroup = DispatchGroup() let widgetData = WidgetData(accounts: accounts) let fileManager = FileManager.default let baseURL = url.deletingLastPathComponent() try? fileManager.contentsOfDirectory(at: baseURL, includingPropertiesForKeys: nil, options: []).forEach { if $0.pathExtension == "png" { try? fileManager.removeItem(at: $0) } } try? fileManager.removeItem(at: url) do { let data = try JSONEncoder().encode(widgetData) try data.write(to: url) let dataManager = NCDataManager() accounts.forEach { account in dispatchGroup.enter() if let image = (try? dataManager.image(characterID: account.characterID, dimension: 64).get())?.value, let data = UIImagePNGRepresentation(image) { try? data.write(to: baseURL.appendingPathComponent("\(account.characterID).png")) } } } catch { } } } }.finally(on: .main) { self.lastScheduleDate = Date() completionHandler?(true) } } } private func pendingNotificationRequests(completionHandler: @escaping ([NotificationRequest]) -> Void) { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().getPendingNotificationRequests { requests in completionHandler(requests) } } else { completionHandler(UIApplication.shared.scheduledLocalNotifications ?? []) } } private func remove(requests: [NotificationRequest]) { if #available(iOS 10.0, *) { let ids = requests.map{$0.identifier} UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ids) } else { let application = UIApplication.shared requests.compactMap {$0 as? UILocalNotification}.forEach { application.cancelLocalNotification($0) } } } private func removeAllNotifications() { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().removeAllPendingNotificationRequests() } else { // Fallback on earlier versions } } private func schedule(skillQueue: [ESI.Skills.SkillQueueItem], account: NCAccount, requests: [NotificationRequest], imageURL: URL) -> Future<Bool> { return DispatchQueue.main.async { let promise = Promise<Bool>() let options = self.skillQueueNotificationOptions guard let context = account.managedObjectContext, !options.isEmpty else { try! promise.fulfill(false) return promise.future } context.perform { guard let uuid = account.uuid else { try! promise.fulfill(false) return } let characterName = account.characterName ?? "" let date = Date() let value = skillQueue.filter {$0.finishDate != nil && $0.finishDate! > date}.sorted {$0.finishDate! < $1.finishDate!} self.remove(requests: requests) let dispatchGroup = DispatchGroup() if options.contains(.skillTrainingComplete) { NCDatabase.sharedDatabase?.performTaskAndWait { managedObjectContext -> [NotificationRequest] in let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext) return value.map { skill -> NotificationRequest in return self.request(title: characterName, subtitle: NSLocalizedString("Skill Training Complete", comment: ""), body: "\(invTypes[skill.skillID]?.typeName ?? NSLocalizedString("Unknown", comment: "")): \(skill.finishedLevel)", date: skill.finishDate!, imageURL: imageURL, identifier: "\(uuid).\(skill.skillID).\(skill.finishedLevel)", accountUUID: uuid) } }.forEach { dispatchGroup.enter() self.add(request: $0) { error in dispatchGroup.leave() } } } if let lastSkill = value.last { let a: [(SkillQueueNotificationOptions, Date)] = [(.inactive, lastSkill.finishDate!), (.oneHour, lastSkill.finishDate!.addingTimeInterval(-3600)), (.fourHours, lastSkill.finishDate!.addingTimeInterval(-3600 * 4)), (.oneDay, lastSkill.finishDate!.addingTimeInterval(-3600 * 24))] a.filter{options.contains($0.0) && $0.1 > date}.compactMap { (option, date) -> NotificationRequest? in let body: String switch option.rawValue { case SkillQueueNotificationOptions.inactive.rawValue: body = NSLocalizedString("Training Queue is inactive", comment: "") case SkillQueueNotificationOptions.oneHour.rawValue: body = NSLocalizedString("Training Queue will finish in 1 hour.", comment: "") case SkillQueueNotificationOptions.fourHours.rawValue: body = NSLocalizedString("Training Queue will finish in 4 hours.", comment: "") case SkillQueueNotificationOptions.oneDay.rawValue: body = NSLocalizedString("Training Queue will finish in 24 hours.", comment: "") default: return nil } return self.request(title: characterName, subtitle: nil, body: body, date: date, imageURL: imageURL, identifier: "\(uuid).\(option.rawValue)", accountUUID: uuid) }.forEach { dispatchGroup.enter() self.add(request: $0) { error in dispatchGroup.leave() } } } dispatchGroup.notify(queue: .main) { try! promise.fulfill(true) } } return promise.future } } private func request (title: String, subtitle: String?, body: String, date: Date, imageURL: URL, identifier: String, accountUUID: String) -> NotificationRequest { if #available(iOS 10.0, *) { let content = UNMutableNotificationContent() content.title = title content.subtitle = NSLocalizedString("Skill Training Complete", comment: "") content.body = body content.userInfo["accountUUID"] = accountUUID let attachmentURL = imageURL.deletingLastPathComponent().appendingPathComponent("\(identifier).png") try? FileManager.default.linkItem(at: imageURL, to: attachmentURL) content.attachments = [try? UNNotificationAttachment(identifier: "uuid", url: attachmentURL, options: nil)].compactMap {$0} content.sound = UNNotificationSound.default() let components = Calendar.current.dateComponents(Set([.year, .month, .day, .hour, .minute, .second, .timeZone]), from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false) let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) return request } else { let notification = UILocalNotification() notification.alertTitle = title if let subtitle = subtitle { notification.alertBody = "\(subtitle)\n\(body)" } else { notification.alertBody = body } notification.fireDate = date notification.userInfo = ["accountUUID": accountUUID] return notification } } private func add(request: NotificationRequest, completionHandler: ((Error?) -> Void)? = nil) { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().add(request as! UNNotificationRequest, withCompletionHandler: completionHandler) } else { UIApplication.shared.scheduleLocalNotification(request as! UILocalNotification) completionHandler?(nil) } } @objc private func managedObjectContextDidSave(_ note: Notification) { guard let viewContext = NCStorage.sharedStorage?.viewContext, let context = note.object as? NSManagedObjectContext else {return} guard context.persistentStoreCoordinator === viewContext.persistentStoreCoordinator else {return} if (note.userInfo?[NSDeletedObjectsKey] as? NSSet)?.contains(where: {$0 is NCAccount}) == true || (note.userInfo?[NSInsertedObjectsKey] as? NSSet)?.contains(where: {$0 is NCAccount}) == true { lastScheduleDate = nil } } }
lgpl-2.1
137849e5536791d00d1cc3a411d083a1
34.606742
209
0.68752
4.197351
false
false
false
false
pawel-sp/PSZCircularPicker
iOS-Example/SimpleCircularPickerViewController.swift
1
2588
// // SimpleCircularPickerViewController.swift // PSZCircularPickerFramework // // Created by Paweł Sporysz on 23.10.2014. // Copyright (c) 2014 Paweł Sporysz. All rights reserved. // import UIKit import PSZCircularPicker class SimpleCircularPickerViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, CircularCollectionViewFlowLayoutDelegate { // MARK: - Outlets @IBOutlet weak var circularCollectionView: SimpleCircularPickerCollectionView! @IBOutlet weak var bottomLabel: UILabel! // MARK: - Properties var data = [ (count:15, offset:30.0, color:UIColor.redColor()), (count:1, offset:0.0, color:UIColor.blackColor()) ] // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.circularCollectionView.circularCollectionViewFlowLayout.delegate = self //navigation bar change insets self.circularCollectionView.contentInset = UIEdgeInsetsMake( -self.navigationController!.navigationBar.bounds.height-UIApplication.sharedApplication().statusBarFrame.height, 0.0, 0.0, 0.0 ) } // MARK: - UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data[section].count } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return data.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell cell.backgroundColor = data[indexPath.section].color return cell } // MARK: - UICollectionViewDelegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { self.bottomLabel.text = "Section: \(indexPath.section) item: \(indexPath.item)" } // MARK : - PSZCircularCollectionFlowLayoutDelegate func circularCollectionViewFlowLayout(circularCollectionViewFlowLayout: CircularCollectionViewFlowLayout, offsetInDegreesForSection section: Int) -> Double { return data[section].offset } func circularCollectionViewFlowLayout(circularCollectionViewFlowLayout: CircularCollectionViewFlowLayout, itemSize: CGSize, forIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(50, 50) } }
mit
8b05b6543e42d203a2bd5d4da22f6297
35.942857
176
0.726605
5.671053
false
false
false
false
ofirsh/watchOS-2-Sampler
watchOS2Sampler WatchKit Extension/TapticInterfaceController.swift
14
2639
// // TapticInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/11. // Copyright © 2015年 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class TapticInterfaceController: WKInterfaceController { @IBOutlet weak var picker: WKInterfacePicker! var pickerItems: [WKPickerItem]! var currentItem: WKPickerItem! var hapticTypes = [ "Notification": WKHapticType.Notification, "DirectionUp": WKHapticType.DirectionUp, "DirectionDown": WKHapticType.DirectionDown, "Success": WKHapticType.Success, "Failure": WKHapticType.Failure, "Retry": WKHapticType.Retry, "Start": WKHapticType.Start, "Stop": WKHapticType.Stop, "Click": WKHapticType.Click, ] override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) pickerItems = [] for typeStr in hapticTypes.keys { let pickerItem = WKPickerItem() pickerItem.title = typeStr pickerItems.append(pickerItem) } picker.setItems(pickerItems) currentItem = pickerItems.first /* // Configure interface objects here. WKPickerItem *pickerItem1 = [WKPickerItem alloc]; [pickerItem1 setTitle:@"First item"]; [pickerItem1 setAccessoryImage:[WKImage imageWithImageName:@"Smile"]]; WKPickerItem *pickerItem2 = [WKPickerItem alloc]; [pickerItem2 setTitle:@"Second item"]; [pickerItem2 setAccessoryImage:[WKImage imageWithImageName:@"Smile"]]; WKPickerItem *pickerItem3 = [WKPickerItem alloc]; [pickerItem3 setTitle:@"Third item"]; [pickerItem3 setAccessoryImage:[WKImage imageWithImageName:@"Smile"]]; self.pickerItems = [[NSArray alloc] initWithObjects:pickerItem1, pickerItem2, pickerItem3, nil]; [self.picker setItems:self.pickerItems]; */ } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func pickerItemSelected(index: Int) { currentItem = pickerItems[index] } @IBAction func hapticBtnTapped() { let hapticType = hapticTypes[currentItem.title!] WKInterfaceDevice.currentDevice().playHaptic(hapticType!) } }
mit
860d22724d668a4b82fec83225c4d174
29.651163
104
0.644917
4.775362
false
false
false
false
justindarc/firefox-ios
Client/Telemetry/UnifiedTelemetry.swift
2
11122
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import Telemetry // // 'Unified Telemetry' is the name for Mozilla's telemetry system // class UnifiedTelemetry { // Boolean flag to temporarily remember if we crashed during the // last run of the app. We cannot simply use `Sentry.crashedLastLaunch` // because we want to clear this flag after we've already reported it // to avoid re-reporting the same crash multiple times. private var crashedLastLaunch: Bool private func migratePathComponentInDocumentsDirectory(_ pathComponent: String, to destinationSearchPath: FileManager.SearchPathDirectory) { guard let oldPath = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(pathComponent).path, FileManager.default.fileExists(atPath: oldPath) else { return } print("Migrating \(pathComponent) from ~/Documents to \(destinationSearchPath)") guard let newPath = try? FileManager.default.url(for: destinationSearchPath, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent(pathComponent).path else { print("Unable to get destination path \(destinationSearchPath) to move \(pathComponent)") return } do { try FileManager.default.moveItem(atPath: oldPath, toPath: newPath) print("Migrated \(pathComponent) to \(destinationSearchPath) successfully") } catch let error as NSError { print("Unable to move \(pathComponent) to \(destinationSearchPath): \(error.localizedDescription)") } } init(profile: Profile) { crashedLastLaunch = Sentry.crashedLastLaunch migratePathComponentInDocumentsDirectory("MozTelemetry-Default-core", to: .cachesDirectory) migratePathComponentInDocumentsDirectory("MozTelemetry-Default-mobile-event", to: .cachesDirectory) migratePathComponentInDocumentsDirectory("eventArray-MozTelemetry-Default-mobile-event.json", to: .cachesDirectory) NotificationCenter.default.addObserver(self, selector: #selector(uploadError), name: Telemetry.notificationReportError, object: nil) let telemetryConfig = Telemetry.default.configuration telemetryConfig.appName = "Fennec" telemetryConfig.userDefaultsSuiteName = AppInfo.sharedContainerIdentifier telemetryConfig.dataDirectory = .cachesDirectory telemetryConfig.updateChannel = AppConstants.BuildChannel.rawValue let sendUsageData = profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true telemetryConfig.isCollectionEnabled = sendUsageData telemetryConfig.isUploadEnabled = sendUsageData telemetryConfig.measureUserDefaultsSetting(forKey: "profile.blockPopups", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.saveLogins", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.showClipboardBar", withDefaultValue: false) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.settings.closePrivateTabs", withDefaultValue: false) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASPocketStoriesVisible", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASBookmarkHighlightsVisible", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASRecentHighlightsVisible", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.normalbrowsing", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.privatebrowsing", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.strength", withDefaultValue: "basic") telemetryConfig.measureUserDefaultsSetting(forKey: ThemeManagerPrefs.automaticSwitchIsOn.rawValue, withDefaultValue: false) telemetryConfig.measureUserDefaultsSetting(forKey: ThemeManagerPrefs.automaticSliderValue.rawValue, withDefaultValue: 0) telemetryConfig.measureUserDefaultsSetting(forKey: ThemeManagerPrefs.themeName.rawValue, withDefaultValue: "normal") telemetryConfig.measureUserDefaultsSetting(forKey: "profile.show-translation", withDefaultValue: true) let prefs = profile.prefs Telemetry.default.beforeSerializePing(pingType: CorePingBuilder.PingType) { (inputDict) -> [String: Any?] in var outputDict = inputDict // make a mutable copy var settings: [String: Any?] = inputDict["settings"] as? [String: Any?] ?? [:] if let newTabChoice = prefs.stringForKey(NewTabAccessors.HomePrefKey) { outputDict["defaultNewTabExperience"] = newTabChoice as AnyObject? } if let chosenEmailClient = prefs.stringForKey(PrefsKeys.KeyMailToOption) { outputDict["defaultMailClient"] = chosenEmailClient as AnyObject? } // Report this flag as a `1` or `0` integer to allow it // to be counted easily when reporting. Then, clear the // flag to avoid it getting reported multiple times. settings["crashedLastLaunch"] = self.crashedLastLaunch ? 1 : 0 self.crashedLastLaunch = false outputDict["settings"] = settings return outputDict } Telemetry.default.beforeSerializePing(pingType: MobileEventPingBuilder.PingType) { (inputDict) -> [String: Any?] in var outputDict = inputDict var settings: [String: String?] = inputDict["settings"] as? [String: String?] ?? [:] let searchEngines = SearchEngines(prefs: profile.prefs, files: profile.files) settings["defaultSearchEngine"] = searchEngines.defaultEngine.engineID ?? "custom" if let windowBounds = UIApplication.shared.keyWindow?.bounds { settings["windowWidth"] = String(describing: windowBounds.width) settings["windowHeight"] = String(describing: windowBounds.height) } outputDict["settings"] = settings // App Extension telemetry requires reading events stored in prefs, then clearing them from prefs. if let extensionEvents = profile.prefs.arrayForKey(PrefsKeys.AppExtensionTelemetryEventArray) as? [[String: String]], var pingEvents = outputDict["events"] as? [[Any?]] { profile.prefs.removeObjectForKey(PrefsKeys.AppExtensionTelemetryEventArray) extensionEvents.forEach { extensionEvent in let category = UnifiedTelemetry.EventCategory.appExtensionAction.rawValue let newEvent = TelemetryEvent(category: category, method: extensionEvent["method"] ?? "", object: extensionEvent["object"] ?? "") pingEvents.append(newEvent.toArray()) } outputDict["events"] = pingEvents } return outputDict } Telemetry.default.add(pingBuilderType: CorePingBuilder.self) Telemetry.default.add(pingBuilderType: MobileEventPingBuilder.self) } @objc func uploadError(notification: NSNotification) { guard !DeviceInfo.isSimulator(), let error = notification.userInfo?["error"] as? NSError else { return } Sentry.shared.send(message: "Upload Error", tag: SentryTag.unifiedTelemetry, severity: .info, description: error.debugDescription) } } // Enums for Event telemetry. extension UnifiedTelemetry { public enum EventCategory: String { case action = "action" case appExtensionAction = "app-extension-action" case prompt = "prompt" } public enum EventMethod: String { case add = "add" case background = "background" case cancel = "cancel" case change = "change" case delete = "delete" case deleteAll = "deleteAll" case drag = "drag" case drop = "drop" case foreground = "foreground" case open = "open" case press = "press" case scan = "scan" case share = "share" case tap = "tap" case translate = "translate" case view = "view" case applicationOpenUrl = "application-open-url" } public enum EventObject: String { case app = "app" case bookmark = "bookmark" case bookmarksPanel = "bookmarks-panel" case download = "download" case downloadLinkButton = "download-link-button" case downloadNowButton = "download-now-button" case downloadsPanel = "downloads-panel" case keyCommand = "key-command" case locationBar = "location-bar" case qrCodeText = "qr-code-text" case qrCodeURL = "qr-code-url" case readerModeCloseButton = "reader-mode-close-button" case readerModeOpenButton = "reader-mode-open-button" case readingListItem = "reading-list-item" case setting = "setting" case tab = "tab" case trackingProtectionStatistics = "tracking-protection-statistics" case trackingProtectionWhitelist = "tracking-protection-whitelist" case url = "url" case searchText = "searchText" } public enum EventValue: String { case activityStream = "activity-stream" case appMenu = "app-menu" case awesomebarResults = "awesomebar-results" case bookmarksPanel = "bookmarks-panel" case browser = "browser" case contextMenu = "context-menu" case downloadCompleteToast = "download-complete-toast" case downloadsPanel = "downloads-panel" case homePanel = "home-panel" case homePanelTabButton = "home-panel-tab-button" case markAsRead = "mark-as-read" case markAsUnread = "mark-as-unread" case pageActionMenu = "page-action-menu" case readerModeToolbar = "reader-mode-toolbar" case readingListPanel = "reading-list-panel" case shareExtension = "share-extension" case shareMenu = "share-menu" case tabTray = "tab-tray" case topTabs = "top-tabs" } public static func recordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: EventValue, extras: [String: Any?]? = nil) { Telemetry.default.recordEvent(category: category.rawValue, method: method.rawValue, object: object.rawValue, value: value.rawValue, extras: extras) } public static func recordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: String? = nil, extras: [String: Any?]? = nil) { Telemetry.default.recordEvent(category: category.rawValue, method: method.rawValue, object: object.rawValue, value: value, extras: extras) } }
mpl-2.0
ed2bad06d268b99d34a2e256393fd1a3
50.253456
237
0.693221
5.228961
false
true
false
false
cikelengfeng/HTTPIDL
Sources/Runtime/ResponseDecoder.swift
1
4482
// // ResponseBodyDecoderImpl.swift // everfilter // // Created by 徐 东 on 2016/12/31. // import Foundation public protocol Decoder { var outputStream: OutputStream? {get} func decode(_ response: HTTPResponse) throws -> ResponseContent? } private func decode(json: Any) throws -> ResponseContent? { if let number = json as? NSNumber { return .number(value: number) }else if let tmp = json as? String { return .string(value: tmp) } else if let tmp = json as? [Any] { return .array(value: try tmp.compactMap({ return try decode(json: $0) })) } else if json is [String: Any], let tmp = json as? [String: Any] { return .dictionary(value: try tmp.reduce([String: ResponseContent](), { (soFar, soGood) in var ret = soFar ret[soGood.key] = try decode(json: soGood.value) return ret })) } return nil } private func decodeRoot(json: Any) throws -> ResponseContent? { if let tmp = json as? [String: Any] { return .dictionary(value: try tmp.reduce([String: ResponseContent](), { (soFar, soGood) in var ret = soFar ret[soGood.key] = try decode(json: soGood.value) return ret })) } else if let tmp = json as? [Any] { return .array(value: try tmp.compactMap({ (element) in return try decode(json: element) })) } else { return try decode(json: json) } } public enum JSONDecoderError: HIError { case JSONSerializationError(rawError: Error) public var errorDescription: String? { get { switch self { case .JSONSerializationError(let rawError): return (rawError as NSError).localizedDescription } } } } public struct JSONDecoder: Decoder { public private(set) var outputStream: OutputStream? public var jsonReadOptions: JSONSerialization.ReadingOptions = .allowFragments public init() { self.outputStream = OutputStream(toMemory: ()) } public func decode(_ response: HTTPResponse) throws -> ResponseContent? { guard let stream = response.bodyStream, let body = stream.property(forKey: Stream.PropertyKey.dataWrittenToMemoryStreamKey) as? Data else { return nil } let json: Any do { json = try JSONSerialization.jsonObject(with: body, options: jsonReadOptions) } catch let error { throw JSONDecoderError.JSONSerializationError(rawError: error) } return try decodeRoot(json: json) } } public struct FileDecoder: Decoder { public private(set) var outputStream: OutputStream? public private(set) var filePath: String; public init(filePath: String) { self.filePath = filePath self.outputStream = OutputStream(toFileAtPath: filePath, append: false) } public func decode(_ response: HTTPResponse) throws -> ResponseContent? { let fileURL = URL(fileURLWithPath: self.filePath) let contentType = response.headers["Content-Type"] ?? "application/octet-stream" return ResponseContent.file(value: fileURL, fileName: nil, mimeType: contentType) } } public struct BinaryDecoder: Decoder { public private(set) var outputStream: OutputStream? public init() { self.outputStream = OutputStream(toMemory: ()) } public func decode(_ response: HTTPResponse) throws -> ResponseContent? { guard let stream = response.bodyStream, let body = stream.property(forKey: Stream.PropertyKey.dataWrittenToMemoryStreamKey) as? Data else { return nil } let contentType = response.headers["Content-Type"] ?? "application/octet-stream" return ResponseContent.data(value: body, fileName: nil, mimeType: contentType) } } public struct UTF8StringDecoder: Decoder { public private(set) var outputStream: OutputStream? public init() { self.outputStream = OutputStream(toMemory: ()) } public func decode(_ response: HTTPResponse) throws -> ResponseContent? { guard let stream = response.bodyStream, let body = stream.property(forKey: Stream.PropertyKey.dataWrittenToMemoryStreamKey) as? Data else { return nil } let str = String(data: body, encoding: String.Encoding.utf8) return ResponseContent.string(value: str ?? "") } }
mit
15426dbc710cacdd8f696f8796f1438d
32.924242
147
0.637561
4.532389
false
false
false
false
ello/ello-ios
Sources/Utilities/Tmp.swift
1
4893
//// /// Tmp.swift // struct Tmp { static let uniqDir = Tmp.uniqueName() static func clear() { try? FileManager.default.removeItem(atPath: NSTemporaryDirectory()) } static func fileExists(_ fileName: String) -> Bool { guard let fileURL = self.fileURL(fileName) else { return false } return FileManager.default.fileExists(atPath: fileURL.path) } static func directoryURL() -> URL? { guard let pathURL = URL(string: NSTemporaryDirectory()) else { return nil } let directoryName = pathURL.appendingPathComponent(Tmp.uniqDir).absoluteString return URL(fileURLWithPath: directoryName, isDirectory: true) } static func fileURL(_ fileName: String) -> URL? { guard let directoryURL = directoryURL() else { return nil } return directoryURL.appendingPathComponent(fileName) } static func uniqueName() -> String { return ProcessInfo.processInfo.globallyUniqueString } static func write(_ toDataable: ToData, to fileName: String) -> URL? { guard let data = toDataable.toData(), let directoryURL = self.directoryURL() else { return nil } do { try FileManager.default.createDirectory( at: directoryURL, withIntermediateDirectories: true, attributes: nil ) if let fileURL = self.fileURL(fileName) { try? data.write(to: fileURL, options: [.atomic]) return fileURL } return nil } catch { return nil } } static func read(_ fileName: String) -> Data? { guard fileExists(fileName), let fileURL = fileURL(fileName) else { return nil } return (try? Data(contentsOf: fileURL)) } static func read(_ fileName: String) -> String? { guard let data:Data = read(fileName), let string = String(data: data, encoding: .utf8) else { return nil } return string } static func read(_ fileName: String) -> UIImage? { if let data:Data = read(fileName) { return UIImage(data: data) } return nil } static func remove(_ fileName: String) -> Bool { guard let filePath = fileURL(fileName)?.path, FileManager.default.fileExists(atPath: filePath) else { return false } do { try FileManager.default.removeItem(atPath: filePath) return true } catch { return false } } } extension Tmp { static func sizeDiagnostics() -> (String, Int) { let paths = [ ElloLinkedStore.databaseFolder(), FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.path, FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first? .path, FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.path, URL(string: NSTemporaryDirectory())?.path, ].compactMap { path -> Path? in path.map { Path($0) } } var text = "" var totalSize = 0 for path in paths { guard let (desc, size) = sizeOf(path) else { continue } totalSize += size if !text.isEmpty { text += "------------------------------\n" } text += "---- \(path.abbreviate()) ----\n" text += "\(desc)\n" } text += "---- TOTAL ----\n" text += "\(totalSize.numberToHuman())\n" return (text, totalSize) } private static func sizeOf(_ path: Path, prefix: String? = nil, isLast: Bool = true) -> ( String, Int )? { guard let fileDictionary = try? FileManager.default.attributesOfItem(atPath: path.path), var size = fileDictionary[.size] as? Int else { return nil } if let children = try? path.children() { let myPrefix = (prefix.map { $0 + (isLast ? "`--/" : "+--/") }) ?? "" let childPrefix = (prefix.map { $0 + (isLast ? " " : "| ") } ?? "") var childrenDesc = "" for child in children { guard let (childDesc, childSize) = sizeOf( child, prefix: childPrefix, isLast: child == children.last ) else { continue } childrenDesc += childDesc size += childSize } return ( "\(myPrefix)\(path.lastComponent) \(size.numberToHuman())\n" + childrenDesc, size ) } else { return ("", size) } } }
mit
0e98080a5cefaa95f0b34359f9f7f6c2
30.165605
99
0.523605
4.839763
false
false
false
false
edstewbob/cs193p-winter-2015
GraphingCalculator/GraphingCalculator/CalculatorBrain.swift
2
8855
// // CalculatorBrain.swift // Calculator // // Created by jrm on 3/6/15. // Copyright (c) 2015 Riesam LLC. All rights reserved. // import Foundation class CalculatorBrain { private enum Op: Printable { case Operand(Double) case Variable(String) case Constant(String, () -> Double) case UnaryOperation(String, Double -> Double) case BinaryOperation(String, Int, (Double, Double) -> Double) var description: String { get { switch self { case .Operand(let operand): return "\(operand)" case .Variable(let variable): return variable case .Constant(let symbol, _): return symbol case .UnaryOperation(let symbol, _): return symbol case .BinaryOperation(let symbol, _, _): return symbol default: return "" } } } var precedence: Int { get { switch self { case .BinaryOperation(_, let precedence, _): return precedence default: return Int.max } } } } private var opStack = [Op]() private var knownOps = [String: Op]() var variableValues = Dictionary<String, Double>() private var error: String? init(){ func learnOp(op: Op) { knownOps[op.description] = op } learnOp(Op.BinaryOperation("×", 2, { $0 * $1 } ) ) learnOp(Op.BinaryOperation("÷", 2, { $1 / $0 } ) ) learnOp(Op.BinaryOperation("+", 1, { $0 + $1 } ) ) learnOp(Op.BinaryOperation("−", 1, { $1 - $0 } ) ) learnOp(Op.UnaryOperation("±", { $0 * -1.0 } ) ) learnOp(Op.UnaryOperation("√", { sqrt($0) } ) ) learnOp(Op.UnaryOperation("sin", { sin($0) } ) ) learnOp(Op.UnaryOperation("cos", { cos($0) } ) ) learnOp(Op.UnaryOperation("tan", { tan($0) } ) ) learnOp(Op.UnaryOperation("log", { log($0) } ) ) learnOp(Op.Constant("π", { M_PI } ) ) learnOp(Op.Constant("e", { M_E } ) ) } var program: AnyObject { // guaranteed to be a PropertyList get { return opStack.map { $0.description } } set { if let opSymbols = newValue as? Array<String> { var newOpStack = [Op]() for opSymbol in opSymbols { if let op = knownOps[opSymbol] { newOpStack.append(op) } else if let operand = NSNumberFormatter().numberFromString(opSymbol)?.doubleValue { newOpStack.append(.Operand(operand)) } else { newOpStack.append(.Variable(opSymbol)) } } opStack = newOpStack } } } private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]){ if !ops.isEmpty { var remainingOps = ops let op = remainingOps.removeLast() switch op { case .Operand(let operand): return (operand, remainingOps) case .Variable(let key): if let value = variableValues[key] { return (value, remainingOps) }else{ error = "Variable Not Found" } return (nil, remainingOps) case .Constant(_, let operation): return (operation(), remainingOps) case .UnaryOperation(_,let operation): let operandEvaluation = evaluate(remainingOps) if let operand = operandEvaluation.result { return (operation(operand), operandEvaluation.remainingOps) } case .BinaryOperation(_, _, let operation): let op1Evaluation = evaluate(remainingOps) if let operand1 = op1Evaluation.result { let op2Evaluation = evaluate(op1Evaluation.remainingOps) if let operand2 = op2Evaluation.result { return (operation(operand1, operand2), op2Evaluation.remainingOps) } } default: return (nil,[]) } } return (nil, ops) } func evaluate() -> Double? { let (result, remainder) = evaluate(opStack) //println("\(opStack) = \(result) with \(remainder) left over") //println("variables \(variableValues) ") //println("program \(program) ") return result } /* evaluate() except that if there is a problem of any kind evaluating the stack (not just unset variables or missing operands, but also divide by zero, square root of a negative number, etc.), instead of returning nil, it will return a String with what the problem is */ func evaluateAndReportErrors() -> AnyObject? { let (result, _) = evaluate(opStack) return result != nil ? result : error } func pushOperand(operand: Double) -> Double? { opStack.append(Op.Operand(operand)) return evaluate() } func pushOperand(symbol: String) -> Double? { opStack.append(Op.Variable(symbol)) return evaluate() } func performOperation(symbol: String) -> Double? { if let operation = knownOps[symbol] { opStack.append(operation) } return evaluate() } func clear(){ opStack.removeAll() variableValues = Dictionary<String, Double>() } func removeLast() -> Double? { if(opStack.count > 0){ opStack.removeLast() } return evaluate() } var description: String { get { var remainingOps = opStack var(desc, newRemainingOps, _) = describe(remainingOps) while(newRemainingOps.count > 0) { var(nextDesc, nextRemainingOps, _) = describe(newRemainingOps) desc = nextDesc + ", " + desc newRemainingOps = nextRemainingOps } return desc + " = " } } //for use as GraphView label var shortDescription: String { var remainingOps = opStack var(desc, newRemainingOps, _) = describe(remainingOps) return desc } private func describe(ops: [Op]) -> (result: String, remainingOps: [Op], precedence: Int){ //println("describing \(ops) ") if !ops.isEmpty { var remainingOps = ops let op = remainingOps.removeLast() switch op { case .Operand(let operand): return (operand.description, remainingOps, op.precedence) case .Variable(let key): return (key, remainingOps, op.precedence) case .Constant(let symbol, _): return (symbol, remainingOps, op.precedence) case .UnaryOperation(let symbol, _): let (stringForRemainder,remainingOps, _) = describe(remainingOps) return (symbol + "(" + stringForRemainder + ")", remainingOps, op.precedence) case .BinaryOperation(let symbol, let precedence, _): var (stringForRemainder1,remainingOps1, precedence1) = describe(remainingOps) var (stringForRemainder2,remainingOps2, precedence2) = describe(remainingOps1) if(precedence > precedence1) { stringForRemainder1 = "(" + stringForRemainder1 + ")" } if(precedence > precedence2) { stringForRemainder2 = "(" + stringForRemainder2 + ")" } return (stringForRemainder2 + symbol + stringForRemainder1, remainingOps2, precedence) default: return ("", [], Int.max) } } return ("?", ops, Int.max) } //return y value for x //used by GraphViewController to generate x,y coord for graph func y(x: Double) -> Double? { variableValues["M"] = x if let y = evaluate() { //println("x: \(x) y: \(y)") return y } //println("x: \(x) y: is nil") return nil } }
mit
c2c1a50f7cd5ff2b4eecc54c812536c1
34.53012
121
0.493162
4.950755
false
false
false
false
Ares42/Portfolio
HackerRankMobile/DataStructuresViewController.swift
1
1446
// // DataStructuresViewController.swift // HackerRankMobile // // Created by Luke Solomon on 9/27/17. // Copyright © 2017 Solomon Stuff. All rights reserved. // import UIKit class DataStructuresViewController: UIViewController { @IBOutlet weak var textView: UITextView! var list = LinkedList.init(array: [Int](1...50)) var palindrome = LinkedList.init(array: [1,2,3,4,4,3,2,1]) override func viewDidLoad() { super.viewDidLoad() textView.text = list.description } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func reverseButtonTapped(_ sender: Any) { list.reverse() textView.text = list.description } @IBAction func palindromeButtonTapped(_ sender: Any) { var message = "" if list.isPalindrome(palindrome) == true { message = "It's a Palindrome!" } else { message = "It's not a Palindrome." } let alertController = UIAlertController(title: "Palindrome Check Completed", message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default) { action in } alertController.addAction(OKAction) self.present(alertController, animated: true) { } } }
mit
3821b574fa0384ea467ce21d10985804
26.788462
126
0.609689
4.676375
false
false
false
false
daher-alfawares/Chart
Chart/CircleCalculator.swift
1
2571
// // CircleCalculator.swift // Circle // // Created by Daher Alfawares on 1/13/16. // Copyright © 2016 Daher Alfawares. All rights reserved. // import Foundation import UIKit class CircleCalculator { let π = Double(M_PI) var data : Array<Double> var spaceAngle : Double var startAngle : Double init(Data : Array<Double>, StartAngle : Double, SpaceAngle : Double){ data = Data spaceAngle = SpaceAngle startAngle = StartAngle } func count()->Double { var filteredCount : Double = 0 for item in data { if item > 0 { filteredCount += 1 } } return filteredCount } func space()->Double { if data.count <= 1 { return 0 } return π * spaceAngle / 180 } func totalSpace()->Double { return space() * count() } func start()->Double { return π * startAngle / 180 } func totalAngle()->Double { return 2 * π - totalSpace() } func arcs()->Array<Arc> { var arcs = Array<Arc>() let total = self.total() var angle : Double = start() for (i,element) in data.enumerated() { if element <= 0 { continue } let normal = totalAngle() * element / total let startAngle = angle let endAngle = angle + normal angle += normal angle += space() arcs.append( Arc( index : i, startAngle : startAngle, endAngle : endAngle ) ) } return arcs } func total()->Double { var total : Double = 0 for i in data { total += i } return total } // innter class, defines an arc class Arc { fileprivate var a1 : Double fileprivate var a2 : Double fileprivate var i : Int init(index:Int, startAngle:Double, endAngle:Double){ i = index a1 = startAngle a2 = endAngle } func start()->Double { return a1 } func end()->Double { return a2 } func index()->Int { return i } } }
apache-2.0
9ad9e164d08947aed4c0144b40700887
20.206612
73
0.437646
4.925144
false
false
false
false
box/box-ios-sdk
Tests/Modules/MetadataModuleSpecs.swift
1
46328
// // BoxFileModulesSpecs.swift // BoxSDK // // Created by Daniel Cech on 6/20/19. // Copyright © 2019 Box. All rights reserved. // @testable import BoxSDK import Nimble import OHHTTPStubs import OHHTTPStubs.NSURLRequest_HTTPBodyTesting import Quick class MetadataModuleSpecs: QuickSpec { var sut: BoxClient! override func spec() { beforeEach { self.sut = BoxSDK.getClient(token: "asdads") } afterEach { OHHTTPStubs.removeAllStubs() } describe("MetadataModule") { // MARK: - Metadata Templates describe("getTemplateByKey(scope:templateId:completion)") { it("should make API call to get metadata template by name and produce file model when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/metadata_templates/enterprise/productInfo/schema") && isMethodGET()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetMetadataTemplate.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.getTemplateByKey(scope: "enterprise", templateKey: "productInfo") { result in switch result { case let .success(template): expect(template).toNot(beNil()) expect(template.id).to(equal("f7a9891f")) expect(template.templateKey).to(equal("productInfo")) expect(template.scope).to(equal("enterprise_12345")) expect(template.displayName).to(equal("Product Info")) expect(template.hidden).to(equal(false)) guard let firstField = template.fields?[0] else { fail() done() return } expect(firstField).toNot(beNil()) expect(firstField.id).to(equal("f7a9892f")) expect(firstField.type).to(equal("float")) expect(firstField.key).to(equal("skuNumber")) expect(firstField.displayName).to(equal("SKU Number")) expect(firstField.hidden).to(equal(false)) case let .failure(error): fail("Expected call to getTemplateByKey to succeed, but instead got \(error)") } done() } } } } describe("getTemplateById(id:completion:)") { it("should make API call to get metadata template by id and produce file model when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/metadata_templates/f7a9891f") && isMethodGET()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetMetadataTemplate.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.getTemplateById(id: "f7a9891f") { result in switch result { case let .success(template): expect(template).toNot(beNil()) expect(template.id).to(equal("f7a9891f")) expect(template.templateKey).to(equal("productInfo")) expect(template.scope).to(equal("enterprise_12345")) expect(template.displayName).to(equal("Product Info")) expect(template.hidden).to(equal(false)) guard let firstField = template.fields?[0] else { fail() done() return } expect(firstField).toNot(beNil()) expect(firstField.id).to(equal("f7a9892f")) expect(firstField.type).to(equal("float")) expect(firstField.key).to(equal("skuNumber")) expect(firstField.displayName).to(equal("SKU Number")) expect(firstField.hidden).to(equal(false)) case let .failure(error): fail("Expected call to getTemplateId to succeed, but instead got \(error)") } done() } } } } describe("createTemplate()") { it("should make API call to create metadata template and produce file model when API call succeeds") { stub( condition: isHost("api.box.com") && isPath("/2.0/metadata_templates/schema") && isMethodPOST() && hasJsonBody([ "scope": "enterprise_490685", "templateKey": "customer", "displayName": "Customer", "hidden": false, "fields": [ ["type": "string", "key": "customerTeam", "displayName": "Customer team", "hidden": false], ["type": "multiSelect", "hidden": false, "options": [ ["key": "FY11"], ["key": "FY12"], ["key": "FY13"], ["key": "FY14"], ["key": "FY15"] ], "key": "fy", "displayName": "FY"] ] ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("CreateMetadataTemplate.json", type(of: self))!, statusCode: 201, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let options: [[String: String]] = [ ["key": "FY11"], ["key": "FY12"], ["key": "FY13"], ["key": "FY14"], ["key": "FY15"] ] self.sut.metadata.createTemplate( scope: "enterprise_490685", templateKey: "customer", displayName: "Customer", hidden: false, fields: [ MetadataField(id: nil, type: "string", key: "customerTeam", displayName: "Customer team", options: nil, hidden: false), MetadataField(id: nil, type: "multiSelect", key: "fy", displayName: "FY", options: options, hidden: false) ] ) { result in switch result { case let .success(template): expect(template).toNot(beNil()) expect(template.templateKey).to(equal("customer")) expect(template.scope).to(equal("enterprise_490685")) expect(template.displayName).to(equal("Customer")) guard let firstField = template.fields?[0] else { fail() done() return } expect(firstField).toNot(beNil()) expect(firstField.type).to(equal("string")) expect(firstField.key).to(equal("customerTeam")) expect(firstField.displayName).to(equal("Customer team")) expect(firstField.hidden).to(equal(false)) guard let secondField = template.fields?[1] else { fail() done() return } expect(secondField).toNot(beNil()) expect(secondField.type).to(equal("multiSelect")) expect(secondField.key).to(equal("fy")) expect(secondField.displayName).to(equal("FY")) expect(secondField.hidden).to(equal(false)) guard let firstOption = secondField.options?[0] else { fail() done() return } expect(firstOption).toNot(beNil()) expect(firstOption["key"]).to(equal("FY11")) case let .failure(error): fail("Expected call to createTemplate to succeed, but instead got \(error)") } done() } } } it("should make API call to create metadata template with copyInstanceOnItemCopy and produce file model when API call succeeds") { stub( condition: isHost("api.box.com") && isPath("/2.0/metadata_templates/schema") && isMethodPOST() && hasJsonBody([ "scope": "enterprise_490685", "templateKey": "customer", "displayName": "Customer", "hidden": false, "copyInstanceOnItemCopy": true, "fields": [ ["type": "string", "key": "customerTeam", "displayName": "Customer team", "hidden": false] ] ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("CreateMetadataTemplate2.json", type(of: self))!, statusCode: 201, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.createTemplate( scope: "enterprise_490685", templateKey: "customer", displayName: "Customer", hidden: false, copyInstanceOnItemCopy: true, fields: [ MetadataField(id: nil, type: "string", key: "customerTeam", displayName: "Customer team", options: nil, hidden: false) ] ) { result in switch result { case let .success(template): expect(template).toNot(beNil()) expect(template.templateKey).to(equal("customer")) expect(template.scope).to(equal("enterprise_490685")) expect(template.displayName).to(equal("Customer")) expect(template.copyInstanceOnItemCopy).to(equal(true)) guard let firstField = template.fields?[0] else { fail() done() return } expect(firstField).toNot(beNil()) expect(firstField.type).to(equal("string")) expect(firstField.key).to(equal("customerTeam")) expect(firstField.displayName).to(equal("Customer team")) expect(firstField.hidden).to(equal(false)) case let .failure(error): fail("Expected call to createTemplate to succeed, but instead got \(error)") } done() } } } } describe("updateTemplate()") { it("should make API call to update metadata template and produce file model when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/metadata_templates/enterprise_490685/customer/schema") && isMethodPUT()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("UpdateMetadataTemplate.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.updateTemplate( scope: "enterprise_490685", templateKey: "customer", operation: .editTemplate(data: ["displayName": "Client"]) ) { result in switch result { case let .success(template): expect(template).toNot(beNil()) expect(template.templateKey).to(equal("customer")) expect(template.scope).to(equal("enterprise_490685")) expect(template.displayName).to(equal("Client")) guard let firstField = template.fields?[0] else { fail() done() return } expect(firstField).toNot(beNil()) expect(firstField.type).to(equal("string")) expect(firstField.key).to(equal("customerTeam")) expect(firstField.displayName).to(equal("Customer team")) expect(firstField.hidden).to(equal(false)) guard let secondField = template.fields?[1] else { fail() done() return } expect(secondField).toNot(beNil()) expect(secondField.type).to(equal("multiSelect")) expect(secondField.key).to(equal("fy")) expect(secondField.displayName).to(equal("FY")) expect(secondField.hidden).to(equal(false)) guard let firstOption = secondField.options?[0] else { fail() done() return } expect(firstOption).toNot(beNil()) expect(firstOption["key"]).to(equal("FY11")) case let .failure(error): fail("Expected call to updateTemplate to succeed, but instead got \(error)") } done() } } } } describe("deleteTemplate()") { it("should make API call to create metadata template and produce file model when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/metadata_templates/enterprise/vendorContract/schema") && isMethodDELETE()) { _ in OHHTTPStubsResponse( data: Data(), statusCode: 204, headers: [:] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.deleteTemplate( scope: "enterprise", templateKey: "vendorContract" ) { result in switch result { case .success: break case let .failure(error): fail("Expected call to updateTemplate to succeed, but instead got \(error)") } done() } } } } describe("listEnterpriseTemplates()") { it("should make API call to get enterprise metadata templates and produce file model when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/metadata_templates/enterprise") && isMethodGET()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetEnterpriseTemplates.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let iterator = self.sut.metadata.listEnterpriseTemplates(scope: "enterprise") iterator.next { result in switch result { case let .success(page): let firstTemplate = page.entries[0] expect(firstTemplate).to(beAKindOf(MetadataTemplate.self)) expect(firstTemplate.templateKey).to(equal("documentFlow")) expect(firstTemplate.scope).to(equal("enterprise_12345")) expect(firstTemplate.displayName).to(equal("Document Flow")) expect(firstTemplate.hidden).to(equal(false)) case let .failure(error): fail("Expected call to listEnterpriseTemplates to succeed, but instead got \(error)") } done() } } } } // MARK: - File Metadata describe("list(forFileId)") { it("should make API call to get all metadata objects for particular file when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/files/5010739061/metadata") && isMethodGET()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetAllMetadataOnFile.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.list(forFileId: "5010739061") { result in switch result { case let .success(metadataObjects): guard let firstMetadataObject = metadataObjects.first else { fail("Metadata object array is empty") done() return } expect(firstMetadataObject).to(beAKindOf(MetadataObject.self)) expect(firstMetadataObject.template).to(equal("documentFlow")) expect(firstMetadataObject.scope).to(equal("enterprise_12345")) expect(firstMetadataObject.type).to(equal("documentFlow-452b4c9d-c3ad-4ac7-b1ad-9d5192f2fc5f")) expect(firstMetadataObject.parent).to(equal("file_5010739061")) expect(firstMetadataObject.id).to(equal("50ba0dba-0f89-4395-b867-3e057c1f6ed9")) expect(firstMetadataObject.version).to(equal(4)) expect(firstMetadataObject.typeVersion).to(equal(2)) guard let customKeys = firstMetadataObject.keys as? [String: String] else { fail("Unable to access custom keys") done() return } expect(customKeys["currentDocumentStage"]).to(equal("Init")) expect(customKeys["needsApprovalFrom"]).to(equal("Smith")) case let .failure(error): fail("Expected call to list to succeed, but instead got \(error)") } done() } } } } describe("get(forFileWithId:)") { it("should make API call to get metadata objects for particular file when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/files/5010739061/metadata/enterprise/marketingCollateral") && isMethodGET()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetMetadataOnFile.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.get(forFileWithId: "5010739061", scope: "enterprise", templateKey: "marketingCollateral") { result in switch result { case let .success(metadataObject): expect(metadataObject).to(beAKindOf(MetadataObject.self)) expect(metadataObject.template).to(equal("marketingCollateral")) expect(metadataObject.scope).to(equal("enterprise_12345")) expect(metadataObject.type).to(equal("marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe")) expect(metadataObject.parent).to(equal("file_5010739061")) expect(metadataObject.id).to(equal("2094c584-68e1-475c-a581-534a4609594e")) expect(metadataObject.version).to(equal(0)) expect(metadataObject.typeVersion).to(equal(0)) guard let customKeys = metadataObject.keys as? [String: String] else { fail("Unable to access custom keys") done() return } expect(customKeys["audience1"]).to(equal("internal")) expect(customKeys["documentType"]).to(equal("Q1 plans")) expect(customKeys["competitiveDocument"]).to(equal("no")) expect(customKeys["status"]).to(equal("active")) expect(customKeys["author"]).to(equal("Jones")) expect(customKeys["currentState"]).to(equal("proposal")) case let .failure(error): fail("Expected call to get to succeed, but instead got \(error)") } done() } } } } describe("create(forFileWithId:)") { it("should make API call to create metadata objects for particular file when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/files/5010739061/metadata/enterprise/marketingCollateral") && isMethodPOST()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("CreateMetadataOnFile.json", type(of: self))!, statusCode: 201, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let keys: [String: Any] = [ "audience1": "internal", "documentType": "Q1 plans", "competitiveDocument": "no", "status": "active", "author": "Jones", "currentState": "proposal" ] self.sut.metadata.create( forFileWithId: "5010739061", scope: "enterprise", templateKey: "marketingCollateral", keys: keys ) { result in switch result { case let .success(metadataObject): expect(metadataObject).to(beAKindOf(MetadataObject.self)) expect(metadataObject.template).to(equal("marketingCollateral")) expect(metadataObject.scope).to(equal("enterprise_12345")) expect(metadataObject.type).to(equal("marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe")) expect(metadataObject.parent).to(equal("file_5010739061")) expect(metadataObject.id).to(equal("2094c584-68e1-475c-a581-534a4609594e")) expect(metadataObject.version).to(equal(0)) expect(metadataObject.typeVersion).to(equal(0)) guard let customKeys = metadataObject.keys as? [String: String] else { fail("Unable to access custom keys") done() return } expect(customKeys["audience1"]).to(equal("internal")) expect(customKeys["documentType"]).to(equal("Q1 plans")) expect(customKeys["competitiveDocument"]).to(equal("no")) expect(customKeys["status"]).to(equal("active")) expect(customKeys["author"]).to(equal("Jones")) expect(customKeys["currentState"]).to(equal("proposal")) case let .failure(error): fail("Expected call to create to succeed, but instead got \(error)") } done() } } } } describe("update(forFileWithId:)") { it("should make API call to get metadata objects for particular file when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/files/5010739061/metadata/enterprise/marketingCollateral") && isMethodPUT()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("UpdateMetadataOnFile.json", type(of: self))!, statusCode: 201, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let operations: [FileMetadataOperation] = [ .test(path: "/competitiveDocument", value: "no"), .remove(path: "/competitiveDocument"), .test(path: "/competitiveDocument", value: "no"), .replace(path: "/status", value: "inactive"), .test(path: "/author", value: "Jones"), .copy(from: "/competitiveDocument", path: "/editor"), .test(path: "/currentState", value: "proposal"), .move(from: "/currentState", path: "/previousState"), .add(path: "/currentState", value: "reviewed") ] self.sut.metadata.update( forFileWithId: "5010739061", scope: "enterprise", templateKey: "marketingCollateral", operations: operations ) { result in switch result { case let .success(metadataObject): expect(metadataObject).to(beAKindOf(MetadataObject.self)) expect(metadataObject.template).to(equal("marketingCollateral")) expect(metadataObject.scope).to(equal("enterprise_12345")) expect(metadataObject.type).to(equal("marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe")) expect(metadataObject.parent).to(equal("file_5010739061")) expect(metadataObject.id).to(equal("2094c584-68e1-475c-a581-534a4609594e")) expect(metadataObject.version).to(equal(1)) expect(metadataObject.typeVersion).to(equal(0)) guard let customKeys = metadataObject.keys as? [String: String] else { fail("Unable to access custom keys") done() return } expect(customKeys["audience1"]).to(equal("internal")) expect(customKeys["documentType"]).to(equal("Q1 plans")) expect(customKeys["status"]).to(equal("inactive")) expect(customKeys["author"]).to(equal("Jones")) expect(customKeys["editor"]).to(equal("Jones")) expect(customKeys["currentState"]).to(equal("reviewed")) case let .failure(error): fail("Expected call to update to succeed, but instead got \(error)") } done() } } } } describe("delete(forFileWithId:)") { it("should make API call to delete metadata objects for particular file when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/files/5010739061/metadata/enterprise/marketingCollateral") && isMethodDELETE()) { _ in OHHTTPStubsResponse( data: Data(), statusCode: 204, headers: [:] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.delete( forFileWithId: "5010739061", scope: "enterprise", templateKey: "marketingCollateral" ) { result in switch result { case .success: break case let .failure(error): fail("Expected call to delete to succeed, but instead got \(error)") } done() } } } } // MARK: - Folder Metadata describe("list(forFolderId)") { it("should make API call to get all metadata objects for particular folder when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/folders/998951261/metadata") && isMethodGET()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetAllMetadataOnFolder.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.list(forFolderId: "998951261") { result in switch result { case let .success(metadataObjects): guard let firstMetadataObject = metadataObjects.first else { fail("Metadata object array is empty") done() return } expect(firstMetadataObject).to(beAKindOf(MetadataObject.self)) expect(firstMetadataObject.template).to(equal("documentFlow")) expect(firstMetadataObject.scope).to(equal("enterprise_12345")) expect(firstMetadataObject.type).to(equal("documentFlow-452b4c9d-c3ad-4ac7-b1ad-9d5192f2fc5f")) expect(firstMetadataObject.parent).to(equal("folder_998951261")) expect(firstMetadataObject.id).to(equal("e57f90ff-0044-48c2-807d-06b908765baf")) expect(firstMetadataObject.version).to(equal(1)) expect(firstMetadataObject.typeVersion).to(equal(2)) expect(firstMetadataObject.keys["currentDocumentStage"] as? String).to(equal("prioritization")) expect(firstMetadataObject.keys["needsApprovalFrom"] as? String).to(equal("planning team")) case let .failure(error): fail("Expected call to list to succeed, but instead got \(error)") } done() } } } } describe("get(forFolderWithId:)") { it("should make API call to get metadata objects for particular folder when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/folders/998951261/metadata/enterprise/documentFlow") && isMethodGET()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetMetadataOnFolder.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.get(forFolderWithId: "998951261", scope: "enterprise", templateKey: "documentFlow") { result in switch result { case let .success(metadataObject): expect(metadataObject).to(beAKindOf(MetadataObject.self)) expect(metadataObject.template).to(equal("documentFlow")) expect(metadataObject.scope).to(equal("enterprise_12345")) expect(metadataObject.type).to(equal("documentFlow-452b4c9d-c3ad-4ac7-b1ad-9d5192f2fc5f")) expect(metadataObject.parent).to(equal("folder_998951261")) expect(metadataObject.id).to(equal("e57f90ff-0044-48c2-807d-06b908765baf")) expect(metadataObject.version).to(equal(0)) expect(metadataObject.typeVersion).to(equal(2)) guard let customKeys = metadataObject.keys as? [String: String] else { fail("Unable to access custom keys") done() return } expect(customKeys["currentDocumentStage"]).to(equal("initial vetting")) expect(customKeys["needsApprovalFrom"]).to(equal("vetting team")) expect(customKeys["nextDocumentStage"]).to(equal("prioritization")) case let .failure(error): fail("Expected call to getto succeed, but instead got \(error)") } done() } } } } describe("create(forFolderWithId:)") { it("should make API call to create metadata objects for particular folder when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/folders/998951261/metadata/enterprise/documentFlow") && isMethodPOST()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("CreateMetadataOnFolder.json", type(of: self))!, statusCode: 201, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let keys: [String: Any] = [ "currentDocumentStage": "initial vetting", "needsApprovalFrom": "vetting team", "nextDocumentStage": "prioritization" ] self.sut.metadata.create( forFolderWithId: "998951261", scope: "enterprise", templateKey: "documentFlow", keys: keys ) { result in switch result { case let .success(metadataObject): expect(metadataObject).to(beAKindOf(MetadataObject.self)) expect(metadataObject.template).to(equal("documentFlow")) expect(metadataObject.scope).to(equal("enterprise_12345")) expect(metadataObject.type).to(equal("documentFlow-452b4c9d-c3ad-4ac7-b1ad-9d5192f2fc5f")) expect(metadataObject.parent).to(equal("folder_998951261")) expect(metadataObject.id).to(equal("e57f90ff-0044-48c2-807d-06b908765baf")) expect(metadataObject.version).to(equal(0)) expect(metadataObject.typeVersion).to(equal(0)) guard let customKeys = metadataObject.keys as? [String: String] else { fail("Unable to access custom keys") done() return } expect(customKeys["currentDocumentStage"]).to(equal("initial vetting")) expect(customKeys["needsApprovalFrom"]).to(equal("vetting team")) expect(customKeys["nextDocumentStage"]).to(equal("prioritization")) case let .failure(error): fail("Expected call to create to succeed, but instead got \(error)") } done() } } } } describe("update(forFolderWithId:)") { it("should make API call to get metadata objects for particular folder when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/folders/998951261/metadata/enterprise/documentFlow") && isMethodPUT()) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("UpdateMetadataOnFolder.json", type(of: self))!, statusCode: 201, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let operations: [FolderMetadataOperation] = [ .test(path: "/currentDocumentStage", value: "initial vetting"), .replace(path: "/currentDocumentStage", value: "prioritization"), .test(path: "/needsApprovalFrom", value: "vetting team"), .replace(path: "/needsApprovalFrom", value: "planning team"), .add(path: "/maximumDaysAllowedInCurrentStage", value: "5"), .test(path: "/nextDocumentStage", value: "prioritization"), .remove(path: "/nextDocumentStage") ] self.sut.metadata.update( forFolderWithId: "998951261", scope: "enterprise", templateKey: "documentFlow", operations: operations ) { result in switch result { case let .success(metadataObject): expect(metadataObject).to(beAKindOf(MetadataObject.self)) expect(metadataObject.template).to(equal("documentFlow")) expect(metadataObject.scope).to(equal("enterprise_12345")) expect(metadataObject.type).to(equal("documentFlow-452b4c9d-c3ad-4ac7-b1ad-9d5192f2fc5f")) expect(metadataObject.parent).to(equal("folder_998951261")) expect(metadataObject.id).to(equal("e57f90ff-0044-48c2-807d-06b908765baf")) expect(metadataObject.version).to(equal(1)) expect(metadataObject.typeVersion).to(equal(2)) expect(metadataObject.keys["currentDocumentStage"] as? String).to(equal("prioritization")) expect(metadataObject.keys["needsApprovalFrom"] as? String).to(equal("planning team")) expect(metadataObject.keys["maximumDaysAllowedInCurrentStage"] as? Int).to(equal(5)) case let .failure(error): fail("Expected call to update to succeed, but instead got \(error)") } done() } } } } describe("delete(forFolderWithId:)") { it("should make API call to delete metadata objects for particular folder when API call succeeds") { stub(condition: isHost("api.box.com") && isPath("/2.0/folders/998951261/metadata/enterprise/documentFlow") && isMethodDELETE()) { _ in OHHTTPStubsResponse( data: Data(), statusCode: 204, headers: [:] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.metadata.delete( forFolderWithId: "998951261", scope: "enterprise", templateKey: "documentFlow" ) { result in switch result { case .success: break case let .failure(error): fail("Expected call to delete to succeed, but instead got \(error)") } done() } } } } } } }
apache-2.0
4d284ffcd9994e215021b2d1600fdfaf
53.630896
160
0.427073
5.971513
false
false
false
false
rhx/gir2swift
Sources/libgir2swift/utilities/generation.swift
1
22749
// // generation.swift // gir2swift // // Created by Rene Hexel on 20/5/2021. // Copyright © 2016, 2017, 2018, 2019, 2020, 2021, 2022 Rene Hexel. All rights reserved. // import Foundation import Dispatch private extension String { func nonEmptyComponents<S: StringProtocol>(separatedBy separator: S) -> [String] { components(separatedBy: separator).filter { !$0.isEmpty } } } /// load a GIR file, then invoke the processing closure private func load_gir(_ file: String, quiet q: Bool = false, process: (GIR) -> Void = { _ in }) { do { try Data(contentsOf: URL(fileURLWithPath: file), options: .alwaysMapped).withUnsafeBytes { bytes in guard let gir = GIR(buffer: bytes.bindMemory(to: CChar.self), quiet: q) else { print("Error: Cannot parse GIR file '\(file)'", to: &Streams.stdErr) return } if gir.prefix.isEmpty { print("Warning: no namespace in GIR file '\(file)'", to: &Streams.stdErr) } process(gir); } } catch { print("Error: Failed to open '\(file)' \(error)", to: &Streams.stdErr) } } /// process blacklist and verbatim constants information /// - Parameters: /// - gir: The in-memory object representing the `.gir` file /// - targetDirectoryURL: URL representing the target source directory containing the module configuration files /// - node: File name node of the `.gir` file without extension private func processSpecialCases(_ gir: GIR, for targetDirectoryURL: URL, node: String) { let prURL = targetDirectoryURL.appendingPathComponent(node + ".preamble") gir.preamble = (try? String(contentsOf: prURL)) ?? "" let exURL = targetDirectoryURL.appendingPathComponent(node + ".exclude") let blURL = targetDirectoryURL.appendingPathComponent(node + ".blacklist") GIR.blacklist = ((try? String(contentsOf: exURL)) ?? (try? String(contentsOf: blURL))).flatMap { Set($0.nonEmptyComponents(separatedBy: "\n")) } ?? [] let vbURL = targetDirectoryURL.appendingPathComponent(node + ".verbatim") GIR.verbatimConstants = (try? String(contentsOf: vbURL)).flatMap { Set($0.nonEmptyComponents(separatedBy: "\n")) } ?? [] let ovURL = targetDirectoryURL.appendingPathComponent(node + ".override") GIR.overrides = (try? String(contentsOf: ovURL)).flatMap { Set($0.nonEmptyComponents(separatedBy: "\n")) } ?? [] } extension Gir2Swift { /// pre-load a GIR without processing, but adding to known types / records func preload_gir(file: String) { load_gir(file, quiet: true) } /// process a GIR file /// - Parameters: /// - file: The `.gir` file to proces /// - targetDirectoryURL: URL representing the target source directory containing the module configuration files /// - boilerPlate: A string containing the boilerplate to use for the generated module file, `<node>.module` file if empty /// - outputDirectory: The directory to output generated files in, `stdout` if `nil` /// - singleFilePerClass: Flag indicating whether a separate output file should be created per class /// - generateAll: Flag indicating whether private members should be emitted /// - useAlphaNames: Flag indicating whether a fixed number of output files should be generated /// - postProcess: Array of additional file names to include in post-processing func process_gir(file: String, for targetDirectoryURL: URL, boilerPlate: String, to outputDirectory: String? = nil, split singleFilePerClass: Bool = false, generateAll: Bool = false, useAlphaNames: Bool = false, postProcess additionalFilesToPostProcess: [String]) { let node = file.components(separatedBy: "/").last?.stringByRemoving(suffix: ".gir") ?? file let modulePrefix: String if boilerPlate.isEmpty { let bpURL = targetDirectoryURL.appendingPathComponent(node + ".module") modulePrefix = (try? String(contentsOf: bpURL)) ?? boilerPlate } else { modulePrefix = boilerPlate } let pkgConfigArg = pkgConfigName ?? node.lowercased() let inURL = targetDirectoryURL.appendingPathComponent(node + ".include") let wlURL = targetDirectoryURL.appendingPathComponent(node + ".whitelist") if let inclusionList = ((try? String(contentsOf: inURL)) ?? (try? String(contentsOf: wlURL))).flatMap({ Set($0.nonEmptyComponents(separatedBy: "\n")) }) { for name in inclusionList { GIR.knownDataTypes.removeValue(forKey: name) GIR.knownRecords.removeValue(forKey: name) GIR.KnownFunctions.removeValue(forKey: name) } } let escURL = targetDirectoryURL.appendingPathComponent(node + ".callbackSuffixes") GIR.callbackSuffixes = (try? String(contentsOf: escURL))?.nonEmptyComponents(separatedBy: "\n") ?? [ "Notify", "Func", "Marshaller", "Callback" ] let nsURL = targetDirectoryURL.appendingPathComponent(node + ".namespaceReplacements") if let ns = (try? String(contentsOf: nsURL)).flatMap({Set($0.nonEmptyComponents(separatedBy: "\n"))}) { for line in ns { let keyValues: [Substring] let tabbedKeyValues: [Substring] = line.split(separator: "\t") if tabbedKeyValues.count >= 2 { keyValues = tabbedKeyValues } else { keyValues = line.split(separator: " ") guard keyValues.count >= 2 else { continue } } let key = keyValues[0] let value = keyValues[1] GIR.namespaceReplacements[key] = value } } let fileManager = FileManager.default var outputFiles = Set(additionalFilesToPostProcess) var outputString = "" load_gir(file) { gir in processSpecialCases(gir, for: targetDirectoryURL, node: node) let blacklist = GIR.blacklist let boilerplate = gir.boilerPlate let preamble = gir.preamble let modulePrefix = modulePrefix + boilerplate let queues = DispatchGroup() let background = DispatchQueue.global() let atChar = Character("@").utf8.first! let alphaQueues = useAlphaNames ? (0...26).map { i in DispatchQueue(label: "com.github.rhx.gir2swift.alphaqueue.\(Character(UnicodeScalar(atChar + UInt8(i))))") } : [] let outq = DispatchQueue(label: "com.github.rhx.gir2swift.outputqueue") if outputDirectory == nil { outputString += modulePrefix + preamble } func write(_ string: String, to fileName: String, preamble: String = preamble, append doAppend: Bool = false) { do { if doAppend && fileManager.fileExists(atPath: fileName) { let oldContent = try String(contentsOfFile: fileName, encoding: .utf8) let newContent = oldContent + string try newContent.write(toFile: fileName, atomically: true, encoding: .utf8) } else { let newContent = preamble + string try newContent.write(toFile: fileName, atomically: true, encoding: .utf8) } outq.async(group: queues) { outputFiles.insert(fileName) } } catch { outq.async(group: queues) { print("\(error)", to: &Streams.stdErr) } } } func writebg(queue: DispatchQueue = background, _ string: String, to fileName: String, append doAppend: Bool = false) { queue.async(group: queues) { write(string, to: fileName, append: doAppend) } } func write<T: GIR.Record>(_ types: [T], using ptrconvert: (String) -> (GIR.Record) -> String) { if let dir = outputDirectory { var output = "" var first: Character? = nil var firstName = "" var name = "" var alphaq = background for type in types { let convert = ptrconvert(type.ptrName) let code = convert(type) output += code + "\n\n" name = type.className guard let firstChar = name.first else { continue } let f: String if useAlphaNames { name = firstChar.isASCII && firstChar.isLetter ? type.className.upperInitial : "@" first = firstChar firstName = name let i = Int((name.utf8.first ?? atChar) - atChar) alphaq = alphaQueues[i] f = "\(dir)/\(node)-\(firstName).swift" } else { guard singleFilePerClass || ( first != nil && first != firstChar ) else { if first == nil { first = firstChar firstName = name + "-" } continue } f = "\(dir)/\(node)-\(firstName)\(name).swift" } writebg(queue: alphaq, output, to: f, append: alphaNames) output = "" first = nil } if first != nil { let f: String if useAlphaNames { let i = Int((name.utf8.first ?? atChar) - atChar) alphaq = alphaQueues[i] f = "\(dir)/\(node)-\(firstName).swift" } else { f = "\(dir)/\(node)-\(firstName)\(name).swift" } writebg(queue: alphaq, output, to: f, append: alphaNames) } } else { let code = types.map { type in let convert = ptrconvert(type.ptrName) return convert(type) }.joined(separator: "\n\n") outq.async(group: queues) { outputString += code } } } if let dir = outputDirectory { writebg(modulePrefix, to: "\(dir)/\(node).swift") DispatchQueue.concurrentPerform(iterations: 27) { i in let ascii = atChar + UInt8(i) let f = "\(dir)/\(node)-\(Character(UnicodeScalar(ascii))).swift" try? fileManager.removeItem(atPath: f) if alphaNames { try? preamble.write(toFile: f, atomically: true, encoding: .utf8) outq.async(group: queues) { outputFiles.insert(f) } } } } background.async(group: queues) { let aliases = gir.aliases.filter{!blacklist.contains($0.name)}.map(swiftCode).joined(separator: "\n\n") if let dir = outputDirectory { let f = "\(dir)/\(node)-aliases.swift" write(aliases, to: f) } else { outq.async(group: queues) { outputString += aliases } } } background.async(group: queues) { let callbacks = gir.callbacks.filter{!blacklist.contains($0.name)}.map(swiftCallbackAliasCode).joined(separator: "\n\n") if let dir = outputDirectory { let f = "\(dir)/\(node)-callbacks.swift" write(callbacks, to: f) } else { outq.async(group: queues) { outputString += callbacks } } } background.async(group: queues) { let constants = gir.constants.filter{!blacklist.contains($0.name)}.map(swiftCode).joined(separator: "\n\n") if let dir = outputDirectory { let f = "\(dir)/\(node)-constants.swift" write(constants, to: f) } else { outq.async(group: queues) { outputString += constants } } } background.async(group: queues) { let enumerations = gir.enumerations.filter{!blacklist.contains($0.name)}.map(swiftCode).joined(separator: "\n\n") if let dir = outputDirectory { let f = "\(dir)/\(node)-enumerations.swift" write(enumerations, to: f) } else { outq.async(group: queues) { outputString += enumerations } } } background.async(group: queues) { let bitfields = gir.bitfields.filter{!blacklist.contains($0.name)}.map(swiftCode).joined(separator: "\n\n") if let dir = outputDirectory { let f = "\(dir)/\(node)-bitfields.swift" write(bitfields, to: f) } else { outq.async(group: queues) { outputString += bitfields } } } background.async(group: queues) { let convert = swiftUnionsConversion(gir.functions) let unions = gir.unions.filter {!blacklist.contains($0.name)}.map(convert).joined(separator: "\n\n") if let dir = outputDirectory { let f = "\(dir)/\(node)-unions.swift" write(unions, to: f) } else { outq.async(group: queues) { outputString += unions } } } background.async(group: queues) { let convert = swiftCode(gir.functions) let types = gir.interfaces.filter {!blacklist.contains($0.name)} write(types, using: convert) } background.async(group: queues) { let convert = swiftCode(gir.functions) let classes = generateAll ? [:] : Dictionary(gir.classes.map { ($0.name, $0) }) { lhs, _ in lhs} let records = gir.records.filter { r in !blacklist.contains(r.name) && ( generateAll || !r.name.hasSuffix("Private") || r.name.stringByRemoving(suffix: "Private").flatMap { classes[$0] }.flatMap { $0.fields.allSatisfy { $0.isPrivate || $0.typeRef.type.name != r.name }} != true ) } write(records, using: convert) } background.async(group: queues) { let convert = swiftCode(gir.functions) let types = gir.classes.filter{!blacklist.contains($0.name)} write(types, using: convert) } background.async(group: queues) { let functions = gir.functions.filter{!blacklist.contains($0.name)}.map(swiftCode).joined(separator: "\n\n") if let dir = outputDirectory { let f = "\(dir)/\(node)-functions.swift" write(functions, to: f) } else { outq.async(group: queues) { outputString += functions } } } if !(namespace.isEmpty && extensionNamespace.isEmpty) { let namespaces = namespace + extensionNamespace let extensions = Set(extensionNamespace) background.async(group: queues) { let privatePrefix = "_" + gir.prefix + "_" let prefixedAliasSwiftCode = typeAliasSwiftCode(prefixedWith: privatePrefix) let privateRecords = gir.records.filter{!blacklist.contains($0.name)}.map(prefixedAliasSwiftCode).joined(separator: "\n") let privateAliases = gir.aliases.filter{!blacklist.contains($0.name)}.map(prefixedAliasSwiftCode).joined(separator: "\n") let privateEnumerations = gir.enumerations.filter{!blacklist.contains($0.name)}.map(prefixedAliasSwiftCode).joined(separator: "\n") let privateBitfields = gir.bitfields.filter{!blacklist.contains($0.name)}.map(prefixedAliasSwiftCode).joined(separator: "\n") let privateUnions = gir.unions.filter {!blacklist.contains($0.name)}.map(prefixedAliasSwiftCode).joined(separator: "\n") let code = [privateRecords, privateAliases, privateEnumerations, privateBitfields, privateUnions].joined(separator: "\n\n") + "\n" let outputFile = outputDirectory.map { "\($0)/\(node)-namespaces.swift" } if let f = outputFile { write(code, to: f, preamble: preamble) } else { outq.async(group: queues) { outputString += code } } let indent = " " let constSwiftCode = constantSwiftCode(indentedBy: indent, scopePrefix: "static") let datatypeSwiftCode = namespacedAliasSwiftCode(prefixedWith: privatePrefix, indentation: indent) let constants = gir.constants.filter{!blacklist.contains($0.name)}.map(constSwiftCode).joined(separator: "\n") let aliases = gir.aliases.filter{!blacklist.contains($0.name)}.map(datatypeSwiftCode).joined(separator: "\n") let enumerations = gir.enumerations.filter{!blacklist.contains($0.name)}.map(datatypeSwiftCode).joined(separator: "\n") let bitfields = gir.bitfields.filter{!blacklist.contains($0.name)}.map(datatypeSwiftCode).joined(separator: "\n") let unions = gir.unions.filter {!blacklist.contains($0.name)}.map(datatypeSwiftCode).joined(separator: "\n") let classes = generateAll ? [:] : Dictionary(gir.classes.map { ($0.name, $0) }) { lhs, _ in lhs} let records = gir.records.filter { r in !blacklist.contains(r.name) && (generateAll || !r.name.hasSuffix("Private") || r.name.stringByRemoving(suffix: "Private").flatMap { classes[$0] }.flatMap { $0.fields.allSatisfy { $0.isPrivate || $0.typeRef.type.name != r.name } } != true ) }.map(datatypeSwiftCode).joined(separator: "\n\n") namespaces.forEach { namespace in let namespaceDeclaration: String if extensions.contains(namespace) { namespaceDeclaration = "extension " + namespace + " {\n" } else if let record = GIR.knownRecords[namespace] { namespaceDeclaration = "extension " + record.className + " {\n" } else { namespaceDeclaration = "public enum " + namespace + " {\n" } let code = namespaceDeclaration + [constants, records, aliases, enumerations, bitfields, unions].joined(separator: "\n\n") + "\n}\n\n" if let f = outputFile { write(code, to: f, append: true) } else { outq.async(group: queues) { outputString += code } } } } } queues.wait() libgir2swift.postProcess(node, for: targetDirectoryURL, pkgConfigName: pkgConfigArg, outputString: outputString, outputDirectory: outputDirectory, outputFiles: outputFiles) if verbose { let pf = outputString.isEmpty ? "** " : "// " let nl = outputString.isEmpty ? "\n" : "\n// " print("\(pf)Verbatim: \(GIR.verbatimConstants.count)\(nl)\(GIR.verbatimConstants.joined(separator: nl))\n", to: &Streams.stdErr) print("\(pf)Blacklisted: \(blacklist.count)\(nl)\(blacklist.joined(separator: "\n" + nl))\n", to: &Streams.stdErr) } } } /// create opaque pointer declarations func process_gir_to_opaque_decls(file: String, in targetDirectoryURL: URL, generateAll: Bool = false) { let node = file.components(separatedBy: "/").last?.stringByRemoving(suffix: ".gir") ?? file let inURL = targetDirectoryURL.appendingPathComponent(node + ".include") let wlURL = targetDirectoryURL.appendingPathComponent(node + ".whitelist") if let inclusionList = ((try? String(contentsOf: inURL)) ?? (try? String(contentsOf: wlURL))).flatMap({ Set($0.nonEmptyComponents(separatedBy: "\n")) }) { for name in inclusionList { GIR.knownDataTypes.removeValue(forKey: name) GIR.knownRecords.removeValue(forKey: name) GIR.KnownFunctions.removeValue(forKey: name) } } let nsURL = targetDirectoryURL.appendingPathComponent(node + ".namespaceReplacements") if let ns = (try? String(contentsOf: nsURL)).flatMap({Set($0.nonEmptyComponents(separatedBy: "\n"))}) { for line in ns { let keyValues: [Substring] let tabbedKeyValues: [Substring] = line.split(separator: "\t") if tabbedKeyValues.count >= 2 { keyValues = tabbedKeyValues } else { keyValues = line.split(separator: " ") guard keyValues.count >= 2 else { continue } } let key = keyValues[0] let value = keyValues[1] GIR.namespaceReplacements[key] = value } } load_gir(file) { gir in processSpecialCases(gir, for: targetDirectoryURL, node: node) let blacklist = GIR.blacklist let classes = generateAll ? [:] : Dictionary(gir.classes.map { ($0.name, $0) }) { lhs, _ in lhs} let records = gir.records.filter { r in !blacklist.contains(r.name) && ( generateAll || !r.name.hasSuffix("Private") || r.name.stringByRemoving(suffix: "Private").flatMap { classes[$0] }.flatMap { $0.fields.allSatisfy { $0.isPrivate || $0.typeRef.type.name != r.name }} != true ) } for recordCName in records.compactMap(\.correspondingCType) { print("struct " + recordCName + " {};") } } } }
bsd-2-clause
c939ef9e1c1eba790ab07cadaa911a89
56.012531
269
0.540883
4.73325
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Home/YYCache+HiPDA.swift
1
4376
// // YYCache+HiPDA.swift // HiPDA // // Created by leizh007 on 2017/5/5. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import YYCache import Argo import HandyJSON // MARK: - Associated Object private var kTidsKey: Void? private var kLRUKey: Void? private var kLockKey: Void? extension YYCache { /// 帖子id的数组,0到N-1按时间从近到远 var tids: [Int] { get { lock?.lock() defer { lock?.unlock() } return objc_getAssociatedObject(self, &kTidsKey) as? [Int] ?? [] } set { lock?.lock() defer { lock?.unlock() } objc_setAssociatedObject(self, &kTidsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// tids是否使用LRU策略 var useLRUStrategy: Bool { get { return objc_getAssociatedObject(self, &kLRUKey) as? Bool ?? false } set { objc_setAssociatedObject(self, &kLRUKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var lock: NSRecursiveLock? { get { return objc_getAssociatedObject(self, &kLockKey) as? NSRecursiveLock } set { objc_setAssociatedObject(self, &kLockKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// 是否包含帖子 /// /// - Parameter thread: 帖子 /// - Returns: 包含返回true,否则返回false func containsThread(_ thread: HiPDA.Thread) -> Bool { return containsObject(forKey: "\(thread.id)") } /// 根据id查找帖子 /// /// - Parameter id: 帖子id /// - Returns: 找到帖子返回,否则返回nil func thread(for id: Int) -> HiPDA.Thread? { guard let threadString = object(forKey: "\(id)") as? String, let threadData = threadString.data(using: .utf8), let attributes = try? JSONSerialization.jsonObject(with: threadData, options: []), let thread = try? HiPDA.Thread.decode(JSON(attributes)).dematerialize() else { return nil } return thread } /// 添加帖子 /// /// - Parameter thread: 帖子 func addThread(_ thread: HiPDA.Thread) { if let index = tids.index(of: thread.id) { if useLRUStrategy { tids.insert(tids.remove(at: index), at: 0) } } else { tids.insert(thread.id, at: 0) } while tids.count > Int(memoryCache.countLimit) { if let tid = tids.last { removeObject(forKey: "\(tid)") } tids.removeLast() } let threadString = thread.encode() setObject(threadString as NSString, forKey: "\(thread.id)") } /// 移除帖子 /// /// - Parameter thread: 帖子 func removeThread(_ thread: HiPDA.Thread) { tids = tids.filter { $0 != thread.id } removeObject(forKey: "\(thread.id)") } /// 清空缓存 func clear() { tids = [] removeAllObjects() } /// 获取帖子帖子列表 /// /// - Parameters: /// - fid: 论坛版块id /// - typeid: 论坛版块子id /// - Returns: 论坛版块帖子列表 func threads(forFid fid: Int, typeid: Int) -> [HiPDA.Thread]? { let key = "fid=\(fid)&typeid=\(typeid)" guard let threadsString = object(forKey: key) as? String, let threadsData = threadsString.data(using: .utf8), let data = try? JSONSerialization.jsonObject(with: threadsData, options: []), let arr = data as? NSArray else { return nil } return arr.flatMap { return try? HiPDA.Thread.decode(JSON($0)).dematerialize() } } /// 添加论坛帖子帖子列表 /// /// - Parameters: /// - threads: 帖子列表 /// - fid: 论坛版块id /// - typeid: 论坛版块帖子列表 func setThreads(threads: [HiPDA.Thread], forFid fid: Int, typeid: Int) { let key = "fid=\(fid)&typeid=\(typeid)" let threadsString = JSONSerializer.serializeToJSON(object: threads) ?? "" setObject(threadsString as NSString, forKey: key) } }
mit
b9d05cbc4432f5b9c34811ccf527a0c5
26.885135
99
0.53574
3.889727
false
false
false
false
domenicosolazzo/practice-swift
Views/SplitViews/Presidents/Presidents/MasterViewController.swift
1
2992
// // MasterViewController.swift // Presidents // // Created by Domenico on 25.04.15. // Copyright (c) 2015 Domenico Solazzo. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var presidents = [[String:String]]() override func awakeFromNib() { super.awakeFromNib() if UIDevice.current.userInterfaceIdiom == .pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Loading the presidents let path = Bundle.main.path(forResource: "PresidentList", ofType: "plist")! let presidentInfo = NSDictionary(contentsOfFile: path)! presidents = presidentInfo["presidents"]! as! [NSDictionary] as! [[String: String]] if let split = self.splitViewController { let controllers = split.viewControllers let leftNavController = controllers.first as! UINavigationController self.detailViewController = leftNavController.topViewController as? DetailViewController } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = presidents[(indexPath as NSIndexPath).row] let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController if let oldController = detailViewController { controller.languageString = oldController.languageString } controller.detailItem = object as AnyObject? controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true detailViewController = controller } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return presidents.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let president = presidents[(indexPath as NSIndexPath).row] cell.textLabel!.text = president["name"] return cell } }
mit
279a2a517fcf0b27ae374de258870ee6
33.790698
122
0.658422
5.602996
false
false
false
false
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/Connect View Controllers/CustomRaceViewController/CustomRaceNotificationsController.swift
2
3986
// // CustomRaceNotificationsController.swift // WikiRaces // // Created by Andrew Finke on 5/3/20. // Copyright © 2020 Andrew Finke. All rights reserved. // import UIKit import WKRKit final class CustomRaceNotificationsController: CustomRaceController { // MARK: - Types - private class Cell: UITableViewCell { // MARK: - Properties - let toggle = UISwitch() static let reuseIdentifier = "reuseIdentifier" // MARK: - Initalization - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(toggle) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle - override func layoutSubviews() { super.layoutSubviews() toggle.onTintColor = .wkrTextColor(for: traitCollection) toggle.center = CGPoint( x: contentView.frame.width - contentView.layoutMargins.right - toggle.frame.width / 2, y: contentView.frame.height / 2) } } // MARK: - Properties - var notifications: WKRGameSettings.Notifications { didSet { didUpdate?(notifications) } } var didUpdate: ((WKRGameSettings.Notifications) -> Void)? // MARK: - Initalization - init(notifications: WKRGameSettings.Notifications) { self.notifications = notifications super.init(style: .grouped) title = "Player Messages".uppercased() tableView.allowsSelection = false tableView.register(Cell.self, forCellReuseIdentifier: Cell.reuseIdentifier) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UITableViewDataSource - override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else { fatalError() } cell.toggle.tag = indexPath.row cell.toggle.addTarget(self, action: #selector(switchChanged(updatedSwitch:)), for: .valueChanged) switch indexPath.row { case 0: cell.textLabel?.text = "Player needed help" cell.toggle.isOn = notifications.neededHelp case 1: cell.textLabel?.text = "Player is close" cell.toggle.isOn = notifications.linkOnPage case 2: cell.textLabel?.text = "Player missed the link" cell.toggle.isOn = notifications.missedLink case 3: cell.textLabel?.text = "Player is on USA" cell.toggle.isOn = notifications.isOnUSA case 4: cell.textLabel?.text = "Player is on same page" cell.toggle.isOn = notifications.isOnSamePage default: fatalError() } return cell } // MARK: - Helpers - @objc func switchChanged(updatedSwitch: UISwitch) { notifications = WKRGameSettings.Notifications( neededHelp: updatedSwitch.tag == 0 ? updatedSwitch.isOn : notifications.neededHelp, linkOnPage: updatedSwitch.tag == 1 ? updatedSwitch.isOn : notifications.linkOnPage, missedTheLink: updatedSwitch.tag == 2 ? updatedSwitch.isOn : notifications.missedLink, isOnUSA: updatedSwitch.tag == 3 ? updatedSwitch.isOn : notifications.isOnUSA, isOnSamePage: updatedSwitch.tag == 4 ? updatedSwitch.isOn : notifications.isOnSamePage) } }
mit
58201b5fada082a573dd05fe8fff944a
31.663934
109
0.624592
4.907635
false
false
false
false
calkinssean/TIY-Assignments
Day 23/SpotifyAPI 2/SpotifyAPI/DataStore.swift
1
1428
// // DataStore.swift // SpotifyAPI // // Created by Sean Calkins on 3/2/16. // Copyright © 2016 Dape App Productions LLC. All rights reserved. // import Foundation class DataStore: NSObject { static let sharedInstance = DataStore() override private init() {} var artistsArray = [Artist]() func saveArtists() -> Bool { let filePath = self.documentsDirectory().URLByAppendingPathComponent("artists.archive") return NSKeyedArchiver.archiveRootObject(artistsArray, toFile: filePath.path!) } func loadArtists() -> Bool { let filePath = self.documentsDirectory().URLByAppendingPathComponent("artists.archive") if let archivedArtists = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath.path!) as? [Artist] { self.artistsArray = archivedArtists print("artists have been loaded") return true } else { print("I had a problem loading the artists") } return false } func documentsDirectory() -> NSURL { let documentsDirectories = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let documentDirectory = documentsDirectories.first! return documentDirectory } func debugDump() { for a in artistsArray { print(a.name) print(a.albums.count) } } }
cc0-1.0
6097dd9053f2acda4327474baf09003a
29.382979
130
0.644709
5.189091
false
false
false
false
Q42/ElementDiff
Examples/Example-SPM/ElementDiff-Example/ViewController.swift
2
2673
// // ViewController.swift // ElementDiff-Example // // Created by Tom on 2016-12-06. // Copyright © 2016 Q42. All rights reserved. // import UIKit import GameKit import ElementDiff class ViewController: UITableViewController { var items: [(String, UIColor)] = [] { didSet { do { let diff = try oldValue.diff(items, identifierSelector: { $0.0 }) tableView.beginUpdates() tableView.updateSection(0, diff: diff) tableView.endUpdates() } catch { print("[ElementDiff] \(error.localizedDescription)") tableView.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.tableView.contentInset.top = 20 self.items = allItems Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in self.items = newItems() } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = items[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.textColor = .white cell.textLabel?.text = item.0 cell.backgroundColor = item.1 return cell } } // Produce new data var allItems: [(String, UIColor)] = [ ("One", #colorLiteral(red: 0.8274509804, green: 0.2784313725, blue: 0.2784313725, alpha: 1)), ("Two", #colorLiteral(red: 0.8156862745, green: 0.5215686275, blue: 0.2784313725, alpha: 1)), ("Three", #colorLiteral(red: 0.1647058824, green: 0.4941176471, blue: 0.4941176471, alpha: 1)), ("Four", #colorLiteral(red: 0.2274509804, green: 0.662745098, blue: 0.2235294118, alpha: 1)), ("Five", #colorLiteral(red: 0.6039215686, green: 0.1960784314, blue: 0.4039215686, alpha: 1)), ("Six", #colorLiteral(red: 0.7333333333, green: 0.7176470588, blue: 0.2392156863, alpha: 1)), ("Seven", #colorLiteral(red: 0.3568627451, green: 0.1803921569, blue: 0.4941176471, alpha: 1)), ("Eight", #colorLiteral(red: 0.5098039216, green: 0.6823529412, blue: 0.2156862745, alpha: 1)) ] func newItems() -> [(String, UIColor)] { var items = allItems if arc4random_uniform(3) == 1 { items.remove(at: Int(arc4random_uniform(UInt32(items.count)))) } if arc4random_uniform(3) == 1 { let from = Int(arc4random_uniform(UInt32(items.count))) let item = items.remove(at: from) let to = Int(arc4random_uniform(UInt32(items.count))) items.insert(item, at: to) } return items }
mit
af2e5b4336704159eb75b0e9e1215595
29.022472
107
0.671781
3.520422
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Post/Prepublishing Nudge/Blog+Title.swift
1
260
import Foundation extension Blog { /// The title of the blog var title: String? { let blogName = settings?.name let title = blogName != nil && blogName?.isEmpty == false ? blogName : displayURL as String? return title } }
gpl-2.0
7807160adf588a0656835691667dd155
22.636364
100
0.611538
4.642857
false
false
false
false
coinbase/coinbase-ios-sdk
Example/Source/ViewControllers/Currencies/CurrenciesViewController.swift
1
4475
// // CurrenciesViewController.swift // iOS Example // // Copyright © 2018 Coinbase All rights reserved. // import UIKit import CoinbaseSDK class CurrenciesViewController: UIViewController { private static let kSpotPricesSegueIdentifier = "spotPrices" private static let kCurrencyCellID = "currencyCell" @IBOutlet weak var tableView: UITableView! // MARK: - Private Properties private let coinbase = Coinbase.default private let searchController = UISearchController(searchResultsController: nil) private var currencies: [CurrencyInfo] = [] private lazy var indexedDataSource: IndexedDataSource<CurrencyInfo> = IndexedDataSource(cellIdentifier: CurrenciesViewController.kCurrencyCellID, groupingBy: { String($0.id.first ?? "#").uppercased() }, configuration: { (cell, currency) in guard let cell = cell as? CurrencyTableViewCell else { return } cell.setup(with: currency) }) // MARK: - Lifecycle Methods override func viewDidLoad() { setupTableView() setupSearch() let activityIndicator = view.addCenteredActivityIndicator() coinbase.currenciesResource.get { [weak self] result in switch result { case .success(let currencies): self?.update(with: currencies) case .failure(let error): self?.present(error: error) } activityIndicator.stopAnimating() activityIndicator.removeFromSuperview() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case CurrenciesViewController.kSpotPricesSegueIdentifier: let spotPricesViewController = segue.destination as! SpotPricesViewController let indexPath = tableView.indexPath(for: sender as! UITableViewCell)! spotPricesViewController.selectedCurrency = indexedDataSource.item(at: indexPath)!.id default: super.prepare(for: segue, sender: sender) } } // MARK: - Private Methods private func setupTableView() { tableView.dataSource = self.indexedDataSource tableView.delegate = self tableView.separatorColor = Colors.lightGray tableView.tintColor = Colors.lightBlue tableView.tableFooterView = UIView() } private func setupSearch() { searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search Currency" navigationItem.searchController = searchController definesPresentationContext = true searchController.searchBar.barStyle = .black } private func update(with currencies: [CurrencyInfo]) { self.currencies = currencies updateTableView() } private func updateTableView() { indexedDataSource.items = filterCurrencies(for: searchController.searchBar.text) tableView.reloadData() } private func filterCurrencies(for text: String?) -> [CurrencyInfo] { guard let searchText = text?.lowercased(), !searchText.isEmpty else { return currencies } return currencies.filter { currency in [currency.id, currency.name] .map { $0.lowercased() } .contains(where: { name in name.contains(searchText) }) } } } // MARK: - UISearchResultsUpdating extension extension CurrenciesViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { updateTableView() } } // MARK: - UITableViewDelegate extension extension CurrenciesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as? UITableViewHeaderFooterView header?.textLabel?.font = UIFont(name: Fonts.demiBold, size: 20) header?.textLabel?.textColor = Colors.darkGray header?.backgroundView?.backgroundColor = Colors.lightGray } }
apache-2.0
5dbb7ffb797fd3a68e451c42bcd8a32a
33.682171
107
0.654895
5.627673
false
false
false
false
wayfindrltd/wayfindr-demo-ios
Wayfindr Demo/Classes/Constants/WAYStrings.swift
1
11554
// // WAYStrings.swift // Wayfindr Demo // // Created by Wayfindr on 16/11/2015. // Copyright (c) 2016 Wayfindr (http://www.wayfindr.net) // // 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 /** * Localized strings used within the app. */ struct WAYStrings { // MARK: - General struct CommonStrings { static let Back = NSLocalizedString("Back", comment: "") static let Battery = NSLocalizedString("Battery", comment: "") static let Beacon = NSLocalizedString("Beacon", comment: "") static let Cancel = NSLocalizedString("Cancel", comment: "") static let Change = NSLocalizedString("Change", comment: "") static let DateWord = NSLocalizedString("Date", comment: "") static let Developer = NSLocalizedString("Developer", comment: "") static let Done = NSLocalizedString("Done", comment: "") static let Error = NSLocalizedString("Error", comment: "") static let Maintainer = NSLocalizedString("Maintainer", comment: "") static let Major = NSLocalizedString("Major", comment: "") static let Minor = NSLocalizedString("Minor", comment: "") static let PrivateWord = NSLocalizedString("Private", comment: "") static let PublicWord = NSLocalizedString("Public", comment: "") static let Save = NSLocalizedString("Save", comment: "") static let YesWord = NSLocalizedString("Yes", comment: "") static let Unknown = NSLocalizedString("Unknown", comment: "") static let BatteryLevels = NSLocalizedString("Battery Levels", comment: "") static let DataExport = NSLocalizedString("Data Export", comment: "") static let DeveloperOptions = NSLocalizedString("Developer Options", comment: "") static let SelectVenue = NSLocalizedString("Select Venue", comment: "") } struct ErrorTitles { static let DisconnectedGraph = NSLocalizedString("Disconnected Graph", comment: "") static let GraphLoading = NSLocalizedString("Error Loading Graph", comment: "") static let NoDirections = NSLocalizedString("Missing Instructions", comment: "") static let NoInternet = NSLocalizedString("Internet", comment: "") static let VenueLoading = NSLocalizedString("Error Loading Venue", comment: "") } struct ErrorMessages { static let AudioEngine = NSLocalizedString("There was a problem creating the audio engine. Please restart the app.", comment: "") static let DisconnectedGraph = NSLocalizedString("Warning! You have loaded a disconnected GRAPHML file. This means that we may not be able to route you from any beacon to any other beacon.", comment: "") static let FailedParsing = NSLocalizedString("Failed parsing data.", comment: "") static let GraphLoading = NSLocalizedString("There was an error loading the venue GRAPHML data.", comment: "") static let NoDirections = NSLocalizedString("Oops! We appear to be missing some instructions!", comment: "") static let NoInternet = NSLocalizedString("Please check your Internet connection and restart the app. Wayfindr needs a working Internet connection during first launch.", comment: "") static let VenueLoading = NSLocalizedString("There was an error loading the venue JSON data.", comment: "") static let UnableBeacons = NSLocalizedString("Unable to fetch beacons.", comment: "") static let UnableFindFiles = NSLocalizedString("Unable to find data files.", comment: "") static let UnableMonitor = NSLocalizedString("This device cannot monitor beacons in its current configuration. Please check to make sure you have Bluetooth turned on.", comment: "") static let UnknownError = NSLocalizedString("Unknown Error", comment: "") static let UnknownVenue = NSLocalizedString("Unknown Venue", comment: "") } struct ModeSelection { static let User = NSLocalizedString("User", comment: "") } // MARK: - Developer struct DeveloperActionSelection { static let GraphValidation = NSLocalizedString("Graph Validation", comment: "") static let KeyRoutePaths = NSLocalizedString("Key Route Paths", comment: "") static let MissingKeyRoutes = NSLocalizedString("Missing Key Routes", comment: "") } // MARK: - Maintainer struct BatteryLevel { static let Updated = NSLocalizedString("Updated", comment: "") } struct BeaconsInRange { static let Accuracy = NSLocalizedString("Accuracy", comment: "") static let AdvertisingRate = NSLocalizedString("Advertising Rate", comment: "") static let BeaconsInRange = NSLocalizedString("Beacons in Range", comment: "") static let NoBeacons = NSLocalizedString("No Beacons in Range", comment: "") static let NoSpecificBeacon = NSLocalizedString("Beacon %@ not in range.", comment: "") static let RSSI = NSLocalizedString("RSSI", comment: "") static let TBD = NSLocalizedString("To Be Determined", comment: "") static let TxPower = NSLocalizedString("Tx Power", comment: "") static let UUID = NSLocalizedString("UUID", comment: "") } struct BeaconsInRangeMode { static let AnyBeacon = NSLocalizedString("Any Beacon", comment: "") static let Instructions = NSLocalizedString("Please choose whether you would like to search for a specific beacon or any nearby beacons.", comment: "") static let ModeWord = NSLocalizedString("Mode", comment: "") static let SelectMode = NSLocalizedString("Select Mode", comment: "") static let SpecificBeacon = NSLocalizedString("Specific Beacon", comment: "") } struct BeaconsInRangeSearch { static let BeaconSearch = NSLocalizedString("Beacon Search", comment: "") static let SearchPlaceholder = NSLocalizedString("Search beacons", comment: "") } struct DeveloperOptions { static let ShowForceNextButton = NSLocalizedString("Show Force Next Beacon Button", comment: "") static let ShowRepeatButton = NSLocalizedString("Show Repeat Button with Voiceover", comment: "") static let StopwatchEnabled = NSLocalizedString("Show Stopwatch", comment: "") static let AudioFlashEnabled = NSLocalizedString("Audio Flash Enabled", comment: "") static let StrictRouting = NSLocalizedString("Strict Routing", comment: "") } struct KeyRoutePaths { static let KeyPaths = NSLocalizedString("Key Paths", comment: "") } struct KeyRoutePathsDetail { static let Instructions = NSLocalizedString("Instructions", comment: "") static let Paths = NSLocalizedString("Paths", comment: "") static let RouteDetails = NSLocalizedString("Route Details", comment: "") } struct MaintainerActionSelection { static let CheckBeacons = NSLocalizedString("Check Beacons in Range", comment: "") } struct MissingKeyRoutes { static let MissingRoutes = NSLocalizedString("Missing Routes", comment: "") static let Congratulations = NSLocalizedString("Congratulations! You have no missing key routes.", comment: "") } // MARK: - User struct ActiveRoute { static let ActiveRoute = NSLocalizedString("Active Route", comment: "") static let Calculating = NSLocalizedString("Calculating Route", comment: "") static let Repeat = NSLocalizedString("Repeat", comment: "") static let UnableToRoute = NSLocalizedString("Unable to Find Route", comment: "") static let FirstInstructionPrefix = NSLocalizedString("For your destination", comment: "") static let FirstInstructionPrefixFormat = NSLocalizedString("%@:\n", comment: "") } struct DirectionsPreview { static let BeginRoute = NSLocalizedString("Begin Route", comment: "") static let SkipWord = NSLocalizedString("Skip", comment: "") static let Title = NSLocalizedString("Preview", comment: "") } struct RouteCalculation { static let CalculatingRoute = NSLocalizedString("Calculating Route...", comment: "") static let InstructionsQuestion = NSLocalizedString("Do you want to preview all instructions before starting your journey?", comment: "") static let Routing = NSLocalizedString("Routing", comment: "") static let SkipPreview = NSLocalizedString("Skip Preview", comment: "") static let TroubleRouting = NSLocalizedString("We are having trouble finding your current location. Please begin walking while we continue to locate you within the venue.", comment: "") static let Yes = NSLocalizedString("Yes", comment: "") } struct UserActionSelection { static let SelectDestination = NSLocalizedString("Select a destination point below", comment: "") static let TrainPlatforms = NSLocalizedString("Destinations", comment: "") static let StationExits = NSLocalizedString("Exits", comment: "") static let StationFacilities = NSLocalizedString("Facilities", comment: "") } struct DestinationSearch { static let TrainPlatformSearch = NSLocalizedString("Destination Search", comment: "") static let SearchPlatformPlaceholder = NSLocalizedString("Search platforms", comment: "") } struct ExitSearch { static let ExitSearch = NSLocalizedString("Exit Search", comment: "") static let SearchPlaceholder = NSLocalizedString("Search exits", comment: "") } struct StationFacilitySearch { static let StationFacilitySearch = NSLocalizedString("Facility Search", comment: "") static let SearchPlaceholder = NSLocalizedString("Search facilities", comment: "") } struct WarningView { static let Dismiss = NSLocalizedString("Dismiss", comment: "") } }
mit
b2f1ee539c879b3ff2e0108e5fead9ee
54.019048
214
0.653713
5.51767
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/CougarCash/model/CougarCashClient.swift
1
7372
// // CougarCashClient.swift // byuSuite // // Created by Erik Brady on 9/14/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let BASE_URL = "https://api.byu.edu/domains/cougar-cash/v1.1" private let TX_PAGE_SIZE = "20" private let DEFAULT_PAYMENT_ERROR_MESSAGE = "There was an error while submitting your payment, however, the payment may have processed properly. Please check back later before adding more funds to your account." class CougarCashClient: ByuClient2 { static func getBalance(callback: @escaping (CougarCashBalance?, ByuError?) -> Void) { let request = createRequest(pathParams: ["balance"]) makeRequest(request) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any] { callback(CougarCashBalance(dict: data), nil) } else { callback(nil, response.error) } } } static func getTransactions(pageNum: Int, callback: @escaping ([CougarCashTransaction]?, Bool, ByuError?) -> Void) { let request = createRequest(pathParams: ["transactions"], queryParams: ["page_num": "\(pageNum)", "page_size": TX_PAGE_SIZE]) makeRequest(request) { (response) in if response.succeeded, let responseDict = response.getDataJson() as? [String: Any], let transactionData = responseDict["transactions"] as? [[String: Any]] { do { //Default to true so that we are not loading more pages if the last_page value does not come back properly callback(try transactionData.map { try CougarCashTransaction(dict: $0) }, responseDict["last_page"] as? Bool ?? true, nil) } catch { callback(nil, true, InvalidModelError.byuError) } } else { callback(nil, true, response.error) } } } static func getCardStatus(callback: @escaping (Bool, ByuError?) -> Void) { let request = createRequest(pathParams: ["card"]) makeRequest(request) { (response) in if response.succeeded, let responseData = response.getDataJson() as? [String: Any], let lostValue = responseData["card_lost"] as? Bool { callback(lostValue, nil) } else { callback(false, response.error) } } } static func reportCardLost(lost: Bool, callback: @escaping (ByuError?) -> Void) { var pathParams = ["card"] if !lost { pathParams.append("found") } let request = createRequest(method: .PUT, pathParams: pathParams) request.acceptType = nil makeRequest(request) { (response) in if response.succeeded { callback(nil) } else { callback(response.error) } } } static func getPaymentAccounts(callback: @escaping ([CougarCashPaymentAccount]?, [CougarCashPaymentAccount]?, ByuError?) -> Void) { let request = createRequest(pathParams: ["payment-types"]) makeRequest(request) { (response) in if response.succeeded, let responseData = response.getDataJson() as? [String: Any], let paymentAccountsJson = responseData["payment_types"] as? [[String: Any]] { var creditCards = [CougarCashPaymentAccount]() var bankAccounts = [CougarCashPaymentAccount]() //Wrap this whole block in the do so that we are not returning InvalidModelError callbacks for each individual failure but one error of there are any failures at all. do { for dict in paymentAccountsJson { let paymentAccount = try CougarCashPaymentAccount(cougarCashDict: dict) if paymentAccount.type == .creditCard { creditCards.append(paymentAccount) } else { bankAccounts.append(paymentAccount) } } callback(creditCards, bankAccounts, nil) } catch { callback(nil, nil, InvalidModelError.byuError) } } else { callback(nil, nil, response.error) } } } static func startPayment(amount: Double, paymentType: CougarCashPaymentAccount, callback: @escaping (CougarCashPayment?, ByuError?) -> Void) { let responseHandler: (ByuResponse2, () -> Void) -> Void = { (response, errorHandler) in if response.succeeded, let responseDict = response.getDataJson() as? [String: Any] { do { try callback(CougarCashPayment(dict: responseDict), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { //The error handler will be passed in whenever responseHandler is called errorHandler() } } let request = createRequest(method: .POST, pathParams: ["payment"], data: ["amount": "\(amount)", "payment_type_id": paymentType.id]) //Set retryCount to 0 since we will manually handle the retry request.retryCount = 0 makeRequest(request) { (response) in responseHandler(response, { //If the statusCode matches one of CougarCash's readable errors, don't retry. Otherwise, retry. if let debugMessage = response.error?.debugMessage, check(string: debugMessage, forPrefixes: ["Payment Manager Start Payment Error for", "Start Payment Input Error for", "Start Payment Error for", "No plan found for"]) { response.error?.readableMessage = debugMessage response.error?.debugMessage = nil callback(nil, response.error) } else { //Send the request again makeRequest(request) { (response) in responseHandler(response, { callback(nil, response.error) }) } } }) } } static func finishPayment(invoiceId: String, paymentTypeId: String, callback: @escaping (CougarCashBalance?, ByuError?) -> Void) { let responseHandler: (ByuResponse2, () -> Void) -> Void = { (response, errorHandler) in if response.succeeded, let responseDict = response.getDataJson() as? [String: Any] { callback(CougarCashBalance(dict: responseDict), nil) } else { //The error handler will be passed in whenever responseHandler is called errorHandler() } } let request = createRequest(method: .PUT, pathParams: ["payment", invoiceId], data: ["payment_type_id": paymentTypeId]) //Set retryCount to 0 since we will manually handle the retry request.retryCount = 0 makeRequest(request) { (response) in responseHandler(response, { //If the statusCode matches one of CougarCash's readable errors, don't retry. Otherwise, retry. if let debugMessage = response.error?.debugMessage, check(string: debugMessage, forPrefixes: ["Pay Error", "Start Payment Input Error", "No plan found for"]) { response.error?.readableMessage = debugMessage response.error?.debugMessage = nil callback(nil, response.error) } else { //Send the request again makeRequest(request) { (response) in responseHandler(response, { response.error?.readableMessage = DEFAULT_PAYMENT_ERROR_MESSAGE callback(nil, response.error) }) } } }) } } private static func check(string: String, forPrefixes prefixes: [String]) -> Bool { //Reduce the array to one boolean value indicating if prefixes contains the prefix for the string passed in return prefixes.reduce(false, { $0 || string.hasPrefix($1) }) } private static func createRequest(method: ByuRequest2.RequestMethod = .GET, pathParams: [String], queryParams: [String: String]? = nil, data: [String: Any]? = nil) -> ByuRequest2 { let request = ByuRequest2(requestMethod: method, url: super.url(base: BASE_URL, pathParams: pathParams, queryParams: queryParams), contentType: .JSON) if let body = data { request.body = try? JSONSerialization.data(withJSONObject: body) } return request } }
apache-2.0
3157693e4de495b5c6afaffb3e54e09c
37.591623
224
0.693393
3.764556
false
false
false
false
wcm-io-devops/aem-manager-osx
aem-manager-osx/InstanceMenu.swift
1
6024
// // InstanceMenu.swift // aem-manager-osx // // Created by mceruti on 27.11.18. // Copyright © 2018 Peter Mannel-Wiedemann. // Fixes and additional Tweaks by Matteo Ceruti. // All rights reserved. // import Foundation import Cocoa protocol InstanceMenuDelegate { func deleteInstance(_ instance: AEMInstanceSupplier) func newInstance() func editInstance(_ instance: AEMInstanceSupplier) func startInstance(_ instance: AEMInstanceSupplier) func stopInstance(_ instance: AEMInstanceSupplier) func openAuthor(_ instance: AEMInstanceSupplier) func openCRX(_ instance: AEMInstanceSupplier) func openCRXDE(_ instance: AEMInstanceSupplier) func openFelixConsole(_ instance: AEMInstanceSupplier) func openInstanceFolder(_ instance: AEMInstanceSupplier) func openRequestLog(_ instance: AEMInstanceSupplier) func openErrorLog(_ instance: AEMInstanceSupplier) } // Represents the Instances-Menu. It is also used for the context-menu. Therefore I had to introduce the abstraction AEMInstanceSupplier // that supplies the AEM-Instance in question to support all those cases. // The status-bar item's menus inherit from this class. See StatusBarInstanceMenu below class InstanceMenu : NSMenu { internal let instance: AEMInstanceSupplier internal let target: InstanceMenuDelegate! init(target: InstanceMenuDelegate!, instance: @escaping AEMInstanceSupplier){ self.instance = instance self.target = target super.init(title: "Instances") autoenablesItems = true addItems() } fileprivate func addItems(){ addNewInstanceItem() addEditInstanceItem() addDeleteItem() addItem(NSMenuItem.separator()) addStandardMenuItems() } fileprivate func addStandardMenuItems() { addItem(InstanceMenuItem(t: "Start Instance", a: {self.target.startInstance(self.instance)}, k: "",self.instance)) addItem(InstanceMenuItem(t: "Stop Instance", a: {self.target.stopInstance(self.instance)}, k: "",self.instance)) addItem(NSMenuItem.separator()) addItem(InstanceMenuItem(t: "Open Author/Publish", a: {self.target.openAuthor(self.instance)}, k: "",self.instance)) addItem(InstanceMenuItem(t: "Open CRX", a: {self.target.openCRX(self.instance)}, k: "",self.instance)) addItem(InstanceMenuItem(t: "Open CRXDE Lite", a: {self.target.openCRXDE(self.instance)}, k: "",self.instance)) addItem(InstanceMenuItem(t: "Open Felix Console", a: {self.target.openFelixConsole(self.instance)}, k: "",self.instance)) addItem(NSMenuItem.separator()) addItem(InstanceMenuItem(t: "Open in \"Finder\"", a: {self.target.openInstanceFolder(self.instance)}, k: "",self.instance)) addItem(NSMenuItem.separator()) addItem(InstanceMenuItem(t: "Error Log", a: {self.target.openErrorLog(self.instance)}, k: "", self.instance)) addItem(InstanceMenuItem(t: "Request Log", a: {self.target.openRequestLog(self.instance)}, k: "",self.instance)) } fileprivate func addEditInstanceItem() { addItem(InstanceMenuItem(t: "Edit", a: {self.target.editInstance(self.instance)}, k: "", self.instance)) } fileprivate func addNewInstanceItem() { addItem(NewInstanceMenuItem(t: "New", a: {self.target.newInstance()}, k: "n",{nil})) } fileprivate func addDeleteItem(){ addItem(InstanceMenuItem(t: "Delete", a: {self.target.deleteInstance(self.instance)}, k: String(UnicodeScalar(NSBackspaceCharacter)!),self.instance)) } required init(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class StatusBarInstanceMenu : InstanceMenu { internal var statusMenuItem:NSMenuItem? override init(target: InstanceMenuDelegate!, instance: @escaping AEMInstanceSupplier){ super.init(target: target,instance: instance) } fileprivate func addStatusItem() { statusMenuItem = NSMenuItem(title: instance()!.name, action: nil, keyEquivalent: "") statusMenuItem!.isEnabled = false addItem(statusMenuItem!) } fileprivate override func addItems() { addStatusItem() addItem(NSMenuItem.separator()) addEditInstanceItem() addItem(NSMenuItem.separator()) addStandardMenuItems() } func updateStatus(){ statusMenuItem?.title = getStatusText() } func getStatusText() -> String { return StatusBarInstanceMenu.getStatusText(instance: self.instance()) } static func getStatusText(instance:AEMInstance!) -> String { return "\(instance.name) (\(instance.status.rawValue))" } required init(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class NewInstanceMenuItem : InstanceMenuItem { override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { return true } } class InstanceMenuItem : NSMenuItem, NSMenuItemValidation { var actionClosure: () -> () internal let instance : AEMInstanceSupplier init(t: String, a: @escaping ()->(), k: String, _ instance: @escaping AEMInstanceSupplier ) { self.actionClosure = a self.instance = instance; super.init(title: t, action: #selector(InstanceMenuItem.action(sender:)), keyEquivalent: k) self.target = self; } required init(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func action(sender: InstanceMenuItem) { self.actionClosure() } override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { return instance() != nil } }
apache-2.0
9c66a76edc0e0e5aa4bf6032343acdd5
30.534031
157
0.650672
4.458179
false
false
false
false
dinhchitrung/MediumScrollFullScreen
MediumScrollFullScreen-Sample/MediumScrollFullScreen-Sample/WebViewController.swift
1
5767
// // ViewController.swift // MediumScrollFullScreen-Sample // // Created by pixyzehn on 2/24/15. // Copyright (c) 2015 pixyzehn. All rights reserved. // import UIKit class WebViewController: UIViewController { enum State { case Showing case Hiding } @IBOutlet weak var webView: UIWebView! var statement: State = .Hiding var scrollProxy: MediumScrollFullScreen? var scrollView: UIScrollView? var enableTap = false override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) hideToolbar() } override func viewDidLoad() { super.viewDidLoad() scrollProxy = MediumScrollFullScreen(forwardTarget: webView) webView.scrollView.delegate = scrollProxy scrollProxy?.delegate = self as MediumScrollFullScreenDelegate webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://nshipster.com/swift-collection-protocols/")!)) let screenTap = UITapGestureRecognizer(target: self, action: "tapGesture:") screenTap.delegate = self webView.addGestureRecognizer(screenTap) // Add temporary item navigationItem.hidesBackButton = true let menuColor = UIColor(red:0.2, green:0.2, blue:0.2, alpha:1) let backButton = UIBarButtonItem(image: UIImage(named: "back_arrow"), style: .Plain, target: self, action: "popView") backButton.tintColor = menuColor navigationItem.leftBarButtonItem = backButton let rightButton = UIButton.buttonWithType(.Custom) as! UIButton rightButton.frame = CGRectMake(0, 0, 60, 60) rightButton.addTarget(self, action: "changeIcon:", forControlEvents: .TouchUpInside) rightButton.setImage(UIImage(named: "star_n"), forState: .Normal) rightButton.setImage(UIImage(named: "star_s"), forState: .Selected) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) let favButton = UIButton.buttonWithType(.Custom) as! UIButton favButton.frame = CGRectMake(0, 0, 60, 60) favButton.addTarget(self, action: "changeIcon:", forControlEvents: .TouchUpInside) favButton.setImage(UIImage(named: "fav_n"), forState: .Normal) favButton.setImage(UIImage(named: "fav_s"), forState: .Selected) let toolItem: UIBarButtonItem = UIBarButtonItem(customView: favButton) let timeLabel = UILabel(frame: CGRectMake(0, 0, 100, 20)) timeLabel.text = "?? min left" timeLabel.textAlignment = .Center timeLabel.tintColor = menuColor let timeButton = UIBarButtonItem(customView: timeLabel as UIView) let actionButton = UIBarButtonItem(barButtonSystemItem: .Action, target: nil, action: nil) actionButton.tintColor = menuColor let gap = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil) fixedSpace.width = 20 toolbarItems = [toolItem, gap, timeButton, gap, actionButton, fixedSpace] } func changeIcon(sender: UIButton) { sender.selected = !sender.selected } func popView() { navigationController?.popViewControllerAnimated(true) } func tapGesture(sender: UITapGestureRecognizer) { if !enableTap { return } if statement == .Hiding { if navigationController?.toolbarHidden == true { UIView.animateWithDuration(0.3, animations: {[unowned self]() -> () in self.navigationController?.toolbarHidden = false }) } showNavigationBar() showToolbar() statement = .Showing } else { hideNavigationBar() hideToolbar() statement = .Hiding } } } extension WebViewController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } extension WebViewController: MediumScrollFullScreenDelegate { func scrollFullScreen(fullScreenProxy: MediumScrollFullScreen, scrollViewDidScrollUp deltaY: Float, userInteractionEnabled enabled: Bool) { enableTap = enabled ? false : true; moveNavigationBar(deltaY: deltaY) moveToolbar(deltaY: -deltaY) } func scrollFullScreen(fullScreenProxy: MediumScrollFullScreen, scrollViewDidScrollDown deltaY: Float, userInteractionEnabled enabled: Bool) { if enabled { enableTap = false moveNavigationBar(deltaY: deltaY) hideToolbar() } else { enableTap = true moveNavigationBar(deltaY: -deltaY) moveToolbar(deltaY: deltaY) } } func scrollFullScreenScrollViewDidEndDraggingScrollUp(fullScreenProxy: MediumScrollFullScreen, userInteractionEnabled enabled: Bool) { hideNavigationBar() hideToolbar() statement = .Hiding } func scrollFullScreenScrollViewDidEndDraggingScrollDown(fullScreenProxy: MediumScrollFullScreen, userInteractionEnabled enabled: Bool) { if enabled { showNavigationBar() hideToolbar() statement = .Showing } else { hideNavigationBar() hideToolbar() statement = .Hiding } } }
mit
2a31d378d46f253657f25867f2e4a20d
35.967949
145
0.652159
5.344764
false
false
false
false
dnevera/IMProcessing
IMProcessing/Classes/Histogram/IMPColorWeightsAnalyzer.swift
1
4557
// // IMPColorWeightsAnalyzer.swift // IMProcessing // // Created by denis svinarchuk on 21.12.15. // Copyright © 2015 Dehancer.photo. All rights reserved. // #if os(iOS) import UIKit #else import Cocoa #endif import Accelerate public class IMPColorWeightsSolver: NSObject, IMPHistogramSolver { public struct ColorWeights{ public let count = 6 public var reds:Float { return weights[0] } public var yellows:Float { return weights[1] } public var greens:Float { return weights[2] } public var cyans:Float { return weights[3] } public var blues:Float { return weights[4] } public var magentas:Float { return weights[5] } public subscript(index:Int)-> Float { return weights[index] } internal init(weights:[Float]){ self.weights = weights } private var weights:[Float] } public struct NeutralWeights{ public let saturated:Float public let blacks:Float public let whites:Float public let neutrals:Float internal init(weights:[Float]){ saturated = weights[0] blacks = weights[1] whites = weights[2] neutrals = weights[3] } } private var _colorWeights = ColorWeights(weights: [Float](count: 6, repeatedValue: 0)) private var _neutralWeights = NeutralWeights(weights: [Float](count: 4, repeatedValue: 0)) public var colorWeights:ColorWeights{ get{ return _colorWeights } } public var neutralWeights:NeutralWeights{ get{ return _neutralWeights } } private func normalize(inout A A:[Float]){ var n:Float = 0 let sz = vDSP_Length(A.count) vDSP_sve(&A, 1, &n, sz); if n != 0 { vDSP_vsdiv(&A, 1, &n, &A, 1, sz); } } public func analizerDidUpdate(analizer: IMPHistogramAnalyzerProtocol, histogram: IMPHistogram, imageSize: CGSize) { // // hues placed at start of channel W // var huesCircle = [Float](histogram[.W][0...5]) // // normalize hues // normalize(A: &huesCircle) _colorWeights = ColorWeights(weights: huesCircle) // // weights of diferrent classes (neutral) brightness is placed at the and of channel W // var weights = [Float](histogram[analizer.hardware == .GPU ? .W : .Z][252...255]) // // normalize neutral weights // normalize(A: &weights) _neutralWeights = NeutralWeights(weights: weights) } } public class IMPColorWeightsAnalyzer: IMPHistogramAnalyzer { public static var defaultClipping = IMPColorWeightsClipping(white: 0.1, black: 0.1, saturation: 0.1) public var clipping:IMPColorWeightsClipping!{ didSet{ clippingBuffer = clippingBuffer ?? context.device.newBufferWithLength(sizeof(IMPColorWeightsClipping), options: .CPUCacheModeDefaultCache) if let b = clippingBuffer { memcpy(b.contents(), &clipping, b.length) } self.dirty = true } } public let solver = IMPColorWeightsSolver() private var clippingBuffer:MTLBuffer? public required init(context: IMPContext, hardware:IMPHistogramAnalyzer.Hardware) { var function = "kernel_impColorWeightsPartial" if hardware == .DSP { function = "kernel_impColorWeightsVImage" } else if context.hasFastAtomic() { function = "kernel_impColorWeightsAtomic" } super.init(context: context, function: function, hardware: hardware) super.addSolver(solver) defer{ clipping = IMPColorWeightsAnalyzer.defaultClipping } } convenience required public init(context: IMPContext) { self.init(context: context, hardware: .GPU) } public override func configure(function: IMPFunction, command: MTLComputeCommandEncoder) { command.setBuffer(self.clippingBuffer, offset: 0, atIndex: 4) } override public func addSolver(solver: IMPHistogramSolver) { fatalError("IMPColorWeightsAnalyzer can't add new solver but internal") } }
mit
e276954702c8b638870f38cbed7906b7
26.445783
150
0.580114
4.546906
false
false
false
false
shiningdracon/WebComicTranslatePlatform
Sources/main.swift
2
38006
import Foundation import PerfectLib import PerfectHTTP import PerfectHTTPServer import PerfectMustache import PerfectLogger import MySQL import OpenCC import SwiftGD class SiteMain { struct DatabaseConfig { var host: String var user: String var password: String var dbname: String var tablePrefix: String } struct ServerConfig { var address: String var port: UInt16 var sslCertificatePath: String var sslKeyPath: String var enableHTTP2: Bool } struct SiteConfig { var uploadSizeLimit: Int var galleryUploadDir: String var postUploadDir: String var privateMessageUploadDir: String var chatUploadDir: String var avatarUploadDir: String var cookieName: String var cookieDomain: String var cookiePath: String var cookieSecure: Bool var cookieSeed: String var baseUrl: String } typealias PageHandler = (SiteController, SessionInfo, HTTPRequest, HTTPResponse) -> SiteResponse static func parseAcceptLanguage(_ value: String) -> i18nLocale { let components = value.components(separatedBy: ",") for language in components { let params = language.components(separatedBy: CharacterSet(charactersIn: "-_")) if params.count == 1 { if params[0].caseInsensitiveCompare("zh") == .orderedSame { return .zh_CN } } else if params.count > 1 { if params[0].caseInsensitiveCompare("zh") == .orderedSame { if params[1].caseInsensitiveCompare("tw") == .orderedSame || params[1].caseInsensitiveCompare("hk") == .orderedSame || params[1].caseInsensitiveCompare("mo") == .orderedSame { return .zh_TW } else { return .zh_CN } } } } return .zh_CN } struct CommonHandler: MustachePageHandler { var pageHandler: PageHandler var databaseConfig: DatabaseConfig var siteConfig: SiteConfig var utilities: UtilitiesPerfect var memoryStorage: MemoryStorage init(pageHandler: @escaping PageHandler, util: UtilitiesPerfect, databaseConfig: DatabaseConfig, siteConfig: SiteConfig, memoryStorage: MemoryStorage) { self.pageHandler = pageHandler self.databaseConfig = databaseConfig self.siteConfig = siteConfig self.utilities = util self.memoryStorage = memoryStorage } func extendValuesForResponse(context contxt: MustacheWebEvaluationContext, collector: MustacheEvaluationOutputCollector) { let request = contxt.webRequest let response = contxt.webResponse let templatesDir = "./views" let locale: i18nLocale = SiteMain.parseAcceptLanguage(request.header(.acceptLanguage) ?? "") let session: ForumSessionInfo = ForumSessionInfo(remoteAddress: request.remoteAddress.host, locale: locale, referer: request.header(.referer) ?? "", userID: 0, passwordHash: "", expirationTime: 0, sessionHash: "") let cookies = request.cookies for cookie in cookies { if cookie.0 == siteConfig.cookieName { let value = cookie.1 let properties = value.characters.split(separator: "|").map(String.init) if properties.count == 4 { if let userId = UInt32.init(properties[0]), let expirationTime = Double.init(properties[2]) { session.userID = userId session.passwordHash = properties[1] session.expirationTime = expirationTime session.sessionHash = properties[3] } } } } guard let mysql = MySQLPerfect(host: databaseConfig.host, user: databaseConfig.user, passwd: databaseConfig.password, dbname: databaseConfig.dbname) else { LogFile.error("Database init failed") return } let dbStorage = DatabaseStorage(database: mysql, prefix: databaseConfig.tablePrefix) let data = DataManager(dbStorage: dbStorage, memoryStorage: self.memoryStorage) let controller = SiteController(util: utilities, data: data) controller.siteConfig["cookieSeed"] = siteConfig.cookieSeed controller.siteConfig["galleryUploadDir"] = siteConfig.galleryUploadDir controller.siteConfig["postUploadDir"] = siteConfig.postUploadDir controller.siteConfig["privateMessageUploadDir"] = siteConfig.privateMessageUploadDir controller.siteConfig["chatUploadDir"] = siteConfig.chatUploadDir controller.siteConfig["avatarUploadDir"] = siteConfig.avatarUploadDir controller.siteConfig["baseUrl"] = self.siteConfig.baseUrl let result = self.pageHandler(controller, session, request, response) if let responseSession = result.session as? ForumSessionInfo { let value = "\(responseSession.userID)|\(responseSession.passwordHash)|\(responseSession.expirationTime)|\(responseSession.sessionHash))" response.addCookie(HTTPCookie(name: siteConfig.cookieName, value: value, domain: siteConfig.cookieDomain, expires: HTTPCookie.Expiration.relativeSeconds(Int(responseSession.expirationTime)), path: nil, secure: siteConfig.cookieSecure, httpOnly: true)) } else { response.addCookie(HTTPCookie(name: siteConfig.cookieName, value: "", domain: siteConfig.cookieDomain, expires: HTTPCookie.Expiration.absoluteSeconds(0), path: nil, secure: siteConfig.cookieSecure, httpOnly: true)) } response.addHeader(.contentSecurityPolicy, value: "default-src 'self'; img-src * data: blob:; media-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src * wss:;") switch result.status { case .OK(view: let view, data: let data): contxt.templatePath = "\(templatesDir)/\(view)" contxt.extendValues(with: data as! [String: Any]) do { try contxt.requestCompleted(withCollector: collector) LogFile.info("[\(request.remoteAddress.host)] URI: \(request.uri)") } catch { response.status = .internalServerError response.appendBody(string: "Service error") response.completed() LogFile.error("[\(request.remoteAddress.host)] \(error)") } case .Redirect(location: let location): response.status = .found response.setHeader(HTTPResponseHeader.Name.location, value: location) response.completed() case .NotFound: response.status = .notFound response.appendBody(string: "Not found") response.completed() LogFile.warning("[\(request.remoteAddress.host)] Not found: \(request.uri)") case .Error(message: let message): response.status = .internalServerError response.appendBody(string: "Service error") response.completed() LogFile.error("[\(request.remoteAddress.host)] URI: \(request.uri), error: \(message)") } } } var databaseConfig: DatabaseConfig var serverConfig: ServerConfig var siteConfig: SiteConfig var routes: Routes var utilities: UtilitiesPerfect var memoryStorage: MemoryStorage init() { LogFile.location = "./server.log" self.routes = Routes() do { let config = try String(contentsOfFile: "./config.json", encoding: String.Encoding.utf8) if let jsonData = config.data(using: String.Encoding.utf8) { if let json = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any], let databaseConfigJSON = json["databaseConfig"] as? [String: Any], let host = databaseConfigJSON["host"] as? String, let user = databaseConfigJSON["user"] as? String, let password = databaseConfigJSON["password"] as? String, let dbname = databaseConfigJSON["dbname"] as? String, let tablePrefix = databaseConfigJSON["tablePrefix"] as? String, let serverConfigJSON = json["serverConfig"] as? [String: Any], let address = serverConfigJSON["address"] as? String, let portString = serverConfigJSON["port"] as? String, let port = UInt16(portString), let sslCertificatePath = serverConfigJSON["sslCertificatePath"] as? String, let sslKeyPath = serverConfigJSON["sslKeyPath"] as? String, let enableHTTP2String = serverConfigJSON["enableHTTP2"] as? String, let enableHTTP2 = Bool(enableHTTP2String), let siteConfigJSON = json["siteConfig"] as? [String: Any], let uploadSizeLimitString = siteConfigJSON["uploadSizeLimit"] as? String, let uploadSizeLimit = Int(uploadSizeLimitString), let galleryUploadDir = siteConfigJSON["galleryUploadDir"] as? String, let postUploadDir = siteConfigJSON["postUploadDir"] as? String, let privateMessageUploadDir = siteConfigJSON["privateMessageUploadDir"] as? String, let chatUploadDir = siteConfigJSON["chatUploadDir"] as? String, let avatarUploadDir = siteConfigJSON["avatarUploadDir"] as? String, let cookieName = siteConfigJSON["cookieName"] as? String, let cookieDomain = siteConfigJSON["cookieDomain"] as? String, let cookiePath = siteConfigJSON["cookiePath"] as? String, let cookieSecureString = siteConfigJSON["cookieSecure"] as? String, let cookieSecure = Bool(cookieSecureString), let cookieSeed = siteConfigJSON["cookieSeed"] as? String, let baseUrl = siteConfigJSON["baseUrl"] as? String { self.databaseConfig = DatabaseConfig(host: host, user: user, password: password, dbname: dbname, tablePrefix: tablePrefix) self.serverConfig = ServerConfig(address: address, port: port, sslCertificatePath: sslCertificatePath, sslKeyPath: sslKeyPath, enableHTTP2: enableHTTP2) self.siteConfig = SiteConfig(uploadSizeLimit: uploadSizeLimit, galleryUploadDir: galleryUploadDir, postUploadDir: postUploadDir, privateMessageUploadDir: privateMessageUploadDir, chatUploadDir: chatUploadDir, avatarUploadDir: avatarUploadDir, cookieName: cookieName, cookieDomain: cookieDomain, cookiePath: cookiePath, cookieSecure: cookieSecure, cookieSeed: cookieSeed, baseUrl: baseUrl) } else { fatalError("Load config failed") } } else { fatalError("Load config failed") } } catch { fatalError("Load config failed") } guard let utilities = UtilitiesPerfect() else { fatalError("Utilities init failed") } self.utilities = utilities self.memoryStorage = MemoryStorage() guard let mysql = MySQLPerfect(host: databaseConfig.host, user: databaseConfig.user, passwd: databaseConfig.password, dbname: databaseConfig.dbname) else { fatalError("Database init failed") } let forumdb = DatabaseStorage(database: mysql, prefix: databaseConfig.tablePrefix) do { try self.memoryStorage.initMemoryStorageForum(forumdb) } catch MemoryStorageError.initFailed(let message) { fatalError("MemoryStorage init failed: \(message)") } catch { fatalError("Unknow error") } } func addRouteMustache(method: HTTPMethod, uri: String, handler: @escaping PageHandler) { routes.add(method: method, uri: uri, handler: { (request: HTTPRequest, response: HTTPResponse) in mustacheRequest(request: request, response: response, handler: CommonHandler(pageHandler: handler, util: self.utilities, databaseConfig: self.databaseConfig, siteConfig: self.siteConfig, memoryStorage: self.memoryStorage), templatePath: "") }) } func addRouteJson(method: HTTPMethod, uri: String, handler: @escaping PageHandler) { routes.add(method: method, uri: uri, handler: { (request: HTTPRequest, response: HTTPResponse) in let locale: i18nLocale = SiteMain.parseAcceptLanguage(request.header(.acceptLanguage) ?? "") let session: ForumSessionInfo = ForumSessionInfo(remoteAddress: request.remoteAddress.host, locale: locale, referer: request.header(.referer) ?? "", userID: 0, passwordHash: "", expirationTime: 0, sessionHash: "") let cookies = request.cookies for cookie in cookies { if cookie.0 == self.siteConfig.cookieName { let value = cookie.1 let properties = value.characters.split(separator: "|").map(String.init) if properties.count == 4 { if let userId = UInt32.init(properties[0]), let expirationTime = Double.init(properties[2]) { session.userID = userId session.passwordHash = properties[1] session.expirationTime = expirationTime session.sessionHash = properties[3] } } } } guard let mysql = MySQLPerfect(host: self.databaseConfig.host, user: self.databaseConfig.user, passwd: self.databaseConfig.password, dbname: self.databaseConfig.dbname) else { LogFile.error("Database init failed") return } let dbStorage = DatabaseStorage(database: mysql, prefix: self.databaseConfig.tablePrefix) let data = DataManager(dbStorage: dbStorage, memoryStorage: self.memoryStorage) let controller = SiteController(util: self.utilities, data: data) controller.siteConfig["cookieSeed"] = self.siteConfig.cookieSeed controller.siteConfig["galleryUploadDir"] = self.siteConfig.galleryUploadDir controller.siteConfig["postUploadDir"] = self.siteConfig.postUploadDir controller.siteConfig["privateMessageUploadDir"] = self.siteConfig.privateMessageUploadDir controller.siteConfig["chatUploadDir"] = self.siteConfig.chatUploadDir controller.siteConfig["avatarUploadDir"] = self.siteConfig.avatarUploadDir controller.siteConfig["baseUrl"] = self.siteConfig.baseUrl let result = handler(controller, session, request, response) if let responseSession = result.session as? ForumSessionInfo { let value = "\(responseSession.userID)|\(responseSession.passwordHash)|\(responseSession.expirationTime)|\(responseSession.sessionHash))" response.addCookie(HTTPCookie(name: self.siteConfig.cookieName, value: value, domain: self.siteConfig.cookieDomain, expires: HTTPCookie.Expiration.relativeSeconds(Int(responseSession.expirationTime)), path: nil, secure: self.siteConfig.cookieSecure, httpOnly: true)) } else { response.addCookie(HTTPCookie(name: self.siteConfig.cookieName, value: "", domain: self.siteConfig.cookieDomain, expires: HTTPCookie.Expiration.absoluteSeconds(0), path: nil, secure: self.siteConfig.cookieSecure, httpOnly: true)) } response.setHeader(.contentType, value: "application/json; charset=utf-8") switch result.status { case .OK(view: _, data: let data): do { let jsonDataValidated = try JSONSerialization.data(withJSONObject: data) guard let jsonString = String(data: jsonDataValidated, encoding: .utf8) else { return } response.status = .ok response.appendBody(string: jsonString) response.completed() LogFile.info("[\(request.remoteAddress.host)] URI: \(request.uri)") } catch { response.status = .internalServerError response.appendBody(string: "Service error") response.completed() LogFile.error("[\(request.remoteAddress.host)] \(error)") } case .Redirect(location: let location): response.status = .found response.setHeader(HTTPResponseHeader.Name.location, value: location) response.completed() case .NotFound: response.status = .notFound response.appendBody(string: "Not found") response.completed() LogFile.warning("[\(request.remoteAddress.host)] Not found: \(request.uri)") case .Error(message: let message): response.status = .internalServerError response.appendBody(string: "Service error") response.completed() LogFile.error("[\(request.remoteAddress.host)] URI: \(request.uri), error: \(message)") } }) } func start() { setupForumRoutes() setupComicRoutes() let server = HTTPServer() server.serverAddress = serverConfig.address server.serverPort = serverConfig.port if !serverConfig.sslCertificatePath.isEmpty && !serverConfig.sslKeyPath.isEmpty { server.ssl = (serverConfig.sslCertificatePath, serverConfig.sslKeyPath) } if serverConfig.enableHTTP2 { server.alpnSupport = [.http2, .http11] } server.addRoutes(routes) server.documentRoot = "./webroot" // Setting the document root will add a default URL route which permits static files to be served from within. do { try server.start() } catch { fatalError("\(error)") } } } extension SiteMain { func setupForumRoutes() { addRouteMustache(method: .get, uri: "/", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let tab = UInt32.init(request.param(name: "tab") ?? "1") { return controller.mainPage(session: session as! ForumSessionInfo, tab: tab, page: 1) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/page/{page}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let tab = UInt32.init(request.param(name: "tab") ?? "1") { if let page = UInt32.init(request.urlVariables["page"] ?? "0"), page > 0 { return controller.mainPage(session: session as! ForumSessionInfo, tab: tab, page: page) } } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/login", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in return controller.loginPage(session: session as! ForumSessionInfo) }) addRouteMustache(method: .get, uri: "/forget", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in return controller.forgetPage(session: session as! ForumSessionInfo) }) addRouteMustache(method: .post, uri: "/login", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in let identity = request.param(name: "req_username") ?? "" let password = request.param(name: "req_password") ?? "" let savepass: Bool = (request.param(name: "save_pass") == "1") ? true : false let location = request.param(name: "redirect_url") ?? "/" if identity.range(of:"@") != nil { return controller.loginHandler(session: session as! ForumSessionInfo, email: identity, password: password, savepass: savepass, redirectURL: location) } else { return controller.loginHandler(session: session as! ForumSessionInfo, username: identity, password: password, savepass: savepass, redirectURL: location) } }) addRouteMustache(method: .get, uri: "/logout", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in let csrf = request.param(name: "csrf_token") ?? "" return controller.logoutHandler(session: session as! ForumSessionInfo, csrf: csrf) }) addRouteMustache(method: .get, uri: "/forum/{id}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let paramId = UInt32(request.urlVariables["id"] ?? "0"), paramId > 0 { return controller.forumPage(session: session as! ForumSessionInfo, id: paramId, page: 1) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/forum/{id}/page/{page}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let paramId = UInt32(request.urlVariables["id"] ?? "0"), paramId > 0 { if let page = UInt32(request.urlVariables["page"] ?? "0"), page > 0 { return controller.forumPage(session: session as! ForumSessionInfo, id: paramId, page: page) } } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/topic/{id}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let paramId = UInt32(request.urlVariables["id"] ?? "0"), paramId > 0 { return controller.topicPage(session: session as! ForumSessionInfo, id: paramId, page: 1) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/forum/{id}/post", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let forumId = UInt32(request.urlVariables["id"] ?? "0"), forumId > 0 { return controller.postTopicPage(session: session as! ForumSessionInfo, forumId: forumId) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .post, uri: "/forum/{id}/post", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let forumId = UInt32(request.urlVariables["id"] ?? "0"), forumId > 0 { if let subject = request.param(name: "req_subject") { if let message = request.param(name: "req_message") { if let CSRFToken = request.param(name: "csrf_token") { return controller.postTopicHandler(session: session as! ForumSessionInfo, subject: subject, message: message, forumId: forumId, CSRFToken: CSRFToken) } } } } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/topic/{id}/page/{page}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let paramId = UInt32(request.urlVariables["id"] ?? "0"), paramId > 0 { if let page = UInt32(request.urlVariables["page"] ?? "0"), page > 0 { return controller.topicPage(session: session as! ForumSessionInfo, id: paramId, page: page) } } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/post/{id}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let postId = UInt32(request.urlVariables["id"] ?? "0"), postId > 0 { return controller.topicPage(session: session as! ForumSessionInfo, postId: postId) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/topic/{id}/postreply", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let topicId = UInt32(request.urlVariables["id"] ?? "0"), topicId > 0 { return controller.postReplyPage(session: session as! ForumSessionInfo, topicId: topicId) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .post, uri: "/topic/{id}/postreply", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let topicId = UInt32(request.urlVariables["id"] ?? "0"), topicId > 0 { if let message = request.param(name: "req_message") { if let CSRFToken = request.param(name: "csrf_token") { return controller.postReplyHandler(session: session as! ForumSessionInfo, topicId: topicId, message: message, CSRFToken: CSRFToken) } } } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/user/{uid}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let userId = UInt32(request.urlVariables["uid"] ?? "0"), userId > 0 { return controller.draconityPage(session: session as! ForumSessionInfo, userId: userId) } return SiteResponse(status: .NotFound, session: session) }) addRouteJson(method: .post, uri: "/{module}/{id}/upload", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let moduleString = request.urlVariables["module"] { let module: SiteController.ForumUploadModule switch moduleString { case "forum": module = .gallery case "topic": module = .post case "message": module = .privateMessage case "chat": module = .chat default: return SiteResponse(status: .NotFound, session: session) } if let id = UInt32(request.urlVariables["id"] ?? "0"), id > 0 { if let uploads = request.postFileUploads , uploads.count > 0 { var files: Array<(path: String, fileName: String, trackingId: String)> = [] for upload in uploads { if upload.file != nil { files.append((path: upload.tmpFileName, fileName: upload.fileName, trackingId: upload.fieldName)) } } return controller.postFileHandler(session: session as! ForumSessionInfo, module: module, id: id, files: files) } return controller.errorNotifyPage(session: session, message: "No file uploaded") } } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .post, uri: "/user/avatar/upload", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let uploads = request.postFileUploads , uploads.count == 1 { return controller.postAvatarUploadHandler(session: session as! ForumSessionInfo, file: (path: uploads[0].tmpFileName, fileName: uploads[0].fileName)) } return SiteResponse(status: .NotFound, session: session) }) } func setupComicRoutes() { addRouteMustache(method: .get, uri: "/comic/{id}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["id"] ?? "0"), cid > 0 { return controller.viewComic(session: session, comicId: cid) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/addcomic", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in return controller.addComic(session: session) }) addRouteMustache(method: .post, uri: "/addcomic", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in let title = request.param(name: "title") ?? "" let author = request.param(name: "author") ?? "" let description = request.param(name: "description") ?? "" return controller.postAddComic(session: session, title: title, author: author, description: description) }) addRouteMustache(method: .get, uri: "/comic/{id}/edit", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["id"] ?? "0"), cid > 0 { return controller.editComic(session: session, comicId: cid) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .post, uri: "/comic/{id}/edit", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["id"] ?? "0"), cid > 0 { let title = request.param(name: "title") ?? "" let author = request.param(name: "author") ?? "" let description = request.param(name: "description") ?? "" return controller.postUpdateComic(session: session, comicId: cid, title: title, author: author, description: description) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/comic/{cid}/page/{pidx}", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["cid"] ?? "0"), cid > 0 { if let pidx = UInt32(request.urlVariables["pidx"] ?? "0"), pidx > 0 { return controller.viewPage(session: session, comicId: cid, pageIndex: pidx) } else if request.urlVariables["pidx"] == "add" { return controller.addPage(session: session, comicId: cid) } else if request.urlVariables["pidx"] == "end" { return controller.viewLastPage(session: session, comicId: cid) } } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/comic/{cid}/pageend", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["cid"] ?? "0"), cid > 0 { return controller.viewLastPage(session: session, comicId: cid) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/comic/{cid}/addpage", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["cid"] ?? "0"), cid > 0 { return controller.addPage(session: session, comicId: cid) } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .post, uri: "/comic/{cid}/addpage", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["cid"] ?? "0"), cid > 0 { if let uploads = request.postFileUploads , uploads.count > 0 { for upload in uploads { if upload.file != nil { let title = request.param(name: "title") ?? "" let description = request.param(name: "description") ?? "" LogFile.info("fieldName: \(upload.fieldName), fileName: \(upload.fileName), contentType: \(upload.contentType), fileSize: \(upload.fileSize)") // Validate file type var fileExtension: String if upload.contentType == "image/jpeg" { fileExtension = "jpeg" } else if upload.contentType == "image/png" { fileExtension = "png" } else if upload.contentType == "" { fileExtension = upload.fileName.filePathExtension } else { fileExtension = "" } guard fileExtension == "png" || fileExtension == "jpg" || fileExtension == "jpeg" else { return controller.errorNotifyPage(session: session, message: "File type") } // Validate file size guard upload.fileSize > 0 && upload.fileSize < self.siteConfig.uploadSizeLimit else { return controller.errorNotifyPage(session: session, message: "File size") } // Validate image guard let image = Image(url: URL(fileURLWithPath: upload.tmpFileName)) else { return controller.errorNotifyPage(session: session, message: "Not valid file") } let localname = "\(UUID().string).\(fileExtension)" return controller.postAddPage(session: session, comicId: cid, title: title, description: description, imgWebURL: "/images/"+localname, onSeccuss: { (pageId: UInt32) in try controller.comicAddFile(pageId: pageId, filename: upload.fileName, localname: localname, mimetype: upload.contentType, size: UInt32(upload.fileSize)) guard image.write(to: URL(fileURLWithPath: "webroot/images/"+localname), quality: 75) else { throw WebFrameworkError.RuntimeError("Failed write image file") } }) } } } return controller.errorNotifyPage(session: session, message: "No file uploaded") } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .get, uri: "/comic/{cid}/page/{pidx}/edit", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["cid"] ?? "0"), cid > 0 { if let pidx = UInt32(request.urlVariables["pidx"] ?? "0"), pidx > 0 { return controller.editPage(session: session, comicId: cid, pageIndex: pidx) } } return SiteResponse(status: .NotFound, session: session) }) addRouteMustache(method: .post, uri: "/comic/{cid}/page/{pidx}/update", handler: { (controller: SiteController, session: SessionInfo, request: HTTPRequest, response: HTTPResponse) in if let cid = UInt32(request.urlVariables["cid"] ?? "0"), cid > 0 { if let pidx = UInt32(request.urlVariables["pidx"] ?? "0"), pidx > 0 { if let content = request.param(name: "content") { let title = request.param(name: "title") ?? "" let description = request.param(name: "description") ?? "" return controller.postUpdatePage(session: session, comicId: cid, pageIndex: pidx, title: title, description: description, content: content) } else { return controller.errorNotifyPage(session: session, message: "Empty content") } } } return SiteResponse(status: .NotFound, session: session) }) } } let main = SiteMain() main.start()
apache-2.0
2802d341b8e4aca25c89ede84eb9cf62
56.237952
408
0.596011
4.888232
false
true
false
false
zapdroid/RXWeather
Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift
1
12771
// // DelegateProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !os(Linux) #if !RX_NO_MODULE import RxSwift #if SWIFT_PACKAGE && !os(Linux) import RxCocoaRuntime #endif #endif var delegateAssociatedTag: UnsafeRawPointer = UnsafeRawPointer(UnsafeMutablePointer<UInt8>.allocate(capacity: 1)) var dataSourceAssociatedTag: UnsafeRawPointer = UnsafeRawPointer(UnsafeMutablePointer<UInt8>.allocate(capacity: 1)) /// Base class for `DelegateProxyType` protocol. /// /// This implementation is not thread safe and can be used only from one thread (Main thread). open class DelegateProxy: _RXDelegateProxy { private var sentMessageForSelector = [Selector: MessageDispatcher]() private var methodInvokedForSelector = [Selector: MessageDispatcher]() /// Parent object associated with delegate proxy. private(set) weak var parentObject: AnyObject? /// Initializes new instance. /// /// - parameter parentObject: Optional parent object that owns `DelegateProxy` as associated object. public required init(parentObject: AnyObject) { self.parentObject = parentObject MainScheduler.ensureExecutingOnScheduler() #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif super.init() } /** Returns observable sequence of invocations of delegate methods. Elements are sent *before method is invoked*. Only methods that have `void` return value can be observed using this method because those methods are used as a notification mechanism. It doesn't matter if they are optional or not. Observing is performed by installing a hidden associated `PublishSubject` that is used to dispatch messages to observers. Delegate methods that have non `void` return value can't be observed directly using this method because: * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism * there is no sensible automatic way to determine a default return value In case observing of delegate methods that have return type is required, it can be done by manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. e.g. // delegate proxy part (RxScrollViewDelegateProxy) let internalSubject = PublishSubject<CGPoint> public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { internalSubject.on(.next(arg1)) return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue } .... // reactive property implementation in a real class (`UIScrollView`) public var property: Observable<CGPoint> { let proxy = RxScrollViewDelegateProxy.proxyForObject(base) return proxy.internalSubject.asObservable() } **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.", that means that manual observing method is required analog to the example above because delegate method has already been implemented.** - parameter selector: Selector used to filter observed invocations of delegate methods. - returns: Observable sequence of arguments passed to `selector` method. */ open func sentMessage(_ selector: Selector) -> Observable<[Any]> { MainScheduler.ensureExecutingOnScheduler() checkSelectorIsObservable(selector) let subject = sentMessageForSelector[selector] if let subject = subject { return subject.asObservable() } else { let subject = MessageDispatcher(delegateProxy: self) sentMessageForSelector[selector] = subject return subject.asObservable() } } /** Returns observable sequence of invoked delegate methods. Elements are sent *after method is invoked*. Only methods that have `void` return value can be observed using this method because those methods are used as a notification mechanism. It doesn't matter if they are optional or not. Observing is performed by installing a hidden associated `PublishSubject` that is used to dispatch messages to observers. Delegate methods that have non `void` return value can't be observed directly using this method because: * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism * there is no sensible automatic way to determine a default return value In case observing of delegate methods that have return type is required, it can be done by manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. e.g. // delegate proxy part (RxScrollViewDelegateProxy) let internalSubject = PublishSubject<CGPoint> public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { internalSubject.on(.next(arg1)) return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue } .... // reactive property implementation in a real class (`UIScrollView`) public var property: Observable<CGPoint> { let proxy = RxScrollViewDelegateProxy.proxyForObject(base) return proxy.internalSubject.asObservable() } **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.", that means that manual observing method is required analog to the example above because delegate method has already been implemented.** - parameter selector: Selector used to filter observed invocations of delegate methods. - returns: Observable sequence of arguments passed to `selector` method. */ open func methodInvoked(_ selector: Selector) -> Observable<[Any]> { MainScheduler.ensureExecutingOnScheduler() checkSelectorIsObservable(selector) let subject = methodInvokedForSelector[selector] if let subject = subject { return subject.asObservable() } else { let subject = MessageDispatcher(delegateProxy: self) methodInvokedForSelector[selector] = subject return subject.asObservable() } } private func checkSelectorIsObservable(_ selector: Selector) { MainScheduler.ensureExecutingOnScheduler() if hasWiredImplementation(for: selector) { print("Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.") return } guard (self.forwardToDelegate()?.responds(to: selector) ?? false) || voidDelegateMethodsContain(selector) else { rxFatalError("This class doesn't respond to selector \(selector)") } } // proxy open override func _sentMessage(_ selector: Selector, withArguments arguments: [Any]) { sentMessageForSelector[selector]?.on(.next(arguments)) } open override func _methodInvoked(_ selector: Selector, withArguments arguments: [Any]) { methodInvokedForSelector[selector]?.on(.next(arguments)) } /// Returns tag used to identify associated object. /// /// - returns: Associated object tag. open class func delegateAssociatedObjectTag() -> UnsafeRawPointer { return delegateAssociatedTag } /// Initializes new instance of delegate proxy. /// /// - returns: Initialized instance of `self`. open class func createProxyForObject(_ object: AnyObject) -> AnyObject { return self.init(parentObject: object) } /// Returns assigned proxy for object. /// /// - parameter object: Object that can have assigned delegate proxy. /// - returns: Assigned delegate proxy or `nil` if no delegate proxy is assigned. open class func assignedProxyFor(_ object: AnyObject) -> AnyObject? { let maybeDelegate = objc_getAssociatedObject(object, self.delegateAssociatedObjectTag()) return castOptionalOrFatalError(maybeDelegate.map { $0 as AnyObject }) } /// Assigns proxy to object. /// /// - parameter object: Object that can have assigned delegate proxy. /// - parameter proxy: Delegate proxy object to assign to `object`. open class func assignProxy(_ proxy: AnyObject, toObject object: AnyObject) { precondition(proxy.isKind(of: self.classForCoder())) objc_setAssociatedObject(object, self.delegateAssociatedObjectTag(), proxy, .OBJC_ASSOCIATION_RETAIN) } /// Sets reference of normal delegate that receives all forwarded messages /// through `self`. /// /// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`. /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. open func setForwardToDelegate(_ delegate: AnyObject?, retainDelegate: Bool) { #if DEBUG // 4.0 all configurations MainScheduler.ensureExecutingOnScheduler() #endif self._setForward(toDelegate: delegate, retainDelegate: retainDelegate) self.reset() } /// Returns reference of normal delegate that receives all forwarded messages /// through `self`. /// /// - returns: Value of reference if set or nil. open func forwardToDelegate() -> AnyObject? { return self._forwardToDelegate } private func hasObservers(selector: Selector) -> Bool { return (sentMessageForSelector[selector]?.hasObservers ?? false) || (methodInvokedForSelector[selector]?.hasObservers ?? false) } open override func responds(to aSelector: Selector!) -> Bool { return super.responds(to: aSelector) || (self._forwardToDelegate?.responds(to: aSelector) ?? false) || (self.voidDelegateMethodsContain(aSelector) && self.hasObservers(selector: aSelector)) } internal func reset() { guard let delegateProxySelf = self as? DelegateProxyType else { rxFatalErrorInDebug("\(self) doesn't implement delegate proxy type.") return } guard let parentObject = self.parentObject else { return } let selfType = type(of: delegateProxySelf) let maybeCurrentDelegate = selfType.currentDelegateFor(parentObject) if maybeCurrentDelegate === self { selfType.setCurrentDelegate(nil, toObject: parentObject) selfType.setCurrentDelegate(self, toObject: parentObject) } } deinit { for v in sentMessageForSelector.values { v.on(.completed) } for v in methodInvokedForSelector.values { v.on(.completed) } #if TRACE_RESOURCES _ = Resources.decrementTotal() #endif } } fileprivate let mainScheduler = MainScheduler() fileprivate final class MessageDispatcher { private let dispatcher: PublishSubject<[Any]> private let result: Observable<[Any]> init(delegateProxy _delegateProxy: DelegateProxy) { weak var weakDelegateProxy = _delegateProxy let dispatcher = PublishSubject<[Any]>() self.dispatcher = dispatcher self.result = dispatcher .do(onSubscribed: { weakDelegateProxy?.reset() }, onDispose: { weakDelegateProxy?.reset() }) .share() .subscribeOn(mainScheduler) } var on: (Event<[Any]>) -> Void { return self.dispatcher.on } var hasObservers: Bool { return self.dispatcher.hasObservers } func asObservable() -> Observable<[Any]> { return self.result } } #endif
mit
29b5603d714f35068ad4ae91ca384b6e
40.326861
128
0.641582
5.801908
false
false
false
false
WhisperSystems/Signal-iOS
SignalServiceKit/src/Messages/OutgoingMessagePreparer.swift
1
2366
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import PromiseKit @objc public class OutgoingMessagePreparer: NSObject { @objc public let message: TSOutgoingMessage private let unsavedAttachmentInfos: [OutgoingAttachmentInfo] private var didCompletePrep = false @objc public var savedAttachmentIds: [String]? @objc public var unpreparedMessage: TSOutgoingMessage { assert(!didCompletePrep) return message } @objc convenience init(_ message: TSOutgoingMessage) { self.init(message, unsavedAttachmentInfos: []) } @objc public init(_ message: TSOutgoingMessage, unsavedAttachmentInfos: [OutgoingAttachmentInfo]) { self.message = message self.unsavedAttachmentInfos = unsavedAttachmentInfos } @objc public func insertMessage(linkPreviewDraft: OWSLinkPreviewDraft?, transaction: SDSAnyWriteTransaction) { unpreparedMessage.anyInsert(transaction: transaction) if let linkPreviewDraft = linkPreviewDraft { do { let linkPreview = try OWSLinkPreview.buildValidatedLinkPreview(fromInfo: linkPreviewDraft, transaction: transaction) unpreparedMessage.update(with: linkPreview, transaction: transaction) } catch { Logger.error("error: \(error)") } } } @objc public func prepareMessage(transaction: SDSAnyWriteTransaction) throws -> TSOutgoingMessage { assert(!didCompletePrep) if unsavedAttachmentInfos.count > 0 { try OutgoingMessagePreparerHelper.insertAttachments(unsavedAttachmentInfos, for: message, transaction: transaction) } self.savedAttachmentIds = OutgoingMessagePreparerHelper.prepareMessage(forSending: message, transaction: transaction) didCompletePrep = true return message } } @objc public extension TSOutgoingMessage { var asPreparer: OutgoingMessagePreparer { return OutgoingMessagePreparer(self) } }
gpl-3.0
7c3e8730563c51a903ee3fc10d6dc6f1
31.861111
106
0.603128
6.035714
false
false
false
false
IAskWind/IAWExtensionTool
Pods/Kingfisher/Sources/Cache/ImageCache.swift
4
37721
// // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif extension Notification.Name { /// This notification will be sent when the disk cache got cleaned either there are cached files expired or the /// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger /// this notification. /// /// The `object` of this notification is the `ImageCache` object which sends the notification. /// A list of removed hashes (files) could be retrieved by accessing the array under /// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. /// By checking the array, you could know the hash codes of files are removed. public static let KingfisherDidCleanDiskCache = Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache") } /// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" /// Cache type of a cached image. /// - none: The image is not cached yet when retrieving it. /// - memory: The image is cached in memory. /// - disk: The image is cached in disk. public enum CacheType { /// The image is not cached yet when retrieving it. case none /// The image is cached in memory. case memory /// The image is cached in disk. case disk /// Whether the cache type represents the image is already cached or not. public var cached: Bool { switch self { case .memory, .disk: return true case .none: return false } } } /// Represents the caching operation result. public struct CacheStoreResult { /// The cache result for memory cache. Caching an image to memory will never fail. public let memoryCacheResult: Result<(), Never> /// The cache result for disk cache. If an error happens during caching operation, /// you can get it from `.failure` case of this `diskCacheResult`. public let diskCacheResult: Result<(), KingfisherError> } extension KFCrossPlatformImage: CacheCostCalculable { /// Cost of an image public var cacheCost: Int { return kf.cost } } extension Data: DataTransformable { public func toData() throws -> Data { return self } public static func fromData(_ data: Data) throws -> Data { return data } public static let empty = Data() } /// Represents the getting image operation from the cache. /// /// - disk: The image can be retrieved from disk cache. /// - memory: The image can be retrieved memory cache. /// - none: The image does not exist in the cache. public enum ImageCacheResult { /// The image can be retrieved from disk cache. case disk(KFCrossPlatformImage) /// The image can be retrieved memory cache. case memory(KFCrossPlatformImage) /// The image does not exist in the cache. case none /// Extracts the image from cache result. It returns the associated `Image` value for /// `.disk` and `.memory` case. For `.none` case, `nil` is returned. public var image: KFCrossPlatformImage? { switch self { case .disk(let image): return image case .memory(let image): return image case .none: return nil } } /// Returns the corresponding `CacheType` value based on the result type of `self`. public var cacheType: CacheType { switch self { case .disk: return .disk case .memory: return .memory case .none: return .none } } } /// Represents a hybrid caching system which is composed by a `MemoryStorage.Backend` and a `DiskStorage.Backend`. /// `ImageCache` is a high level abstract for storing an image as well as its data to disk memory and disk, and /// retrieving them back. /// /// While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create /// your own cache object and configure its storages as your need. This class also provide an interface for you to set /// the memory and disk storage config. open class ImageCache { // MARK: Singleton /// The default `ImageCache` object. Kingfisher will use this cache for its related methods if there is no /// other cache specified. The `name` of this default cache is "default", and you should not use this name /// for any of your customize cache. public static let `default` = ImageCache(name: "default") // MARK: Public Properties /// The `MemoryStorage.Backend` object used in this cache. This storage holds loaded images in memory with a /// reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set /// the storage `config` and its properties. public let memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage> /// The `DiskStorage.Backend` object used in this cache. This storage stores loaded images in disk with a /// reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set /// the storage `config` and its properties. public let diskStorage: DiskStorage.Backend<Data> private let ioQueue: DispatchQueue /// Closure that defines the disk cache path from a given path and cacheName. public typealias DiskCachePathClosure = (URL, String) -> URL // MARK: Initializers /// Creates an `ImageCache` from a customized `MemoryStorage` and `DiskStorage`. /// /// - Parameters: /// - memoryStorage: The `MemoryStorage.Backend` object to use in the image cache. /// - diskStorage: The `DiskStorage.Backend` object to use in the image cache. public init( memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>, diskStorage: DiskStorage.Backend<Data>) { self.memoryStorage = memoryStorage self.diskStorage = diskStorage let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)" ioQueue = DispatchQueue(label: ioQueueName) let notifications: [(Notification.Name, Selector)] #if !os(macOS) && !os(watchOS) #if swift(>=4.2) notifications = [ (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)), (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)), (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache)) ] #else notifications = [ (NSNotification.Name.UIApplicationDidReceiveMemoryWarning, #selector(clearMemoryCache)), (NSNotification.Name.UIApplicationWillTerminate, #selector(cleanExpiredDiskCache)), (NSNotification.Name.UIApplicationDidEnterBackground, #selector(backgroundCleanExpiredDiskCache)) ] #endif #elseif os(macOS) notifications = [ (NSApplication.willResignActiveNotification, #selector(cleanExpiredDiskCache)), ] #else notifications = [] #endif notifications.forEach { NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil) } } /// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created /// with a default config based on the `name`. /// /// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue. /// You should not use the same `name` for different caches, otherwise, the disk storage would /// be conflicting to each other. The `name` should not be an empty string. public convenience init(name: String) { try! self.init(name: name, cacheDirectoryURL: nil, diskCachePathClosure: nil) } /// Creates an `ImageCache` with a given `name`, cache directory `path` /// and a closure to modify the cache directory. /// /// - Parameters: /// - name: The name of cache object. It is used to setup disk cache directories and IO queue. /// You should not use the same `name` for different caches, otherwise, the disk storage would /// be conflicting to each other. /// - cacheDirectoryURL: Location of cache directory URL on disk. It will be internally pass to the /// initializer of `DiskStorage` as the disk cache directory. If `nil`, the cache /// directory under user domain mask will be used. /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates /// the final disk cache path. You could use it to fully customize your cache path. /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given /// path. public convenience init( name: String, cacheDirectoryURL: URL?, diskCachePathClosure: DiskCachePathClosure? = nil) throws { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let totalMemory = ProcessInfo.processInfo.physicalMemory let costLimit = totalMemory / 4 let memoryStorage = MemoryStorage.Backend<KFCrossPlatformImage>(config: .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit))) var diskConfig = DiskStorage.Config( name: name, sizeLimit: 0, directory: cacheDirectoryURL ) if let closure = diskCachePathClosure { diskConfig.cachePathBlock = closure } let diskStorage = try DiskStorage.Backend<Data>(config: diskConfig) diskConfig.cachePathBlock = nil self.init(memoryStorage: memoryStorage, diskStorage: diskStorage) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: Storing Images open func store(_ image: KFCrossPlatformImage, original: Data? = nil, forKey key: String, options: KingfisherParsedOptionsInfo, toDisk: Bool = true, completionHandler: ((CacheStoreResult) -> Void)? = nil) { let identifier = options.processor.identifier let callbackQueue = options.callbackQueue let computedKey = key.computedKey(with: identifier) // Memory storage should not throw. memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration) guard toDisk else { if let completionHandler = completionHandler { let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) callbackQueue.execute { completionHandler(result) } } return } ioQueue.async { let serializer = options.cacheSerializer if let data = serializer.data(with: image, original: original) { self.syncStoreToDisk( data, forKey: key, processorIdentifier: identifier, callbackQueue: callbackQueue, expiration: options.diskCacheExpiration, completionHandler: completionHandler) } else { guard let completionHandler = completionHandler else { return } let diskError = KingfisherError.cacheError( reason: .cannotSerializeImage(image: image, original: original, serializer: serializer)) let result = CacheStoreResult( memoryCacheResult: .success(()), diskCacheResult: .failure(diskError)) callbackQueue.execute { completionHandler(result) } } } } /// Stores an image to the cache. /// /// - Parameters: /// - image: The image to be stored. /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for /// further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to /// data for caching in disk, it checks the image format based on `original` data to determine in /// which image format should be used. For other types of `serializer`, it depends on their /// implementation detail on how to use this original data. /// - key: The key used for caching the image. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the /// image, pass the identifier of processor to this parameter. /// - serializer: The `CacheSerializer` /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory. /// Otherwise, it is cached in both memory storage and disk storage. Default is `true`. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case /// that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the /// caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called /// from an internal file IO queue. To change this behavior, specify another `CallbackQueue` /// value. /// - completionHandler: A closure which is invoked when the cache operation finishes. open func store(_ image: KFCrossPlatformImage, original: Data? = nil, forKey key: String, processorIdentifier identifier: String = "", cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, toDisk: Bool = true, callbackQueue: CallbackQueue = .untouch, completionHandler: ((CacheStoreResult) -> Void)? = nil) { struct TempProcessor: ImageProcessor { let identifier: String func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { return nil } } let options = KingfisherParsedOptionsInfo([ .processor(TempProcessor(identifier: identifier)), .cacheSerializer(serializer), .callbackQueue(callbackQueue) ]) store(image, original: original, forKey: key, options: options, toDisk: toDisk, completionHandler: completionHandler) } open func storeToDisk( _ data: Data, forKey key: String, processorIdentifier identifier: String = "", expiration: StorageExpiration? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: ((CacheStoreResult) -> Void)? = nil) { ioQueue.async { self.syncStoreToDisk( data, forKey: key, processorIdentifier: identifier, callbackQueue: callbackQueue, expiration: expiration, completionHandler: completionHandler) } } private func syncStoreToDisk( _ data: Data, forKey key: String, processorIdentifier identifier: String = "", callbackQueue: CallbackQueue = .untouch, expiration: StorageExpiration? = nil, completionHandler: ((CacheStoreResult) -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) let result: CacheStoreResult do { try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration) result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) } catch { let diskError: KingfisherError if let error = error as? KingfisherError { diskError = error } else { diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error)) } result = CacheStoreResult( memoryCacheResult: .success(()), diskCacheResult: .failure(diskError) ) } if let completionHandler = completionHandler { callbackQueue.execute { completionHandler(result) } } } // MARK: Removing Images /// Removes the image for the given key from the cache. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: The identifier of processor being used for caching. If you are using a processor for the /// image, pass the identifier of processor to this parameter. /// - fromMemory: Whether this image should be removed from memory storage or not. /// If `false`, the image won't be removed from the memory storage. Default is `true`. /// - fromDisk: Whether this image should be removed from disk storage or not. /// If `false`, the image won't be removed from the disk storage. Default is `true`. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. /// - completionHandler: A closure which is invoked when the cache removing operation finishes. open func removeImage(forKey key: String, processorIdentifier identifier: String = "", fromMemory: Bool = true, fromDisk: Bool = true, callbackQueue: CallbackQueue = .untouch, completionHandler: (() -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) if fromMemory { try? memoryStorage.remove(forKey: computedKey) } if fromDisk { ioQueue.async{ try? self.diskStorage.remove(forKey: computedKey) if let completionHandler = completionHandler { callbackQueue.execute { completionHandler() } } } } else { if let completionHandler = completionHandler { callbackQueue.execute { completionHandler() } } } } func retrieveImage(forKey key: String, options: KingfisherParsedOptionsInfo, callbackQueue: CallbackQueue = .mainCurrentOrAsync, completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?) { // No completion handler. No need to start working and early return. guard let completionHandler = completionHandler else { return } // Try to check the image from memory cache first. if let image = retrieveImageInMemoryCache(forKey: key, options: options) { let image = options.imageModifier?.modify(image) ?? image callbackQueue.execute { completionHandler(.success(.memory(image))) } } else if options.fromMemoryCacheOrRefresh { callbackQueue.execute { completionHandler(.success(.none)) } } else { // Begin to disk search. self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) { result in switch result { case .success(let image): guard let image = image else { // No image found in disk storage. callbackQueue.execute { completionHandler(.success(.none)) } return } let finalImage = options.imageModifier?.modify(image) ?? image // Cache the disk image to memory. // We are passing `false` to `toDisk`, the memory cache does not change // callback queue, we can call `completionHandler` without another dispatch. var cacheOptions = options cacheOptions.callbackQueue = .untouch self.store( finalImage, forKey: key, options: cacheOptions, toDisk: false) { _ in callbackQueue.execute { completionHandler(.success(.disk(finalImage))) } } case .failure(let error): callbackQueue.execute { completionHandler(.failure(error)) } } } } } // MARK: Getting Images /// Gets an image for a given key from the cache, either from memory storage or disk storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`. /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the /// image retrieving operation finishes without problem, an `ImageCacheResult` value /// will be sent to this closure as result. Otherwise, a `KingfisherError` result /// with detail failing reason will be sent. open func retrieveImage(forKey key: String, options: KingfisherOptionsInfo? = nil, callbackQueue: CallbackQueue = .mainCurrentOrAsync, completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?) { retrieveImage( forKey: key, options: KingfisherParsedOptionsInfo(options), callbackQueue: callbackQueue, completionHandler: completionHandler) } func retrieveImageInMemoryCache( forKey key: String, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { let computedKey = key.computedKey(with: options.processor.identifier) return memoryStorage.value(forKey: computedKey, extendingExpiration: options.memoryCacheAccessExtendingExpiration) } /// Gets an image for a given key from the memory storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or /// has already expired, `nil` is returned. open func retrieveImageInMemoryCache( forKey key: String, options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage? { return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options)) } func retrieveImageInDiskCache( forKey key: String, options: KingfisherParsedOptionsInfo, callbackQueue: CallbackQueue = .untouch, completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void) { let computedKey = key.computedKey(with: options.processor.identifier) let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue) loadingQueue.execute { do { var image: KFCrossPlatformImage? = nil if let data = try self.diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) { image = options.cacheSerializer.image(with: data, options: options) } callbackQueue.execute { completionHandler(.success(image)) } } catch { if let error = error as? KingfisherError { callbackQueue.execute { completionHandler(.failure(error)) } } else { assertionFailure("The internal thrown error should be a `KingfisherError`.") } } } } /// Gets an image for a given key from the disk storage. /// /// - Parameters: /// - key: The key used for caching the image. /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. /// - completionHandler: A closure which is invoked when the operation finishes. open func retrieveImageInDiskCache( forKey key: String, options: KingfisherOptionsInfo? = nil, callbackQueue: CallbackQueue = .untouch, completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void) { retrieveImageInDiskCache( forKey: key, options: KingfisherParsedOptionsInfo(options), callbackQueue: callbackQueue, completionHandler: completionHandler) } // MARK: Cleaning /// Clears the memory storage of this cache. @objc public func clearMemoryCache() { try? memoryStorage.removeAll() } /// Clears the disk storage of this cache. This is an async operation. /// /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. /// This `handler` will be called from the main queue. open func clearDiskCache(completion handler: (()->())? = nil) { ioQueue.async { do { try self.diskStorage.removeAll() } catch _ { } if let handler = handler { DispatchQueue.main.async { handler() } } } } /// Clears the expired images from disk storage. This is an async operation. open func cleanExpiredMemoryCache() { memoryStorage.removeExpired() } /// Clears the expired images from disk storage. This is an async operation. @objc func cleanExpiredDiskCache() { cleanExpiredDiskCache(completion: nil) } /// Clears the expired images from disk storage. This is an async operation. /// /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. /// This `handler` will be called from the main queue. open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) { ioQueue.async { do { var removed: [URL] = [] let removedExpired = try self.diskStorage.removeExpiredValues() removed.append(contentsOf: removedExpired) let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues() removed.append(contentsOf: removedSizeExceeded) if !removed.isEmpty { DispatchQueue.main.async { let cleanedHashes = removed.map { $0.lastPathComponent } NotificationCenter.default.post( name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } } if let handler = handler { DispatchQueue.main.async { handler() } } } catch {} } } #if !os(macOS) && !os(watchOS) /// Clears the expired images from disk storage when app is in background. This is an async operation. /// In most cases, you should not call this method explicitly. /// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. @objc public func backgroundCleanExpiredDiskCache() { // if 'sharedApplication()' is unavailable, then return guard let sharedApplication = KingfisherWrapper<UIApplication>.shared else { return } func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) { sharedApplication.endBackgroundTask(task) #if swift(>=4.2) task = UIBackgroundTaskIdentifier.invalid #else task = UIBackgroundTaskInvalid #endif } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = sharedApplication.beginBackgroundTask { endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCache { endBackgroundTask(&backgroundTask!) } } #endif // MARK: Image Cache State /// Returns the cache type for a given `key` and `identifier` combination. /// This method is used for checking whether an image is cached in current cache. /// It also provides information on which kind of cache can it be found in the return value. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: A `CacheType` instance which indicates the cache status. /// `.none` means the image is not in cache or it is already expired. open func imageCachedType( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType { let computedKey = key.computedKey(with: identifier) if memoryStorage.isCached(forKey: computedKey) { return .memory } if diskStorage.isCached(forKey: computedKey) { return .disk } return .none } /// Returns whether the file exists in cache for a given `key` and `identifier` combination. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination. /// /// - Note: /// The return value does not contain information about from which kind of storage the cache matches. /// To get the information about cache type according `CacheType`, /// use `imageCachedType(forKey:processorIdentifier:)` instead. public func isCached( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool { return imageCachedType(forKey: key, processorIdentifier: identifier).cached } /// Gets the hash used as cache file name for the key. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: The hash which is used as the cache file name. /// /// - Note: /// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value /// returned by this method as the cache file name. You can use this value to check and match cache file /// if you need. open func hash( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String { let computedKey = key.computedKey(with: identifier) return diskStorage.cacheFileName(forKey: computedKey) } /// Calculates the size taken by the disk storage. /// It is the total file size of all cached files in the `diskStorage` on disk in bytes. /// /// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue. open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void)) { ioQueue.async { do { let size = try self.diskStorage.totalSize() DispatchQueue.main.async { handler(.success(size)) } } catch { if let error = error as? KingfisherError { DispatchQueue.main.async { handler(.failure(error)) } } else { assertionFailure("The internal thrown error should be a `KingfisherError`.") } } } } /// Gets the cache path for the key. /// It is useful for projects with web view or anyone that needs access to the local file path. /// /// i.e. Replacing the `<img src='path_for_key'>` tag in your HTML. /// /// - Parameters: /// - key: The key used for caching the image. /// - identifier: Processor identifier which used for this image. Default is the `identifier` of /// `DefaultImageProcessor.default`. /// - Returns: The disk path of cached image under the given `key` and `identifier`. /// /// - Note: /// This method does not guarantee there is an image already cached in the returned path. It just gives your /// the path that the image should be, if it exists in disk storage. /// /// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk. open func cachePath( forKey key: String, processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String { let computedKey = key.computedKey(with: identifier) return diskStorage.cacheFileURL(forKey: computedKey).path } } extension Dictionary { func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] { return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } } } #if !os(macOS) && !os(watchOS) // MARK: - For App Extensions extension UIApplication: KingfisherCompatible { } extension KingfisherWrapper where Base: UIApplication { public static var shared: UIApplication? { let selector = NSSelectorFromString("sharedApplication") guard Base.responds(to: selector) else { return nil } return Base.perform(selector).takeUnretainedValue() as? UIApplication } } #endif extension String { func computedKey(with identifier: String) -> String { if identifier.isEmpty { return self } else { return appending("@\(identifier)") } } } extension ImageCache { /// Creates an `ImageCache` with a given `name`, cache directory `path` /// and a closure to modify the cache directory. /// /// - Parameters: /// - name: The name of cache object. It is used to setup disk cache directories and IO queue. /// You should not use the same `name` for different caches, otherwise, the disk storage would /// be conflicting to each other. /// - path: Location of cache URL on disk. It will be internally pass to the initializer of `DiskStorage` as the /// disk cache directory. /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates /// the final disk cache path. You could use it to fully customize your cache path. /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given /// path. @available(*, deprecated, message: "Use `init(name:cacheDirectoryURL:diskCachePathClosure:)` instead", renamed: "init(name:cacheDirectoryURL:diskCachePathClosure:)") public convenience init( name: String, path: String?, diskCachePathClosure: DiskCachePathClosure? = nil) throws { let directoryURL = path.flatMap { URL(string: $0) } try self.init(name: name, cacheDirectoryURL: directoryURL, diskCachePathClosure: diskCachePathClosure) } }
mit
fcc850c1634380414673aa68f5d62007
43.959476
144
0.626574
5.244855
false
false
false
false
bartekchlebek/Stenotype
Demo/Demo/AppDelegate.swift
1
519
import Cocoa import Stenotype struct Size { var width = 0.0 } let log = LoggersManager() @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(aNotification: NSNotification) { var c1 = Logger() var c2 = c1 c2.shouldDisplayDate = false c2.minimumLevelToLog = .Warning log.addLogger(c1) log.addLogger(c2) log.error("ERROR") log.verbose { return "VERBOSE" } } }
mit
ab223b635183f572f7df9732f74db4d5
16.3
69
0.672447
3.902256
false
false
false
false
AfricanSwift/TUIKit
TUIKit/Source/Ansi/Ansi+Terminal.swift
1
9364
// // File: Ansi+Terminal.swift // Created by: African Swift import Darwin import Foundation // MARK: - // MARK: Command, fileDescriptor, currentTTY - public extension Ansi { public enum Terminal { // public enum Program // { // // mac Terminal "Apple_Terminal" // // mac iTerm "iTerm.app" // case macTerminal, iTerm, linuxXterm // } public static func hasUnicodeSupport() -> Bool { let value = [getenv("LANG"), getenv("LC_CTYPE"), getenv("LC_ALL")] .flatMap { return $0 == nil ? nil : $0 } .map { String(cString: $0) }.first ?? "" return value.lowercased().contains("utf") } public static func bell() { Ansi("\(Ansi.C0.BEL)").stdout() } /// Soft Terminal Reset (DECSTR) public static func softReset() { Ansi("\(Ansi.C1.CSI)!p").stdout() } /// Hard Terminal Reset (RIS) public static func hardReset() { Ansi("\(Ansi.C0.ESC)c").stdout() } /// Adjustments (DECALN) /// /// The terminal has a screen alignment pattern that service personnel use to /// adjust the screen. You can display the screen alignment pattern with the /// DECALN sequence. This sequence fills the screen with uppercase E's. public static func testPattern() { Ansi("\(Ansi.C0.ESC)#8").stdout() } /// Terminal Ansi command and expected response /// /// ```` /// let cursorReport = Ansi.Terminal.Command( /// request: Ansi.Cursor.Report.position(), /// response: "\u{1B}[#;#R") /// ```` public struct Command { var request: Ansi var response: String } /// Retrieve file descriptor /// /// - parameters: /// - device: UnsafeMutablePointer<CChar> /// - returns: CInt private static func fileDescriptor(_ device: UnsafeMutablePointer<CChar>) -> CInt { var descriptor: Int32 repeat { descriptor = open(device, O_RDWR | O_NOCTTY) } while descriptor == -1 && errno == EINTR return descriptor } /// File descriptor for current TTY /// /// - returns: Int32 internal static func currentTTY() -> Int32 { if let device = ttyname(STDIN_FILENO) { return Ansi.Terminal.fileDescriptor(device) } else if let device = ttyname(STDOUT_FILENO) { return Ansi.Terminal.fileDescriptor(device) } else if let device = ttyname(STDERR_FILENO) { return Ansi.Terminal.fileDescriptor(device) } return -1 } } } // REPLACE with new termios code // MARK: - // MARK: readValue - public extension Ansi.Terminal { /// Read value from TTY /// /// - parameters: /// - tty: Int32 /// - returns: Int32 internal static func readValue(tty: Int32) -> Int32 { // Maximum time (ms) to allow read to block let maximumBlockDuration = 0.2 var buffer = [UInt8](repeating: 0, count: 4) var n: ssize_t let RD_EOF = Int32(-1) let RD_EIO = Int32(-2) let start = Date().timeIntervalSince1970 // Disable read blocking var flags = Darwin.fcntl(tty, F_GETFL, 0) _ = Darwin.fcntl(tty, F_SETFL, flags | O_NONBLOCK) // Restore flags on exit defer { _ = Darwin.fcntl(tty, F_SETFL, flags) } while true { n = Darwin.read(tty, &buffer, 1) if n > ssize_t(0) { return Int32(buffer[0]) } else if n == ssize_t(0) { print("RD_EOF") return RD_EOF } else if n != ssize_t(-1) { print("RD_EIOa") return RD_EIO } else if errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK { print("RD_EIOb") return RD_EIO } // Precaution -- prevent blocking for longer than maximumBlockDuration if (Date().timeIntervalSince1970 - start) * 1000 > maximumBlockDuration { return Int32.max } } } } // MARK: - // MARK: saveSettings, enableNonCanon, restoreSettings - public extension Ansi.Terminal { /// Save current terminal settings /// /// - parameters: /// - tty: Int32 /// - returns: termios? internal static func saveSettings(tty: Int32) -> termios? { var result: Int32 var settings = termios.init() repeat { result = tcgetattr(tty, &settings) } while result == -1 && errno == EINTR return result == -1 ? nil : settings } /// Set termios control chars /// /// - parameters: /// - settings: inout termios /// - index: Int32 /// - value: UInt8 internal static func setc_cc(settings: inout termios, index: Int32, value: UInt8) { withUnsafeMutablePointer(&settings.c_cc) { tuplePointer -> Void in let c_ccPointer = UnsafeMutablePointer<cc_t>(tuplePointer) c_ccPointer[Int(index)] = value } } /// Enabled Non Canonical Input (Disable ICANON, ECHO & CREAD) /// /// - parameters: /// - tty: Int32 /// - settings: inout termios /// - returns: Bool internal static func enableNonCanon(tty: Int32, settings: inout termios) -> Bool { settings.c_lflag &= ~UInt(ICANON) settings.c_lflag &= ~UInt(ECHO) settings.c_cflag &= ~UInt(CREAD) Ansi.Terminal.setc_cc(settings: &settings, index: VMIN, value: 1) Ansi.Terminal.setc_cc(settings: &settings, index: VTIME, value: 1) // Set modified settings var result: Int32 repeat { result = tcsetattr(tty, TCSANOW, &settings) } while result == -1 && errno == EINTR return result == -1 ? false : true } /// Restore TTY settings /// /// - parameters: /// - tty: Int32 /// - settings: inout termios internal static func restoreSettings(tty: Int32, settings: inout termios) { // Restore saved terminal settings` var result: Int32 repeat { result = tcsetattr(tty, TCSANOW, &settings) } while result == -1 && errno == EINTR } } // MARK: - // MARK: readResponse & responseTTY - public extension Ansi.Terminal { /// Read TTY response /// /// - parameters: /// - tty: Int32 /// - expected: String /// - returns: String? private static func readResponse(tty: Int32, expected: String) -> String? { var result: Int32 = -1 let values: [Character] = expected.characters.map{$0} guard let terminator = values.last else { return nil } var index = 0 var reply = "" var ch = Character(" ") repeat { result = Ansi.Terminal.readValue(tty: tty) if result == Int32.max { return nil } ch = Character(UnicodeScalar(Int(result))) if index == 0 && ch != values[0] { return nil } reply += String(ch) index += 1 } while ch != terminator return reply.characters.count == 0 ? nil : reply } /// Issue a command to TTY and await a response /// /// - parameters: /// - command: Ansi.Terminal.Command /// - returns: String? internal static func responseTTY(command: Command) -> String? { // Save the current error number var savedError: Int32 = errno var result: Int32 = -1 let tty = Ansi.Terminal.currentTTY() // Inappropriate TTY if tty == -1 { errno = savedError return nil } // Save the current state guard var currentState = Ansi.Terminal.saveSettings(tty: tty) else { return nil } // Restore current state on completion defer { Ansi.Terminal.restoreSettings(tty: tty, settings: &currentState) errno = savedError } // Enable temporary state with non canonical input var temporaryState = currentState guard Ansi.Terminal.enableNonCanon(tty: tty, settings: &temporaryState) == true else { return nil } // Submit ansi request and flush standard out command.request.stdout() Ansi.flush() // Nominal delay, without which buffer overruns occur for consecutive requests. Thread.sleep(forTimeInterval: 0.02) // Retrieve response return Ansi.Terminal.readResponse(tty: tty, expected: command.response) } } public extension Ansi.Terminal { internal static func readAll(fd: CInt) -> String { var buffer = [UInt8](repeating: 0, count: 1024) var usedBytes = 0 while true { print("here") let readResult: ssize_t = buffer.withUnsafeMutableBufferPointer { value in guard let address = value.baseAddress else { print("12345") return ssize_t.max } let ptr = UnsafeMutablePointer<Void>(address + usedBytes) return read(fd, ptr, size_t(buffer.count - usedBytes)) } if readResult > 0 { usedBytes += readResult // print("readResult > 0", usedBytes, readResult) continue } if readResult == 0 { // print("readResult == 0", usedBytes, readResult) break } print("precondition") preconditionFailure("read() failed") } // return (0..<usedBytes) // .map { String(UnicodeScalar(Int(buffer[$0]))) } // .joined(separator: "") // return String(cString: buffer[0..<usedBytes], encoding: .utf8) return String._fromCodeUnitSequenceWithRepair( UTF8.self, input: buffer[0..<usedBytes]).0 } }
mit
496f662da52aced01bcda961f3513b59
24.445652
85
0.587142
3.934454
false
false
false
false
kak-ios-codepath/everest
Everest/Everest/Models/Category.swift
1
691
// // Category.swift // Everest // // Created by user on 10/21/17. // Copyright © 2017 Kavita Gaitonde. All rights reserved. // import UIKit import SwiftyJSON import AFNetworking class Category { var title: String! var acts: [Act]! var imageUrl: String! init(categoryTitle: String, category: NSDictionary) { self.title = categoryTitle self.acts = category.flatMap { Act(id: $0 as! String, category: categoryTitle, title: $1 as! String, score: ACT_DEFAULT_SCORE) } FireBaseManager.shared.fetchCategoryImageUrl(title: title) { (url, error) in if error == nil { self.imageUrl = url } } } }
apache-2.0
3c55a89091387f1f26edf84e5c0453f0
24.555556
136
0.62029
3.72973
false
false
false
false
zxpLearnios/MyProject
test_projectDemo1/PhotoBrowser/更好的图片浏览器/MyPhotoBrowserScrollView.swift
1
8481
// // xxx.swift // test_projectDemo1 // // Created by Jingnan Zhang on 2017/2/23. // Copyright © 2017年 Jingnan Zhang. All rights reserved. /* 1. 图片浏览器里用到的UIscrollview,利用其强大的功能实现图片的缩放 2. UIScrollView有苹果自带的api,进行图片的缩放非常简单,只需设置scrollView.minimumZoomScale = 0.5; // 设置最小缩放系数scrollView.maximumZoomScale = 2.0; //设置最大缩放系数 及实现代理方法function viewForZoomingInScrollView和scrollViewDidZoom即可 3. 它的tag值在cell里赋的 4. 将之禁止与用户交互,这样将它加入cell后,此cell的TableView或COllectionView就可以被点击,可以相应自身的didSelectRowAt、didSelectItemAt了。 5. 在drawRect里加单击、双击手势或者在touchBegan里根据单击的count数类判断是单击还是双击 6. CGAffineTransformMakeRotation(CGFloat angle)不同的是这个方法可以叠加其他CGAffineTransform效果 7. 此时不管在谁上面加旋转手势都是没用的 { layoutSubviews方法:这个方法,默认没有做任何事情,需要子类进行重写 setNeedsLayout方法: 标记为需要重新布局,异步调用layoutIfNeeded刷新布局,不立即刷新,但layoutSubviews一定会被调用 layoutIfNeeded方法:如果,有需要刷新的标记,立即调用layoutSubviews进行布局(如果没有标记,不会调用layoutSubviews) } */ import UIKit @objc protocol MyPhotoBrowserScrollViewDelegate { @objc optional func didClickPhotoBrowserScrollView(_ scrollView:MyPhotoBrowserScrollView) } class MyPhotoBrowserScrollView: UIScrollView, UIScrollViewDelegate { var imgView = UIImageView() weak var photoBrowserScrollViewDelegate:MyPhotoBrowserScrollViewDelegate! private var originImageViewFrame = CGRect.zero // 记录图片原来的frame,以便在缩放后的恢复 private let animateTime = 0.2 private var lastRoration:CGFloat = 0.0 var image:UIImage! { didSet{ addImageView() } } override func layoutSubviews() { super.layoutSubviews() self.delegate = self self.minimumZoomScale = 0.5 //设置最小缩放系数 self.maximumZoomScale = 2.0 //设置最大缩放系数 self.isMultipleTouchEnabled = true // self.isUserInteractionEnabled = true self.backgroundColor = UIColor.clear self.isScrollEnabled = true } override func draw(_ rect: CGRect) { super.draw(rect) // 单击 双击 手势 let tapDouble = UITapGestureRecognizer.init(target: self, action: #selector(doubleTapAction)) tapDouble.numberOfTapsRequired = 2 let tapSingle = UITapGestureRecognizer.init(target: self, action: #selector(singleTapAction)) //这行很关键,意思是只有当没有检测到doubleTapGestureRecognizer 或者 检测doubleTapGestureRecognizer失败,singleTapGestureRecognizer才有效 tapSingle.require(toFail: tapDouble) // self.addGestureRecognizer(tapSingle) // self.addGestureRecognizer(tapDouble) } // ------------------ public ---------------- // // MARK: 复原 func recoveryZoomScale() { if self.zoomScale != 1{ self.zoomScale = 1.0 } self.contentSize = CGSize.zero // 不要亦可 imgView.frame = originImageViewFrame } // ------------------ private ---------------- // private func addImageView(){ imgView.image = image var imgVW:CGFloat = 0 var imgVH:CGFloat = 0 // 根据图片尺寸确定ImgV的大小 let imageW = image.size.width let imageH = image.size.height if imageW >= imageH { // 图片宽 >= 高 if imageW > self.frame.width { // 图片比屏幕宽 imgVW = self.frame.width }else{ imgVW = imageW // 此时按原图展示 } imgVH = imgVW / (imageW / imageH) }else{ // 图片宽 < 高 if imageH > self.frame.height { // 图片比屏幕高 imgVH = self.frame.height }else{ imgVH = imageH // 此时按原图展示 } imgVW = imgVH / (imageH / imageW) } imgView.bounds = CGRect(x: 0, y: 0, width: imgVW, height: imgVH) imgView.center = CGPoint.init(x: self.frame.width / 2, y: self.frame.height / 2) self.addSubview(imgView) originImageViewFrame = imgView.frame } // MARK: 单击 @objc private func singleTapAction(){ if photoBrowserScrollViewDelegate != nil { photoBrowserScrollViewDelegate.didClickPhotoBrowserScrollView!(self) } } // MARK: 双击 @objc private func doubleTapAction(){ if self.zoomScale != 1 { // 处于放大或缩小状态时,都复原 UIView.animate(withDuration: animateTime, animations: { self.zoomScale = 1 }) }else{ // 让其放大 UIView.animate(withDuration: animateTime, animations: { self.zoomScale = self.maximumZoomScale }) } } // MARK: 旋转 // @objc private func rotateAction(rotate:UIRotationGestureRecognizer){ // // let absRotation = Double(abs(rotate.rotation)) // // var endPositin = 0.0 // 图片旋转后,停留的角度位置 // let t = CGAffineTransform.identity // // // if rotate.state == .began || rotate.state == .changed{ // // imgView.transform = t.rotated(by: rotate.rotation) // }else if rotate.state == .ended || rotate.state == .cancelled{ //// if absRotation % (M_PI * 2) >= 0.0 && absRotation <= M_PI_4 { //// endPositin = //// } // // lastRoration += rotate.rotation // } // // // } // MARK: 单击、双击手势 internal override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = ((touches as NSSet).anyObject()) as! UITouch let count = touch.tapCount if count == 1{ // 取消双击 NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(doubleTapAction), object: nil) // 开始单击 这里必须延迟一会 self.perform(#selector(singleTapAction), with: nil, afterDelay: 0.1) }else if count == 2{ // 取消单击 NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(singleTapAction), object: nil) // 开始双击 self.perform(#selector(doubleTapAction), with: nil, afterDelay: 0) } } // ---------------------UIScrollViewDelegate-------------------- // MARK: 当scrollView缩放时,调用该方法。在缩放过程中,缩放过程中动态计算图片的frame,会多次调 func scrollViewDidZoom(_ scrollView: UIScrollView) { let photoX:CGFloat = (self.frame.width - imgView.frame.width) / 2 let photoY:CGFloat = (self.frame.height - imgView.frame.height) / 2 var photoF:CGRect = imgView.frame if photoX > 0 { photoF.origin.x = photoX }else { photoF.origin.x = 0 } if (photoY > 0) { photoF.origin.y = photoY }else { photoF.origin.y = 0 } imgView.frame = photoF } // MARK: 返回将要缩放的UIView对象。要执行多次 func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imgView } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { self.isScrollEnabled = true } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { self.isUserInteractionEnabled = true // scrollView.setZoomScale(scale, animated: false) } }
mit
b25ac0329e2268007f620e84b98b8323
29.904564
136
0.578545
4.285386
false
false
false
false
MrZoidberg/metapp
metapp/metapp/AppDelegate.swift
1
5136
// // AppDelegate.swift // metapp // // Created by Mikhail Merkulov on 9/22/16. // Copyright © 2016 ZoidSoft. All rights reserved. // import UIKit import Swinject import SwinjectStoryboard import XCGLogger import Carpaccio import RealmSwift typealias RealmFactory = () -> Realm func synchronized(_ lock: AnyObject, _ body: () -> ()) { objc_sync_enter(lock) defer { objc_sync_exit(lock) } body() } func synchronized<T>(_ lockObj: AnyObject!, _ closure: () throws -> T) rethrows -> T { objc_sync_enter(lockObj) defer { objc_sync_exit(lockObj) } return try closure() } extension SwinjectStoryboard { class func setup() { defaultContainer.registerForStoryboard(MainViewController.self) {r, c in c.viewModel = MainViewModel(photoRequestorFactory: { r.resolve(MAPhotoRequestor.self)! }, analyzer: r.resolve(MAMetadataAnalyzer.self)!, realm: r.resolve(Realm.self)!, log: r.resolve(XCGLogger.self) ) } defaultContainer.register(XCGLogger.self) { _ in let log = XCGLogger.default log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true) let emojiLogFormatter = PrePostFixLogFormatter() emojiLogFormatter.apply(prefix: "🗯", postfix: "", to: .verbose) emojiLogFormatter.apply(prefix: "🔹", postfix: "", to: .debug) emojiLogFormatter.apply(prefix: "ℹ️", postfix: "", to: .info) emojiLogFormatter.apply(prefix: "⚠️", postfix: "", to: .warning) emojiLogFormatter.apply(prefix: "‼️", postfix: "", to: .error) emojiLogFormatter.apply(prefix: "💣", postfix: "", to: .severe) log.formatters = [emojiLogFormatter] return log }.inObjectScope(ObjectScope.container) defaultContainer.register(MAPhotoRequestor.self) {r in MACachedPhotoRequestor(log: r.resolve(XCGLogger.self)) }.inObjectScope(ObjectScope.container) defaultContainer.register(ImageMetadataLoader.self) {r in RAWImageMetadataLoader() } defaultContainer.register(MAMetadataAnalyzer.self) {r in MABgMetadataAnalyzer(imageMetadataLoaderFactory: { r.resolve(ImageMetadataLoader.self)!}, realm:{ r.resolve(Realm.self)!}, log: r.resolve(XCGLogger.self)) }.inObjectScope(ObjectScope.container) defaultContainer.register(Realm.Configuration.self) { _ in // not really necessary if you stick to the defaults everywhere return Realm.Configuration() } defaultContainer.register(Realm.self) { r in try! Realm(configuration: r.resolve(Realm.Configuration.self)!) } defaultContainer.register(PhotoSet.self) { r in return MAPhotoSet((r.resolve(Realm.self)?.object(ofType: MAPhotoSetRepresentation.self, forPrimaryKey: PhotoSetId.main.rawValue)) ?? MAPhotoSetRepresentation(), realm: { r.resolve(Realm.self)!}) }.inObjectScope(ObjectScope.container) } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mpl-2.0
1ee9648849aecb868bdccbe3a64526b2
39.912
279
0.684396
4.713364
false
false
false
false
bdotdub/TriplePlay
tvOS/Timehop/Timehop/AuthViewController.swift
1
3044
// // AuthViewController.swift // Timehop // // Created by Benny Wong on 11/4/15. // Copyright © 2015 Benny Wong. All rights reserved. // import UIKit import CocoaAsyncSocket class AuthViewController: UIViewController, NSNetServiceBrowserDelegate, NSNetServiceDelegate, GCDAsyncSocketDelegate { var browser = NSNetServiceBrowser() var service: NSNetService? var socket: GCDAsyncSocket? var sockets = [GCDAsyncSocket]() override func viewDidLoad() { // Start searching for services self.browser.delegate = self self.browser.searchForServicesOfType("_timehop_auth._tcp", inDomain: "local.") } // mark: NSNetServiceBrowserDelegate func netServiceBrowser(browser: NSNetServiceBrowser, didFindService service: NSNetService, moreComing: Bool) { // Hold a strong reference to service to it isn't dealloc-ed self.service = service self.service!.delegate = self self.service!.resolveWithTimeout(30) } // mark: NSNetServiceDelegate func netServiceDidResolveAddress(sender: NSNetService) { self.socket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue()) do { // Connect to try self.socket!.connectToAddress(sender.addresses![0]) } catch { self.presentError("Could not connect to service: \(sender.name)") } } func netService(sender: NSNetService, didNotResolve errorDict: [String : NSNumber]) { self.presentError("Could not resolve service: \(sender.name)") } // GCDAsyncSockerDelegate func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) { // Once connected, let's start reading data! sock.readDataWithTimeout(-1, tag: 0) } func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) { // Read data from iOS service - in this case, an authentication token. let message = String(data: data!, encoding: NSUTF8StringEncoding) // Show the token let controller = UIAlertController(title: "Got token!", message: message!, preferredStyle: .Alert) controller.addAction(UIAlertAction(title: "OK", style: .Default) { _ in controller.dismissViewControllerAnimated(true, completion: nil) self.performSegueWithIdentifier("LoggedIn", sender: self) }) self.presentViewController(controller, animated: true, completion: nil) // Disconnect sock.disconnect() self.browser.stop() } // Utility func presentError(message: String) { let controller = UIAlertController(title: "An Error Occurred", message: message, preferredStyle: .Alert) controller.addAction(UIAlertAction(title: "OK", style: .Default) { _ in controller.dismissViewControllerAnimated(true, completion: nil) }) self.presentViewController(controller, animated: true, completion: nil) } }
mit
f5c3f63cb584f8a5f05d82e1868a78c6
35.22619
119
0.664804
4.876603
false
false
false
false
erinshihshih/ETripTogether
Pods/LiquidFloatingActionButton/Pod/Classes/LiquittableCircle.swift
5
2233
// // LiquittableCircle.swift // LiquidLoading // // Created by Takuma Yoshida on 2015/08/17. // Copyright (c) 2015年 yoavlt. All rights reserved. // import Foundation import UIKit public class LiquittableCircle : UIView { var points: [CGPoint] = [] var radius: CGFloat { didSet { self.frame = CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius) setup() } } var color: UIColor = UIColor.redColor() { didSet { setup() } } override public var center: CGPoint { didSet { self.frame = CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius) setup() } } let circleLayer = CAShapeLayer() init(center: CGPoint, radius: CGFloat, color: UIColor) { let frame = CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius) self.radius = radius self.color = color super.init(frame: frame) setup() self.layer.addSublayer(circleLayer) self.opaque = false } init() { self.radius = 0 super.init(frame: CGRectZero) setup() self.layer.addSublayer(circleLayer) self.opaque = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { self.frame = CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius) drawCircle() } func drawCircle() { let bezierPath = UIBezierPath(ovalInRect: CGRect(origin: CGPointZero, size: CGSize(width: radius * 2, height: radius * 2))) draw(bezierPath) } func draw(path: UIBezierPath) -> CAShapeLayer { circleLayer.lineWidth = 3.0 circleLayer.fillColor = self.color.CGColor circleLayer.path = path.CGPath return circleLayer } func circlePoint(rad: CGFloat) -> CGPoint { return CGMath.circlePoint(center, radius: radius, rad: rad) } public override func drawRect(rect: CGRect) { drawCircle() } }
mit
ec65675baf22c5cb28475b826448f3d8
26.219512
131
0.585388
4.170093
false
false
false
false
jie-json/swift-corelibs-foundation-master
Foundation/NSXMLParser.swift
1
13368
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // public enum NSXMLParserExternalEntityResolvingPolicy : UInt { case ResolveExternalEntitiesNever // default case ResolveExternalEntitiesNoNetwork case ResolveExternalEntitiesSameOriginOnly //only applies to NSXMLParser instances initialized with -initWithContentsOfURL: case ResolveExternalEntitiesAlways } public class NSXMLParser : NSObject { // initializes the parser with the specified URL. public convenience init?(contentsOfURL url: NSURL) { NSUnimplemented() } // create the parser from data public init(data: NSData) { NSUnimplemented() } //create a parser that incrementally pulls data from the specified stream and parses it. public convenience init(stream: NSInputStream) { NSUnimplemented() } public weak var delegate: NSXMLParserDelegate? public var shouldProcessNamespaces: Bool public var shouldReportNamespacePrefixes: Bool //defaults to NSXMLNodeLoadExternalEntitiesNever public var externalEntityResolvingPolicy: NSXMLParserExternalEntityResolvingPolicy public var allowedExternalEntityURLs: Set<NSURL>? // called to start the event-driven parse. Returns YES in the event of a successful parse, and NO in case of error. public func parse() -> Bool { NSUnimplemented() } // called by the delegate to stop the parse. The delegate will get an error message sent to it. public func abortParsing() { NSUnimplemented() } /*@NSCopying*/ public var parserError: NSError? { NSUnimplemented() } // can be called after a parse is over to determine parser state. //Toggles between disabling external entities entirely, and the current setting of the 'externalEntityResolvingPolicy'. //The 'externalEntityResolvingPolicy' property should be used instead of this, unless targeting 10.9/7.0 or earlier public var shouldResolveExternalEntities: Bool // Once a parse has begun, the delegate may be interested in certain parser state. These methods will only return meaningful information during parsing, or after an error has occurred. public var publicID: String? { NSUnimplemented() } public var systemID: String? { NSUnimplemented() } public var lineNumber: Int { NSUnimplemented() } public var columnNumber: Int { NSUnimplemented() } } /* For the discussion of event methods, assume the following XML: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type='text/css' href='cvslog.css'?> <!DOCTYPE cvslog SYSTEM "cvslog.dtd"> <cvslog xmlns="http://xml.apple.com/cvslog"> <radar:radar xmlns:radar="http://xml.apple.com/radar"> <radar:bugID>2920186</radar:bugID> <radar:title>API/NSXMLParser: there ought to be an NSXMLParser</radar:title> </radar:radar> </cvslog> */ // The parser's delegate is informed of events through the methods in the NSXMLParserDelegateEventAdditions category. public protocol NSXMLParserDelegate : class { // Document handling methods func parserDidStartDocument(parser: NSXMLParser) // sent when the parser begins parsing of the document. func parserDidEndDocument(parser: NSXMLParser) // sent when the parser has completed parsing. If this is encountered, the parse was successful. // DTD handling methods for various declarations. func parser(parser: NSXMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) func parser(parser: NSXMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) func parser(parser: NSXMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) func parser(parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) func parser(parser: NSXMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) func parser(parser: NSXMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) // sent when the parser finds an element start tag. // In the case of the cvslog tag, the following is what the delegate receives: // elementName == cvslog, namespaceURI == http://xml.apple.com/cvslog, qualifiedName == cvslog // In the case of the radar tag, the following is what's passed in: // elementName == radar, namespaceURI == http://xml.apple.com/radar, qualifiedName == radar:radar // If namespace processing >isn't< on, the xmlns:radar="http://xml.apple.com/radar" is returned as an attribute pair, the elementName is 'radar:radar' and there is no qualifiedName. func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) // sent when an end tag is encountered. The various parameters are supplied as above. func parser(parser: NSXMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) // sent when the parser first sees a namespace attribute. // In the case of the cvslog tag, before the didStartElement:, you'd get one of these with prefix == @"" and namespaceURI == @"http://xml.apple.com/cvslog" (i.e. the default namespace) // In the case of the radar:radar tag, before the didStartElement: you'd get one of these with prefix == @"radar" and namespaceURI == @"http://xml.apple.com/radar" func parser(parser: NSXMLParser, didEndMappingPrefix prefix: String) // sent when the namespace prefix in question goes out of scope. func parser(parser: NSXMLParser, foundCharacters string: String) // This returns the string of the characters encountered thus far. You may not necessarily get the longest character run. The parser reserves the right to hand these to the delegate as potentially many calls in a row to -parser:foundCharacters: func parser(parser: NSXMLParser, foundIgnorableWhitespace whitespaceString: String) // The parser reports ignorable whitespace in the same way as characters it's found. func parser(parser: NSXMLParser, foundProcessingInstructionWithTarget target: String, data: String?) // The parser reports a processing instruction to you using this method. In the case above, target == @"xml-stylesheet" and data == @"type='text/css' href='cvslog.css'" func parser(parser: NSXMLParser, foundComment comment: String) // A comment (Text in a <!-- --> block) is reported to the delegate as a single string func parser(parser: NSXMLParser, foundCDATA CDATABlock: NSData) // this reports a CDATA block to the delegate as an NSData. func parser(parser: NSXMLParser, resolveExternalEntityName name: String, systemID: String?) -> NSData? // this gives the delegate an opportunity to resolve an external entity itself and reply with the resulting data. func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) // ...and this reports a fatal error to the delegate. The parser will stop parsing. func parser(parser: NSXMLParser, validationErrorOccurred validationError: NSError) } extension NSXMLParserDelegate { func parserDidStartDocument(parser: NSXMLParser) { } func parserDidEndDocument(parser: NSXMLParser) { } func parser(parser: NSXMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(parser: NSXMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) { } func parser(parser: NSXMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) { } func parser(parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) { } func parser(parser: NSXMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) { } func parser(parser: NSXMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { } func parser(parser: NSXMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { } func parser(parser: NSXMLParser, didEndMappingPrefix prefix: String) { } func parser(parser: NSXMLParser, foundCharacters string: String) { } func parser(parser: NSXMLParser, foundIgnorableWhitespace whitespaceString: String) { } func parser(parser: NSXMLParser, foundProcessingInstructionWithTarget target: String, data: String?) { } func parser(parser: NSXMLParser, foundComment comment: String) { } func parser(parser: NSXMLParser, foundCDATA CDATABlock: NSData) { } func parser(parser: NSXMLParser, resolveExternalEntityName name: String, systemID: String?) -> NSData? { return nil } func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { } func parser(parser: NSXMLParser, validationErrorOccurred validationError: NSError) { } } // If validation is on, this will report a fatal validation error to the delegate. The parser will stop parsing. public let NSXMLParserErrorDomain: String = "NSXMLParserErrorDomain" // for use with NSError. // Error reporting public enum NSXMLParserError : Int { case InternalError case OutOfMemoryError case DocumentStartError case EmptyDocumentError case PrematureDocumentEndError case InvalidHexCharacterRefError case InvalidDecimalCharacterRefError case InvalidCharacterRefError case InvalidCharacterError case CharacterRefAtEOFError case CharacterRefInPrologError case CharacterRefInEpilogError case CharacterRefInDTDError case EntityRefAtEOFError case EntityRefInPrologError case EntityRefInEpilogError case EntityRefInDTDError case ParsedEntityRefAtEOFError case ParsedEntityRefInPrologError case ParsedEntityRefInEpilogError case ParsedEntityRefInInternalSubsetError case EntityReferenceWithoutNameError case EntityReferenceMissingSemiError case ParsedEntityRefNoNameError case ParsedEntityRefMissingSemiError case UndeclaredEntityError case UnparsedEntityError case EntityIsExternalError case EntityIsParameterError case UnknownEncodingError case EncodingNotSupportedError case StringNotStartedError case StringNotClosedError case NamespaceDeclarationError case EntityNotStartedError case EntityNotFinishedError case LessThanSymbolInAttributeError case AttributeNotStartedError case AttributeNotFinishedError case AttributeHasNoValueError case AttributeRedefinedError case LiteralNotStartedError case LiteralNotFinishedError case CommentNotFinishedError case ProcessingInstructionNotStartedError case ProcessingInstructionNotFinishedError case NotationNotStartedError case NotationNotFinishedError case AttributeListNotStartedError case AttributeListNotFinishedError case MixedContentDeclNotStartedError case MixedContentDeclNotFinishedError case ElementContentDeclNotStartedError case ElementContentDeclNotFinishedError case XMLDeclNotStartedError case XMLDeclNotFinishedError case ConditionalSectionNotStartedError case ConditionalSectionNotFinishedError case ExternalSubsetNotFinishedError case DOCTYPEDeclNotFinishedError case MisplacedCDATAEndStringError case CDATANotFinishedError case MisplacedXMLDeclarationError case SpaceRequiredError case SeparatorRequiredError case NMTOKENRequiredError case NAMERequiredError case PCDATARequiredError case URIRequiredError case PublicIdentifierRequiredError case LTRequiredError case GTRequiredError case LTSlashRequiredError case EqualExpectedError case TagNameMismatchError case UnfinishedTagError case StandaloneValueError case InvalidEncodingNameError case CommentContainsDoubleHyphenError case InvalidEncodingError case ExternalStandaloneEntityError case InvalidConditionalSectionError case EntityValueRequiredError case NotWellBalancedError case ExtraContentError case InvalidCharacterInEntityError case ParsedEntityRefInInternalError case EntityRefLoopError case EntityBoundaryError case InvalidURIError case URIFragmentError case NoDTDError case DelegateAbortedParseError }
apache-2.0
5e38790f0112e44382ad8d9a2de0559a
46.404255
248
0.761969
5.279621
false
false
false
false
alexburtnik/ABSwiftExtensions
ABSwiftExtensions/Classes/Photos/Photos.swift
1
2505
// // Photos+Extensions.swift // Croppy // // Created by Alex Burtnik on 7/3/17. // Copyright © 2017 alexburtnik. All rights reserved. // import Foundation import UIKit import Photos public extension PHAssetCollection { public var photosCount: Int { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue) let result = PHAsset.fetchAssets(in: self, options: fetchOptions) return result.count } public func fetchLastPhoto(resizeTo size: CGSize?, imageCallback: @escaping (UIImage?) -> Void) { let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] fetchOptions.fetchLimit = 1 let fetchResult = PHAsset.fetchAssets(in: self, options: fetchOptions) if let asset = fetchResult.firstObject { let manager = PHImageManager.default() let targetSize = size == nil ? CGSize(width: asset.pixelWidth, height: asset.pixelHeight) : size! manager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: nil, resultHandler: { image, info in imageCallback(image) }) } else { imageCallback(nil) } } } public extension PHAsset { public func image(size: CGSize) -> UIImage? { let manager = PHImageManager.default() let options = PHImageRequestOptions() options.isSynchronous = true var result: UIImage? manager.requestImage(for: self, targetSize: size, contentMode: .aspectFit, options: options) { image, info in result = image } return result } public func originalImage() -> UIImage? { var result: UIImage? let manager = PHImageManager.default() let options = PHImageRequestOptions() options.version = .original options.isSynchronous = true manager.requestImageData(for: self, options: options) { data, _, _, _ in if let data = data { result = UIImage(data: data) } } return result } }
mit
c0ad93eef377837e3a407d736c96d2a7
31.947368
109
0.561502
5.350427
false
false
false
false
k-ori/algorithm-playground
src/Set.swift
1
4976
// // Set.swift // // // Created by kori on 8/10/16. // // import Foundation // Intersection of two sorted arrays let ar1 = [1, 12, 15, 19, 20, 21] let ar2 = [2, 15, 17, 19, 19, 21, 25, 27] func intersection(ar1: [Int], _ ar2: [Int]) -> Set<Int> { var i1 = 0 var i2 = 0 var intersection = Set<Int>() while(i1 < ar1.count && i2 < ar2.count) { if ar1[i1] < ar2[i2] { i1 += 1 } if ar1[i1] > ar2[i2] { i2 += 1 } if ar1[i1] == ar2[i2] { intersection.insert(ar1[i1]) i1+=1 i2+=1 } } return intersection } assert(intersection(ar1, ar2)==Set([15, 19, 21])) ///////////////////////////////// // http://www.slideshare.net/gayle2/cracking-the-facebook-coding-interview // https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X // Q 8.3 // // All subsets // s = {"a", "b", "c"} -> [{}, {a}, {b}, {c}, {a, b}, ..., {a, b, c}] // time complexity: n + (n-1) + .. 1 = O(S^2), S = Size of set // space complexity: nCn + nCn-1 + ... + nC1 = 1 + n + .. n := O(S^2)? func generateSubset(set: Set<String>) -> [Set<String>] { var orgSet = set guard let first = orgSet.first else { return [Set()] } orgSet.remove(first) let subset = generateSubset(orgSet) // Call stack: S return subset + subset.flatMap { Set([first]).union($0) } } assert(generateSubset(["a", "b", "c"]).count == 8) ///////////////////////////////// /** https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X Q 8.4 s = "{a,b,c} -> "abc", "acb", "bac", "bca", "cab", "cba" [a + p({b,c})], [b + p({a,c})] */ // time complexity: O(n!) // space complexity: O(n!) func generatePermutation(set: Set<String>) -> [String] { guard set.count > 0 else { return [""] } return set.flatMap { (ch: String) -> [String] in var myset = set myset.remove(ch) return generatePermutation(myset).map { ch + $0 } } } assert(generatePermutation(Set(["a","b","c"])).count==6) /** https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X Q 8.5 3 -> [[1,1,1], [1,2], [2,1], [3]] -> "()()()","()(())","(())()","((()))" */ func generateParenthesesComb(n: Int) -> [String] { return generateNumSet(n).map { nums in return nums .map { String(count: $0, repeatedValue: Character("(")) + String(count: $0, repeatedValue: Character(")")) } .joinWithSeparator("") } } // 3 -> // 1 -> {1} + {gen(2)} // 2 -> {2} + {gen(1)} // 3 -> {3} + {gen(0)} // 2 -> // 1 -> {1} + {gen(1)} // 2 -> {2} + {gen(0)} func generateNumSet(n: Int) -> [[Int]] { guard n > 0 else { return [[]] } // invariant: n >= 1 return Array(1...n).flatMap { m in return generateNumSet(n-m).map { [m] + $0 } } } assert(generateParenthesesComb(3).count==4) /** https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X Q 8.7 31 -> 25*1 + p(6) -> 10*3 + p(1) -> 10*2 + p(6) -> 10*1 + p(21) -> 5*6 + p(1) -> 5*5 + p(6) X(1) = 1 X(2) = 1 / X(1) X(3) = 1 / X(1) X(4) = 1 / X(1) X(5) = 2 / X(4) + 1(5x1) / 1(5) [5:1] X(6) = 2 / X(5) ... X(10) = 4 / X(9) (1x10, 5x1+1x5) + 1(5x2) + 1(10x1) / DP(5)[5] + 1(10) / [5:1,10:1] X(11) = 4 ... X(15) = 6 / X(14) + 1(5x3) + 1(10x1+5x1) / DP(10)[5] + DP(10)[10] [5:2] ... X(20) = X(19) + 1(5x4) + 1(10x1+5x2) + 1(10x2) / DP(15)[5] + DP(10)[10] [5:2, 10:1] 1x20,1x15+5x1,1x X(25) = X(24) + 1(5x5) + 1(10x1+5x2) / 3 DP(20).all + 0 DP(15)[10] + 1(25) [5:3, 10: 0, 25: 1] X(30) = X(29) + 4 + 1 + 0 / DP(25).all + DP(20)[10] + DP[5][25] [5:4, 10:1, 25:0] X(N) = X(N-1) + (1 if new appearance) + X(N-5)[10] + X(N-5)[10] + X(N-5)[25] + (1 if new appearance) + X(N-10)[10] + X(N-10)[25] + (1 if new appearance) + X(N-25)[25] */ func payNCents(n: Int) -> Int { // Actually only floating window 25 is needed for computation! Space complexity: O(1) var coinDP: [[Int: Int]] = Array(count: n+1, repeatedValue: [5: 0, 10: 0, 25: 0]) guard n > 0 else { return 0 } var res = 1 for i in 2...n { let lastFive = existingPattern(i, coin: 5, coinDP: coinDP) + firstAppearance(i, coin: 5) let lastTen = existingPattern(i, coin: 10, coinDP: coinDP) + firstAppearance(i, coin: 10) let lastTwentyFive = existingPattern(i, coin: 25, coinDP: coinDP) + firstAppearance(i, coin: 25) res += lastFive + lastTen + lastTwentyFive coinDP[i] = [5: lastFive, 10: lastTen, 25: lastTwentyFive] } return res } func firstAppearance(n: Int, coin: Int) -> Int { return n == coin ? 1 : 0 } func existingPattern(n: Int, coin: Int, coinDP: [[Int: Int]]) -> Int { guard n % coin == 0 && n > coin else { return 0 } guard n-coin < coinDP.count else { return 0 } let prevPat = coinDP[n-coin] return prevPat.filter { $0.0 >= coin }.reduce(0) { return $0+$1.1 } } assert(payNCents(10)==4) assert(payNCents(15)==6) assert(payNCents(20)==9) assert(payNCents(25)==13) assert(payNCents(26)==13) assert(payNCents(30)==18)
mit
4acdf4b8c4faa7971175f43af4b06854
24.517949
114
0.546021
2.433252
false
false
false
false
beckasaurus/skin-ios
skin/skin/DailyLogViewController.swift
1
6083
//// //// DailyLogViewController.swift //// skin //// //// Created by Becky Henderson on 9/5/17. //// Copyright © 2017 Becky Henderson. All rights reserved. //// // //import UIKit //import RealmSwift // //let applicationCellIdentifier = "application" //let applicationSegue = "applicationSegue" //let changedLogDateNotificationName = Notification.Name("changedLogDate") // //enum LogError: Error { // case invalidDate //} // ////TODO: sort applications by time when displaying, writing and inserting // //class DailyLogViewController: UIViewController { // // @IBOutlet weak var tableView: UITableView! // @IBOutlet weak var dateLabel: UILabel! // // var log: Log? { // didSet { // let formatter = DateFormatter() // formatter.dateStyle = .medium // dateLabel.text = formatter.string(from: log!.date) // } // } // // var applications: List<Application>? { // return log?.applications // } // // var notificationToken: NotificationToken! // var realmConnectedNotification: NSObjectProtocol? // // override func viewDidLoad() { // super.viewDidLoad() // // realmConnectedNotification = NotificationCenter.default.addObserver(forName: realmConnected, object: nil, queue: OperationQueue.main) { [weak self] (notification) in // self?.setupRealm() // } // } // // deinit { // notificationToken.invalidate() // realmConnectedNotification = nil // } // // func updatePerformedRoutineList() { // self.tableView.reloadData() // } // // func setupRealm() { // let currentDatePredicate = try! predicate(for: Date()) //default to current date // if let log = self.realm!.objects(Log.self).filter(currentDatePredicate).first { // self.log = log // } else { // createNewLog(date: Date()) // } // // updatePerformedRoutineList() // // // Notify us when Realm changes // self.notificationToken = self.log?.realm!.observe { [weak self] notification, realm in // self?.updatePerformedRoutineList() // } // } //} // //// MARK: Segues //extension DailyLogViewController { // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // if segue.identifier == applicationSegue { // let cell = sender as! UITableViewCell // let rowIndexPath = tableView.indexPath(for: cell)! // let application = applications![rowIndexPath.row] // let navController = segue.destination as! UINavigationController // let applicationViewController = navController.topViewController as! ApplicationViewController // applicationViewController.application = application // applicationViewController.delegate = self // // applicationViewController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem // applicationViewController.navigationItem.leftItemsSupplementBackButton = true // } // } // // @IBAction func applicationViewUnwind(segue: UIStoryboardSegue) { // //unwind segue for done/cancel in application view // //we register as the application view's delegate so we'll receive a notification when a new application is added and handle adding to our list there // //nothing really needs to be done here, we just need the segue to be present so we can manually unwind // } //} // //// MARK: Create new log //extension DailyLogViewController { // func createNewLog(date: Date) { // try! self.realm!.write { // let dailyLog = Log() // dailyLog.date = date // dailyLog.id = String(date.timeIntervalSince1970) // self.realm!.add(dailyLog) // self.log = dailyLog // } // } //} // //// MARK: Date navigation //extension DailyLogViewController { // func predicate(for date: Date) throws -> NSPredicate { // guard let nextDayBegin = Calendar.current.date(bySettingHour: 00, minute: 00, second: 00, of: date), // let nextDayEnd = Calendar.current.date(bySettingHour: 23, minute: 59, second: 59, of: date) // else { throw LogError.invalidDate } // // return NSPredicate(format: "date >= %@ AND date <= %@", nextDayBegin as CVarArg, nextDayEnd as CVarArg) // } // // func changeDay(by days: Int) { // var dayComponent = DateComponents() // dayComponent.day = days // guard let nextDay = Calendar.current.date(byAdding: dayComponent, to: log!.date) // else { return } // // do { // let datePredicate = try predicate(for: nextDay) // if let nextLog = realm!.objects(Log.self).filter(datePredicate).first { // log = nextLog // } else { // createNewLog(date: nextDay) // } // // updatePerformedRoutineList() // // NotificationCenter.default.post(name: changedLogDateNotificationName, object: self) // } catch { // return // } // } // // @IBAction func swipeRight(_ sender: UIButton) { // changeDay(by: 1) // } // // @IBAction func swipeLeft(_ sender: UIButton) { // changeDay(by: -1) // } //} // //// MARK: ApplicationDelegate //extension DailyLogViewController: ApplicationDelegate { // func didAdd(application: Application) { // try! realm?.write { // log?.applications.insert(application, // at: applications!.count) // } // } //} // //// MARK: UITableViewDataSource //extension DailyLogViewController: UITableViewDataSource { // func numberOfSections(in tableView: UITableView) -> Int { // return 1 // } // // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return applications?.count ?? 0 // } // // // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: applicationCellIdentifier, for: indexPath) // let application = applications![indexPath.row] // cell.textLabel?.text = application.name // // let timeFormatter = DateFormatter() // timeFormatter.timeStyle = .short // timeFormatter.dateStyle = .none // cell.detailTextLabel?.text = timeFormatter.string(from: application.time) // return cell // } // // func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { // if editingStyle == .delete { // try! self.realm?.write { // let item = applications![indexPath.row] // self.realm?.delete(item) // } // } // } //}
mit
656e39fbf146dfca20b795a8bb4ea00d
30.030612
169
0.695988
3.569249
false
false
false
false
wireapp/wire-ios
Wire-iOS Share Extension/UnlockViewController.swift
1
7364
// // Wire // Copyright (C) 2021 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 UIKit import WireDataModel import WireCommonComponents final class UnlockViewController: UIViewController { typealias Callback = (_ passcode: String?) -> Void // MARK: - Properties var callback: Callback? private let contentView: UIView = UIView() private let stackView: UIStackView = UIStackView.verticalStackView() private lazy var unlockButton: UIButton = { var button = UIButton() button.setBackgroundImage(UIImage.singlePixelImage(with: .white), for: .normal) button.setTitleColor(.graphite, for: .normal) button.setTitleColor(.lightGraphite, for: .highlighted) button.titleLabel?.font = UIFont.systemFont(ofSize: 12) button.setTitle("share_extension.unlock.submit_button.title".localized(uppercased: true), for: .normal) button.isEnabled = false button.layer.cornerRadius = 4 button.layer.masksToBounds = true button.addTarget(self, action: #selector(onUnlockButtonPressed(sender:)), for: .touchUpInside) button.accessibilityIdentifier = "unlock_screen.button.unlock" return button }() private lazy var passcodeTextField: PasscodeTextField = { let textField = PasscodeTextField.createPasscodeTextField(delegate: self) textField.isSecureTextEntry = true textField.autocapitalizationType = .none textField.placeholder = "share_extension.unlock.textfield.placeholder".localized textField.accessibilityIdentifier = "unlock_screen.text_field.enter_passcode" return textField }() private let titleLabel: UILabel = { let label = UILabel() label.text = "share_extension.unlock.title_label".localized label.accessibilityIdentifier = "unlock_screen.title.enter_passcode" label.font = UIFont.boldSystemFont(ofSize: 14) label.textColor = .white label.textAlignment = .center label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.setContentCompressionResistancePriority(.required, for: .horizontal) label.setContentCompressionResistancePriority(.required, for: .vertical) return label }() private let hintFont = UIFont.systemFont(ofSize: 10) private let hintLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 10) label.textColor = .white let leadingMargin: CGFloat = 16 let style = NSMutableParagraphStyle() style.firstLineHeadIndent = leadingMargin style.headIndent = leadingMargin label.attributedText = NSAttributedString(string: "share_extension.unlock.hint_label".localized, attributes: [NSAttributedString.Key.paragraphStyle: style]) return label }() private let errorLabel: UILabel = { let label = UILabel() label.text = " " label.font = UIFont.systemFont(ofSize: 10) label.textColor = UIColor.PasscodeUnlock.error return label }() // MARK: - Life cycle init() { super.init(nibName: nil, bundle: nil) setupViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupInitialStates() } } // MARK: - View creation extension UnlockViewController { private func setupViews() { view.backgroundColor = .black view.addSubview(contentView) stackView.distribution = .fill contentView.addSubview(stackView) [titleLabel, hintLabel, passcodeTextField, errorLabel, unlockButton].forEach(stackView.addArrangedSubview) createConstraints() } private func createConstraints() { [contentView, stackView].forEach { (view) in view.translatesAutoresizingMaskIntoConstraints = false } let widthConstraint = contentView.createContentWidthConstraint() let contentPadding: CGFloat = 24 NSLayoutConstraint.activate([ // content view widthConstraint, contentView.widthAnchor.constraint(lessThanOrEqualToConstant: CGFloat.iPhone4_7Inch.width), contentView.topAnchor.constraint(equalTo: view.topAnchor), contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor), contentView.centerXAnchor.constraint(equalTo: view.centerXAnchor), contentView.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: contentPadding), contentView.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -contentPadding), // stack view stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), stackView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), // unlock button unlockButton.heightAnchor.constraint(equalToConstant: CGFloat.PasscodeUnlock.buttonHeight) ]) } private func setupInitialStates() { errorLabel.text = " " passcodeTextField.text = "" unlockButton.isEnabled = false passcodeTextField.becomeFirstResponder() } } // MARK: - Actions extension UnlockViewController { @objc private func onUnlockButtonPressed(sender: AnyObject?) { unlock() } private func unlock() { guard let passcode = passcodeTextField.text else { return } callback?(passcode) } func showWrongPasscodeMessage() { let textAttachment = NSTextAttachment.textAttachment(for: .exclamationMarkCircle, with: UIColor.PasscodeUnlock.error, iconSize: StyleKitIcon.Size.CreatePasscode.errorIconSize, verticalCorrection: -1, insets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 4)) let attributedString = NSAttributedString(string: "share_extension.unlock.error_label".localized) && hintFont errorLabel.attributedText = NSAttributedString(attachment: textAttachment) + attributedString unlockButton.isEnabled = false } } // MARK: - PasscodeTextFieldDelegate extension UnlockViewController: PasscodeTextFieldDelegate { func textFieldValueChanged(_ value: String?) { errorLabel.text = " " if let isEmpty = value?.isEmpty { unlockButton.isEnabled = !isEmpty } else { unlockButton.isEnabled = false } } }
gpl-3.0
aefe9a5fbe0efce18cabeb955fea8ed6
31.584071
267
0.681016
5.200565
false
false
false
false
ivanasmiljic/test
Segmentio/Source/Segmentio.swift
1
23032
// // Segmentio.swift // Segmentio // // Created by Dmitriy Demchenko // Copyright © 2016 Yalantis Mobile. All rights reserved. // import UIKit import QuartzCore public typealias SegmentioSelectionCallback = ((_ segmentio: Segmentio, _ selectedSegmentioIndex: Int) -> Void) open class Segmentio: UIView { internal struct Points { var startPoint: CGPoint var endPoint: CGPoint } internal struct Context { var isFirstCell: Bool var isLastCell: Bool var isLastOrPrelastVisibleCell: Bool var isFirstOrSecondVisibleCell: Bool var isFirstIndex: Bool } internal struct ItemInSuperview { var collectionViewWidth: CGFloat var cellFrameInSuperview: CGRect var shapeLayerWidth: CGFloat var startX: CGFloat var endX: CGFloat } open var valueDidChange: SegmentioSelectionCallback? open var selectedSegmentioIndex = -1 { didSet { if selectedSegmentioIndex != oldValue { reloadSegmentio() valueDidChange?(self, selectedSegmentioIndex) } } } open fileprivate(set) var segmentioItems = [SegmentioItem]() fileprivate var segmentioCollectionView: UICollectionView? fileprivate var segmentioOptions = SegmentioOptions() fileprivate var segmentioStyle = SegmentioStyle.imageOverLabel fileprivate var isPerformingScrollAnimation = false fileprivate var topSeparatorView: UIView? fileprivate var bottomSeparatorView: UIView? fileprivate var indicatorLayer: CAShapeLayer? fileprivate var selectedLayer: CAShapeLayer? // MARK: - Lifecycle required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } open override func layoutSubviews() { super.layoutSubviews() reloadSegmentio() } fileprivate func commonInit() { setupSegmentedCollectionView() } fileprivate func setupSegmentedCollectionView() { let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets.zero layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 let collectionView = UICollectionView( frame: frameForSegmentCollectionView(), collectionViewLayout: layout ) collectionView.dataSource = self collectionView.delegate = self collectionView.isPagingEnabled = false collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.bounces = true collectionView.isScrollEnabled = segmentioOptions.scrollEnabled collectionView.backgroundColor = .clear collectionView.accessibilityIdentifier = "segmentio_collection_view" segmentioCollectionView = collectionView if let segmentioCollectionView = segmentioCollectionView { addSubview(segmentioCollectionView, options: .overlay) } } fileprivate func frameForSegmentCollectionView() -> CGRect { var separatorsHeight: CGFloat = 0 var collectionViewFrameMinY: CGFloat = 0 if let horizontalSeparatorOptions = segmentioOptions.horizontalSeparatorOptions { let separatorHeight = horizontalSeparatorOptions.height switch horizontalSeparatorOptions.type { case .none: separatorsHeight = 0 case .top: collectionViewFrameMinY = separatorHeight separatorsHeight = separatorHeight case .bottom: separatorsHeight = separatorHeight case .topAndBottom: collectionViewFrameMinY = separatorHeight separatorsHeight = separatorHeight * 2 } } return CGRect( x: 0, y: collectionViewFrameMinY, width: bounds.width, height: bounds.height - separatorsHeight ) } // MARK: - Setups: // MARK: Main setup open func setup(content: [SegmentioItem], style: SegmentioStyle, options: SegmentioOptions?) { segmentioItems = content segmentioStyle = style selectedLayer?.removeFromSuperlayer() indicatorLayer?.removeFromSuperlayer() if let options = options { segmentioOptions = options segmentioCollectionView?.isScrollEnabled = segmentioOptions.scrollEnabled backgroundColor = options.backgroundColor } if segmentioOptions.states.selectedState.backgroundColor != .clear { selectedLayer = CAShapeLayer() if let selectedLayer = selectedLayer, let sublayer = segmentioCollectionView?.layer { setupShapeLayer( shapeLayer: selectedLayer, backgroundColor: segmentioOptions.states.selectedState.backgroundColor, height: bounds.height, sublayer: sublayer ) } } if let indicatorOptions = segmentioOptions.indicatorOptions { indicatorLayer = CAShapeLayer() if let indicatorLayer = indicatorLayer { setupShapeLayer( shapeLayer: indicatorLayer, backgroundColor: indicatorOptions.color, height: indicatorOptions.height, sublayer: layer ) } } setupHorizontalSeparatorIfPossible() setupCellWithStyle(segmentioStyle) segmentioCollectionView?.reloadData() } open override func didMoveToSuperview() { super.didMoveToSuperview() setupHorizontalSeparatorIfPossible() } open func addBadge(at index: Int, count: Int, color: UIColor = .red) { segmentioItems[index].addBadge(count, color: color) segmentioCollectionView?.reloadData() } open func removeBadge(at index: Int) { segmentioItems[index].removeBadge() segmentioCollectionView?.reloadData() } // MARK: Collection view setup fileprivate func setupCellWithStyle(_ style: SegmentioStyle) { var cellClass: SegmentioCell.Type { switch style { case .onlyLabel: return SegmentioCellWithLabel.self case .onlyImage: return SegmentioCellWithImage.self case .imageOverLabel: return SegmentioCellWithImageOverLabel.self case .imageUnderLabel: return SegmentioCellWithImageUnderLabel.self case .imageBeforeLabel: return SegmentioCellWithImageBeforeLabel.self case .imageAfterLabel: return SegmentioCellWithImageAfterLabel.self } } segmentioCollectionView?.register( cellClass, forCellWithReuseIdentifier: segmentioStyle.rawValue ) segmentioCollectionView?.layoutIfNeeded() } // MARK: Horizontal separators setup fileprivate func setupHorizontalSeparatorIfPossible() { if superview != nil && segmentioOptions.horizontalSeparatorOptions != nil { setupHorizontalSeparator() } } fileprivate func setupHorizontalSeparator() { topSeparatorView?.removeFromSuperview() bottomSeparatorView?.removeFromSuperview() guard let horizontalSeparatorOptions = segmentioOptions.horizontalSeparatorOptions else { return } let height = horizontalSeparatorOptions.height let type = horizontalSeparatorOptions.type if type == .top || type == .topAndBottom { topSeparatorView = UIView(frame: CGRect.zero) setupConstraintsForSeparatorView( separatorView: topSeparatorView, originY: 0 ) } if type == .bottom || type == .topAndBottom { bottomSeparatorView = UIView(frame: CGRect.zero) setupConstraintsForSeparatorView( separatorView: bottomSeparatorView, originY: bounds.maxY - height ) } } fileprivate func setupConstraintsForSeparatorView(separatorView: UIView?, originY: CGFloat) { guard let horizontalSeparatorOptions = segmentioOptions.horizontalSeparatorOptions, let separatorView = separatorView else { return } separatorView.translatesAutoresizingMaskIntoConstraints = false separatorView.backgroundColor = horizontalSeparatorOptions.color addSubview(separatorView) let topConstraint = NSLayoutConstraint( item: separatorView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: originY ) topConstraint.isActive = true let leadingConstraint = NSLayoutConstraint( item: separatorView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0 ) leadingConstraint.isActive = true let trailingConstraint = NSLayoutConstraint( item: separatorView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0 ) trailingConstraint.isActive = true let heightConstraint = NSLayoutConstraint( item: separatorView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: horizontalSeparatorOptions.height ) heightConstraint.isActive = true } // MARK: CAShapeLayers setup fileprivate func setupShapeLayer(shapeLayer: CAShapeLayer, backgroundColor: UIColor, height: CGFloat, sublayer: CALayer) { shapeLayer.fillColor = backgroundColor.cgColor shapeLayer.strokeColor = backgroundColor.cgColor shapeLayer.lineWidth = height layer.insertSublayer(shapeLayer, below: sublayer) } // MARK: - Actions: // MARK: Reload segmentio public func reloadSegmentio() { segmentioCollectionView?.collectionViewLayout.invalidateLayout() segmentioCollectionView?.reloadData() scrollToItemAtContext() moveShapeLayerAtContext() } // MARK: Move shape layer to item fileprivate func moveShapeLayerAtContext() { if let indicatorLayer = indicatorLayer, let options = segmentioOptions.indicatorOptions { let item = itemInSuperview(ratio: options.ratio) let context = contextForItem(item) let points = Points( context: context, item: item, pointY: indicatorPointY() ) moveShapeLayer( indicatorLayer, startPoint: points.startPoint, endPoint: points.endPoint, animated: true ) } if let selectedLayer = selectedLayer { let item = itemInSuperview() let context = contextForItem(item) let points = Points( context: context, item: item, pointY: bounds.midY ) moveShapeLayer( selectedLayer, startPoint: points.startPoint, endPoint: points.endPoint, animated: true ) } } // MARK: Scroll to item fileprivate func scrollToItemAtContext() { guard let numberOfSections = segmentioCollectionView?.numberOfSections else { return } let item = itemInSuperview() let context = contextForItem(item) if context.isLastOrPrelastVisibleCell == true { let newIndex = selectedSegmentioIndex + (context.isLastCell ? 0 : 1) let newIndexPath = IndexPath(item: newIndex, section: numberOfSections - 1) segmentioCollectionView?.scrollToItem( at: newIndexPath, at: UICollectionViewScrollPosition(), animated: true ) } if context.isFirstOrSecondVisibleCell == true && selectedSegmentioIndex != -1 { let newIndex = selectedSegmentioIndex - (context.isFirstIndex ? 1 : 0) let newIndexPath = IndexPath(item: newIndex, section: numberOfSections - 1) segmentioCollectionView?.scrollToItem( at: newIndexPath, at: UICollectionViewScrollPosition(), animated: true ) } } // MARK: Move shape layer fileprivate func moveShapeLayer(_ shapeLayer: CAShapeLayer, startPoint: CGPoint, endPoint: CGPoint, animated: Bool = false) { var endPointWithVerticalSeparator = endPoint let isLastItem = selectedSegmentioIndex + 1 == segmentioItems.count endPointWithVerticalSeparator.x = endPoint.x - (isLastItem ? 0 : 1) let shapeLayerPath = UIBezierPath() shapeLayerPath.move(to: startPoint) shapeLayerPath.addLine(to: endPointWithVerticalSeparator) if animated == true { isPerformingScrollAnimation = true isUserInteractionEnabled = false CATransaction.begin() let animation = CABasicAnimation(keyPath: "path") animation.fromValue = shapeLayer.path animation.toValue = shapeLayerPath.cgPath animation.duration = segmentioOptions.animationDuration CATransaction.setCompletionBlock() { self.isPerformingScrollAnimation = false self.isUserInteractionEnabled = true } shapeLayer.add(animation, forKey: "path") CATransaction.commit() } shapeLayer.path = shapeLayerPath.cgPath } // MARK: - Context for item fileprivate func contextForItem(_ item: ItemInSuperview) -> Context { let cellFrame = item.cellFrameInSuperview let cellWidth = cellFrame.width let lastCellMinX = floor(item.collectionViewWidth - cellWidth) let minX = floor(cellFrame.minX) let maxX = floor(cellFrame.maxX) let isLastVisibleCell = maxX >= item.collectionViewWidth let isLastVisibleCellButOne = minX < lastCellMinX && maxX > lastCellMinX let isFirstVisibleCell = minX <= 0 let isNextAfterFirstVisibleCell = minX < cellWidth && maxX > cellWidth return Context( isFirstCell: selectedSegmentioIndex == 0, isLastCell: selectedSegmentioIndex == segmentioItems.count - 1, isLastOrPrelastVisibleCell: isLastVisibleCell || isLastVisibleCellButOne, isFirstOrSecondVisibleCell: isFirstVisibleCell || isNextAfterFirstVisibleCell, isFirstIndex: selectedSegmentioIndex > 0 ) } // MARK: - Item in superview fileprivate func itemInSuperview(ratio: CGFloat = 1) -> ItemInSuperview { var collectionViewWidth: CGFloat = 0 var cellWidth: CGFloat = 0 var cellRect = CGRect.zero var shapeLayerWidth: CGFloat = 0 if let collectionView = segmentioCollectionView { collectionViewWidth = collectionView.frame.width let maxVisibleItems = segmentioOptions.maxVisibleItems > segmentioItems.count ? CGFloat(segmentioItems.count) : CGFloat(segmentioOptions.maxVisibleItems) cellWidth = floor(collectionViewWidth / maxVisibleItems) cellRect = CGRect( x: floor(CGFloat(selectedSegmentioIndex) * cellWidth - collectionView.contentOffset.x), y: 0, width: floor(collectionViewWidth / maxVisibleItems), height: collectionView.frame.height ) shapeLayerWidth = floor(cellWidth * ratio) } return ItemInSuperview( collectionViewWidth: collectionViewWidth, cellFrameInSuperview: cellRect, shapeLayerWidth: shapeLayerWidth, startX: floor(cellRect.midX - (shapeLayerWidth / 2)), endX: floor(cellRect.midX + (shapeLayerWidth / 2)) ) } // MARK: - Indicator point Y fileprivate func indicatorPointY() -> CGFloat { var indicatorPointY: CGFloat = 0 guard let indicatorOptions = segmentioOptions.indicatorOptions else { return indicatorPointY } switch indicatorOptions.type { case .top: indicatorPointY = (indicatorOptions.height / 2) case .bottom: indicatorPointY = frame.height - (indicatorOptions.height / 2) } guard let horizontalSeparatorOptions = segmentioOptions.horizontalSeparatorOptions else { return indicatorPointY } let separatorHeight = horizontalSeparatorOptions.height let isIndicatorTop = indicatorOptions.type == .top switch horizontalSeparatorOptions.type { case .none: break case .top: indicatorPointY = isIndicatorTop ? indicatorPointY + separatorHeight : indicatorPointY case .bottom: indicatorPointY = isIndicatorTop ? indicatorPointY : indicatorPointY - separatorHeight case .topAndBottom: indicatorPointY = isIndicatorTop ? indicatorPointY + separatorHeight : indicatorPointY - separatorHeight } return indicatorPointY } } // MARK: - UICollectionViewDataSource extension Segmentio: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return segmentioItems.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: segmentioStyle.rawValue, for: indexPath) as! SegmentioCell let content = segmentioItems[indexPath.row] cell.configure( content: content, style: segmentioStyle, options: segmentioOptions, isLastCell: indexPath.row == segmentioItems.count - 1 ) cell.configure( selected: (indexPath.row == selectedSegmentioIndex), selectedImage: content.selectedImage, image: content.image ) return cell } } // MARK: - UICollectionViewDelegate extension Segmentio: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedSegmentioIndex = indexPath.row } } // MARK: - UICollectionViewDelegateFlowLayout extension Segmentio: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let maxVisibleItems = segmentioOptions.maxVisibleItems > segmentioItems.count ? CGFloat(segmentioItems.count) : CGFloat(segmentioOptions.maxVisibleItems) return CGSize( width: floor(collectionView.frame.width / maxVisibleItems), height: collectionView.frame.height) } } // MARK: - UIScrollViewDelegate extension Segmentio: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { if isPerformingScrollAnimation { return } if let options = segmentioOptions.indicatorOptions, let indicatorLayer = indicatorLayer { let item = itemInSuperview(ratio: options.ratio) moveShapeLayer( indicatorLayer, startPoint: CGPoint(x: item.startX, y: indicatorPointY()), endPoint: CGPoint(x: item.endX, y: indicatorPointY()), animated: false ) } if let selectedLayer = selectedLayer { let item = itemInSuperview() moveShapeLayer( selectedLayer, startPoint: CGPoint(x: item.startX, y: bounds.midY), endPoint: CGPoint(x: item.endX, y: bounds.midY), animated: false ) } } } extension Segmentio.Points { init(context: Segmentio.Context, item: Segmentio.ItemInSuperview, pointY: CGFloat) { let cellWidth = item.cellFrameInSuperview.width var startX = item.startX var endX = item.endX if context.isFirstCell == false && context.isLastCell == false { if context.isLastOrPrelastVisibleCell == true { let updatedStartX = item.collectionViewWidth - (cellWidth * 2) + ((cellWidth - item.shapeLayerWidth) / 2) startX = updatedStartX let updatedEndX = updatedStartX + item.shapeLayerWidth endX = updatedEndX } if context.isFirstOrSecondVisibleCell == true { let updatedEndX = (cellWidth * 2) - ((cellWidth - item.shapeLayerWidth) / 2) endX = updatedEndX let updatedStartX = updatedEndX - item.shapeLayerWidth startX = updatedStartX } } if context.isFirstCell == true { startX = (cellWidth - item.shapeLayerWidth) / 2 endX = startX + item.shapeLayerWidth } if context.isLastCell == true { startX = item.collectionViewWidth - cellWidth + (cellWidth - item.shapeLayerWidth) / 2 endX = startX + item.shapeLayerWidth } startPoint = CGPoint(x: startX, y: pointY) endPoint = CGPoint(x: endX, y: pointY) } }
mit
b4cf280af37d616a11d9c280eb3cf473
33.948407
167
0.60983
5.909931
false
false
false
false
gregjinkim/ios-dev
photo_tutorial/photo_tutorial/ViewController.swift
1
18443
// // ViewController.swift // photo_tutorial // // Created by Greg J. Kim on 6/14/16. // Copyright © 2016 Greg Kim. All rights reserved. // import UIKit import Firebase import FBSDKCoreKit import FBSDKLoginKit class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate { private let dataURL = "https://photo-tutorial.firebaseio.com" private var currentImageURL = "" var imagePicker: UIImagePickerController! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){ view.endEditing(true) super.touchesBegan(touches, withEvent: event) } // Opens view controller to allow user to pick photo from library func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { // Need to upload pickedImage to firebase let targetSize = CGSize(width: 350.0, height: 320.0) let resizedImage = self.ResizeImage(pickedImage, targetSize: targetSize) let imageData: NSData = UIImagePNGRepresentation(resizedImage)! self.uploadImageView.contentMode = UIViewContentMode.ScaleAspectFill self.uploadImageView.clipsToBounds = false self.uploadImageView.layer.masksToBounds = true self.uploadImageView.image = resizedImage let storage = FIRStorage.storage() let imagesURL = "gs://photo-tutorial.appspot.com/images/" let imagesRef = storage.referenceForURL(imagesURL) let defaults = NSUserDefaults.standardUserDefaults() let uid = defaults.stringForKey("uid")! let databaseRef = FIRDatabase.database().reference() let key = databaseRef.child("imagesInfo").childByAutoId().key //let randomNum = arc4random_uniform(1024 * 1024) let imageName = key + ".jpeg" let userImagesRef = imagesRef.child(imageName) userImagesRef.putData(imageData, metadata: nil) { metadata, error in if (error != nil) { print("Fuck error") } else { print("yay it worked") //self.loadRandomPicture() } } //let databaseRef = FIRDatabase.database().reference() //let key = databaseRef.child("imagesInfo").childByAutoId().key let userImagePost = ["imageURL" : imagesURL + imageName] let imagesInfoPost = ["imageURL": imagesURL + imageName, "uid": uid] let update = ["/userImages/\(uid)/\(key)/": userImagePost, "/imagesInfo/\(key)/": imagesInfoPost] databaseRef.updateChildValues(update) } dismissViewControllerAnimated(true, completion: nil) } func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio) } else { newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRectMake(0, 0, newSize.width, newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } func loadRandomPicture() { let databaseRef = FIRDatabase.database().reference() databaseRef.child("imagesInfo").observeSingleEventOfType(.Value, withBlock: { (snapshot) in let childrenCount = snapshot.childrenCount var randomImageIndex = arc4random_uniform(UInt32(childrenCount)) let children = snapshot.children.allObjects var imageURL: String? = nil var tries = 0 while (imageURL == nil && tries < 10) { let child = children[Int(randomImageIndex)] let imageUserId = child.value!["uid"] as! String if (self.canShowImage(imageUserId)) { imageURL = child.value!["imageURL"] as? String } randomImageIndex = arc4random_uniform(UInt32(childrenCount)) tries += 1 } if (imageURL != nil) { let storage = FIRStorage.storage() let imageRef = storage.referenceForURL(imageURL!) imageRef.dataWithMaxSize(100 * 1024 * 1024) { (data, error) -> Void in if (error != nil) { print("error with downloading image from Firebase: \(error.debugDescription)") } else { let image: UIImage! = UIImage(data: data!) self.randomImageView.contentMode = UIViewContentMode.ScaleAspectFill self.randomImageView.clipsToBounds = false self.randomImageView.layer.masksToBounds = true self.randomImageView.image = image self.currentImageURL = imageURL! } } } }) { (error) in print(error.localizedDescription) } } func canShowImage(imageUserId: String) -> Bool { //let defaults = NSUserDefaults.standardUserDefaults() //let uid = defaults.stringForKey("uid")! /*let friends = defaults.arrayForKey("friends")! for friend in friends { if (imageUserId == friend as! String) { return false } } if (uid == imageUserId) { return false }*/ return true } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } @IBOutlet weak var uploadImageView: UIImageView! @IBOutlet weak var randomImageView: UIImageView! @IBOutlet weak var ratingScore: UILabel! @IBOutlet weak var myRating: UILabel! @IBOutlet weak var raterImageView: UIImageView! @IBAction func sliderValueChanged(sender: UISlider) { let rating = Int(sender.value) self.ratingScore.text = "\(rating)" } @IBAction func rateImage(sender: AnyObject) { let scoreString = self.ratingScore.text if let scoreInt = Int(scoreString!) { if (scoreInt >= 0 && scoreInt <= 100) { let databaseRef = FIRDatabase.database().reference() let key = databaseRef.child("imageRatings").childByAutoId().key let imageURL = self.currentImageURL let defaults = NSUserDefaults.standardUserDefaults() let uid = defaults.stringForKey("uid")! let ratingPost = ["rating" : scoreInt, "uid" : uid] let imageId = self.getImageIdFromURL(imageURL) let update = ["/imageRatings/\(imageId)/\(key)/": ratingPost] databaseRef.updateChildValues(update) loadRandomPicture() } else { self.showErrorForRating() } } else { self.showErrorForRating() } } func getImageIdFromURL(imageURL: String) -> String { return imageURL.componentsSeparatedByString(".")[2].componentsSeparatedByString("/")[2] } @IBAction func showNextRating(sender: AnyObject) { let defaults = NSUserDefaults.standardUserDefaults() let uid = defaults.stringForKey("uid")! let databaseRef = FIRDatabase.database().reference() databaseRef.child("userImages").child(uid).queryLimitedToLast(1).observeSingleEventOfType(.Value, withBlock: { (snapshot) in if (snapshot.childrenCount > 0) { let imagePost = snapshot.children.nextObject() let imageURL = imagePost!.value!["imageURL"] as! String let imageId = self.getImageIdFromURL(imageURL) databaseRef.child("imageRatings").child(imageId).observeSingleEventOfType(.Value, withBlock: { (snapshot) in if (snapshot.childrenCount > 0) { let currentRatingPost = snapshot.children.nextObject() as! FIRDataSnapshot let currentRating = currentRatingPost.value!["rating"] as! Int self.myRating.text = String(currentRating) self.accumulateAndDeleteRating(imageId, ratingKey: currentRatingPost.key, rating: currentRating) let raterId = currentRatingPost.value!["uid"] as! String let databaseRef = FIRDatabase.database().reference() databaseRef.child("userImages").child(String(raterId)).queryLimitedToLast(1).observeSingleEventOfType(.Value, withBlock: { (snapshot) in if (snapshot.childrenCount > 0) { let imagePost = snapshot.children.nextObject() let imageURL = imagePost!.value!["imageURL"] as! String let storage = FIRStorage.storage() let imageRef = storage.referenceForURL(imageURL) imageRef.dataWithMaxSize(100 * 1024 * 1024) { (data, error) -> Void in if (error != nil) { print("error with downloading image from Firebase: \(error.debugDescription)") } else { let image: UIImage! = UIImage(data: data!) self.raterImageView.contentMode = UIViewContentMode.ScaleAspectFill self.raterImageView.clipsToBounds = false self.raterImageView.layer.masksToBounds = true self.raterImageView.image = image } } } }) { (error) in print(error.localizedDescription) } } }) { (error) in print(error.localizedDescription) } } }) { (error) in print(error.localizedDescription) } } func accumulateAndDeleteRating(imageId: String, ratingKey: String, rating: Int) { // put the rating into this user's average and then delete the post from imageRatings so user doesn't see same rating twice. let defaults = NSUserDefaults.standardUserDefaults() let uid = defaults.stringForKey("uid")! // update average let databaseRef = FIRDatabase.database().reference() databaseRef.child("averageRatings").child(uid).observeSingleEventOfType(.Value, withBlock: { (snapshot) in var count = snapshot.value!["count"] as! Int var sum = snapshot.value!["sum"]as! Int count += 1 sum += rating databaseRef.child("averageRatings").child(uid).setValue(["sum": sum, "count": count]) }) { (error) in print(error.localizedDescription) } // delete rating databaseRef.child("imageRatings").child(imageId).child(ratingKey).removeValue() } func showErrorForRating() { // show error message for inputing invalid rating } @IBAction func uploadPhoto(sender: UIButton) { imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.sourceType = .PhotoLibrary presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func viewNextImage(sender: AnyObject) { loadRandomPicture() } @IBAction func loginWithFacebook(sender: AnyObject) { let facebookLogin = FBSDKLoginManager() facebookLogin.logOut() facebookLogin.logInWithReadPermissions(["user_friends", "public_profile", "email"], fromViewController: self, handler:{(facebookResult, facebookError) -> Void in if facebookError != nil { print("Facebook login failed. Error \(facebookError)") } else if facebookResult.isCancelled { print("Facebook login was cancelled.") } else { let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString) FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in // ... if let error = error { print(error.localizedDescription) } else { print("successfully logged in user: \(user!.uid)") // save user id as default variable in app let defaults = NSUserDefaults.standardUserDefaults() if((FBSDKAccessToken.currentAccessToken()) != nil){ FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id"], tokenString: FBSDKAccessToken.currentAccessToken().tokenString, version: nil, HTTPMethod: "GET").startWithCompletionHandler({ (connection, result, error) -> Void in if (error == nil){ let idData = result as! NSDictionary let uid = idData.objectForKey("id")! as! String defaults.setValue(uid, forKey: "uid") defaults.synchronize() // saved user id to database let databaseRef = FIRDatabase.database().reference() databaseRef.child("users").observeSingleEventOfType(.Value, withBlock: { (snapshot) in if (!snapshot.hasChild(uid)) { databaseRef.child("users").child(uid).setValue(["placeholder": "placeholder"]) databaseRef.child("averageRatings").child(uid).setValue(["sum": 0, "count": 0]) } }) { (error) in print(error.localizedDescription) } } else { print("error \(error)") } }) FBSDKGraphRequest(graphPath: "me/friends", parameters: ["fields": "user_friends"], tokenString: FBSDKAccessToken.currentAccessToken().tokenString, version: nil, HTTPMethod: "GET").startWithCompletionHandler({ (connection, result, error) -> Void in if (error == nil){ let friendsData = result as! NSDictionary let friendIdsDict = friendsData.objectForKey("data")! as! NSArray var friendsArray = [String]() for friendIdData in friendIdsDict { let friendId = friendIdData as! NSDictionary friendsArray.append(friendId.objectForKey("id")! as! String) } defaults.setValue(friendsArray, forKey: "friends") defaults.synchronize() } else { print("error \(error)") } }) } let photoTakerController = (self.storyboard?.instantiateViewControllerWithIdentifier("PhotoTaker"))! as UIViewController self.presentViewController(photoTakerController, animated: true, completion: nil) if((FBSDKAccessToken.currentAccessToken()) != nil){ FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "user_friends"]).startWithCompletionHandler({ (connection, result, error) -> Void in if (error == nil){ print("friends \(result)") } }) } } } } }); } }
mit
0af1192661138bf0573c10a88b0e6720
45.926209
275
0.527058
6.046557
false
false
false
false
rlopezdiez/RLDTableViewSwift
Classes/RLDTableViewController.swift
1
8202
import UIKit import RLDTableViewSwift // MARK: UIView extension to find the first responder private extension UIView { private weak static var _firstResponder:UIView? class func rld_firstResponder() -> UIView? { UIApplication.sharedApplication().sendAction(Selector("setFirstResponder"), to:nil, from:nil, forEvent:nil) return _firstResponder } func setFirstResponder() { UIView._firstResponder = self } } // MARK: UITableView extension to scroll to the first responder cell private extension UITableView { func scrollToFirstResponder(animated:Bool) { if let firstResponder = UIView.rld_firstResponder() { let firstResponderFrame = firstResponder.convertRect(firstResponder.bounds, toView:self) self.scrollRectToVisible(firstResponderFrame, animated:animated) } } } // MARK: UITableView extension to know wether multiple selection is enabled private extension UITableView { var multipleSelectionModeEnabled: Bool { return (self.editing ? self.allowsMultipleSelectionDuringEditing : self.allowsMultipleSelection) } } // MARK: RLDTableViewController class public class RLDTableViewController:UIViewController { // MARK: Initialization required public init(style: UITableViewStyle) { super.init(nibName:nil, bundle:nil) tableView = UITableView(frame:CGRectZero, style:style) } required public init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } // MARK: Data source and delegate configuration private var tableViewDataSource:RLDTableViewDataSource? private var tableViewDelegate:RLDTableViewDelegate? public var tableViewModel:RLDTableViewModel? { didSet { if let tableViewModel = tableViewModel { tableViewDataSource = RLDTableViewDataSource(tableViewModel:tableViewModel) tableViewDelegate = RLDTableViewDelegate(tableViewModel:tableViewModel) tableView?.dataSource = tableViewDataSource tableView?.delegate = tableViewDelegate tableView?.reloadData() } } } // MARK: View management lazy public var tableView: UITableView? = { return UITableView(frame:CGRectZero) }() override public var view: UIView! { get { return super.view } set { if let tableView = newValue as? UITableView { self.tableView = tableView super.view = tableView } else { fatalError("The view must be an UITableView") } } } var clearsSelectionOnViewWillAppear: Bool = true var refreshControl: UIRefreshControl? { didSet { if let refreshControl = refreshControl { self.tableView!.insertSubview(refreshControl, atIndex:0) } } } override public func viewWillAppear(animated:Bool) { startObservingKeyboardNotifications() if clearsSelectionOnViewWillAppear { clearTableViewSelection(animated) } super.viewWillAppear(animated) } override public func viewWillDisappear(animated:Bool) { super.viewWillDisappear(animated) stopObservingKeyboardNotifications() } override public func viewDidAppear(animated:Bool) { super.viewDidAppear(animated) tableView!.flashScrollIndicators() } override public func setEditing(editing:Bool, animated:Bool) { super.setEditing(editing, animated:animated) tableView!.setEditing(editing, animated:animated) } // MARK: Keyboard notifications handling private func startObservingKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RLDTableViewController.keyboardWillShowWithKeyboardChangeNotification(_:)), name:UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RLDTableViewController.keyboardWillHideWithKeyboardChangeNotification(_:)), name:UIKeyboardWillHideNotification, object: nil) } private func stopObservingKeyboardNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShowWithKeyboardChangeNotification(notification:NSNotification) { synchronizeAnimationWithKeyboardChangeNotification(notification, animations: { () -> Void in self.tableView!.frame = CGRect(x:self.tableView!.frame.origin.x, y:self.tableView!.frame.origin.y, width:self.tableView!.frame.size.width, height:self.tableView!.superview!.bounds.size.height - self.keyboardHeightWithKeyboardNotification(notification)) self.tableView?.scrollToFirstResponder(false) }) } func keyboardWillHideWithKeyboardChangeNotification(notification:NSNotification) { synchronizeAnimationWithKeyboardChangeNotification(notification, animations: { () -> Void in self.tableView!.frame = self.tableView!.superview!.bounds }) } private func synchronizeAnimationWithKeyboardChangeNotification(notification:NSNotification, animations:(()->Void)?) { if let animations = animations, let userInfo = notification.userInfo as? [String:AnyObject] { let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue if (animationDuration == 0) { animations() } else { let animationCurve = UIViewAnimationCurve(rawValue:(userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue)! UIView.beginAnimations(nil, context:nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(animationCurve) UIView.setAnimationBeginsFromCurrentState(true) animations() UIView.commitAnimations() } } } private func keyboardHeightWithKeyboardNotification(notification:NSNotification) -> CGFloat { let keyboardBounds = keyboardBoundsWithKeyboardNotification(notification) return keyboardBounds.size.height } private func keyboardBoundsWithKeyboardNotification(notification:NSNotification) -> CGRect { if let userInfo = notification.userInfo as? [String:NSValue], let keyboardFrameValue = userInfo[UIKeyboardFrameEndUserInfoKey] { return keyboardFrameValue.CGRectValue() } return CGRectZero } // MARK: Selection clearing private func clearTableViewSelection(animated:Bool) { if !tableView!.multipleSelectionModeEnabled { if let indexPathForSelectedRow = tableView?.indexPathForSelectedRow { synchronizeDeselectionAnimationOfRow(indexPathForSelectedRow, animated:animated) } } } private func synchronizeDeselectionAnimationOfRow(indexPathForSelectedRow:NSIndexPath, animated:Bool) { if let transitionCoordinator = transitionCoordinator() { transitionCoordinator.animateAlongsideTransitionInView(tableView, animation: { (context:UIViewControllerTransitionCoordinatorContext!) -> Void in self.tableView!.deselectRowAtIndexPath(indexPathForSelectedRow, animated:animated) }, completion: { (context:UIViewControllerTransitionCoordinatorContext!) -> Void in if context.isCancelled() { self.tableView!.selectRowAtIndexPath(indexPathForSelectedRow, animated:false, scrollPosition:UITableViewScrollPosition.None) } }) } } }
apache-2.0
24fe55a84935816cae3fab6c52f15b06
37.693396
208
0.65545
6.309231
false
false
false
false
richardpiazza/MiseEnPlace
Tests/MiseEnPlaceTests/TestIngredient.swift
1
1659
import Foundation @testable import MiseEnPlace struct TestIngredient: Ingredient { var uuid: UUID = UUID() var creationDate: Date = Date() var modificationDate: Date = Date() var name: String? var commentary: String? var classification: String? var imagePath: String? var volume: Double = 1.0 var weight: Double = 1.0 var amount: Double = 1.0 var unit: MeasurementUnit = .ounce init() { } } extension TestIngredient { static var water: Ingredient { var ingredient = TestIngredient() ingredient.uuid = UUID(uuidString: "218ab2d0-16d1-4804-adf8-5918d800c25c")! ingredient.name = "Water" ingredient.volume = 1.0 ingredient.weight = 1.0 return ingredient } static var flour: Ingredient { var ingredient = TestIngredient() ingredient.uuid = UUID(uuidString: "d7602b04-3984-4cb5-8c26-7512aadd90c5")! ingredient.name = "Flour" ingredient.volume = 1.882 ingredient.weight = 1.0 return ingredient } static var salt: Ingredient { var ingredient = TestIngredient() ingredient.uuid = UUID(uuidString: "b803c759-9590-4dbf-9cd7-38cbac8ab0ae")! ingredient.name = "Salt" ingredient.volume = 1.0 ingredient.weight = 1.2 return ingredient } static var yeast: Ingredient { var ingredient = TestIngredient() ingredient.uuid = UUID(uuidString: "9814b4c8-e4dc-4197-a9b9-4ec3af437145")! ingredient.name = "Yeast" ingredient.volume = 1.25 ingredient.weight = 1.0 return ingredient } }
mit
4366b984f74b36f9b27cb4fb989c318c
28.105263
83
0.628692
3.840278
false
true
false
false
raulriera/HuntingCompanion
ProductHunt/StateViewContoller.swift
1
2481
// // StateViewContoller.swift // ProductHunt // // Created by Raúl Riera on 11/05/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit class StateViewContoller: UIViewController { private var titleLabel: UILabel! private var descriptionLabel: UILabel! private var imageView: UIImageView! override func loadView() { let applicationFrame = UIScreen.mainScreen().applicationFrame let contentView = UIView(frame: applicationFrame) contentView.backgroundColor = UIColor.whiteColor() view = contentView titleLabel = UILabel(frame: view.bounds) titleLabel.textAlignment = .Center titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .ByWordWrapping titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false) descriptionLabel = UILabel(frame: view.bounds) descriptionLabel.textAlignment = .Center descriptionLabel.numberOfLines = 0 descriptionLabel.lineBreakMode = .ByWordWrapping descriptionLabel.setTranslatesAutoresizingMaskIntoConstraints(false) view.addSubview(titleLabel) view.addSubview(descriptionLabel) setupConstraints() } private func setupConstraints() { let views = ["titleLabel": titleLabel, "descriptionLabel": descriptionLabel] // Center the title in the view and pin it to the edges view.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -20)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[titleLabel]-20-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)) // Pin the description to the title view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[descriptionLabel]-20-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[titleLabel]-4-[descriptionLabel]", options: NSLayoutFormatOptions(0), metrics: nil, views: views)) } }
mit
3bef1fb613921a4d9f22d9c187f8919c
44.925926
219
0.718548
5.688073
false
false
false
false
ksco/swift-algorithm-club-cn
Boyer-Moore/BoyerMoore.playground/Contents.swift
1
1181
//: Playground - noun: a place where people can play extension String { func indexOf(pattern: String) -> String.Index? { let patternLength = pattern.characters.count assert(patternLength > 0) assert(patternLength <= self.characters.count) var skipTable = [Character: Int]() for (i, c) in pattern.characters.enumerate() { skipTable[c] = patternLength - i - 1 } let p = pattern.endIndex.predecessor() let lastChar = pattern[p] var i = self.startIndex.advancedBy(patternLength - 1) func backwards() -> String.Index? { var q = p var j = i while q > pattern.startIndex { j = j.predecessor() q = q.predecessor() if self[j] != pattern[q] { return nil } } return j } while i < self.endIndex { let c = self[i] if c == lastChar { if let k = backwards() { return k } i = i.successor() } else { i = i.advancedBy(skipTable[c] ?? patternLength) } } return nil } } // A few simple tests let s = "Hello, World" s.indexOf("World") // 7 let animals = "🐶🐔🐷🐮🐱" animals.indexOf("🐮") // 6
mit
17f36c2eb723f477a122fe160dd20b53
22.26
57
0.565778
3.66877
false
false
false
false
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Polls/PollsList/PollTableViewCell.swift
1
2523
// // GenericTableViewCell.swift // GetSocialInternalDemo // // Copyright © 2020 GetSocial BV. All rights reserved. // import Foundation import UIKit protocol PollTableViewCellDelegate { func onShowActions(_ ofActivity: String) } class PollTableViewCell: UITableViewCell { var internalActivityId: String? var pollText: UILabel = UILabel() var totalVotes: UILabel = UILabel() var actionButton: UIButton = UIButton.init(type: .roundedRect) var delegate: PollTableViewCellDelegate? public required init?(coder: NSCoder) { super.init(coder: coder) addUIElements() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addUIElements() } func update(activity: Activity) { self.internalActivityId = activity.id self.pollText.text = "Text: \(activity.text ?? "")" self.totalVotes.text = "Total votes: \(activity.poll?.totalVotes ?? 0)" self.actionButton.setTitle("Actions", for: .normal) self.actionButton.addTarget(self, action: #selector(showActions(sender:)), for: .touchUpInside) } @objc func showActions(sender: Any?) { self.delegate?.onShowActions(self.internalActivityId!) } private func addUIElements() { self.actionButton.frame = CGRect(x: 0, y: 0, width: 140, height: 30) self.actionButton.setTitleColor(.black, for: .normal) self.actionButton.backgroundColor = .lightGray self.actionButton.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(self.actionButton) let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = 4 stackView.addArrangedSubview(self.pollText) stackView.addArrangedSubview(self.totalVotes) self.contentView.addSubview(stackView) NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: self.actionButton.leadingAnchor, constant: -8), stackView.topAnchor.constraint(equalTo: self.contentView.topAnchor), stackView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor), self.actionButton.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -8), self.actionButton.widthAnchor.constraint(equalToConstant: 80), self.actionButton.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor) ]) } }
apache-2.0
a50a3eb59d726c309fccdc37fe611a96
30.135802
103
0.751388
4.296422
false
false
false
false
Yummypets/YPImagePicker
Source/Filters/Video/YPVideoView.swift
1
4577
// // YPVideoView.swift // YPImagePicker // // Created by Nik Kov || nik-kov.com on 18.04.2018. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import Stevia import AVFoundation /// A video view that contains video layer, supports play, pause and other actions. /// Supports xib initialization. public class YPVideoView: UIView { public let playImageView = UIImageView(image: nil) internal let playerView = UIView() internal let playerLayer = AVPlayerLayer() internal var previewImageView = UIImageView() public var player: AVPlayer { guard let player = playerLayer.player else { return AVPlayer() } playImageView.image = YPConfig.icons.playImage return player } public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } internal func setup() { let singleTapGR = UITapGestureRecognizer(target: self, action: #selector(singleTap)) singleTapGR.numberOfTapsRequired = 1 addGestureRecognizer(singleTapGR) playerView.alpha = 0 playImageView.alpha = 0.8 playerLayer.videoGravity = .resizeAspect previewImageView.contentMode = .scaleAspectFit subviews( previewImageView, playerView, playImageView ) previewImageView.fillContainer() playerView.fillContainer() playImageView.centerInContainer() playerView.layer.addSublayer(playerLayer) } override public func layoutSubviews() { super.layoutSubviews() playerLayer.frame = playerView.bounds } @objc internal func singleTap() { pauseUnpause() } @objc public func playerItemDidReachEnd(_ note: Notification) { player.actionAtItemEnd = .none player.seek(to: CMTime.zero) player.play() } } // MARK: - Video handling extension YPVideoView { /// The main load video method public func loadVideo<T>(_ item: T) { var player: AVPlayer switch item.self { case let video as YPMediaVideo: player = AVPlayer(url: video.url) case let url as URL: player = AVPlayer(url: url) case let playerItem as AVPlayerItem: player = AVPlayer(playerItem: playerItem) default: return } playerLayer.player = player playerView.alpha = 1 setNeedsLayout() } /// Convenience func to pause or unpause video dependely of state public func pauseUnpause() { (player.rate == 0.0) ? play() : pause() } /// Mute or unmute the video public func muteUnmute() { player.isMuted = !player.isMuted } public func play() { player.play() showPlayImage(show: false) addReachEndObserver() } public func pause() { player.pause() showPlayImage(show: true) } public func stop() { player.pause() player.seek(to: CMTime.zero) showPlayImage(show: true) removeReachEndObserver() } public func deallocate() { playerLayer.player = nil playImageView.image = nil } } // MARK: - Other API extension YPVideoView { public func setPreviewImage(_ image: UIImage) { previewImageView.image = image } /// Shows or hide the play image over the view. public func showPlayImage(show: Bool) { UIView.animate(withDuration: 0.1) { self.playImageView.alpha = show ? 0.8 : 0 } } public func addReachEndObserver() { NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(_:)), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem) } /// Removes the observer for AVPlayerItemDidPlayToEndTime. Could be needed to implement own observer public func removeReachEndObserver() { NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem) } }
mit
77208e7f2d8320ddef0269fa63317a78
27.246914
104
0.578016
5.158963
false
false
false
false
DopamineLabs/DopamineKit-iOS
BoundlessKit/Classes/BKLog.swift
1
5701
// // BKLog.swift // BoundlessKit // // Created by Akash Desai on 3/14/18. // import Foundation @objc open class BKLogPreferences : NSObject { @objc open var printEnabled = true @objc open var debugEnabled = false // @objc open var debugEnabled = true } @objc open class BKLog : NSObject { @objc static let preferences = BKLogPreferences() /// This function prints to the console if preferences.printEnabled is true /// /// - parameters: /// - message: The debug message. /// - filePath: Used to get filename of bug. Do not use this parameter. Defaults to #file. /// - function: Used to get function name of bug. Do not use this parameter. Defaults to #function. /// - line: Used to get the line of bug. Do not use this parameter. Defaults to #line. /// @objc open class func print(_ message: String, filePath: String = #file, function: String = #function, line: Int = #line) { guard preferences.printEnabled else { return } var functionSignature:String = function if let parameterNames = functionSignature.range(of: "\\((.*?)\\)", options: .regularExpression) { functionSignature.replaceSubrange(parameterNames, with: "()") } let fileName = NSString(string: filePath).lastPathComponent Swift.print("[\(fileName):\(line):\(functionSignature)] - \(message)") } /// This function prints debug messages to the console if preferences.printEnabled and preferences.debugEnabled are true /// /// - parameters: /// - message: The debug message. /// - filePath: Used to get filename of bug. Do not use this parameter. Defaults to #file. /// - function: Used to get function name of bug. Do not use this parameter. Defaults to #function. /// - line: Used to get the line of bug. Do not use this parameter. Defaults to #line. /// @objc open class func debug(_ message: String, filePath: String = #file, function: String = #function, line: Int = #line) { guard preferences.printEnabled && preferences.debugEnabled else { return } var functionSignature:String = function if let parameterNames = functionSignature.range(of: "\\((.*?)\\)", options: .regularExpression) { functionSignature.replaceSubrange(parameterNames, with: "()") } let fileName = NSString(string: filePath).lastPathComponent Swift.print("[\(fileName):\(line):\(functionSignature)] - \(message)") } /// This function prints confirmation messages to the console if preferences.printEnabled and preferences.debugEnabled are true /// /// - parameters: /// - message: The confirmation message. /// - filePath: Used to get filename. Do not use this parameter. Defaults to #file. /// - function: Used to get function name. Do not use this parameter. Defaults to #function. /// - line: Used to get the line. Do not use this parameter. Defaults to #line. /// @objc open class func debug(confirmed message: String, filePath: String = #file, function: String = #function, line: Int = #line) { guard preferences.printEnabled && preferences.debugEnabled else { return } var functionSignature:String = function if let parameterNames = functionSignature.range(of: "\\((.*?)\\)", options: .regularExpression) { functionSignature.replaceSubrange(parameterNames, with: "()") } let fileName = NSString(string: filePath).lastPathComponent Swift.print("[\(fileName):\(line):\(functionSignature)] - ✅ \(message)") } /// This function prints error messages to the console if preferences.printEnabled and preferences.debugEnabled are true /// /// - parameters: /// - message: The debug message. /// - visual: If true, also displays an OK alert. /// - filePath: Used to get filename of bug. Do not use this parameter. Defaults to #file. /// - function: Used to get function name of bug. Do not use this parameter. Defaults to #function. /// - line: Used to get the line of bug. Do not use this parameter. Defaults to #line. /// @objc open class func debug(error message: String, visual: Bool = false, filePath: String = #file, function: String = #function, line: Int = #line) { guard preferences.printEnabled && preferences.debugEnabled else { return } var functionSignature:String = function if let parameterNames = functionSignature.range(of: "\\((.*?)\\)", options: .regularExpression) { functionSignature.replaceSubrange(parameterNames, with: "()") } let fileName = NSString(string: filePath).lastPathComponent Swift.print("[\(fileName):\(line):\(functionSignature)] - ❌ \(message)") if visual { alert(title: "☠️", message: "🚫 \(message)") } } /// This function displays an OK alert if preferences.printEnabled and preferences.debugEnabled are true /// /// - parameters: /// - message: The debug message. /// - title: The alert's title. /// @objc open class func alert(title: String, message: String) { guard preferences.printEnabled && preferences.debugEnabled else { return } DispatchQueue.main.async { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) UIWindow.presentTopLevelAlert(alertController: alertController) } } }
mit
34eb2b07e3146530f57ba55cc22baf39
49.803571
154
0.644464
4.614761
false
false
false
false
arvindhsukumar/PredicateEditor
PredicateEditor/Classes/PredicateEditorViewController.swift
1
6486
// // PredicateEditorViewController.swift // Pods // // Created by Arvindh Sukumar on 07/07/16. // // import UIKit import StackViewController import SnapKit public struct PredicatorEditorConfig { public var keyPathDisplayColor: UIColor! public var comparisonButtonColor: UIColor! public var inputColor: UIColor! public var backgroundColor: UIColor! public var sectionBackgroundColor: UIColor! public var errorColor: UIColor! public init() { self.keyPathDisplayColor = UIColor(red:0.64, green:0.41, blue:0.65, alpha:1.00) self.comparisonButtonColor = UIColor(red:0.27, green:0.47, blue:0.74, alpha:1.00) self.inputColor = UIColor(red:0.00, green:0.53, blue:0.19, alpha:1.00) self.backgroundColor = UIColor(red:0.87, green:0.89, blue:0.93, alpha:1.00) self.sectionBackgroundColor = UIColor(red:0.94, green:0.95, blue:0.97, alpha:1.00) self.errorColor = UIColor(red:0.44, green:0.15, blue:0.20, alpha:1.00) } } @objc public protocol PredicateEditorDelegate { func predicateEditorDidFinishWithPredicates(predicates: [NSPredicate]) } public class PredicateEditorViewController: UIViewController { public weak var delegate: PredicateEditorDelegate? var config: PredicatorEditorConfig! var sections: [Section] = [] var sectionViews: [SectionView] = [] private let stackViewController: StackViewController public convenience init(sections:[Section], config: PredicatorEditorConfig = PredicatorEditorConfig() ) { self.init() self.sections = sections self.config = config } init() { stackViewController = StackViewController() stackViewController.stackViewContainer.separatorViewFactory = StackViewContainer.createSeparatorViewFactory() super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(PredicateEditorViewController.dismiss)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(PredicateEditorViewController.createPredicateAndDismiss)) edgesForExtendedLayout = .None setupStackView() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.translucent = false } private func setupStackView(){ stackViewController.view.backgroundColor = config.backgroundColor addChildViewController(stackViewController) view.addSubview(stackViewController.view) stackViewController.view.snp_makeConstraints { make in make.edges.equalTo(view) } stackViewController.didMoveToParentViewController(self) stackViewController.stackViewContainer.scrollView.alwaysBounceVertical = true for section in sections { let sectionViewController = SectionViewController(section: section, config: config) stackViewController.addItem(sectionViewController) } } func dismiss() { dismissViewControllerAnimated(true, completion: nil) } func createPredicateAndDismiss() { do { try delegate?.predicateEditorDidFinishWithPredicates(predicates()) dismiss() } catch RowPredicateError.InsufficientData(keyPath: let keyPath) { var message: String = "Please update all filters" if let kp = keyPath { message = "Please update value for \"\(kp.title)\"" } showErrorToast(message) } catch { print(error) } } private func showErrorToast(message: String){ navigationItem.rightBarButtonItem?.enabled = false let toast = ErrorToastView(message: message) toast.backgroundColor = config.errorColor let tap = UITapGestureRecognizer(target: self, action: #selector(PredicateEditorViewController.dismissToastOnTap(_:))) var toastTopConstraint: Constraint! view.addSubview(toast) toast.snp_makeConstraints { (make) in make.left.equalTo(view) make.right.equalTo(view) toastTopConstraint = make.top.equalTo(view.snp_bottom).constraint } view.setNeedsLayout() view.layoutIfNeeded() UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: UIViewAnimationOptions.CurveEaseInOut, animations: { toastTopConstraint.updateOffset(-toast.frame.size.height) self.view.setNeedsLayout() self.view.layoutIfNeeded() }) { (finished) in let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.hideErrorToast(toast) } } } func dismissToastOnTap(gesture: UITapGestureRecognizer) { if gesture.state == UIGestureRecognizerState.Recognized { hideErrorToast(gesture.view as! ErrorToastView) } } private func hideErrorToast(toast: ErrorToastView){ var frame = toast.frame UIView.animateWithDuration(0.25, animations: { frame.origin.y = self.view.frame.size.height toast.frame = frame }) { (finished: Bool) in toast.removeFromSuperview() self.navigationItem.rightBarButtonItem?.enabled = true } } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } public extension PredicateEditorViewController { public func predicates() throws -> [NSPredicate] { let predicates = try sections.map({ (section) -> NSPredicate in return try section.compoundPredicate() }) return predicates.filter({ (predicate:NSPredicate) -> Bool in return !predicate.isEmpty }) } }
mit
c1b301488ca4216154c8aa145e6bd1c0
35.234637
198
0.660037
5.051402
false
true
false
false
SASAbus/SASAbus-ios
SASAbus/Util/Extensions/JSONExtension.swift
1
858
import SwiftyJSON extension JSON { func to<T>(type: T?) -> Any? { if let baseObj = type as? JSONable.Type { if self.type == .array { var arrObject: [Any] = [] for obj in self.arrayValue { let object = baseObj.init(parameter: obj) arrObject.append(object) } return arrObject } else { return baseObj.init(parameter: self) } } return nil } } protocol JSONCollection { static func collection(parameter: JSON) -> [Self] } protocol JSONable { init(parameter: JSON) } extension Array { func find(_ predicate: (Array.Iterator.Element) throws -> Bool) rethrows -> Array.Iterator.Element? { return try index(where: predicate).map({ self[$0] }) } }
gpl-3.0
5efc32730754eb29acc159a0fe8027bd
22.189189
105
0.529138
4.268657
false
false
false
false
KaushalElsewhere/AllHandsOn
KeyboardObserverTry/KeyboardObserverTry/Utility/Keyboard.swift
1
3382
// // Keyboard.swift // Ello // // Created by Colin Gray on 2/26/2015. // Copyright (c) 2015 Ello. All rights reserved. // import UIKit import Foundation import CoreGraphics private let sharedKeyboard = Keyboard() public class Keyboard { public struct Notifications { public static let KeyboardWillShow = TypedNotification<Keyboard>(name: "com.elsewhere.Keyboard.KeyboardWillShow") public static let KeyboardDidShow = TypedNotification<Keyboard>(name: "com.elsewhere.Keyboard.KeyboardDidShow") public static let KeyboardWillHide = TypedNotification<Keyboard>(name: "com.elsewhere.Keyboard.KeyboardWillHide") public static let KeyboardDidHide = TypedNotification<Keyboard>(name: "com.elsewhere.Keyboard.KeyboardDidHide") } public class func shared() -> Keyboard { return sharedKeyboard } public class func setup() { let _ = shared() } public var active = false public var external = false public var bottomInset: CGFloat = 0.0 public var endFrame = CGRectZero public var curve = UIViewAnimationCurve.Linear public var options = UIViewAnimationOptions.CurveLinear public var duration: Double = 0.0 public init() { let center: NSNotificationCenter = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: #selector(Keyboard.willShow(_:)), name: UIKeyboardWillShowNotification, object: nil) center.addObserver(self, selector: #selector(Keyboard.didShow(_:)), name: UIKeyboardDidShowNotification, object: nil) center.addObserver(self, selector: #selector(Keyboard.willHide(_:)), name: UIKeyboardWillHideNotification, object: nil) center.addObserver(self, selector: #selector(Keyboard.didHide(_:)), name: UIKeyboardDidHideNotification, object: nil) } deinit { let center: NSNotificationCenter = NSNotificationCenter.defaultCenter() center.removeObserver(self) } public func keyboardBottomInset(inView inView: UIView) -> CGFloat { let window: UIView = inView.window ?? inView let bottom = window.convertPoint(CGPoint(x: 0, y: window.bounds.size.height - bottomInset), toView: inView.superview).y let inset = inView.frame.size.height - bottom if inset < 0 { return 0 } else { return inset } } @objc func didShow(notification: NSNotification) { postNotification(Notifications.KeyboardDidShow, value: self) } @objc func didHide(notification: NSNotification) { postNotification(Notifications.KeyboardDidHide, value: self) } func setFromNotification(notification: NSNotification) { if let durationValue = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber { duration = durationValue.doubleValue } else { duration = 0 } if let rawCurveValue = (notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber) { let rawCurve = rawCurveValue.integerValue curve = UIViewAnimationCurve(rawValue: rawCurve) ?? .EaseOut let curveInt = UInt(rawCurve << 16) options = UIViewAnimationOptions(rawValue: curveInt) } else { curve = .EaseOut options = .CurveEaseOut } } }
mit
d4c2864f65cc01ee84eead960f3b9cac
35.365591
127
0.67948
5.070465
false
false
false
false
hirooka/chukasa-ios
chukasa-ios/src/controller/ChukasaViewController.swift
1
11593
import UIKit import CoreData import WatchConnectivity class ChukasaViewController: UIViewController, URLSessionDelegate, ChukasaCoreDataOperatorDelegate { let START_API = "api/v1/chukasa/start" let STOP_API = "api/v1/chukasa/stop" let chukasaCoreDataOperator = ChukasaCoreDataOperator() var playlistType = PlaylistType.LIVE.rawValue var streamingType = StreamingType.TUNER.rawValue var remoteControllerChannel = 0 var physicalLogicalChannel = 0 var fileName = "" override func viewDidLoad() { super.viewDidLoad() self.getPlaylist() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func isSettingsExist() -> Bool { let chukasaServerSettingsArray = chukasaCoreDataOperator.fetch("ChukasaServerSettings", key: "id", ascending: true) if chukasaServerSettingsArray.count == 1 { let chukasaSettingsArray = chukasaCoreDataOperator.fetch("ChukasaSettings", key: "id", ascending: true) if chukasaSettingsArray.count == 1 { return true } } return false } @IBOutlet weak var buttonStartChukasa: UIButton! @IBAction func buttonStartChukasa(_ sender: Any) { self.getPlaylist() } @IBOutlet weak var buttonStopChukasa: UIButton! @IBAction func buttonStopChukasa(_ sender: Any) { var chukasaServerDestination = ChukasaServerDestination() let chukasaServerDestinationArray = chukasaCoreDataOperator.fetch("ChukasaServerDestination", key: "id", ascending: true) if chukasaServerDestinationArray.count == 1 { chukasaServerDestination = EntityConvertor.convertChukasaServerDestination(chukasaServerDestinationArray[0] as AnyObject) } let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) let urlString = "\(chukasaServerDestination.scheme.rawValue)://\(chukasaServerDestination.host):\(chukasaServerDestination.port)/\(STOP_API)"; let url = URLComponents(string: urlString) let murableRequest = NSMutableURLRequest(url: (url?.url)!) var request: URLRequest = murableRequest as URLRequest let username = chukasaServerDestination.username let password = chukasaServerDestination.password let loginString = String(format: "%@:%@", username, password) let loginData = loginString.data(using: String.Encoding.utf8)! let base64LoginString = loginData.base64EncodedString() request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") let task = session.dataTask(with: request, completionHandler: { (data, response, error) in do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary print(json) //let status = json.object(forKey: "status") as! String //print("status = \(status)") } catch { // } self.sendStopNotification() DispatchQueue.main.async(execute: { self.buttonStartChukasa.isEnabled = true self.buttonStopChukasa.isEnabled = false }) }) task.resume() } func sendHLSStartNotification(_ chukasaHLSPlaylistNotification: ChukasaHLSPlaylistNotification){ NotificationCenter.default.post(name: Notification.Name(rawValue: "playlist"), object: chukasaHLSPlaylistNotification) } // func sendNotification(_ chukasaPlaylistNotificationModel: ChukasaPlaylistNotificationModel){ // NotificationCenter.default.post(name: Notification.Name(rawValue: "playlist"), object: chukasaPlaylistNotificationModel) // } func sendM4vNotification(_ chukasaHLSPlaylistNotification: ChukasaHLSPlaylistNotification){ NotificationCenter.default.post(name: Notification.Name(rawValue: "m4v"), object: chukasaHLSPlaylistNotification) } func sendStopNotification(){ NotificationCenter.default.post(name: Notification.Name(rawValue: "stop"), object: nil) } @IBAction func barButtonItemClose(_ sender: Any) { dismiss(animated: true, completion: nil) } // @IBOutlet weak var barButtonItemBack: UIBarButtonItem! @IBAction func barButtonItemBack(_ sender: Any) { NotificationCenter.default.post(name: Notification.Name(rawValue: "webView"), object: "back") } @IBOutlet weak var barButtonItemReload: UIBarButtonItem! @IBAction func barButtonItemReload(_ sender: Any) { NotificationCenter.default.post(name: Notification.Name(rawValue: "webView"), object: "reload") } @IBOutlet weak var barButtonItemForward: UIBarButtonItem! @IBAction func barButtonItemForward(_ sender: Any) { NotificationCenter.default.post(name: Notification.Name(rawValue: "webView"), object: "forward") } @IBOutlet weak var barButtonItemHome: UIBarButtonItem! @IBAction func barButtonItemHome(_ sender: Any) { NotificationCenter.default.post(name: Notification.Name(rawValue: "webView"), object: "home") } func getPlaylist(){ var chukasaServerDestination = ChukasaServerDestination() let chukasaServerDestinationArray = chukasaCoreDataOperator.fetch("ChukasaServerDestination", key: "id", ascending: true) if chukasaServerDestinationArray.count == 1 { chukasaServerDestination = EntityConvertor.convertChukasaServerDestination(chukasaServerDestinationArray[0] as AnyObject) } var chukasaPreferences = ChukasaPreferences() let chukasaPreferencesArray = chukasaCoreDataOperator.fetch("ChukasaPreferences", key: "id", ascending: true) if chukasaPreferencesArray.count == 1 { chukasaPreferences = EntityConvertor.convertChukasaPreferences(chukasaPreferencesArray[0] as AnyObject) } let chukasaPreferencesDictionary = [ "channelRecording" : physicalLogicalChannel, "transcodingSettings" : chukasaPreferences.transcodingSettings.rawValue, "canEncrypt" : chukasaPreferences.canEncrypt, "fileName" : fileName, "playlistType" : playlistType, "streamingType" : streamingType ] as [String : Any] // TODO: - check if true { do { let chukasaSettings = try JSONSerialization.data(withJSONObject: chukasaPreferencesDictionary, options: JSONSerialization.WritingOptions.prettyPrinted) let sessionConfiguration = URLSessionConfiguration.default let urlSession = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil) let urlString = "\(chukasaServerDestination.scheme.rawValue)://\(chukasaServerDestination.host):\(chukasaServerDestination.port)/\(START_API)" print("Chukasa Server -> \(urlString)") let url = URLComponents(string: urlString) let mutableURLRequest = NSMutableURLRequest(url: (url?.url)!) mutableURLRequest.httpMethod = "POST" mutableURLRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") let username = chukasaServerDestination.username let password = chukasaServerDestination.password let loginString = String(format: "%@:%@", username, password) let loginData = loginString.data(using: String.Encoding.utf8)! let base64LoginString = loginData.base64EncodedString() mutableURLRequest.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") let urlSessionUploadTask = urlSession.uploadTask(with: mutableURLRequest as URLRequest, from: chukasaSettings, completionHandler: { (data, response, error) in if error != nil { DispatchQueue.main.async(execute: { let message = error?.localizedDescription let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) }) return } let urlComponents = URLComponents(string: (response?.url?.absoluteString)!) let scheme = urlComponents?.scheme let host = urlComponents?.host var port = urlComponents?.port let path = urlComponents?.path print("response -> \(response?.mimeType), \(response?.url?.absoluteString), \(scheme), \(host), \(port), \(path)") let responseData = String(data: data!, encoding: String.Encoding.utf8) print(responseData as Any) do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary let playlistURI = json.object(forKey: "uri") as! String if port == nil { port = NSNumber(value: 80 as Int) as Int? } let enumScheme = URIScheme(rawValue: scheme!) let chukasaHLSPlaylist = ChukasaHLSPlaylist(scheme: enumScheme!, host: host!, port: Int(port!), path: path!) let chukasaHLSPlaylistNotification = ChukasaHLSPlaylistNotification(chukasaHLSPlaylist: chukasaHLSPlaylist, chukasaPreferences: chukasaPreferences, hlsPlaylistURI: playlistURI) self.sendHLSStartNotification(chukasaHLSPlaylistNotification) } catch { // } let redirectAbsoluteURI = response?.url?.absoluteString let playlistURI = redirectAbsoluteURI?.components(separatedBy: ";")[0] print("playlistURI -> \(playlistURI)") DispatchQueue.main.async(execute: { self.buttonStartChukasa.isEnabled = false self.buttonStopChukasa.isEnabled = true }) urlSession.invalidateAndCancel() }) urlSessionUploadTask.resume() } catch { print("error") } }else{ DispatchQueue.main.async(execute: { let message = "No settings" let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) }) } } }
mit
2ee7f15c3601103f218d02253be408cf
48.122881
200
0.61839
5.296026
false
false
false
false
wxxsw/GSMessages
GSMessagesExample/GSMessagesExample/ViewController.swift
1
5431
// // ViewController.swift // GSMessagesExample // // Created by Gesen on 15/7/10. // Copyright (c) 2015年 Gesen. All rights reserved. // import UIKit import GSMessages class ViewController: UIViewController { @IBOutlet weak var someView: UIView! @IBAction func tapSuccess(_ sender: AnyObject) { showMessage("Something success", type: .success) } @IBAction func tapError(_ sender: AnyObject) { showMessage("Something failed", type: .error) } @IBAction func tapWarning(_ sender: AnyObject) { showMessage("Some warning", type: .warning) } @IBAction func tapInfo(_ sender: AnyObject) { showMessage("Some message", type: .info, options: [ .handleTap({ print("Custom tap handle") }) ]) } @IBAction func tapEndless(_ sender: AnyObject) { showMessage("Endless", type: .success, options: [ .autoHide(false), .hideOnTap(false) ]) } @IBAction func tapDismiss(_ sender: AnyObject) { hideMessage() someView.hideMessage() } @IBAction func tapFade(_ sender: AnyObject) { showMessage("Fade", type: .success, options: [.animations([.fade])]) } @IBAction func tapLongTime(_ sender: AnyObject) { showMessage("Long Time", type: .success, options: [.autoHideDelay(10)]) } @IBAction func tapInView(_ sender: AnyObject) { someView.showMessage("In View", type: .success) } @IBAction func tapHeight(_ sender: AnyObject) { showMessage("Height", type: .success, options: [.height(100)]) } @IBAction func tapLongText(_ sender: AnyObject) { showMessage("This will be a very long message that someone wanna show in a high message", type: .success, options: [.textNumberOfLines(0)]) } @IBAction func tapBottom(_ sender: AnyObject) { showMessage("Bottom", type: .success, options: [.position(.bottom)]) } @IBAction func tapMargin(_ sender: Any) { someView.showMessage("Margin", type: .success, options: [ .margin(.init(top: 20, left: 20, bottom: 0, right: 20)), .cornerRadius(5) ]) } @IBAction func tapPadding(_ sender: Any) { showMessage("Padding,Padding,Padding,Padding,Padding,Padding", type: .success, options: [ .padding(.init(top: 10, left: 50, bottom: 10, right: 0)) ]) } @IBAction func tapRoundedCorners(_ sender: Any) { showMessage("Rounded Corners", type: .success, options: [ .cornerRadius(10), .margin(.init(top: 0, left: 10, bottom: 0, right: 10)) ]) } @IBAction func tapTopLeft(_ sender: AnyObject) { showMessage("TopLeft", type: .success, options: [ .textAlignment(.topLeft), .height(60) ]) } @IBAction func tapCenter(_ sender: AnyObject) { showMessage("Center", type: .success, options: [ .textAlignment(.center), .height(60) ]) } @IBAction func tapBottomRight(_ sender: AnyObject) { showMessage("BottomRight", type: .success, options: [ .textAlignment(.bottomRight), .height(60) ]) } @IBAction func tapWindow(_ sender: Any) { guard let window = UIApplication.shared.keyWindow else { return } let attributedText = NSAttributedString( string: "In Window", attributes: [ .font: GSMessage.font, .paragraphStyle: NSParagraphStyle() ] ) let paddingX: CGFloat = 14 let maxWidth = view.bounds.width - 20 - paddingX * 2 let size = attributedText.sizeToFits(CGSize(width: maxWidth, height: 20)) let marginX = (view.bounds.width - size.width - paddingX * 2) / 2 let marginY = (navigationController!.isNavigationBarHidden ? 0 : navigationController!.navigationBar.frame.height) + UIApplication.shared.statusBarFrame.height + 10 let options: [GSMessageOption] = [ .animations([.fade, .slide(.distance(50))]), .cornerRadius(16), .height(32), .margin(.init(top: marginY, left: marginX, bottom: 0, right: marginX)), .padding(.init(top: 6, left: paddingX, bottom: 6, right: paddingX)), ] GSMessage.showMessageAddedTo( attributedText: attributedText, type: .success, options: options, inView: window, inViewController: nil ) } @IBAction func tapToggleNavBarTranslucent(_ sender: AnyObject) { navigationController!.navigationBar.isTranslucent = !navigationController!.navigationBar.isTranslucent } @IBAction func tapToggleNavBarHidden(_ sender: AnyObject) { navigationController!.setNavigationBarHidden(!navigationController!.isNavigationBarHidden, animated: true) } } private extension NSAttributedString { func sizeToFits(_ size: CGSize) -> CGSize { let framesetter = CTFramesetterCreateWithAttributedString(self as CFAttributedString) let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRange(), nil, size, nil) return textSize } }
mit
cc82e1e671caed636ac689c000bde03a
31.315476
172
0.592006
4.696367
false
false
false
false
hyperoslo/Wall
Source/Cells/PostTableViewCell.swift
2
8169
import UIKit public protocol PostActionDelegate: class { func likeButtonDidPress(postID: Int) func commentsButtonDidPress(postID: Int) } public protocol PostInformationDelegate: class { func likesInformationDidPress(postID: Int) func commentsInformationDidPress(postID: Int) func seenInformationDidPress(postID: Int) func authorDidTap(postID: Int) func mediaDidTap(postID: Int, kind: Media.Kind, index: Int) func groupDidTap(postID: Int) func reportButtonDidPress(postID: Int) } public class PostTableViewCell: WallTableViewCell { public static let reusableIdentifier = "PostTableViewCell" public override class func height(post: Post) -> CGFloat { let postText = post.text as NSString let textFrame = postText.boundingRectWithSize(CGSize(width: UIScreen.mainScreen().bounds.width - 40, height: CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [ NSFontAttributeName : FontList.Post.text ], context: nil) var imageHeight: CGFloat = ceil((UIScreen.mainScreen().bounds.width - 20) / 1.295) var imageTop: CGFloat = 60 if post.media.isEmpty { imageHeight = 0 imageTop = 50 } var textOffset: CGFloat = 12 if post.text == "" { textOffset = 0 } var informationHeight: CGFloat = 44 if (post.likeCount == 0 && post.commentCount == 0 && post.text == "") || (post.likeCount == 0 && post.commentCount == 0) { informationHeight = 16 } return ceil(imageHeight + imageTop + informationHeight + 44 + 14 + textOffset + textFrame.height) } public lazy var authorView: PostAuthorView = { [unowned self] in let view = PostAuthorView() view.delegate = self return view }() public lazy var postMediaView: PostMediaView = { [unowned self] in let view = PostMediaView() view.delegate = self return view }() public lazy var textView: UITextView = { [unowned self] in let textView = UITextView() textView.font = FontList.Post.text textView.dataDetectorTypes = .Link textView.editable = false textView.scrollEnabled = false textView.delegate = self textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = UIEdgeInsetsZero textView.linkTextAttributes = [ NSForegroundColorAttributeName: ColorList.Basis.highlightedColor, NSUnderlineColorAttributeName: ColorList.Basis.highlightedColor, NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue] textView.subviews.first?.backgroundColor = UIColor.whiteColor() return textView }() public lazy var informationView: PostInformationBarView = { [unowned self] in let view = PostInformationBarView() view.delegate = self return view }() public lazy var actionBarView: PostActionBarView = { [unowned self] in let view = PostActionBarView() view.delegate = self return view }() public lazy var bottomSeparator: UIView = { let view = UIView() return view }() public weak var actionDelegate: PostActionDelegate? public weak var informationDelegate: PostInformationDelegate? public var detail = false // MARK: - Initialization public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) [authorView, postMediaView, textView, informationView, actionBarView, bottomSeparator].forEach { addSubview($0) $0.opaque = true $0.backgroundColor = UIColor.whiteColor() $0.layer.drawsAsynchronously = true } bottomSeparator.backgroundColor = ColorList.Basis.tableViewBackground opaque = true selectionStyle = .None } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup public override func configureCell(post: Post) { super.configureCell(post) guard let author = post.author else { return } var imageHeight: CGFloat = 0 var imageTop: CGFloat = 50 if !post.media.isEmpty { imageHeight = ceil((UIScreen.mainScreen().bounds.width - 20) / 1.295) imageTop = 60 postMediaView.configureView(post.media) postMediaView.alpha = 1 } else { postMediaView.alpha = 0 } var informationHeight: CGFloat = 44 if (post.likeCount == 0 && post.commentCount == 0 && post.text == "") || (post.likeCount == 0 && post.commentCount == 0) { informationHeight = 16 } if detail && post.likeCount == 0 { informationHeight = 16 } var textOffset: CGFloat = 12 if post.text == "" { textOffset = 0 } authorView.frame = CGRectIntegral(CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 60)) postMediaView.frame = CGRectIntegral(CGRect(x: 0, y: imageTop, width: UIScreen.mainScreen().bounds.width, height: imageHeight)) informationView.frame.size = CGSize(width: UIScreen.mainScreen().bounds.width, height: ceil(informationHeight)) actionBarView.frame.size = CGSize(width: UIScreen.mainScreen().bounds.width, height: 44) bottomSeparator.frame = CGRectIntegral(CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 14)) authorView.configureView(author, date: post.publishDate, group: post.group) informationView.configureView(post.likeCount, comments: post.commentCount, seen: post.seenCount) actionBarView.configureView(post.liked) textView.text = post.text textView.frame.size.width = UIScreen.mainScreen().bounds.width - 40 textView.sizeToFit() textView.frame = CGRectIntegral(CGRect(x: 20, y: CGRectGetMaxY(postMediaView.frame) + textOffset, width: textView.frame.width, height: textView.frame.height)) informationView.frame.origin = CGPoint(x: 0, y: ceil(CGRectGetMaxY(textView.frame))) actionBarView.frame.origin = CGPoint(x: 0, y: ceil(CGRectGetMaxY(informationView.frame))) bottomSeparator.frame.origin.y = ceil(CGRectGetMaxY(actionBarView.frame)) } } // MARK: - UITextViewDelegate extension PostTableViewCell: UITextViewDelegate { public func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { return true } } // MARK: - PostInformationBarViewDelegate extension PostTableViewCell: PostInformationBarViewDelegate { public func likesInformationButtonDidPress() { guard let post = post else { return } informationDelegate?.likesInformationDidPress(post.id) } public func commentInformationButtonDidPress() { guard let post = post else { return } informationDelegate?.commentsInformationDidPress(post.id) } public func seenInformationButtonDidPress() { guard let post = post else { return } informationDelegate?.seenInformationDidPress(post.id) } } // MARK: - PostActionBarViewDelegate extension PostTableViewCell: PostActionBarViewDelegate { public func likeButtonDidPress(liked: Bool) { guard let post = post else { return } post.liked = liked post.likeCount += liked ? 1 : -1 informationView.configureLikes(post.likeCount) informationView.configureComments(post.commentCount) delegate?.updateCellSize(post.id, liked: liked) actionDelegate?.likeButtonDidPress(post.id) } public func commentButtonDidPress() { guard let post = post else { return } actionDelegate?.commentsButtonDidPress(post.id) } } // MARK: - PostAuthorViewDelegate extension PostTableViewCell: PostAuthorViewDelegate { public func authorDidTap() { guard let post = post else { return } informationDelegate?.authorDidTap(post.id) } public func groupDidTap() { guard let post = post else { return } informationDelegate?.groupDidTap(post.id) } public func reportButtonDidPress() { guard let post = post else { return } informationDelegate?.reportButtonDidPress(post.id) } } extension PostTableViewCell: PostMediaViewDelegate { public func mediaDidTap(index: Int) { guard let post = post, firstMedia = post.media.first else { return } informationDelegate?.mediaDidTap(post.id, kind: firstMedia.kind, index: index) } }
mit
d382d2800ae21adce43c314605a57a3d
30.419231
131
0.713184
4.434853
false
false
false
false
billyburton/SwiftMySql
Tests/SwiftMySqlTests/Dog.swift
1
1775
// // Dog.swift // SwiftMySql // // Created by William Burton on 17/02/2017. // // import Foundation import SwiftMySql class Dog { let name: String let age: Int init(name: String, age: Int) { self.name = name self.age = age } } extension Dog: MySqlReadAdapterProtocol { public static func build(reader: MySqlReaderProtocol) throws -> MySqlReadAdapterProtocol { do { let name = try reader.getString(columnName: "name") let dog = Dog(name: name, age: 2) return dog } } public static var readCommandText: String { return "SELECT * FROM Dogs" } static func createCommand(connection: MySqlConnectionProtocol) -> MySqlCommandProtocol { let reader = try? MySqlReaderMock(connection: connection) let command = MySqlCommandMock(command: readCommandText, connection: connection) command.reader = reader! return command } } extension Dog: MySqlCreateAdapterProtocol { public var createCommandText: String { return "INSERT INTO Dogs VALUES (@name, @age)" } var createParameters: [String : String] { return ["@name": self.name, "@age": String(describing: self.age)] } } extension Dog: MySqlUpdateAdapterProtocol { public var updateCommandText: String { return "UPDATE Dogs SET Age = @age WHERE Name = @name" } var updateParameters: [String: String] { return ["@name": self.name, "@age": String(describing: self.age)] } } extension Dog: MySqlDeleteAdapterProtocol { public var deleteCommandText: String { return "DELETE FROM Dogs WHERE Name = 'Fido'" } var deleteParameters: [String: String] { return ["@name": self.name] } }
apache-2.0
5d7e59a5405c628b5e248707d3637ff5
24
94
0.636056
3.953229
false
false
false
false
nayzak/Swift-MVVM
Swift MVVM/Framework/Dynamic/Command.swift
1
930
// // Command.swift // // Created by NayZaK on 24.02.15. // Copyright (c) 2015 Amur.net. All rights reserved. // import Foundation final class Command<T> { typealias CommandType = (value: T, sender: AnyObject?) -> () weak var enabled: Dynamic<Bool>? private let command: CommandType init (enabled: Dynamic<Bool>, command: CommandType) { self.enabled = enabled self.command = command } init (command: CommandType) { self.command = command } func execute(value: T) { execute(value, sender: nil) } func execute(value: T, sender: AnyObject?) { var enabled = true if let en = self.enabled?.value { enabled = en } if enabled { command(value: value, sender: sender) } } } protocol Commander { typealias CommandType func setCommand(command: Command<CommandType>) } func >> <T, B: Commander where B.CommandType == T>(left: B, right: Command<T>) { left.setCommand(right) }
mit
5b15fc2003b3ca70358d025897e349d4
20.651163
80
0.663441
3.549618
false
false
false
false
avito-tech/Paparazzo
Example/PaparazzoExample/StreamHandlers/ObjectsRecognitionStreamHandler.swift
1
1691
import Paparazzo import ImageIO import Vision import CoreML @available(iOS 11.0, *) final class ObjectsRecognitionStreamHandler: ScannerOutputHandler { let sampler = Sampler(delay: 0.1) var onRecognize: ((_ label: String) -> ())? var orientation: UInt32 = 0 var imageBuffer: CVImageBuffer? { didSet { sampler.sample { [weak self] in guard let model = try? VNCoreMLModel(for: SqueezeNet().model), let handleVisionRequestUpdate = self?.handleVisionRequestUpdate else { return } let request = VNCoreMLRequest(model: model, completionHandler: handleVisionRequestUpdate) do { if let imageBuffer = self?.imageBuffer, let strongSelf = self { try strongSelf.visionSequenceHandler.perform( [request], on: imageBuffer, orientation: CGImagePropertyOrientation(rawValue: strongSelf.orientation) ?? .left ) } } catch { print("Throws: \(error)") } } } } private let visionSequenceHandler = VNSequenceRequestHandler() private func handleVisionRequestUpdate(_ request: VNRequest, error: Error?) { DispatchQueue.main.async { guard let topResult = request.results?.first as? VNClassificationObservation else { return } self.onRecognize?(topResult.identifier) } } }
mit
42865158e7ad09985daacf0108a55b1b
30.90566
110
0.529273
5.655518
false
false
false
false
CallMeMrAlex/DYTV
DYTV-AlexanderZ-Swift/DYTV-AlexanderZ-Swift/Classes/Main(主框架)/Model/AnchorModel.swift
1
812
// // AnchorModel.swift // DYTV-AlexanderZ-Swift // // Created by Alexander Zou on 16/9/30. // Copyright © 2016年 Alexander Zou. All rights reserved. // import UIKit class AnchorModel: NSObject { // 房间id var room_id : Int = 0 // 房间缩略图 var vertical_src : String = "" // 判断是手机直播还是电脑直播 var isVertical : Int = 0 // 房间名称 var room_name : String = "" // 主播昵称 var nickname : String = "" // 在线人数 var online : Int = 0 // 所在的城市 var anchor_city : String = "" init(dict : [String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
mit
758cef239ea326eaaaf80759ffe78219
16.926829
73
0.542857
3.848168
false
false
false
false
xmartlabs/AKPickerView-Swift
AKPickerViewSample/ViewController.swift
1
2622
// // ViewController.swift // AKPickerViewSample // // Created by Akio Yasui on 2/10/15. // Copyright (c) 2015 Akio Yasui. All rights reserved. // import UIKit class ViewController: UIViewController, AKPickerViewDataSource, AKPickerViewDelegate { @IBOutlet var pickerView: AKPickerView! @IBOutlet weak var leftArrow: UIButton! @IBOutlet weak var rigthArrow: UIButton! let titles = ["Tokyo", "Kanagawa", "Osaka", "Aichi", "Saitama", "Chiba", "Hyogo", "Hokkaido", "Fukuoka", "Shizuoka"] override func viewDidLoad() { super.viewDidLoad() self.pickerView.delegate = self self.pickerView.dataSource = self self.pickerView.font = UIFont(name: "HelveticaNeue-Light", size: 20)! self.pickerView.highlightedFont = UIFont(name: "HelveticaNeue", size: 20)! self.pickerView.pickerViewStyle = .Wheel self.pickerView.maskDisabled = false self.pickerView.highlightedTextColor = UIColor.blueColor() self.pickerView.reloadData() } // MARK: - AKPickerViewDataSource func numberOfItemsInPickerView(pickerView: AKPickerView) -> Int { return self.titles.count } /* Image Support ------------- Please comment '-pickerView:titleForItem:' entirely and uncomment '-pickerView:imageForItem:' to see how it works. */ func pickerView(pickerView: AKPickerView, titleForItem item: Int) -> String { return self.titles[item] } func pickerView(pickerView: AKPickerView, imageForItem item: Int) -> UIImage { return UIImage(named: self.titles[item])! } // MARK: - AKPickerViewDelegate func pickerView(pickerView: AKPickerView, didSelectItem item: Int) { print("Your favorite city is \(self.titles[item])") } /* Label Customization ------------------- You can customize labels by their any properties (except for fonts,) and margin around text. These methods are optional, and ignored when using images. */ /* func pickerView(pickerView: AKPickerView, configureLabel label: UILabel, forItem item: Int) { label.textColor = UIColor.lightGrayColor() label.highlightedTextColor = UIColor.whiteColor() label.backgroundColor = UIColor( hue: CGFloat(item) / CGFloat(self.titles.count), saturation: 1.0, brightness: 0.5, alpha: 1.0) } func pickerView(pickerView: AKPickerView, marginForItem item: Int) -> CGSize { return CGSizeMake(40, 20) } */ /* UIScrollViewDelegate Support ---------------------------- AKPickerViewDelegate inherits UIScrollViewDelegate. You can use UIScrollViewDelegate methods by simply setting pickerView's delegate. */ func scrollViewDidScroll(scrollView: UIScrollView) { // println("\(scrollView.contentOffset.x)") } }
mit
3a2895ed973453573e2347f4396b827e
24.960396
117
0.720442
3.844575
false
false
false
false
CreazyShadow/SimpleDemo
SimpleApp/Pods/SnapKit/Source/Constraint.swift
1
11778
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public final class Constraint { internal let sourceLocation: (String, UInt) internal let label: String? private let from: ConstraintItem private let to: ConstraintItem private let relation: ConstraintRelation private let multiplier: ConstraintMultiplierTarget private var constant: ConstraintConstantTarget { didSet { self.updateConstantAndPriorityIfNeeded() } } private var priority: ConstraintPriorityTarget { didSet { self.updateConstantAndPriorityIfNeeded() } } public var layoutConstraints: [LayoutConstraint] public var isActive: Bool { for layoutConstraint in self.layoutConstraints { if layoutConstraint.isActive { return true } } return false } // MARK: Initialization internal init(from: ConstraintItem, to: ConstraintItem, relation: ConstraintRelation, sourceLocation: (String, UInt), label: String?, multiplier: ConstraintMultiplierTarget, constant: ConstraintConstantTarget, priority: ConstraintPriorityTarget) { self.from = from self.to = to self.relation = relation self.sourceLocation = sourceLocation self.label = label self.multiplier = multiplier self.constant = constant self.priority = priority self.layoutConstraints = [] // get attributes let layoutFromAttributes = self.from.attributes.layoutAttributes let layoutToAttributes = self.to.attributes.layoutAttributes // get layout from let layoutFrom = self.from.layoutConstraintItem! // get relation let layoutRelation = self.relation.layoutRelation for layoutFromAttribute in layoutFromAttributes { // get layout to attribute let layoutToAttribute: LayoutAttribute #if os(iOS) || os(tvOS) if layoutToAttributes.count > 0 { if self.from.attributes == .edges && self.to.attributes == .margins { switch layoutFromAttribute { case .left: layoutToAttribute = .leftMargin case .right: layoutToAttribute = .rightMargin case .top: layoutToAttribute = .topMargin case .bottom: layoutToAttribute = .bottomMargin default: fatalError() } } else if self.from.attributes == .margins && self.to.attributes == .edges { switch layoutFromAttribute { case .leftMargin: layoutToAttribute = .left case .rightMargin: layoutToAttribute = .right case .topMargin: layoutToAttribute = .top case .bottomMargin: layoutToAttribute = .bottom default: fatalError() } } else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else { layoutToAttribute = layoutToAttributes[0] } } else { if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) { layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top } else { layoutToAttribute = layoutFromAttribute } } #else if self.from.attributes == self.to.attributes { layoutToAttribute = layoutFromAttribute } else if layoutToAttributes.count > 0 { layoutToAttribute = layoutToAttributes[0] } else { layoutToAttribute = layoutFromAttribute } #endif // get layout constant let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) // get layout to var layoutTo: AnyObject? = self.to.target // use superview if possible if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height { layoutTo = layoutFrom.superview } // create layout constraint let layoutConstraint = LayoutConstraint( item: layoutFrom, attribute: layoutFromAttribute, relatedBy: layoutRelation, toItem: layoutTo, attribute: layoutToAttribute, multiplier: self.multiplier.constraintMultiplierTargetValue, constant: layoutConstant ) // set label layoutConstraint.label = self.label // set priority layoutConstraint.priority = LayoutPriority(self.priority.constraintPriorityTargetValue) // set constraint layoutConstraint.constraint = self // append self.layoutConstraints.append(layoutConstraint) } } // MARK: Public @available(*, deprecated:3.0, message:"Use activate().") public func install() { self.activate() } @available(*, deprecated:3.0, message:"Use deactivate().") public func uninstall() { self.deactivate() } public func activate() { self.activateIfNeeded() } public func deactivate() { self.deactivateIfNeeded() } @discardableResult public func update(offset: ConstraintOffsetTarget) -> Constraint { self.constant = offset.constraintOffsetTargetValue return self } @discardableResult public func update(inset: ConstraintInsetTarget) -> Constraint { self.constant = inset.constraintInsetTargetValue return self } @discardableResult public func update(priority: ConstraintPriorityTarget) -> Constraint { self.priority = priority.constraintPriorityTargetValue return self } @available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.") public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) } @available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.") public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) } @available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityRequired() -> Void {} @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") } @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.") public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") } // MARK: Internal internal func updateConstantAndPriorityIfNeeded() { for layoutConstraint in self.layoutConstraints { let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute) let requiredPriority = ConstraintPriority.required.value if (layoutConstraint.priority < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) { layoutConstraint.priority = LayoutPriority(self.priority.constraintPriorityTargetValue) } } } internal func activateIfNeeded(updatingExisting: Bool = false) { guard let item = self.from.layoutConstraintItem else { print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.") return } let layoutConstraints = self.layoutConstraints if updatingExisting { var existingLayoutConstraints: [LayoutConstraint] = [] for constraint in item.constraints { existingLayoutConstraints += constraint.layoutConstraints } for layoutConstraint in layoutConstraints { let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint } guard let updateLayoutConstraint = existingLayoutConstraint else { fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)") } let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute) } } else { NSLayoutConstraint.activate(layoutConstraints) item.add(constraints: [self]) } } internal func deactivateIfNeeded() { guard let item = self.from.layoutConstraintItem else { print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.") return } let layoutConstraints = self.layoutConstraints NSLayoutConstraint.deactivate(layoutConstraints) item.remove(constraints: [self]) } }
apache-2.0
b498c9e857f4f8813164619805a1842d
39.754325
184
0.618017
5.993893
false
false
false
false
synchromation/MinimalJSON
MinimalJson/MinimalJSON.swift
1
2718
// // JSON.swift // MinimalJson // // Created by Nick Banks on 07/01/2015. // Copyright (c) 2015 Synchromation. All rights reserved. // import Foundation /** * Main struct definition */ public class MinimalJSON { typealias JSONArray = Array<AnyObject> typealias JSONDictionary = Dictionary<String, AnyObject> let rootObject: AnyObject // Failable initialiser (i.e return nil if JSON containted in NSData object is invalid) init?(data: NSData) { var error: NSError? if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &error) { rootObject = object } else { rootObject = NSNull() return nil } } // Initializer for testing init (object: AnyObject) { rootObject = object } } /** * Subscript support */ extension MinimalJSON { subscript(hash: String) -> MinimalJSON { if let dictionary = rootObject as? Dictionary<String, AnyObject> { if let object: AnyObject = dictionary[hash] { return MinimalJSON(object: object) } else { return MinimalJSON(object: NSNull()) } } else { return MinimalJSON(object: NSNull()) } } subscript(index: Int) -> MinimalJSON { if let array = rootObject as? Array<AnyObject> { if (index >= 0) && (index < array.count) { return MinimalJSON(object: array[index]) } else { return MinimalJSON(object: NSNull()) } } else { return MinimalJSON(object: NSNull()) } } } /** * Value support */ extension MinimalJSON { var array: JSONArray? { return rootObject as? JSONArray } var dictionary: JSONDictionary? { return rootObject as? JSONDictionary } var bool: Bool? { if let i = rootObject as? Int { if (i == 0) || (i == 1) { return Bool(i) } else { return nil } } else { return nil } } var string: String? { return rootObject as? String } var int: Int? { return rootObject as? Int } var unsignedInt: UInt? { if let i = rootObject as? Int { if i >= 0 { return UInt(i) } else { return nil } } else { return nil } } var float: Float? { return rootObject as? Float } var double: Double? { return rootObject as? Double } }
mit
b1a8c06b5acda3748e98938f79921e4b
20.919355
122
0.518764
4.614601
false
false
false
false
iMasanari/cmd-eikana
cmd-eikana/MappingMenu.swift
1
1205
// // MappingMenu.swift // ⌘英かな // // MIT License // Copyright (c) 2016 iMasanari // import Cocoa class MappingMenu: NSPopUpButton { var row: Int? = nil func up() { if let row = self.row, row - 1 != -1 { let keyMapping = keyMappingList[row] keyMappingList[row] = keyMappingList[row - 1] keyMappingList[row - 1] = keyMapping } } func move(_ at: Int) { var at = at if let row = self.row { let keyMapping = keyMappingList[row] if at < 0 { at = 0 } else if at > keyMappingList.count - 1 { at = keyMappingList.count - 1 } keyMappingList.remove(at: row) keyMappingList.insert(keyMapping, at: at) } } func down() { if let row = self.row, row + 1 != keyMappingList.count { let keyMapping = keyMappingList[row] keyMappingList[row] = keyMappingList[row + 1] keyMappingList[row + 1] = keyMapping } } func remove() { keyMappingList.remove(at: self.row!) } }
mit
7df97b39dc2de97de1d032334da9eae1
23.428571
64
0.487051
3.836538
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/Conversation/ZMConversation+Patches.swift
1
8424
// // 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 extension ZMConversation { @objc public static let defaultAdminRoleName = "wire_admin" @objc public static let defaultMemberRoleName = "wire_member" static func predicateSecureWithIgnored() -> NSPredicate { return NSPredicate(format: "%K == %d", #keyPath(ZMConversation.securityLevel), ZMConversationSecurityLevel.secureWithIgnored.rawValue) } /// After changes to conversation security degradation logic we need /// to migrate all conversations from .secureWithIgnored to .notSecure /// so that users wouldn't get degratation prompts to conversations that /// at any point in the past had been secure static func migrateAllSecureWithIgnored(in moc: NSManagedObjectContext) { let predicate = ZMConversation.predicateSecureWithIgnored() let request = ZMConversation.sortedFetchRequest(with: predicate) guard let allConversations = moc.fetchOrAssert(request: request) as? [ZMConversation] else { fatal("fetchOrAssert failed") } for conversation in allConversations { conversation.securityLevel = .notSecure } } // Migration rules for the Model version 2.78.0 static func introduceParticipantRoles(in moc: NSManagedObjectContext) { migrateUsersToParticipants(in: moc) migrateIsSelfAnActiveMemberToTheParticipantRoles(in: moc) addUserFromTheConnectionToTheParticipantRoles(in: moc) forceToFetchConversationRoles(in: moc) } // Model version 2.78.0 adds a `participantRoles` attribute to the `Conversation` entity. // The set should contain the self user if 'isSelfAnActiveMember' is true. static func migrateIsSelfAnActiveMemberToTheParticipantRoles(in moc: NSManagedObjectContext) { let selfUser = ZMUser.selfUser(in: moc) let request = ZMConversation.sortedFetchRequest() guard let allConversations = moc.fetchOrAssert(request: request) as? [ZMConversation] else { fatal("fetchOrAssert failed") } for conversation in allConversations { let oldKey = "isSelfAnActiveMember" conversation.willAccessValue(forKey: oldKey) let isSelfAnActiveMember = (conversation.primitiveValue(forKey: oldKey) as! NSNumber).boolValue conversation.didAccessValue(forKey: oldKey) if isSelfAnActiveMember { var participantRoleForSelfUser: ParticipantRole let adminRole = conversation.getRoles().first(where: {$0.name == defaultAdminRoleName}) if let conversationTeam = conversation.team, conversationTeam == selfUser.team, selfUser.isTeamMember { participantRoleForSelfUser = getAParticipantRole(in: moc, adminRole: adminRole, user: selfUser, conversation: conversation, team: conversationTeam) } else { participantRoleForSelfUser = getAParticipantRole(in: moc, adminRole: adminRole, user: selfUser, conversation: conversation, team: nil) } conversation.participantRoles.insert(participantRoleForSelfUser) } } } static private func getAParticipantRole(in moc: NSManagedObjectContext, adminRole: Role?, user: ZMUser, conversation: ZMConversation, team: Team?) -> ParticipantRole { let participantRoleForUser = ParticipantRole.create(managedObjectContext: moc, user: user, conversation: conversation) let customRole = Role.fetchOrCreateRole(with: defaultAdminRoleName, teamOrConversation: team != nil ? .team(team!) : .conversation(conversation), in: moc) if let adminRole = adminRole { participantRoleForUser.role = adminRole } else { participantRoleForUser.role = customRole } return participantRoleForUser } // Model version 2.78.0 adds a `participantRoles` attribute to the `Conversation` entity. // After creating a new connection, we should add user to the participants roles, because we do not get it from the backend. static func addUserFromTheConnectionToTheParticipantRoles(in moc: NSManagedObjectContext) { guard let allConnections = ZMConnection.connections(inManagedObjectContext: moc) as? [ZMConnection] else { return } for connection in allConnections { guard let conversation = connection.conversation, let user = connection.to else { continue } conversation.addParticipantAndUpdateConversationState(user: user, role: nil) } } // Model version 2.78.0 adds a `participantRoles` attribute to the `Conversation` entity, // and `Role` to `Team` and `ZMConversation`. All group conversation memberships need to be refetched // in order to get which roles the users have. Additionally, we need to download the roles // definitions for teams and conversations. static func forceToFetchConversationRoles(in moc: NSManagedObjectContext) { // Mark group conversation membership to be refetched let selfUser = ZMUser.selfUser(in: moc) let groupConversationsFetch = ZMConversation.sortedFetchRequest( with: NSPredicate(format: "%K == %d", ZMConversationConversationTypeKey, ZMConversationType.group.rawValue)) guard let conversations = moc.fetchOrAssert(request: groupConversationsFetch) as? [ZMConversation] else { fatal("fetchOrAssert failed") } conversations.forEach { guard $0.isSelfAnActiveMember else { return } $0.needsToBeUpdatedFromBackend = true $0.needsToDownloadRoles = $0.team == nil || $0.team != selfUser.team } // Mark team as need to download roles selfUser.team?.needsToDownloadRoles = true } // Model version 2.78.0 adds a `participantRoles` attribute to the `Conversation` entity, and deprecates the `lastServerSyncedActiveParticipants`. // Those need to be migrated to the new relationship static func migrateUsersToParticipants(in moc: NSManagedObjectContext) { let oldKey = "lastServerSyncedActiveParticipants" let request = ZMConversation.sortedFetchRequest() guard let conversations = moc.fetchOrAssert(request: request) as? [ZMConversation] else { fatal("fetchOrAssert failed") } conversations.forEach { convo in let users = (convo.value(forKey: oldKey) as! NSOrderedSet).array as? [ZMUser] users?.forEach { user in let participantRole = ParticipantRole.insertNewObject(in: moc) participantRole.conversation = convo participantRole.user = user participantRole.role = nil } convo.setValue(NSOrderedSet(), forKey: oldKey) } } // Model version add a `accessRoleStringsV2` attribute to the `Conversation` entity. The values from accessRoleString, need to be migrated to the new relationship static func forceToFetchConversationAccessRoles(in moc: NSManagedObjectContext) { let conversationsToFetch = ZMConversation.fetchRequest() guard let conversations = moc.fetchOrAssert(request: conversationsToFetch) as? [ZMConversation] else { fatal("fetchOrAssert failed") } conversations.forEach { guard $0.isSelfAnActiveMember else { return } $0.needsToBeUpdatedFromBackend = true } } // Migration rules for the Model Version 2.98.0 static func introduceAccessRoleV2(in moc: NSManagedObjectContext) { forceToFetchConversationAccessRoles(in: moc) } }
gpl-3.0
d0084882dac77a45b88ba322bc097a8c
45.285714
171
0.69207
5.002375
false
false
false
false
AntonTheDev/CoreFlightAnimation
Source/FAAnimation/FAAnimationGroup.swift
1
10115
// // FAAnimationGroup.swift // FlightAnimator // // Created by Anton Doudarev on 2/24/16. // Copyright © 2016 Anton Doudarev. All rights reserved. // import Foundation import UIKit /** Equatable FAAnimationGroup Implementation */ func ==(lhs:FAAnimationGroup, rhs:FAAnimationGroup) -> Bool { return lhs.animatingLayer == rhs.animatingLayer && lhs.animationUUID == rhs.animationUUID } /** Timing Priority to apply during synchronisation of hte animations within the calling animationGroup. The more property animations within a group, the more likely some animations will need more control over the synchronization of the timing over others. There are 4 timing priorities to choose from: .MaxTime, .MinTime, .Median, and .Average By default .MaxTime is applied, so lets assume we have 4 animations: 1. bounds 2. position 3. alpha 4. transform FABasicAnimation(s) are not defined as primary by default, synchronization will figure out the relative progress for each property animation within the group in flight, then adjust the timing based on the remaining progress to the final destination of the new animation being applied. Then based on .MaxTime, it will pick the longest duration form all the synchronized property animations, and resynchronize the others with a new duration, and apply it to the group itself. If the isPrimary flag is set on the bounds and position animations, it will only include those two animation in figuring out the the duration. Use .MinTime, to select the longest duration in the group Use .MinTime, to select the shortest duration in the group Use .Median, to select the median duration in the group Use .Average, to select the average duration in the group - MaxTime: find the longest duration, and adjust all animations to match - MinTime: find the shortest duration and adjust all animations to match - Median: find the median duration, and adjust all animations to match - Average: find the average duration, and adjust all animations to match */ public enum FAPrimaryTimingPriority : Int { case MaxTime case MinTime case Median case Average } //MARK: - FAAnimationGroup public class FAAnimationGroup : FASequenceAnimationGroup { public var timingPriority : FAPrimaryTimingPriority = .MaxTime required public init() { super.init() animations = [CAAnimation]() fillMode = kCAFillModeForwards removedOnCompletion = true } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func copyWithZone(zone: NSZone) -> AnyObject { let animationGroup = super.copyWithZone(zone) as! FAAnimationGroup animationGroup.primaryAnimation = primaryAnimation animationGroup.startTime = startTime animationGroup.timingPriority = timingPriority return animationGroup } internal func synchronizeAnimationGroup(withLayer layer: CALayer, forKey key: String?) { animationUUID = key animatingLayer = layer if let keys = animatingLayer?.animationKeys() { for key in Array(Set(keys)) { if let oldAnimation = animatingLayer?.animationForKey(key) as? FAAnimationGroup { oldAnimation.sequenceDelegate?.stopSequence() synchronizeAnimations(oldAnimation) } } } else { synchronizeAnimations(nil) } var reverseAnimationArray = [FABasicAnimation]() if let animations = animations { for animation in animations { if let customAnimation = animation as? FABasicAnimation, let reverseAnimation = customAnimation.reverseAnimation as? FABasicAnimation { if autoreverseInvertEasing { reverseAnimation.easingFunction = reverseAnimation.easingFunction.autoreverseEasing() } reverseAnimationArray.append(reverseAnimation) } } } let animationGroup = self.sequenceCopy() as! FAAnimationGroup animationGroup.animationUUID = animationUUID! + "REVERSE" animationGroup.animations = reverseAnimationArray animationGroup.progessValue = autoreverseInvertProgress ? (1.0 - progessValue) : progessValue animationGroup.autoreverse = autoreverse animationGroup.autoreverseCount = autoreverseCount animationGroup.autoreverseDelay = autoreverseDelay animationGroup.autoreverseInvertEasing = autoreverseInvertEasing animationGroup.autoreverseInvertProgress = autoreverseInvertProgress animationGroup.reverseAnimation = self reverseAnimation = animationGroup } } //MARK: - Synchronization Logic internal extension FAAnimationGroup { internal func synchronizeAnimations(oldAnimationGroup : FAAnimationGroup?) { var oldAnimations = animationDictionaryForGroup(oldAnimationGroup) var newAnimations = animationDictionaryForGroup(self) for key in newAnimations.keys { newAnimations[key]!.animatingLayer = animatingLayer if let oldAnimation = oldAnimations[key] { newAnimations[key]!.synchronize(relativeTo: oldAnimation) } else { newAnimations[key]!.synchronize(relativeTo: nil) } } var primaryAnimations = newAnimations.filter({ $0.1.isPrimary == true }) let hasPrimaryAnimations : Bool = (primaryAnimations.count > 0) if hasPrimaryAnimations == false { primaryAnimations = newAnimations.filter({ $0.1 != nil }) } let durationsArray = primaryAnimations.map({ $0.1.duration}) switch timingPriority { case .MaxTime: duration = durationsArray.maxElement()! case .MinTime: duration = durationsArray.minElement()! case .Median: duration = durationsArray.sort(<)[durationsArray.count / 2] case .Average: duration = durationsArray.reduce(0, combine: +) / Double(durationsArray.count) } let nonSynchronizedAnimations = newAnimations.filter({ $0.1.duration != duration }) if hasPrimaryAnimations { primaryAnimation = (primaryAnimations.filter({ $0.1.duration == duration})).first?.1 } else { primaryAnimation = (newAnimations.filter({ $0.1.duration == duration})).first?.1 } for animation in nonSynchronizedAnimations { if animation.1.keyPath != primaryAnimation?.keyPath && animation.1.duration > primaryAnimation?.duration { newAnimations[animation.1.keyPath!]!.duration = duration newAnimations[animation.1.keyPath!]!.synchronize() } } animations = newAnimations.map {$1} } } internal extension FAAnimationGroup { /** Returns a dictionary format of the animations in the FAAnimationGroup. The keypath of the animation is used as the key i.e [keyPath : FABasicAnimation] - parameter animationGroup: The animation group to transform - returns: [keyPath : FABasicAnimation] representation of hte animations array */ func animationDictionaryForGroup(animationGroup : FAAnimationGroup?, primary : Bool = false) -> [String : FABasicAnimation] { var animationDictionary = [String: FABasicAnimation]() if let group = animationGroup { if let currentAnimations = group.animations { for animation in currentAnimations { if let customAnimation = animation as? FABasicAnimation { if primary { if customAnimation.isPrimary { animationDictionary[customAnimation.keyPath!] = customAnimation } } else { animationDictionary[customAnimation.keyPath!] = customAnimation } } } } } return animationDictionary } } //MARK: - Animation Progress Values internal extension FAAnimationGroup { func valueProgress() -> CGFloat { if let animation = animatingLayer?.animationForKey(animationUUID!) as? FAAnimationGroup{ return animation.primaryAnimation!.valueProgress() } guard let primaryAnimation = primaryAnimation else { print("Primary Animation Nil") return 0.0 } return primaryAnimation.valueProgress() } func timeProgress() -> CGFloat { if let animation = animatingLayer?.presentationLayer()?.animationForKey(animationUUID!) as? FAAnimationGroup { return animation.primaryAnimation!.timeProgress() } guard let primaryAnimation = primaryAnimation else { print("Primary Animation Nil") return 0.0 } return primaryAnimation.timeProgress() } /** Not Ready for Prime Time, being declared as private Adjusts animation based on the progress form 0 - 1 - parameter progress: scrub "to progress" value private func scrubToProgress(progress : CGFloat) { animatingLayer?.speed = 0.0 animatingLayer?.timeOffset = CFTimeInterval(duration * Double(progress)) } */ }
mit
a82ccbf695db1433bf38cd8b001b7e2c
32.604651
129
0.622503
5.532823
false
false
false
false
1000copy/fin
Controller/NodesViewController.swift
1
4337
import UIKit class NodesViewController: UIViewController { fileprivate weak var _loadView:V2LoadingView? func showLoadingView (){ self._loadView = V2LoadingView(view) } func hideLoadingView() { self._loadView?.hideLoadingView() } fileprivate var collectionView:CollectionView! override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("Navigation") self.view.backgroundColor = V2EXColor.colors.v2_backgroundColor self.collectionView = CollectionView(frame: self.view.bounds) self.view.addSubview(self.collectionView!) NodeGroupModel.getNodes { (response) -> Void in if response.success { self.collectionView.nodeGroupArray = response.value self.collectionView?.reloadData() } self.hideLoadingView() } self.showLoadingView() } } fileprivate class CollectionView : TJCollectionView { convenience init(frame: CGRect){ let layout = UICollectionViewFlowLayout(); layout.sectionInset = UIEdgeInsetsMake(10, 15, 10, 15); self.init(frame:frame,collectionViewLayout:layout) registerCell(NodeCell.self) registerHeaderView(NodeView.self) backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor } var nodeGroupArray:[NodeGroupModel]? override func sectionCount() -> Int { if let count = self.nodeGroupArray?.count{ return count } return 0 } override func itemCount(_ section: Int) -> Int { return self.nodeGroupArray![section].children.count } override func cellAt(_ indexPath: IndexPath) -> UICollectionViewCell { let nodeModel = self.nodeGroupArray![indexPath.section].children[indexPath.row] let cell = dequeueCell(NodeCell.self,indexPath) as! NodeCell cell.textLabel.text = nodeModel.nodeName return cell; } override func viewFor(_ kind: String, _ indexPath: IndexPath) -> UICollectionReusableView { let view = dequeueHeaderView(NodeView.self,indexPath) as! NodeView view.label.text = self.nodeGroupArray![indexPath.section].groupName return view } override func didSelectItemAt(_ indexPath: IndexPath){ let nodeModel = self.nodeGroupArray![indexPath.section].children[indexPath.row] Msg.send("openNodeTopicList",[nodeModel.nodeId ,nodeModel.nodeName]) } override func sizeFor(_ collectionViewLayout: UICollectionViewLayout, _ indexPath: IndexPath) -> CGSize { let nodeModel = self.nodeGroupArray![indexPath.section].children[indexPath.row] return CGSize(width: nodeModel.width, height: 25); } override func minimumInteritemSpacingForSectionAt(_ collectionViewLayout: UICollectionViewLayout, section: Int) -> CGFloat{ return 15 } override func referenceSizeForHeaderIn(_ collectionViewLayout: UICollectionViewLayout, _ section: Int) -> CGSize{ return CGSize(width: self.bounds.size.width, height: 35) } } fileprivate class NodeCell: UICollectionViewCell { var textLabel:UILabel = { let label = UILabel() label.font = v2Font(15) // label.textColor = V2EXColor.colors.v2_TopicListUserNameColor // label.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor return label }() fileprivate override func layoutSubviews() { self.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor self.contentView.addSubview(textLabel) textLabel.snp.remakeConstraints({ (make) -> Void in make.center.equalTo(self.contentView) }) } } fileprivate class NodeView: UICollectionReusableView { var label : UILabel = { let _label = UILabel() _label.font = v2Font(16) // _label.textColor = V2EXColor.colors.v2_TopicListTitleColor // _label.backgroundColor = V2EXColor.colors.v2_backgroundColor return _label }() fileprivate override func layoutSubviews() { super.layoutSubviews() self.backgroundColor = V2EXColor.colors.v2_backgroundColor self.addSubview(label); label.snp.makeConstraints{ $0.centerY.equalTo(self) $0.left.equalTo(self).offset(15) } } }
mit
386180f54827291f4d898f4fdb3f4323
40.304762
127
0.676735
4.724401
false
false
false
false
chayelheinsen/Mercury
MercuryApp/ViewController.swift
1
3409
/* import UIKit import Mercury class ViewController: UIViewController, MercuryDelegate { let mercury = Mercury.sharedInstance override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .whiteColor() mercury.delegate = self let notification1 = MercuryNotification() notification1.text = "Upload complete! Tap here to show an alert!" notification1.image = UIImage(named: "logo") notification1.color = .greenColor() notification1.userInfo = [ "key" : "This is from the dictionary!", ] notification1.action = { notification in if let title = notification1.userInfo?["key"] as? String { let alert = UIAlertView(title: title, message: "Mercury notifications are actionable", delegate: nil, cancelButtonTitle: "Close") alert.show() } else { let alert = UIAlertView(title: "Success", message: "Mercury notifications are actionable", delegate: nil, cancelButtonTitle: "Close") alert.show() } } notification1.soundPath = NSBundle.mainBundle().pathForResource("notify", ofType: "wav") let notification2 = MercuryNotification() let attributedText = NSMutableAttributedString(string: "Alan ") attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: NSMakeRange(0, attributedText.length)) attributedText.addAttribute(NSFontAttributeName , value: UIFont(name: "Helvetica-Bold", size: 14)!, range: NSMakeRange(0, attributedText.length)) attributedText.appendAttributedString(NSAttributedString(string: "commented on your ")) let imageText = NSMutableAttributedString(string: "image") imageText.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSMakeRange(0, imageText.length)) imageText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: 15)!, range: NSMakeRange(0, imageText.length)) attributedText.appendAttributedString(imageText) notification2.attributedText = attributedText notification2.image = UIImage(named: "logo") notification2.color = .redColor() let notification3 = MercuryNotification() notification3.text = "ATTN: There is a major update to your app! Please go to the app store now and download it! Also, this message is purposely really long." notification3.image = UIImage(named: "logo") notification3.color = .yellowColor() var delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.mercury.postNotifications([notification1, notification2, notification3, notification1, notification2, notification3]) } delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(4 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.mercury.postNotifications([notification1, notification2, notification3, notification1, notification2, notification3]) } } // MARK: - MercuryDelegate func mercuryNotificationViewForNotification(mercury mercury: Mercury, notification: MercuryNotification) -> MercuryNotificationView? { // You can create your own MercuryNotificationView subclass and return it here :D (or return nil for the default notification view) return nil } } */
mit
d9f934d92ef3b3df97f0bbbdb5660a39
43.855263
163
0.718099
4.787921
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ImageCodec/Algorithm/GrayPixelDecoder.swift
1
10679
// // GrayPixelDecoder.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public struct GrayPixelDecoder { public var width: Int public var height: Int public var resolution: Resolution public var colorSpace: ColorSpace<GrayColorModel> public init(width: Int, height: Int, resolution: Resolution, colorSpace: ColorSpace<GrayColorModel>) { self.width = width self.height = height self.resolution = resolution self.colorSpace = colorSpace } } extension GrayPixelDecoder { @inlinable public func decode_opaque_gray8(data: Data, fileBacked: Bool) -> Image<Gray16ColorPixel> { var image = Image<Gray16ColorPixel>(width: width, height: height, resolution: resolution, colorSpace: colorSpace, fileBacked: fileBacked) let pixels_count = min(image.pixels.count, data.count) data.withUnsafeBufferPointer(as: UInt8.self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { destination.pointee = Gray16ColorPixel(white: source.pointee) source += 1 destination += 1 } } } return image } @inlinable public func decode_opaque_gray16(data: Data, endianness: RawBitmap.Endianness, fileBacked: Bool) -> Image<Gray32ColorPixel> { var image = Image<Gray32ColorPixel>(width: width, height: height, resolution: resolution, colorSpace: colorSpace, fileBacked: fileBacked) let pixels_count = min(image.pixels.count, data.count / 2) switch endianness { case .big: data.withUnsafeBufferPointer(as: BEUInt16.self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { destination.pointee = Gray32ColorPixel(white: source.pointee.representingValue) source += 1 destination += 1 } } } case .little: data.withUnsafeBufferPointer(as: LEUInt16.self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { destination.pointee = Gray32ColorPixel(white: source.pointee.representingValue) source += 1 destination += 1 } } } } return image } } extension GrayPixelDecoder { @inlinable public func decode_gray8(data: Data, transparent: UInt8, fileBacked: Bool) -> Image<Gray16ColorPixel> { var image = Image<Gray16ColorPixel>(width: width, height: height, resolution: resolution, colorSpace: colorSpace, fileBacked: fileBacked) let pixels_count = min(image.pixels.count, data.count) data.withUnsafeBufferPointer(as: UInt8.self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { let value = source.pointee if value != transparent { destination.pointee = Gray16ColorPixel(white: value) } source += 1 destination += 1 } } } return image } @inlinable public func decode_gray16(data: Data, transparent: UInt16, endianness: RawBitmap.Endianness, fileBacked: Bool) -> Image<Gray32ColorPixel> { var image = Image<Gray32ColorPixel>(width: width, height: height, resolution: resolution, colorSpace: colorSpace, fileBacked: fileBacked) let pixels_count = min(image.pixels.count, data.count / 2) switch endianness { case .big: data.withUnsafeBufferPointer(as: BEUInt16.self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { let value = source.pointee.representingValue if value != transparent { destination.pointee = Gray32ColorPixel(white: value) } source += 1 destination += 1 } } } case .little: data.withUnsafeBufferPointer(as: LEUInt16.self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { let value = source.pointee.representingValue if value != transparent { destination.pointee = Gray32ColorPixel(white: value) } source += 1 destination += 1 } } } } return image } } extension GrayPixelDecoder { @inlinable public func decode_gray16(data: Data, fileBacked: Bool) -> Image<Gray16ColorPixel> { var image = Image<Gray16ColorPixel>(width: width, height: height, resolution: resolution, colorSpace: colorSpace, fileBacked: fileBacked) let pixels_count = min(image.pixels.count, data.count / 2) data.withUnsafeBufferPointer(as: (UInt8, UInt8).self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { let (w, a) = source.pointee destination.pointee = Gray16ColorPixel(white: w, opacity: a) source += 1 destination += 1 } } } return image } @inlinable public func decode_gray32(data: Data, endianness: RawBitmap.Endianness, fileBacked: Bool) -> Image<Gray32ColorPixel> { var image = Image<Gray32ColorPixel>(width: width, height: height, resolution: resolution, colorSpace: colorSpace, fileBacked: fileBacked) let pixels_count = min(image.pixels.count, data.count / 4) switch endianness { case .big: data.withUnsafeBufferPointer(as: (BEUInt16, BEUInt16).self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { let (w, a) = source.pointee destination.pointee = Gray32ColorPixel(white: w.representingValue, opacity: a.representingValue) source += 1 destination += 1 } } } case .little: data.withUnsafeBufferPointer(as: (LEUInt16, LEUInt16).self) { guard var source = $0.baseAddress else { return } image.withUnsafeMutableBufferPointer { guard var destination = $0.baseAddress else { return } for _ in 0..<pixels_count { let (w, a) = source.pointee destination.pointee = Gray32ColorPixel(white: w.representingValue, opacity: a.representingValue) source += 1 destination += 1 } } } } return image } }
mit
356d30571fc97d18b1198862561fe35e
34.956229
145
0.50501
5.713751
false
false
false
false
jorgetemp/maps-sdk-for-ios-samples
tutorials/places-address-form/places-address-form/ViewController.swift
1
4757
/* * Copyright 2017 Google Inc. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import GooglePlaces class ViewController: UIViewController { // Declare UI elements. @IBOutlet weak var address_line_1: UITextField! @IBOutlet weak var address_line_2: UITextField! @IBOutlet weak var city: UITextField! @IBOutlet weak var state: UITextField! @IBOutlet weak var postal_code_field: UITextField! @IBOutlet weak var country_field: UITextField! @IBOutlet weak var button: UIButton! // Declare variables to hold address form values. var street_number: String = "" var route: String = "" var neighborhood: String = "" var locality: String = "" var administrative_area_level_1: String = "" var country: String = "" var postal_code: String = "" var postal_code_suffix: String = "" // Present the Autocomplete view controller when the user taps the search field. @IBAction func autocompleteClicked(_ sender: UIButton) { let autocompleteController = GMSAutocompleteViewController() autocompleteController.delegate = self // Set a filter to return only addresses. let addressFilter = GMSAutocompleteFilter() addressFilter.type = .address autocompleteController.autocompleteFilter = addressFilter present(autocompleteController, animated: true, completion: nil) } // Populate the address form fields. func fillAddressForm() { address_line_1.text = street_number + " " + route city.text = locality state.text = administrative_area_level_1 if postal_code_suffix != "" { postal_code_field.text = postal_code + "-" + postal_code_suffix } else { postal_code_field.text = postal_code } country_field.text = country // Clear values for next time. street_number = "" route = "" neighborhood = "" locality = "" administrative_area_level_1 = "" country = "" postal_code = "" postal_code_suffix = "" } } extension ViewController: GMSAutocompleteViewControllerDelegate { // Handle the user's selection. func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { // Print place info to the console. print("Place name: \(place.name)") print("Place address: \(place.formattedAddress)") print("Place attributions: \(place.attributions)") // Get the address components. if let addressLines = place.addressComponents { // Populate all of the address fields we can find. for field in addressLines { switch field.type { case kGMSPlaceTypeStreetNumber: street_number = field.name case kGMSPlaceTypeRoute: route = field.name case kGMSPlaceTypeNeighborhood: neighborhood = field.name case kGMSPlaceTypeLocality: locality = field.name case kGMSPlaceTypeAdministrativeAreaLevel1: administrative_area_level_1 = field.name case kGMSPlaceTypeCountry: country = field.name case kGMSPlaceTypePostalCode: postal_code = field.name case kGMSPlaceTypePostalCodeSuffix: postal_code_suffix = field.name // Print the items we aren't using. default: print("Type: \(field.type), Name: \(field.name)") } } } // Call custom function to populate the address form. fillAddressForm() // Close the autocomplete widget. self.dismiss(animated: true, completion: nil) } func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) { // TODO: handle the error. print("Error: ", error.localizedDescription) } func wasCancelled(_ viewController: GMSAutocompleteViewController) { dismiss(animated: true, completion: nil) } // Show the network activity indicator. func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } // Hide the network activity indicator. func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } }
apache-2.0
c999a8eddbf5a56968266f5ac1afcfa1
32.737589
115
0.702333
4.582852
false
false
false
false
stupidfive/AutoLayoutCodeGenerator
AutoLayoutCodeGenerator/ViewController.swift
1
5631
// // ViewController.swift // XibToSwift // // Created by George Wu on 7/4/15. // Copyright © 2015 George Wu. All rights reserved. // import UIKit class ViewController: UIViewController, NSXMLParserDelegate { // MARK: - Properties /// A dictionary for view items for a quick search of id. var viewItemDict: [String: ConstraintedView] = [:] /// Stack that keeps track of element infos when serializing nib. var elementInfoStack = Stack< (elementName: String, attributeDict: [String: String]) >() var constraintsFlag: Int = 0 var constraintsCode: String = "\n" var currentViewItemName: String = "" // MARK: - Methods override func viewDidLoad() { super.viewDidLoad() // Place storyboard path here. let path = "/Volumes/Warehouse/Main.storyboard" if !NSFileManager().fileExistsAtPath(path) { fatalError("Error: File doesn't exsit."); } // nib serialization guard let xmlParser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: path)) else { fatalError("Error: File format may be incorrect."); } xmlParser.delegate = self xmlParser.parse() } // MARK: - NSXMLParserDelegate methods func parserDidStartDocument(parser: NSXMLParser) { print("---parserDidStartDocument---") } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { // record id and the corresponding view item in dictionary if it has one if let viewItemId = attributeDict["id"] { let viewItem = ConstraintedView(attributeDict: attributeDict) viewItemDict[viewItemId] = viewItem if "NO" == attributeDict["translatesAutoresizingMaskIntoConstraints"] { constraintsCode += "\(viewItem.variableName).translatesAutoresizingMaskIntoConstraints = false\n" } } // prepare when enter <constraints> if elementName == "constraints" { constraintsFlag++ currentViewItemName = elementInfoStack.top()!.attributeDict["id"]! } // add constraint code if the node is <constraint> if constraintsFlag > 0 && elementName == "constraint" { let firstItemValue: String? = attributeDict["firstItem"] // id let firstAttributeValue: String? = attributeDict["firstAttribute"] let secondItemValue: String? = attributeDict["secondItem"] let secondAttributeValue: String? = attributeDict["secondAttribute"] let constantValue: String? = attributeDict["constant"] let multiplierValue: String? = attributeDict["multiplier"] let firstItemCode: String let firstAttributeCode: String let secondItemCode: String let secondAttributeCode: String let constantCode: String = constantValue ?? "0" let multiplierCode: String = multiplierValue ?? "1.0" // view on which the constraint's been added let onView = ConstraintedView(attributeDict: elementInfoStack.second()!.attributeDict).variableName if (firstItemValue == nil) { // unilateral constraint firstItemCode = viewItemDict[currentViewItemName]!.variableName firstAttributeCode = layoutAttributeDict[firstAttributeValue!]! secondItemCode = "nil" secondAttributeCode = "NotAnAttribute" // concat comment constraintsCode += "// \(firstItemCode) constriants\n" constraintsCode += onView constraintsCode += ".addConstraint(NSLayoutConstraint(item: \(firstItemCode), attribute: NSLayoutAttribute.\(firstAttributeCode), relatedBy: NSLayoutRelation.Equal, toItem: \(secondItemCode), attribute: NSLayoutAttribute.\(secondAttributeCode), multiplier: \(multiplierCode), constant: \(constantCode)))\n" } else { // bilateral constraint firstItemCode = viewItemDict[firstItemValue!]!.variableName firstAttributeCode = layoutAttributeDict[firstAttributeValue!]! secondItemCode = viewItemDict[secondItemValue!]!.variableName secondAttributeCode = layoutAttributeDict[secondAttributeValue!]! constraintsCode += "// \(firstItemCode) constriants\n" constraintsCode += onView constraintsCode += ".addConstraint(NSLayoutConstraint(item: \(firstItemCode), attribute: NSLayoutAttribute.\(firstAttributeCode), relatedBy: NSLayoutRelation.Equal, toItem: \(secondItemCode), attribute: NSLayoutAttribute.\(secondAttributeCode), multiplier: \(multiplierCode), constant: \(constantCode)))\n" } } // push element info into info stack elementInfoStack.push( (elementName, attributeDict) ) } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { // decrease constraintsFlag when getting out of "constraints" element if elementName == "constraints" { constraintsFlag-- currentViewItemName = "" } // pop element from element info stack elementInfoStack.pop() } func parserDidEndDocument(parser: NSXMLParser) { print(constraintsCode) print("---parserDidEndDocument---") } } let layoutAttributeDict: [String: String] = ["left": "Left", "right": "Right", "top": "Top", "bottom": "Bottom", "leading": "Leading", "trailing": "Trailing", "width": "Width", "height": "Height", "centerX": "CenterX", "centerY": "CenterY", "baseline": "Baseline", "lastBaseline": "LastBaseline", "firstBaseline": "FirstBaseline", "leftMargin": "LeftMargin", "rightMargin": "RightMargin", "topMargin": "TopMargin", "bottomMargin": "BottomMargin", "leadingMargin": "LeadingMargin", "trailingMargin": "TrailingMargin", "centerXWithinMargins": "CenterXWithinMargins", "centerYWithinMargins": "CenterYWithinMargins", "notAnAttribute": "NotAnAttribute"]
mit
0babb8f58924192f7e64ccde17784780
32.313609
292
0.721137
4.34749
false
false
false
false
ThornTechPublic/InteractiveSlideOutMenu
InteractiveSlideoutMenu/MenuHelper.swift
1
3426
// // MenuHelper.swift // InteractiveSlideoutMenu // // Created by Robert Chen on 2/7/16. // // Copyright (c) 2016 Thorn Technologies LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit enum Direction { case up case down case left case right } struct MenuHelper { static let menuWidth:CGFloat = 0.8 static let percentThreshold:CGFloat = 0.3 static let snapshotNumber = 12345 static func calculateProgress(_ translationInView:CGPoint, viewBounds:CGRect, direction:Direction) -> CGFloat { let pointOnAxis:CGFloat let axisLength:CGFloat switch direction { case .up, .down: pointOnAxis = translationInView.y axisLength = viewBounds.height case .left, .right: pointOnAxis = translationInView.x axisLength = viewBounds.width } let movementOnAxis = pointOnAxis / axisLength let positiveMovementOnAxis:Float let positiveMovementOnAxisPercent:Float switch direction { case .right, .down: // positive positiveMovementOnAxis = fmaxf(Float(movementOnAxis), 0.0) positiveMovementOnAxisPercent = fminf(positiveMovementOnAxis, 1.0) return CGFloat(positiveMovementOnAxisPercent) case .up, .left: // negative positiveMovementOnAxis = fminf(Float(movementOnAxis), 0.0) positiveMovementOnAxisPercent = fmaxf(positiveMovementOnAxis, -1.0) return CGFloat(-positiveMovementOnAxisPercent) } } static func mapGestureStateToInteractor(_ gestureState:UIGestureRecognizerState, progress:CGFloat, interactor: Interactor?, triggerSegue: () -> ()){ guard let interactor = interactor else { return } switch gestureState { case .began: interactor.hasStarted = true triggerSegue() case .changed: interactor.shouldFinish = progress > percentThreshold interactor.update(progress) case .cancelled: interactor.hasStarted = false interactor.cancel() case .ended: interactor.hasStarted = false interactor.shouldFinish ? interactor.finish() : interactor.cancel() default: break } } }
mit
c2e838508f9532f153ef1cb1b765715f
35.83871
152
0.668418
4.706044
false
false
false
false
adamnemecek/AudioKit
Sources/AudioKit/MIDI/Utilities/MIDIVariableLengthQuantity.swift
1
1806
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import Foundation /// MIDI Varialbe Length Quantity public struct MIDIVariableLengthQuantity { /// Data in bytes public let data: [MIDIByte] /// Length of the quantity public var length: Int { return vlqResult.0 } /// Quantity public var quantity: UInt32 { return vlqResult.1 } private let vlqResult: (Int, UInt32) /// Initialize from bytes /// - Parameter data: Array slide of MIDI Bytes public init?(fromBytes data: ArraySlice<MIDIByte>) { self.init(fromBytes: Array(data)) } /// Initialize from arry /// - Parameter data: MIDI Byte array public init?(fromBytes data: [MIDIByte]) { guard data.isNotEmpty else { return nil } vlqResult = MIDIVariableLengthQuantity.read(bytes: data) self.data = Array(data.prefix(vlqResult.0)) guard self.data.count == length else { return nil } } /// Read from array of MIDI Bytes /// - Parameter bytes: Array of MIDI Bytes /// - Returns: Tuple of processed byte count and result UInt32 public static func read(bytes: [MIDIByte]) -> (Int, UInt32) { var processedBytes = 0 var result: UInt32 = 0 var lastByte: MIDIByte = 0xFF var byte = bytes[processedBytes] while lastByte & noteOffByte == noteOffByte && processedBytes < bytes.count { let shifted = result << 7 let masked: MIDIByte = byte & 0x7f result = shifted | UInt32(masked) processedBytes += 1 lastByte = byte if processedBytes >= bytes.count { break } byte = bytes[processedBytes] } return (processedBytes, result) } }
mit
2e5caf2d0b3bef4900172a51826faaee
33.730769
100
0.62237
4.459259
false
false
false
false
dobleuber/my-swift-exercises
Project17/Project17/GameViewController.swift
1
1395
// // GameViewController.swift // Project17 // // Created by Wbert Castro on 22/07/17. // Copyright © 2017 Wbert Castro. All rights reserved. // import UIKit import SpriteKit import GameplayKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let view = self.view as! SKView? { // Load the SKScene from 'GameScene.sks' if let scene = SKScene(fileNamed: "GameScene") { // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) } view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } }
mit
0e0d68625bfb5f3ec88d0944b6780a40
24.345455
77
0.580344
5.466667
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/NetworkServices/FreeEpisodesNS.swift
1
1874
// // FreeEpisodesNS.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 16/03/18. // import Foundation class FreeEpisodesNS: BaseNS { static let shared = FreeEpisodesNS() lazy var awesomeRequester: AwesomeCoreRequester = AwesomeCoreRequester(cacheType: .realm) override init() {} var freeEpisodesRequest: URLSessionDataTask? func fetchFreeEpisodes(params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping ([FreeCourse], ErrorData?) -> Void) { func processResponse(data: Data?, error: ErrorData? = nil, response: @escaping ([FreeCourse], ErrorData?) -> Void ) -> Bool { if let jsonObject = data { self.freeEpisodesRequest = nil response(FreeEpisodesMP.parsefreeEpisodesFrom(jsonObject).courses, nil) return true } else { self.freeEpisodesRequest = nil if let error = error { response([], error) return false } response([], ErrorData(.unknown, "response Data could not be parsed")) return false } } let url = ACConstants.shared.freeEpisodes let method: URLMethod = .GET if params.contains(.shouldFetchFromCache) { _ = processResponse(data: dataFromCache(url, method: method, params: params, bodyDict: nil), response: response) } freeEpisodesRequest = awesomeRequester.performRequestAuthorized( url, forceUpdate: true, completion: { (data, error, responseType) in if processResponse(data: data, error: error, response: response) { self.saveToCache(url, method: method, bodyDict: nil, data: data) } }) } }
mit
158dd3aa841aafabd3846386f4621444
35.038462
137
0.591249
5.024129
false
false
false
false
jad6/CV
Swift/Jad's CV/Sections/Education/EducationViewController.swift
1
1323
// // EducationViewController.swift // Jad's CV // // Created by Jad Osseiran on 25/07/2014. // Copyright (c) 2014 Jad. All rights reserved. // import UIKit class EducationViewController: UIViewController { //MARK:- Properties let education = Education.education() var educationView: EducationView! { return view as? EducationView } //MARK:- Init required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override init() { super.init(nibName: nil, bundle: nil) } //MARK:- View lifecycle override func loadView() { view = UIDevice.isPad() ? EducationView_Pad() : EducationView_Phone() } override func viewDidLoad() { super.viewDidLoad() setupEducationView() } //MARK:- Logic func setupEducationView() { educationView.universityLogoImageView.image = education.universityLogo educationView.statusLabel.text = education.status educationView.establishmentLabel.text = education.establishment educationView.completionDateLabel.text = education.completion educationView.textView.text = education.detailDescription educationView.backgroundImageView.image = education.backgroundImage } }
bsd-3-clause
aee70b14462649d96a1bbbc90a5e941d
23.962264
78
0.650038
4.793478
false
false
false
false
PigDogBay/Food-Hygiene-Ratings
Food Hygiene Ratings/Ratings.swift
1
2656
// // Ratings.swift // Food Hygiene Ratings // // Created by Mark Bailey on 09/10/2017. // Copyright © 2017 MPD Bailey Technology. All rights reserved. // import Foundation import UIKit import StoreKit class Ratings { fileprivate let countKey = "RatingsRequestCount" fileprivate let installDateKey = "RatingsInstallDate" //ask after 32 requests fileprivate let maxCount = 32 //Ask after a week, time interval is in seconds fileprivate let maxTimeInterval = TimeInterval(7*24*60*60) fileprivate var appUrl : String init(appId : String){ self.appUrl = "itms-apps://itunes.apple.com/app/\(appId)" } fileprivate var count : Int { get{ let defaults = UserDefaults.standard let c = defaults.object(forKey: countKey) as? Int if c == nil { defaults.set(0, forKey: countKey) defaults.synchronize() return 0 } return c! } set(value){ let defaults = UserDefaults.standard defaults.set(value, forKey: countKey) defaults.synchronize() } } fileprivate var installDate : Date { get{ let defaults = UserDefaults.standard let c = defaults.object(forKey: installDateKey) as? Date if c == nil { let date = Date() defaults.set(date, forKey: installDateKey) defaults.synchronize() return date } return c! } set(value){ let defaults = UserDefaults.standard defaults.set(value, forKey: installDateKey) defaults.synchronize() } } func viewOnAppStore() { if #available(iOS 10.0, *) { UIApplication.shared.open(URL(string: appUrl)!, options: [:]) } else { UIApplication.shared.openURL(URL(string: appUrl)!) } } func requestRating() { if #available( iOS 10.3,*){ let askDate = installDate.addingTimeInterval(maxTimeInterval) let today = Date() count = count + 1 if count>maxCount && today > askDate{ //try again next week, requestReview will take care of showing or not reset() //requestReview() will only show 3 times per year and not again if the user has left a review SKStoreReviewController.requestReview() } } } func reset(){ count = 0 installDate = Date() } }
apache-2.0
6d03552bd13d21e462c9c8157a2e5332
27.548387
109
0.546516
4.792419
false
false
false
false
ton-katsu/ImageLoaderSwift
ImageLoaderExample/SimpleViewController.swift
1
2735
// // SimpleViewController.swift // ImageLoaderSample // // Created by Hirohisa Kawasaki on 10/17/14. // Copyright (c) 2014 Hirohisa Kawasaki. All rights reserved. // import UIKit import ImageLoader extension UIButton { convenience init(title: String, highlightedColor: UIColor) { self.init() frame = CGRect(x: 0, y: 0, width: 100, height: 50) setTitle(title, forState: .Normal) setTitleColor(UIColor.blackColor(), forState: .Normal) setTitleColor(highlightedColor, forState: .Highlighted) } } class SimpleViewController: UIViewController { let imageView: UIImageView = { let imageView: UIImageView = UIImageView() imageView.frame = CGRect(x: 0, y: 0, width: 200, height: 300) return imageView }() let successURLButton = UIButton(title: "success", highlightedColor: UIColor.greenColor()) let failureURLButton = UIButton(title: "failure", highlightedColor: UIColor.redColor()) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() imageView.center = CGPoint( x: CGRectGetWidth(view.frame)/2, y: CGRectGetHeight(view.frame)/2 ) view.addSubview(imageView) configureButtons() tryLoadSuccessURL() } // MARK: - view func configureButtons() { successURLButton.center = CGPoint( x: CGRectGetWidth(view.frame)/2 - 50, y: CGRectGetHeight(view.frame)/2 + 200 ) failureURLButton.center = CGPoint( x: CGRectGetWidth(view.frame)/2 + 50, y: CGRectGetHeight(view.frame)/2 + 200 ) view.addSubview(successURLButton) view.addSubview(failureURLButton) successURLButton.addTarget(self, action: Selector("tryLoadSuccessURL"), forControlEvents: .TouchUpInside) failureURLButton.addTarget(self, action: Selector("tryLoadFailureURL"), forControlEvents: .TouchUpInside) } // MARK: - try func tryLoadSuccessURL() { let string = "http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg" tryLoad(string) } func tryLoadFailureURL() { let string = "http://upload.wikimedia.org/wikipedia/commons/1/1b/Bachalpseeflowers.jpg" tryLoad(string) } func tryLoad(URL: URLLiteralConvertible) { testLoad(imageView, URL: URL) } func testLoad(imageView: UIImageView, URL: URLLiteralConvertible) { imageView.load(URL, placeholder: nil) { URL, image, error, cacheType in println("URL \(URL)") println("error \(error)") println("cacheType \(cacheType.hashValue)") } } }
mit
bec6eafb13b3f336f03b4c508281ec35
27.789474
113
0.642413
4.383013
false
false
false
false
noehou/TWB
TWB/TWB/Tools/NSDate-Extension.swift
1
2145
// // NSDate-Extension.swift // 08-时间处理 // // Created by xiaomage on 16/4/8. // Copyright © 2016年 小码哥. All rights reserved. // import Foundation extension NSDate { class func createDateString(createAtStr : String) -> String { // 1.创建时间格式化对象 let fmt = DateFormatter() fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy" fmt.locale = NSLocale(localeIdentifier: "en") as Locale! // 2.将字符串时间,转成NSDate类型 guard let createDate = fmt.date(from: createAtStr) else { return "" } // 3.创建当前时间 let nowDate = Date() // 4.计算创建时间和当前时间的时间差 let interval = Int(nowDate.timeIntervalSince(createDate)) // 5.对时间间隔处理 // 5.1.显示刚刚 if interval < 60 { return "刚刚" } // 5.2.59分钟前 if interval < 60 * 60 { return "\(interval / 60)分钟前" } // 5.3.11小时前 if interval < 60 * 60 * 24 { return "\(interval / (60 * 60))小时前" } // 5.4.创建日历对象 let calendar = NSCalendar.current // 5.5.处理昨天数据: 昨天 12:23 if calendar.isDateInYesterday(createDate) { fmt.dateFormat = "昨天 HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } // 5.6.处理一年之内: 02-22 12:22 // let cmps = calendar.components(.Year, fromDate: createDate, toDate: nowDate, options: []) let cmps = calendar.dateComponents(Set<Calendar.Component>([.year]), from: createDate, to: nowDate) if cmps.year! < 1 { fmt.dateFormat = "MM-dd HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } // 5.7.超过一年: 2014-02-12 13:22 fmt.dateFormat = "yyyy-MM-dd HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } }
mit
8cd7d2a6e747c0eed62960e6b89a91c2
27.202899
107
0.520555
3.939271
false
false
false
false
m-schmidt/PopoverRestoration
PopoverRestoration/ViewController.swift
1
1491
// ViewController.swift import UIKit class ViewController: UIViewController, PopoverRestorationDelegate { // The button that triggers a popver segue @IBOutlet weak var showPopoverButton: UIButton! // Catch segues to the popover override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "popoverSegue" { // Define a correct sourceRect to center the popover's anchor if let pc = segue.destination.presentationController as? UIPopoverPresentationController { pc.sourceRect = pc.sourceView!.bounds pc.delegate = self } // Update the Done-button state of a presented navigation controller if let nc = segue.destination as? PresentedNavigationController { nc.updateNavigationItemsForTraits(self.traitCollection); } } } // When the traits change, update the Done-button state of a presented navigation controller override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) if let nc = presentedViewController as? PresentedNavigationController { nc.updateNavigationItemsForTraits(newCollection); } } // MARK: PopoverRestorationDelegate func popoverSourceView() -> UIView? { return showPopoverButton } }
bsd-3-clause
d29426fdf29764914bfcb5b9de7f7368
31.413043
128
0.684775
5.801556
false
false
false
false