repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
efremidze/animated-tab-bar
refs/heads/master
RAMAnimatedTabBarController/RAMAnimatedTabBarController.swift
mit
1
// AnimationTabBarController.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class RAMAnimatedTabBarItem: UITabBarItem { @IBOutlet public var animation: RAMItemAnimation? @IBInspectable public var textColor = UIColor.blackColor() func playAnimation(icon: UIImageView, textLabel: UILabel){ guard let animation = animation else { print("add animation in UITabBarItem") return } animation.playAnimation(icon, textLabel: textLabel) } func deselectAnimation(icon: UIImageView, textLabel: UILabel) { animation?.deselectAnimation(icon, textLabel: textLabel, defaultTextColor: textColor) } func selectedState(icon: UIImageView, textLabel: UILabel) { animation?.selectedState(icon, textLabel: textLabel) } } public class RAMAnimatedTabBarController: UITabBarController { var iconsView: [(icon: UIImageView, textLabel: UILabel)] = [] // MARK: life circle public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let containers = createViewContainers() createCustomIcons(containers) } // MARK: create methods func createCustomIcons(containers : [String: UIView]) { if let items = tabBar.items as? [RAMAnimatedTabBarItem] { let itemsCount = items.count as Int - 1 for (index, item) in items.enumerate() { assert(item.image != nil, "add image icon in UITabBarItem") guard let container = containers["container\(itemsCount-index)"] else { print("No container given") continue } container.tag = index let icon = UIImageView(image: item.image) icon.translatesAutoresizingMaskIntoConstraints = false icon.tintColor = UIColor.clearColor() // text let textLabel = UILabel() textLabel.text = item.title textLabel.backgroundColor = UIColor.clearColor() textLabel.textColor = item.textColor textLabel.font = UIFont.systemFontOfSize(10) textLabel.textAlignment = NSTextAlignment.Center textLabel.translatesAutoresizingMaskIntoConstraints = false container.addSubview(icon) if let itemImage = item.image { createConstraints(icon, container: container, size: itemImage.size, yOffset: -5) } container.addSubview(textLabel) if let tabBarItem = tabBar.items { let textLabelWidth = tabBar.frame.size.width / CGFloat(tabBarItem.count) - 5.0 createConstraints(textLabel, container: container, size: CGSize(width: textLabelWidth , height: 10), yOffset: 16) } let iconsAndLabels = (icon:icon, textLabel:textLabel) iconsView.append(iconsAndLabels) if 0 == index { // selected first elemet item.selectedState(icon, textLabel: textLabel) } item.image = nil item.title = "" } } } func createConstraints(view: UIView, container: UIView, size: CGSize, yOffset: CGFloat) { let constX = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: container, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) container.addConstraint(constX) let constY = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: container, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: yOffset) container.addConstraint(constY) let constW = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: size.width) view.addConstraint(constW) let constH = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: size.height) view.addConstraint(constH) } func createViewContainers() -> [String: UIView] { var containersDict = [String: UIView]() guard let tabBarItems = tabBar.items else { return containersDict } let itemsCount: Int = tabBarItems.count - 1 for index in 0...itemsCount { let viewContainer = createViewContainer() containersDict["container\(index)"] = viewContainer } var formatString = "H:|-(0)-[container0]" for index in 1...itemsCount { formatString += "-(0)-[container\(index)(==container0)]" } formatString += "-(0)-|" let constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString, options:NSLayoutFormatOptions.DirectionRightToLeft, metrics: nil, views: containersDict) view.addConstraints(constranints) return containersDict } func createViewContainer() -> UIView { let viewContainer = UIView() viewContainer.backgroundColor = UIColor.clearColor() // for test viewContainer.translatesAutoresizingMaskIntoConstraints = false view.addSubview(viewContainer) // add gesture let tapGesture = UITapGestureRecognizer(target: self, action: "tapHandler:") tapGesture.numberOfTouchesRequired = 1 viewContainer.addGestureRecognizer(tapGesture) // add constrains let constY = NSLayoutConstraint(item: viewContainer, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) view.addConstraint(constY) let constH = NSLayoutConstraint(item: viewContainer, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: tabBar.frame.size.height) viewContainer.addConstraint(constH) return viewContainer } // MARK: actions func tapHandler(gesture:UIGestureRecognizer) { let items = tabBar.items as! [RAMAnimatedTabBarItem] let currentIndex = gesture.view!.tag if selectedIndex != currentIndex { let animationItem : RAMAnimatedTabBarItem = items[currentIndex] let icon = iconsView[currentIndex].icon let textLabel = iconsView[currentIndex].textLabel animationItem.playAnimation(icon, textLabel: textLabel) let deselelectIcon = iconsView[selectedIndex].icon let deselelectTextLabel = iconsView[selectedIndex].textLabel let deselectItem = items[selectedIndex] deselectItem.deselectAnimation(deselelectIcon, textLabel: deselelectTextLabel) selectedIndex = gesture.view!.tag } } public func setSelectIndex(from from: Int,to: Int) { selectedIndex = to let items = tabBar.items as! [RAMAnimatedTabBarItem] items[from].deselectAnimation(iconsView[from].icon, textLabel: iconsView[from].textLabel) items[to].playAnimation(iconsView[to].icon, textLabel: iconsView[to].textLabel) } }
81bf860a1bff223875840682bc504e26
37.142292
133
0.599482
false
false
false
false
3pillarlabs/ios-charts
refs/heads/master
Sources/Charts/model/GraphInputRow.swift
mit
1
// // GraphInputRow.swift // ChartsApp // // Created by Gil Eluard on 16/02/16. // Copyright © 2016 3PillarGlobal. All rights reserved. // import UIKit public class GraphInputRow: NSObject { /// Set row name public var name = "" /// Set tint color for Row public var tintColor = UIColor.black { didSet { delegate?.rowTintColorDidChange(row: self) } } /// Array of values in a row public var values: [Double] = [] { didSet { computeMinMax() delegate?.rowValuesDidChange(row: self) } } private(set) var min: Double = 0 private(set) var max: Double = 0 private(set) var total: Double = 0 weak var delegate: GraphInputRowDelegate? // MARK: - business methods public convenience init(name: String) { self.init(name: name, tintColor: nil) } public convenience init(name: String, tintColor: UIColor?) { self.init(name: name, tintColor: tintColor, values:[]) } public init(name: String, tintColor: UIColor?, values:[Double]) { super.init() self.name = name self.values = values self.tintColor = tintColor ?? UIColor.black computeMinMax() } // MARK: - private methods private func computeMinMax() { var min: Double = .greatestFiniteMagnitude var max: Double = 0 var total: Double = 0 for value in values { min = fmin(min, value) max = fmax(max, value) total += value } self.min = min self.max = max self.total = total } }
a3463ce02dfe7f7ae1aeb41f1e708ba8
22.859155
68
0.556671
false
false
false
false
rsmoz/swift-corelibs-foundation
refs/heads/master
TestFoundation/TestUtils.swift
apache-2.0
1
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif func ensureFiles(fileNames: [String]) -> Bool { var result = true let fm = NSFileManager.defaultManager() for name in fileNames { guard !fm.fileExistsAtPath(name) else { continue } if name.hasSuffix("/") { do { try fm.createDirectoryAtPath(name, withIntermediateDirectories: true, attributes: nil) } catch let err { print(err) return false } } else { var isDir: ObjCBool = false let dir = name.bridge().stringByDeletingLastPathComponent if !fm.fileExistsAtPath(dir, isDirectory: &isDir) { do { try fm.createDirectoryAtPath(dir, withIntermediateDirectories: true, attributes: nil) } catch let err { print(err) return false } } else if !isDir { return false } result = result && fm.createFileAtPath(name, contents: nil, attributes: nil) } } return result }
51b9deb8f290d70fc9f086fc29a40ad9
30.461538
105
0.572477
false
false
false
false
nextriot/Abacus
refs/heads/master
Abacus/GameOptionsViewController.swift
apache-2.0
1
// // GameOptionsViewController.swift // Abacus // // Created by Kyle Gillen on 02/09/2015. // Copyright © 2015 Next Riot. All rights reserved. // import UIKit class GameOptionsViewController: UIViewController, ModalDelegate { @IBOutlet private weak var summaryView: UIView! { didSet { let topBorder = UIView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(summaryView.frame), height: 1.0)) topBorder.backgroundColor = Constants.Colors.MediumGrey summaryView.layer.addSublayer(topBorder.layer) } } @IBOutlet private weak var containerView: UIView! private var fabView: FabButtonView! override func viewDidLoad() { super.viewDidLoad() styleNavBar(navigationController!.navigationBar) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let backBtnItem = UIBarButtonItem(image: UIImage(named: "icon-overview"), style: .Plain, target: self, action: "dismissModal") title = "Game Options" navigationItem.leftBarButtonItem = backBtnItem } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) fabView = FabButtonView(bgColor: Constants.Colors.Fuchsia, iconName: "icon-tick", superView: summaryView, mainView: view) fabView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } // MARK: Utiility Methods func styleNavBar(navBar: UINavigationBar) { navBar.barTintColor = Constants.Colors.Fuchsia navBar.translucent = false navBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] navBar.tintColor = .whiteColor() } // MARK: Modal Delegate Methods func configModal() { dismissViewControllerAnimated(true, completion: nil) } func dismissModal() { dismissViewControllerAnimated(true, completion: nil) } }
94edc6cf3e97df19af60b2064263b94d
29.84
130
0.718426
false
false
false
false
steelwheels/Coconut
refs/heads/master
CoconutData/Source/Value/CNValuePath.swift
lgpl-2.1
1
/** * @file CNValuePath.swift * @brief Define CNValuePath class * @par Copyright * Copyright (C) 2022 Steel Wheels Project */ import Foundation public class CNValuePath { public enum Element { case member(String) // member name case index(Int) // array index to select array element case keyAndValue(String, CNValue) // key and it's value to select array element static func isSame(source0 src0: Element, source1 src1: Element) -> Bool { let result: Bool switch src0 { case .member(let memb0): switch src1 { case .member(let memb1): result = memb0 == memb1 case .index(_), .keyAndValue(_, _): result = false } case .index(let idx0): switch src1 { case .member(_), .keyAndValue(_, _): result = false case .index(let idx1): result = idx0 == idx1 } case .keyAndValue(let key0, let val0): switch src1 { case .member(_), .index(_): result = false case .keyAndValue(let key1, let val1): if key0 == key1 { switch CNCompareValue(nativeValue0: val0, nativeValue1: val1){ case .orderedAscending, .orderedDescending: result = false case .orderedSame: result = true } } else { result = false } } } return result } } private struct Elements { var firstIdent: String? var elements: Array<Element> public init(firstIdentifier fidt: String?, elements elms: Array<Element>){ firstIdent = fidt elements = elms } } private var mIdentifier: String? private var mElements: Array<Element> private var mExpression: String public var identifier: String? { get { return mIdentifier }} public var elements: Array<Element> { get { return mElements }} public var expression: String { get { return mExpression }} public init(identifier ident: String?, elements elms: Array<Element>){ mIdentifier = ident mElements = elms mExpression = CNValuePath.toExpression(identifier: ident, elements: elms) } public init(identifier ident: String?, member memb: String){ mIdentifier = ident mElements = [ .member(memb) ] mExpression = CNValuePath.toExpression(identifier: ident, elements: mElements) } public init(path pth: CNValuePath, subPath subs: Array<Element>){ mIdentifier = pth.identifier mElements = [] for src in pth.elements { mElements.append(src) } for subs in subs { mElements.append(subs) } mExpression = CNValuePath.toExpression(identifier: pth.identifier, elements: mElements) } public func isIncluded(in targ: CNValuePath) -> Bool { let selms = self.mElements let telms = targ.mElements if selms.count <= telms.count { for i in 0..<selms.count { if !Element.isSame(source0: selms[i], source1: telms[i]) { return false } } return true } else { return false } } public var description: String { get { var result = "" var is1st = true for elm in mElements { switch elm { case .member(let str): if is1st { is1st = false } else { result += "." } result += "\(str)" case .index(let idx): result += "[\(idx)]" case .keyAndValue(let key, let val): result += "[\(key):\(val.description)]" } } return result }} public static func toExpression(identifier ident: String?, elements elms: Array<Element>) -> String { var result: String = "" var is1st: Bool = true if let str = ident { result = "@" + str is1st = false } for elm in elms { switch elm { case .member(let str): if is1st { is1st = false } else { result += "." } result += str case .index(let idx): result += "[\(idx)]" case .keyAndValue(let key, let val): let path: String let quote = "\"" switch val { case .stringValue(let str): path = quote + str + quote default: path = quote + val.description + quote } result += "[\(key):\(path)]" } } return result } public static func pathExpression(string str: String) -> Result<CNValuePath, NSError> { let conf = CNParserConfig(allowIdentiferHasPeriod: false) switch CNStringToToken(string: str, config: conf) { case .ok(let tokens): let stream = CNTokenStream(source: tokens) switch pathExpression(stream: stream) { case .success(let elms): let path = CNValuePath(identifier: elms.firstIdent, elements: elms.elements) return .success(path) case .failure(let err): return .failure(err) } case .error(let err): return .failure(err) } } private static func pathExpression(stream strm: CNTokenStream) -> Result<Elements, NSError> { switch pathExpressionIdentifier(stream: strm) { case .success(let identp): switch pathExpressionMembers(stream: strm, hasIdentifier: identp != nil) { case .success(let elms): return .success(Elements(firstIdentifier: identp, elements: elms)) case .failure(let err): return .failure(err) } case .failure(let err): return .failure(err) } } private static func pathExpressionIdentifier(stream strm: CNTokenStream) -> Result<String?, NSError> { if strm.requireSymbol(symbol: "@") { if let ident = strm.getIdentifier() { return .success(ident) } else { let _ = strm.unget() // unget symbol CNLog(logLevel: .error, message: "Identifier is required for label", atFunction: #function, inFile: #file) } } return .success(nil) } private static func pathExpressionMembers(stream strm: CNTokenStream, hasIdentifier hasident: Bool) -> Result<Array<Element>, NSError> { var is1st: Bool = !hasident var result: Array<Element> = [] while !strm.isEmpty() { /* Parse comma */ if is1st { is1st = false } else if !strm.requireSymbol(symbol: ".") { return .failure(NSError.parseError(message: "Period is expected between members \(near(stream: strm))")) } /* Parse member */ guard let member = strm.getIdentifier() else { return .failure(NSError.parseError(message: "Member for path expression is required \(near(stream: strm))")) } result.append(.member(member)) /* Check "[" symbol */ while strm.requireSymbol(symbol: "[") { switch pathExpressionIndex(stream: strm) { case .success(let elm): result.append(elm) case .failure(let err): return .failure(err) } if !strm.requireSymbol(symbol: "]") { return .failure(NSError.parseError(message: "']' is expected")) } } } return .success(result) } private static func pathExpressionIndex(stream strm: CNTokenStream) -> Result<Element, NSError> { if let index = strm.requireUInt() { return .success(.index(Int(index))) } else if let ident = strm.requireIdentifier() { if strm.requireSymbol(symbol: ":") { switch requireAnyValue(stream: strm) { case .success(let val): return .success(.keyAndValue(ident, val)) case .failure(let err): return .failure(err) } } else { return .failure(NSError.parseError(message: "':' is required between dictionary key and value \(near(stream: strm))")) } } else { return .failure(NSError.parseError(message: "Invalid index \(near(stream: strm))")) } } private static func requireAnyValue(stream strm: CNTokenStream) -> Result<CNValue, NSError> { if let ival = strm.requireUInt() { return .success(.numberValue(NSNumber(integerLiteral: Int(ival)))) } else if let sval = strm.requireIdentifier() { return .success(.stringValue(sval)) } else if let sval = strm.requireString() { return .success(.stringValue(sval)) } else { return .failure(NSError.parseError(message: "immediate value is required for value in key-value index")) } } public static func description(of val: Dictionary<String, Array<CNValuePath.Element>>) -> CNText { let sect = CNTextSection() sect.header = "{" ; sect.footer = "}" for (key, elm) in val { let subsect = CNTextSection() subsect.header = "\(key): {" ; subsect.footer = "}" let desc = toExpression(identifier: nil, elements: elm) let line = CNTextLine(string: desc) subsect.add(text: line) sect.add(text: subsect) } return sect } private static func near(stream strm: CNTokenStream) -> String { if let token = strm.peek(offset: 0) { return "near " + token.toString() } else { return "" } } public func compare(_ val: CNValuePath) -> ComparisonResult { let selfstr = self.mExpression let srcstr = val.mExpression if selfstr == srcstr { return .orderedSame } else if selfstr > srcstr { return .orderedDescending } else { return .orderedAscending } } }
ff548c1bb3597ceabac9d5f1f6f361e6
26.324841
138
0.654079
false
false
false
false
cdmx/MiniMancera
refs/heads/master
miniMancera/View/HomeSplash/VHomeSplashCellScore.swift
mit
1
import UIKit class VHomeSplashCellScore:VHomeSplashCell { private weak var labelScore:UILabel! private weak var imageView:UIImageView! private weak var layoutLabelLeft:NSLayoutConstraint! private weak var timer:Timer? private var expectedScore:Int private var currentScore:Int private let numberFormatter:NumberFormatter private let kFontSize:CGFloat = 20 private let kLabelWidth:CGFloat = 110 private let kImageWidth:CGFloat = 60 private let kImageTop:CGFloat = 10 private let kTimerInterval:TimeInterval = 0.02 private let kMinIntegers:Int = 0 private let kMaxDecimals:Int = 0 override init(frame:CGRect) { numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal numberFormatter.minimumIntegerDigits = kMinIntegers numberFormatter.maximumFractionDigits = kMaxDecimals expectedScore = 0 currentScore = 0 super.init(frame:frame) isUserInteractionEnabled = false let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center self.imageView = imageView let labelScore:UILabel = UILabel() labelScore.translatesAutoresizingMaskIntoConstraints = false labelScore.isUserInteractionEnabled = false labelScore.font = UIFont.game(size:kFontSize) labelScore.textColor = UIColor.white labelScore.textAlignment = NSTextAlignment.right self.labelScore = labelScore addSubview(imageView) addSubview(labelScore) NSLayoutConstraint.equalsVertical( view:labelScore, toView:self) layoutLabelLeft = NSLayoutConstraint.leftToLeft( view:labelScore, toView:self) NSLayoutConstraint.width( view:labelScore, constant:kLabelWidth) NSLayoutConstraint.topToTop( view:imageView, toView:self, constant:kImageTop) NSLayoutConstraint.bottomToBottom( view:imageView, toView:self) NSLayoutConstraint.leftToRight( view:imageView, toView:labelScore) NSLayoutConstraint.width( view:imageView, constant:kImageWidth) } required init?(coder:NSCoder) { return nil } deinit { timer?.invalidate() } override func layoutSubviews() { let width:CGFloat = bounds.maxX let contentWidth:CGFloat = kLabelWidth + kImageWidth let remainWidth:CGFloat = width - contentWidth let marginLeft:CGFloat = remainWidth / 2.0 layoutLabelLeft.constant = marginLeft super.layoutSubviews() } override func config(controller:CHomeSplash, model:MHomeSplashProtocol) { super.config(controller:controller, model:model) timer?.invalidate() guard let model:MHomeSplashScore = model as? MHomeSplashScore else { return } imageView.image = model.icon guard let dataOption:DOption = model.dataOption else { return } expectedScore = Int(dataOption.maxScore) currentScore = 0 printScore() timer = Timer.scheduledTimer( timeInterval:kTimerInterval, target:self, selector:#selector(actionTimer(sender:)), userInfo:nil, repeats:true) } //MARK: actions func actionTimer(sender timer:Timer) { if currentScore >= expectedScore { timer.invalidate() } else { currentScore += 1 printScore() } } //MARK: private private func printScore() { let score:NSNumber = self.currentScore as NSNumber guard let scoreString:String = numberFormatter.string(from:score) else { return } labelScore.text = scoreString } }
0a5696b83ddd853ed58adc41e8985561
25.898204
75
0.592609
false
false
false
false
rjstelling/HTTPFormRequest
refs/heads/master
Projects/HTTPFormEncoder/HTTPFormEncoder/HTTPFormSingleValueEncodingContainer.swift
mit
1
// // HTTPFormSingleValueEncodingContainer.swift // HTTPFormEncoder // // Created by Richard Stelling on 18/07/2018. // Copyright © 2018 Lionheart Applications Ltd. All rights reserved. // import Foundation struct HTTPFormSingleValueEncodingContainer: SingleValueEncodingContainer { var codingPath: [CodingKey] let encoder: HTTPFormEncoder let containerName: String internal init(referencing encoder: HTTPFormEncoder, codingPath: [CodingKey], name: String) { self.encoder = encoder self.codingPath = codingPath self.containerName = name } mutating func encodeNil() throws { print("nil… skipping!)") } mutating func encode(_ value: Bool) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: String) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Double) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Float) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int8) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int16) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int32) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: Int64) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt8) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt16) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt32) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode(_ value: UInt64) throws { self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) } mutating func encode<T>(_ value: T) throws where T : Encodable { //self.encoder.parameters[self.containerName] = try encoder.box( value ) //print("VLAUE: \(value)") //fatalError("NOT IMP") self.encoder.parameters.append( ( self.containerName, try encoder.box_(value) ) ) //self.encoder.parameters[self.containerName] = try encoder.box_( value ) } }
4c284142b33814fc6c00b5a919fbefd2
26.743802
96
0.617814
false
false
false
false
segmentio/analytics-swift
refs/heads/main
Examples/apps/SegmentExtensionsExample/SegmentExtensionsExample/LoginViewController.swift
mit
1
// // LoginViewController.swift // SegmentExtensionsExample // // Created by Alan Charles on 8/10/21. // import UIKit import AuthenticationServices class LoginViewController: UIViewController { var analytics = UIApplication.shared.delegate?.analytics @IBOutlet weak var loginProviderStackView: UIStackView! override func viewDidLoad() { super.viewDidLoad() setupProviderLoginView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) performExistingAccountSetupFlows() } //appleId button func setupProviderLoginView() { let authorizationButton = ASAuthorizationAppleIDButton() authorizationButton.addTarget(self, action: #selector(handleAuthorizationAppleIDButtonPress), for: .touchUpInside) self.loginProviderStackView.addArrangedSubview(authorizationButton) } //prompts the user if existing login info is found. func performExistingAccountSetupFlows() { //prepare requests for Apple ID and password providers let requests = [ASAuthorizationAppleIDProvider().createRequest(), ASAuthorizationPasswordProvider().createRequest()] //create and authorization controller with above requests let authorizationController = ASAuthorizationController(authorizationRequests: requests) authorizationController.delegate = self authorizationController.presentationContextProvider = self authorizationController.performRequests() } //perform appleId request @objc func handleAuthorizationAppleIDButtonPress() { let appleIDProvider = ASAuthorizationAppleIDProvider() let request = appleIDProvider.createRequest() request.requestedScopes = [.fullName, .email] let authorizationController = ASAuthorizationController(authorizationRequests: [request]) authorizationController.delegate = self authorizationController.presentationContextProvider = self authorizationController.performRequests() analytics?.track(name: "Apple ID Button Pressed") } } //MARK: - ASAuthorizationController Delegate conformance extension LoginViewController: ASAuthorizationControllerDelegate { func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { switch authorization.credential { case let appleIDCredential as ASAuthorizationAppleIDCredential: //struct for identify (better place to put this?) struct UserTraits: Codable { let name: PersonNameComponents? let email: String? var username: String? = nil } let userIdentifier = appleIDCredential.user let fullName = appleIDCredential.fullName let email = appleIDCredential.email self.saveUserInKeychain(userIdentifier) //identify the user analytics?.identify(userId: userIdentifier, traits: UserTraits(name: fullName, email: email)) self.showResultViewController(userIdentifier: userIdentifier, fullName: fullName, email: email) case let passwordCredential as ASPasswordCredential: let username = passwordCredential.user let password = passwordCredential.password DispatchQueue.main.async { self.showPasswordCredentialAlert(username: username, password: password) } default: break } } private func saveUserInKeychain(_ userIdentifier: String) { //change 'co.alancharles.SegmentExtensionsExample' to your identifier do { try KeychainItem(service: "co.alancharles.SegmentExtensionsExample", account: "userIdentifier").saveItem(userIdentifier) analytics?.track(name: "Saved to Keychain") } catch { //handle error and optionally track it analytics?.log(message: "Unable to save userId to keychain.", kind: .error) } } private func showResultViewController(userIdentifier: String, fullName: PersonNameComponents?, email: String?){ guard let viewController = self.presentingViewController as? ResultViewController else { return } DispatchQueue.main.async { viewController.userIdentifierLabel.text = userIdentifier if let givenName = fullName?.givenName { viewController.givenNameLabel.text = givenName } if let familyName = fullName?.familyName { viewController.familyNameLabel.text = familyName } if let email = email { viewController.emailLabel.text = email } self.dismiss(animated: true, completion: nil) } } private func showPasswordCredentialAlert(username: String, password: String) { let message = "This app has recieved your selected credential from the keychain.\n\n Username: \(username)\n Password: \(password)" let alertController = UIAlertController(title: "Keychain Credential Received", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { //handle error analytics?.log(message: error, king: .error) } } //MARK: - ASAuthorizationController Delegate presentation conformance extension LoginViewController: ASAuthorizationControllerPresentationContextProviding { func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { return self.view.window! } } extension UIViewController { func showLoginViewController() { let storyboard = UIStoryboard(name: "Main", bundle: nil) if let loginViewController = storyboard.instantiateViewController(identifier: "loginViewController") as? LoginViewController { loginViewController.modalPresentationStyle = .formSheet loginViewController.isModalInPresentation = true self.present(loginViewController, animated: true, completion: nil) } } }
eac9a5e978d923021c16f9157524473f
39.084848
139
0.673874
false
false
false
false
fe9lix/PennyPincher
refs/heads/master
PennyPincher/PennyPincher.swift
mit
1
import UIKit public typealias PennyPincherResult = (template: PennyPincherTemplate, similarity: CGFloat) public class PennyPincher { private static let NumResamplingPoints = 16 public class func createTemplate(_ id: String, points: [CGPoint]) -> PennyPincherTemplate? { guard points.count > 0 else { return nil } return PennyPincherTemplate(id: id, points: PennyPincher.resampleBetweenPoints(points)) } public class func recognize(_ points: [CGPoint], templates: [PennyPincherTemplate]) -> PennyPincherResult? { guard points.count > 0 && templates.count > 0 else { return nil } let c = PennyPincher.resampleBetweenPoints(points) guard c.count > 0 else { return nil } var similarity = CGFloat.leastNormalMagnitude var t: PennyPincherTemplate! var d: CGFloat for template in templates { d = 0.0 let count = min(c.count, template.points.count) for i in 0...count - 1 { let tp = template.points[i] let cp = c[i] d = d + tp.x * cp.x + tp.y * cp.y if d > similarity { similarity = d t = template } } } guard t != nil else { return nil } return (t, similarity) } private class func resampleBetweenPoints(_ p: [CGPoint]) -> [CGPoint] { var points = p let i = pathLength(points) / CGFloat(PennyPincher.NumResamplingPoints - 1) var d: CGFloat = 0.0 var v = [CGPoint]() var prev = points.first! var index = 0 for _ in points { if index == 0 { index += 1 continue } let thisPoint = points[index] let prevPoint = points[index - 1] let pd = distanceBetween(thisPoint, to: prevPoint) if (d + pd) >= i { let q = CGPoint( x: prevPoint.x + (thisPoint.x - prevPoint.x) * (i - d) / pd, y: prevPoint.y + (thisPoint.y - prevPoint.y) * (i - d) / pd ) var r = CGPoint(x: q.x - prev.x, y: q.y - prev.y) let rd = distanceBetween(CGPoint.zero, to: r) r.x = r.x / rd r.y = r.y / rd d = 0.0 prev = q v.append(r) points.insert(q, at: index) index += 1 } else { d = d + pd } index += 1 } return v } private class func pathLength(_ points: [CGPoint]) -> CGFloat { var d: CGFloat = 0.0 for i in 1..<points.count { d = d + distanceBetween(points[i - 1], to: points[i]) } return d } private class func distanceBetween(_ pointA: CGPoint, to pointB: CGPoint) -> CGFloat { let distX = pointA.x - pointB.x let distY = pointA.y - pointB.y return sqrt((distX * distX) + (distY * distY)) } }
b921232e00763ef03d9315f9358990e4
29.618182
112
0.461995
false
false
false
false
OBJCC/Flying-Swift
refs/heads/master
test-swift/UIDynamicsCatalog/CollisionsGravitySpringViewController.swift
apache-2.0
3
// // CollisionsGravitySpringViewController.swift // test-swift // // Created by Su Wei on 14-6-14. // Copyright (c) 2014年 OBJCC.COM. All rights reserved. // import UIKit class CollisionsGravitySpringViewController: UIViewController { //! The view that displays the attachment point on square1. var square1AttachmentView : UIImageView! //! The view that the user drags to move square1. var attachmentView : UIImageView! var square1 : UIView! var animator : UIDynamicAnimator! var attachmentBehavior : UIAttachmentBehavior! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let box1:UIImageView = UIImageView(image:UIImage(named:"Box1")) self.attachmentView = UIImageView(image:UIImage(named:"AttachmentPoint_Mask")) self.square1AttachmentView = UIImageView(image:UIImage(named:"AttachmentPoint_Mask")) self.attachmentView.center = CGPointMake(self.view.center.x, 170) self.square1 = UIView(frame: box1.frame) self.square1.center = CGPointMake(self.view.center.x, 320) self.square1.addSubview(box1) self.square1.addSubview(square1AttachmentView) self.view.addSubview(self.square1) self.view.addSubview(self.attachmentView) let animator:UIDynamicAnimator = UIDynamicAnimator(referenceView: self.view) let collisionBehavior:UICollisionBehavior = UICollisionBehavior(items:[self.square1]) // Creates collision boundaries from the bounds of the dynamic animator's // reference view (self.view). collisionBehavior.translatesReferenceBoundsIntoBoundary = true animator.addBehavior(collisionBehavior) let squareCenterPoint:CGPoint = CGPointMake(self.square1.center.x, self.square1.center.y - 110.0) let attachmentPoint:UIOffset = UIOffsetMake(-25.0, -25.0); // By default, an attachment behavior uses the center of a view. By using a // small offset, we get a more interesting effect which will cause the view // to have rotation movement when dragging the attachment. let attachmentBehavior:UIAttachmentBehavior = UIAttachmentBehavior(item:self.square1, offsetFromCenter:attachmentPoint, attachedToAnchor:squareCenterPoint) animator.addBehavior(attachmentBehavior) self.attachmentBehavior = attachmentBehavior // Visually show the attachment points self.attachmentView.center = attachmentBehavior.anchorPoint self.attachmentView.tintColor = UIColor.redColor() self.attachmentView.image = self.attachmentView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.square1AttachmentView.center = CGPointMake(25.0, 25.0) self.square1AttachmentView.tintColor = UIColor.blueColor() self.square1AttachmentView.image = self.square1AttachmentView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) // Visually show the connection between the attachment points. (self.view as UIDCDecorationView).trackAndDrawAttachmentFromView(self.attachmentView, toView:self.square1, withAttachmentOffset:CGPointMake(-25.0, -25.0)); // These parameters set the attachment in spring mode, instead of a rigid // connection. attachmentBehavior.frequency = 1.0 attachmentBehavior.damping = 0.1 let gravityBehavior:UIGravityBehavior = UIGravityBehavior(items:[self.square1]) animator.addBehavior(gravityBehavior) self.animator = animator; JLToast.makeText("A little different from the apple's for fun").show() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // #pragma 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. } */ @IBAction func handleAttachmentGesture(sender : UIPanGestureRecognizer) { self.attachmentBehavior!.anchorPoint = sender.locationInView(self.view) self.attachmentView.center = self.attachmentBehavior!.anchorPoint print("aaaa->") println(self.attachmentView) print("bbbb->") println(self.square1) } }
056a687b4e343472f4939c934bd44b79
40.016393
163
0.694844
false
false
false
false
gregomni/swift
refs/heads/main
test/SILGen/without_actually_escaping.swift
apache-2.0
2
// RUN: %target-swift-emit-silgen -module-name without_actually_escaping %s | %FileCheck %s var escapeHatch: Any = 0 // CHECK-LABEL: sil hidden [ossa] @$s25without_actually_escaping9letEscape1fyycyyXE_tF func letEscape(f: () -> ()) -> () -> () { // CHECK: bb0([[ARG:%.*]] : $@noescape @callee_guaranteed () -> ()): // CHECK: [[THUNK:%.*]] = function_ref @$sIg_Ieg_TR : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // TODO: Use a canary wrapper instead of just copying the nonescaping value // CHECK: [[ESCAPABLE_COPY:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG]]) // CHECK: [[MD_ESCAPABLE_COPY:%.*]] = mark_dependence [[ESCAPABLE_COPY]] // CHECK: [[BORROW_MD_ESCAPABLE_COPY:%.*]] = begin_borrow [[MD_ESCAPABLE_COPY]] // CHECK: [[SUB_CLOSURE:%.*]] = function_ref @ // CHECK: [[RESULT:%.*]] = apply [[SUB_CLOSURE]]([[BORROW_MD_ESCAPABLE_COPY]]) // CHECK: destroy_value [[MD_ESCAPABLE_COPY]] // CHECK: return [[RESULT]] return withoutActuallyEscaping(f) { return $0 } } // thunk for @callee_guaranteed () -> () // The thunk must be [without_actually_escaping]. // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [without_actually_escaping] [ossa] @$sIg_Ieg_TR : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () { // CHECK-LABEL: sil hidden [ossa] @$s25without_actually_escaping14letEscapeThrow1fyycyycyKXE_tKF // CHECK: bb0([[ARG:%.*]] : $@noescape @callee_guaranteed () -> (@owned @callee_guaranteed () -> (), @error Error)): // CHECK: [[CVT:%.*]] = function_ref @$sIeg_s5Error_pIgozo_Ieg_sAA_pIegozo_TR // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CVT]]([[ARG]]) // CHECK: [[MD:%.*]] = mark_dependence [[CLOSURE]] : {{.*}} on [[ARG]] // CHECK: [[BORROW:%.*]] = begin_borrow [[MD]] // CHECK: [[USER:%.*]] = function_ref @$s25without_actually_escaping14letEscapeThrow1fyycyycyKXE_tKFyycyycyKcKXEfU_ // CHECK: try_apply [[USER]]([[BORROW]]) : {{.*}}, normal bb1, error bb2 // // CHECK: bb1([[RES:%.*]] : @owned $@callee_guaranteed () -> ()): // CHECK: [[ESCAPED:%.*]] = is_escaping_closure [[BORROW]] // CHECK: cond_fail [[ESCAPED]] : $Builtin.Int1 // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value [[MD]] // CHECK: return [[RES]] // // CHECK: bb2([[ERR:%.*]] : @owned $Error): // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value [[MD]] // CHECK: throw [[ERR]] : $Error // CHECK: } func letEscapeThrow(f: () throws -> () -> ()) throws -> () -> () { return try withoutActuallyEscaping(f) { return try $0() } } // thunk for @callee_guaranteed () -> (@owned @escaping @callee_guaranteed () -> (), @error @owned Error) // The thunk must be [without_actually_escaping]. // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [without_actually_escaping] [ossa] @$sIeg_s5Error_pIgozo_Ieg_sAA_pIegozo_TR : $@convention(thin) (@noescape @callee_guaranteed () -> (@owned @callee_guaranteed () -> (), @error Error)) -> (@owned @callee_guaranteed () -> (), @error Error) { // We used to crash on this example because we would use the wrong substitution // map. struct DontCrash { private func firstEnv<L1>( closure1: (L1) -> Bool, closure2: (L1) -> Bool ) { withoutActuallyEscaping(closure1) { closure1 in secondEnv( closure1: closure1, closure2: closure2 ) } } private func secondEnv<L2>( closure1: @escaping (L2) -> Bool, closure2: (L2) -> Bool ) { withoutActuallyEscaping(closure2) { closure2 in } } } func modifyAndPerform<T>(_ _: UnsafeMutablePointer<T>, closure: () ->()) { closure() } // Make sure that we properly handle cases where the input closure is not // trivial. This means we need to copy first. // CHECK-LABEL: sil hidden [ossa] @$s25without_actually_escaping0A24ActuallyEscapingConflictyyF : $@convention(thin) () -> () { // CHECK: [[CLOSURE_1_FUN:%.*]] = function_ref @$s25without_actually_escaping0A24ActuallyEscapingConflictyyFyycfU_ : // CHECK: [[CLOSURE_1:%.*]] = partial_apply [callee_guaranteed] [[CLOSURE_1_FUN]]( // CHECK: [[BORROWED_CLOSURE_1:%.*]] = begin_borrow [lexical] [[CLOSURE_1]] // CHECK: [[COPY_BORROWED_CLOSURE_1:%.*]] = copy_value [[BORROWED_CLOSURE_1]] // CHECK: [[COPY_2_BORROWED_CLOSURE_1:%.*]] = copy_value [[COPY_BORROWED_CLOSURE_1]] // CHECK: [[THUNK_FUNC:%.*]] = function_ref @$sIeg_Ieg_TR : // CHECK: [[THUNK_PA:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FUNC]]([[COPY_2_BORROWED_CLOSURE_1]]) // CHECK: [[THUNK_PA_MDI:%.*]] = mark_dependence [[THUNK_PA]] : $@callee_guaranteed () -> () on [[COPY_BORROWED_CLOSURE_1]] : $@callee_guaranteed () -> () // CHECK: destroy_value [[THUNK_PA_MDI]] // CHECK: destroy_value [[COPY_BORROWED_CLOSURE_1]] // CHECK: } // end sil function '$s25without_actually_escaping0A24ActuallyEscapingConflictyyF' func withoutActuallyEscapingConflict() { var localVar = 0 let nestedModify = { localVar = 3 } withoutActuallyEscaping(nestedModify) { modifyAndPerform(&localVar, closure: $0) } } // CHECK-LABEL: sil [ossa] @$s25without_actually_escaping0A25ActuallyEscapingCFunction8functionyyyXC_tF // CHECK: bb0([[ARG:%.*]] : $@convention(c) @noescape () -> ()): // CHECK: [[E:%.*]] = convert_function [[ARG]] : $@convention(c) @noescape () -> () to [without_actually_escaping] $@convention(c) () -> () // CHECK: [[F:%.*]] = function_ref @$s25without_actually_escaping0A25ActuallyEscapingCFunction8functionyyyXC_tFyyyXCXEfU_ : $@convention(thin) (@convention(c) () -> ()) -> () // CHECK: apply [[F]]([[E]]) : $@convention(thin) (@convention(c) () -> ()) -> () public func withoutActuallyEscapingCFunction(function: (@convention(c) () -> Void)) { withoutActuallyEscaping(function) { f in var pointer: UnsafeRawPointer? = nil pointer = unsafeBitCast(f, to: UnsafeRawPointer.self) print(pointer) } }
6f44ddff8503bf28f5ec9d46cb106274
49.930435
316
0.640772
false
false
false
false
Chaosspeeder/YourGoals
refs/heads/master
YourGoals/Business/Tasks/TaskOrderManager.swift
lgpl-3.0
1
// // TaskPrioManager.swift // YourGoals // // Created by André Claaßen on 29.10.17. // Copyright © 2017 André Claaßen. All rights reserved. // import Foundation import CoreData extension ActionableType { /// get the name of the entity in core data for the actionable type /// /// - Returns: name of the entity func entityName() -> String { switch self { case .habit: return "Habit" case .task: return "Task" } } } /// priority management for tasks class TaskOrderManager:StorageManagerWorker { /// retrieve the tasks ordered from the core data store for the given goal /// /// - Parameter goal: the goal /// - Returns: tasks by order /// - Throws: core data exception func tasksByOrder(forGoal goal: Goal) throws -> [Task] { let tasks = try self.manager.tasksStore.fetchItems { request in request.predicate = NSPredicate(format: "goal == %@", goal) request.sortDescriptors = [ NSSortDescriptor(key: "state", ascending: true), NSSortDescriptor(key: "prio", ascending: true) ] } return tasks } /// update the order of actionables by prio and "renumber" the prio in the tasks /// /// - Parameter goal: update the task order for this goal func updateOrderByPrio(forGoal goal: Goal, andType type:ActionableType) { let actionablesSortedByPrio = goal.all(actionableType: type).sorted(by: { $0.prio < $1.prio }) updateOrder(actionables: actionablesSortedByPrio, type: type) } /// update the order of actionabels by renumbering the prio in order to the offset in the array /// /// - Parameter tasks: ordered array of tasks func updateOrder(actionables: [Actionable], type: ActionableType) { for tuple in actionables.enumerated() { let prio = Int16(tuple.offset) var actionable = tuple.element actionable.prio = prio } } // MARK: - TaskPositioningProtocol /// after a reorder is done, a task has changed its position from the old offset to the new offset /// /// - Parameters: /// - tasks: original tasks /// - fromPosition: old position of the task in the array /// - toPosition: new position for the task in the array /// - Returns: updated task order func updateTaskPosition(tasks: [Task], fromPosition: Int, toPosition: Int) throws { var tasksReorderd = tasks tasksReorderd.rearrange(from: fromPosition, to: toPosition) updateOrder(actionables: tasksReorderd, type: .task) try self.manager.saveContext() } }
890d283ee5a6bd5c90662346a1325f9d
32.9375
102
0.627993
false
false
false
false
hhsolar/MemoryMaster-iOS
refs/heads/master
MemoryMaster/Controller/TabLibrary/EditNoteViewController.swift
mit
1
// // EditNoteViewController.swift // MemoryMaster // // Created by apple on 23/10/2017. // Copyright © 2017 greatwall. All rights reserved. // import UIKit import CoreData import Photos import SVProgressHUD protocol EditNoteViewControllerDelegate: class { func passNoteInforBack(noteInfo: MyBasicNoteInfo) } private let cellReuseIdentifier = "EditNoteCollectionViewCell" class EditNoteViewController: BaseTopViewController { // public api var isFirstTimeEdit = false var passedInCardIndex: IndexPath? var passedInCardStatus: String? var passedInNoteInfo: MyBasicNoteInfo! { didSet { minAddCardIndex = passedInNoteInfo?.numberOfCard minRemoveCardIndex = passedInNoteInfo?.numberOfCard } } var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer { didSet { setupData() } } @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var flipButton: UIBarButtonItem! @IBOutlet weak var saveButton: UIButton! var notes = [CardContent]() var changedCard = Set<Int>() var minAddCardIndex: Int? var minRemoveCardIndex: Int? var currentCardIndex: Int { return Int(collectionView.contentOffset.x) / Int(collectionView.bounds.width) } weak var delegate: EditNoteViewControllerDelegate? var keyBoardHeight: CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() setupUI() setupCollectionView() } override func setupUI() { super.setupUI() titleLabel.text = passedInNoteInfo.name if passedInNoteInfo.type == NoteType.single.rawValue { flipButton.image = UIImage(named: "flip_icon_disable") flipButton.isEnabled = false } saveButton.setTitleColor(UIColor.white, for: .normal) view.bringSubview(toFront: saveButton) } private func setupCollectionView() { collectionView.delegate = self collectionView.dataSource = self collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor.lightGray let layout = UICollectionViewFlowLayout.init() layout.itemSize = CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height) layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 collectionView.collectionViewLayout = layout let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(returnKeyBoard)) swipeRecognizer.direction = .down swipeRecognizer.numberOfTouchesRequired = 1 collectionView.addGestureRecognizer(swipeRecognizer) let nib = UINib(nibName: cellReuseIdentifier, bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: cellReuseIdentifier) } private func setupData() { for i in 0..<passedInNoteInfo.numberOfCard { let cardContent = CardContent.getCardContent(with: passedInNoteInfo.name, at: i, in: passedInNoteInfo.type) notes.append(cardContent) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) collectionView.setNeedsLayout() if let indexPath = passedInCardIndex { collectionView.scrollToItem(at: indexPath, at: .left, animated: false) if let status = passedInCardStatus { setFilpButton(cellStatus: CardStatus(rawValue: status)!) } else { if passedInNoteInfo.type == NoteType.single.rawValue && notes[indexPath.item].title == NSAttributedString() { flipButton.image = UIImage(named: "flip_icon_disable") flipButton.isEnabled = false } else { flipButton.image = UIImage(named: "flip_icon") flipButton.isEnabled = true } } } self.registerForKeyboardNotifications() } private func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell let status: CardStatus! = cell.currentStatus if var dict = UserDefaults.standard.dictionary(forKey: UserDefaultsKeys.lastReadStatus) { dict.updateValue((passedInNoteInfo?.id)!, forKey: UserDefaultsDictKey.id) dict.updateValue(currentCardIndex, forKey: UserDefaultsDictKey.cardIndex) dict.updateValue(ReadType.edit.rawValue, forKey: UserDefaultsDictKey.readType) dict.updateValue(status.rawValue, forKey: UserDefaultsDictKey.cardStatus) UserDefaults.standard.set(dict, forKey: UserDefaultsKeys.lastReadStatus) } } // MARK: show and dismiss keyboard @objc private func keyboardWasShown(notification: Notification) { let info = notification.userInfo! as NSDictionary let nsValue = info.object(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue keyBoardHeight = nsValue.cgRectValue.size.height let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell cell.cutTextView(KBHeight: keyBoardHeight) } @objc func returnKeyBoard(byReactionTo swipeRecognizer: UISwipeGestureRecognizer) { if swipeRecognizer.state == .ended { let indexPath = IndexPath(item: currentCardIndex, section: 0) let cell = collectionView.cellForItem(at: indexPath) as! EditNoteCollectionViewCell cell.editingTextView?.resignFirstResponder() cell.extendTextView() } } @IBAction func addNoteAction(_ sender: UIBarButtonItem) { let cardContent = CardContent(title: NSAttributedString.init(), body: NSAttributedString.init()) collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: true) let index = currentCardIndex + 1 notes.insert(cardContent, at: index) collectionView.reloadData() collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .left, animated: true) collectionView.reloadItems(at: [IndexPath(item: index - 1, section: 0)]) if var minIndex = minAddCardIndex, minIndex > index { minIndex = index } if passedInNoteInfo.type == NoteType.single.rawValue { setFilpButton(cellStatus: CardStatus.bodyFrontWithoutTitle) } else { setFilpButton(cellStatus: CardStatus.titleFront) } } @IBAction func removeNoteAction(_ sender: UIBarButtonItem) { if notes.count == 1 { self.showAlert(title: "Error!", message: "A note must has one item at least.") return } let index = currentCardIndex if index == 0 { collectionView.scrollToItem(at: IndexPath(item: index + 1, section: 0), at: .left, animated: true) notes.remove(at: index) collectionView.reloadData() // have to add function reloadItems, or there will be a cell not update collectionView.reloadItems(at: [IndexPath(item: index, section: 0)]) collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .left, animated: true) return } collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: true) notes.remove(at: index) collectionView.reloadData() collectionView.scrollToItem(at: IndexPath(item: index - 1, section: 0), at: .left, animated: true) collectionView.reloadItems(at: [IndexPath(item: index - 1, section: 0)]) if var minIndex = minRemoveCardIndex, minIndex > index { minIndex = index } if passedInNoteInfo.type == NoteType.single.rawValue { let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell setFilpButton(cellStatus: cell.currentStatus!) } } @IBAction func addPhotoAction(_ sender: UIBarButtonItem) { let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell cell.editingTextView?.resignFirstResponder() cell.extendTextView() showPhotoMenu() } @IBAction func addBookmarkAction(_ sender: UIBarButtonItem) { let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell let placeholder = String(format: "%@-%@-%@-%d-%@", passedInNoteInfo.name, passedInNoteInfo.type, ReadType.edit.rawValue, currentCardIndex, cell.currentStatus!.rawValue) let alert = UIAlertController(title: "Bookmark", message: "Give a name for the bookmark.", preferredStyle: .alert) alert.addTextField { textFiled in textFiled.placeholder = placeholder } let ok = UIAlertAction(title: "OK", style: .default, handler: { [weak self = self] action in var text = placeholder if alert.textFields![0].text! != "" { text = alert.textFields![0].text! } let isNameUsed = try? BookMark.find(matching: text, in: (self?.container?.viewContext)!) if isNameUsed! { self?.showAlert(title: "Error!", message: "Name already used, please give another name.") } else { let bookmark = MyBookmark(name: text, id: (self?.passedInNoteInfo.id)!, time: Date(), readType: ReadType.edit.rawValue, readPage: (self?.currentCardIndex)!, readPageStatus: cell.currentStatus!.rawValue) self?.container?.performBackgroundTask({ (context) in self?.save() BookMark.findOrCreate(matching: bookmark, in: context) DispatchQueue.main.async { self?.showSavedPrompt() } }) } }) let cancel = UIAlertAction(title: "cancel", style: .cancel, handler: nil) alert.addAction(ok) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } @IBAction func flipCardAction(_ sender: UIBarButtonItem) { let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell if cell.currentStatus! == CardStatus.titleFront { cell.currentStatus = CardStatus.bodyFrontWithTitle cell.showBody(noteType: NoteType(rawValue: passedInNoteInfo.type)!) } else { cell.currentStatus = CardStatus.titleFront cell.showTitle(noteType: NoteType(rawValue: passedInNoteInfo.type)!) } } @IBAction func saveAction(_ sender: UIButton) { playSound.playClickSound(SystemSound.buttonClick) save() showSavedPrompt() } override func backAction(_ sender: UIButton) { playSound.playClickSound(SystemSound.buttonClick) let minChangedIndex = minRemoveCardIndex! < minAddCardIndex! ? minRemoveCardIndex! : minAddCardIndex! if changedCard.isEmpty && minChangedIndex == passedInNoteInfo.numberOfCard && notes.count == passedInNoteInfo.numberOfCard { if let context = container?.viewContext { _ = try? BasicNoteInfo.findOrCreate(matching: passedInNoteInfo!, in: context) try? context.save() } dismissView() } else { showAlertWithAction(title: "Reminder!", message: "Do you want to save your change?", hasNo: true, yesHandler: { [weak self] _ in self?.save() self?.showSavedPrompt() self?.afterDelay(0.8) { self?.dismissView() } }, noHandler: { [weak self] _ in self?.dismissView() }) } } private func save() { let minChangedIndex = minRemoveCardIndex! < minAddCardIndex! ? minRemoveCardIndex! : minAddCardIndex! if minChangedIndex == passedInNoteInfo.numberOfCard && notes.count == passedInNoteInfo.numberOfCard { // case 1: no card added or removed for i in changedCard { notes[i].saveCardContentToFile(cardIndex: i, noteName: passedInNoteInfo.name, noteType: passedInNoteInfo.type) } } else if minChangedIndex == passedInNoteInfo.numberOfCard && notes.count > passedInNoteInfo.numberOfCard { // case 2: card only add or removed after original length for i in minChangedIndex..<notes.count { notes[i].saveCardContentToFile(cardIndex: i, noteName: passedInNoteInfo.name, noteType: passedInNoteInfo.type) } for i in changedCard { notes[i].saveCardContentToFile(cardIndex: i, noteName: passedInNoteInfo.name, noteType: passedInNoteInfo.type) } } else { // case 3: card inserted or removed in original array range for i in minChangedIndex..<passedInNoteInfo.numberOfCard { CardContent.removeCardContent(with: passedInNoteInfo.name, at: i, in: passedInNoteInfo.type) } if minChangedIndex <= notes.count { for i in minChangedIndex..<notes.count { notes[i].saveCardContentToFile(cardIndex: i, noteName: passedInNoteInfo.name, noteType: passedInNoteInfo.type) } } for i in changedCard { if i < minChangedIndex { notes[i].saveCardContentToFile(cardIndex: i, noteName: passedInNoteInfo.name, noteType: passedInNoteInfo.type) } else { break } } } changedCard.removeAll() passedInNoteInfo.numberOfCard = notes.count let context = container?.viewContext _ = try? BasicNoteInfo.findOrCreate(matching: passedInNoteInfo!, in: context!) try? context?.save() } private func afterDelay(_ seconds: Double, closure: @escaping () -> ()) { DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: closure) } private func dismissView() { delegate?.passNoteInforBack(noteInfo: passedInNoteInfo!) guard isFirstTimeEdit else { dismiss(animated: true, completion: nil) return } let controller = self.presentingViewController?.presentingViewController controller?.dismiss(animated: true, completion: { NotificationCenter.default.post(name: Notification.Name(rawValue: "RefreshPage"), object: nil) }) } private func setFilpButton(cellStatus: CardStatus) { if cellStatus == CardStatus.bodyFrontWithoutTitle { flipButton.image = UIImage(named: "flip_icon_disable") flipButton.isEnabled = false } else { flipButton.image = UIImage(named: "flip_icon") flipButton.isEnabled = true } } } extension EditNoteViewController: UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if passedInNoteInfo.type == NoteType.single.rawValue { let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell setFilpButton(cellStatus: cell.currentStatus!) } } } extension EditNoteViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return notes.count } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let newCell = cell as! EditNoteCollectionViewCell var cellStatus = CardStatus.titleFront if passedInNoteInfo.type == NoteType.single.rawValue && notes[indexPath.item].title == NSAttributedString() { cellStatus = CardStatus.bodyFrontWithoutTitle } else if let passIndex = passedInCardIndex, let status = passedInCardStatus, indexPath == passIndex { cellStatus = CardStatus(rawValue: status)! } newCell.updateCell(with: notes[indexPath.row], at: indexPath.row, total: notes.count, cellStatus: cellStatus, noteType: NoteType(rawValue: passedInNoteInfo.type)!) newCell.delegate = self } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: "EditNoteCollectionViewCell", for: indexPath) as! EditNoteCollectionViewCell } } extension EditNoteViewController: EditNoteCollectionViewCellDelegate { func noteTitleEdit(for cell: EditNoteCollectionViewCell) { if cell.titleEditButton.titleLabel?.text == "Add Title" { cell.currentStatus = CardStatus.titleFront cell.showTitle(noteType: NoteType.single) } else { cell.currentStatus = CardStatus.bodyFrontWithoutTitle cell.showBody(noteType: NoteType.single) cell.titleTextView.attributedText = NSAttributedString() } setFilpButton(cellStatus: cell.currentStatus!) } func noteTextContentChange(cardIndex: Int, textViewType: String, textContent: NSAttributedString) { if textViewType == "title" { if !notes[cardIndex].title.isEqual(to: textContent) { notes[cardIndex].title = textContent if cardIndex < passedInNoteInfo.numberOfCard { changedCard.insert(cardIndex) } } } else { if !notes[cardIndex].body.isEqual(to: textContent) { notes[cardIndex].body = textContent if cardIndex < passedInNoteInfo.numberOfCard { changedCard.insert(cardIndex) } } } } func noteAddPhoto() { let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell cell.editingTextView?.resignFirstResponder() cell.extendTextView() showPhotoMenu() } } extension EditNoteViewController: TOCropViewControllerDelegate { func cropViewController(_ cropViewController: TOCropViewController, didCropToImage image: UIImage, rect cropRect: CGRect, angle: Int) { let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell let width = (cell.editingTextView?.bounds.width)! - CustomDistance.wideEdge * 2 - (cell.editingTextView?.textContainer.lineFragmentPadding)! * 2 let insertImage = UIImage.scaleImageToFitTextView(image, fit: width) if cell.editingTextView?.tag == OutletTag.titleTextView.rawValue { notes[currentCardIndex].title = updateTextView(notes[currentCardIndex].title , image: insertImage!) } else { notes[currentCardIndex].body = updateTextView(notes[currentCardIndex].body, image: insertImage!) } changedCard.insert(currentCardIndex) cropViewController.dismiss(animated: true) { [weak self] in cell.updateCell(with: (self?.notes[(self?.currentCardIndex)!])!, at: (self?.currentCardIndex)!, total: (self?.notes.count)!, cellStatus: cell.currentStatus!, noteType: NoteType(rawValue: (self?.passedInNoteInfo.type)!)!) } } private func updateTextView(_ text: NSAttributedString, image: UIImage) -> NSAttributedString { let cell = collectionView.cellForItem(at: IndexPath(item: currentCardIndex, section: 0)) as! EditNoteCollectionViewCell let font = cell.editingTextView?.font let imgTextAtta = NSTextAttachment() imgTextAtta.image = image var range: NSRange! = cell.editingTextView?.selectedRange if range.location == NSNotFound { range.location = (cell.editingTextView?.text.count)! } cell.editingTextView?.textStorage.insert(NSAttributedString.init(attachment: imgTextAtta), at: range.location) cell.editingTextView?.font = font cell.editingTextView?.selectedRange = NSRange(location: range.location + 1, length: 0) return (cell.editingTextView?.attributedText)! } } extension EditNoteViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func showPhotoMenu() { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) let takePhotoAction = UIAlertAction(title: "Take Photo", style: .default, handler: { _ in self.takePhotoWithCamera() }) alertController.addAction(takePhotoAction) let chooseFormLibraryAction = UIAlertAction(title: "Choose From Library", style: .default, handler: { _ in self.choosePhotoFromLibrary() }) alertController.addAction(chooseFormLibraryAction) present(alertController, animated: true, completion: nil) } func takePhotoWithCamera() { let oldStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) AVCaptureDevice.requestAccess(for: .video) { [weak self] isPermit in if isPermit { DispatchQueue.main.async { let imagePicker = UIImagePickerController() imagePicker.sourceType = .camera imagePicker.delegate = self imagePicker.allowsEditing = true self?.present(imagePicker, animated: true, completion: nil) } } else { if oldStatus == .notDetermined { return } DispatchQueue.main.async { self?.showAlert(title: "Alert!", message: "Please allow us to use your phone camera. You can set the permission at Setting -> Privacy -> Camera") } } } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as? UIImage let controller = TOCropViewController.init(image: image!) controller.delegate = self dismiss(animated: true, completion: { [weak self] in self?.present(controller, animated: true, completion: nil) }) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { passedInCardIndex = IndexPath(item: currentCardIndex, section: 0) let cell = collectionView.cellForItem(at: passedInCardIndex!) as! EditNoteCollectionViewCell passedInCardStatus = cell.currentStatus?.rawValue dismiss(animated: true, completion: nil) } func choosePhotoFromLibrary() { let oldStatus = PHPhotoLibrary.authorizationStatus() PHPhotoLibrary.requestAuthorization { [weak self] status in switch status { case .authorized: DispatchQueue.main.async { let controller = ImagePickerViewController.init(nibName: "ImagePickerViewController", bundle: nil) controller.noteController = self self?.present(controller, animated: true, completion: { let indexPath = IndexPath(item: (self?.currentCardIndex)!, section: 0) self?.passedInCardIndex = indexPath }) } case .denied: if oldStatus == .notDetermined { return } DispatchQueue.main.async { self?.showAlert(title: "Alert!", message: "Please allow us to access your photo library. You can set the permission at Setting -> Privacy -> Photos") } default: break } } } }
f4f9b6f840041447f12f7bd219992f83
44.500907
232
0.643213
false
false
false
false
kokoroe/kokoroe-sdk-ios
refs/heads/develop
KokoroeSDK/Entity/Category/KKRCategoryEntity.swift
mit
1
// // KKRCategoryEntity.swift // KokoroeSDK // // Created by Guillaume Mirambeau on 22/04/2016. // Copyright © 2016 I know u will. All rights reserved. // import Foundation import ObjectMapper /* class KKRCategoryResponse: Mappable { var categories: [KKRCategoryEntity]? required init?(_ map: Map){ } func mapping(map: Map) { categories <- map["three_day_forecast"] } } */ public class KKRCategoryEntity: Mappable { public var categoryID: Int = 0 public var parentID: Int? public var rootID: Int? public var left: Int = 0 public var right: Int = 0 public var level: Int = 0 public var nbCourses: Int? public var title: String? public var locale: String? public var media: String? public var slug: String? public var top = false public var children = [KKRCategoryEntity]?() required public init?(_ map: Map){ } public func mapping(map: Map) { self.categoryID <- map["id"] self.parentID <- map["parent_id"] self.rootID <- map["root"] self.left <- map["lft"] self.right <- map["rgt"] self.level <- map["lvl"] self.nbCourses <- map["nbcourses"] self.title <- map["display_title"] self.locale <- map["locale"] //self.media <- map["media"] self.media <- map["images.120x120"] self.slug <- map["slug"] self.top <- map["top"] self.children <- map["children"] } }
08597580613cc65781ebc26705dbfc8b
24.825397
56
0.542435
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Views/TextView/InteractableTextView/InteractableTextTableViewCell.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public final class InteractableTextTableViewCell: UITableViewCell { // MARK: - IBOutlets private var horizontalConstraints: UIView.Axis.Constraints! private var verticalConstraints: UIView.Axis.Constraints! private let instructionTextView = InteractableTextView() // MARK: - Injected public var contentInset = UIEdgeInsets() { didSet { horizontalConstraints.leading.constant = contentInset.left horizontalConstraints.trailing.constant = -contentInset.right verticalConstraints.leading.constant = contentInset.top verticalConstraints.trailing.constant = -contentInset.bottom contentView.layoutIfNeeded() } } public var viewModel: InteractableTextViewModel! { didSet { guard let viewModel = viewModel else { return } instructionTextView.viewModel = viewModel instructionTextView.setupHeight() } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none contentView.addSubview(instructionTextView) horizontalConstraints = instructionTextView.layoutToSuperview(axis: .horizontal) verticalConstraints = instructionTextView.layoutToSuperview(axis: .vertical) } @available(*, unavailable) public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func prepareForReuse() { super.prepareForReuse() viewModel = nil } }
90f757f44de80c1c12babfd871d128e8
33.2
88
0.693567
false
false
false
false
zapdroid/RXWeather
refs/heads/master
Pods/Alamofire/Source/Response.swift
mit
1
// // Response.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Used to store all data associated with an non-serialized response of a data or upload request. public struct DefaultDataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDataResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?, timeline: Timeline = Timeline(), metrics _: AnyObject? = nil) { self.request = request self.response = response self.data = data self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter data: The data returned by the server. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DataResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension DataResponse { /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result /// value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's /// result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - /// Used to store all data associated with an non-serialized response of a download request. public struct DefaultDownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDownloadResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - temporaryURL: The temporary destination URL of the data returned from the server. /// - destinationURL: The final destination URL of the data returned from the server if it was moved. /// - resumeData: The resume data generated if the request was cancelled. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, error: Error?, timeline: Timeline = Timeline(), metrics _: AnyObject? = nil) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DownloadResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serialization result and the /// timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension DownloadResponse { /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this /// instance's result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - protocol Response { /// The task metrics containing the request / response statistics. var _metrics: AnyObject? { get set } mutating func add(_ metrics: AnyObject?) } extension Response { mutating func add(_ metrics: AnyObject?) { #if !os(watchOS) guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } guard let metrics = metrics as? URLSessionTaskMetrics else { return } _metrics = metrics #endif } } // MARK: - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif }
55b3f49c4d665873fd63148b3a71570a
37.765727
119
0.656315
false
false
false
false
dogo/AKMediaViewer
refs/heads/develop
AKMediaViewerExample/AKMediaViewerExample/ViewController.swift
mit
1
// // ViewController.swift // AKMediaViewerExample // // Created by Diogo Autilio on 3/18/16. // Copyright © 2017 AnyKey Entertainment. All rights reserved. // import UIKit import AKMediaViewer class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AKMediaViewerDelegate { var statusBarHidden = false var mediaNames = ["1f.jpg", "2f.jpg", "3f.mp4", "4f.jpg"] var mediaFocusManager = AKMediaViewerManager() @IBOutlet weak var tableView: UITableView? override func viewDidLoad() { super.viewDidLoad() mediaFocusManager.delegate = self mediaFocusManager.elasticAnimation = true mediaFocusManager.focusOnPinch = true mediaFocusManager.infiniteLoop = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all } override open var prefersStatusBarHidden: Bool { return statusBarHidden } // MARK: - <AKMediaViewerDelegate> func parentViewControllerForMediaViewerManager(_ manager: AKMediaViewerManager) -> UIViewController { return self } func mediaViewerManager(_ manager: AKMediaViewerManager, mediaURLForView view: UIView) -> URL { let index: Int = view.tag - 1 let name = mediaNames[index] as NSString let url = Bundle.main.url(forResource: name.deletingPathExtension, withExtension: name.pathExtension)! return url } func mediaViewerManager(_ manager: AKMediaViewerManager, titleForView view: UIView) -> String { let url = mediaViewerManager(manager, mediaURLForView: view) let fileExtension = url.pathExtension.lowercased() let isVideo = fileExtension == "mp4" || fileExtension == "mov" return (isVideo ? "Videos are also supported." : "Of course, you can zoom in and out on the image.") } func mediaViewerManagerWillAppear(_ manager: AKMediaViewerManager) { /* * Call here setDefaultDoneButtonText, if you want to change the text and color of default "Done" button * eg: mediaFocusManager!.setDefaultDoneButtonText("Panda", withColor: UIColor.purple) */ statusBarHidden = true if self.responds(to: #selector(UIViewController.setNeedsStatusBarAppearanceUpdate)) { self.setNeedsStatusBarAppearanceUpdate() } } func mediaViewerManagerWillDisappear(_ mediaFocusManager: AKMediaViewerManager) { statusBarHidden = false if self.responds(to: #selector(UIViewController.setNeedsStatusBarAppearanceUpdate)) { self.setNeedsStatusBarAppearanceUpdate() } } // MARK: - <UITableViewDataSource> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "MediaCell", for: indexPath) as? MediaCell else { //The impossible happened fatalError("Wrong Cell Type") } cell.thumbnailView.image = UIImage(named: "\(indexPath.row + 1).jpg") cell.thumbnailView.tag = indexPath.row + 1 mediaFocusManager.installOnView(cell.thumbnailView) return cell } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mediaNames.count } }
e6eb4f00bb4c7e8674331c5660e08bbd
32.990385
120
0.689109
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPressKit/WordPressKit/AccountSettingsRemote.swift
gpl-2.0
1
import Foundation import WordPressShared import CocoaLumberjack public class AccountSettingsRemote: ServiceRemoteWordPressComREST { public static let remotes = NSMapTable<AnyObject, AnyObject>(keyOptions: NSPointerFunctions.Options(), valueOptions: NSPointerFunctions.Options.weakMemory) /// Returns an AccountSettingsRemote with the given api, reusing a previous /// remote if it exists. public static func remoteWithApi(_ api: WordPressComRestApi) -> AccountSettingsRemote { // We're hashing on the authToken because we don't want duplicate api // objects for the same account. // // In theory this would be taken care of by the fact that the api comes // from a WPAccount, and since WPAccount is a managed object Core Data // guarantees there's only one of it. // // However it might be possible that the account gets deallocated and // when it's fetched again it would create a different api object. // FIXME: not thread safe // @koke 2016-01-21 if let remote = remotes.object(forKey: api) as? AccountSettingsRemote { return remote } else { let remote = AccountSettingsRemote(wordPressComRestApi: api)! remotes.setObject(remote, forKey: api) return remote } } public func getSettings(success: @escaping (AccountSettings) -> Void, failure: @escaping (Error) -> Void) { let endpoint = "me/settings" let parameters = ["context": "edit"] let path = self.path(forEndpoint: endpoint, with: .version_1_1) wordPressComRestApi.GET(path!, parameters: parameters as [String : AnyObject]?, success: { responseObject, httpResponse in do { let settings = try self.settingsFromResponse(responseObject) success(settings) } catch { failure(error) } }, failure: { error, httpResponse in failure(error) }) } public func updateSetting(_ change: AccountSettingsChange, success: @escaping () -> Void, failure: @escaping (Error) -> Void) { let endpoint = "me/settings" let path = self.path(forEndpoint: endpoint, with: .version_1_1) let parameters = [fieldNameForChange(change): change.stringValue] wordPressComRestApi.POST(path!, parameters: parameters as [String : AnyObject]?, success: { responseObject, httpResponse in success() }, failure: { error, httpResponse in failure(error) }) } fileprivate func settingsFromResponse(_ responseObject: AnyObject) throws -> AccountSettings { guard let response = responseObject as? [String: AnyObject], let firstName = response["first_name"] as? String, let lastName = response["last_name"] as? String, let displayName = response["display_name"] as? String, let aboutMe = response["description"] as? String, let username = response["user_login"] as? String, let email = response["user_email"] as? String, let emailPendingAddress = response["new_user_email"] as? String?, let emailPendingChange = response["user_email_change_pending"] as? Bool, let primarySiteID = response["primary_site_ID"] as? Int, let webAddress = response["user_URL"] as? String, let language = response["language"] as? String else { DDLogError("Error decoding me/settings response: \(responseObject)") throw ResponseError.decodingFailure } let aboutMeText = aboutMe.decodingXMLCharacters() return AccountSettings(firstName: firstName, lastName: lastName, displayName: displayName, aboutMe: aboutMeText!, username: username, email: email, emailPendingAddress: emailPendingAddress, emailPendingChange: emailPendingChange, primarySiteID: primarySiteID, webAddress: webAddress, language: language) } fileprivate func fieldNameForChange(_ change: AccountSettingsChange) -> String { switch change { case .firstName: return "first_name" case .lastName: return "last_name" case .displayName: return "display_name" case .aboutMe: return "description" case .email: return "user_email" case .emailRevertPendingChange: return "user_email_change_pending" case .primarySite: return "primary_site_ID" case .webAddress: return "user_URL" case .language: return "language" } } enum ResponseError: Error { case decodingFailure } }
5512bf78756cb409279a74c7e44733a4
39.899225
159
0.573541
false
false
false
false
dnevera/ImageMetalling
refs/heads/master
ImageMetalling-12/ImageMetalling-12/Classes/IMPDocument.swift
mit
2
// // IMPDocument.swift // ImageMetalling-07 // // Created by denis svinarchuk on 15.12.15. // Copyright © 2015 IMetalling. All rights reserved. // import Cocoa import IMProcessing public enum IMPDocumentType{ case Image } public typealias IMPDocumentObserver = ((file:String, type:IMPDocumentType) -> Void) public class IMPDocument: NSObject { private override init() {} private var didUpdateDocumnetHandlers = [IMPDocumentObserver]() private var didSaveDocumnetHandlers = [IMPDocumentObserver]() static let sharedInstance = IMPDocument() var currentFile:String?{ didSet{ guard let path = currentFile else { return } NSApplication.sharedApplication().keyWindow?.title = self.currentFile! let code = access(path, R_OK) if code < 0 { let error = NSError( domain: "com.dehancer.DehancerEAPOSX", code: Int(code), userInfo: [ NSLocalizedDescriptionKey: String(format: NSLocalizedString("File %@ could not be opened", comment:""), path), NSLocalizedFailureReasonErrorKey: String(format: NSLocalizedString("File open error", comment:"")) ]) let alert = NSAlert(error: error) alert.runModal() removeOpenRecentFileMenuItem(path) return } addOpenRecentFileMenuItem(currentFile!) for o in self.didUpdateDocumnetHandlers{ o(file: currentFile!, type: .Image) } } } func addDocumentObserver(observer:IMPDocumentObserver){ didUpdateDocumnetHandlers.append(observer) } func addSavingObserver(observer:IMPDocumentObserver){ didSaveDocumnetHandlers.append(observer) } private let openRecentKey = "imageMetalling-open-recent" private var openRecentMenuItems = Dictionary<String,NSMenuItem>() public weak var openRecentMenu: NSMenu! { didSet{ if let list = openRecentList { if list.count>0{ for file in list.reverse() { addOpenRecentMenuItemMenu(file) } IMPDocument.sharedInstance.currentFile = list[0] } } } } public func clearRecent(){ if let list = openRecentList { for file in list { removeOpenRecentFileMenuItem(file) } } } public func openRecentListAdd(urls:[NSURL]){ for url in urls{ if let file = url.path{ self.addOpenRecentFileMenuItem(file) } } } private func addOpenRecentMenuItemMenu(file:String){ if let menu = openRecentMenu { let menuItem = menu.insertItemWithTitle(file, action: Selector("openRecentHandler:"), keyEquivalent: "", atIndex: 0) openRecentMenuItems[file]=menuItem } } private func openFilePath(filePath: String){ currentFile = filePath } private var openRecentList:[String]?{ get { return NSUserDefaults.standardUserDefaults().objectForKey(openRecentKey) as? [String] } } private func addOpenRecentFileMenuItem(file:String){ var list = removeOpenRecentFileMenuItem(file) list.insert(file, atIndex: 0) if list.count > 10 { for i in list[10..<list.count]{ if let menuItem = openRecentMenuItems[i] { openRecentMenu.removeItem(menuItem) } } list.removeRange(10..<list.count) } NSUserDefaults.standardUserDefaults().setObject(list, forKey: openRecentKey) NSUserDefaults.standardUserDefaults().synchronize() addOpenRecentMenuItemMenu(file) } private func removeOpenRecentFileMenuItem(file:String) -> [String] { var list = openRecentList ?? [String]() if let index = list.indexOf(file){ list.removeAtIndex(index) if let menuItem = openRecentMenuItems[file] { openRecentMenu.removeItem(menuItem) } } NSUserDefaults.standardUserDefaults().setObject(list, forKey: openRecentKey) NSUserDefaults.standardUserDefaults().synchronize() return list } public func openFilePanel(types:[String]){ let openPanel = NSOpenPanel() openPanel.canChooseFiles = true; openPanel.resolvesAliases = true; openPanel.extensionHidden = false; openPanel.allowedFileTypes = types let result = openPanel.runModal() if result == NSModalResponseOK { IMPDocument.sharedInstance.currentFile = openPanel.URLs[0].path } } var savingQueue:dispatch_queue_t = dispatch_queue_create("com.dehancer.saving", DISPATCH_QUEUE_SERIAL) public func saveCurrent(filename:String){ dispatch_async(savingQueue, { () -> Void in for o in self.didSaveDocumnetHandlers { o(file: filename, type: .Image) } }) } }
eeab0f9938a813d87c1628d46d3db08c
28.918033
130
0.569498
false
false
false
false
ovenbits/Alexandria
refs/heads/master
Sources/ImageEffects/UIImage+Effects.swift
mit
1
/* File: UIImage+ImageEffects.m Abstract: This is a category of UIImage that adds methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013 Apple Inc. All Rights Reserved. Copyright © 2013 Apple Inc. All rights reserved. WWDC 2013 License NOTE: This Apple Software was supplied by Apple as part of a WWDC 2013 Session. Please refer to the applicable WWDC 2013 Session for further information. IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EA1002 5/3/2013 */ // // UIImage.swift // Today // // Created by Alexey Globchastyy on 15/09/14. // Copyright (c) 2014 Alexey Globchastyy. All rights reserved. // import UIKit import Accelerate public extension UIImage { /** Applies a lightening (blur) effect to the image - returns: The lightened image, or nil if error. */ public func applyLightEffect() -> UIImage? { return applyBlur(withRadius: 30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.0) } /** Applies an extra lightening (blur) effect to the image - returns: The extra lightened image, or nil if error. */ public func applyExtraLightEffect() -> UIImage? { return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8) } /** Applies a darkening (blur) effect to the image. - returns: The darkened image, or nil if error. */ public func applyDarkEffect() -> UIImage? { return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8) } /** Tints the image with the given color. - parameter tintColor: The tint color - returns: The tinted image, or nil if error. */ public func applyTintEffect(withColor tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = tintColor.cgColor.numberOfComponents if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) { effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha) } } return applyBlur(withRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil) } /** Core function to create a new image with the given blur. - parameter blurRadius: The blur radius - parameter tintColor: The color to tint the image; optional. - parameter saturationDeltaFactor: The delta by which to change the image saturation - parameter maskImage: An optional image mask. - returns: The adjusted image, or nil if error. */ public func applyBlur(withRadius blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { // Check pre-conditions. guard size.width >= 1 && size.height >= 1 else { print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") return nil } guard let cgImage = self.cgImage else { print("*** error: image must be backed by a CGImage: \(self)") return nil } if maskImage != nil && maskImage!.cgImage == nil { print("*** error: maskImage must be backed by a CGImage: \(maskImage)") return nil } defer { UIGraphicsEndImageContext() } let epsilon = CGFloat(FLT_EPSILON) let screenScale = UIScreen.main.scale let imageRect = CGRect(origin: .zero, size: size) var effectImage: UIImage? = self let hasBlur = blurRadius > epsilon let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > epsilon if hasBlur || hasSaturationChange { func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { let data = context.data let width = context.width let height = context.height let rowBytes = context.bytesPerRow return vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: rowBytes) } UIGraphicsBeginImageContextWithOptions(size, false, screenScale) guard let effectInContext = UIGraphicsGetCurrentContext() else { return self } effectInContext.scaleBy(x: 1, y: -1) effectInContext.translateBy(x: 0, y: -size.height) effectInContext.draw(cgImage, in: imageRect) var effectInBuffer = createEffectBuffer(effectInContext) UIGraphicsBeginImageContextWithOptions(size, false, screenScale) guard let effectOutContext = UIGraphicsGetCurrentContext() else { return self } var effectOutBuffer = createEffectBuffer(effectOutContext) if hasBlur { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // let inputRadius = blurRadius * screenScale let input = inputRadius * 3 * sqrt(2 * .pi) / 4 + 0.5 var radius = UInt32(floor(input)) if radius % 2 != 1 { radius += 1 // force radius to be odd so that the three box-blur methodology works. } let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) } var effectImageBuffersAreSwapped = false if hasSaturationChange { let s: CGFloat = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1 ] let divisor: CGFloat = 256 let saturationMatrix = floatingPointSaturationMatrix.map { Int16(round($0) * divisor) } if hasBlur { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) effectImageBuffersAreSwapped = true } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) } } if !effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() if effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() } // Set up output context. UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let outputContext = UIGraphicsGetCurrentContext() outputContext?.scaleBy(x: 1, y: -1) outputContext?.translateBy(x: 0, y: -size.height) // Draw base image. outputContext?.draw(cgImage, in: imageRect) // Draw effect image. if let effectImage = effectImage?.cgImage, hasBlur { outputContext?.saveGState() if let image = maskImage?.cgImage { outputContext?.clip(to: imageRect, mask: image) } outputContext?.draw(effectImage, in: imageRect) outputContext?.restoreGState() } // Add in color tint. if let color = tintColor { outputContext?.saveGState() outputContext?.setFillColor(color.cgColor) outputContext?.fill(imageRect) outputContext?.restoreGState() } // Output image is ready. return UIGraphicsGetImageFromCurrentImageContext() } }
9ba864d19c6f865635484b4d21be4eff
43.398773
205
0.647575
false
false
false
false
cuappdev/tcat-ios
refs/heads/master
TCAT/Cells/RouteTableViewCell.swift
mit
1
// // RouteTableViewCell.swift // TCAT // // Created by Monica Ong on 2/13/17. // Copyright © 2017 cuappdev. All rights reserved. // import FutureNova import SwiftyJSON import UIKit class RouteTableViewCell: UITableViewCell { // MARK: - View vars private let arrowImageView = UIImageView(image: #imageLiteral(resourceName: "side-arrow")) private let containerView = UIView() private var departureStackView: UIStackView! private let departureTimeLabel = UILabel() private let liveContainerView = UIView() private let liveIndicatorView = LiveIndicator(size: .small, color: .clear) private let liveLabel = UILabel() private var routeDiagram: RouteDiagram! private let travelTimeLabel = UILabel() // MARK: - Data vars private let containerViewLayoutInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 12) private let networking: Networking = URLSession.shared.request // MARK: - Init override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(containerView) setupCellBackground() setupDepartureStackView() setupTravelTimeLabel() setupLiveContainerView() setupConstraints() } // MARK: - Style private func setupCellBackground() { let cornerRadius: CGFloat = 16 layer.backgroundColor = UIColor.clear.cgColor contentView.backgroundColor = .clear backgroundColor = .clear containerView.backgroundColor = Colors.white containerView.layer.cornerRadius = cornerRadius containerView.layer.masksToBounds = true } private func setupDepartureStackView() { let spaceBtnDepartureElements: CGFloat = 4 departureStackView = UIStackView(arrangedSubviews: [departureTimeLabel, arrowImageView]) departureStackView.axis = .horizontal departureStackView.spacing = spaceBtnDepartureElements departureStackView.alignment = .center departureTimeLabel.font = .getFont(.semibold, size: 14) departureTimeLabel.textColor = Colors.primaryText arrowImageView.tintColor = Colors.metadataIcon containerView.addSubview(departureStackView) } private func setupTravelTimeLabel() { travelTimeLabel.font = .getFont(.semibold, size: 16) travelTimeLabel.textColor = Colors.primaryText containerView.addSubview(travelTimeLabel) } private func setupLiveContainerView() { liveLabel.font = .getFont(.semibold, size: 14) liveContainerView.addSubview(liveLabel) liveContainerView.addSubview(liveIndicatorView) setLiveIndicatorViewsConstraints() containerView.addSubview(liveContainerView) } private func setupConstraints() { let arrowImageViewSize = CGSize(width: 6, height: 11.5) let cellMargin: CGFloat = 12 containerView.snp.makeConstraints { make in make.leading.bottom.trailing.equalToSuperview().inset(cellMargin) make.top.equalToSuperview() } arrowImageView.snp.makeConstraints { make in make.size.equalTo(arrowImageViewSize) } travelTimeLabel.snp.makeConstraints { make in make.leading.top.equalToSuperview().inset(containerViewLayoutInsets) } departureStackView.snp.makeConstraints { make in make.trailing.top.equalToSuperview().inset(containerViewLayoutInsets) } liveContainerView.snp.makeConstraints { make in make.top.equalTo(travelTimeLabel.snp.bottom) make.leading.equalTo(travelTimeLabel) make.trailing.equalTo(departureStackView) } } private func setLiveIndicatorViewsConstraints() { let spaceBtnLiveElements: CGFloat = 4 liveLabel.snp.remakeConstraints { make in make.leading.top.equalToSuperview() make.bottom.equalToSuperview() } liveIndicatorView.snp.remakeConstraints { make in make.leading.equalTo(liveLabel.snp.trailing).offset(spaceBtnLiveElements) make.centerY.equalTo(liveLabel) } } private func setupDataDependentConstraints() { let routeDiagramTopOffset = 8 liveContainerView.snp.makeConstraints { make in make.bottom.equalTo(routeDiagram.snp.top).offset(-routeDiagramTopOffset) } // Set trailing and bottom prioirites to .high to surpress constraint errors routeDiagram.snp.remakeConstraints { make in make.top.equalTo(liveContainerView.snp.bottom).offset(routeDiagramTopOffset) make.leading.equalTo(travelTimeLabel) make.trailing.equalTo(departureStackView).priority(.high) make.bottom.equalToSuperview().inset(containerViewLayoutInsets).priority(.high) } } // MARK: - Set Data func configure(for route: Route, delayState: DelayState? = nil) { setTravelTime(withDepartureTime: route.departureTime, withArrivalTime: route.arrivalTime) setDepartureTimeAndLiveElements(withRoute: route) if let delay = delayState { setLiveElements(withDelayState: delay) setDepartureTime(withStartTime: Date(), withDelayState: delay) } routeDiagram = RouteDiagram(withDirections: route.rawDirections, withTravelDistance: route.travelDistance, withWalkingRoute: route.isRawWalkingRoute()) containerView.addSubview(routeDiagram) setupDataDependentConstraints() } // MARK: - Get Data private func getDelayState(fromRoute route: Route) -> DelayState { if let firstDepartDirection = route.getFirstDepartRawDirection() { let departTime = firstDepartDirection.startTime if let delay = firstDepartDirection.delay { let delayedDepartTime = departTime.addingTimeInterval(TimeInterval(delay)) // Our live tracking only updates once every 30 seconds, so we want to show // buses that are delayed by < 120 as on time in order to be more accurate // about the status of slightly delayed buses. This way riders get to a bus // stop earlier rather than later when trying to catch such buses. if Time.compare(date1: departTime, date2: delayedDepartTime) == .orderedAscending { // bus is delayed if delayedDepartTime >= Date() || delay >= 120 { return .late(date: delayedDepartTime) } else { // delay < 120 return .onTime(date: departTime) } } else { // bus is not delayed return .onTime(date: departTime) } } else { return .noDelay(date: departTime) } } return .noDelay(date: route.departureTime) } private func setDepartureTimeAndLiveElements(withRoute route: Route) { let isWalkingRoute = route.isRawWalkingRoute() if isWalkingRoute { setDepartureTimeToWalking() return } let delayState = getDelayState(fromRoute: route) setDepartureTime(withStartTime: Date(), withDelayState: delayState) setLiveElements(withDelayState: delayState) } private func setLiveElements(withDelayState delayState: DelayState) { switch delayState { case .late(date: let delayedDepartureTime): liveLabel.textColor = Colors.lateRed liveLabel.text = "Late - \(Time.timeString(from: delayedDepartureTime))" liveIndicatorView.setColor(to: Colors.lateRed) liveContainerView.addSubview(liveIndicatorView) liveContainerView.addSubview(liveLabel) setLiveIndicatorViewsConstraints() case .onTime(date: _): liveLabel.textColor = Colors.liveGreen liveLabel.text = "On Time" liveIndicatorView.setColor(to: Colors.liveGreen) liveContainerView.addSubview(liveIndicatorView) liveContainerView.addSubview(liveLabel) setLiveIndicatorViewsConstraints() case .noDelay(date: _): liveLabel.removeFromSuperview() liveIndicatorView.removeFromSuperview() } } private func setDepartureTime(withStartTime startTime: Date, withDelayState delayState: DelayState) { switch delayState { case .late(date: let departureTime): let boardTime = Time.timeString(from: startTime, to: departureTime) departureTimeLabel.text = boardTime == "0 min" ? "Board now" : "Board in \(boardTime)" departureTimeLabel.textColor = Colors.lateRed case .onTime(date: let departureTime): let boardTime = Time.timeString(from: startTime, to: departureTime) departureTimeLabel.text = boardTime == "0 min" ? "Board now" : "Board in \(boardTime)" departureTimeLabel.textColor = Colors.liveGreen case .noDelay(date: let departureTime): let boardTime = Time.timeString(from: startTime, to: departureTime) departureTimeLabel.text = boardTime == "0 min" ? "Board now" : "Board in \(boardTime)" departureTimeLabel.textColor = Colors.primaryText } arrowImageView.tintColor = Colors.primaryText } private func setTravelTime(withDepartureTime departureTime: Date, withArrivalTime arrivalTime: Date) { travelTimeLabel.text = "\(Time.timeString(from: departureTime)) - \(Time.timeString(from: arrivalTime))" } private func setDepartureTimeToWalking() { departureTimeLabel.text = "Directions" departureTimeLabel.textColor = Colors.metadataIcon arrowImageView.tintColor = Colors.metadataIcon } // MARK: - Reuse override func prepareForReuse() { routeDiagram.removeFromSuperview() liveLabel.removeFromSuperview() liveIndicatorView.removeFromSuperview() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
8b329ceaaec1288f08903ffbcf815e66
34.982456
159
0.665724
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/AutoLayoutCookbook/DynamicHeightColumns.swift
mit
1
// // SimpleLabelAndTextField.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/10/22. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit class DynamicHeightColumns: AutoLayoutBaseController { private var labels: [UILabel] = [] override func initSubviews() { let firstLabel = generatLabel(with: "First Name") labels.append(firstLabel) view.addSubview(firstLabel) firstLabel.topAnchor.constraint(greaterThanOrEqualTo: topLayoutGuide.bottomAnchor, constant: 20).isActive = true firstLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true let firstLabelTopCostraint = firstLabel.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 20) firstLabelTopCostraint.priority = UILayoutPriority(rawValue: 249) firstLabelTopCostraint.isActive = true let firstField = generatField(with: "Enter First Name") view.addSubview(firstField) firstField.topAnchor.constraint(greaterThanOrEqualTo: topLayoutGuide.bottomAnchor, constant: 20).isActive = true let firstFieldTopCostraint = firstField.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 20) firstFieldTopCostraint.priority = UILayoutPriority(rawValue: 249) firstFieldTopCostraint.isActive = true firstField.lastBaselineAnchor.constraint(equalTo: firstLabel.lastBaselineAnchor).isActive = true firstField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true firstField.leadingAnchor.constraint(equalTo: firstLabel.trailingAnchor, constant: 8).isActive = true let middleLabel = generatLabel(with: "Middle Name") labels.append(middleLabel) view.addSubview(middleLabel) middleLabel.leadingAnchor.constraint(equalTo: firstLabel.leadingAnchor).isActive = true middleLabel.topAnchor.constraint(greaterThanOrEqualTo: firstLabel.bottomAnchor).isActive = true let middleLabelTopCostraint = middleLabel.topAnchor.constraint(equalTo: firstLabel.bottomAnchor) middleLabelTopCostraint.priority = UILayoutPriority(rawValue: 249) middleLabelTopCostraint.isActive = true let middleField = generatField(with: "Enter Middle Name") view.addSubview(middleField) middleField.leadingAnchor.constraint(equalTo: middleLabel.trailingAnchor, constant: 8).isActive = true middleField.lastBaselineAnchor.constraint(equalTo: middleLabel.lastBaselineAnchor).isActive = true middleField.trailingAnchor.constraint(equalTo: firstField.trailingAnchor).isActive = true middleField.widthAnchor.constraint(equalTo: firstField.widthAnchor).isActive = true middleField.topAnchor.constraint(greaterThanOrEqualTo: firstField.bottomAnchor, constant: 8).isActive = true let middleFieldTopCostraint = middleField.topAnchor.constraint(equalTo: firstField.bottomAnchor) middleFieldTopCostraint.priority = UILayoutPriority(rawValue: 245) middleFieldTopCostraint.isActive = true let lastLabel = generatLabel(with: "Last Name") labels.append(lastLabel) view.addSubview(lastLabel) lastLabel.leadingAnchor.constraint(equalTo: firstLabel.leadingAnchor).isActive = true lastLabel.topAnchor.constraint(greaterThanOrEqualTo: middleLabel.bottomAnchor).isActive = true let lastLabelTopCostraint = lastLabel.topAnchor.constraint(equalTo: middleLabel.bottomAnchor) lastLabelTopCostraint.priority = UILayoutPriority(rawValue: 249) lastLabelTopCostraint.isActive = true let lastField = generatField(with: "Enter Last Name") view.addSubview(lastField) lastField.trailingAnchor.constraint(equalTo: firstField.trailingAnchor).isActive = true lastField.widthAnchor.constraint(equalTo: firstField.widthAnchor).isActive = true lastField.leadingAnchor.constraint(equalTo: lastLabel.trailingAnchor, constant: 8).isActive = true lastField.lastBaselineAnchor.constraint(equalTo: lastLabel.lastBaselineAnchor).isActive = true lastField.topAnchor.constraint(greaterThanOrEqualTo: middleField.bottomAnchor, constant: 8).isActive = true let lastFieldTopCostraint = lastField.topAnchor.constraint(equalTo: middleField.bottomAnchor) lastFieldTopCostraint.priority = UILayoutPriority(rawValue: 245) lastFieldTopCostraint.isActive = true } private func generatLabel(with title: String) -> UILabel { let titleLabel = UILabel() titleLabel.text = title titleLabel.font = UIFont.preferredFont(forTextStyle: .headline) titleLabel.setContentHuggingPriority(UILayoutPriority(251), for: .vertical) titleLabel.setContentHuggingPriority(UILayoutPriority(251), for: .horizontal) titleLabel.translatesAutoresizingMaskIntoConstraints = false return titleLabel } private func generatField(with placeholder: String) -> UITextField { let field = UITextField() field.borderStyle = .roundedRect field.placeholder = placeholder field.translatesAutoresizingMaskIntoConstraints = false return field } var usingLargeFont = false var timer: Timer? // MARK: UIViewController override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(changeFontSizeTimerDidFire), userInfo: nil, repeats: true) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) timer?.invalidate() timer = nil } // MARK: Timer @objc func changeFontSizeTimerDidFire(_ timer: Timer) { // Toggle the font preference. usingLargeFont = !usingLargeFont // Determine which font should now be used. let font = UIFont.systemFont(ofSize: usingLargeFont ? 36.0 : 17.0) for label in labels { label.font = font } } }
a22497eb1e3d330eaec310f174d19a9e
43.722628
148
0.728578
false
false
false
false
adams0619/AngelHacks8-App
refs/heads/master
AngelHacksCaitlyn/AngelHacksCaitlyn/Helpers/RestApiManager.swift
mit
1
// // RestApiManager.swift // AngelHacksCaitlyn // // Created by Adams Ombonga on 7/18/15. // Copyright (c) 2015 Caitlyn Chen. All rights reserved. // import UIKit import Foundation import Alamofire import SwiftyJSON typealias ServiceResponse = (JSON, NSError?) -> Void class RestApiManager: NSObject { static let sharedInstance = RestApiManager() let baseURL = "" //let json = JSON(data: dataFromNetworking) func getRandomUser(onCompletion: (JSON) -> Void) { let route = baseURL makeHTTPGetRequest(route, onCompletion: { json, err in onCompletion(json as JSON) }) } func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) { let request = NSMutableURLRequest(URL: NSURL(string: path)!) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in let json:JSON = JSON(data: data) onCompletion(json, error) }) task.resume() } }
d7d4a63805497f6a1b4308d452bf3d8f
25.119048
108
0.641423
false
false
false
false
jaouahbi/OMCircularProgress
refs/heads/master
Example/Example/OMShadingGradientLayer/Classes/Categories/UIColor+Interpolation.swift
apache-2.0
4
// // Copyright 2015 - Jorge Ouahbi // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // // // UIColor+Interpolation.swift // // Created by Jorge Ouahbi on 27/4/16. // Copyright © 2016 Jorge Ouahbi. All rights reserved. // import UIKit extension UIColor { // RGBA /// Linear interpolation /// /// - Parameters: /// - start: start UIColor /// - end: start UIColor /// - t: alpha /// - Returns: return UIColor public class func lerp(_ start:UIColor, end:UIColor, t:CGFloat) -> UIColor { let srgba = start.components let ergba = end.components return UIColor(red: Interpolation.lerp(srgba[0],y1: ergba[0],t: t), green: Interpolation.lerp(srgba[1],y1: ergba[1],t: t), blue: Interpolation.lerp(srgba[2],y1: ergba[2],t: t), alpha: Interpolation.lerp(srgba[3],y1: ergba[3],t: t)) } /// Cosine interpolate /// /// - Parameters: /// - start: start UIColor /// - end: start UIColor /// - t: alpha /// - Returns: return UIColor public class func coserp(_ start:UIColor, end:UIColor, t:CGFloat) -> UIColor { let srgba = start.components let ergba = end.components return UIColor(red: Interpolation.coserp(srgba[0],y1: ergba[0],t: t), green: Interpolation.coserp(srgba[1],y1: ergba[1],t: t), blue: Interpolation.coserp(srgba[2],y1: ergba[2],t: t), alpha: Interpolation.coserp(srgba[3],y1: ergba[3],t: t)) } /// Exponential interpolation /// /// - Parameters: /// - start: start UIColor /// - end: start UIColor /// - t: alpha /// - Returns: return UIColor public class func eerp(_ start:UIColor, end:UIColor, t:CGFloat) -> UIColor { let srgba = start.components let ergba = end.components let r = clamp(Interpolation.eerp(srgba[0],y1: ergba[0],t: t), lowerValue: 0,upperValue: 1) let g = clamp(Interpolation.eerp(srgba[1],y1: ergba[1],t: t),lowerValue: 0, upperValue: 1) let b = clamp(Interpolation.eerp(srgba[2],y1: ergba[2],t: t), lowerValue: 0, upperValue: 1) let a = clamp(Interpolation.eerp(srgba[3],y1: ergba[3],t: t), lowerValue: 0,upperValue: 1) assert(r <= 1.0 && g <= 1.0 && b <= 1.0 && a <= 1.0); return UIColor(red: r, green: g, blue: b, alpha: a) } /// Bilinear interpolation /// /// - Parameters: /// - start: start UIColor /// - end: start UIColor /// - t: alpha /// - Returns: return UIColor public class func bilerp(_ start:[UIColor], end:[UIColor], t:[CGFloat]) -> UIColor { let srgba0 = start[0].components let ergba0 = end[0].components let srgba1 = start[1].components let ergba1 = end[1].components return UIColor(red: Interpolation.bilerp(srgba0[0], y1: ergba0[0], t1: t[0], y2: srgba1[0], y3: ergba1[0], t2: t[1]), green: Interpolation.bilerp(srgba0[1], y1: ergba0[1], t1: t[0], y2: srgba1[1], y3: ergba1[1], t2: t[1]), blue: Interpolation.bilerp(srgba0[2], y1: ergba0[2], t1: t[0], y2: srgba1[2], y3: ergba1[2], t2: t[1]), alpha: Interpolation.bilerp(srgba0[3], y1: ergba0[3], t1: t[0], y2: srgba1[3], y3: ergba1[3], t2: t[1])) } }
76c4c188add77757800dc548673e217e
34.102564
128
0.556854
false
false
false
false
hanhailong/practice-swift
refs/heads/master
Views/ActivityViewController/ActivityViewController Example/ActivityViewController Example/ViewController.swift
mit
2
// // ViewController.swift // ActivityViewController Example // // Created by Domenico Solazzo on 05/05/15. // License MIT // import UIKit class ViewController: UIViewController, UITextFieldDelegate { var textField: UITextField! var buttonShare: UIButton! override func viewDidLoad() { super.viewDidLoad() self.createTextField() self.createButton() } func createTextField(){ textField = UITextField(frame: CGRect(x: 20, y: 35, width: 280, height: 30)) textField.borderStyle = .RoundedRect textField.placeholder = "Enter the text to share..." textField.delegate = self self.view.addSubview(textField) } func createButton(){ buttonShare = UIButton.buttonWithType(UIButtonType.System) as? UIButton buttonShare.frame = CGRect(x: 20, y: 80, width: 280, height: 44) buttonShare.setTitle("Share", forState: UIControlState.Normal) buttonShare.addTarget(self, action: "handleShare:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(buttonShare) } //- MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } //- MARK: UIButton func handleShare(sender: UIButton){ if (textField.text.isEmpty){ var message = "Please enter a text and then click Share" var alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction( UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) ) presentViewController(alert, animated: true, completion: nil) return } /* it is VERY important to cast your strings to NSString otherwise the controller cannot display the appropriate sharing options */ var activityController = UIActivityViewController( activityItems: [textField.text as NSString], applicationActivities: nil ) presentViewController(activityController, animated: true, completion: nil ) } }
2cc1f8719c20ea00f72badede2b1ea0a
29.884615
79
0.607306
false
false
false
false
OscarSwanros/swift
refs/heads/master
benchmark/single-source/ArrayOfGenericPOD.swift
apache-2.0
3
//===--- ArrayOfGenericPOD.swift ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This benchmark tests creation and destruction of arrays of enum and // generic type bound to trivial types. It should take the same time as // ArrayOfPOD. (In practice, it takes a little longer to construct // the optional arrays). // // For comparison, we always create three arrays of 200,000 words. // An integer enum takes two words. import TestsUtils public let ArrayOfGenericPOD = BenchmarkInfo( name: "ArrayOfGenericPOD", runFunction: run_ArrayOfGenericPOD, tags: [.validation, .api, .Array]) class RefArray<T> { var array: [T] init(_ i:T) { array = [T](repeating: i, count: 100000) } } // Check the performance of destroying an array of enums (optional) where the // enum has a single payload of trivial type. Destroying the // elements should be a nop. @inline(never) func genEnumArray() { _ = RefArray<Int?>(3) // should be a nop } // Check the performance of destroying an array of implicit unwrapped // optional where the optional has a single payload of trivial // type. Destroying the elements should be a nop. @inline(never) func genIOUArray() { _ = RefArray<Int!>(3) // should be a nop } // Check the performance of destroying an array of structs where the // struct has multiple fields of trivial type. Destroying the // elements should be a nop. struct S<T> { var x: T var y: T } @inline(never) func genStructArray() { _ = RefArray<S<Int>>(S(x:3, y:4)) // should be a nop } @inline(never) public func run_ArrayOfGenericPOD(_ N: Int) { for _ in 0...N { genEnumArray() genIOUArray() genStructArray() } }
43a265e98b4142870157a98399cee5f3
27.378378
80
0.662857
false
false
false
false
IngmarStein/swift
refs/heads/master
test/decl/ext/generic.swift
apache-2.0
2
// RUN: %target-parse-verify-swift protocol P1 { associatedtype AssocType } protocol P2 : P1 { } protocol P3 { } struct X<T : P1, U : P2, V> { struct Inner<A, B : P3> { } // expected-error{{generic type 'Inner' cannot be nested in type 'X'}} struct NonGenericInner { } // expected-error{{nested in generic type}} } extension Int : P1 { typealias AssocType = Int } extension Double : P2 { typealias AssocType = Double } extension X<Int, Double, String> { } // expected-error{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}} // Lvalue check when the archetypes are not the same. struct LValueCheck<T> { let x = 0 } extension LValueCheck { init(newY: Int) { x = 42 } } // Member type references into another extension. struct MemberTypeCheckA<T> { } protocol MemberTypeProto { associatedtype AssocType func foo(_ a: AssocType) init(_ assoc: MemberTypeCheckA<AssocType>) } struct MemberTypeCheckB<T> : MemberTypeProto { func foo(_ a: T) {} typealias Element = T var t1: T } extension MemberTypeCheckB { typealias Underlying = MemberTypeCheckA<T> } extension MemberTypeCheckB { init(_ x: Underlying) { } } extension MemberTypeCheckB { var t2: Element { return t1 } } // rdar://problem/19795284 extension Array { var pairs: [(Element, Element)] { get { return [] } } } // rdar://problem/21001937 struct GenericOverloads<T, U> { var t: T var u: U init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 0 } subscript (i: Int) -> Int { return i } } extension GenericOverloads where T : P1, U : P2 { init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 1 } subscript (i: Int) -> Int { return i } } extension Array where Element : Hashable { var worseHashEver: Int { var result = 0 for elt in self { result = (result << 1) ^ elt.hashValue } return result } } func notHashableArray<T>(_ x: [T]) { x.worseHashEver // expected-error{{type 'T' does not conform to protocol 'Hashable'}} } func hashableArray<T : Hashable>(_ x: [T]) { // expected-warning @+1 {{unused}} x.worseHashEver // okay } func intArray(_ x: [Int]) { // expected-warning @+1 {{unused}} x.worseHashEver } class GenericClass<T> { } extension GenericClass where T : Equatable { func foo(_ x: T, y: T) -> Bool { return x == y } } func genericClassEquatable<T : Equatable>(_ gc: GenericClass<T>, x: T, y: T) { _ = gc.foo(x, y: y) } func genericClassNotEquatable<T>(_ gc: GenericClass<T>, x: T, y: T) { gc.foo(x, y: y) // expected-error{{type 'T' does not conform to protocol 'Equatable'}} } // FIXME: Future direction extension Array where Element == String { } // expected-error{{same-type requirement makes generic parameter 'Element' non-generic}} extension GenericClass : P3 where T : P3 { } // expected-error{{extension of type 'GenericClass' with constraints cannot have an inheritance clause}} extension GenericClass where Self : P3 { } // expected-error@-1{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'GenericClass'?}} {{30-34=GenericClass}} // expected-error@-2{{type 'GenericClass' in conformance requirement does not refer to a generic parameter or associated type}} protocol P4 { associatedtype T init(_: T) } protocol P5 { } struct S4<Q>: P4 { init(_: Q) { } } extension S4 where T : P5 {} // expected-FIXME-error{{type 'T' in conformance requirement does not refer to a generic parameter or associated type}}
94df817b70ff311d3af81dc52a4924ef
22.393548
181
0.663265
false
false
false
false
lforme/VisualArts
refs/heads/master
VisualArts/NetworkingLayer/ServerConfiguration.swift
mit
1
// // ServerConfiguration.swift // VisualArts // // Created by 木瓜 on 2017/6/22. // Copyright © 2017年 WHY. All rights reserved. // import Foundation struct Server { // eg: http https let scheme: String // eg: www.baidu.com let host: String // eg: "/" let basePath: String var url: String { let urlString = "\(scheme)://\(host)\(basePath)" return urlString } } // MARK: - path public struct Path: ExpressibleByStringLiteral { var rawValue: String private let dateFormatter = DateFormatter() public init(path: String) { let date = Date() dateFormatter.dateFormat = "yyyy-M" let convertedDate: String = dateFormatter.string(from: date) let time = convertedDate.components(separatedBy: "-") self.rawValue = path + time.first! + "/" + time.last! + ".json" } public init(stringLiteral value: String){ rawValue = value } public init(unicodeScalarLiteral value: String){ rawValue = value } public init(extendedGraphemeClusterLiteral value: String){ rawValue = value } } extension Server { func urlString(_ path: Path) -> String { return self.url + path.rawValue } func url(_ path: Path) -> URL? { return URL(string: self.url)?.appendingPathComponent(path.rawValue) } }
4639d5cd700900c556fddbceae90255b
20.469697
75
0.592096
false
false
false
false
intonarumori/FloatingLabelTextField
refs/heads/master
Source/FloatingLabelIconTextField.swift
mit
1
// // FloatingLabelIconTextField.swift // FloatingLabelTextField // // Created by Daniel Langh on 2017. 02. 07.. // Copyright © 2017. rumori. All rights reserved. // import UIKit @IBDesignable open class FloatingLabelIconTextField: FloatingLabelTextField { open var iconInsets: UIEdgeInsets = .zero { didSet { setNeedsLayout() } } @IBInspectable open var iconImage: UIImage? { didSet { updateIconView() } } @IBInspectable open var selectedIconImage: UIImage? { didSet { updateIconView() } } private(set) lazy var iconView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .left return imageView }() // MARK: - public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func init_FloatingLabelIconTextField() { addTarget(self, action: #selector(updateIconView), for: .editingDidBegin) addTarget(self, action: #selector(updateIconView), for: .editingDidEnd) } // MARK: - open override func editingRect(forBounds bounds: CGRect) -> CGRect { var rect = super.editingRect(forBounds: bounds) let offset = iconInsets.right rect.origin.x += offset rect.size.width -= offset return rect } open override func textRect(forBounds bounds: CGRect) -> CGRect { var rect = super.textRect(forBounds: bounds) let offset = iconInsets.right rect.origin.x += offset rect.size.width -= offset return rect } open override func leftViewRect(forBounds bounds: CGRect) -> CGRect { var rect = super.leftViewRect(forBounds: bounds) rect.origin.x += iconInsets.left rect.origin.y += iconInsets.top return rect } // MARK: - @objc open func updateIconView() { if let iconImage = iconImage { let image = hasText ? iconImage.withRenderingMode(.alwaysTemplate) : iconImage iconView.image = image iconView.sizeToFit() leftView = iconView leftViewMode = .always } else { iconView.image = nil leftView = nil leftViewMode = .never } } } // MARK: - // Helper extension to make icon insets available in Interface Builder property inspector extension FloatingLabelIconTextField { @IBInspectable public var iconInsetsTop: CGFloat { set { iconInsets.top = newValue } get { return iconInsets.top } } @IBInspectable public var iconInsetsBottom: CGFloat { set { iconInsets.bottom = newValue } get { return iconInsets.bottom } } @IBInspectable public var iconInsetsLeft: CGFloat { set { iconInsets.left = newValue } get { return iconInsets.left } } @IBInspectable public var iconInsetsRight: CGFloat { set { iconInsets.right = newValue } get { return iconInsets.right } } }
cc3720c5d4adee81a62b844a2dbd177d
23.946154
90
0.595745
false
false
false
false
krzysztofzablocki/Sourcery
refs/heads/master
SourceryStencil/Sources/TypedNode.swift
mit
1
import Stencil extension Array { func chunked(into size: Int) -> [[Element]] { return stride(from: 0, to: count, by: size).map { Array(self[$0 ..< Swift.min($0 + size, count)]) } } } class TypedNode: NodeType { enum Content { case nodes([NodeType]) case reference(resolvable: Resolvable) } typealias Binding = (name: String, type: String) let token: Token? let bindings: [Binding] class func parse(_ parser: TokenParser, token: Token) throws -> NodeType { let components = token.components guard components.count > 1, (components.count - 1) % 3 == 0 else { throw TemplateSyntaxError( """ 'typed' tag takes only triple of arguments e.g. name as Type """ ) } let chunks = Array(components.dropFirst()).chunked(into: 3) let bindings: [Binding] = chunks.compactMap { binding in return (name: binding[0], type: binding[2]) } return TypedNode(bindings: bindings) } init(token: Token? = nil, bindings: [Binding]) { self.token = token self.bindings = bindings } func render(_ context: Context) throws -> String { return "" } }
da5c21c67e5d3cb26425490db6538d1e
26.468085
78
0.557707
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
refs/heads/master
精通Swift设计模式/Chapter 06/SportsStore/SportsStore/ViewController.swift
mit
1
import UIKit class ProductTableCell : UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var stockStepper: UIStepper! @IBOutlet weak var stockField: UITextField! var product:Product?; } var handler = { (p:Product) in print("Change: \(p.name) \(p.stockLevel) items in stock"); }; class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var totalStockLabel: UILabel! @IBOutlet weak var tableView: UITableView! //let logger = Logger<Product>(callback: handler); var products = [ Product(name:"Kayak", description:"A boat for one person", category:"Watersports", price:275.0, stockLevel:10), Product(name:"Lifejacket", description:"Protective and fashionable", category:"Watersports", price:48.95, stockLevel:14), Product(name:"Soccer Ball", description:"FIFA-approved size and weight", category:"Soccer", price:19.5, stockLevel:32), Product(name:"Corner Flags", description:"Give your playing field a professional touch", category:"Soccer", price:34.95, stockLevel:1), Product(name:"Stadium", description:"Flat-packed 35,000-seat stadium", category:"Soccer", price:79500.0, stockLevel:4), Product(name:"Thinking Cap", description:"Improve your brain efficiency by 75%", category:"Chess", price:16.0, stockLevel:8), Product(name:"Unsteady Chair", description:"Secretly give your opponent a disadvantage", category: "Chess", price: 29.95, stockLevel:3), Product(name:"Human Chess Board", description:"A fun game for the family", category:"Chess", price:75.0, stockLevel:2), Product(name:"Bling-Bling King", description:"Gold-plated, diamond-studded King", category:"Chess", price:1200.0, stockLevel:4)]; override func viewDidLoad() { super.viewDidLoad() displayStockTotal(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return products.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let product = products[indexPath.row]; let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell") as! ProductTableCell; cell.product = products[indexPath.row]; cell.nameLabel.text = product.name; cell.descriptionLabel.text = product.productDescription; cell.stockStepper.value = Double(product.stockLevel); cell.stockField.text = String(product.stockLevel); return cell; } @IBAction func stockLevelDidChange(_ sender: AnyObject) { if var currentCell = sender as? UIView { while (true) { currentCell = currentCell.superview!; if let cell = currentCell as? ProductTableCell { if let product = cell.product { if let stepper = sender as? UIStepper { product.stockLevel = Int(stepper.value); } else if let textfield = sender as? UITextField { if let newValue = textfield.text.toInt()? { product.stockLevel = newValue; } } cell.stockStepper.value = Double(product.stockLevel); cell.stockField.text = String(product.stockLevel); productLogger.logItem(product); } break; } } displayStockTotal(); } } func displayStockTotal() { let finalTotals:(Int, Double) = products.reduce((0, 0.0), {(totals, product) -> (Int, Double) in return ( totals.0 + product.stockLevel, totals.1 + product.stockValue ); }); totalStockLabel.text = "\(finalTotals.0) Products in Stock. " + "Total Value: \(Utils.currencyStringFromNumber(finalTotals.1))"; } }
2d0cec6562c62305eb9649fba57dd963
39.035714
83
0.577386
false
false
false
false
noxytrux/RescueKopter
refs/heads/master
RescueKopter/KPTGameViewController.swift
mit
1
// // GameViewController.swift // RescueKopter // // Created by Marcin Pędzimąż on 15.11.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit import Metal import QuartzCore #if os(tvOS) import GameController #else import CoreMotion #endif let maxFramesToBuffer = 3 struct sunStructure { var sunVector = Vector3() var sunColor = Vector3() } struct matrixStructure { var projMatrix = Matrix4x4() var viewMatrix = Matrix4x4() var normalMatrix = Matrix4x4() } class KPTGameViewController: UIViewController { @IBOutlet weak var loadingLabel: UILabel! let device = { MTLCreateSystemDefaultDevice()! }() let metalLayer = { CAMetalLayer() }() var commandQueue: MTLCommandQueue! = nil var timer: CADisplayLink! = nil var pipelineState: MTLRenderPipelineState! = nil let inflightSemaphore = dispatch_semaphore_create(maxFramesToBuffer) //logic stuff internal var previousUpdateTime : CFTimeInterval = 0.0 internal var delta : CFTimeInterval = 0.0 internal var accumulator:CFTimeInterval = 0.0 internal let fixedDelta = 0.03 var defaultLibrary: MTLLibrary! = nil //vector for viewMatrix var eyeVec = Vector3(x: 0.0,y: 2,z: 3.0) var dirVec = Vector3(x: 0.0,y: -0.23,z: -1.0) var upVec = Vector3(x: 0, y: 1, z: 0) var loadedModels = [KPTModel]() //sun info var sunPosition = Vector3(x: 5.316387,y: -2.408824,z: 0) var orangeColor = Vector3(x: 1.0, y: 0.5, z: 0.0) var yellowColor = Vector3(x: 1.0, y: 1.0, z: 0.8) //MARK: Render states var pipelineStates = [String : MTLRenderPipelineState]() //MARK: uniform data var sunBuffer: MTLBuffer! = nil var cameraMatrix: Matrix4x4 = Matrix4x4() var sunData = sunStructure() var matrixData = matrixStructure() var inverted = Matrix33() var baseStiencilState: MTLDepthStencilState! = nil var upRotation: Float = 0 var modelDirection: Float = 0 //MOTION #if os(tvOS) var gamePad:GCController? = nil #else let manager = CMMotionManager() #endif let queue = NSOperationQueue() weak var kopter:KPTModel? = nil weak var heightMap:KPTHeightMap? = nil override func viewDidLoad() { super.viewDidLoad() metalLayer.device = device metalLayer.pixelFormat = .BGRA8Unorm metalLayer.framebufferOnly = true self.resize() view.layer.addSublayer(metalLayer) view.opaque = true view.backgroundColor = UIColor.whiteColor() commandQueue = device.newCommandQueue() commandQueue.label = "main command queue" //load data here: defaultLibrary = device.newDefaultLibrary() KPTModelManager.sharedInstance KPTTextureManager.sharedInstance //generate shaders and descriptors preparePipelineStates() //set matrix let aspect = Float32(view.frame.size.width/view.frame.size.height) matrixData.projMatrix = matrix44MakePerspective(degToRad(60), aspect: aspect, nearZ: 0.01, farZ: 15000) //set unifor buffers sunBuffer = device.newBufferWithBytes(&sunData, length: sizeof(sunStructure), options: .CPUCacheModeDefaultCache) #if os(tvOS) //register for controller search NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("controllerDidConnect:"), name: GCControllerDidConnectNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("controllerDidDisconnect:"), name: GCControllerDidDisconnectNotification, object: nil) if GCController.controllers().count > 0 { self.gamePad = GCController.controllers().first self.initializeGamePad() } else { GCController.startWirelessControllerDiscoveryWithCompletionHandler { //this is called in case of failure (searching stops) print("Remote discovery ended") if GCController.controllers().count == 0 { //throw some error there is nothing we can control in our game } } } #else if manager.deviceMotionAvailable { manager.deviceMotionUpdateInterval = 0.01 manager.startDeviceMotionUpdatesToQueue(queue) { (motion:CMDeviceMotion?, error:NSError?) -> Void in if let motion = motion { let attitude:CMAttitude = motion.attitude self.upRotation = Float(atan2(Double(radToDeg(Float32(attitude.pitch))), Double(radToDeg(Float32(attitude.roll))))) } } } self.initializeGame() #endif } func initializeGame() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in self.loadGameData() dispatch_sync(dispatch_get_main_queue(), { () -> Void in self.loadingLabel.hidden = true self.view.backgroundColor = nil self.timer = CADisplayLink(target: self, selector: Selector("renderLoop")) self.timer.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) }) }) } #if os(tvOS) func controllerDidConnect(notification:NSNotification) { print("controllerDidConnect: \(notification.object)") //do not allow to connect more than 1 if let _ = self.gamePad { return } self.gamePad = GCController.controllers().first self.initializeGamePad() } func controllerDidDisconnect(notification:NSNotification) { print("controllerDidDisconnect: \(notification.object)") //stop game, infor about missing controller etc. } func initializeGamePad() { //we are connected start motion monitoring and game if let gamePad = self.gamePad { print("found at index: \(gamePad.playerIndex) - device: (\(gamePad)") guard let _ = gamePad.motion else { print("Motion not supported") return } if let profile = gamePad.microGamepad { gamePad.motion!.valueChangedHandler = {[unowned self](motion) in //TODO: Figure out is there any way to use gyro in Apple Remote // let attitude = motion.attitude // // let roll = atan2(2*attitude.y*attitude.w - 2*attitude.x*attitude.z, 1 - 2*attitude.y*attitude.y - 2*attitude.z*attitude.z); // let pitch = atan2(2*attitude.x*attitude.w - 2*attitude.y*attitude.z, 1 - 2*attitude.x*attitude.x - 2*attitude.z*attitude.z); // // self.upRotation = Float(atan2(Double(radToDeg(Float32(pitch))), Double(radToDeg(Float32(roll))))) let gravity = motion.gravity let upVector = Float32(abs(gravity.x)) let rotation = Float32(-gravity.y * 0.2) * (gravity.x > 0 ? 1 : -1) self.upRotation = Float(atan2(radToDeg(rotation), radToDeg(upVector))) } profile.valueChangedHandler = { (gamepad, element) in print("PROFILE UPDATE") } } self.initializeGame() } } #endif func loadGameData() { let skyboxSphere = KPTModelManager.sharedInstance.loadModel("sphere", device: device) if let skyboxSphere = skyboxSphere { skyboxSphere.modelScale = 5000 skyboxSphere.modelMatrix.t = Vector3() skyboxSphere.modelMatrix.M.rotY(0) //no back culling at all is skybox! skyboxSphere.setCullModeForMesh(0, mode: .None) skyboxSphere.setPipelineState(0, name: "skybox") let skyboxTex = KPTTextureManager.sharedInstance.loadCubeTexture("skybox", device: device) if let skyboxTex = skyboxTex { skyboxSphere.setTexture(0, texture: skyboxTex) } loadedModels.append(skyboxSphere) } let helicopter = KPTModelManager.sharedInstance.loadModel("helicopter", device: device) if let helicopter = helicopter { helicopter.modelScale = 1.0 helicopter.modelMatrix.t = Vector3(x:0,y:34,z:-3) var rotX = Matrix33() rotX.rotX(Float(M_PI_2)) var rotZ = Matrix33() rotZ.rotY(Float(M_PI)) helicopter.modelMatrix.M = rotX * rotZ loadedModels.append(helicopter) kopter = helicopter } let gameMap = KPTMapModel() gameMap.load("heightmap", device: device) heightMap = gameMap.heightMap loadedModels.append(gameMap) } func preparePipelineStates() { let desc = MTLDepthStencilDescriptor() desc.depthWriteEnabled = true; desc.depthCompareFunction = .LessEqual; baseStiencilState = device.newDepthStencilStateWithDescriptor(desc) //create all pipeline states for shaders let pipelineStateDescriptor = MTLRenderPipelineDescriptor() var fragmentProgram: MTLFunction? var vertexProgram: MTLFunction? do { //BASIC SHADER fragmentProgram = defaultLibrary?.newFunctionWithName("basicRenderFragment") vertexProgram = defaultLibrary?.newFunctionWithName("basicRenderVertex") pipelineStateDescriptor.vertexFunction = vertexProgram pipelineStateDescriptor.fragmentFunction = fragmentProgram pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm let basicState = try device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor) pipelineStates["basic"] = basicState } catch { print("Failed to create pipeline state, error \(error)") } do { //SKYBOX SHADER fragmentProgram = defaultLibrary?.newFunctionWithName("skyboxFragment") vertexProgram = defaultLibrary?.newFunctionWithName("skyboxVertex") pipelineStateDescriptor.vertexFunction = vertexProgram pipelineStateDescriptor.fragmentFunction = fragmentProgram pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm let basicState = try device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor) pipelineStates["skybox"] = basicState } catch { print("Failed to create pipeline state, error \(error)") } } #if os(iOS) override func prefersStatusBarHidden() -> Bool { return true } #endif override func viewDidLayoutSubviews() { self.resize() } func resize() { if (view.window == nil) { return } let window = view.window! let nativeScale = window.screen.nativeScale view.contentScaleFactor = nativeScale metalLayer.frame = view.layer.frame var drawableSize = view.bounds.size drawableSize.width = drawableSize.width * CGFloat(view.contentScaleFactor) drawableSize.height = drawableSize.height * CGFloat(view.contentScaleFactor) metalLayer.drawableSize = drawableSize } deinit { timer.invalidate() } func renderLoop() { autoreleasepool { self.render() } } func render() { dispatch_semaphore_wait(inflightSemaphore, DISPATCH_TIME_FOREVER) self.update() let commandBuffer = commandQueue.commandBuffer() commandBuffer.label = "Frame command buffer" if let drawable = metalLayer.nextDrawable() { let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = drawable.texture renderPassDescriptor.colorAttachments[0].loadAction = .Clear renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0) renderPassDescriptor.colorAttachments[0].storeAction = .Store let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor) renderEncoder.label = "render encoder" renderEncoder.setFrontFacingWinding(.CounterClockwise) renderEncoder.setDepthStencilState(baseStiencilState) renderEncoder.setVertexBuffer(sunBuffer, offset: 0, atIndex: 2) //game rendering here var cameraViewMatrix = Matrix34(initialize: false) cameraViewMatrix.setColumnMajor44(cameraMatrix) for model in loadedModels { //calcualte real model view matrix let modelViewMatrix = cameraViewMatrix * (model.modelMatrix * model.modelScale) var normalMatrix = Matrix33(other: modelViewMatrix.M) if modelViewMatrix.M.getInverse(&inverted) == true { normalMatrix.setTransposed(inverted) } //set updated buffer info modelViewMatrix.getColumnMajor44(&matrixData.viewMatrix) let normal4x4 = Matrix34(rot: normalMatrix, trans: Vector3(x: 0, y: 0, z: 0)) normal4x4.getColumnMajor44(&matrixData.normalMatrix) //cannot modify single value let matrices = UnsafeMutablePointer<matrixStructure>(model.matrixBuffer.contents()) matrices.memory = matrixData renderEncoder.setVertexBuffer(model.matrixBuffer, offset: 0, atIndex: 1) model.render(renderEncoder, states: pipelineStates, shadowPass: false) } renderEncoder.endEncoding() commandBuffer.addCompletedHandler{ [weak self] commandBuffer in if let strongSelf = self { dispatch_semaphore_signal(strongSelf.inflightSemaphore) } return } commandBuffer.presentDrawable(drawable) commandBuffer.commit() } } func update() { delta = timer.timestamp - self.previousUpdateTime previousUpdateTime = timer.timestamp if delta > 0.3 { delta = 0.3 } //update gyro: let uprotationValue = min(max(upRotation, -0.7), 0.7) var realUp = upVec var rotationMat = Matrix33() rotationMat.rotZ(uprotationValue) rotationMat.multiply(upVec, dst: &realUp) accumulator += delta while (accumulator > fixedDelta) { calculatePhysic() accumulator -= fixedDelta } //update lookAt matrix cameraMatrix = matrix44MakeLookAt(eyeVec, center: eyeVec+dirVec, up: realUp) //udpate sun position and color sunPosition.y += Float32(delta) * 0.05 sunPosition.x += Float32(delta) * 0.05 sunData.sunVector = Vector3(x: -cosf(sunPosition.x) * sinf(sunPosition.y), y: -cosf(sunPosition.y), z: -sinf(sunPosition.x) * sinf(sunPosition.y)) let sun_cosy = sunData.sunVector.y let factor = 0.25 + sun_cosy * 0.75 sunData.sunColor = ((orangeColor * (1.0 - factor)) + (yellowColor * factor)) memcpy(sunBuffer.contents(), &sunData, Int(sizeof(sunStructure))) } func calculatePhysic() { //update kopter logic if let kopter = kopter { let kopterRotation = min(max(upRotation, -0.4), 0.4) modelDirection += kopterRotation * 0.5 var rotX = Matrix33() rotX.rotX(Float(M_PI_2)) var rotY = Matrix33() rotY.rotY(Float(M_PI)) var rotK1 = Matrix33() rotK1.rotZ(modelDirection) var rotK2 = Matrix33() rotK2.rotY(kopterRotation) kopter.modelMatrix.M = rotX * rotY * rotK1 * rotK2 //flying let speed:Float = 9.0 let pos = Vector3(x: Float32(sin(modelDirection) * speed * Float(fixedDelta)), y: 0.0, z: Float32(cos(modelDirection) * speed * Float(fixedDelta))) let dist = Vector3(x: Float32(sin(modelDirection) * speed), y: 0.0, z: Float32(cos(modelDirection) * speed)) eyeVec = kopter.modelMatrix.t + dist eyeVec.y += 2 dirVec = eyeVec - kopter.modelMatrix.t dirVec.normalize() dirVec.setNegative() dirVec.y = -0.23 kopter.modelMatrix.t -= pos let px: Float32 = kopter.modelMatrix.t.x + 256.0 let pz: Float32 = kopter.modelMatrix.t.z + 256.0 kopter.modelMatrix.t.y = fabs(heightMap!.GetHeight(px/2.0, z: pz/2.0) / 8.0 ) + 10.0 } } }
3e824e18a88a1aabe2a635e86ca019cc
31.153979
159
0.560913
false
false
false
false
infinum/iOS-Loggie
refs/heads/master
Loggie/Classes/LogList/LogListTableViewController.swift
mit
1
// // LogListTableViewController.swift // Pods // // Created by Filip Bec on 12/03/2017. // // import UIKit public class LogListTableViewController: UITableViewController { private static let cellReuseIdentifier = "cell" internal var logsDataSourceDelegate: LogsDataSourceDelegate! @IBOutlet private var searchBar: UISearchBar! private var logs = [Log]() { didSet { tableView.reloadData() } } public var filter: ((Log) -> Bool)? = nil { didSet { updateLogs() } } override public func viewDidLoad() { super.viewDidLoad() title = "Logs" setupTableView() navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .stop, target: self, action: #selector(closeButtonActionHandler) ) NotificationCenter.default.addObserver( self, selector: #selector(loggieDidUpdateLogs), name: .LoggieDidUpdateLogs, object: nil ) updateLogs() } private func setupTableView() { tableView.rowHeight = 70 tableView.tableFooterView = UIView(frame: CGRect.zero) let cellNib = UINib(nibName: "LogListTableViewCell", bundle: .loggie) tableView.register(cellNib, forCellReuseIdentifier: LogListTableViewController.cellReuseIdentifier) } @IBAction func clearAction() { logsDataSourceDelegate.clearLogs() logs = [] } } // MARK: - Table view data source extension LogListTableViewController { override public func numberOfSections(in tableView: UITableView) -> Int { return 1 } override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return logs.count } override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell( withIdentifier: LogListTableViewController.cellReuseIdentifier, for: indexPath ) as! LogListTableViewCell cell.configure(with: logs[indexPath.row]) return cell } } // MARK: - Table view delegate extension LogListTableViewController { override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { showLogDetails(with: logs[indexPath.row]) } public override func scrollViewDidScroll(_ scrollView: UIScrollView) { if searchBar.isFirstResponder { searchBar.resignFirstResponder() } } } // MARK: - Search bar delegate extension LogListTableViewController: UISearchBarDelegate { public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { updateLogs() } public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } } // MARK: - Private extension LogListTableViewController { private func updateLogs() { var _logs: [Log] = LoggieManager.shared.logs.reversed() if let filter = filter { _logs = _logs.filter(filter) } if let text = searchBar?.text, text.isEmpty == false { _logs = _logs.filter(filter(by: text)) } logs = _logs } private func filter(by searchText: String) -> (Log) -> Bool { return { (log) in log.searchKeywords.contains(where: { $0.range(of: searchText, options: .caseInsensitive) != nil }) } } private func showLogDetails(with log: Log) { let storyboard = UIStoryboard(name: "LogDetails", bundle: .loggie) let viewController = storyboard.instantiateInitialViewController() as! LogDetailsViewController viewController.log = log navigationController?.pushViewController(viewController, animated: true) } @objc private func loggieDidUpdateLogs() { updateLogs() } @objc private func closeButtonActionHandler() { dismiss(animated: true, completion: nil) } }
4eeb8cc70e98cb3debe2bb0e0ce20284
26.384106
116
0.643531
false
false
false
false
Anviking/Chromatism
refs/heads/master
Chromatism/CodeViewController.swift
mit
1
// // JLTextViewController.swift // Chromatism // // Created by Johannes Lund on 2014-07-18. // Copyright (c) 2014 anviking. All rights reserved. // import UIKit public class CodeViewController: UIViewController { public var textView: UITextView private let delegate: JLTextStorageDelegate public required init(text: String, language: Language, theme: ColorTheme) { let textView = UITextView() self.textView = textView textView.text = text delegate = JLTextStorageDelegate(managing: textView, language: language, theme: theme) super.init(nibName: nil, bundle: nil) registerForKeyboardNotifications() } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { unregisterForKeyboardNotifications() } override public func loadView() { view = textView } // MARK: Content Insets and Keyboard func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func unregisterForKeyboardNotifications() { NotificationCenter.default.removeObserver(self) } // Called when the UIKeyboardDidShowNotification is sent. func keyboardWasShown(_ notification: Notification) { // FIXME: ! could be wrong let info = (notification as NSNotification).userInfo! let scrollView = self.textView let kbSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size; var contentInsets = scrollView.contentInset; contentInsets.bottom = kbSize.height; scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets; // FIXME: ! could be wrong var point = textView.caretRect(for: textView.selectedTextRange!.start).origin; point.y = min(point.y, self.textView.frame.size.height - kbSize.height); var aRect = self.view.frame; aRect.size.height -= kbSize.height; if (!aRect.contains(point) ) { var rect = CGRect(x: point.x, y: point.y, width: 1, height: 1) rect.size.height = kbSize.height rect.origin.y += kbSize.height textView.scrollRectToVisible(rect, animated: true) } } // Called when the UIKeyboardWillHideNotification is sent func keyboardWillBeHidden(_ notification: Notification) { var contentInsets = textView.contentInset; contentInsets.bottom = 0; textView.contentInset = contentInsets; textView.scrollIndicatorInsets = contentInsets; textView.contentInset = contentInsets; textView.scrollIndicatorInsets = contentInsets; } }
1180f83594699b1c91136f908e56f3c5
35.023529
154
0.669824
false
false
false
false
hiddenswitch/ObjectiveDDP
refs/heads/master
Example/swiftExample/swiftddp/ViewController.swift
mit
1
// // ViewController.swift // swiftddp // // Created by Michael Arthur on 7/6/14. // Copyright (c) 2014. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDataSource, AddViewControllerDelegate { var meteor:MeteorClient! var listName:NSString! var userId:NSString! @IBOutlet weak var tableview: UITableView! required init(coder aDecoder: NSCoder!) { super.init() if aDecoder != nil { } } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) if(self != nil) { } } init(nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!, meteor: MeteorClient!, listName:NSString!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) if(self != nil) { self.meteor = meteor self.listName = listName } } override func viewWillAppear(animated: Bool) { self.navigationItem.title = self.listName UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "didTouchAdd:") NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveUpdate:", name: "added", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveUpdate:", name: "removed", object: nil) } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self) } func didReceiveUpdate(notification:NSNotification) { self.tableview.reloadData() } func computedList() -> NSArray { var pred:NSPredicate = NSPredicate(format: "(listName like %@)", self.listName) return self.meteor.collections["things"].filteredArrayUsingPredicate(pred) } @IBAction func didTouchAdd(sender: AnyObject) { var addController = AddViewController(nibName: "AddViewController", bundle: nil) addController.delegate = self self.presentViewController(addController, animated: true, completion: nil) } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return self.computedList().count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cellIdentifier:NSString! = "thing" var cell:UITableViewCell if var tmpCell: AnyObject = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) { cell = tmpCell as UITableViewCell } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) as UITableViewCell } var thing:NSDictionary = self.computedList()[indexPath.row] as NSDictionary cell.textLabel.text = thing["msg"] as String return cell } func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { return true } func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if(editingStyle == UITableViewCellEditingStyle.Delete) { var thing:NSDictionary = self.computedList()[indexPath.row] as NSDictionary self.meteor.callMethodName("/things/remove", parameters: [["_id":thing["_id"]]], responseCallback: nil) } } func didAddThing(message: NSString!) { self.dismissViewControllerAnimated(true, completion: nil) var parameters:NSArray = [["_id": NSUUID.UUID().UUIDString, "msg":message, "owner":self.userId, "listName":self.listName]] self.meteor.callMethodName("/things/insert", parameters: parameters, responseCallback: nil) } 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. } }
8233e539407db48b14a3d9b57cf851c9
33.968504
150
0.640621
false
false
false
false
rubnsbarbosa/swift
refs/heads/master
secApp/secApp/ViewController.swift
mit
1
// // ViewController.swift // secApp // // Created by Rubens Santos Barbosa on 22/05/17. // Copyright © 2017 Rubens Santos Barbosa. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var myLabel: UILabel! @IBOutlet weak var myLabel2: UILabel! @IBOutlet weak var myLabel3: UILabel! @IBOutlet weak var myTextField: UITextField! @IBOutlet weak var myTextField2: UITextField! @IBOutlet weak var myTextField3: UITextField! override func viewDidLoad() { super.viewDidLoad() myTextField.delegate = self myTextField2.delegate = self myTextField3.delegate = self myTextField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: --> TextFieldDelegate func textFieldDidEndEditing(_ textField: UITextField) { if (textField == myTextField) { myTextField2.becomeFirstResponder() } else if (textField == myTextField2) { myTextField3.becomeFirstResponder() } else if (textField == myTextField3) { myTextField.becomeFirstResponder() } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
39515889aea52102b142067dd4413c29
25.035714
66
0.648834
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Banking
refs/heads/master
HatchReadyApp/apps/Hatch/iphone/native/Hatch/Extensions/UILabelExtension.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation import UIKit extension UILabel { /** Method to resize a label of variable height based on some text and a fixed width. - parameter fixedWidth: The size we want our width to always be at. */ func sizeToFitFixedWidth(fixedWidth: CGFloat) { if self.text != "" { let objcString: NSString = self.text! let frame = objcString.boundingRectWithSize(CGSizeMake(fixedWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:self.font], context: nil) self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, frame.size.height) } } /** Method to return the height based on some text, font, and width. - parameter text: The text to base the height on. - parameter font: The font of the text. - parameter width: The width to base the height on. */ class func heightForText(text: String, font: UIFont, width: CGFloat)->CGFloat{ let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.ByWordWrapping label.font = font label.text = text label.sizeToFit() return label.frame.size.height } func setKernAttribute(size: CGFloat!){ let kernAttribute : Dictionary = [NSKernAttributeName: size] if self.text != nil { self.attributedText = NSAttributedString(string: self.text!, attributes: kernAttribute) } } }
54959d2555ed2557f799e976508c6bdb
32.392157
207
0.659812
false
false
false
false
eduarenas/GithubClient
refs/heads/master
Sources/GitHubClient/Models/Request/AuthorizationUpdate.swift
mit
1
// // AuthorizationUpdate.swift // GithubClient // // Created by Eduardo Arenas on 2/18/18. // Copyright © 2018 GameChanger. All rights reserved. // public struct AuthorizationUpdate: Encodable { public let note: String? public let noteUrl: String? public let scopes: [String]? public let addScopes: [String]? public let removeScopes: [String]? public let fingerprint: String? public init(note: String? = nil, noteUrl: String? = nil, scopes: [String]? = nil, addScopes: [String]? = nil, removeScopes: [String]? = nil, fingerprint: String? = nil) { self.note = note self.noteUrl = noteUrl self.scopes = scopes self.addScopes = addScopes self.removeScopes = removeScopes self.fingerprint = fingerprint } }
3d421fe75acd9dba83a6731ece0e9e31
25.483871
54
0.633374
false
false
false
false
adrfer/swift
refs/heads/master
test/Interpreter/builtin_bridge_object.swift
apache-2.0
2
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -parse-stdlib %s -o %t/a.out // RUN: %target-run %t/a.out | FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux import Swift import SwiftShims class C { deinit { print("deallocated") } } #if arch(i386) || arch(arm) // We have no ObjC tagged pointers, and two low spare bits due to alignment. let NATIVE_SPARE_BITS: UInt = 0x0000_0003 let OBJC_TAGGED_POINTER_BITS: UInt = 0 #elseif arch(x86_64) // We have ObjC tagged pointers in the lowest and highest bit let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0006 let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0001 #elseif arch(arm64) // We have ObjC tagged pointers in the highest bit let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0007 let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0000 #elseif arch(powerpc64) || arch(powerpc64le) // We have no ObjC tagged pointers, and three low spare bits due to alignment. let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007 let OBJC_TAGGED_POINTER_BITS: UInt = 0 #endif func bitPattern(x: Builtin.BridgeObject) -> UInt { return UInt(Builtin.castBitPatternFromBridgeObject(x)) } func nonPointerBits(x: Builtin.BridgeObject) -> UInt { return bitPattern(x) & NATIVE_SPARE_BITS } // Try without any bits set. if true { let x = C() let bo = Builtin.castToBridgeObject(x, 0._builtinWordValue) let bo2 = bo let x1: C = Builtin.castReferenceFromBridgeObject(bo) let x2: C = Builtin.castReferenceFromBridgeObject(bo2) // CHECK: true print(x === x1) // CHECK-NEXT: true print(x === x2) print(nonPointerBits(bo) == 0) // CHECK-NEXT: true var bo3 = Builtin.castToBridgeObject(C(), 0._builtinWordValue) print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: true let bo4 = bo3 print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: false _fixLifetime(bo3) _fixLifetime(bo4) } // CHECK-NEXT: deallocated // CHECK-NEXT: deallocated // Try with all spare bits set. if true { let x = C() let bo = Builtin.castToBridgeObject(x, NATIVE_SPARE_BITS._builtinWordValue) let bo2 = bo let x1: C = Builtin.castReferenceFromBridgeObject(bo) let x2: C = Builtin.castReferenceFromBridgeObject(bo2) // CHECK-NEXT: true print(x === x1) // CHECK-NEXT: true print(x === x2) print(nonPointerBits(bo) == NATIVE_SPARE_BITS) // CHECK-NEXT: true var bo3 = Builtin.castToBridgeObject(C(), NATIVE_SPARE_BITS._builtinWordValue) print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: true let bo4 = bo3 print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: false _fixLifetime(bo3) _fixLifetime(bo4) } // CHECK-NEXT: deallocated // CHECK-NEXT: deallocated import Foundation func nonNativeBridgeObject(o: AnyObject) -> Builtin.BridgeObject { let tagged = ((Builtin.reinterpretCast(o) as UInt) & OBJC_TAGGED_POINTER_BITS) != 0 return Builtin.castToBridgeObject( o, tagged ? 0._builtinWordValue : NATIVE_SPARE_BITS._builtinWordValue) } // Try with a (probably) tagged pointer. No bits may be masked into a // non-native object. if true { let x = NSNumber(integer: 22) let bo = nonNativeBridgeObject(x) let bo2 = bo let x1: NSNumber = Builtin.castReferenceFromBridgeObject(bo) let x2: NSNumber = Builtin.castReferenceFromBridgeObject(bo2) // CHECK-NEXT: true print(x === x1) // CHECK-NEXT: true print(x === x2) var bo3 = nonNativeBridgeObject(NSNumber(integer: 22)) print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: false _fixLifetime(bo3) } var unTaggedString: NSString { return NSString(format: "A long string that won't fit in a tagged pointer") } // Try with an un-tagged pointer. if true { let x = unTaggedString let bo = nonNativeBridgeObject(x) let bo2 = bo let x1: NSString = Builtin.castReferenceFromBridgeObject(bo) let x2: NSString = Builtin.castReferenceFromBridgeObject(bo2) // CHECK-NEXT: true print(x === x1) // CHECK-NEXT: true print(x === x2) var bo3 = nonNativeBridgeObject(unTaggedString) print(_getBool(Builtin.isUnique(&bo3))) // CHECK-NEXT: false _fixLifetime(bo3) } func hitOptionalGenerically<T>(x: T?) { switch x { case .Some: print("Some") case .None: print("None") } } func hitOptionalSpecifically(x: Builtin.BridgeObject?) { switch x { case .Some: print("Some") case .None: print("None") } } if true { // CHECK-NEXT: true print(sizeof(Optional<Builtin.BridgeObject>.self) == sizeof(Builtin.BridgeObject.self)) var bo: Builtin.BridgeObject? = nil // CHECK-NEXT: None hitOptionalSpecifically(bo) // CHECK-NEXT: None hitOptionalGenerically(bo) bo = Builtin.castToBridgeObject(C(), 0._builtinWordValue) // CHECK-NEXT: Some hitOptionalSpecifically(bo) // CHECK: Some hitOptionalGenerically(bo) }
a666be4b563e7fb36101c42ce2f237f2
24.534031
85
0.69879
false
false
false
false
j-chao/venture
refs/heads/master
source/venture/foodVC.swift
mit
1
// // foodVC.swift // venture // // Created by Connie Liu on 4/10/17. // Copyright © 2017 Group1. All rights reserved. // import UIKit class foodVC: UIViewController { var nameStr:String? var address1Str:String? var address2Str:String? var categoryStr:String? var rating:Decimal? var phoneStr:String? var priceStr:String? var eventDate:Date! @IBOutlet weak var foodAddress1Lbl: UILabel! @IBOutlet weak var foodAddress2Lbl: UILabel! @IBOutlet weak var foodPhoneLbl: UILabel! @IBOutlet weak var foodRatingLbl: UILabel! @IBOutlet weak var foodCategoryLbl: UILabel! @IBOutlet weak var foodPriceLbl: UILabel! override func viewDidLoad() { self.setBackground() super.viewDidLoad() self.title = nameStr foodAddress1Lbl.text = address1Str foodAddress2Lbl.text = address2Str foodPhoneLbl.text = phoneStr foodRatingLbl.text = "\(rating!) / 5" foodCategoryLbl.text = categoryStr foodPriceLbl.text = priceStr } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toEventFromFood"{ if let destinationVC = segue.destination as? AddEventVC { destinationVC.fromFoodorPlace = true destinationVC.eventDate = self.eventDate destinationVC.eventDescStr = nameStr destinationVC.eventLocStr = "\(address1Str!) \(address2Str!)" } } } }
8df4d67fa7ce57e790e2f1f2e37d3c2c
27.773585
77
0.64459
false
false
false
false
Ivacker/swift
refs/heads/master
test/IDE/print_clang_decls_AppKit.swift
apache-2.0
12
// RUN: rm -rf %t // RUN: mkdir -p %t // This file deliberately does not use %clang-importer-sdk for most RUN lines. // Instead, it generates custom overlay modules itself, and uses -I %t when it // wants to use them. // REQUIRES: OS=macosx // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/AppKit.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=AppKit -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: FileCheck %s -check-prefix=APPKIT -strict-whitespace < %t.printed.txt // APPKIT-LABEL: {{^}}extension NSString {{{$}} // APPKIT-LABEL: {{^}}class NSView : NSObject, NSCoding, NSAccessibility {{{$}} // APPKIT-NEXT: init?(coder aDecoder: NSCoder) // APPKIT-NEXT: func isDescendantOf(aView: NSView) -> Bool // APPKIT-NEXT: func ancestorSharedWithView(aView: NSView) -> NSView? // APPKIT-NEXT: func addSubview(aView: NSView) // APPKIT-NEXT: func addSubview(aView: NSView, positioned place: UInt32, relativeTo otherView: NSView?) // APPKIT-NEXT: unowned(unsafe) var superview: @sil_unmanaged NSView? { get } // APPKIT-NEXT: var layer: CALayer? // APPKIT-NEXT: var trackingAreas: [AnyObject] { get } // APPKIT-NEXT: var subviews: [AnyObject] // APPKIT-LABEL: extension NSView { // APPKIT-NEXT: unowned(unsafe) var nextKeyView: @sil_unmanaged NSView? // APPKIT-LABEL: {{^}}class NSMenuItem : NSObject, NSCopying, NSCoding { // APPKIT-NEXT: unowned(unsafe) var menu: @sil_unmanaged NSMenu? // APPKIT-NEXT: var title: String // APPKIT-NEXT: @NSCopying var attributedTitle: NSAttributedString? // APPKIT-NEXT: weak var target: @sil_weak AnyObject // APPKIT-NEXT: var action: Selector // APPKIT: {{^}}}{{$}} // APPKIT: let NSViewFrameDidChangeNotification: String // APPKIT: let NSViewFocusDidChangeNotification: String
ba6247e762eeba5f22b118fc21be87b5
54.418605
210
0.719261
false
false
false
false
pksprojects/ElasticSwift
refs/heads/master
Sources/ElasticSwift/Serialization/Serialization.swift
mit
1
// // Serialization.swift // ElasticSwift // // Created by Prafull Kumar Soni on 6/5/17. // // import ElasticSwiftCore import Foundation // MARK: - DefaultSerializer /// `JSONEncoder/JSONDecoder` based default implementation of `Serializer` public class DefaultSerializer: Serializer { /// The encoder of the serializer public let encoder: JSONEncoder /// The decoder of the serializer public let decoder: JSONDecoder /// Initializes new serializer. /// - Parameters: /// - encoder: json encoder for encoding /// - decoder: json decoder for decoding public init(encoder: JSONEncoder = JSONEncoder(), decoder: JSONDecoder = JSONDecoder()) { self.encoder = encoder self.decoder = decoder } /// Decodes data into object of type `T` conforming to `Decodable` /// - Parameter data: data to decode /// - Returns: result of either success `T` or failure `DecodingError` public func decode<T>(data: Data) -> Result<T, DecodingError> where T: Decodable { do { let decoded = try decoder.decode(T.self, from: data) return .success(decoded) } catch { return .failure(DecodingError(T.self, data: data, error: error)) } } /// Decodes data into object of type `T` conforming to `Encodable` /// - Parameter value: value to encode /// - Returns: result of either success `Data` or failure `DecodingError` public func encode<T>(_ value: T) -> Result<Data, EncodingError> where T: Encodable { do { let encoded = try encoder.encode(value) return .success(encoded) } catch { return .failure(EncodingError(value: value, error: error)) } } }
fbeeaa70f96dceabf149f17543e714a3
31.388889
93
0.636364
false
false
false
false
diegosanchezr/Chatto
refs/heads/master
ChattoAdditions/Tests/Input/ChatInputItemTests.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest @testable import ChattoAdditions class ChatInputItemTests: XCTestCase { } @objc class MockInputItem: NSObject, ChatInputItemProtocol { var selected = false var presentationMode: ChatInputItemPresentationMode = .Keyboard var showsSendButton = false var inputView: UIView? = nil let tabView = UIView() private(set) var handledInput: AnyObject? func handleInput(input: AnyObject) { self.handledInput = input } }
497666be2fa0f4a063dbe561c65e1954
35.930233
78
0.770151
false
true
false
false
jvk75/NFCNDEFParse
refs/heads/master
NFCNDEFParse/NFCForumWellKnownTypeSmartPoster.swift
mit
1
// // NFCForumWellKnownTypeSmartPoster.swift // NFCNDEFParse // // Created by Jari Kalinainen on 09.10.17. // import Foundation import CoreNFC /// NFCForum-SmartPoster_RTD_1.0 2006-07-24 /// (only URI and Text records supported, Action and Size records are ignored, Type and Icon records may cause problems) /// - **records** : [NFCForumWellKnownTypeProtocol] /// - collection of the NFCForumWellKnownTypes public class NFCForumWellKnownTypeSmartPoster: NSObject, NFCForumWellKnownTypeSmartPosterProtocol { public var type: NFCForumWellKnownTypeEnum = .smartPoster public var records: [NFCForumWellKnownTypeProtocol] = [] public var recordDescription: String { let recordDescriptions = records.map({ $0.recordDescription }).joined(separator: "\n") return "- \(self.type.description): {\n\(recordDescriptions)\n}\n" } private var payloadFirstByte: Int = 0 public init?(payload: Data) { super.init() let allBytes = [UInt8](payload) guard allBytes.count > 3 else { return } var newRecords: [NFCForumWellKnownTypeProtocol?] = [] while payloadFirstByte < allBytes.count { let bytes = Array(allBytes[payloadFirstByte...]) let typeLength = Int(bytes[1]) let type = NFCForumWellKnownTypeEnum(data: Data(bytes: bytes[3...(2+typeLength)])) let payloadLength: Int switch type { case .action: payloadLength = 1 case .size: payloadLength = 4 default: payloadLength = Int(bytes[2]) } let payloadLastByte = (2+typeLength) + payloadLength let payload = Data(bytes: bytes[(2+typeLength + 1)...payloadLastByte]) switch type { case .text: newRecords.append(NFCForumWellKnownTypeText(payload: payload)) case .uri: newRecords.append(NFCForumWellKnownTypeUri(payload: payload)) case .size: newRecords.append(NFCForumWellKnownSubTypeSize(payload: payload)) case .action: newRecords.append(NFCForumWellKnownSubTypeAction(payload: payload)) default: continue } payloadFirstByte += payloadLastByte + 1 } self.records = newRecords.flatMap({ $0 }) } } // MARK: - Smart Poster Action Record Enum @objc public enum NFCSmartPosterActionRecord: UInt8 { case execute = 0x00 case save = 0x01 case open = 0x02 var description: String { switch self { case .execute: return "do the action" case .save: return "save for later" case .open: return "open for editing" } } } // MARK: - Smart Poster Action Record /// NFCForum-SmartPoster_RTD_1.0 2006-07-24 /// Smart Poster Action Record /// - **action** : NFCSmartPosterActionRecord /// - **execute** : Do the action (send the SMS, launch the browser, make the telephone call) /// - **save** : Save for later (store the SMS in INBOX, put the URI in a bookmark, save the telephone number in contacts) /// - **open** : Open for editing (open an SMS in the SMS editor, open the URI in an URI editor, open the telephone number for editing). @objc public class NFCForumWellKnownSubTypeAction: NSObject, NFCForumWellKnownTypeActionProtocol, NFCForumWellKnownTypeActionProtocolObjC { @objc public var type: NFCForumWellKnownTypeEnum = .action @objc public var recordDescription: String { return "-\(type.description)\naction: " + (self.action?.description ?? "nil") } public var action: NFCSmartPosterActionRecord? @objc public var actionByte: UInt8 = 0xFF public init?(payload: Data) { super.init() let bytes = [UInt8](payload) self.actionByte = bytes[0] if let byte = bytes.first { self.action = NFCSmartPosterActionRecord(rawValue: byte) } } } // MARK: - Smart Poster Size Record /// NFCForum-SmartPoster_RTD_1.0 2006-07-24 /// Smart Poster Size Record /// - **size** : Int /// - value of the size payload public class NFCForumWellKnownSubTypeSize: NSObject, NFCForumWellKnownTypeSizeProtocol { public var type: NFCForumWellKnownTypeEnum = .action public var recordDescription: String { return "-\(type.description)\nsize: \(size)" } public var size: Int = 0 public init?(payload: Data) { super.init() let bytes = [UInt8](payload) if let byte = bytes.first { self.size = Int(byte) } } }
904a46dc89591d96d893c3c913b7d922
32.571429
139
0.625745
false
false
false
false
Jnosh/swift
refs/heads/master
stdlib/public/core/StringIndexConversions.swift
apache-2.0
4
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String.Index { /// Creates an index in the given string that corresponds exactly to the /// specified `UnicodeScalarView` position. /// /// The following example converts the position of the Unicode scalar `"e"` /// into its corresponding position in the string. The character at that /// position is the composed `"é"` character. /// /// let cafe = "Cafe\u{0301}" /// print(cafe) /// // Prints "Café" /// /// let scalarsIndex = cafe.unicodeScalars.index(of: "e")! /// let stringIndex = String.Index(scalarsIndex, within: cafe)! /// /// print(cafe[...stringIndex]) /// // Prints "Café" /// /// If the position passed in `unicodeScalarIndex` doesn't have an exact /// corresponding position in `other`, the result of the initializer is /// `nil`. For example, an attempt to convert the position of the combining /// acute accent (`"\u{0301}"`) fails. Combining Unicode scalars do not have /// their own position in a string. /// /// let nextIndex = String.Index(cafe.unicodeScalars.index(after: scalarsIndex), /// within: cafe) /// print(nextIndex) /// // Prints "nil" /// /// - Parameters: /// - unicodeScalarIndex: A position in the `unicodeScalars` view of the /// `other` parameter. /// - other: The string referenced by both `unicodeScalarIndex` and the /// resulting index. public init?( _ unicodeScalarIndex: String.UnicodeScalarIndex, within other: String ) { if !other.unicodeScalars._isOnGraphemeClusterBoundary(unicodeScalarIndex) { return nil } self.init(_base: unicodeScalarIndex, in: other.characters) } /// Creates an index in the given string that corresponds exactly to the /// specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string. The /// value `32` is the UTF-16 encoded value of a space character. /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.index(of: 32)! /// let stringIndex = String.Index(utf16Index, within: cafe)! /// /// print(cafe[..<stringIndex]) /// // Prints "Café" /// /// If the position passed in `utf16Index` doesn't have an exact /// corresponding position in `other`, the result of the initializer is /// `nil`. For example, an attempt to convert the position of the trailing /// surrogate of a UTF-16 surrogate pair fails. /// /// The next example attempts to convert the indices of the two UTF-16 code /// points that represent the teacup emoji (`"🍵"`). The index of the lead /// surrogate is successfully converted to a position in `other`, but the /// index of the trailing surrogate is not. /// /// let emojiHigh = cafe.utf16.index(after: utf16Index) /// print(String.Index(emojiHigh, within: cafe)) /// // Prints "Optional(String.Index(...))" /// /// let emojiLow = cafe.utf16.index(after: emojiHigh) /// print(String.Index(emojiLow, within: cafe)) /// // Prints "nil" /// /// - Parameters: /// - utf16Index: A position in the `utf16` view of the `other` parameter. /// - other: The string referenced by both `utf16Index` and the resulting /// index. public init?( _ utf16Index: String.UTF16Index, within other: String ) { if let me = utf16Index.samePosition( in: other.unicodeScalars )?.samePosition(in: other) { self = me } else { return nil } } /// Creates an index in the given string that corresponds exactly to the /// specified `UTF8View` position. /// /// If the position passed in `utf8Index` doesn't have an exact corresponding /// position in `other`, the result of the initializer is `nil`. For /// example, an attempt to convert the position of a UTF-8 continuation byte /// returns `nil`. /// /// - Parameters: /// - utf8Index: A position in the `utf8` view of the `other` parameter. /// - other: The string referenced by both `utf8Index` and the resulting /// index. public init?( _ utf8Index: String.UTF8Index, within other: String ) { if let me = utf8Index.samePosition( in: other.unicodeScalars )?.samePosition(in: other) { self = me } else { return nil } } /// Returns the position in the given UTF-8 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf8)`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `utf8` view. /// /// let cafe = "Café" /// if let i = cafe.index(of: "é") { /// let j = i.samePosition(in: cafe.utf8) /// print(Array(cafe.utf8[j...])) /// } /// // Prints "[195, 169]" /// /// - Parameter utf8: The view to use for the index conversion. /// - Returns: The position in `utf8` that corresponds exactly to this index. public func samePosition( in utf8: String.UTF8View ) -> String.UTF8View.Index { return String.UTF8View.Index(self, within: utf8) } /// Returns the position in the given UTF-16 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf16)`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `utf16` view. /// /// let cafe = "Café" /// if let i = cafe.index(of: "é") { /// let j = i.samePosition(in: cafe.utf16) /// print(cafe.utf16[j]) /// } /// // Prints "233" /// /// - Parameter utf16: The view to use for the index conversion. /// - Returns: The position in `utf16` that corresponds exactly to this index. public func samePosition( in utf16: String.UTF16View ) -> String.UTF16View.Index { return String.UTF16View.Index(self, within: utf16) } /// Returns the position in the given view of Unicode scalars that /// corresponds exactly to this index. /// /// The index must be a valid index of `String(unicodeScalars)`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `unicodeScalars` /// view. /// /// let cafe = "Café" /// if let i = cafe.index(of: "é") { /// let j = i.samePosition(in: cafe.unicodeScalars) /// print(cafe.unicodeScalars[j]) /// } /// // Prints "é" /// /// - Parameter unicodeScalars: The view to use for the index conversion. /// - Returns: The position in `unicodeScalars` that corresponds exactly to /// this index. public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarView.Index { return String.UnicodeScalarView.Index(self, within: unicodeScalars) } }
18890503b4854db26173e222d179cde2
35.84878
86
0.620201
false
false
false
false
eBardX/XestiMonitors
refs/heads/master
Sources/Core/CoreMotion/DeviceMotionMonitor.swift
mit
1
// // DeviceMotionMonitor.swift // XestiMonitors // // Created by J. G. Pusey on 2016-12-20. // // © 2016 J. G. Pusey (see LICENSE.md) // #if os(iOS) || os(watchOS) import CoreMotion import Foundation /// /// A `DeviceMotionMonitor` instance monitors the device’s accelerometer, /// gyroscope, and magnetometer for periodic raw measurements which are /// processed into device motion measurements. /// public class DeviceMotionMonitor: BaseMonitor { /// /// Encapsulates updates to the measurement of device motion. /// public enum Event { /// /// The device motion measurement has been updated. /// case didUpdate(Info) } /// /// Encapsulates the measurement of device motion. /// public enum Info { /// /// The device motion measurement at a moment of time. /// case data(CMDeviceMotion) /// /// The error encountered in attempting to obtain the device motion /// measurement. /// case error(Error) /// /// No device motion measurement is available. /// case unknown } /// /// Initializes a new `DeviceMotionMonitor`. /// /// - Parameters: /// - interval: The interval, in seconds, for providing device /// motion measurements to the handler. /// - referenceFrame: The reference frame to use for device motion /// measurements. /// - queue: The operation queue on which the handler /// executes. Because the events might arrive at a /// high rate, using the main operation queue is /// not recommended. /// - handler: The handler to call periodically when a new /// device motion measurement is available. /// public init(interval: TimeInterval, using referenceFrame: CMAttitudeReferenceFrame, queue: OperationQueue, handler: @escaping (Event) -> Void) { self.handler = handler self.interval = interval self.motionManager = MotionManagerInjector.inject() self.queue = queue self.referenceFrame = referenceFrame } /// /// The latest device motion measurement available. /// public var info: Info { guard let data = motionManager.deviceMotion else { return .unknown } return .data(data) } /// /// A Boolean value indicating whether device motion measuring is /// available on the device. /// public var isAvailable: Bool { return motionManager.isDeviceMotionAvailable } private let handler: (Event) -> Void private let interval: TimeInterval private let motionManager: MotionManagerProtocol private let queue: OperationQueue private let referenceFrame: CMAttitudeReferenceFrame override public func cleanupMonitor() { motionManager.stopDeviceMotionUpdates() super.cleanupMonitor() } override public func configureMonitor() { super.configureMonitor() motionManager.deviceMotionUpdateInterval = interval motionManager.startDeviceMotionUpdates(using: self.referenceFrame, to: queue) { [unowned self] data, error in var info: Info if let error = error { info = .error(error) } else if let data = data { info = .data(data) } else { info = .unknown } self.handler(.didUpdate(info)) } } } #endif
693f5efe881139a520968cbb1669ce0f
30
89
0.53115
false
false
false
false
Daij-Djan/GitLogView
refs/heads/master
GitLogView/GTRepository+FindCached.swift
mit
1
// // GTRepository+Find.swift // CoprightModifier // // Created by Dominik Pich on 15/06/15. // Copyright (c) 2015 Dominik Pich. All rights reserved. // import Foundation import ObjectiveGit extension GTRepository { private static var cachedRepositories = Dictionary<String, GTRepository>() //searches for the closest repo for a given fileUrl. Same as the git CLI client. class func findCachedRepositoryWithURL(fileUrl:NSURL) -> GTRepository? { //search on disk var path = fileUrl.path var repo:GTRepository? //search in our list of cached repos if cachedRepositories.count > 0 { while(repo == nil && path != nil) { repo = cachedRepositories[path!] //change stringByDeletingLastPathComponent behaviour ;) if path == "/" { path = nil } else { let url = NSURL(fileURLWithPath: path!) path = url.URLByDeletingLastPathComponent?.path } } } if repo != nil { return repo } //search on disk path = fileUrl.path while(repo == nil && path != nil) { let url = NSURL(fileURLWithPath: path!) do { try repo = GTRepository(URL: url) cachedRepositories[path!] = repo } catch { } //change stringByDeletingLastPathComponent behaviour ;) if path == "/" { path = nil } else { let url = NSURL(fileURLWithPath: path!) path = url.URLByDeletingLastPathComponent?.path } } return repo } }
53f81f8aba982b5105d70a6e88cf4665
25.871429
84
0.494149
false
false
false
false
osorioabel/my-location-app
refs/heads/master
My Locations/My Locations/Controllers/MapViewController.swift
mit
1
// // MapViewController.swift // My Locations // // Created by Abel Osorio on 2/17/16. // Copyright © 2016 Abel Osorio. All rights reserved. // import UIKit import CoreData import MapKit class MapViewController: UIViewController { var managedObjectContext: NSManagedObjectContext! { didSet { NSNotificationCenter.defaultCenter().addObserverForName( NSManagedObjectContextObjectsDidChangeNotification,object: managedObjectContext,queue: NSOperationQueue.mainQueue()) { notification in if self.isViewLoaded() { self.updateLocations() } } } } var locations = [Location]() @IBOutlet weak var mapView: MKMapView! // MARK: - LifeCycle override func viewDidLoad() { updateLocations() if !locations.isEmpty{ showLocations() } } func updateLocations() { mapView.removeAnnotations(locations) let entity = NSEntityDescription.entityForName("Location", inManagedObjectContext: managedObjectContext) let fetchRequest = NSFetchRequest() fetchRequest.entity = entity mapView.delegate = self locations = try! managedObjectContext.executeFetchRequest( fetchRequest) as! [Location] mapView.addAnnotations(locations) } // MARK: - Actions @IBAction func showUser() { let region = MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000) mapView.setRegion(mapView.regionThatFits(region), animated: true) } @IBAction func showLocations() { let region = regionForAnnotations(locations) mapView.setRegion(region, animated: true) } func regionForAnnotations(annotations: [MKAnnotation])-> MKCoordinateRegion { var region: MKCoordinateRegion switch annotations.count { case 0: region = MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000) case 1: let annotation = annotations[annotations.count - 1] region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 1000, 1000) default: var topLeftCoord = CLLocationCoordinate2D(latitude: -90,longitude: 180) var bottomRightCoord = CLLocationCoordinate2D(latitude: 90,longitude: -180) for annotation in annotations { topLeftCoord.latitude = max(topLeftCoord.latitude,annotation.coordinate.latitude) topLeftCoord.longitude = min(topLeftCoord.longitude,annotation.coordinate.longitude) bottomRightCoord.latitude = min(bottomRightCoord.latitude,annotation.coordinate.latitude) bottomRightCoord.longitude = max(bottomRightCoord.longitude,annotation.coordinate.longitude) } let finallatitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) / 2 let finallongitude = topLeftCoord.longitude - (topLeftCoord.longitude - bottomRightCoord.longitude) / 2 let center = CLLocationCoordinate2D(latitude: finallatitude, longitude: finallongitude) let extraSpace = 1.1 let span = MKCoordinateSpan(latitudeDelta: abs(topLeftCoord.latitude - bottomRightCoord.latitude) * extraSpace,longitudeDelta: abs(topLeftCoord.longitude - bottomRightCoord.longitude) * extraSpace) region = MKCoordinateRegion(center: center, span: span) } return mapView.regionThatFits(region) } func showLocationDetails(sender: UIButton) { performSegueWithIdentifier("EditLocation", sender: sender) } // MARK: - Navegation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "EditLocation" { let navigationController = segue.destinationViewController as! UINavigationController let controller = navigationController.topViewController as! LocationDetailsViewController controller.managedObjectContext = managedObjectContext let button = sender as! UIButton let location = locations[button.tag] controller.locationToEdit = location } } } // MARK: - NavigationDelegate extension MapViewController: UINavigationBarDelegate { func positionForBar(bar: UIBarPositioning) -> UIBarPosition { return .TopAttached } } // MARK: - MapViewDelegate extension MapViewController: MKMapViewDelegate { func mapView(mapView: MKMapView,viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard annotation is Location else { return nil } let identifier = "Location" var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as! MKPinAnnotationView! if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation,reuseIdentifier: identifier) annotationView.enabled = true annotationView.canShowCallout = true annotationView.animatesDrop = false annotationView.tintColor = UIColor(white: 0.0, alpha: 0.5) if #available(iOS 9.0, *) { annotationView.pinTintColor = UIColor(red: 0.32, green: 0.82,blue: 0.4, alpha: 1) } else { // Fallback on earlier versions } let rightButton = UIButton(type: .DetailDisclosure) rightButton.addTarget(self,action: Selector("showLocationDetails:"),forControlEvents: .TouchUpInside) annotationView.rightCalloutAccessoryView = rightButton } else { annotationView.annotation = annotation } let button = annotationView.rightCalloutAccessoryView as! UIButton if let index = locations.indexOf(annotation as! Location) { button.tag = index } return annotationView } }
9a5630a14aaacd0b4dc588dc3b43bfee
34.311765
201
0.671498
false
false
false
false
CodaFi/swift
refs/heads/main
test/decl/protocol/special/Error.swift
apache-2.0
53
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -typecheck -verify -primary-file %t/main.swift %S/Inputs/Error_other.swift enum ClericalErrorDomain: Error { case MisplacedDocument(name: String) case AccidentallyErasedTape(fromMinute: Double, toMinute: Double) } let error = ClericalErrorDomain.AccidentallyErasedTape(fromMinute: 5, toMinute: 23.5) let domain: String = error._domain let code: Int = error._code struct UseEnumBeforeDeclaration { let errorDomain: String = EnumToUseBeforeDeclaration.A._domain let errorCode: Int = EnumToUseBeforeDeclaration.A._code } enum EnumToUseBeforeDeclaration: Error { case A } let domainFromOtherFile: String = FromOtherFile.A._domain let codeFromOtherFile: Int = AlsoFromOtherFile.A._code enum NotAnError { case A } let notAnErrorDomain: String = NotAnError.A._domain // expected-error{{value of type 'NotAnError' has no member '_domain'}} let notAnErrorCode: Int = NotAnError.A._code // expected-error{{value of type 'NotAnError' has no member '_code'}} enum EmptyErrorDomain: Error {} struct ErrorStruct : Error { } class ErrorClass : Error { } struct ErrorStruct2 { } extension ErrorStruct2 : Error { } class ErrorClass2 { } extension ErrorClass2 : Error { }
dc2c5a7c2354cf364469c789dfaf0b87
26.565217
123
0.753155
false
false
false
false
Dreezydraig/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/AppDelegate.swift
mit
5
// // Copyright (C) 2014-2015 Actor LLC. <https://actor.im> // import Foundation @objc class AppDelegate : UIResponder, UIApplicationDelegate { var window : UIWindow? private var binder = Binder() private var syncTask: UIBackgroundTaskIdentifier? private var completionHandler: ((UIBackgroundFetchResult) -> Void)? private let badgeView = UIImageView() private var badgeCount = 0 private var isBadgeVisible = false func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { createActor() var config = Actor.config // Apply crash logging if config.mint != nil { Mint.sharedInstance().disableNetworkMonitoring() Mint.sharedInstance().initAndStartSession(config.mint!) } // Register hockey app if config.hockeyapp != nil { BITHockeyManager.sharedHockeyManager().configureWithIdentifier(config.hockeyapp!) BITHockeyManager.sharedHockeyManager().disableCrashManager = true BITHockeyManager.sharedHockeyManager().updateManager.checkForUpdateOnLaunch = true BITHockeyManager.sharedHockeyManager().startManager() BITHockeyManager.sharedHockeyManager().authenticator.authenticateInstallation() } // Register notifications // Register always even when not enabled in build for local notifications if application.respondsToSelector("registerUserNotificationSettings:") { let types: UIUserNotificationType = (.Alert | .Badge | .Sound) let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound) } // Apply styles MainAppTheme.applyAppearance(application) // Bind Messenger LifeCycle binder.bind(Actor.getAppState().getIsSyncing(), closure: { (value: JavaLangBoolean?) -> () in if value!.booleanValue() { if self.syncTask == nil { self.syncTask = application.beginBackgroundTaskWithName("Background Sync", expirationHandler: { () -> Void in }) } } else { if self.syncTask != nil { application.endBackgroundTask(self.syncTask!) self.syncTask = nil } if self.completionHandler != nil { self.completionHandler!(UIBackgroundFetchResult.NewData) self.completionHandler = nil } } }) // Creating main window window = UIWindow(frame: UIScreen.mainScreen().bounds); window?.backgroundColor = UIColor.whiteColor() if (Actor.isLoggedIn()) { onLoggedIn(false) } else { // Create root layout for login let phoneController = AuthPhoneViewController() var loginNavigation = AANavigationController(rootViewController: phoneController) loginNavigation.navigationBar.tintColor = MainAppTheme.navigation.barColor loginNavigation.makeBarTransparent() window?.rootViewController = loginNavigation } window?.makeKeyAndVisible(); badgeView.image = Imaging.roundedImage(UIColor.RGB(0xfe0000), size: CGSizeMake(16, 16), radius: 8) // badgeView.frame = CGRectMake(16, 22, 32, 16) badgeView.alpha = 0 let badgeText = UILabel() badgeText.text = "0" badgeText.textColor = UIColor.whiteColor() // badgeText.frame = CGRectMake(0, 0, 32, 16) badgeText.font = UIFont.systemFontOfSize(12) badgeText.textAlignment = NSTextAlignment.Center badgeView.addSubview(badgeText) window?.addSubview(badgeView) // Bind badge counter binder.bind(Actor.getAppState().getGlobalCounter(), closure: { (value: JavaLangInteger?) -> () in self.badgeCount = Int((value!).integerValue) application.applicationIconBadgeNumber = self.badgeCount badgeText.text = "\(self.badgeCount)" if (self.isBadgeVisible && self.badgeCount > 0) { self.badgeView.showView() } else if (self.badgeCount == 0) { self.badgeView.hideView() } badgeText.frame = CGRectMake(0, 0, 128, 16) badgeText.sizeToFit() if badgeText.frame.width < 8 { self.badgeView.frame = CGRectMake(16, 22, 16, 16) } else { self.badgeView.frame = CGRectMake(16, 22, badgeText.frame.width + 8, 16) } badgeText.frame = self.badgeView.bounds }) return true; } func onLoggedIn(isAfterLogin: Bool) { // Create root layout for app Actor.onAppVisible() var rootController : UIViewController? = nil if (isIPad) { var splitController = MainSplitViewController() splitController.viewControllers = [MainTabViewController(isAfterLogin: isAfterLogin), NoSelectionViewController()] rootController = splitController } else { var tabController = MainTabViewController(isAfterLogin: isAfterLogin) binder.bind(Actor.getAppState().getIsAppLoaded(), valueModel2: Actor.getAppState().getIsAppEmpty()) { (loaded: JavaLangBoolean?, empty: JavaLangBoolean?) -> () in if (empty!.booleanValue()) { if (loaded!.booleanValue()) { tabController.showAppIsEmptyPlaceholder() } else { tabController.showAppIsSyncingPlaceholder() } } else { tabController.hidePlaceholders() } } rootController = tabController } window?.rootViewController = rootController! } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { println("open url: \(url)") if (url.scheme == "actor") { if (url.host == "invite") { if (Actor.isLoggedIn()) { var token = url.query?.componentsSeparatedByString("=")[1] if token != nil { UIAlertView.showWithTitle(nil, message: localized("GroupJoinMessage"), cancelButtonTitle: localized("AlertNo"), otherButtonTitles: [localized("GroupJoinAction")], tapBlock: { (view, index) -> Void in if (index == view.firstOtherButtonIndex) { self.execute(Actor.joinGroupViaLinkCommandWithUrl(token), successBlock: { (val) -> Void in var groupId = val as! JavaLangInteger self.openChat(ACPeer.groupWithInt(groupId.intValue)) }, failureBlock: { (val) -> Void in if let res = val as? ACRpcException { if res.getTag() == "USER_ALREADY_INVITED" { UIAlertView.showWithTitle(nil, message: localized("ErrorAlreadyJoined"), cancelButtonTitle: localized("AlertOk"), otherButtonTitles: nil, tapBlock: nil) return } } UIAlertView.showWithTitle(nil, message: localized("ErrorUnableToJoin"), cancelButtonTitle: localized("AlertOk"), otherButtonTitles: nil, tapBlock: nil) }) } }) } } return true } } return false } func applicationWillEnterForeground(application: UIApplication) { createActor() Actor.onAppVisible(); // Hack for resync phone book Actor.onPhoneBookChanged() } func applicationDidEnterBackground(application: UIApplication) { createActor() Actor.onAppHidden(); if Actor.isLoggedIn() { var completitionTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid completitionTask = application.beginBackgroundTaskWithName("Completition", expirationHandler: { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid }) // Wait for 40 secs before app shutdown dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(40.0 * Double(NSEC_PER_SEC))), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid } } } // MARK: - // MARK: Notifications func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let tokenString = "\(deviceToken)".stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("<", withString: "").stringByReplacingOccurrencesOfString(">", withString: "") var config = Actor.config if config.pushId != nil { Actor.registerApplePushWithApnsId(jint(config.pushId!), withToken: tokenString) } if config.mixpanel != nil { Mixpanel.sharedInstance().people.addPushDeviceToken(deviceToken) } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { createActor() if !Actor.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { createActor() if !Actor.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } func execute(command: ACCommand) { execute(command, successBlock: nil, failureBlock: nil) } func execute(command: ACCommand, successBlock: ((val: Any?) -> Void)?, failureBlock: ((val: Any?) -> Void)?) { var window = UIApplication.sharedApplication().windows[1] as! UIWindow var hud = MBProgressHUD(window: window) hud.mode = MBProgressHUDMode.Indeterminate hud.removeFromSuperViewOnHide = true window.addSubview(hud) window.bringSubviewToFront(hud) hud.show(true) command.startWithCallback(CocoaCallback(result: { (val:Any?) -> () in dispatchOnUi { hud.hide(true) successBlock?(val: val) } }, error: { (val) -> () in dispatchOnUi { hud.hide(true) failureBlock?(val: val) } })) } func openChat(peer: ACPeer) { for i in UIApplication.sharedApplication().windows { var root = (i as! UIWindow).rootViewController if let tab = root as? MainTabViewController { var controller = tab.viewControllers![tab.selectedIndex] as! AANavigationController var destController = ConversationViewController(peer: peer) destController.hidesBottomBarWhenPushed = true controller.pushViewController(destController, animated: true) return } else if let split = root as? MainSplitViewController { split.navigateDetail(ConversationViewController(peer: peer)) return } } } func showBadge() { isBadgeVisible = true if badgeCount > 0 { self.badgeView.showView() } } func hideBadge() { isBadgeVisible = false self.badgeView.hideView() } }
94b8ee36260782fd6edc141a87078c6a
40.693038
223
0.573706
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Models/Person/PersonType.swift
mit
1
// // PersonType.swift // MEGameTracker // // Created by Emily Ivie on 9/14/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import Foundation /// Defines various person types. public enum PersonType: String, Codable, CaseIterable { case squad = "Squad" case enemy = "Enemy" case associate = "Associate" case other = "Other" /// Returns a list of enum variations used in PersonType categories. public static func categories() -> [PersonType] { return [ .squad, .enemy, .associate ] // no .other } /// Returns the heading string values of all the enum variations. private static let headingValues: [PersonType: String] = [ .squad: "Squad", .enemy: "Enemies", .associate: "Associates", .other: "Others", ] /// Creates an enum from a string value, if possible. public init?(stringValue: String?) { self.init(rawValue: stringValue ?? "") } /// Returns the string value of an enum. public var stringValue: String { return rawValue } /// Creates an enum from a heading string value, if possible. public init?(headingValue: String?) { guard let type = PersonType.headingValues .filter({ $0.1 == headingValue }).map({ $0.0 }).first else { return nil } self = type } /// Returns the heading string value of an enum. public var headingValue: String { return PersonType.headingValues[self] ?? "Unknown" } /// Provides a title prefix for a person of the specified enum type. public var titlePrefix: String { switch self { case .other: return "Person: " default: return "\(stringValue): " } } }
4f2ad38bac57755be0a3260810b08088
22.797101
72
0.651644
false
false
false
false
zhangjk4859/MyWeiBoProject
refs/heads/master
sinaWeibo/sinaWeibo/Classes/Main/JKVisitView.swift
mit
1
// // JKVisitView.swift // sinaWeibo // // Created by 张俊凯 on 16/6/28. // Copyright © 2016年 张俊凯. All rights reserved. // import UIKit protocol VisitViewDelegate:NSObjectProtocol { //登录回调 func loginBtnWillClick() //注册回调 func registerBtnWillClick() } class JKVisitView: UIView { //定义一个属性保存代理,弱引用 weak var delegate:VisitViewDelegate? //设置未登录界面 func setupVisitInfo(isHome:Bool,imageName:String,message:String){ //如果不是首页就隐藏转盘 iconView.hidden = !isHome //修改中间的图标 homeIcon.image = UIImage(named: imageName) //修改文本 messageLabel.text = message //判断是否执行动画 if isHome { startAnimation() } } //播放转盘动画 private func startAnimation(){ //创建动画 let ani = CABasicAnimation(keyPath: "transform.rotation") //设置动画属性 ani.toValue = 2 * M_PI ani.duration = 20 ani.repeatCount = MAXFLOAT //动画执行完毕就移除 ani.removedOnCompletion = false //将动画添加到图层 iconView.layer.addAnimation(ani, forKey: nil) } //登录按钮点击事件 func loginBtnClick(){ delegate?.loginBtnWillClick() } //注册按钮点击事件 func registerBtnClick(){ delegate?.registerBtnWillClick() } //初始化里面布局子控件 override init(frame: CGRect) { super.init(frame: frame) addSubview(iconView) addSubview(maskBGView) addSubview(homeIcon) addSubview(messageLabel) addSubview(loginBtn) addSubview(registerBtn) //设置背景 iconView.jk_AlignInner(type: JK_AlignType.Center, referView: self, size: nil) //设置小房子 homeIcon.jk_AlignInner(type: JK_AlignType.Center, referView: self, size: nil) //设置文本 messageLabel.jk_AlignVertical(type: JK_AlignType.BottomCenter, referView: iconView, size: nil) let widthCons = NSLayoutConstraint(item: messageLabel,attribute: NSLayoutAttribute.Width,relatedBy: NSLayoutRelation.Equal,toItem:nil,attribute:NSLayoutAttribute.NotAnAttribute,multiplier:1.0,constant:224) addConstraint(widthCons) //设置注册按钮 registerBtn.jk_AlignVertical(type: JK_AlignType.BottomLeft, referView: messageLabel, size: CGSize(width: 100, height: 30),offset: CGPoint(x: 0, y: 20)) //设置登录按钮 loginBtn.jk_AlignVertical(type:JK_AlignType.BottomRight, referView: messageLabel, size: CGSize(width: 100, height: 30),offset: CGPoint(x: 0, y: 20)) //设置蒙板 // mask maskBGView.jk_Fill(self) } //定义一个控件,要么是纯代码,要么是xib required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //懒加载控件 //转盘 private lazy var iconView:UIImageView = { let imageView = UIImageView(image: UIImage(named:"visitordiscover_feed_image_smallicon")) return imageView }() //图标 private lazy var homeIcon:UIImageView = { let imageView = UIImageView(image: UIImage(named:"visitordiscover_feed_image_house")) return imageView }() //文本 private lazy var messageLabel:UILabel = { let label = UILabel() label.numberOfLines = 0 label.textColor = UIColor.darkGrayColor() label.text = "测试测试测试测试测试测试测试测试测试" return label }() //登录按钮 private lazy var loginBtn:UIButton = { let btn = UIButton() btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState()) btn.setTitle("登录", forState: UIControlState()) btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: UIControlState()) btn.addTarget(self, action: #selector(JKVisitView.loginBtnClick), forControlEvents:UIControlEvents.TouchUpInside) return btn }() //注册按钮 private lazy var registerBtn:UIButton = { let btn = UIButton() btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState()) btn.setTitle("注册", forState: UIControlState()) btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: UIControlState()) btn.addTarget(self, action: #selector(JKVisitView.registerBtnClick), forControlEvents:UIControlEvents.TouchUpInside) return btn }() //背景图 private lazy var maskBGView:UIImageView = { let imageView = UIImageView(image: UIImage(named:"visitordiscover_feed_mask_smallicon")) return imageView }() }
6ca2b79cae1c577a093fa12c9e605f65
28.849673
213
0.630392
false
false
false
false
RyoAbe/PARTNER
refs/heads/master
PARTNER/PARTNER/UI/MainView/HistoryView/HistoryBaseCell.swift
gpl-3.0
1
// // HistoryCell.swift // PARTNER // // Created by RyoAbe on 2015/03/15. // Copyright (c) 2015年 RyoAbe. All rights reserved. // import UIKit class HistoryBaseCell: UITableViewCell { var prevStatus: Status! var nextStatus: Status! var currentStatus: Status! { didSet { if currentStatus == nil { return } textLabel!.text = currentStatus.types.statusType.name imageView!.image = UIImage(named: currentStatus.types.statusType.iconImageName) let fmt = NSDateFormatter() fmt.dateFormat = "yyyy/MM/dd HH:mm" detailTextLabel?.text = fmt.stringFromDate(currentStatus.date) setNeedsDisplay() } } override func awakeFromNib() { super.awakeFromNib() backgroundColor = UIColor.clearColor() if let textLabel = textLabel { textLabel.textColor = UIColor.blackColor() textLabel.font = UIFont.systemFontOfSize(12) } if let detailTextLabel = detailTextLabel { detailTextLabel.textColor = UIColor(white: 0.2, alpha: 1.000) detailTextLabel.font = UIFont.systemFontOfSize(10) } if let imageView = imageView { imageView.tintColor = UIColor.blackColor() } } var iconDiameter : CGFloat { return 30 } var iconRadius : CGFloat { return iconDiameter * 0.5 } var lineWidth : CGFloat { return 1 / UIScreen.mainScreen().scale } var lineColor : UIColor { return UIColor.blackColor() } var iconMargin : CGFloat { return 10 } var marginPointX : CGFloat { return 20 } var marginPointY : CGFloat { return 18 } override func layoutSubviews() { super.layoutSubviews() if let imageView = imageView { var f = imageView.frame f.size = CGSizeMake(iconDiameter, iconDiameter) f.origin.y = frame.size.height * 0.5 - f.size.height * 0.5 imageView.frame = f } } override func drawRect(rect: CGRect) { super.drawRect(rect) drawCircle() drawUpperLine() drawLowerLine() } func drawCircle() { var circle = UIBezierPath(ovalInRect:CGRectInset(imageView!.frame, -4, -4)) lineColor.setStroke() circle.lineWidth = lineWidth circle.stroke() } func drawUpperLine() { if prevStatus == nil { return } let isSameState = object_getClassName(prevStatus) == object_getClassName(currentStatus) let startPointX = isSameState ? imageView!.center.x : frame.size.width * 0.5 let startPoint = CGPointMake(startPointX, 0) let endPointY = isSameState ? CGRectGetMinY(imageView!.frame) - iconMargin : imageView!.center.y var endPoint = CGPointMake(imageView!.center.x, endPointY) if !isSameState { if currentStatus is MyStatus { let marginPoint = calcMarginPoint(startPoint, endPoint: endPoint) endPoint = CGPointMake(endPoint.x + marginPointX, endPoint.y - marginPointY) } else if currentStatus is PartnersStatus { endPoint = CGPointMake(endPoint.x - marginPointX, endPoint.y - marginPointY) } } drawLineWithStartPoint(startPoint, endPoint: endPoint) } func drawLowerLine() { if nextStatus == nil { return } let isSameState = object_getClassName(nextStatus) == object_getClassName(currentStatus) let startPointY = isSameState ? CGRectGetMaxY(imageView!.frame) + iconMargin : imageView!.center.y let endPointX = isSameState ? imageView!.center.x : frame.size.width * 0.5 var startPoint = CGPointMake(imageView!.center.x, startPointY) let endPoint = CGPointMake(endPointX, frame.size.height) if !isSameState { if currentStatus is MyStatus { startPoint = CGPointMake(startPoint.x + marginPointX, startPoint.y + marginPointY) } else if currentStatus is PartnersStatus { startPoint = CGPointMake(startPoint.x - marginPointX, startPoint.y + marginPointY) } } drawLineWithStartPoint(startPoint, endPoint: endPoint) } func calcMarginPoint(startPoint: CGPoint, endPoint: CGPoint) -> CGPoint { let x = endPoint.x - startPoint.x let y = endPoint.y - startPoint.y let radians = atan2f(Float(y), Float(x)) let degree = radians * Float(180 / M_PI) let marginY = CGFloat(Float(iconRadius + iconMargin) * sinf(degree)) let marginX = CGFloat(Float(iconRadius + iconMargin) * cosf(degree)) return CGPointMake(marginX, marginY) } func drawLineWithStartPoint(startPoint: CGPoint, endPoint: CGPoint){ var line = UIBezierPath() line.moveToPoint(startPoint) line.addLineToPoint(endPoint) lineColor.setStroke() line.lineWidth = lineWidth line.stroke(); } }
8c177f5804d4b12313f66d11b3b51fe5
34.25
106
0.616627
false
false
false
false
mattiasjahnke/arduino-projects
refs/heads/master
matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/SignalProvider.swift
mit
1
// // SignalProvider.swift // Flow // // Created by Måns Bernhardt on 2015-09-17. // Copyright © 2015 iZettle. All rights reserved. // import Foundation /// Allows conforming types to provide a default signal. /// By implementing signal transforms such as `map()` as extensions on `SignalProvider`, /// these transforms could be used directly on conforming types. /// /// extension UITextField: SignalProvider { ... } /// /// bag += textField.map { $0.isValidPassword }.onValue { isEnabled = $0 } /// /// As `CoreSignal` the base of `Signal`, `ReadSignal`, `ReadWriteSignal` and `FiniteSignal`, also conforms to `SignalProvider`, /// transforms should only be implemented on `SignalProvider`. /// /// extension SignalProvider { /// func map<T>(_ transform: @escaping (Value) -> T) -> CoreSignal<Kind.DropWrite, T> /// } public protocol SignalProvider { associatedtype Value /// What access (`Plain`, `Read`, `ReadWrite` or `Finite`) the provided signal has associatedtype Kind: SignalKind /// The signal used when doing transformation on conforming types. var providedSignal: CoreSignal<Kind, Value> { get } } /// Specifies the kind of a signal, `Plain`, `Read` or `ReadWrite`. public protocol SignalKind { associatedtype DropWrite: SignalKind /// The type of self without write access associatedtype DropReadWrite: SignalKind /// The type of self without read nor write access associatedtype PotentiallyRead: SignalKind // The type of self if self could become readable. } public extension SignalKind { static var isReadable: Bool { return DropWrite.self == Read.self } } /// A signal kind with no read nor write access public enum Plain: SignalKind { public typealias DropWrite = Plain public typealias DropReadWrite = Plain public typealias PotentiallyRead = Read } /// A signal kind with read access but no write access public enum Read: SignalKind { public typealias DropWrite = Read public typealias DropReadWrite = Plain public typealias PotentiallyRead = Read } /// A signal kind with both read and write access public enum ReadWrite: SignalKind { public typealias DropWrite = Read public typealias DropReadWrite = Plain public typealias PotentiallyRead = Read } /// A signal kind that can terminate public enum Finite: SignalKind { public typealias DropWrite = Finite public typealias DropReadWrite = Finite public typealias PotentiallyRead = Finite }
d6c284dbf8814c303ca224554a9fa27e
33.583333
128
0.717671
false
false
false
false
hugweb/StackBox
refs/heads/master
Example/StackBox/TableViewController.swift
mit
1
// // TableViewController.swift // PopStackView // // Created by Hugues Blocher on 31/05/2017. // Copyright © 2017 Hugues Blocher. All rights reserved. // import UIKit extension Array { @discardableResult mutating func shuffle() -> Array { for _ in 0..<((count>0) ? (count-1) : 0) { sort { (_,_) in arc4random() < arc4random() } } return self } } extension UIColor { static var random: UIColor { return UIColor(red: CGFloat(arc4random()) / CGFloat(UInt32.max), green: CGFloat(arc4random()) / CGFloat(UInt32.max), blue: CGFloat(arc4random()) / CGFloat(UInt32.max), alpha: 1.0) } } class TableViewController: UITableViewController { var options = ["Vertical Classic", "Vertical Random", "Vertical SnapKit", "Horizontal Classic", "Horizontal Random", "Horizontal SnapKit", "Horizontal Paginated Classic", "Horizontal Paginated Random", "Horizontal Paginated SnapKit", "Profile Screen", "Specific Index"] override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "UITableViewCell") cell.textLabel?.text = options[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: self.navigationController?.pushViewController(VerticalClassicController(), animated: true) case 1: self.navigationController?.pushViewController(VerticalRandomController(), animated: true) case 2: self.navigationController?.pushViewController(VerticalSnapController(), animated: true) case 3: self.navigationController?.pushViewController(HorizontalClassicController(), animated: true) case 4: self.navigationController?.pushViewController(HorizontalRandomController(), animated: true) case 5: self.navigationController?.pushViewController(HorizontalSnapController(), animated: true) case 6: let vc = HorizontalClassicController() vc.stack.isPagingEnabled = true self.navigationController?.pushViewController(vc, animated: true) case 7: let vc = HorizontalRandomController() vc.stack.isPagingEnabled = true self.navigationController?.pushViewController(vc, animated: true) case 8: let vc = HorizontalSnapController() vc.stack.isPagingEnabled = true self.navigationController?.pushViewController(vc, animated: true) case 9: self.navigationController?.pushViewController(ProfileController(), animated: true) case 10: self.navigationController?.pushViewController(VerticalSpecificIndexController(), animated: true) default: break } } }
dde1afedba1ebc1f9f677270ecc31f9e
38.892857
123
0.644882
false
false
false
false
Ehrippura/firefox-ios
refs/heads/master
Storage/SQL/SQLiteRemoteClientsAndTabs.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger import Deferred private let log = Logger.syncLogger open class SQLiteRemoteClientsAndTabs: RemoteClientsAndTabs { let db: BrowserDB public init(db: BrowserDB) { self.db = db } class func remoteClientFactory(_ row: SDRow) -> RemoteClient { let guid = row["guid"] as? String let name = row["name"] as! String let mod = (row["modified"] as! NSNumber).uint64Value let type = row["type"] as? String let form = row["formfactor"] as? String let os = row["os"] as? String let version = row["version"] as? String let fxaDeviceId = row["fxaDeviceId"] as? String return RemoteClient(guid: guid, name: name, modified: mod, type: type, formfactor: form, os: os, version: version, fxaDeviceId: fxaDeviceId) } class func remoteTabFactory(_ row: SDRow) -> RemoteTab { let clientGUID = row["client_guid"] as? String let url = URL(string: row["url"] as! String)! // TODO: find a way to make this less dangerous. let title = row["title"] as! String let history = SQLiteRemoteClientsAndTabs.convertStringToHistory(row["history"] as? String) let lastUsed = row.getTimestamp("last_used")! return RemoteTab(clientGUID: clientGUID, URL: url, title: title, history: history, lastUsed: lastUsed, icon: nil) } class func convertStringToHistory(_ history: String?) -> [URL] { if let data = history?.data(using: String.Encoding.utf8) { if let urlStrings = try! JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.allowFragments]) as? [String] { return optFilter(urlStrings.map { URL(string: $0) }) } } return [] } class func convertHistoryToString(_ history: [URL]) -> String? { let historyAsStrings = optFilter(history.map { $0.absoluteString }) let data = try! JSONSerialization.data(withJSONObject: historyAsStrings, options: []) return String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) } open func wipeClients() -> Success { return db.run("DELETE FROM \(TableClients)") } open func wipeRemoteTabs() -> Success { return db.run("DELETE FROM \(TableTabs) WHERE client_guid IS NOT NULL") } open func wipeTabs() -> Success { return db.run("DELETE FROM \(TableTabs)") } open func insertOrUpdateTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return self.insertOrUpdateTabsForClientGUID(nil, tabs: tabs) } open func insertOrUpdateTabsForClientGUID(_ clientGUID: String?, tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { let deleteQuery = "DELETE FROM \(TableTabs) WHERE client_guid IS ?" let deleteArgs: Args = [clientGUID] return db.transaction { connection -> Int in // Delete any existing tabs. try connection.executeChange(deleteQuery, withArgs: deleteArgs) // Insert replacement tabs. var inserted = 0 for tab in tabs { let args: Args = [ tab.clientGUID, tab.URL.absoluteString, tab.title, SQLiteRemoteClientsAndTabs.convertHistoryToString(tab.history), NSNumber(value: tab.lastUsed) ] let lastInsertedRowID = connection.lastInsertedRowID // We trust that each tab's clientGUID matches the supplied client! // Really tabs shouldn't have a GUID at all. Future cleanup! try connection.executeChange("INSERT INTO \(TableTabs) (client_guid, url, title, history, last_used) VALUES (?, ?, ?, ?, ?)", withArgs: args) if connection.lastInsertedRowID == lastInsertedRowID { log.debug("Unable to INSERT RemoteTab!") } else { inserted += 1 } } return inserted } } open func insertOrUpdateClients(_ clients: [RemoteClient]) -> Deferred<Maybe<Int>> { // TODO: insert multiple clients in a single query. // ORM systems are foolish. return db.transaction { connection -> Int in var succeeded = 0 // Update or insert client records. for client in clients { let args: Args = [ client.name, NSNumber(value: client.modified), client.type, client.formfactor, client.os, client.version, client.fxaDeviceId, client.guid ] try connection.executeChange("UPDATE \(TableClients) SET name = ?, modified = ?, type = ?, formfactor = ?, os = ?, version = ?, fxaDeviceId = ? WHERE guid = ?", withArgs: args) if connection.numberOfRowsModified == 0 { let args: Args = [ client.guid, client.name, NSNumber(value: client.modified), client.type, client.formfactor, client.os, client.version, client.fxaDeviceId ] let lastInsertedRowID = connection.lastInsertedRowID try connection.executeChange("INSERT INTO \(TableClients) (guid, name, modified, type, formfactor, os, version, fxaDeviceId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", withArgs: args) if connection.lastInsertedRowID == lastInsertedRowID { log.debug("INSERT did not change last inserted row ID.") } } succeeded += 1 } return succeeded } } open func insertOrUpdateClient(_ client: RemoteClient) -> Deferred<Maybe<Int>> { return insertOrUpdateClients([client]) } open func deleteClient(guid: GUID) -> Success { let deleteTabsQuery = "DELETE FROM \(TableTabs) WHERE client_guid = ?" let deleteClientQuery = "DELETE FROM \(TableClients) WHERE guid = ?" let deleteArgs: Args = [guid] return db.transaction { connection -> Void in try connection.executeChange(deleteClientQuery, withArgs: deleteArgs) try connection.executeChange(deleteTabsQuery, withArgs: deleteArgs) } } open func getClient(guid: GUID) -> Deferred<Maybe<RemoteClient?>> { let factory = SQLiteRemoteClientsAndTabs.remoteClientFactory return self.db.runQuery("SELECT * FROM \(TableClients) WHERE guid = ?", args: [guid], factory: factory) >>== { deferMaybe($0[0]) } } open func getClient(fxaDeviceId: String) -> Deferred<Maybe<RemoteClient?>> { let factory = SQLiteRemoteClientsAndTabs.remoteClientFactory return self.db.runQuery("SELECT * FROM \(TableClients) WHERE fxaDeviceId = ?", args: [fxaDeviceId], factory: factory) >>== { deferMaybe($0[0]) } } open func getClientWithId(_ clientID: GUID) -> Deferred<Maybe<RemoteClient?>> { return self.getClient(guid: clientID) } open func getClients() -> Deferred<Maybe<[RemoteClient]>> { return db.withConnection { connection -> [RemoteClient] in let cursor = connection.executeQuery("SELECT * FROM \(TableClients) WHERE EXISTS (SELECT 1 FROM \(TableRemoteDevices) rd WHERE rd.guid = fxaDeviceId) ORDER BY modified DESC", factory: SQLiteRemoteClientsAndTabs.remoteClientFactory) defer { cursor.close() } return cursor.asArray() } } open func getClientGUIDs() -> Deferred<Maybe<Set<GUID>>> { let c = db.runQuery("SELECT guid FROM \(TableClients) WHERE guid IS NOT NULL", args: nil, factory: { $0["guid"] as! String }) return c >>== { cursor in let guids = Set<GUID>(cursor.asArray()) return deferMaybe(guids) } } open func getTabsForClientWithGUID(_ guid: GUID?) -> Deferred<Maybe<[RemoteTab]>> { let tabsSQL: String let clientArgs: Args? if let _ = guid { tabsSQL = "SELECT * FROM \(TableTabs) WHERE client_guid = ?" clientArgs = [guid] } else { tabsSQL = "SELECT * FROM \(TableTabs) WHERE client_guid IS NULL" clientArgs = nil } log.debug("Looking for tabs for client with guid: \(guid ?? "nil")") return db.runQuery(tabsSQL, args: clientArgs, factory: SQLiteRemoteClientsAndTabs.remoteTabFactory) >>== { let tabs = $0.asArray() log.debug("Found \(tabs.count) tabs for client with guid: \(guid ?? "nil")") return deferMaybe(tabs) } } open func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return db.withConnection { conn -> ([RemoteClient], [RemoteTab]) in let clientsCursor = conn.executeQuery("SELECT * FROM \(TableClients) WHERE EXISTS (SELECT 1 FROM \(TableRemoteDevices) rd WHERE rd.guid = fxaDeviceId) ORDER BY modified DESC", factory: SQLiteRemoteClientsAndTabs.remoteClientFactory) let tabsCursor = conn.executeQuery("SELECT * FROM \(TableTabs) WHERE client_guid IS NOT NULL ORDER BY client_guid DESC, last_used DESC", factory: SQLiteRemoteClientsAndTabs.remoteTabFactory) defer { clientsCursor.close() tabsCursor.close() } return (clientsCursor.asArray(), tabsCursor.asArray()) } >>== { clients, tabs in var acc = [String: [RemoteTab]]() for tab in tabs { if let guid = tab.clientGUID { if acc[guid] == nil { acc[guid] = [tab] } else { acc[guid]!.append(tab) } } else { log.error("RemoteTab (\(tab)) has a nil clientGUID") } } // Most recent first. let fillTabs: (RemoteClient) -> ClientAndTabs = { client in var tabs: [RemoteTab]? = nil if let guid: String = client.guid { tabs = acc[guid] } return ClientAndTabs(client: client, tabs: tabs ?? []) } return deferMaybe(clients.map(fillTabs)) } } open func deleteCommands() -> Success { return db.run("DELETE FROM \(TableSyncCommands)") } open func deleteCommands(_ clientGUID: GUID) -> Success { return db.run("DELETE FROM \(TableSyncCommands) WHERE client_guid = ?", withArgs: [clientGUID] as Args) } open func insertCommand(_ command: SyncCommand, forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>> { return insertCommands([command], forClients: clients) } open func insertCommands(_ commands: [SyncCommand], forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>> { return db.transaction { connection -> Int in var numberOfInserts = 0 // Update or insert client records. for command in commands { for client in clients { do { if let commandID = try self.insert(connection, sql: "INSERT INTO \(TableSyncCommands) (client_guid, value) VALUES (?, ?)", args: [client.guid, command.value] as Args) { log.verbose("Inserted command: \(commandID)") numberOfInserts += 1 } else { log.warning("Command not inserted, but no error!") } } catch let err as NSError { log.error("insertCommands(_:, forClients:) failed: \(err.localizedDescription) (numberOfInserts: \(numberOfInserts)") throw err } } } return numberOfInserts } } open func getCommands() -> Deferred<Maybe<[GUID: [SyncCommand]]>> { return db.withConnection { connection -> [GUID: [SyncCommand]] in let cursor = connection.executeQuery("SELECT * FROM \(TableSyncCommands)", factory: { row -> SyncCommand in SyncCommand( id: row["command_id"] as? Int, value: row["value"] as! String, clientGUID: row["client_guid"] as? GUID) }) defer { cursor.close() } return self.clientsFromCommands(cursor.asArray()) } } func clientsFromCommands(_ commands: [SyncCommand]) -> [GUID: [SyncCommand]] { var syncCommands = [GUID: [SyncCommand]]() for command in commands { var cmds: [SyncCommand] = syncCommands[command.clientGUID!] ?? [SyncCommand]() cmds.append(command) syncCommands[command.clientGUID!] = cmds } return syncCommands } func insert(_ db: SQLiteDBConnection, sql: String, args: Args?) throws -> Int? { let lastID = db.lastInsertedRowID try db.executeChange(sql, withArgs: args) let id = db.lastInsertedRowID if id == lastID { log.debug("INSERT did not change last inserted row ID.") return nil } return id } } extension SQLiteRemoteClientsAndTabs: RemoteDevices { open func replaceRemoteDevices(_ remoteDevices: [RemoteDevice]) -> Success { // Drop corrupted records and our own record too. let remoteDevices = remoteDevices.filter { $0.id != nil && $0.type != nil && !$0.isCurrentDevice } return db.transaction { conn -> Void in try conn.executeChange("DELETE FROM \(TableRemoteDevices)") let now = Date.now() for device in remoteDevices { let sql = "INSERT INTO \(TableRemoteDevices) (guid, name, type, is_current_device, date_created, date_modified, last_access_time) " + "VALUES (?, ?, ?, ?, ?, ?, ?)" let args: Args = [device.id, device.name, device.type, device.isCurrentDevice, now, now, device.lastAccessTime] try conn.executeChange(sql, withArgs: args) } } } } extension SQLiteRemoteClientsAndTabs: ResettableSyncStorage { public func resetClient() -> Success { // For this engine, resetting is equivalent to wiping. return self.clear() } public func clear() -> Success { return db.transaction { conn -> Void in try conn.executeChange("DELETE FROM \(TableTabs) WHERE client_guid IS NOT NULL") try conn.executeChange("DELETE FROM \(TableClients)") } } } extension SQLiteRemoteClientsAndTabs: AccountRemovalDelegate { public func onRemovedAccount() -> Success { log.info("Clearing clients and tabs after account removal.") // TODO: Bug 1168690 - delete our client and tabs records from the server. return self.resetClient() } }
f245c33c0625b30918f80b9b1bc2771e
40.392105
244
0.567932
false
false
false
false
sonsongithub/numsw
refs/heads/master
Tests/numswTests/NDArrayTests/NDArraySubscriptTests.swift
mit
1
import XCTest @testable import numsw class NDArraySubscriptTests: XCTestCase { func testSubscriptGetElement() { let x = NDArray<Int>(shape: [3, 2], elements: [1, 2, 3, 4, 5, 6]) // normal access XCTAssertEqual(x[0, 0], 1) XCTAssertEqual(x[0, 1], 2) XCTAssertEqual(x[1, 0], 3) XCTAssertEqual(x[1, 1], 4) XCTAssertEqual(x[2, 0], 5) XCTAssertEqual(x[2, 1], 6) // minus index access XCTAssertEqual(x[-3, -2], 1) XCTAssertEqual(x[-3, -1], 2) XCTAssertEqual(x[-2, -2], 3) XCTAssertEqual(x[-2, -1], 4) XCTAssertEqual(x[-1, -2], 5) XCTAssertEqual(x[-1, -1], 6) } func testSubscriptSetElement() { var x = NDArray<Int>(shape: [3, 2], elements: [1, 2, 3, 4, 5, 6]) x[0, 0] = -1 XCTAssertEqual(x, NDArray<Int>(shape: [3, 2], elements: [-1, 2, 3, 4, 5, 6])) x[-1, -1] = -2 XCTAssertEqual(x, NDArray<Int>(shape: [3, 2], elements: [-1, 2, 3, 4, 5, -2])) } func testSubscriptGetSubarray() { let x = NDArray<Int>(shape: [3, 2], elements: [1, 2, 3, 4, 5, 6]) // get subarray XCTAssertEqual(x[[0, 1], [0, 1]], NDArray(shape: [2, 2], elements: [1, 2, 3, 4])) XCTAssertEqual(x[0..<2, 0..<2], NDArray(shape: [2, 2], elements: [1, 2, 3, 4])) // auto fulfill XCTAssertEqual(x[[0]], NDArray(shape: [1, 2], elements: [1, 2])) XCTAssertEqual(x[[-3]], NDArray(shape: [1, 2], elements: [1, 2])) XCTAssertEqual(x[0..<1], NDArray(shape: [1, 2], elements: [1, 2])) XCTAssertEqual(x[(-3)..<(-2)], NDArray(shape: [1, 2], elements: [1, 2])) // nil means numpy's `:` XCTAssertEqual(x[nil, [0]], NDArray(shape: [3, 1], elements: [1, 3, 5])) } func testSubscriptSetSubarray() { var x = NDArray<Int>(shape: [3, 2], elements: [1, 2, 3, 4, 5, 6]) x[[-3]] = NDArray(shape: [1, 2], elements: [0, 0]) XCTAssertEqual(x, NDArray<Int>(shape: [3, 2], elements: [0, 0, 3, 4, 5, 6])) x[nil, [0]] = NDArray(shape: [3, 1], elements: [0, 0, 0]) XCTAssertEqual(x, NDArray(shape: [3, 2], elements: [0, 0, 0, 4, 0, 6])) } static var allTests: [(String, (NDArraySubscriptTests) -> () throws -> Void)] { return [ ("testSubscriptGetElement", testSubscriptGetElement), ("testSubscriptSetElement", testSubscriptSetElement), ("testSubscriptGetSubarray", testSubscriptGetSubarray), ("testSubscriptSetSubarray", testSubscriptSetSubarray) ] } }
6ca2a20d0a3e02216419a56d6e3cf300
37.565217
89
0.520857
false
true
false
false
anhnc55/fantastic-swift-library
refs/heads/master
Example/Example/AppDelegate.swift
mit
1
// // AppDelegate.swift // Example // // Created by AnhNC on 6/2/16. // Copyright © 2016 AnhNC. All rights reserved. // import UIKit import Material @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let navigationController: AppNavigationController = AppNavigationController(rootViewController: RecipesViewController()) let menuController: AppMenuController = AppMenuController(rootViewController: navigationController) menuController.edgesForExtendedLayout = .None let bottomNavigationController: BottomNavigationController = BottomNavigationController() bottomNavigationController.viewControllers = [menuController, VideoViewController(), PhotoViewController()] bottomNavigationController.selectedIndex = 0 bottomNavigationController.tabBar.tintColor = MaterialColor.white bottomNavigationController.tabBar.backgroundColor = MaterialColor.grey.darken4 let sideNavigationController: SideNavigationController = SideNavigationController(rootViewController: bottomNavigationController, leftViewController: AppLeftViewController()) sideNavigationController.statusBarStyle = .LightContent window = UIWindow(frame: UIScreen.mainScreen().bounds) window!.rootViewController = sideNavigationController window!.makeKeyAndVisible() 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:. } }
88def310659657ec06e5f0f1587b5d36
55.137931
285
0.757985
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/swift-sdk/Source/AssistantV1/Models/UpdateIntent.swift
mit
2
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** UpdateIntent. */ public struct UpdateIntent: Encodable { /// The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. public var intent: String? /// The description of the intent. public var description: String? /// An array of user input examples for the intent. public var examples: [CreateExample]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case intent = "intent" case description = "description" case examples = "examples" } /** Initialize a `UpdateIntent` with member variables. - parameter intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. - parameter description: The description of the intent. - parameter examples: An array of user input examples for the intent. - returns: An initialized `UpdateIntent`. */ public init(intent: String? = nil, description: String? = nil, examples: [CreateExample]? = nil) { self.intent = intent self.description = description self.examples = examples } }
e2be326fec1a04e47b1d3d9657d0aabd
39.716981
286
0.7076
false
false
false
false
keyeMyria/edx-app-ios
refs/heads/master
Source/Result+JSON.swift
apache-2.0
4
// // Result+JSON.swift // edX // // Created by Akiva Leffert on 6/23/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation extension Result { init(jsonData : NSData?, error : NSError? = nil, constructor: JSON -> A?) { if let data = jsonData, json : AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: nil), result = constructor(JSON(json)) { self = Success(Box(result)) } else { self = Failure(error ?? NSError.oex_unknownError()) } } }
3d4f0f6cc53534c74983e7f76f921780
25.304348
121
0.584437
false
false
false
false
sleekbyte/tailor
refs/heads/master
src/test/swift/com/sleekbyte/tailor/grammar/Initialization.swift
mit
1
struct Fahrenheit { var temperature: Double init() { temperature = 32.0 } } struct Fahrenheit { var temperature = 32.0 } struct Celsius { var temperatureInCelsius: Double init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin - 273.15 } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) struct Color { let red, green, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } init(white: Double) { red = white green = white blue = white } } struct Celsius { var temperatureInCelsius: Double init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin - 273.15 } init(_ celsius: Double) { temperatureInCelsius = celsius } } class SurveyQuestion { var text: String var response: String? init(text: String) { self.text = text } func ask() { print(text) } } let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?") class SurveyQuestion { let text: String var response: String? init(text: String) { self.text = text } func ask() { print(text) } } struct Rect { var origin = Point() var size = Size() init() {} init(origin: Point, size: Size) { self.origin = origin self.size = size } init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } let originRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { self.init(name: name, quantity: 1) } } var breakfastList = [ ShoppingListItem(), ShoppingListItem(name: "Bacon"), ShoppingListItem(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } if let giraffe = someCreature { print("An animal was initialized with a species of \(giraffe.species)") } if anonymousCreature == nil { print("The anonymous creature could not be initialized") } enum TemperatureUnit { case Kelvin, Celsius, Fahrenheit init?(symbol: Character) { switch symbol { case "K": self = .Kelvin case "C": self = .Celsius case "F": self = .Fahrenheit default: return nil } } } class CartItem: Product { let quantity: Int! init?(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) if quantity < 1 { return nil } } } if let twoSocks = CartItem(name: "sock", quantity: 2) { print("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)") } class AutomaticallyNamedDocument: Document { override init() { super.init() self.name = "[Untitled]" } override init(name: String) { super.init() if name.isEmpty { self.name = "[Untitled]" } else { self.name = name } } } class SomeSubclass: SomeClass { required init() { // subclass implementation of the required initializer goes here } } struct Celsius { var temperatureInCelsius: Double init(fromFahrenheit fahrenheit: Double) throws { temperatureInCelsius = (fahrenheit - 32.0) / 1.8 } init(_ celsius: Double) { temperatureInCelsius = celsius } }
b8f717518465af67cd5e165d0cef0d05
20.645631
75
0.588473
false
false
false
false
josve05a/wikipedia-ios
refs/heads/develop
Wikipedia/Code/IconBarButtonItem.swift
mit
2
import UIKit class IconBarButtonItem: UIBarButtonItem { private var theme: Theme? @objc convenience init(iconName: String, target: Any?, action: Selector, for controlEvents: UIControl.Event) { let image = UIImage(named: iconName) let customView = UIButton(type: .system) customView.setImage(image, for: .normal) customView.addTarget(target, action: action, for: controlEvents) customView.adjustsImageWhenDisabled = false self.init(customView: customView) } override var isEnabled: Bool { get { return super.isEnabled } set { super.isEnabled = newValue if let theme = theme { apply(theme: theme) } } } } extension IconBarButtonItem: Themeable { public func apply(theme: Theme) { self.theme = theme if let customView = customView as? UIButton { customView.tintColor = isEnabled ? theme.colors.link : theme.colors.disabledLink } else { tintColor = isEnabled ? theme.colors.link : theme.colors.disabledLink } } }
067f20d8dd5ca94ac99b44ff0926f455
30.297297
114
0.606218
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/ViewModels/FindFriendsFriendFollowCellViewModel.swift
apache-2.0
1
import Foundation import KsApi import Prelude import ReactiveExtensions import ReactiveSwift public protocol FindFriendsFriendFollowCellViewModelInputs { /// Call to set friend from whence it comes func configureWith(friend: User) /// Call when follow friend button is tapped func followButtonTapped() /// Call when unfollow friend button is tapped func unfollowButtonTapped() } public protocol FindFriendsFriendFollowCellViewModelOutputs { /// Emits accessibilityValue for the Cell var cellAccessibilityValue: Signal<String, Never> { get } /// Emits whether Follow button should be enabled var enableFollowButton: Signal<Bool, Never> { get } /// Emits whether Unfollow button should be enabled var enableUnfollowButton: Signal<Bool, Never> { get } // Emits follow button accessibilityLabel that includes friend's name var followButtonAccessibilityLabel: Signal<String, Never> { get } /// Emits when to show Follow button var hideFollowButton: Signal<Bool, Never> { get } /// Emits whether should show projects created text var hideProjectsCreated: Signal<Bool, Never> { get } /// Emits when to show Unfollow button var hideUnfollowButton: Signal<Bool, Never> { get } /// Emits an URL to friend's avatar var imageURL: Signal<URL?, Never> { get } /// Emits friend's location var location: Signal<String, Never> { get } /// Emits friend's name var name: Signal<String, Never> { get } /// Emits number of projects backed text var projectsBackedText: Signal<String, Never> { get } /// Emits number of projects created text var projectsCreatedText: Signal<String, Never> { get } // Emits unfollow button accessibilityLabel that includes friend's name var unfollowButtonAccessibilityLabel: Signal<String, Never> { get } } public protocol FindFriendsFriendFollowCellViewModelType { var inputs: FindFriendsFriendFollowCellViewModelInputs { get } var outputs: FindFriendsFriendFollowCellViewModelOutputs { get } } public final class FindFriendsFriendFollowCellViewModel: FindFriendsFriendFollowCellViewModelType, FindFriendsFriendFollowCellViewModelInputs, FindFriendsFriendFollowCellViewModelOutputs { public init() { let friend: Signal<User, Never> = self.configureWithFriendProperty.signal.skipNil() .map(cached(friend:)) self.imageURL = friend.map { (friend: User) -> URL? in URL(string: friend.avatar.medium) } self.location = friend.map { (friend: User) -> String in friend.location?.displayableName ?? "" } self.name = friend.map { (friend: User) -> String in friend.name } self.projectsBackedText = friend .map { (friend: User) -> Int in friend.stats.backedProjectsCount ?? 0 } .map(Strings.social_following_friend_projects_count_backed(backed_count:)) let projectsCreatedCount: Signal<Int, Never> = friend.map { (friend: User) -> Int in friend.stats.createdProjectsCount ?? 0 } self.hideProjectsCreated = projectsCreatedCount.map { (count: Int) -> Bool in count == 0 } self.projectsCreatedText = projectsCreatedCount .filter { $0 > 0 } .map(Strings.social_following_friend_projects_count_created(created_count:)) let isLoadingFollowRequest: MutableProperty<Bool> = MutableProperty(false) let isLoadingUnfollowRequest: MutableProperty<Bool> = MutableProperty(false) let followFriendEvent: Signal<Signal<User, ErrorEnvelope>.Event, Never> = friend .takeWhen(self.followButtonTappedProperty.signal) .switchMap { user in AppEnvironment.current.apiService.followFriend(userId: user.id) .on( starting: { isLoadingFollowRequest.value = true }, terminated: { isLoadingFollowRequest.value = false } ) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .mapConst(user |> \.isFriend .~ true) .materialize() } let unfollowFriendEvent: Signal<Signal<User, ErrorEnvelope>.Event, Never> = friend .takeWhen(self.unfollowButtonTappedProperty.signal) .switchMap { user in AppEnvironment.current.apiService.unfollowFriend(userId: user.id) .on( starting: { isLoadingUnfollowRequest.value = true }, terminated: { isLoadingUnfollowRequest.value = false } ) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .mapConst(user |> \.isFriend .~ false) .materialize() } let updatedFriendToFollowed: Signal<User, Never> = followFriendEvent.values() .on(value: { (friend: User) -> Void in cache(friend: friend, isFriend: true) }) let updatedFriendToUnfollowed: Signal<User, Never> = unfollowFriendEvent.values() .on(value: { (friend: User) -> Void in cache(friend: friend, isFriend: false) }) let isFollowed: Signal<Bool, Never> = Signal.merge( friend, updatedFriendToFollowed, updatedFriendToUnfollowed ) .map { $0.isFriend ?? false } self.hideFollowButton = isFollowed.skipRepeats() self.hideUnfollowButton = isFollowed.map(negate).skipRepeats() self.enableFollowButton = Signal.merge( self.hideFollowButton.map(negate), isLoadingFollowRequest.signal.map(negate) ) .skipRepeats() self.enableUnfollowButton = Signal.merge( self.hideUnfollowButton.map(negate), isLoadingUnfollowRequest.signal.map(negate) ) .skipRepeats() self.followButtonAccessibilityLabel = self.name.map(Strings.Follow_friend_name) self.unfollowButtonAccessibilityLabel = self.name.map(Strings.Unfollow_friend_name) self.cellAccessibilityValue = isFollowed.map { $0 ? Strings.Followed() : Strings.Not_followed() } } public var inputs: FindFriendsFriendFollowCellViewModelInputs { return self } public var outputs: FindFriendsFriendFollowCellViewModelOutputs { return self } fileprivate let configureWithFriendProperty = MutableProperty<User?>(nil) public func configureWith(friend: User) { self.configureWithFriendProperty.value = friend } fileprivate let followButtonTappedProperty = MutableProperty(()) public func followButtonTapped() { self.followButtonTappedProperty.value = () } fileprivate let unfollowButtonTappedProperty = MutableProperty(()) public func unfollowButtonTapped() { self.unfollowButtonTappedProperty.value = () } public let cellAccessibilityValue: Signal<String, Never> public let enableFollowButton: Signal<Bool, Never> public let enableUnfollowButton: Signal<Bool, Never> public let followButtonAccessibilityLabel: Signal<String, Never> public let hideFollowButton: Signal<Bool, Never> public let hideProjectsCreated: Signal<Bool, Never> public let hideUnfollowButton: Signal<Bool, Never> public let imageURL: Signal<URL?, Never> public let location: Signal<String, Never> public let name: Signal<String, Never> public let projectsBackedText: Signal<String, Never> public let projectsCreatedText: Signal<String, Never> public let unfollowButtonAccessibilityLabel: Signal<String, Never> } private func cached(friend: User) -> User { if let friendCache = AppEnvironment.current.cache[KSCache.ksr_findFriendsFollowing] as? [Int: Bool] { let isFriend = friendCache[friend.id] ?? friend.isFriend return friend |> \.isFriend .~ isFriend } else { return friend } } private func cache(friend: User, isFriend: Bool) { AppEnvironment.current.cache[KSCache.ksr_findFriendsFollowing] = AppEnvironment.current.cache[KSCache.ksr_findFriendsFollowing] ?? [Int: Bool]() var cache = AppEnvironment.current.cache[KSCache.ksr_findFriendsFollowing] as? [Int: Bool] cache?[friend.id] = isFriend AppEnvironment.current.cache[KSCache.ksr_findFriendsFollowing] = cache }
b570697dff7b9ba14c1d3e863006471e
36.473934
103
0.722777
false
false
false
false
2briancox/ioscreator
refs/heads/master
IOS8SwiftHeaderFooterTutorial/IOS8SwiftHeaderFooterTutorial/TableViewController.swift
mit
38
// // TableViewController.swift // IOS8SwiftHeaderFooterTutorial // // Created by Arthur Knopper on 09/12/14. // Copyright (c) 2014 Arthur Knopper. All rights reserved. // import UIKit class TableViewController: UITableViewController { var countriesinEurope = ["France","Spain","Germany"] var countriesinAsia = ["Japan","China","India"] var countriesInSouthAmerica = ["Argentia","Brasil","Chile"] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // 1 // Return the number of sections. return 3 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 2 return 3 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell // 3 // Configure the cell... switch (indexPath.section) { case 0: cell.textLabel?.text = countriesinEurope[indexPath.row] case 1: cell.textLabel?.text = countriesinAsia[indexPath.row] case 2: cell.textLabel?.text = countriesInSouthAmerica[indexPath.row] //return sectionHeaderView default: cell.textLabel?.text = "Other" } return cell } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell headerCell.backgroundColor = UIColor.cyanColor() switch (section) { case 0: headerCell.headerLabel.text = "Europe"; //return sectionHeaderView case 1: headerCell.headerLabel.text = "Asia"; //return sectionHeaderView case 2: headerCell.headerLabel.text = "South America"; //return sectionHeaderView default: headerCell.headerLabel.text = "Other"; } return headerCell } override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40)) footerView.backgroundColor = UIColor.blackColor() return footerView } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 40.0 } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
1ea2ce58c5e98345b137243067dc4829
30.20979
157
0.674658
false
false
false
false
fewspider/OAuthSwift
refs/heads/master
OAuthSwift/OAuthSwiftHTTPRequest.swift
mit
3
// // OAuthSwiftHTTPRequest.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation public class OAuthSwiftHTTPRequest: NSObject, NSURLSessionDelegate { public typealias SuccessHandler = (data: NSData, response: NSHTTPURLResponse) -> Void public typealias FailureHandler = (error: NSError) -> Void public enum Method: String { case GET, POST, PUT, DELETE, PATCH, HEAD //, OPTIONS, TRACE, CONNECT var isBody: Bool { return self == .POST || self == .PUT || self == .PATCH } } var URL: NSURL var HTTPMethod: Method var HTTPBody: NSData? var request: NSMutableURLRequest? var session: NSURLSession! var headers: Dictionary<String, String> var parameters: Dictionary<String, AnyObject> var dataEncoding: NSStringEncoding var charset: CFString { return CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.dataEncoding)) } var timeoutInterval: NSTimeInterval var HTTPShouldHandleCookies: Bool var response: NSHTTPURLResponse! var responseData: NSMutableData var successHandler: SuccessHandler? var failureHandler: FailureHandler? convenience init(URL: NSURL) { self.init(URL: URL, method: .GET, parameters: [:]) } init(URL: NSURL, method: Method, parameters: Dictionary<String, AnyObject>) { self.URL = URL self.HTTPMethod = method self.headers = [:] self.parameters = parameters self.dataEncoding = NSUTF8StringEncoding self.timeoutInterval = 60 self.HTTPShouldHandleCookies = false self.responseData = NSMutableData() } init(request: NSURLRequest) { self.request = request as? NSMutableURLRequest self.URL = request.URL! self.HTTPMethod = Method(rawValue: request.HTTPMethod ?? "") ?? .GET self.headers = [:] self.parameters = [:] self.dataEncoding = NSUTF8StringEncoding self.timeoutInterval = 60 self.HTTPShouldHandleCookies = false self.responseData = NSMutableData() } func start() { if (request == nil) { var error: NSError? do { self.request = try self.makeRequest() } catch let error1 as NSError { error = error1 self.request = nil } if ((error) != nil) { print(error!.localizedDescription) } } dispatch_async(dispatch_get_main_queue(), { self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue()) let task: NSURLSessionDataTask = self.session.dataTaskWithRequest(self.request!) { [unowned self] data, response, error -> Void in #if os(iOS) #if !OAUTH_APP_EXTENSIONS UIApplication.sharedApplication().networkActivityIndicatorVisible = false #endif #endif guard error == nil else { self.failureHandler?(error: error!) return } guard response != nil && (response as? NSHTTPURLResponse) != nil && data != nil else { let responseString = NSString(data: self.responseData, encoding: self.dataEncoding) let localizedDescription = OAuthSwiftHTTPRequest.descriptionForHTTPStatus(self.response.statusCode, responseString: responseString! as String) let userInfo : [NSObject : AnyObject] = [NSLocalizedDescriptionKey: localizedDescription, "Response-Headers": self.response.allHeaderFields] let error = NSError(domain: NSURLErrorDomain, code: self.response.statusCode, userInfo: userInfo) self.failureHandler?(error: error) return } self.response = response as? NSHTTPURLResponse self.responseData.length = 0 self.responseData.appendData(data!) if (response as? NSHTTPURLResponse)?.statusCode >= 400 { let responseString = NSString(data: self.responseData, encoding: self.dataEncoding) let localizedDescription = OAuthSwiftHTTPRequest.descriptionForHTTPStatus(self.response.statusCode, responseString: responseString! as String) let userInfo : [NSObject : AnyObject] = [NSLocalizedDescriptionKey: localizedDescription, "Response-Headers": self.response.allHeaderFields] let error = NSError(domain: NSURLErrorDomain, code: self.response.statusCode, userInfo: userInfo) self.failureHandler?(error: error) return } self.successHandler?(data: self.responseData, response: self.response) } task.resume() #if os(iOS) #if !OAUTH_APP_EXTENSIONS UIApplication.sharedApplication().networkActivityIndicatorVisible = true #endif #endif }) } public func makeRequest() throws -> NSMutableURLRequest { return try OAuthSwiftHTTPRequest.makeRequest(self.URL, method: self.HTTPMethod, headers: self.headers, parameters: self.parameters, dataEncoding: self.dataEncoding, body: self.HTTPBody) } public class func makeRequest( URL: NSURL, method: Method, headers: [String : String], parameters: Dictionary<String, AnyObject>, dataEncoding: NSStringEncoding, body: NSData? = nil) throws -> NSMutableURLRequest { let request = NSMutableURLRequest(URL: URL) request.HTTPMethod = method.rawValue return try setupRequestForOAuth(request, headers: headers, parameters: parameters, dataEncoding: dataEncoding, body: body) } public class func setupRequestForOAuth(request: NSMutableURLRequest, headers: [String : String], parameters: Dictionary<String, AnyObject>, dataEncoding: NSStringEncoding, body: NSData? = nil) throws -> NSMutableURLRequest { for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(dataEncoding)) let nonOAuthParameters = parameters.filter { key, _ in !key.hasPrefix("oauth_") } if let b = body { request.HTTPBody = b } else { if nonOAuthParameters.count > 0 { if request.HTTPMethod == "GET" || request.HTTPMethod == "HEAD" || request.HTTPMethod == "DELETE" { let queryString = nonOAuthParameters.urlEncodedQueryStringWithEncoding(dataEncoding) let URL = request.URL! request.URL = URL.URLByAppendingQueryString(queryString) if headers["Content-Type"] == nil { request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type") } } else { if let contentType = headers["Content-Type"] where contentType.rangeOfString("application/json") != nil { let jsonData: NSData = try NSJSONSerialization.dataWithJSONObject(nonOAuthParameters, options: []) request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type") request.HTTPBody = jsonData } else { request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type") let queryString = nonOAuthParameters.urlEncodedQueryStringWithEncoding(dataEncoding) request.HTTPBody = queryString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) } } } } return request } class func stringWithData(data: NSData, encodingName: String?) -> String { var encoding: UInt = NSUTF8StringEncoding if (encodingName != nil) { let encodingNameString = encodingName! as NSString encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingNameString)) if encoding == UInt(kCFStringEncodingInvalidId) { encoding = NSUTF8StringEncoding // by default } } return NSString(data: data, encoding: encoding)! as String } class func descriptionForHTTPStatus(status: Int, responseString: String) -> String { var s = "HTTP Status \(status)" var description: String? // http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml if status == 400 { description = "Bad Request" } if status == 401 { description = "Unauthorized" } if status == 402 { description = "Payment Required" } if status == 403 { description = "Forbidden" } if status == 404 { description = "Not Found" } if status == 405 { description = "Method Not Allowed" } if status == 406 { description = "Not Acceptable" } if status == 407 { description = "Proxy Authentication Required" } if status == 408 { description = "Request Timeout" } if status == 409 { description = "Conflict" } if status == 410 { description = "Gone" } if status == 411 { description = "Length Required" } if status == 412 { description = "Precondition Failed" } if status == 413 { description = "Payload Too Large" } if status == 414 { description = "URI Too Long" } if status == 415 { description = "Unsupported Media Type" } if status == 416 { description = "Requested Range Not Satisfiable" } if status == 417 { description = "Expectation Failed" } if status == 422 { description = "Unprocessable Entity" } if status == 423 { description = "Locked" } if status == 424 { description = "Failed Dependency" } if status == 425 { description = "Unassigned" } if status == 426 { description = "Upgrade Required" } if status == 427 { description = "Unassigned" } if status == 428 { description = "Precondition Required" } if status == 429 { description = "Too Many Requests" } if status == 430 { description = "Unassigned" } if status == 431 { description = "Request Header Fields Too Large" } if status == 432 { description = "Unassigned" } if status == 500 { description = "Internal Server Error" } if status == 501 { description = "Not Implemented" } if status == 502 { description = "Bad Gateway" } if status == 503 { description = "Service Unavailable" } if status == 504 { description = "Gateway Timeout" } if status == 505 { description = "HTTP Version Not Supported" } if status == 506 { description = "Variant Also Negotiates" } if status == 507 { description = "Insufficient Storage" } if status == 508 { description = "Loop Detected" } if status == 509 { description = "Unassigned" } if status == 510 { description = "Not Extended" } if status == 511 { description = "Network Authentication Required" } if (description != nil) { s = s + ": " + description! + ", Response: " + responseString } return s } }
22d635b5801c4e648095a1b9cc00e566
43.20073
193
0.596895
false
false
false
false
openbuild-sheffield/jolt
refs/heads/master
Sources/RouteCMS/route.CMSMarkdownAdd.swift
gpl-2.0
1
import Foundation import PerfectLib import PerfectHTTP import OpenbuildExtensionCore import OpenbuildExtensionPerfect import OpenbuildMysql import OpenbuildRepository import OpenbuildRouteRegistry import OpenbuildSingleton import Markdown public class RequestCMSMarkdownAdd: OpenbuildExtensionPerfect.RequestProtocol { public var method: String public var uri: String public var description: String = "Add a CMS markdown item." public var validation: OpenbuildExtensionPerfect.RequestValidation public init(method: String, uri: String){ self.method = method self.uri = uri self.validation = OpenbuildExtensionPerfect.RequestValidation() self.validation.addValidators(validators: [ ValidateTokenRoles, ValidateBodyHandle, ValidateBodyMarkdown ]) } } public let handlerRouteCMSMarkdownAdd = { (request: HTTPRequest, response: HTTPResponse) in guard let handlerResponse = RouteRegistry.getHandlerResponse( uri: request.path.lowercased(), method: request.method, response: response ) else { return } do { let mdString = request.validatedRequestData?.validated["markdown"] as! String //FIXME - This is a hack to updated clients don't send new lines properly... let mdStringNL = mdString.replacingOccurrences(of: "\\n", with: "\n", options: .literal, range: nil) let md = try Markdown( string: mdStringNL ) let html = try md.document() var repository = try RepositoryCMSMarkdown() var model = ModelCMSMarkdown( handle: request.validatedRequestData?.validated["handle"] as! String, markdown: mdString, html: html ) let entity = repository.create( model: model ) if entity.errors.isEmpty { //Success handlerResponse.complete( status: 200, model: ModelCMSMarkdown200Entity(entity: entity) ) } else { //422 Unprocessable Entity handlerResponse.complete( status: 422, model: ResponseModel422( validation: request.validatedRequestData!, messages: [ "added": false, "errors": entity.errors ] ) ) } } catch { print(error) handlerResponse.complete( status: 500, model: ResponseModel500Messages(messages: [ "message": "Failed to generate a successful response." ]) ) } } public class RouteCMSMarkdownAdd: OpenbuildRouteRegistry.FactoryRoute { override public func route() -> NamedRoute? { let handlerResponse = ResponseDefined() handlerResponse.register(status: 200, model: "RouteCMS.ModelCMSMarkdown200Entity") handlerResponse.register(status: 403) handlerResponse.register(status: 422) handlerResponse.register(status: 500) return NamedRoute( handlerRequest: RequestCMSMarkdownAdd( method: "post", uri: "/api/cms/markdown" ), handlerResponse: handlerResponse, handlerRoute: handlerRouteCMSMarkdownAdd ) } }
65c28544f8cf5bfa5a8147c99f24f160
25.612403
108
0.606643
false
false
false
false
adoosii/edx-app-ios
refs/heads/master
Source/SegmentAnalyticsTracker.swift
apache-2.0
3
// // SegmentAnalyticsTracker.swift // edX // // Created by Akiva Leffert on 9/15/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation class SegmentAnalyticsTracker : NSObject, OEXAnalyticsTracker { private let GoogleCategoryKey = "category"; private let GoogleLabelKey = "label"; var currentOrientationValue : String { return UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) ? OEXAnalyticsValueOrientationPortrait : OEXAnalyticsValueOrientationLandscape } var currentOutlineModeValue : String { switch CourseDataManager.currentOutlineMode { case .Full: return OEXAnalyticsValueNavigationModeFull case .Video: return OEXAnalyticsValueNavigationModeVideo } } func identifyUser(user : OEXUserDetails) { if let userID = user.userId { var traits : [String:AnyObject] = [:] if let email = user.email { traits[key_email] = email } if let username = user.username { traits[key_username] = username } SEGAnalytics.sharedAnalytics().identify(userID.description, traits:traits) } } func clearIdentifiedUser() { SEGAnalytics.sharedAnalytics().reset() } func trackEvent(event: OEXAnalyticsEvent, forComponent component: String?, withProperties properties: [NSObject : AnyObject]) { var context = [key_app_name : value_app_name] if let component = component { context[key_component] = component } if let courseID = event.courseID { context[key_course_id] = courseID } if let browserURL = event.openInBrowserURL { context[key_open_in_browser] = browserURL } var info : [String : AnyObject] = [ key_data : properties, key_context : context, key_name : event.name, OEXAnalyticsKeyOrientation : currentOrientationValue, OEXAnalyticsKeyNavigationMode : currentOutlineModeValue ] if let category = event.category { info[GoogleCategoryKey] = category } if let label = event.label { info[GoogleLabelKey] = label } SEGAnalytics.sharedAnalytics().track(event.displayName, properties: info) } func trackScreenWithName(screenName: String) { SEGAnalytics.sharedAnalytics().screen(screenName, properties: [ key_context: [ key_appname : value_appname ] ] ) } }
fce5707de387d58b4a10c868c3d5d12f
31.321429
183
0.606485
false
false
false
false
jngd/advanced-ios10-training
refs/heads/master
T4E02/T4E02/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // T4E02 // // Created by jngd on 12/02/2017. // Copyright © 2017 jngd. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self 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:. } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
b5cdb6f398ccadaaff13447cf2be5e41
50.819672
279
0.796267
false
false
false
false
eTilbudsavis/native-ios-eta-sdk
refs/heads/master
Sources/CoreAPI/Models/CoreAPI_Branding.swift
mit
1
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import UIKit extension CoreAPI { public struct Branding: Decodable, Equatable { public var name: String? public var website: URL? public var description: String? public var logoURL: URL? public var color: UIColor? public init(name: String?, website: URL?, description: String?, logoURL: URL?, color: UIColor?) { self.name = name self.website = website self.description = description self.logoURL = logoURL self.color = color } // MARK: Decodable enum CodingKeys: String, CodingKey { case name case website case description case logoURL = "logo" case colorStr = "color" } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.name = try? values.decode(String.self, forKey: .name) self.website = try? values.decode(URL.self, forKey: .website) self.description = try? values.decode(String.self, forKey: .description) self.logoURL = try? values.decode(URL.self, forKey: .logoURL) if let colorStr = try? values.decode(String.self, forKey: .colorStr) { self.color = UIColor(hex: colorStr) } } } }
72c5649320752b14ff22f320874102de
31.096154
105
0.494907
false
false
false
false
svachmic/ios-url-remote
refs/heads/master
URLRemote/Classes/Controllers/CustomCriteriaTableViewCell.swift
apache-2.0
1
// // CustomCriteriaTableViewCell.swift // URLRemote // // Created by Michal Švácha on 26/01/17. // Copyright © 2017 Svacha, Michal. All rights reserved. // import UIKit import Material /// Cell displayed only when Custom criteria is selected as the action type. Displays a text field to type custom string to be evaluated against the action's result. class CustomCriteriaTableViewCell: UITableViewCell { @IBOutlet weak var criteriaField: TextField! @IBOutlet weak var infoButton: UIButton! override func awakeFromNib() { super.awakeFromNib() criteriaField.placeholder = NSLocalizedString("CUSTOM_CRITERIA", comment: "") criteriaField.font = RobotoFont.regular(with: 13) criteriaField.placeholderActiveColor = UIColor(named: .green).darker() criteriaField.dividerActiveColor = UIColor(named: .green).darker() criteriaField.isClearIconButtonEnabled = true criteriaField.detailColor = UIColor(named: .red) infoButton.tintColor = UIColor(named: .green) self.selectionStyle = .none } }
c2315a6aad859dbcfa30e35687549491
34.741935
165
0.703069
false
false
false
false
kelan/Synchronized
refs/heads/master
Synchronized/Synchronized.swift
mit
1
// Copyright © 2016 Kelan Champagne. All rights reserved. import Foundation // MARK: - Synchronized /// Holds a value, and makes sure that it is only accessed while a lock is held. public final class Synchronized<T> { private var value: T private var lock: Lockable /// - parameter lock: Lets you choose the type of lock you want. public init(_ value: T, lock: Lockable = DispatchSemaphore(value: 1)) { self.value = value self.lock = lock } /// Get read-write access to the synchronized resource /// /// Pass a closure that takes the old value as an `inout` argument, so /// you can use that when determining the new value (which you set by just /// mutating that closure parameter. /// - note: The write lock is held during the whole execution of the closure. public func update(block: (inout T) throws -> Void) rethrows { try lock.performWithWriteLock { try block(&value) } } /// Get read-only access to the synchronized resource /// /// You can do a calculation on the value to return some derived value. /// REVIEW: Should this be called `with()`? public func use<R>(block: (T) throws -> R) rethrows -> R { return try lock.performWithReadLock { return try block(value) } } /// - note: If you get a reference type, you shouldn't use it to modify the value /// TODO: How can we enforce that? /// I want to return a copy of the value here, but if it's a reference type, then I can't guarantee the caller doesn't use the result to modify the referenced object… /// Maybe this would make more sense if value were constrainted to be a struct? /// Pehaps a different "flavor" of AtomicBox (with different methods) would be useful for a struct? /// TODO: rename to `.copy()` or `.read()`? /// TODO: Is there such thing as a "safeGet"? public func unsafeGet() -> T { return lock.performWithReadLock { return value } } } // MARK: - Lockable /// This lets you provide different locking implementations for the /// `Synchronized` resource. public protocol Lockable { func performWithReadLock<T>(_ block: () throws -> T) rethrows -> T func performWithWriteLock<T>(_ block: () throws -> T) rethrows -> T } /// Make a `DispatchSemaphore` be Lockable extension DispatchSemaphore: Lockable { public func performWithReadLock<T>(_ block: () throws -> T) rethrows -> T { wait() defer { signal() } return try block() } public func performWithWriteLock<T>(_ block: () throws -> T) rethrows -> T { wait() defer { signal() } return try block() } } /// Make a `DispatchQueue` be Lockable /// - note: You *MUST* use a serial queue for this. Don't use a global/concurrent queue! extension DispatchQueue: Lockable { public func performWithReadLock<T>(_ block: () throws -> T) rethrows -> T { return try sync(execute: block) } public func performWithWriteLock<T>(_ block: () throws -> T) rethrows -> T { return try sync(execute: block) } } public final class RWQueue: Lockable { /// - note: Use a high qos, private let queue = DispatchQueue(label: "RWQueue", qos: .userInitiated, attributes: .concurrent) public func performWithReadLock<T>(_ block: () throws -> T) rethrows -> T { return try queue.sync(execute: block) } public func performWithWriteLock<T>(_ block: () throws -> T) rethrows -> T { return try queue.sync(flags: .barrier, execute: block) } } // MARK: RWLock /// Use a `pthread_rwlock` to allow multiple concurrent reads to /// the `Synchronized` resource, but only allow a single writer. /// /// Based on https://github.com/PerfectlySoft/Perfect-Thread/blob/master/Sources/Threading.swift#L151 public final class RWLock: Lockable { private var lock = pthread_rwlock_t() public init?() { let res = pthread_rwlock_init(&lock, nil) if res != 0 { assertionFailure("rwlock init failed") return nil } } deinit { let res = pthread_rwlock_destroy(&lock) assert(res == 0, "rwlock destroy failed") } // Primitives public func lockForReading() { pthread_rwlock_rdlock(&lock) } public func lockForWriting() { pthread_rwlock_wrlock(&lock) } public func unlock() { pthread_rwlock_unlock(&lock) } // Lockable public func performWithReadLock<T>(_ block: () throws -> T) rethrows -> T { lockForReading() defer { unlock() } return try block() } public func performWithWriteLock<T>(_ block: () throws -> T) rethrows -> T { lockForWriting() defer { unlock() } return try block() } } // MARK: NSLock /// Make a `NSLock` be Lockable extension NSLock: Lockable { public func performWithReadLock<T>(_ block: () throws -> T) rethrows -> T { lock() defer { unlock() } return try block() } public func performWithWriteLock<T>(_ block: () throws -> T) rethrows -> T { lock() defer { unlock() } return try block() } } // MARK: OSSpinLock /// Use an `OSSpinLock` as the Locking strategy /// - note: Because `OSSpinLock()` isn't a class, we can't simple make an /// extension on it here class OSSpinLockable: Lockable { private var spinlock = OSSpinLock() public func performWithReadLock<T>(_ block: () throws -> T) rethrows -> T { OSSpinLockLock(&spinlock) defer { OSSpinLockUnlock(&spinlock) } return try block() } public func performWithWriteLock<T>(_ block: () throws -> T) rethrows -> T { OSSpinLockLock(&spinlock) defer { OSSpinLockUnlock(&spinlock) } return try block() } }
bb6b6a014ccd454deaf37823c3d5ef42
26.755869
170
0.618742
false
false
false
false
mathiasquintero/Sweeft
refs/heads/master
Example/Sweeft/QueensProblem.swift
mit
1
// // QueensProblem.swift // Sweeft // // Created by Mathias Quintero on 2/8/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Sweeft enum QueensProblem { typealias Coordinate = (x: Int, y: Int) static func areClear(a: Coordinate, b: Coordinate) -> Bool { return !(a.x == b.x || a.y == b.y || abs(a.x - b.x) == abs(a.y - b.y)) } static func solve() -> [Int:Coordinate]? { let constraints = 8.anyRange.flatMap { a in return 8.range |> { $0 != a } => { b in return Constraint<Int, Coordinate>.binary(a, b, constraint: areClear) } } let variables = 8.range => { x in (name: x, possible: 8.range => { (x: x, y: $0) }) } let csp = CSP<Int, Coordinate>(variables: variables, constraints: constraints) return csp.solution() } }
a83dd601b88982be8e004ef35b772127
28.033333
93
0.547646
false
false
false
false
AnthonyMDev/AmazonS3RequestManager
refs/heads/develop
Carthage/Checkouts/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift
apache-2.0
69
import Foundation /// If you are running on a slower machine, it could be useful to increase the default timeout value /// or slow down poll interval. Default timeout interval is 1, and poll interval is 0.01. public struct AsyncDefaults { public static var Timeout: TimeInterval = 1 public static var PollInterval: TimeInterval = 0.01 } private func async<T>(style: ExpectationStyle, predicate: Predicate<T>, timeout: TimeInterval, poll: TimeInterval, fnName: String) -> Predicate<T> { return Predicate { actualExpression in let uncachedExpression = actualExpression.withoutCaching() let fnName = "expect(...).\(fnName)(...)" var lastPredicateResult: PredicateResult? let result = pollBlock( pollInterval: poll, timeoutInterval: timeout, file: actualExpression.location.file, line: actualExpression.location.line, fnName: fnName) { lastPredicateResult = try predicate.satisfies(uncachedExpression) return lastPredicateResult!.toBoolean(expectation: style) } switch result { case .completed: return lastPredicateResult! case .timedOut: return PredicateResult(status: .fail, message: lastPredicateResult!.message) case let .errorThrown(error): return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>")) case let .raisedException(exception): return PredicateResult(status: .fail, message: .fail("unexpected exception raised: \(exception)")) case .blockedRunLoop: // swiftlint:disable:next line_length return PredicateResult(status: .fail, message: lastPredicateResult!.message.appended(message: " (timed out, but main thread was unresponsive).")) case .incomplete: internalError("Reached .incomplete state for toEventually(...).") } } } // Deprecated internal struct AsyncMatcherWrapper<T, U>: Matcher where U: Matcher, U.ValueType == T { let fullMatcher: U let timeoutInterval: TimeInterval let pollInterval: TimeInterval init(fullMatcher: U, timeoutInterval: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval) { self.fullMatcher = fullMatcher self.timeoutInterval = timeoutInterval self.pollInterval = pollInterval } func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { let uncachedExpression = actualExpression.withoutCaching() let fnName = "expect(...).toEventually(...)" let result = pollBlock( pollInterval: pollInterval, timeoutInterval: timeoutInterval, file: actualExpression.location.file, line: actualExpression.location.line, fnName: fnName) { try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage) } switch result { case let .completed(isSuccessful): return isSuccessful case .timedOut: return false case let .errorThrown(error): failureMessage.stringValue = "an unexpected error thrown: <\(error)>" return false case let .raisedException(exception): failureMessage.stringValue = "an unexpected exception thrown: <\(exception)>" return false case .blockedRunLoop: failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)." return false case .incomplete: internalError("Reached .incomplete state for toEventually(...).") } } func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { let uncachedExpression = actualExpression.withoutCaching() let result = pollBlock( pollInterval: pollInterval, timeoutInterval: timeoutInterval, file: actualExpression.location.file, line: actualExpression.location.line, fnName: "expect(...).toEventuallyNot(...)") { try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage) } switch result { case let .completed(isSuccessful): return isSuccessful case .timedOut: return false case let .errorThrown(error): failureMessage.stringValue = "an unexpected error thrown: <\(error)>" return false case let .raisedException(exception): failureMessage.stringValue = "an unexpected exception thrown: <\(exception)>" return false case .blockedRunLoop: failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)." return false case .incomplete: internalError("Reached .incomplete state for toEventuallyNot(...).") } } } private let toEventuallyRequiresClosureError = FailureMessage( // swiftlint:disable:next line_length stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function" ) extension Expectation { /// Tests the actual value using a matcher to match by checking continuously /// at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue) let (pass, msg) = execute( expression, .toMatch, async(style: .toMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventually"), to: "to eventually", description: description, captureExceptions: false ) verify(pass, msg) } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventuallyNot(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue) let (pass, msg) = execute( expression, .toNotMatch, async( style: .toNotMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventuallyNot" ), to: "to eventually not", description: description, captureExceptions: false ) verify(pass, msg) } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// Alias of toEventuallyNot() /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toNotEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { return toEventuallyNot(predicate, timeout: timeout, pollInterval: pollInterval, description: description) } } // Deprecated extension Expectation { /// Tests the actual value using a matcher to match by checking continuously /// at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { if expression.isClosure { let (pass, msg) = expressionMatches( expression, matcher: AsyncMatcherWrapper( fullMatcher: matcher, timeoutInterval: timeout, pollInterval: pollInterval), to: "to eventually", description: description ) verify(pass, msg) } else { verify(false, toEventuallyRequiresClosureError) } } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toEventuallyNot<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { if expression.isClosure { let (pass, msg) = expressionDoesNotMatch( expression, matcher: AsyncMatcherWrapper( fullMatcher: matcher, timeoutInterval: timeout, pollInterval: pollInterval), toNot: "to eventually not", description: description ) verify(pass, msg) } else { verify(false, toEventuallyRequiresClosureError) } } /// Tests the actual value using a matcher to not match by checking /// continuously at each pollInterval until the timeout is reached. /// /// Alias of toEventuallyNot() /// /// @discussion /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. public func toNotEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) where U: Matcher, U.ValueType == T { return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description) } }
216c4401d8d342cb123f6c4380955c14
46.262712
209
0.656715
false
false
false
false
CCIP-App/CCIP-iOS
refs/heads/master
OPass/Views/Tabs/RedeemTokenView.swift
gpl-3.0
1
// // RedeemTokenView.swift // OPass // // Created by 張智堯 on 2022/3/5. // 2022 OPass. // import SwiftUI import PhotosUI import CodeScanner struct RedeemTokenView: View { @EnvironmentObject var eventAPI: EventAPIViewModel @State private var token: String = "" @State private var isCameraSOCPresented = false @State private var isManuallySOCPresented = false @State private var isHttp403AlertPresented = false @State private var isNoQRCodeAlertPresented = false @State private var isInvaildTokenAlertPresented = false @State private var selectedPhotoItem: PhotosPickerItem? = nil @FocusState private var focusedField: Field? @Environment(\.colorScheme) private var colorScheme var body: some View { VStack { Form { FastpassLogoView() .frame(height: UIScreen.main.bounds.width * 0.4) .listRowBackground(Color.white.opacity(0)) Section { Button { self.isCameraSOCPresented = true } label: { HStack { Image(systemName: "camera") .foregroundColor(Color.white) .padding(.horizontal, 7) .padding(.vertical, 10) .background(Color.blue) .cornerRadius(9) Text("ScanQRCodeWithCamera") .foregroundColor(colorScheme == .dark ? .white : .black) Spacer() Image(systemName: "chevron.right").foregroundColor(.gray) } } PhotosPicker(selection: $selectedPhotoItem, matching: .any(of: [.images, .not(.livePhotos)])) { HStack { Image(systemName: "photo") .foregroundColor(Color.white) .padding(.horizontal, 7) .padding(.vertical, 10) .background(Color.green) .cornerRadius(9) Text("SelectAPictureToScanQRCode") .foregroundColor(colorScheme == .dark ? .white : .black) Spacer() Image(systemName: "chevron.right").foregroundColor(.gray) } } .alert("NoQRCodeFoundInPicture", isPresented: $isNoQRCodeAlertPresented) Button { self.isManuallySOCPresented = true } label: { HStack { Image(systemName: "keyboard") .foregroundColor(Color.white) .padding(.horizontal, 7) .padding(.vertical, 10) .background(Color.purple) .cornerRadius(9) Text("EnterTokenManually") .foregroundColor(colorScheme == .dark ? .white : .black) Spacer() Image(systemName: "chevron.right").foregroundColor(.gray) } } } } } .http403Alert(title: "CouldntVerifiyYourIdentity", isPresented: $isHttp403AlertPresented) .alert("CouldntVerifiyYourIdentity", message: "InvaildToken", isPresented: $isInvaildTokenAlertPresented) .slideOverCard(isPresented: $isCameraSOCPresented, backgroundColor: (colorScheme == .dark ? .init(red: 28/255, green: 28/255, blue: 30/255) : .white)) { VStack { Text("FastPass").font(Font.largeTitle.weight(.bold)) Text("ScanQRCodeWithCamera") CodeScannerView(codeTypes: [.qr], scanMode: .once, showViewfinder: false, shouldVibrateOnSuccess: true, completion: HandleScan) .frame(height: UIScreen.main.bounds.height * 0.25) .cornerRadius(20) .overlay { if !(AVCaptureDevice.authorizationStatus(for: .video) == .authorized) { VStack { Spacer() Spacer() Text("RequestUserPermitCamera") .foregroundColor(.white) .multilineTextAlignment(.center) Spacer() Button { Constants.OpenInOS(forURL: URL(string: UIApplication.openSettingsURLString)!) } label: { Text("OpenSettings") .foregroundColor(.blue) .bold() } Spacer() Spacer() } .padding(10) } } VStack(alignment: .leading) { Text("ScanToGetToken").bold() Text("ScanToGetTokenContent") .foregroundColor(Color.gray) } } } .slideOverCard( isPresented: $isManuallySOCPresented, onDismiss: { UIApplication.endEditing() }, backgroundColor: (colorScheme == .dark ? .init(red: 28/255, green: 28/255, blue: 30/255) : .white) ) { VStack { Text("FastPass").font(Font.largeTitle.weight(.bold)) Text("EnterTokenManually") TextField("Token", text: $token) .focused($focusedField, equals: .ManuallyToken) .padding(10) .overlay( RoundedRectangle(cornerRadius: 5) .stroke( (focusedField == .ManuallyToken ? .yellow : Color(red: 209/255, green: 209/255, blue: 213/255)), lineWidth: (focusedField == .ManuallyToken ? 2 : 1)) ) VStack(alignment: .leading) { Text("EnterTokenManuallyContent") .foregroundColor(Color.gray) .font(.caption) } Button(action: { UIApplication.endEditing() self.isManuallySOCPresented = false Task { do { self.isInvaildTokenAlertPresented = !(try await eventAPI.redeemToken(token: token)) } catch APIRepo.LoadError.http403Forbidden { self.isHttp403AlertPresented = true } catch { self.isInvaildTokenAlertPresented = true } } }) { HStack { Spacer() Text("Continue") .padding(.vertical, 20) .foregroundColor(Color.white) Spacer() }.background(Color("LogoColor")).cornerRadius(12) } } } .onChange(of: selectedPhotoItem) { item in Task { guard let data = try? await item?.loadTransferable(type: Data.self), let ciImage = CIImage(data: data), let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil), let feature = detector.features(in: ciImage) as? [CIQRCodeFeature], let token = feature.first?.messageString else { self.isNoQRCodeAlertPresented = true; return } do { let result = try await eventAPI.redeemToken(token: token) self.isInvaildTokenAlertPresented = !result } catch APIRepo.LoadError.http403Forbidden { self.isHttp403AlertPresented = true } catch { self.isInvaildTokenAlertPresented = true } } } } private func HandleScan(result: Result<ScanResult, ScanError>) { self.isCameraSOCPresented = false switch result { case .success(let result): Task { do { let result = try await eventAPI.redeemToken(token: result.string) DispatchQueue.main.async { self.isInvaildTokenAlertPresented = !result } } catch APIRepo.LoadError.http403Forbidden { DispatchQueue.main.async { self.isHttp403AlertPresented = true } } catch { DispatchQueue.main.async { self.isInvaildTokenAlertPresented = true } } } case .failure(let error): DispatchQueue.main.async { self.isInvaildTokenAlertPresented = true } print("Scanning failed: \(error.localizedDescription)") } } enum Field: Hashable { case ManuallyToken } } #if DEBUG struct RedeemTokenView_Previews: PreviewProvider { static var previews: some View { RedeemTokenView() .environmentObject(OPassAPIViewModel.mock().currentEventAPI!) } } #endif
244208d6a349ed062745672edc18d7bf
42.815789
160
0.453554
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Healthcare
refs/heads/master
iOS/Healthcare/Models/Patient.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit /** Patient is a model of data representing the current user of the app. This is an extension of IBMDataObject */ class Patient: NSObject { var userID : String! var password : String! var dateOfNextVisit : NSDate! var visitsUsed : NSNumber! var visitsTotal : NSNumber! var stepGoal : NSNumber! var calorieGoal : NSNumber! var routineId : [String]! var questionnaire : String! /** An alternative init method that allows for populating all the properties of the object - parameter userID: The ID of the patient - parameter password: The password for the patient - parameter dateOfNextVisit: NSDate object representing the date of the next visit to doctor - parameter visitsUsed: The number of visits the patient has used on visit plan - parameter visitsTotal: The number of visits the patient has planned with doctor in total - parameter stepGoal: The step goal for the patient as a number - parameter calorieGoal: The calorie goal for the patient as a number */ init(userID : String, password : String, dateOfNextVisit: NSDate, visitsUsed: NSNumber, visitsTotal: NSNumber, stepGoal : NSNumber, calorieGoal : NSNumber, routineId : [String]!, questionnaire : String!) { super.init() self.userID = userID self.password = password self.dateOfNextVisit = dateOfNextVisit self.visitsUsed = visitsUsed self.visitsTotal = visitsTotal self.stepGoal = stepGoal self.calorieGoal = calorieGoal self.routineId = routineId self.questionnaire = questionnaire } init(worklightResponseJson: NSDictionary) { super.init() let jsonResult = worklightResponseJson["result"] as! NSDictionary /* let stringResult = worklightResponseJson["result"] as! String let data = stringResult.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) let jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves, error: nil) as! NSDictionary */ self.userID = jsonResult["userID"] as! String self.visitsUsed = jsonResult["visitsUsed"] as! NSNumber self.visitsTotal = jsonResult["visitsTotal"] as! NSNumber self.stepGoal = jsonResult["stepGoal"] as! NSNumber self.calorieGoal = jsonResult["calorieGoal"] as! NSNumber let dateOfNextVisitString = jsonResult["dateOfNextVisit"] as! String let formatter = NSDateFormatter() formatter.dateFormat = "MM/dd/yyyy" self.dateOfNextVisit = formatter.dateFromString(dateOfNextVisitString) self.routineId = jsonResult["routines"] as! [String] self.questionnaire = jsonResult["questionnaire"] as! String } }
f586edf605c68d42129ffb8bcedf58f3
39.133333
209
0.679402
false
false
false
false
WhisperSystems/Signal-iOS
refs/heads/master
SignalMessaging/Views/ImageEditor/ImageEditorView.swift
gpl-3.0
1
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import UIKit @objc public protocol ImageEditorViewDelegate: class { func imageEditor(presentFullScreenView viewController: UIViewController, isTransparent: Bool) func imageEditorUpdateNavigationBar() func imageEditorUpdateControls() } // MARK: - // A view for editing outgoing image attachments. // It can also be used to render the final output. @objc public class ImageEditorView: UIView { weak var delegate: ImageEditorViewDelegate? private let model: ImageEditorModel private let canvasView: ImageEditorCanvasView // TODO: We could hang this on the model or make this static // if we wanted more color continuity. private var currentColor = ImageEditorColor.defaultColor() @objc public required init(model: ImageEditorModel, delegate: ImageEditorViewDelegate) { self.model = model self.delegate = delegate self.canvasView = ImageEditorCanvasView(model: model) super.init(frame: .zero) model.add(observer: self) } @available(*, unavailable, message: "use other init() instead.") required public init?(coder aDecoder: NSCoder) { notImplemented() } // MARK: - Views private var moveTextGestureRecognizer: ImageEditorPanGestureRecognizer? private var tapGestureRecognizer: UITapGestureRecognizer? private var pinchGestureRecognizer: ImageEditorPinchGestureRecognizer? @objc public func configureSubviews() -> Bool { canvasView.configureSubviews() self.addSubview(canvasView) canvasView.autoPinEdgesToSuperviewEdges() self.isUserInteractionEnabled = true let moveTextGestureRecognizer = ImageEditorPanGestureRecognizer(target: self, action: #selector(handleMoveTextGesture(_:))) moveTextGestureRecognizer.maximumNumberOfTouches = 1 moveTextGestureRecognizer.referenceView = canvasView.gestureReferenceView moveTextGestureRecognizer.delegate = self self.addGestureRecognizer(moveTextGestureRecognizer) self.moveTextGestureRecognizer = moveTextGestureRecognizer let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:))) self.addGestureRecognizer(tapGestureRecognizer) self.tapGestureRecognizer = tapGestureRecognizer let pinchGestureRecognizer = ImageEditorPinchGestureRecognizer(target: self, action: #selector(handlePinchGesture(_:))) pinchGestureRecognizer.referenceView = canvasView.gestureReferenceView self.addGestureRecognizer(pinchGestureRecognizer) self.pinchGestureRecognizer = pinchGestureRecognizer // De-conflict the GRs. // editorGestureRecognizer.require(toFail: tapGestureRecognizer) // editorGestureRecognizer.require(toFail: pinchGestureRecognizer) return true } // MARK: - Navigation Bar private func updateNavigationBar() { delegate?.imageEditorUpdateNavigationBar() } public func navigationBarItems() -> [UIView] { guard !shouldHideControls else { return [] } let undoButton = navigationBarButton(imageName: "image_editor_undo", selector: #selector(didTapUndo(sender:))) let brushButton = navigationBarButton(imageName: "image_editor_brush", selector: #selector(didTapBrush(sender:))) let cropButton = navigationBarButton(imageName: "image_editor_crop", selector: #selector(didTapCrop(sender:))) let newTextButton = navigationBarButton(imageName: "image_editor_text", selector: #selector(didTapNewText(sender:))) let buttons: [UIView] if model.canUndo() { buttons = [undoButton, newTextButton, brushButton, cropButton] } else { buttons = [newTextButton, brushButton, cropButton] } return buttons } private func updateControls() { delegate?.imageEditorUpdateControls() } public var shouldHideControls: Bool { // Hide controls during "text item move". return movingTextItem != nil } // MARK: - Actions @objc func didTapUndo(sender: UIButton) { Logger.verbose("") guard model.canUndo() else { owsFailDebug("Can't undo.") return } model.undo() } @objc func didTapBrush(sender: UIButton) { Logger.verbose("") let brushView = ImageEditorBrushViewController(delegate: self, model: model, currentColor: currentColor) self.delegate?.imageEditor(presentFullScreenView: brushView, isTransparent: false) } @objc func didTapCrop(sender: UIButton) { Logger.verbose("") presentCropTool() } @objc func didTapNewText(sender: UIButton) { Logger.verbose("") createNewTextItem() } private func createNewTextItem() { Logger.verbose("") let viewSize = canvasView.gestureReferenceView.bounds.size let imageSize = model.srcImageSizePixels let imageFrame = ImageEditorCanvasView.imageFrame(forViewSize: viewSize, imageSize: imageSize, transform: model.currentTransform()) let textWidthPoints = viewSize.width * ImageEditorTextItem.kDefaultUnitWidth let textWidthUnit = textWidthPoints / imageFrame.size.width // New items should be aligned "upright", so they should have the _opposite_ // of the current transform rotation. let rotationRadians = -model.currentTransform().rotationRadians // Similarly, the size of the text item shuo let scaling = 1 / model.currentTransform().scaling let textItem = ImageEditorTextItem.empty(withColor: currentColor, unitWidth: textWidthUnit, fontReferenceImageWidth: imageFrame.size.width, scaling: scaling, rotationRadians: rotationRadians) edit(textItem: textItem, isNewItem: true) } @objc func didTapDone(sender: UIButton) { Logger.verbose("") } // MARK: - Tap Gesture @objc public func handleTapGesture(_ gestureRecognizer: UIGestureRecognizer) { AssertIsOnMainThread() guard gestureRecognizer.state == .recognized else { owsFailDebug("Unexpected state.") return } let location = gestureRecognizer.location(in: canvasView.gestureReferenceView) guard let textLayer = self.textLayer(forLocation: location) else { // If there is no text item under the "tap", start a new one. createNewTextItem() return } guard let textItem = model.item(forId: textLayer.itemId) as? ImageEditorTextItem else { owsFailDebug("Missing or invalid text item.") return } edit(textItem: textItem, isNewItem: false) } // MARK: - Pinch Gesture // These properties are valid while moving a text item. private var pinchingTextItem: ImageEditorTextItem? private var pinchHasChanged = false @objc public func handlePinchGesture(_ gestureRecognizer: ImageEditorPinchGestureRecognizer) { AssertIsOnMainThread() // We could undo an in-progress pinch if the gesture is cancelled, but it seems gratuitous. switch gestureRecognizer.state { case .began: let pinchState = gestureRecognizer.pinchStateStart guard let textLayer = self.textLayer(forLocation: pinchState.centroid) else { // The pinch needs to start centered on a text item. return } guard let textItem = model.item(forId: textLayer.itemId) as? ImageEditorTextItem else { owsFailDebug("Missing or invalid text item.") return } pinchingTextItem = textItem pinchHasChanged = false case .changed, .ended: guard let textItem = pinchingTextItem else { return } let view = self.canvasView.gestureReferenceView let viewBounds = view.bounds let locationStart = gestureRecognizer.pinchStateStart.centroid let locationNow = gestureRecognizer.pinchStateLast.centroid let gestureStartImageUnit = ImageEditorCanvasView.locationImageUnit(forLocationInView: locationStart, viewBounds: viewBounds, model: self.model, transform: self.model.currentTransform()) let gestureNowImageUnit = ImageEditorCanvasView.locationImageUnit(forLocationInView: locationNow, viewBounds: viewBounds, model: self.model, transform: self.model.currentTransform()) let gestureDeltaImageUnit = gestureNowImageUnit.minus(gestureStartImageUnit) let unitCenter = CGPointClamp01(textItem.unitCenter.plus(gestureDeltaImageUnit)) // NOTE: We use max(1, ...) to avoid divide-by-zero. let newScaling = CGFloatClamp(textItem.scaling * gestureRecognizer.pinchStateLast.distance / max(1.0, gestureRecognizer.pinchStateStart.distance), ImageEditorTextItem.kMinScaling, ImageEditorTextItem.kMaxScaling) let newRotationRadians = textItem.rotationRadians + gestureRecognizer.pinchStateLast.angleRadians - gestureRecognizer.pinchStateStart.angleRadians let newItem = textItem.copy(unitCenter: unitCenter).copy(scaling: newScaling, rotationRadians: newRotationRadians) if pinchHasChanged { model.replace(item: newItem, suppressUndo: true) } else { model.replace(item: newItem, suppressUndo: false) pinchHasChanged = true } if gestureRecognizer.state == .ended { pinchingTextItem = nil } default: pinchingTextItem = nil } } // MARK: - Editor Gesture // These properties are valid while moving a text item. private var movingTextItem: ImageEditorTextItem? { didSet { updateNavigationBar() updateControls() } } private var movingTextStartUnitCenter: CGPoint? private var movingTextHasMoved = false private func textLayer(forLocation locationInView: CGPoint) -> EditorTextLayer? { let viewBounds = self.canvasView.gestureReferenceView.bounds let affineTransform = self.model.currentTransform().affineTransform(viewSize: viewBounds.size) let locationInCanvas = locationInView.minus(viewBounds.center).applyingInverse(affineTransform).plus(viewBounds.center) return canvasView.textLayer(forLocation: locationInCanvas) } @objc public func handleMoveTextGesture(_ gestureRecognizer: ImageEditorPanGestureRecognizer) { AssertIsOnMainThread() // We could undo an in-progress move if the gesture is cancelled, but it seems gratuitous. switch gestureRecognizer.state { case .began: guard let locationStart = gestureRecognizer.locationFirst else { owsFailDebug("Missing locationStart.") return } guard let textLayer = self.textLayer(forLocation: locationStart) else { owsFailDebug("No text layer") return } guard let textItem = model.item(forId: textLayer.itemId) as? ImageEditorTextItem else { owsFailDebug("Missing or invalid text item.") return } movingTextItem = textItem movingTextStartUnitCenter = textItem.unitCenter movingTextHasMoved = false case .changed, .ended: guard let textItem = movingTextItem else { return } guard let locationStart = gestureRecognizer.locationFirst else { owsFailDebug("Missing locationStart.") return } guard let movingTextStartUnitCenter = movingTextStartUnitCenter else { owsFailDebug("Missing movingTextStartUnitCenter.") return } let view = self.canvasView.gestureReferenceView let viewBounds = view.bounds let locationInView = gestureRecognizer.location(in: view) let gestureStartImageUnit = ImageEditorCanvasView.locationImageUnit(forLocationInView: locationStart, viewBounds: viewBounds, model: self.model, transform: self.model.currentTransform()) let gestureNowImageUnit = ImageEditorCanvasView.locationImageUnit(forLocationInView: locationInView, viewBounds: viewBounds, model: self.model, transform: self.model.currentTransform()) let gestureDeltaImageUnit = gestureNowImageUnit.minus(gestureStartImageUnit) let unitCenter = CGPointClamp01(movingTextStartUnitCenter.plus(gestureDeltaImageUnit)) let newItem = textItem.copy(unitCenter: unitCenter) if movingTextHasMoved { model.replace(item: newItem, suppressUndo: true) } else { model.replace(item: newItem, suppressUndo: false) movingTextHasMoved = true } if gestureRecognizer.state == .ended { movingTextItem = nil } default: movingTextItem = nil } } // MARK: - Brush // These properties are non-empty while drawing a stroke. private var currentStroke: ImageEditorStrokeItem? private var currentStrokeSamples = [ImageEditorStrokeItem.StrokeSample]() @objc public func handleBrushGesture(_ gestureRecognizer: UIGestureRecognizer) { AssertIsOnMainThread() let removeCurrentStroke = { if let stroke = self.currentStroke { self.model.remove(item: stroke) } self.currentStroke = nil self.currentStrokeSamples.removeAll() } let tryToAppendStrokeSample = { let view = self.canvasView.gestureReferenceView let viewBounds = view.bounds let locationInView = gestureRecognizer.location(in: view) let newSample = ImageEditorCanvasView.locationImageUnit(forLocationInView: locationInView, viewBounds: viewBounds, model: self.model, transform: self.model.currentTransform()) if let prevSample = self.currentStrokeSamples.last, prevSample == newSample { // Ignore duplicate samples. return } self.currentStrokeSamples.append(newSample) } let strokeColor = currentColor.color // TODO: Tune stroke width. let unitStrokeWidth = ImageEditorStrokeItem.defaultUnitStrokeWidth() switch gestureRecognizer.state { case .began: removeCurrentStroke() tryToAppendStrokeSample() let stroke = ImageEditorStrokeItem(color: strokeColor, unitSamples: currentStrokeSamples, unitStrokeWidth: unitStrokeWidth) model.append(item: stroke) currentStroke = stroke case .changed, .ended: tryToAppendStrokeSample() guard let lastStroke = self.currentStroke else { owsFailDebug("Missing last stroke.") removeCurrentStroke() return } // Model items are immutable; we _replace_ the // stroke item rather than modify it. let stroke = ImageEditorStrokeItem(itemId: lastStroke.itemId, color: strokeColor, unitSamples: currentStrokeSamples, unitStrokeWidth: unitStrokeWidth) model.replace(item: stroke, suppressUndo: true) if gestureRecognizer.state == .ended { currentStroke = nil currentStrokeSamples.removeAll() } else { currentStroke = stroke } default: removeCurrentStroke() } } // MARK: - Edit Text Tool private func edit(textItem: ImageEditorTextItem, isNewItem: Bool) { Logger.verbose("") // TODO: let maxTextWidthPoints = model.srcImageSizePixels.width * ImageEditorTextItem.kDefaultUnitWidth // let maxTextWidthPoints = canvasView.imageView.width() * ImageEditorTextItem.kDefaultUnitWidth let textEditor = ImageEditorTextViewController(delegate: self, model: model, textItem: textItem, isNewItem: isNewItem, maxTextWidthPoints: maxTextWidthPoints) self.delegate?.imageEditor(presentFullScreenView: textEditor, isTransparent: false) } // MARK: - Crop Tool private func presentCropTool() { Logger.verbose("") guard let srcImage = canvasView.loadSrcImage() else { owsFailDebug("Couldn't load src image.") return } // We want to render a preview image that "flattens" all of the brush strokes, text items, // into the background image without applying the transform (e.g. rotating, etc.), so we // use a default transform. let previewTransform = ImageEditorTransform.defaultTransform(srcImageSizePixels: model.srcImageSizePixels) guard let previewImage = ImageEditorCanvasView.renderForOutput(model: model, transform: previewTransform) else { owsFailDebug("Couldn't generate preview image.") return } let cropTool = ImageEditorCropViewController(delegate: self, model: model, srcImage: srcImage, previewImage: previewImage) self.delegate?.imageEditor(presentFullScreenView: cropTool, isTransparent: false) } } // MARK: - extension ImageEditorView: UIGestureRecognizerDelegate { @objc public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard moveTextGestureRecognizer == gestureRecognizer else { owsFailDebug("Unexpected gesture.") return false } let location = touch.location(in: canvasView.gestureReferenceView) let isInTextArea = self.textLayer(forLocation: location) != nil return isInTextArea } } // MARK: - extension ImageEditorView: ImageEditorModelObserver { public func imageEditorModelDidChange(before: ImageEditorContents, after: ImageEditorContents) { updateNavigationBar() } public func imageEditorModelDidChange(changedItemIds: [String]) { updateNavigationBar() } } // MARK: - extension ImageEditorView: ImageEditorTextViewControllerDelegate { public func textEditDidComplete(textItem: ImageEditorTextItem) { AssertIsOnMainThread() // Model items are immutable; we _replace_ the item rather than modify it. if model.has(itemForId: textItem.itemId) { model.replace(item: textItem, suppressUndo: false) } else { model.append(item: textItem) } self.currentColor = textItem.color } public func textEditDidDelete(textItem: ImageEditorTextItem) { AssertIsOnMainThread() if model.has(itemForId: textItem.itemId) { model.remove(item: textItem) } } public func textEditDidCancel() { } } // MARK: - extension ImageEditorView: ImageEditorCropViewControllerDelegate { public func cropDidComplete(transform: ImageEditorTransform) { // TODO: Ignore no-change updates. model.replace(transform: transform) } public func cropDidCancel() { // TODO: } } // MARK: - extension ImageEditorView: ImageEditorBrushViewControllerDelegate { public func brushDidComplete(currentColor: ImageEditorColor) { self.currentColor = currentColor } }
f2e4c55578c33cd14921a210bbb6dfd8
37.682709
162
0.604995
false
false
false
false
KSU-Mobile-Dev-Club/Branching-Out-iOS
refs/heads/master
BranchingOut-iOS/MDCGalleryCollectionViewCell.swift
mit
1
// // MDCGalleryCollectionViewCell.swift // BranchingOut-iOS // // Created by Kevin Manase on 3/10/16. // Copyright © 2016 MDC. All rights reserved. // import UIKit class MDCGalleryCollectionViewCell: UICollectionViewCell { var imageName: String! @IBOutlet var imageView: UIImageView! @IBOutlet var imageLabel: UILabel! var imageURL: String! func updateCell() { imageLabel.text = imageName imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true DLImageLoader.sharedInstance().imageFromUrl(imageURL) { (error, image) -> () in if (error == nil) { // if we have no any errors self.imageView?.image = image } else { // if we got an error when load an image } } } }
44f5cbe23f5998c9eca652cfcc3bf5fd
25.575758
87
0.598632
false
false
false
false
tootbot/tootbot
refs/heads/master
Tootbot/Source/View Controllers/AddAccountViewController.swift
agpl-3.0
1
// // Copyright (C) 2017 Tootbot Contributors // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import KeyboardLayoutGuide import ReactiveCocoa import ReactiveSwift import Result import SafariServices import UIKit class AddAccountViewController: UIViewController, SFSafariViewControllerDelegate { @IBOutlet var activityIndicatorView: UIActivityIndicatorView! @IBOutlet var containerStackView: UIStackView! @IBOutlet var instanceTextField: UITextField! @IBOutlet var logInButton: UIButton! let disposable = ScopedDisposable(CompositeDisposable()) var loginAction: Action<String, DataController, AddAccountViewModel.Error>! var viewModel: AddAccountViewModel! let doneSignal: Signal<DataController, NoError> let doneObserver: Observer<DataController, NoError> override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { (self.doneSignal, self.doneObserver) = Signal.pipe() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { (self.doneSignal, self.doneObserver) = Signal.pipe() super.init(coder: aDecoder) } // MARK: - Actions @IBAction func logIn(_ sender: AnyObject?) { instanceTextField.resignFirstResponder() let instanceURI: String if let text = instanceTextField.text?.trimmingCharacters(in: .whitespaces), !text.isEmpty { instanceURI = text } else { instanceURI = "mastodon.social" } disposable += loginAction.apply(instanceURI).start() } // MARK: - func configureLayout() { keyboardLayoutGuide.centerYAnchor.constraint(equalTo: containerStackView.centerYAnchor).isActive = true } func presentSafariViewController(url: URL) { let safariViewController = SFSafariViewController(url: url) safariViewController.delegate = self safariViewController.preferredBarTintColor = #colorLiteral(red: 0.1921568627, green: 0.2078431373, blue: 0.262745098, alpha: 1) safariViewController.preferredControlTintColor = .white present(safariViewController, animated: true) } func configureReactivity() { // Set up action loginAction = Action { [unowned self] instanceURI in let replacement = self.viewModel.loginResult(on: instanceURI) .on(value: { [unowned self] signal in // Credential verification began self.dismiss(animated: true) }) .flatten(.latest) return self.viewModel.loginURL(on: instanceURI) .on(value: { [unowned self] loginURL in self.presentSafariViewController(url: loginURL) }) // fatalError is NOT called; `filter()` passes through no values .filter { _ in false } .map { _ in fatalError() } .take(untilReplacement: replacement) .take(until: self.reactive.trigger(for: #selector(AddAccountViewController.safariViewControllerDidFinish))) } // Pass login results through to `doneSignal` disposable += loginAction.values.take(first: 1).observe(doneObserver) // TODO: Handle login verification errors // https://github.com/tootbot/tootbot/issues/26 disposable += loginAction.errors.observeValues { error in print(error) } // Toggle activity view animating disposable += activityIndicatorView.reactive.isAnimating <~ loginAction.isExecuting // Toggle button enabled disposable += logInButton.reactive.isEnabled <~ loginAction.isExecuting.negate() // Toggle text field enabled instanceTextField.reactive.isEnabled <~ loginAction.isExecuting.negate() } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureLayout() configureReactivity() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !loginAction.isExecuting.value { instanceTextField.becomeFirstResponder() instanceTextField.selectedTextRange = instanceTextField.fullTextRange } } // MARK: - Status Bar override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: - Safari View Controller func safariViewControllerDidFinish(_ controller: SFSafariViewController) { // Stub implementation for ReactiveCocoa } }
e951bc7037ba1f597a269382569fbb0a
34.808219
135
0.676167
false
false
false
false
oliveroneill/FeedCollectionViewController
refs/heads/master
Example/FeedCollectionViewController/ColorFeedViewController.swift
mit
1
// // CustomImageViewController.swift // FeedCollectionViewController // // Created by Oliver ONeill on 21/12/2016. // import UIKit import ImageFeedCollectionViewController extension UIColor { func toHexString() -> String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let rgb: Int = (Int)(r * 255) << 16 | (Int)(g * 255) << 8 | (Int)(b * 255) << 0 return NSString(format: "#%06x", rgb) as String } } open class ColorFeedViewController: ImageFeedCollectionViewController, ImageFeedPresenter, ImageFeedDataSource { private let querySize = 20 // Cannot be private as these are changed for testing var length = 50 var loadingDelay = 1 var imageDelay = 0.1 // internal counters private var collectionLength = 0 private var hue = 0.0 override open func viewDidLoad() { super.viewDidLoad() imageFeedSource = self imageFeedPresenter = self } public func getImageReuseIdentifier(cell: ImageCellData) -> String { return "ExampleCell" } public func getSingleImageView(cell: ImageCellData) -> SingleImageView { // This is a slight quirk in Swift, in order for // `ColorCaptionFeedCollectionViewController` to override the default // implementation of `getSingleImageView`, we need to call it here first // See: https://team.goodeggs.com/overriding-swift-protocol-extension-default-implementations-d005a4428bda return self.getSingleImageView(cell: cell) } public func getImageCells(start: Int, callback: @escaping ImageCellDataCallback) { if loadingDelay == 0 { self.loadImages(start: start, callback: callback) return } // delay for 1 second in place of an actual network request DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(loadingDelay)) { [unowned self] in self.loadImages(start: start, callback: callback) } } func loadImages(start: Int, callback: @escaping ImageCellDataCallback) { // limit the cells to LENGTH if self.collectionLength > length { callback([], nil) return } var cells: [ImageCellData] = [] // will only return query size at a time for _ in 0..<querySize { // increase hue slowly for each cell self.hue += 1.0 / Double(length) let color = UIColor(hue: CGFloat(self.hue), saturation: 1, brightness: 1, alpha: 1) cells.append(ColorImageCellData(color: color, delay: self.imageDelay)) } callback(cells, nil) self.collectionLength += querySize } open func refreshContent() { self.refresh() } public func loadImageCell(cellView: UICollectionViewCell, cell: ImageCellData) { if let cellView = cellView as? ImageCollectionViewCell, let cell = cell as? ColorImageCellData { cellView.image = cell } } public func imageFailed(cell: ImageCellData, imageView: UIImageView) { } }
13941578e9f943f13a79a07eacdf84ad
32.819149
114
0.634791
false
false
false
false
Cocoastudies/CocoaCast
refs/heads/master
PodcastApp/PodcastApp/Reachability.swift
mit
1
// // Reachability.swift // PodcastApp // // Created by Bruno Da luz on 6/4/16. // Copyright © 2016 cocoastudies. All rights reserved. // import Foundation import SystemConfiguration public class Reachability { class func isConnection() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = flags == .Reachable let needsConnection = flags == .ConnectionRequired return isReachable && !needsConnection } }
2eb8ffaff37ef4e77c2a842b1fde419a
27.457143
87
0.645226
false
false
false
false
abdullahselek/DragDropUI
refs/heads/master
DragDropUI/DD+View.swift
mit
1
// // DDView.swift // DragDropUI // // Copyright © 2016 Abdullah Selek. All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public extension DDProtocol where Self: UIView { var view: UIView { get { return self } } var parentView: UIView? { get { return self.view.superview } } func registerGesture() { let panGesture = UIPanGestureRecognizer() panGesture.handler = { gesture in self.handlePan(panGesture: gesture as! UIPanGestureRecognizer) } self.view.addGestureRecognizer(panGesture) let pressGesture = UILongPressGestureRecognizer() pressGesture.cancelsTouchesInView = false pressGesture.minimumPressDuration = 0.001 pressGesture.handler = { gesture in self.didPress(pressGesture: gesture as! UILongPressGestureRecognizer) } self.view.addGestureRecognizer(pressGesture) } func removeGesture() { guard self.gestureRecognizers != nil else { return } let _ = self.gestureRecognizers! .filter({ $0.delegate is UIGestureRecognizer.DDGestureDelegate }) .map({ self.removeGestureRecognizer($0) }) } func didPress(pressGesture: UILongPressGestureRecognizer) { switch pressGesture.state { case .began: self.draggedPoint = self.view.center self.parentView?.bringSubviewToFront(self.view) break case .cancelled, .ended, .failed: if self.ddDelegate != nil { self.ddDelegate!.viewWasDropped(view: self, droppedPoint: self.draggedPoint) } break default: break } } func handlePan(panGesture: UIPanGestureRecognizer) { let translation = panGesture.translation(in: self.parentView) self.view.center = CGPoint(x: self.draggedPoint.x + translation.x, y: self.draggedPoint.y + translation.y) if self.ddDelegate != nil { self.ddDelegate!.viewWasDragged(view: self, draggedPoint: self.view.center) } } }
107e6a96a0ad87b189b76d0e9fc7df45
36.388235
114
0.675582
false
false
false
false
Burning-Man-Earth/iBurn-iOS
refs/heads/master
iBurn/EventListViewController.swift
mpl-2.0
1
// // EventListViewController.swift // iBurn // // Created by Chris Ballinger on 7/30/18. // Copyright © 2018 Burning Man Earth. All rights reserved. // import UIKit import Anchorage import ASDayPicker @objc public class EventListViewController: UIViewController { // MARK: - Public Properties public let viewName: String public let searchViewName: String // MARK: - Private Properties internal let listCoordinator: ListCoordinator private let tableView = UITableView.iBurnTableView() private let dayPicker = ASDayPicker() private var selectedDay: Date { didSet { replaceTimeBasedEventMappings() } } private var dayObserver: NSKeyValueObservation? private var loadingIndicator = UIActivityIndicatorView(style: .gray) // MARK: - Init @objc public init(viewName: String, searchViewName: String) { self.viewName = viewName self.searchViewName = searchViewName self.listCoordinator = ListCoordinator(viewName: viewName, searchViewName: searchViewName, tableView: tableView) self.selectedDay = YearSettings.dayWithinFestival(.present) super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle public override func viewDidLoad() { super.viewDidLoad() setupDayPicker() setupTableView() setupFilterButton() setupListCoordinator() setupSearchButton() definesPresentationContext = true view.addSubview(tableView) tableView.edgeAnchors == view.edgeAnchors } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) searchWillAppear() refreshNavigationBarColors(animated) dayPicker.setColorTheme(Appearance.currentColors, animated: true) } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) searchDidAppear() } } private extension EventListViewController { // MARK: - Setup func setupTableView() { let size = CGSize(width: tableView.bounds.width, height: 65) dayPicker.frame = CGRect(origin: .zero, size: size) tableView.tableHeaderView = dayPicker } func setupListCoordinator() { self.listCoordinator.parent = self let groupTransformer: (String) -> String = { let components = $0.components(separatedBy: " ") guard let hourString = components.last, var hour = Int(hourString) else { return $0 } hour = hour % 12 if hour == 0 { hour = 12 } return "\(hour)" } self.listCoordinator.searchDisplayManager.tableViewAdapter.groupTransformer = GroupTransformers.searchGroup self.listCoordinator.tableViewAdapter.groupTransformer = groupTransformer replaceTimeBasedEventMappings() } func setupFilterButton() { let filter = UIBarButtonItem(title: "Filter", style: .plain, target: self, action: #selector(filterButtonPressed(_:))) let loading = UIBarButtonItem(customView: self.loadingIndicator) self.navigationItem.rightBarButtonItems = [filter, loading] } func setupDayPicker() { dayPicker.daysScrollView.isScrollEnabled = true dayPicker.setStart(YearSettings.eventStart, end: YearSettings.eventEnd) dayPicker.weekdayTitles = ASDayPicker.weekdayTitles(withLocaleIdentifier: nil, length: 3, uppercase: true) dayPicker.selectedDateBackgroundImage = UIImage(named: "BRCDateSelection") dayObserver = dayPicker.observe(\.selectedDate) { [weak self] (object, change) in let date = YearSettings.dayWithinFestival(object.selectedDate) self?.selectedDay = date } dayPicker.selectedDate = self.selectedDay } // MARK: - UI Actions @objc func filterButtonPressed(_ sender: Any) { let filterVC = BRCEventsFilterTableViewController(delegate: self) let nav = NavigationController(rootViewController: filterVC) present(nav, animated: true, completion: nil) } // MARK: - UI Refresh func updateFilteredViews() { loadingIndicator.startAnimating() BRCDatabaseManager.shared.refreshEventFilteredViews(withSelectedDay: self.selectedDay) { self.loadingIndicator.stopAnimating() } } func replaceTimeBasedEventMappings() { let selectedDayString = DateFormatter.eventGroupDateFormatter.string(from: self.selectedDay) self.listCoordinator.tableViewAdapter.viewHandler.groups = .filterSort({ (group, transaction) -> Bool in return group.contains(selectedDayString) }, { (group1, group2, transaction) -> ComparisonResult in return group1.compare(group2) }) let searchSelectedDayOnly = UserSettings.searchSelectedDayOnly self.listCoordinator.searchDisplayManager.tableViewAdapter.viewHandler.groups = .filterSort({ (group, transaction) -> Bool in if searchSelectedDayOnly { return group.contains(selectedDayString) } else { return true } }, { (group1, group2, transaction) -> ComparisonResult in return group1.compare(group2) }) } } extension EventListViewController: BRCEventsFilterTableViewControllerDelegate { public func didSetNewFilterSettings(_ viewController: BRCEventsFilterTableViewController) { updateFilteredViews() } } extension EventListViewController: SearchCooordinator { var searchController: UISearchController { return listCoordinator.searchDisplayManager.searchController } } extension ASDayPicker: ColorTheme { public func setColorTheme(_ colors: BRCImageColors, animated: Bool) { weekdayTextColor = colors.primaryColor dateTextColor = colors.primaryColor selectedWeekdayTextColor = colors.primaryColor } }
2a1c66f3201bed384d76a91539fdf398
33.559783
133
0.654348
false
false
false
false
aloe-kawase/aloeutils
refs/heads/develop
Pod/Classes/AloeColor.swift
mit
1
// // AloeColorUtil.swift // Pods // // Created by kawase yu on 2015/09/16. // // import UIKit public class AloeColor: NSObject { public class func fromHex(rgbValue:UInt32)->UIColor{ let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbValue & 0xFF)/256.0 return UIColor(red:red, green:green, blue:blue, alpha:1.0) } public class func fromHexString(str:String)->UIColor{ let colorScanner:NSScanner = NSScanner(string: str) var color:UInt32 = 0x0; colorScanner.scanHexInt(&color) let r:CGFloat = CGFloat((color & 0xFF0000) >> 16) / 255.0 let g:CGFloat = CGFloat((color & 0x00FF00) >> 8) / 255.0 let b:CGFloat = CGFloat(color & 0x0000FF) / 255.0 return UIColor(red:r, green:g, blue:b, alpha:1.0) } }
d27d20a86ad47379271a2bdb5abbd2f2
26.939394
66
0.593275
false
false
false
false
brunchmade/mojito
refs/heads/master
Mojito/MojitoServer.swift
mit
1
// // MojitoServer.swift // Mojito // // Created by Fang-Pen Lin on 12/24/15. // Copyright © 2015 VictorLin. All rights reserved. // import XCGLogger import InputMethodKit import SwiftyJSON import ReactiveCocoa import Result class MojitoServer : IMKServer, MojitoServerProtocol { let log = XCGLogger.defaultInstance() /// Signal for mojito server events let eventSignal:Signal<MojitoServerEvent, NoError> /// Is the candidates window visible or not private(set) var candidatesVisible = MutableProperty<Bool>(false) /// Candidates to display private(set) var candidates = MutableProperty<[EmojiCandidate]>([]) /// Selected candidate private(set) var selectedCandidate = MutableProperty<EmojiCandidate?>(nil) // MARK: Properties private var emojis:[Emoji] = [] private let eventObserver:Observer<MojitoServerEvent, NoError> weak var activeInputController:MojitoInputController? // MARK: Init override init!(name: String, bundleIdentifier: String) { // read emoji lib data let bundle = NSBundle.mainBundle() let emojilibPath = bundle.pathForResource("emojilib", ofType: "json") let emojilibContent = NSData(contentsOfFile: emojilibPath!) let emojilibJSON = JSON(data: emojilibContent!) let keys = emojilibJSON["keys"] for (_, obj):(String, JSON) in keys { let key = obj.stringValue let subJSON = emojilibJSON[key] let categories:[String] = subJSON["category"].map({ $1.stringValue }) let keywords:[String] = subJSON["keywords"].map({ $1.stringValue }) if let char = subJSON["char"].string { let emoji = Emoji( key: key, char:char.characters.first!, categories: categories, keywords: keywords ) emojis.append(emoji) } } (self.eventSignal, self.eventObserver) = Signal<MojitoServerEvent, NoError>.pipe() super.init(name: name, bundleIdentifier: bundleIdentifier) } // MARK: MojitoServerProtocol /// Build an EmojiInputEngine and return /// - Returns: An emoji input engine which conforms EmojiInputEngineProtocol func makeEmojiInputEngine() -> EmojiInputEngineProtocol { // TODO: pass configuration and emoji lib data to emoji input engine return EmojiInputEngine(emojis: emojis) } func moveCandidates(rect: NSRect) { self.eventObserver.sendNext(MojitoServerEvent.CandidatesViewMoved(textRect: rect)) } func selectNext() { self.eventObserver.sendNext(MojitoServerEvent.SelectNext) } func selectPrevious() { self.eventObserver.sendNext(MojitoServerEvent.SelectPrevious) } }
59a5373bc18886bc56f305c6a95c2dfe
34.5875
90
0.649104
false
false
false
false
JGiola/swift
refs/heads/main
test/Interpreter/async_fib.swift
apache-2.0
10
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -disable-availability-checking %s -parse-as-library -module-name main -o %t/main // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: concurrency // REQUIRES: executable_test // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime // UNSUPPORTED: OS=windows-msvc var gg = 0 @inline(never) public func identity<T>(_ x: T) -> T { gg += 1 return x } actor Actor { var x: Int = 0 init(x: Int) { self.x = x } @inline(never) func get(_ i: Int ) async -> Int { return i + x } } // Used to crash with an stack overflow with m >= 18 let m = 22 @inline(never) func asyncFib(_ n: Int, _ a1: Actor, _ a2: Actor) async -> Int { if n == 0 { return await a1.get(n) } if n == 1 { return await a2.get(n) } let first = await asyncFib(n-2, a1, a2) let second = await asyncFib(n-1, a1, a2) let result = first + second return result } @main struct Main { static func main() async { let a1 = Actor(x: 0) let a2 = Actor(x: 0) _ = await asyncFib(identity(m), a1, a2) // CHECK: result: 0 await print("result: \(a1.x)"); await print(a2.x) } }
1c97af9516fa03d7bf6d0a19b7a89352
19.366667
120
0.611293
false
false
false
false
SampleLiao/WWDC
refs/heads/master
WWDC/AppDelegate.swift
bsd-2-clause
5
// // AppDelegate.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa import Crashlytics import Updater @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow? private var downloadListWindowController: DownloadListWindowController? private var preferencesWindowController: PreferencesWindowController? func applicationOpenUntitledFile(sender: NSApplication) -> Bool { window?.makeKeyAndOrderFront(nil) return false } func applicationDidFinishLaunching(aNotification: NSNotification) { // start checking for live event LiveEventObserver.SharedObserver().start() // check for updates checkForUpdates(nil) // Keep a reference to the main application window window = NSApplication.sharedApplication().windows.last as! NSWindow? // continue any paused downloads VideoStore.SharedStore().initialize() // initialize Crashlytics GRCrashlyticsHelper.install() // tell the user he can watch the live keynote using the app, only once if !Preferences.SharedPreferences().userKnowsLiveEventThing { tellUserAboutTheLiveEventThing() } } func applicationWillFinishLaunching(notification: NSNotification) { // register custom URL scheme handler URLSchemeHandler.SharedHandler().register() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func checkForUpdates(sender: AnyObject?) { UDUpdater.sharedUpdater().updateAutomatically = true UDUpdater.sharedUpdater().checkForUpdatesWithCompletionHandler { newRelease in if newRelease != nil { if sender != nil { let alert = NSAlert() alert.messageText = "New version available" alert.informativeText = "Version \(newRelease.version) is now available. It will be installed automatically the next time you launch the app." alert.addButtonWithTitle("Ok") alert.runModal() } else { let notification = NSUserNotification() notification.title = "New version available" notification.informativeText = "A new version is available, relaunch the app to update" NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification) } } else { if sender != nil { let alert = NSAlert() alert.messageText = "You're up to date!" alert.informativeText = "You have the newest version" alert.addButtonWithTitle("Ok") alert.runModal() } } } } @IBAction func showDownloadsWindow(sender: AnyObject?) { if downloadListWindowController == nil { downloadListWindowController = DownloadListWindowController() } downloadListWindowController?.showWindow(self) } @IBAction func showPreferencesWindow(sender: AnyObject?) { if preferencesWindowController == nil { preferencesWindowController = PreferencesWindowController() } preferencesWindowController?.showWindow(self) } private func tellUserAboutTheLiveEventThing() { let alert = NSAlert() alert.messageText = "Did you know?" alert.informativeText = "You can watch live WWDC events using this app! Just open the app while the event is live and It will start playing automatically." alert.addButtonWithTitle("Got It!") alert.runModal() Preferences.SharedPreferences().userKnowsLiveEventThing = true } }
d9deb720022fba0fdb876c60601b3b5d
35.223214
163
0.631008
false
false
false
false
harungunaydin/Agenda-Master
refs/heads/master
FoldingCell/ViewController/AuthorizationsViewController.swift
mit
1
// // AuthorizationsViewController.swift // AgendaMaster // // Created by Harun Gunaydin on 4/28/16. // Copyright © 2016 Harun Gunaydin. All rights reserved. // import UIKit import GoogleAPIClient import GTMOAuth2 import ZFRippleButton import EventKit import StarWars class AuthorizationsViewController: UIViewController, UIViewControllerTransitioningDelegate { private let kKeychainItemName = "Google Calendar API" private let kClientID = "599334841741-tjcmvmd5lq8ovbnpk58pm4k041njh4do.apps.googleusercontent.com" private let service = GTLServiceCalendar() private let scopes = [kGTLAuthScopeCalendarReadonly] @IBOutlet weak var agendaMasterButton: ZFRippleButton! @IBOutlet weak var googleButton: ZFRippleButton! @IBOutlet weak var appleButton: ZFRippleButton! var count: Int = 0 func updateButtons() { dispatch_async(dispatch_get_main_queue(), { let defaults = NSUserDefaults.standardUserDefaults() if ( defaults.objectForKey("isSignedInAgendaMaster") as! Bool ) == false { self.agendaMasterButton.setTitle("Sign In", forState: .Normal) } else { self.agendaMasterButton.setTitle("Sign Out", forState: .Normal) } if ( defaults.objectForKey("isSignedInGoogle") as! Bool ) == false { self.googleButton.setTitle("Sign In", forState: .Normal) } else { self.googleButton.setTitle("Sign Out", forState: .Normal) } if ( defaults.objectForKey("isSignedInApple") as! Bool ) == false { self.appleButton.setTitle("Sync", forState: .Normal) } else { self.appleButton.setTitle("Done", forState: .Normal) self.appleButton.userInteractionEnabled = false } }) } @IBAction func updateBarButtonDidTapped(sender: AnyObject) { let alert = UIAlertController(title: "UPDATE", message: "Do you want to update all calendars?", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "YES", style: .Default, handler: { (action) -> Void in dispatch_async(dispatch_get_main_queue(), { self.pullEvents() }) dispatch_async(dispatch_get_main_queue(), { eventTable.prepareForReload() eventTable.tableView.reloadData() }) self.dismissViewControllerAnimated(true, completion: nil) })) alert.addAction(UIAlertAction(title: "NO", style: .Default, handler: { (action) in self.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.updateButtons() } override func viewDidLoad() { super.viewDidLoad() dispatch_async(dispatch_get_main_queue(), { self.updateButtons() self.agendaMasterButton.addTarget(nil, action: #selector(self.didTappedAgendaMasterButton) , forControlEvents: UIControlEvents.TouchUpInside) self.googleButton.addTarget(nil, action: #selector(self.didTappedGoogleButton) , forControlEvents: UIControlEvents.TouchUpInside) self.appleButton.addTarget(nil, action: #selector(self.didTappedAppleButton) , forControlEvents: UIControlEvents.TouchUpInside) }) } func didTappedAgendaMasterButton() { if agendaMasterButton.titleLabel!.text == "Sign In" { performSegueWithIdentifier("_Login_Agenda_Master", sender: self) } else { NSUserDefaults.standardUserDefaults().setObject(false, forKey: "isSignedInAgendaMaster") agendaMasterButton.setTitle("Sign In", forState: .Normal) NSUserDefaults.standardUserDefaults().removeObjectForKey("Agenda_Master_username") NSUserDefaults.standardUserDefaults().removeObjectForKey("Agenda_Master_password") self.displayAlert("Successful", message: "You have successfully logged out from Agenda Master") var temp = [Event]() for event in allEvents { if event.source.name != "Agenda Master" { temp.append(event) } } allEvents = temp temp.removeAll() dispatch_async(dispatch_get_main_queue(), { eventTable.prepareForReload() eventTable.tableView.reloadData() }) } } func didTappedGoogleButton() { if googleButton.titleLabel!.text == "Sign In" { self.linkWithGoogleCalendar() } else { service.authorizer = nil NSUserDefaults.standardUserDefaults().setObject(false, forKey: "isSignedInGoogle") googleButton.setTitle("Sign In", forState: .Normal) self.displayAlert("Successful", message: "You have successfully logged out from Google") var temp = [Event]() for event in allEvents { if event.source.name != "Google" { temp.append(event) } } allEvents = temp temp.removeAll() dispatch_async(dispatch_get_main_queue(), { eventTable.prepareForReload() eventTable.tableView.reloadData() }) } } func didTappedAppleButton() { if appleButton.titleLabel!.text == "Done" { dispatch_async(dispatch_get_main_queue(), { self.displayAlert("Sync", message: "You have already sycned with your iPhone's calendar") }) } else { self.linkWithIphoneCalendar() } } func linkWithGoogleCalendar() { if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName( kKeychainItemName, clientID: kClientID, clientSecret: nil) { service.authorizer = auth print("Google - service.authorizer = auth") } if ( NSUserDefaults.standardUserDefaults().objectForKey("isSignedInGoogle") as! Bool ) == true { if let authorizer = service.authorizer, canAuth = authorizer.canAuthorize where canAuth { print("Error!!! - Already signed in") } else { NSUserDefaults.standardUserDefaults().setObject(false, forKey: "isSignedInGoogle") service.authorizer = nil presentViewController( createAuthController(), animated: true, completion: nil ) } } else { presentViewController( createAuthController(), animated: true, completion: nil ) } } func linkWithIphoneCalendar() { let defaults = NSUserDefaults.standardUserDefaults() let eventStore = EKEventStore() eventStore.requestAccessToEntityType(.Event) {(granted, error) in if granted == false { defaults.setObject(false, forKey: "isSignedInApple") } else { dispatch_async(dispatch_get_main_queue(), { defaults.setObject(true, forKey: "isSignedInApple") self.updateButtons() self.pullEvents() }) } } } func checkCount() { self.count += 1 print("count = \(self.count)") if self.count == 3 { print("---Finished Pulling Events---") print("#Events = \(allEvents.count)") dispatch_async(dispatch_get_main_queue(), { eventTable.prepareForReload() eventTable.tableView.reloadData() }) } } func pullEvents() { print("---Started Pulling Events---") self.count = 0 if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName( kKeychainItemName, clientID: kClientID, clientSecret: nil) { service.authorizer = auth } allEvents.removeAll() filteredEvents.removeAll() // Pull events from Google Calendar dispatch_async(dispatch_get_main_queue(), { if ( NSUserDefaults.standardUserDefaults().objectForKey("isSignedInGoogle") as! Bool ) == true { print("Google SignIn - YES") self.fetchEventsFromGoogle() } else { print("Google SignIn - NO") self.checkCount() } }) // Pull events from local calendar - iPhone Calendar dispatch_async(dispatch_get_main_queue(), { if ( NSUserDefaults.standardUserDefaults().objectForKey("isSignedInApple") as! Bool ) == true { print("Apple SignIn - YES") self.fetchEventsFromIphoneCalendar() } else { print("Apple SignIn - NO") self.checkCount() } }) // Pull events from Agenda Master Website dispatch_async(dispatch_get_main_queue(), { if ( NSUserDefaults.standardUserDefaults().objectForKey("isSignedInAgendaMaster") as! Bool ) == true { print("Agenda Master SignIn - YES") self.fetchEventsFromAgendaMaster() } else { print("Agenda Master SignIn - NO") self.checkCount() } }) } func fetchEventsFromAgendaMaster() { let username = NSUserDefaults.standardUserDefaults().objectForKey("Agenda_Master_username") as? String let password = NSUserDefaults.standardUserDefaults().objectForKey("Agenda_Master_password") as? String if username == nil || password == nil { print("Did not login to the Agenda Master") self.checkCount() return } let url:NSURL = NSURL(string: "http://clockblocked.us/~brian/resources/php/ios_get_tasks.php?username=" + username! + "&password=" + password! + "&ios_getcode=bb7427431a38")! let urlSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let myQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in if error != nil { print("error getting Agenda Master events") self.checkCount() return } if let content = data { do { let jsonRes = try NSJSONSerialization.JSONObjectWithData(content, options: NSJSONReadingOptions.MutableContainers) let objects = jsonRes["events"]!! print("Json convertion is successful and size => \(objects.count)") for i in 0 ..< objects.count { if let source = objects[i]["source"] as? String { if source != "native" { continue } let newEvent = Event() newEvent.objectId = "AGMASTER" + ( objects[i]["id"] as! String ) newEvent.name = objects[i]["title"] as? String newEvent.summary = objects[i]["description"] as? String let formatter = NSDateFormatter() formatter.dateFormat = "MMM dd, yyyy" let formatter2 = NSDateFormatter() formatter2.dateFormat = "hh:mm a" if let startDate = objects[i]["startDate"] as? String { newEvent.startDate = NSDate(timeIntervalSince1970: Double(startDate)!) newEvent.startDateString = formatter.stringFromDate(newEvent.startDate) newEvent.startHourString = formatter2.stringFromDate(newEvent.startDate) } if let endDate = objects[i]["endDate"] as? String { newEvent.endDate = NSDate(timeIntervalSince1970: Double(endDate)!) newEvent.endDateString = formatter.stringFromDate(newEvent.endDate) newEvent.endHourString = formatter2.stringFromDate(newEvent.endDate) } newEvent.location = objects[i]["location"] as? String newEvent.source = sources[0] allEvents.append(newEvent) } } self.checkCount() } catch { self.checkCount() print("Can not convert to JSON. Check you internet connection") } } else { self.checkCount() print("Check your internet connection") } }) myQuery.resume() } func fetchEventsFromIphoneCalendar() { switch EKEventStore.authorizationStatusForEntityType(.Event) { case .Authorized: let eventStore = EKEventStore() let events = eventStore.eventsMatchingPredicate( eventStore.predicateForEventsWithStartDate(NSDate(), endDate: NSDate(timeIntervalSinceNow: 3*30*24*3600), calendars: [eventStore.defaultCalendarForNewEvents]) ) print( eventStore.defaultCalendarForNewEvents.title ) for event in events { let newEvent = Event() let formatter = NSDateFormatter() formatter.dateFormat = "MMM dd, yyyy" let formatter2 = NSDateFormatter() formatter2.dateFormat = "hh:mm a" newEvent.startDate = event.startDate newEvent.endDate = event.endDate if newEvent.startDate != nil { newEvent.startDateString = formatter.stringFromDate(newEvent.startDate) newEvent.startHourString = formatter2.stringFromDate(newEvent.startDate) } if newEvent.endDate != nil { newEvent.endDateString = formatter.stringFromDate(newEvent.endDate) newEvent.endHourString = formatter2.stringFromDate(newEvent.endDate) } newEvent.objectId = event.eventIdentifier newEvent.location = event.location newEvent.source = sources[2] // Source: Apple if let start = newEvent.startDate { if let end = newEvent.endDate { newEvent.duration = end.timeIntervalSinceDate(start) } } newEvent.name = event.title newEvent.summary = event.notes allEvents.append(newEvent) } self.checkCount() break default: self.checkCount() break } } func fetchEventsFromGoogle() { if let authorizer = service.authorizer, canAuth = authorizer.canAuthorize where canAuth { } else { print("Error!!! - Signed in but could not authorize. fetchEventsFromGoogle - AuthorizationsViewController") googleButton.setTitle("Sign In", forState: .Normal) NSUserDefaults.standardUserDefaults().setObject(false, forKey: "isSignedInGoogle") self.checkCount() return } print("fetchEventsFromGoogle") let query = GTLQueryCalendar.queryForEventsListWithCalendarId("primary") query.maxResults = 100 query.timeMin = GTLDateTime(date: NSDate(), timeZone: NSTimeZone.localTimeZone() ) query.singleEvents = true query.orderBy = kGTLCalendarOrderByStartTime service.executeQuery(query) { (ticket, object, error) in if error != nil { self.dismissViewControllerAnimated(true, completion: { print("Please check your internet connection") }) return } if let events = object.items() as? [GTLCalendarEvent] { for event in events { let newEvent = Event() newEvent.name = event.summary let formatter = NSDateFormatter() formatter.dateFormat = "MMM dd, yyyy" let formatter2 = NSDateFormatter() formatter2.dateFormat = "hh:mm a" if event.start != nil && event.start.dateTime != nil { newEvent.startDate = event.start.dateTime.date newEvent.startDateString = formatter.stringFromDate(newEvent.startDate) newEvent.startHourString = formatter2.stringFromDate(newEvent.startDate) } if event.end != nil && event.end.dateTime != nil { newEvent.endDate = event.end.dateTime.date newEvent.endDateString = formatter.stringFromDate(newEvent.endDate) newEvent.endHourString = formatter2.stringFromDate(newEvent.endDate) } if newEvent.startDate != nil && newEvent.endDate != nil { newEvent.duration = newEvent.endDate.timeIntervalSinceDate(newEvent.startDate) } newEvent.source = sources[1] newEvent.summary = event.descriptionProperty newEvent.location = event.location newEvent.objectId = event.identifier allEvents.append(newEvent) } } print("fetchEventsFromGoogle - Done") self.checkCount() } } // Creates the auth controller for authorizing access to Google Calendar API private func createAuthController() -> GTMOAuth2ViewControllerTouch { let scopeString = scopes.joinWithSeparator(" ") return GTMOAuth2ViewControllerTouch( scope: scopeString, clientID: kClientID, clientSecret: nil, keychainItemName: kKeychainItemName, delegate: self, finishedSelector: #selector(self.viewController(_:finishedWithAuth:error:)) ) } // Handle completion of the authorization process, and update the Google Calendar API // with the new credentials. func viewController(vc : UIViewController, finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) { if let error = error { service.authorizer = nil self.displayAlert("Authentication Error", message: error.localizedDescription) return } service.authorizer = authResult NSUserDefaults.standardUserDefaults().setObject(true, forKey: "isSignedInGoogle") dismissViewControllerAnimated(true, completion: nil) self.pullEvents() } func displayAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in self.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destination = segue.destinationViewController destination.transitioningDelegate = self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { print("animationControllerForDismissedController") return StarWarsGLAnimator() } }
3e7eda005224d81c26e0fbad85bf1de1
37.40411
235
0.523209
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Default Dependency Implementations/Core Data Store/CoreDataStore.swift
mit
1
import CoreData import Foundation import os public struct CoreDataStore: DataStore { private static let log = OSLog(subsystem: "org.eurofurence.EurofurenceModel", category: "Core Data") private class EurofurencePersistentContainer: NSPersistentContainer { override class func defaultDirectoryURL() -> URL { return FileUtilities.sharedContainerURL.appendingPathComponent("Model") } } // MARK: Properties public let container: NSPersistentContainer public let storeLocation: URL // MARK: Initialization public init(storeName: String) { let modelName = "EurofurenceApplicationModel" guard let modelPath = Bundle.module.url(forResource: modelName, withExtension: "momd") else { fatalError("Core Data model missing from bundle") } guard let model = NSManagedObjectModel(contentsOf: modelPath) else { fatalError("Failed to interpolate model from definition") } container = EurofurencePersistentContainer(name: modelName, managedObjectModel: model) storeLocation = EurofurencePersistentContainer.defaultDirectoryURL().appendingPathComponent(storeName) let description = NSPersistentStoreDescription(url: storeLocation) description.type = NSSQLiteStoreType description.shouldMigrateStoreAutomatically = true description.shouldInferMappingModelAutomatically = true container.persistentStoreDescriptions = [description] container.loadPersistentStores { (_, error) in if let error = error { os_log( "Failed to load persistent stores: %{public}s", log: Self.log, type: .error, String(describing: error) ) } } } // MARK: DataStore public func performTransaction(_ block: @escaping (DataStoreTransaction) -> Void) { let context = container.viewContext let transaction = CoreDataStoreTransaction() block(transaction) transaction.performMutations(context: context) do { try context.save() } catch { print(error) } } public func fetchKnowledgeGroups() -> [KnowledgeGroupCharacteristics]? { return getModels(fetchRequest: KnowledgeGroupEntity.fetchRequest()) } public func fetchKnowledgeEntries() -> [KnowledgeEntryCharacteristics]? { return getModels(fetchRequest: KnowledgeEntryEntity.fetchRequest()) } public func fetchLastRefreshDate() -> Date? { var lastRefreshDate: Date? let context = container.viewContext context.performAndWait { do { let fetchRequest: NSFetchRequest<LastRefreshEntity> = LastRefreshEntity.fetchRequest() fetchRequest.fetchLimit = 1 let entity = try fetchRequest.execute() if let date = entity.first?.lastRefreshDate { lastRefreshDate = date as Date } } catch { print(error) } } return lastRefreshDate } public func fetchRooms() -> [RoomCharacteristics]? { return getModels(fetchRequest: RoomEntity.fetchRequest()) } public func fetchTracks() -> [TrackCharacteristics]? { return getModels(fetchRequest: TrackEntity.fetchRequest()) } public func fetchEvents() -> [EventCharacteristics]? { return getModels(fetchRequest: EventEntity.fetchRequest()) } public func fetchAnnouncements() -> [AnnouncementCharacteristics]? { return getModels(fetchRequest: AnnouncementEntity.fetchRequest()) } public func fetchConferenceDays() -> [ConferenceDayCharacteristics]? { return getModels(fetchRequest: ConferenceDayEntity.fetchRequest()) } public func fetchFavouriteEventIdentifiers() -> [EventIdentifier]? { return getModels(fetchRequest: FavouriteEventEntity.fetchRequest()) } public func fetchDealers() -> [DealerCharacteristics]? { return getModels(fetchRequest: DealerEntity.fetchRequest()) } public func fetchMaps() -> [MapCharacteristics]? { return getModels(fetchRequest: MapEntity.fetchRequest()) } public func fetchReadAnnouncementIdentifiers() -> [AnnouncementIdentifier]? { return getModels(fetchRequest: ReadAnnouncementEntity.fetchRequest()) } public func fetchImages() -> [ImageCharacteristics]? { return getModels(fetchRequest: ImageModelEntity.fetchRequest()) } // MARK: Private private func getModels<Entity>( fetchRequest: NSFetchRequest<Entity> ) -> [Entity.AdaptedType]? where Entity: EntityAdapting { var models: [Entity.AdaptedType]? let context = container.viewContext context.performAndWait { do { let entities = try fetchRequest.execute() models = entities.map({ $0.asAdaptedType() }) } catch { print(error) } } return models } }
c62f704799b5f2813b0af67f557bda37
32.623377
110
0.641947
false
false
false
false
calebd/swift
refs/heads/master
stdlib/public/core/Sequence.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that supplies the values of a sequence one at a time. /// /// The `IteratorProtocol` protocol is tightly linked with the `Sequence` /// protocol. Sequences provide access to their elements by creating an /// iterator, which keeps track of its iteration process and returns one /// element at a time as it advances through the sequence. /// /// Whenever you use a `for`-`in` loop with an array, set, or any other /// collection or sequence, you're using that type's iterator. Swift uses a /// sequence's or collection's iterator internally to enable the `for`-`in` /// loop language construct. /// /// Using a sequence's iterator directly gives you access to the same elements /// in the same order as iterating over that sequence using a `for`-`in` loop. /// For example, you might typically use a `for`-`in` loop to print each of /// the elements in an array. /// /// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"] /// for animal in animals { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// Behind the scenes, Swift uses the `animals` array's iterator to loop over /// the contents of the array. /// /// var animalIterator = animals.makeIterator() /// while let animal = animalIterator.next() { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// The call to `animals.makeIterator()` returns an instance of the array's /// iterator. Next, the `while` loop calls the iterator's `next()` method /// repeatedly, binding each element that is returned to `animal` and exiting /// when the `next()` method returns `nil`. /// /// Using Iterators Directly /// ======================== /// /// You rarely need to use iterators directly, because a `for`-`in` loop is the /// more idiomatic approach to traversing a sequence in Swift. Some /// algorithms, however, may call for direct iterator use. /// /// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)` /// method defined in the standard library, which takes an initial value and a /// combining closure, `reduce1(_:)` uses the first element of the sequence as /// the initial value. /// /// Here's an implementation of the `reduce1(_:)` method. The sequence's /// iterator is used directly to retrieve the initial value before looping /// over the rest of the sequence. /// /// extension Sequence { /// func reduce1( /// _ nextPartialResult: (Element, Element) -> Element /// ) -> Element? /// { /// var i = makeIterator() /// guard var accumulated = i.next() else { /// return nil /// } /// /// while let element = i.next() { /// accumulated = nextPartialResult(accumulated, element) /// } /// return accumulated /// } /// } /// /// The `reduce1(_:)` method makes certain kinds of sequence operations /// simpler. Here's how to find the longest string in a sequence, using the /// `animals` array introduced earlier as an example: /// /// let longestAnimal = animals.reduce1 { current, element in /// if current.count > element.count { /// return current /// } else { /// return element /// } /// } /// print(longestAnimal) /// // Prints "Butterfly" /// /// Using Multiple Iterators /// ======================== /// /// Whenever you use multiple iterators (or `for`-`in` loops) over a single /// sequence, be sure you know that the specific sequence supports repeated /// iteration, either because you know its concrete type or because the /// sequence is also constrained to the `Collection` protocol. /// /// Obtain each separate iterator from separate calls to the sequence's /// `makeIterator()` method rather than by copying. Copying an iterator is /// safe, but advancing one copy of an iterator by calling its `next()` method /// may invalidate other copies of that iterator. `for`-`in` loops are safe in /// this regard. /// /// Adding IteratorProtocol Conformance to Your Type /// ================================================ /// /// Implementing an iterator that conforms to `IteratorProtocol` is simple. /// Declare a `next()` method that advances one step in the related sequence /// and returns the current element. When the sequence has been exhausted, the /// `next()` method returns `nil`. /// /// For example, consider a custom `Countdown` sequence. You can initialize the /// `Countdown` sequence with a starting integer and then iterate over the /// count down to zero. The `Countdown` structure's definition is short: It /// contains only the starting count and the `makeIterator()` method required /// by the `Sequence` protocol. /// /// struct Countdown: Sequence { /// let start: Int /// /// func makeIterator() -> CountdownIterator { /// return CountdownIterator(self) /// } /// } /// /// The `makeIterator()` method returns another custom type, an iterator named /// `CountdownIterator`. The `CountdownIterator` type keeps track of both the /// `Countdown` sequence that it's iterating and the number of times it has /// returned a value. /// /// struct CountdownIterator: IteratorProtocol { /// let countdown: Countdown /// var times = 0 /// /// init(_ countdown: Countdown) { /// self.countdown = countdown /// } /// /// mutating func next() -> Int? { /// let nextNumber = countdown.start - times /// guard nextNumber > 0 /// else { return nil } /// /// times += 1 /// return nextNumber /// } /// } /// /// Each time the `next()` method is called on a `CountdownIterator` instance, /// it calculates the new next value, checks to see whether it has reached /// zero, and then returns either the number, or `nil` if the iterator is /// finished returning elements of the sequence. /// /// Creating and iterating over a `Countdown` sequence uses a /// `CountdownIterator` to handle the iteration. /// /// let threeTwoOne = Countdown(start: 3) /// for count in threeTwoOne { /// print("\(count)...") /// } /// // Prints "3..." /// // Prints "2..." /// // Prints "1..." public protocol IteratorProtocol { /// The type of element traversed by the iterator. associatedtype Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns, in order, all the elements of the /// underlying sequence. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// You must not call this method if any other copy of this iterator has been /// advanced with a call to its `next()` method. /// /// The following example shows how an iterator can be used explicitly to /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and /// then call the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. mutating func next() -> Element? } /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// Here's a definition of a `Countdown` sequence that serves as its own /// iterator. The `makeIterator()` method is provided as a default /// implementation. /// /// struct Countdown: Sequence, IteratorProtocol { /// var count: Int /// /// mutating func next() -> Int? { /// if count == 0 { /// return nil /// } else { /// defer { count -= 1 } /// return count /// } /// } /// } /// /// let threeToGo = Countdown(count: 3) /// for i in threeToGo { /// print(i) /// } /// // Prints "3" /// // Prints "2" /// // Prints "1" /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. public protocol Sequence { /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. associatedtype Element associatedtype Iterator : IteratorProtocol where Iterator.Element == Element /// A type that represents a subsequence of some of the sequence's elements. associatedtype SubSequence // FIXME(ABI)#104 (Recursive Protocol Constraints): // FIXME(ABI)#105 (Associated Types with where clauses): // associatedtype SubSequence : Sequence // where // Element == SubSequence.Element, // SubSequence.SubSequence == SubSequence // // (<rdar://problem/20715009> Implement recursive protocol // constraints) // // These constraints allow processing collections in generic code by // repeatedly slicing them in a loop. /// Returns an iterator over the elements of this sequence. func makeIterator() -> Iterator /// A value less than or equal to the number of elements in /// the sequence, calculated nondestructively. /// /// - Complexity: O(1) var underestimatedCount: Int { get } /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. func forEach(_ body: (Element) throws -> Void) rethrows // Note: The complexity of Sequence.dropFirst(_:) requirement // is documented as O(n) because Collection.dropFirst(_:) is // implemented in O(n), even though the default // implementation for Sequence.dropFirst(_:) is O(1). /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the sequence. func dropFirst(_ n: Int) -> SubSequence /// Returns a subsequence containing all but the specified number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func dropLast(_ n: Int) -> SubSequence /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element is a match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func drop( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the specified maximum length, containing /// the initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. func prefix(_ maxLength: Int) -> SubSequence /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func prefix( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number /// of elements in the sequence, the result contains all the elements in /// the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of this sequence with /// at most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func suffix(_ maxLength: Int) -> SubSequence /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " }) /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. func split( maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [SubSequence] func _customContainsEquatableElement( _ element: Element ) -> Bool? /// If `self` is multi-pass (i.e., a `Collection`), invoke `preprocess` and /// return its result. Otherwise, return `nil`. func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? /// Create a native array buffer containing the elements of `self`, /// in the same order. func _copyToContiguousArray() -> ContiguousArray<Element> /// Copy `self` into an unsafe buffer, returning a partially-consumed /// iterator with any elements that didn't fit remaining. func _copyContents( initializing ptr: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) } /// A default makeIterator() function for `IteratorProtocol` instances that /// are declared to conform to `Sequence` extension Sequence where Self.Iterator == Self { /// Returns an iterator over the elements of this sequence. @_inlineable public func makeIterator() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @_versioned @_fixed_layout internal struct _DropFirstSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @_versioned internal var _iterator: Base @_versioned internal let _limit: Int @_versioned internal var _dropped: Int @_versioned @_inlineable internal init(_iterator: Base, limit: Int, dropped: Int = 0) { self._iterator = _iterator self._limit = limit self._dropped = dropped } @_versioned @_inlineable internal func makeIterator() -> _DropFirstSequence<Base> { return self } @_versioned @_inlineable internal mutating func next() -> Base.Element? { while _dropped < _limit { if _iterator.next() == nil { _dropped = _limit return nil } _dropped += 1 } return _iterator.next() } @_versioned @_inlineable internal func dropFirst(_ n: Int) -> AnySequence<Base.Element> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return AnySequence( _DropFirstSequence( _iterator: _iterator, limit: _limit + n, dropped: _dropped)) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` iterator. /// /// The underlying iterator's sequence may be infinite. @_fixed_layout @_versioned internal struct _PrefixSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @_versioned internal let _maxLength: Int @_versioned internal var _iterator: Base @_versioned internal var _taken: Int @_versioned @_inlineable internal init(_iterator: Base, maxLength: Int, taken: Int = 0) { self._iterator = _iterator self._maxLength = maxLength self._taken = taken } @_versioned @_inlineable internal func makeIterator() -> _PrefixSequence<Base> { return self } @_versioned @_inlineable internal mutating func next() -> Base.Element? { if _taken >= _maxLength { return nil } _taken += 1 if let next = _iterator.next() { return next } _taken = _maxLength return nil } @_versioned @_inlineable internal func prefix(_ maxLength: Int) -> AnySequence<Base.Element> { return AnySequence( _PrefixSequence( _iterator: _iterator, maxLength: Swift.min(maxLength, self._maxLength), taken: _taken)) } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @_fixed_layout @_versioned internal struct _DropWhileSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { typealias Element = Base.Element @_versioned internal var _iterator: Base @_versioned internal var _nextElement: Base.Element? @_versioned @_inlineable internal init( iterator: Base, nextElement: Base.Element?, predicate: (Base.Element) throws -> Bool ) rethrows { self._iterator = iterator self._nextElement = nextElement ?? _iterator.next() while try _nextElement.flatMap(predicate) == true { _nextElement = _iterator.next() } } @_versioned @_inlineable internal func makeIterator() -> _DropWhileSequence<Base> { return self } @_versioned @_inlineable internal mutating func next() -> Element? { guard _nextElement != nil else { return _iterator.next() } let next = _nextElement _nextElement = nil return next } @_versioned @_inlineable internal func drop( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { // If this is already a _DropWhileSequence, avoid multiple // layers of wrapping and keep the same iterator. return try AnySequence( _DropWhileSequence( iterator: _iterator, nextElement: _nextElement, predicate: predicate)) } } //===----------------------------------------------------------------------===// // Default implementations for Sequence //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. @_inlineable public func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. @_inlineable public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { return try _filter(isIncluded) } @_transparent public func _filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() var iterator = self.makeIterator() while let element = iterator.next() { if try isIncluded(element) { result.append(element) } } return Array(result) } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number of /// elements in the sequence, the result contains all the elements in the /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func suffix(_ maxLength: Int) -> AnySequence<Element> { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") if maxLength == 0 { return AnySequence([]) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into an `Array` // and return it. This saves memory for sequences particularly longer // than `maxLength`. var ringBuffer: [Element] = [] ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount)) var i = ringBuffer.startIndex for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i += 1 i %= maxLength } } if i != ringBuffer.startIndex { let s0 = ringBuffer[i..<ringBuffer.endIndex] let s1 = ringBuffer[0..<i] return AnySequence([s0, s1].joined()) } return AnySequence(ringBuffer) } /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. Elements that are /// used to split the sequence are not returned as part of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `true` for the `allowEmptySlices` parameter, so /// the returned array contains empty strings where spaces were repeated. /// /// print( /// line.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. @_inlineable public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [AnySequence<Element>] { _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [AnySequence<Element>] = [] var subSequence: [Element] = [] @discardableResult func appendSubsequence() -> Bool { if subSequence.isEmpty && omittingEmptySubsequences { return false } result.append(AnySequence(subSequence)) subSequence = [] return true } if maxSplits == 0 { // We aren't really splitting the sequence. Convert `self` into an // `Array` using a fast entry point. subSequence = Array(self) appendSubsequence() return result } var iterator = self.makeIterator() while let element = iterator.next() { if try isSeparator(element) { if !appendSubsequence() { continue } if result.count == maxSplits { break } } else { subSequence.append(element) } } while let element = iterator.next() { subSequence.append(element) } appendSubsequence() return result } /// Returns a value less than or equal to the number of elements in /// the sequence, nondestructively. /// /// - Complexity: O(*n*) @_inlineable public var underestimatedCount: Int { return 0 } @_inlineable public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return nil } @_inlineable public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. @_inlineable public func forEach( _ body: (Element) throws -> Void ) rethrows { for element in self { try body(element) } } } @_versioned @_fixed_layout internal enum _StopIteration : Error { case stop } extension Sequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// The following example uses the `first(where:)` method to find the first /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let firstNegative = numbers.first(where: { $0 < 0 }) { /// print("The first negative number is \(firstNegative).") /// } /// // Prints "The first negative number is -2." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. @_inlineable public func first( where predicate: (Element) throws -> Bool ) rethrows -> Element? { var foundElement: Element? do { try self.forEach { if try predicate($0) { foundElement = $0 throw _StopIteration.stop } } } catch is _StopIteration { } return foundElement } } extension Sequence where Element : Equatable { /// Returns the longest possible subsequences of the sequence, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the sequence and for each instance of `separator` at the /// start or end of the sequence. If `true`, only nonempty subsequences /// are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. @_inlineable public func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [AnySequence<Element>] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Sequence where SubSequence : Sequence, SubSequence.Element == Element, SubSequence.SubSequence == SubSequence { /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(1). @_inlineable public func dropFirst(_ n: Int) -> AnySequence<Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: n)) } /// Returns a subsequence containing all but the given number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func dropLast(_ n: Int) -> AnySequence<Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= n. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `n` * sizeof(Element) of memory, because slices keep the entire // memory of an `Array` alive. var result: [Element] = [] var ringBuffer: [Element] = [] var i = ringBuffer.startIndex for element in self { if ringBuffer.count < n { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = ringBuffer.index(after: i) % n } } return AnySequence(result) } /// Returns a subsequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `drop(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an /// empty sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence starting after the initial, consecutive elements /// that satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func drop( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { return try AnySequence( _DropWhileSequence( iterator: makeIterator(), nextElement: nil, predicate: predicate)) } /// Returns a subsequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. /// /// - Complexity: O(1) @_inlineable public func prefix(_ maxLength: Int) -> AnySequence<Element> { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence") if maxLength == 0 { return AnySequence(EmptyCollection<Element>()) } return AnySequence( _PrefixSequence(_iterator: makeIterator(), maxLength: maxLength)) } /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func prefix( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { var result: [Element] = [] for element in self { guard try predicate(element) else { break } result.append(element) } return AnySequence(result) } } extension Sequence { /// Returns a subsequence containing all but the first element of the /// sequence. /// /// The following example drops the first element from an array of integers. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst()) /// // Prints "[2, 3, 4, 5]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropFirst()) /// // Prints "[]" /// /// - Returns: A subsequence starting after the first element of the /// sequence. /// /// - Complexity: O(1) @_inlineable public func dropFirst() -> SubSequence { return dropFirst(1) } /// Returns a subsequence containing all but the last element of the /// sequence. /// /// The sequence must be finite. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast()) /// // Prints "[1, 2, 3, 4]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropLast()) /// // Prints "[]" /// /// - Returns: A subsequence leaving off the last element of the sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func dropLast() -> SubSequence { return dropLast(1) } } extension Sequence { /// Copies `self` into the supplied buffer. /// /// - Precondition: The memory in `self` is uninitialized. The buffer must /// contain sufficient uninitialized memory to accommodate `source.underestimatedCount`. /// /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are /// initialized. @_inlineable public func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { var it = self.makeIterator() guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) } for idx in buffer.startIndex..<buffer.count { guard let x = it.next() else { return (it, idx) } ptr.initialize(to: x) ptr += 1 } return (it,buffer.endIndex) } } // FIXME(ABI)#182 // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness" /// A sequence built around an iterator of type `Base`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just an iterator `i`: /// /// for x in IteratorSequence(i) { ... } @_fixed_layout public struct IteratorSequence< Base : IteratorProtocol > : IteratorProtocol, Sequence { /// Creates an instance whose iterator is a copy of `base`. @_inlineable public init(_ base: Base) { _base = base } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @_inlineable public mutating func next() -> Base.Element? { return _base.next() } @_versioned internal var _base: Base } @available(*, unavailable, renamed: "IteratorProtocol") public typealias GeneratorType = IteratorProtocol @available(*, unavailable, renamed: "Sequence") public typealias SequenceType = Sequence extension Sequence { @available(*, unavailable, renamed: "makeIterator()") public func generate() -> Iterator { Builtin.unreachable() } @available(*, unavailable, renamed: "getter:underestimatedCount()") public func underestimateCount() -> Int { Builtin.unreachable() } @available(*, unavailable, message: "call 'split(maxSplits:omittingEmptySubsequences:whereSeparator:)' and invert the 'allowEmptySlices' argument") public func split(_ maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Element) throws -> Bool ) rethrows -> [SubSequence] { Builtin.unreachable() } } extension Sequence where Element : Equatable { @available(*, unavailable, message: "call 'split(separator:maxSplits:omittingEmptySubsequences:)' and invert the 'allowEmptySlices' argument") public func split( _ separator: Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [AnySequence<Element>] { Builtin.unreachable() } } @available(*, unavailable, renamed: "IteratorSequence") public struct GeneratorSequence<Base : IteratorProtocol> {}
5c7615dff7cdf2477506a5eb7bc49c11
35.363817
149
0.630401
false
false
false
false
marekhac/WczasyNadBialym-iOS
refs/heads/master
WczasyNadBialym/WczasyNadBialym/Models/Network/Event/NetworkController+Event.swift
gpl-3.0
1
// // NetworkController+Event.swift // WczasyNadBialym // // Created by Marek Hać on 20/05/2020. // Copyright © 2020 Marek Hać. All rights reserved. // import Foundation extension NetworkController { func getEventsList(_ completionHandlerForEventsList: @escaping (_ result: [EventModel]?) -> Void) { let controller = API.Event.Controller.Events let method = API.Event.Method.List let parameters = [String: String]() let request = NSMutableURLRequest(url: buildURLFromParameters(controller, method, parameters)) as URLRequest downloadContent(with: request) { (result) in switch result { case .success(let content): let sections = content.parseData(using: EventModel.eventsFromResults) completionHandlerForEventsList(sections as? [EventModel]) case .failure(let error): LogEventHandler.report(LogEventType.error, "Unable to download Event Sections", error.localizedDescription, displayWithHUD: true) } } } func getEventDetails (_ eventId : String, _ completionHandlerForEvents: @escaping (_ result: EventDetailModel?) -> Void) { let controller = API.Event.Controller.Events let method = API.Event.Method.Details let parameters = [API.Event.ParameterKey.Id : eventId] let request = NSMutableURLRequest(url: buildURLFromParameters(controller, method, parameters)) as URLRequest downloadContent(with: request) { (result) in switch result { case .success(let content): let details = content.parseData(using: EventDetailModel.detailsFromResults) completionHandlerForEvents(details as? EventDetailModel) case .failure(let error): LogEventHandler.report(LogEventType.error, "Unable to download Event Details", error.localizedDescription, displayWithHUD: true) } } } }
c66ed26892c0e617de65442a2e17d5e6
38.480769
145
0.640039
false
false
false
false
mohitathwani/swift-corelibs-foundation
refs/heads/master
Foundation/NSRange.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public struct _NSRange { public var location: Int public var length: Int public init() { location = 0 length = 0 } public init(location: Int, length: Int) { self.location = location self.length = length } internal init(_ range: CFRange) { location = range.location == kCFNotFound ? NSNotFound : range.location length = range.length } } extension CFRange { internal init(_ range: NSRange) { location = range.location == NSNotFound ? kCFNotFound : range.location length = range.length } } public typealias NSRange = _NSRange extension NSRange { public init(_ x: Range<Int>) { location = x.lowerBound length = x.count } public func toRange() -> Range<Int>? { if location == NSNotFound { return nil } return location..<(location+length) } internal func toCountableRange() -> CountableRange<Int>? { if location == NSNotFound { return nil } return location..<(location+length) } } extension NSRange: NSSpecialValueCoding { init(bytes: UnsafeRawPointer) { self.location = bytes.load(as: Int.self) self.length = bytes.load(fromByteOffset: MemoryLayout<Int>.stride, as: Int.self) } init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if let location = aDecoder.decodeObject(of: NSNumber.self, forKey: "NS.rangeval.location") { self.location = location.intValue } else { self.location = 0 } if let length = aDecoder.decodeObject(of: NSNumber.self, forKey: "NS.rangeval.length") { self.length = length.intValue } else { self.length = 0 } } func encodeWithCoder(_ aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(NSNumber(value: self.location), forKey: "NS.rangeval.location") aCoder.encode(NSNumber(value: self.length), forKey: "NS.rangeval.length") } static func objCType() -> String { #if arch(i386) || arch(arm) return "{_NSRange=II}" #elseif arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) return "{_NSRange=QQ}" #else NSUnimplemented() #endif } func getValue(_ value: UnsafeMutableRawPointer) { value.initializeMemory(as: NSRange.self, to: self) } func isEqual(_ aValue: Any) -> Bool { if let other = aValue as? NSRange { return other.location == self.location && other.length == self.length } else { return false } } var hash: Int { return self.location &+ self.length } var description: String? { return NSStringFromRange(self) } } public typealias NSRangePointer = UnsafeMutablePointer<NSRange> public func NSMakeRange(_ loc: Int, _ len: Int) -> NSRange { return NSRange(location: loc, length: len) } public func NSMaxRange(_ range: NSRange) -> Int { return range.location + range.length } public func NSLocationInRange(_ loc: Int, _ range: NSRange) -> Bool { return !(loc < range.location) && (loc - range.location) < range.length } public func NSEqualRanges(_ range1: NSRange, _ range2: NSRange) -> Bool { return range1.location == range2.location && range1.length == range2.length } public func NSUnionRange(_ range1: NSRange, _ range2: NSRange) -> NSRange { let max1 = range1.location + range1.length let max2 = range2.location + range2.length let maxend: Int if max1 > max2 { maxend = max1 } else { maxend = max2 } let minloc: Int if range1.location < range2.location { minloc = range1.location } else { minloc = range2.location } return NSMakeRange(minloc, maxend - minloc) } public func NSIntersectionRange(_ range1: NSRange, _ range2: NSRange) -> NSRange { let max1 = range1.location + range1.length let max2 = range2.location + range2.length let minend: Int if max1 < max2 { minend = max1 } else { minend = max2 } if range2.location <= range1.location && range1.location < max2 { return NSMakeRange(range1.location, minend - range1.location) } else if range1.location <= range2.location && range2.location < max1 { return NSMakeRange(range2.location, minend - range2.location) } return NSMakeRange(0, 0) } public func NSStringFromRange(_ range: NSRange) -> String { return "{\(range.location), \(range.length)}" } public func NSRangeFromString(_ aString: String) -> NSRange { let emptyRange = NSMakeRange(0, 0) if aString.isEmpty { // fail early if the string is empty return emptyRange } let scanner = Scanner(string: aString) let digitSet = CharacterSet.decimalDigits let _ = scanner.scanUpToCharactersFromSet(digitSet) if scanner.atEnd { // fail early if there are no decimal digits return emptyRange } guard let location = scanner.scanInteger() else { return emptyRange } let partialRange = NSMakeRange(location, 0) if scanner.atEnd { // return early if there are no more characters after the first int in the string return partialRange } let _ = scanner.scanUpToCharactersFromSet(digitSet) if scanner.atEnd { // return early if there are no integer characters after the first int in the string return partialRange } guard let length = scanner.scanInteger() else { return partialRange } return NSMakeRange(location, length) } extension NSValue { public convenience init(range: NSRange) { self.init() self._concreteValue = NSSpecialValue(range) } public var rangeValue: NSRange { let specialValue = self._concreteValue as! NSSpecialValue return specialValue._value as! NSRange } }
4fa047a66fde4951ba95143c65dcbc04
29.036866
100
0.635164
false
false
false
false
edragoev1/pdfjet
refs/heads/master
Sources/PDFjet/OpenTypeFont.swift
mit
1
/** * OpenTypeFont.swift * Copyright 2020 Innovatics Inc. */ import Foundation class OpenTypeFont { internal static func register( _ pdf: PDF, _ font: Font, _ stream: InputStream) { let otf = OTF(stream) font.name = otf.fontName! font.firstChar = otf.firstChar! font.lastChar = otf.lastChar! font.unicodeToGID = otf.unicodeToGID font.unitsPerEm = otf.unitsPerEm! font.bBoxLLx = otf.bBoxLLx! font.bBoxLLy = otf.bBoxLLy! font.bBoxURx = otf.bBoxURx! font.bBoxURy = otf.bBoxURy! font.advanceWidth = otf.advanceWidth! font.glyphWidth = otf.glyphWidth font.fontAscent = otf.ascent! font.fontDescent = otf.descent! font.fontUnderlinePosition = otf.underlinePosition! font.fontUnderlineThickness = otf.underlineThickness! font.setSize(font.size) embedFontFile(pdf, font, otf) addFontDescriptorObject(pdf, font, otf) addCIDFontDictionaryObject(pdf, font, otf) addToUnicodeCMapObject(pdf, font, otf) // Type0 Font Dictionary pdf.newobj() pdf.append("<<\n") pdf.append("/Type /Font\n") pdf.append("/Subtype /Type0\n") pdf.append("/BaseFont /") pdf.append(otf.fontName!) pdf.append("\n") pdf.append("/Encoding /Identity-H\n") pdf.append("/DescendantFonts [") pdf.append(font.cidFontDictObjNumber) pdf.append(" 0 R]\n") pdf.append("/ToUnicode ") pdf.append(font.toUnicodeCMapObjNumber) pdf.append(" 0 R\n") pdf.append(">>\n") pdf.endobj() font.objNumber = pdf.getObjNumber() pdf.fonts.append(font) } private static func embedFontFile(_ pdf: PDF, _ font: Font, _ otf: OTF) { // Check if the font file is already embedded for f in pdf.fonts { if f.fileObjNumber != 0 && f.name == otf.fontName { font.fileObjNumber = f.fileObjNumber return } } let metadataObjNumber = pdf.addMetadataObject(otf.fontInfo!, true) if metadataObjNumber != -1 { pdf.append("/Metadata ") pdf.append(metadataObjNumber) pdf.append(" 0 R\n") } pdf.newobj() pdf.append("<<\n") if otf.cff { pdf.append("/Subtype /CIDFontType0C\n") } pdf.append("/Filter /FlateDecode\n") // pdf.append("/Filter /LZWDecode\n") pdf.append("/Length ") pdf.append(otf.dos.count) // The compressed size pdf.append("\n") if !otf.cff { pdf.append("/Length1 ") pdf.append(otf.buf.count) // The uncompressed size pdf.append("\n") } pdf.append(">>\n") pdf.append("stream\n") pdf.append(otf.dos) pdf.append("\nendstream\n") pdf.endobj() font.fileObjNumber = pdf.getObjNumber() } private static func addFontDescriptorObject( _ pdf: PDF, _ font: Font, _ otf: OTF) { for f in pdf.fonts { if f.fontDescriptorObjNumber != 0 && f.name == otf.fontName { font.fontDescriptorObjNumber = f.fontDescriptorObjNumber return } } let factor = Float(1000.0) / Float(otf.unitsPerEm!) pdf.newobj() pdf.append("<<\n") pdf.append("/Type /FontDescriptor\n") pdf.append("/FontName /") pdf.append(otf.fontName!) pdf.append("\n") if otf.cff { pdf.append("/FontFile3 ") } else { pdf.append("/FontFile2 ") } pdf.append(font.fileObjNumber) pdf.append(" 0 R\n") pdf.append("/Flags 32\n") pdf.append("/FontBBox [") pdf.append(Int32(Float(otf.bBoxLLx!) * factor)) pdf.append(" ") pdf.append(Int32(Float(otf.bBoxLLy!) * factor)) pdf.append(" ") pdf.append(Int32(Float(otf.bBoxURx!) * factor)) pdf.append(" ") pdf.append(Int32(Float(otf.bBoxURy!) * factor)) pdf.append("]\n") pdf.append("/Ascent ") pdf.append(Int32(Float(otf.ascent!) * factor)) pdf.append("\n") pdf.append("/Descent ") pdf.append(Int32(Float(otf.descent!) * factor)) pdf.append("\n") pdf.append("/ItalicAngle 0\n") pdf.append("/CapHeight ") pdf.append(Int32(Float(otf.capHeight!) * factor)) pdf.append("\n") pdf.append("/StemV 79\n") pdf.append(">>\n") pdf.endobj() font.fontDescriptorObjNumber = pdf.getObjNumber() } private static func addToUnicodeCMapObject( _ pdf: PDF, _ font: Font, _ otf: OTF) { for f in pdf.fonts { if f.toUnicodeCMapObjNumber != 0 && f.name == otf.fontName { font.toUnicodeCMapObjNumber = f.toUnicodeCMapObjNumber return } } var sb = String() sb.append("/CIDInit /ProcSet findresource begin\n") sb.append("12 dict begin\n") sb.append("begincmap\n") sb.append("/CIDSystemInfo <</Registry (Adobe) /Ordering (Identity) /Supplement 0>> def\n") sb.append("/CMapName /Adobe-Identity def\n") sb.append("/CMapType 2 def\n") sb.append("1 begincodespacerange\n") sb.append("<0000> <FFFF>\n") sb.append("endcodespacerange\n") var list = [String]() var buf = String() for cid in 0...0xffff { let gid = otf.unicodeToGID[cid] if gid > 0 { buf.append("<") buf.append(toHexString(gid)) buf.append("> <") buf.append(toHexString(cid)) buf.append(">\n") list.append(buf) buf = "" if list.count == 100 { writeListToBuffer(&list, &sb) } } } if list.count > 0 { writeListToBuffer(&list, &sb) } sb.append("endcmap\n") sb.append("CMapName currentdict /CMap defineresource pop\n") sb.append("end\nend") pdf.newobj() pdf.append("<<\n") pdf.append("/Length ") pdf.append(sb.count) pdf.append("\n") pdf.append(">>\n") pdf.append("stream\n") pdf.append(sb) pdf.append("\nendstream\n") pdf.endobj() font.toUnicodeCMapObjNumber = pdf.getObjNumber() } private static func addCIDFontDictionaryObject( _ pdf: PDF, _ font: Font, _ otf: OTF) { for f in pdf.fonts { if f.cidFontDictObjNumber != 0 && f.name == otf.fontName { font.cidFontDictObjNumber = f.cidFontDictObjNumber return } } pdf.newobj() pdf.append("<<\n") pdf.append("/Type /Font\n") if otf.cff { pdf.append("/Subtype /CIDFontType0\n") } else { pdf.append("/Subtype /CIDFontType2\n") } pdf.append("/BaseFont /") pdf.append(otf.fontName!) pdf.append("\n") pdf.append("/CIDSystemInfo <</Registry (Adobe) /Ordering (Identity) /Supplement 0>>\n") pdf.append("/FontDescriptor ") pdf.append(font.fontDescriptorObjNumber) pdf.append(" 0 R\n") var k: Float = 1.0 if font.unitsPerEm != 1000 { k = Float(1000.0) / Float(font.unitsPerEm) } pdf.append("/DW ") pdf.append(Int32(round(k * Float(font.advanceWidth![0])))) pdf.append("\n") pdf.append("/W [0[\n") for i in 0..<font.advanceWidth!.count { pdf.append(Int32(round(k * Float(font.advanceWidth![i])))) pdf.append(" ") } pdf.append("]]\n") pdf.append("/CIDToGIDMap /Identity\n") pdf.append(">>\n") pdf.endobj() font.cidFontDictObjNumber = pdf.getObjNumber() } private static func toHexString(_ code: Int) -> String { let str = String(code, radix: 16) if str.unicodeScalars.count == 1 { return "000" + str } else if str.unicodeScalars.count == 2 { return "00" + str } else if str.unicodeScalars.count == 3 { return "0" + str } return str } private static func writeListToBuffer( _ list: inout [String], _ sb: inout String) { sb.append(String(list.count)) sb.append(" beginbfchar\n") for str in list { sb.append(str) } sb.append("endbfchar\n") list.removeAll() } } // End of OpenTypeFont.swift
fbb1e00fabccb025dd905b3fa55572ae
28.553333
98
0.52425
false
false
false
false
biohazardlover/NintendoEverything
refs/heads/master
NintendoEverything/Posts/PostsViewController.swift
mit
1
import UIKit import DZNEmptyDataSet import RxSwift import RxCocoa import NSObject_Rx import SwiftyJSON import XLPagerTabStrip class PostsViewController: UIViewController { let postCategory: PostCateogry private var items: [Item] = [] @IBOutlet var tableView: UITableView! @IBOutlet var activityIndicatorView: UIActivityIndicatorView! fileprivate lazy var paginationViewModel = PaginationViewModel(service: LatestNewsService(category: postCategory)) init(postCategory: PostCateogry) { self.postCategory = postCategory super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.register(R.nib.postCell(), forCellReuseIdentifier: R.nib.postCell.name) tableView.register(R.nib.nextCell(), forCellReuseIdentifier: R.nib.nextCell.name) addRefreshControl() tableView.rx.setDelegate(self).disposed(by: rx.disposeBag) paginationViewModel.items .map { posts -> Element in var items = posts.map { Item.post($0) } if items.count > 0 { items.append(.next) } return items } .drive(tableView.rx.items(dataSource: self)) .disposed(by: rx.disposeBag) paginationViewModel.load.onNext(.first) paginationViewModel.loadingStatus .map { $0.loadingType == .first ? $0.isLoading : false } .drive(activityIndicatorView.rx.isAnimating) .disposed(by: rx.disposeBag) } private func addRefreshControl() { let refreshControl = UIRefreshControl() refreshControl.rx.controlEvent(.valueChanged) .map { PaginationViewModel.LoadingType.refresh } .bind(to: paginationViewModel.load) .disposed(by: rx.disposeBag) paginationViewModel.loadingStatus .filter { $0.loadingType == .refresh && $0.isLoading == false } .map { $0.isLoading } .drive(refreshControl.rx.isRefreshing) .disposed(by: rx.disposeBag) tableView.refreshControl = refreshControl } } extension PostsViewController: RxTableViewDataSourceType { enum Item { case post(Post) case next } typealias Element = [Item] func tableView(_ tableView: UITableView, observedEvent: Event<Element>) { items = observedEvent.element ?? [] tableView.reloadData() } } extension PostsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch items[indexPath.row] { case .post(let post): let cell = tableView.dequeueReusableCell(withIdentifier: R.nib.postCell.name, for: indexPath) as! PostCell cell.post = post return cell case .next: let cell = tableView.dequeueReusableCell(withIdentifier: R.nib.nextCell.name, for: indexPath) as! NextCell return cell } } } extension PostsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if case .next = items[indexPath.row] { paginationViewModel.load.onNext(.next) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if case .post(let post) = items[indexPath.row] { let postDetailsViewController = PostDetailsViewController(post: post) navigationController?.pushViewController(postDetailsViewController, animated: true) } } } extension PostsViewController: DZNEmptyDataSetSource { func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { return NSAttributedString(string: "No Posts") } } extension PostsViewController: IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: postCategory.description) } }
71dbb554a8b441240f4085d64640a200
32.321168
118
0.645564
false
false
false
false
josherick/DailySpend
refs/heads/master
DailySpend/SpendIndicationNavigationController.swift
mit
1
// // SpendIndicationNavigationController.swift // DailySpend // // Created by Josh Sherick on 5/6/18. // Copyright © 2018 Josh Sherick. All rights reserved. // import UIKit class SpendIndicationNavigationController: UINavigationController { let appDelegate = (UIApplication.shared.delegate as! AppDelegate) override func viewDidLoad() { super.viewDidLoad() view.tintColor = .tint navigationBar.tintColor = .tint navigationBar.isTranslucent = false navigationBar.barTintColor = appDelegate.spendIndicationColor NotificationCenter.default.addObserver( self, selector: #selector(updateBarTintColor), name: NSNotification.Name.init("ChangedSpendIndicationColor"), object: nil ) } deinit { NotificationCenter.default.removeObserver(self) } @objc func updateBarTintColor() { let newColor = self.appDelegate.spendIndicationColor if navigationBar.barTintColor != newColor { UIView.animate(withDuration: 0.2) { self.navigationBar.barTintColor = newColor self.navigationBar.layoutIfNeeded() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
1dd2df962f9f0a670f7a5e7077d93446
28.881356
106
0.653999
false
false
false
false
dhf/SwiftForms
refs/heads/master
SwiftForms/controllers/FormViewController.swift
mit
1
// // FormViewController.swift // SwiftForms // // Created by Miguel Angel Ortuño on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public class FormViewController : UITableViewController { /// MARK: Types private struct Static { static var onceDefaultCellClass: dispatch_once_t = 0 static var defaultCellClasses: [FormRowType : FormBaseCell.Type] = [:] } /// MARK: Properties public var form = FormDescriptor() /// MARK: Init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// MARK: View life cycle public override func viewDidLoad() { super.viewDidLoad() navigationItem.title = form.title } /// MARK: Public interface public func valueForTag(tag: String) -> AnyObject? { for section in form.sections { for row in section.rows { if row.tag == tag { return row.value } } } return nil } public func setValue(value: NSObject, forTag tag: String) { for (sectionIndex, section) in form.sections.enumerate() { if let rowIndex = (section.rows.map { $0.tag }).indexOf(tag), let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: rowIndex, inSection: sectionIndex)) as? FormBaseCell { section.rows[rowIndex].value = value cell.update() } } } public func indexPathOfTag(tag: String) -> NSIndexPath? { for (sectionIndex, section) in form.sections.enumerate() { if let rowIndex = (section.rows.map { $0.tag }).indexOf(tag) { return NSIndexPath(forRow: rowIndex, inSection: sectionIndex) } } return .None } /// MARK: UITableViewDataSource public override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return form.sections.count } public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return form.sections[section].rows.count } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) let reuseIdentifier = NSStringFromClass(formBaseCellClass) var cell: FormBaseCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? FormBaseCell if cell == nil { cell = formBaseCellClass.init(style: .Default, reuseIdentifier: reuseIdentifier) cell?.formViewController = self cell?.configure() } cell?.rowDescriptor = rowDescriptor // apply cell custom design if let cellConfiguration = rowDescriptor.configuration.cellConfiguration { for (keyPath, value) in cellConfiguration { cell?.setValue(value, forKeyPath: keyPath) } } return cell! } public override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return form.sections[section].headerTitle } public override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return form.sections[section].footerTitle } /// MARK: UITableViewDelegate public override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) return formBaseCellClassFromRowDescriptor(rowDescriptor).formRowCellHeight() } public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) if let selectedRow = tableView.cellForRowAtIndexPath(indexPath) as? FormBaseCell { let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) formBaseCellClass.formViewController(self, didSelectRow: selectedRow) } if let didSelectClosure = rowDescriptor.configuration.didSelectClosure { didSelectClosure() } tableView.deselectRowAtIndexPath(indexPath, animated: true) } private class func defaultCellClassForRowType(rowType: FormRowType) -> FormBaseCell.Type { dispatch_once(&Static.onceDefaultCellClass) { Static.defaultCellClasses[FormRowType.Text] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Number] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.NumbersAndPunctuation] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Decimal] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Name] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Phone] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.URL] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Twitter] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.NamePhone] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Email] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.ASCIICapable] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Password] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Button] = FormButtonCell.self Static.defaultCellClasses[FormRowType.BooleanSwitch] = FormSwitchCell.self Static.defaultCellClasses[FormRowType.BooleanCheck] = FormCheckCell.self Static.defaultCellClasses[FormRowType.SegmentedControl] = FormSegmentedControlCell.self Static.defaultCellClasses[FormRowType.Picker] = FormPickerCell.self Static.defaultCellClasses[FormRowType.Date] = FormDateCell.self Static.defaultCellClasses[FormRowType.Time] = FormDateCell.self Static.defaultCellClasses[FormRowType.DateAndTime] = FormDateCell.self Static.defaultCellClasses[FormRowType.Stepper] = FormStepperCell.self Static.defaultCellClasses[FormRowType.Slider] = FormSliderCell.self Static.defaultCellClasses[FormRowType.MultipleSelector] = FormSelectorCell.self Static.defaultCellClasses[FormRowType.MultilineText] = FormTextViewCell.self } return Static.defaultCellClasses[rowType]! } public func formRowDescriptorAtIndexPath(indexPath: NSIndexPath) -> FormRowDescriptor { let section = form.sections[indexPath.section] let rowDescriptor = section.rows[indexPath.row] return rowDescriptor } private func formBaseCellClassFromRowDescriptor(rowDescriptor: FormRowDescriptor) -> FormBaseCell.Type { let formBaseCellClass: FormBaseCell.Type if let cellClass = rowDescriptor.configuration.cellClass { formBaseCellClass = cellClass } else { formBaseCellClass = FormViewController.defaultCellClassForRowType(rowDescriptor.rowType) } return formBaseCellClass } }
436c5368571d0bdee455c563701e99eb
40.620879
137
0.67538
false
false
false
false
ibrdrahim/TopBarMenu
refs/heads/master
TopBarMenu/MenuCell.swift
mit
1
// // MenuCell.swift // TopBarMenu // // Created by ibrahim on 11/3/16. // Copyright © 2016 Indosytem. All rights reserved. // import UIKit class MenuCell: BaseCell { let menu: UILabel = { let lbl = UILabel() lbl.textColor = UIColor.white.withAlphaComponent(0.4) lbl.textAlignment = NSTextAlignment.center lbl.font = lbl.font.withSize(14.0) return lbl }() override var isHighlighted: Bool { didSet { menu.textColor = isHighlighted ? UIColor.white : UIColor.white.withAlphaComponent(0.4) } } override var isSelected: Bool { didSet { menu.textColor = isHighlighted ? UIColor.white : UIColor.white.withAlphaComponent(0.4) } } override func setupViews() { super.setupViews() addSubview(menu) addConstraintsWithFormat(format:"H:[v0(110)]", views: menu) addConstraintsWithFormat(format:"V:[v0(28)]", views: menu) addConstraint(NSLayoutConstraint(item: menu, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: menu, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) } }
2217e338624c94e139df7060632e5bb9
29.5
156
0.621461
false
false
false
false
exercism/xswift
refs/heads/master
exercises/bracket-push/Sources/BracketPush/BracketPushExample.swift
mit
2
struct BracketPush { private static let brackets: [Character: Character] = [ ")": "(", "]": "[", "}": "{" ] static func paired(text: String) -> Bool { var stack = [Character]() for character in text { if brackets.values.contains(character) { stack.append(character) } else if brackets.keys.contains(character) { guard let last = stack.popLast(), last == brackets[character] else { return false } } } return stack.isEmpty } }
82088d5936238f9b4c85ee2d6e728c55
24.16
59
0.461049
false
false
false
false
AccessLite/BYT-Golden
refs/heads/master
BYT/Extension + LanguageFilterManager.swift
mit
1
// // LanguageFilterManager.swift // BYT // // Created by C4Q on 2/1/17. // Copyright © 2017 AccessLite. All rights reserved. // import Foundation //TODO List: //About View Controller //Fixing the bug on constraint breaking after transition to view //madison enter on both fields bug typealias LanguageFilterClosure = (String) -> String class LanguageFilter { private static let languageFilterKey = "filterDefaultPreference" private static let wordsToBeFiltered: Set<String> = ["fuck", "bitch", "ass", "dick", "pussy", "shit", "twat", "cock"] private static let wordsToBeUnfiltered: [String: String] = ["f*ck" : "u", "b*tch" : "i", "*ss" : "a", "d*ck": "i", "p*ssy": "u", "sh*t": "i", "tw*t" : "a", "c*ck" : "o"] private static let vowels: Set<Character> = ["a", "e", "i", "o", "u"] // MARK: - Checking/Saving State static var profanityAllowed: Bool { get { return UserDefaults.standard.bool(forKey: languageFilterKey) } set { UserDefaults.standard.set(newValue, forKey: languageFilterKey) } } // MARK: - Sanitize/Filter Text static func sanitize(text: String, using filter: LanguageFilterClosure) -> String { var words = text.components(separatedBy: " ") for (index, word) in words.enumerated() { let filtered = word.replacingOccurrences(of: word, with: filter(word), options: .caseInsensitive, range: nil) words[index] = filtered } return words.joined(separator: " ") } // MARK: - LanguageFilterClosure Options static let clean: LanguageFilterClosure = { word in for foulWord in wordsToBeFiltered where word.lowercased().contains(foulWord){ for char in word.lowercased().characters where vowels.contains(char) { return word.replacingOccurrences(of: String(char), with: "*", options: .caseInsensitive, range: nil) } } return word } static let dirty: LanguageFilterClosure = { word in for filteredWord in wordsToBeUnfiltered.keys where word.lowercased().contains(filteredWord) { return word.replacingOccurrences(of: "*", with: wordsToBeUnfiltered[filteredWord]!, options: .caseInsensitive, range: nil) } return word } } extension String { func filterBadLanguage() -> String { let filter: LanguageFilterClosure = LanguageFilter.profanityAllowed ? LanguageFilter.clean : LanguageFilter.dirty return LanguageFilter.sanitize(text: self, using: filter) } }
41ad38b5b6f76decb6fd67983381e1b2
37.164179
173
0.648807
false
false
false
false
SimonWaldherr/ColorConverter.swift
refs/heads/master
ColorConverter.playground/section-1.swift
mit
1
func RGB2HSL(r: Int, g: Int, b: Int) -> (h: Int, s: Int, l: Int) { var rf = max(min(Float64(r)/255, 1), 0) var gf = max(min(Float64(g)/255, 1), 0) var bf = max(min(Float64(b)/255, 1), 0) var maxv = max(rf, gf, bf) var minv = min(rf, gf, bf) var l = (maxv + minv) / 2 var h = 0.0, s = 0.0, d = 0.0 if maxv != minv { d = maxv - minv if l > 0.5 { s = d / (2 - maxv - minv) } else { s = d / (maxv + minv) } if maxv == rf { if gf < bf { h = (gf - bf) / d + 6 } else { h = (gf - bf) / d } } else if maxv == gf { h = (bf - rf) / d + 2 } else { h = (rf - gf) / d + 4 } } else { h = 0 s = 0 } var hi = Int(h * 60) var si = Int(s * 100) var li = Int(l * 100) return (hi, si, li) } func CMYK2RGB(c: Int, m: Int, y: Int, k: Int) -> (r: Int, g: Int, b: Int) { var cf = max(min(Float64(c)/255, 1), 0) var mf = max(min(Float64(m)/255, 1), 0) var yf = max(min(Float64(y)/255, 1), 0) var kf = max(min(Float64(k)/255, 1), 0) var rf = (1 - cf * (1 - kf) - kf) var gf = (1 - mf * (1 - kf) - kf) var bf = (1 - yf * (1 - kf) - kf) return (Int(rf * 255), Int(gf * 255), Int(bf * 255)) } CMYK2RGB(24, 0, 79, 71) RGB2HSL(99, 140, 69)
1ee858a7b3eba745697d6422d3e15f22
27
75
0.402143
false
false
false
false
Ivacker/swift
refs/heads/master
stdlib/public/core/Misc.swift
apache-2.0
6
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Extern C functions //===----------------------------------------------------------------------===// // FIXME: Once we have an FFI interface, make these have proper function bodies @_transparent @warn_unused_result public // @testable func _countLeadingZeros(value: Int64) -> Int64 { return Int64(Builtin.int_ctlz_Int64(value._value, false._value)) } /// Returns if `x` is a power of 2. @_transparent @warn_unused_result public // @testable func _isPowerOf2(x: UInt) -> Bool { if x == 0 { return false } // Note: use unchecked subtraction because we have checked that `x` is not // zero. return x & (x &- 1) == 0 } /// Returns if `x` is a power of 2. @_transparent @warn_unused_result public // @testable func _isPowerOf2(x: Int) -> Bool { if x <= 0 { return false } // Note: use unchecked subtraction because we have checked that `x` is not // `Int.min`. return x & (x &- 1) == 0 } #if _runtime(_ObjC) @_transparent public func _autorelease(x: AnyObject) { Builtin.retain(x) Builtin.autorelease(x) } #endif /// Invoke `body` with an allocated, but uninitialized memory suitable for a /// `String` value. /// /// This function is primarily useful to call various runtime functions /// written in C++. func _withUninitializedString<R>( body: (UnsafeMutablePointer<String>) -> R ) -> (R, String) { let stringPtr = UnsafeMutablePointer<String>.alloc(1) let bodyResult = body(stringPtr) let stringResult = stringPtr.move() stringPtr.dealloc(1) return (bodyResult, stringResult) } @_silgen_name("swift_getTypeName") public func _getTypeName(type: Any.Type, qualified: Bool) -> (UnsafePointer<UInt8>, Int) /// Returns the demangled qualified name of a metatype. @warn_unused_result public // @testable func _typeName(type: Any.Type, qualified: Bool = true) -> String { let (stringPtr, count) = _getTypeName(type, qualified: qualified) return ._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: stringPtr, count: count)) } /// Returns `floor(log(x))`. This equals to the position of the most /// significant non-zero bit, or 63 - number-of-zeros before it. /// /// The function is only defined for positive values of `x`. /// /// Examples: /// /// floorLog2(1) == 0 /// floorLog2(2) == floorLog2(3) == 1 /// floorLog2(9) == floorLog2(15) == 3 /// /// TODO: Implement version working on Int instead of Int64. @warn_unused_result @_transparent public // @testable func _floorLog2(x: Int64) -> Int { _sanityCheck(x > 0, "_floorLog2 operates only on non-negative integers") // Note: use unchecked subtraction because we this expression can not // overflow. return 63 &- Int(_countLeadingZeros(x)) }
d63db499c26b9d8a7e24648ffb851d8a
29.140187
80
0.63938
false
false
false
false