repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Sales/Model/SAMSaleOrderDetailListModel.swift
1
1292
// // SAMSaleOrderDetailListModel.swift // SaleManager // // Created by apple on 16/12/9. // Copyright © 2016年 YZH. All rights reserved. // import UIKit class SAMSaleOrderDetailListModel: NSObject { ///明细项id var id: String? ///产品编号id var productID: String? ///产品编号名称 var productIDName: String? ///数量(米数) var countM: Double = 0.0 ///单价 var price: Double = 0.0 ///小计金额 var smallMoney: Double = 0.0 ///备注 var memoInfo: String? ///匹数 var countP: Double = 0.0 ///每匹米数列表 var meterList: String? { didSet{ let listStr = meterList?.lxm_stringByTrimmingWhitespace() if listStr != "" { //字符串有内容 if listStr!.contains(",") { //逗号分隔 meterArr = (listStr?.components(separatedBy: ","))! }else if listStr!.contains("|") { // |分隔 meterArr = (listStr?.components(separatedBy: "|"))! }else { //只有一个数字 meterArr = [listStr!] } } } } //MARK: - 辅助属性 var meterArr = [String]() }
apache-2.0
87059bc82a7c7d75197ff9d183dda3f4
22.54
71
0.491079
3.772436
false
false
false
false
tavultesoft/keymanweb
ios/engine/KMEI/KeymanEngineTests/KeyboardScaleTests.swift
1
3607
// // KeyboardScaleTests.swift // KeymanEngineTests // // Created by Joshua Horton on 2/20/20. // Copyright © 2020 SIL International. All rights reserved. // import XCTest @testable import KeymanEngine import DeviceKit extension KeyboardSize: Equatable { public static func == (lhs: KeyboardSize, rhs: KeyboardSize) -> Bool { if lhs.bannerHeight != rhs.bannerHeight { return false } if lhs.width != rhs.width { return false } if lhs.keyboardHeight != rhs.keyboardHeight { return false } return true } } class KeyboardScaleTests: XCTestCase { // Known to be in the scaling map directly. func testScaleForSE() { let portraitScale = KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: true, onDevice: Device.iPhoneSE)! let landscapeScale = KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: false, onDevice: Device.iPhoneSE)! // scalings[KeyboardScaleMap.hashKey(for: Device.iPhoneSE)] // = Scaling(portrait: KeyboardSize(w: 320, h: 216, b: 38), // landscape: KeyboardSize(w: 568, h: 162, b: 38)) XCTAssertEqual(portraitScale.bannerHeight, 38) XCTAssertEqual(portraitScale.width, 320) XCTAssertEqual(portraitScale.keyboardHeight, 216) XCTAssertEqual(landscapeScale.bannerHeight, 38) XCTAssertEqual(landscapeScale.width, 568) XCTAssertEqual(landscapeScale.keyboardHeight, 162) } func testScaleForUnknown() { let device = Device.unknown("granny smith") log.info(device.isPad) let size1 = CGSize(width: 375, height: 667) // iPhone 8 device height let mappedScale1 = KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: true, onDevice: device, screenSize: size1, asPhone: true) let correctScale1 = KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: true, onDevice: Device.iPhone8) XCTAssertEqual(mappedScale1, correctScale1, "Unknown phone with same resolution as iPhone 8 not given same keyboard dimensions") let size2 = CGSize(width: 834, height: 1112) // iPad Air 3 let mappedScale2 = KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: false, onDevice: device, screenSize: size2, asPhone: false) let correctScale2 = KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: false, onDevice: Device.iPadAir3) XCTAssertEqual(mappedScale2, correctScale2, "Unknown tablet with same resolution as iPadAir 3 not given same keyboard dimensions") let size3 = CGSize(width: 1800, height: 2000) // larger than any existing device let mappedScale3 = KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: true, onDevice: device, screenSize: size3, asPhone: false) let correctScale3 = KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: true, onDevice: Device.iPadPro12Inch3) // largest iPad XCTAssertEqual(mappedScale3, correctScale3, "Unknown super-large tablet not given largest keyboard dimension mapping") } }
apache-2.0
319e7d45b29f2ef8b78a878a6ff9fd93
39.977273
138
0.615641
5.064607
false
true
false
false
pinterest/tulsi
src/TulsiGenerator/TulsiProjectInfoExtractor.swift
1
4709
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation // Provides functionality to generate a TulsiGeneratorConfig from a TulsiProject. public final class TulsiProjectInfoExtractor { public enum ExtractorError: Error { case ruleEntriesFailed(String) } private let project: TulsiProject private let localizedMessageLogger: LocalizedMessageLogger var workspaceInfoExtractor: BazelWorkspaceInfoExtractorProtocol public var bazelURL: URL { get { return workspaceInfoExtractor.bazelURL as URL } set { workspaceInfoExtractor.bazelURL = newValue } } public var bazelExecutionRoot: String { return workspaceInfoExtractor.bazelExecutionRoot } public var workspaceRootURL: URL { return workspaceInfoExtractor.workspaceRootURL } public init(bazelURL: URL, project: TulsiProject) { self.project = project let bundle = Bundle(for: type(of: self)) localizedMessageLogger = LocalizedMessageLogger(bundle: bundle) workspaceInfoExtractor = BazelWorkspaceInfoExtractor(bazelURL: bazelURL, workspaceRootURL: project.workspaceRootURL, localizedMessageLogger: localizedMessageLogger) } public func extractTargetRules() -> [RuleInfo] { return workspaceInfoExtractor.extractRuleInfoFromProject(project) } public func ruleEntriesForInfos(_ infos: [RuleInfo], startupOptions: TulsiOption, extraStartupOptions: TulsiOption, buildOptions: TulsiOption, compilationModeOption: TulsiOption, platformConfigOption: TulsiOption, prioritizeSwiftOption: TulsiOption, features: Set<BazelSettingFeature>) throws -> RuleEntryMap { return try ruleEntriesForLabels(infos.map({ $0.label }), startupOptions: startupOptions, extraStartupOptions: extraStartupOptions, buildOptions: buildOptions, compilationModeOption: compilationModeOption, platformConfigOption: platformConfigOption, prioritizeSwiftOption: prioritizeSwiftOption, features: features) } public func ruleEntriesForLabels(_ labels: [BuildLabel], startupOptions: TulsiOption, extraStartupOptions: TulsiOption, buildOptions: TulsiOption, compilationModeOption: TulsiOption, platformConfigOption: TulsiOption, prioritizeSwiftOption: TulsiOption, features: Set<BazelSettingFeature>) throws -> RuleEntryMap { do { return try workspaceInfoExtractor.ruleEntriesForLabels(labels, startupOptions: startupOptions, extraStartupOptions: extraStartupOptions, buildOptions: buildOptions, compilationModeOption: compilationModeOption, platformConfigOption: platformConfigOption, prioritizeSwiftOption: prioritizeSwiftOption, features: features) } catch BazelWorkspaceInfoExtractorError.aspectExtractorFailed(let info) { throw ExtractorError.ruleEntriesFailed(info) } } public func extractBuildfiles(_ targets: [BuildLabel]) -> Set<BuildLabel> { return workspaceInfoExtractor.extractBuildfiles(targets) } }
apache-2.0
3526756d92a4c3c28ca9f85b2f03676b
47.05102
106
0.580803
6.44186
false
true
false
false
devandsev/theTVDB-iOS
tvShows/Source/Services/API/APIResources/SeriesAPI.swift
1
1481
// // SeriesAPI.swift // tvShows // // Created by Andrey Sevrikov on 22/07/2017. // Copyright © 2017 devandsev. All rights reserved. // import Foundation import ObjectMapper class SeriesAPI: HasDependencies { typealias Dependencies = HasApiService var di: Dependencies! let endpoint = "/series" func series(id: Int, success: @escaping (Series) -> Void, failure: @escaping (APIError) -> Void) { let request = APIRequest(url: endpoint + "/\(id)", method: .get, parameters: [:]) self.di.apiService.send(request: request, schema: DataKeyPathSchema<Series>.self) { schema, error in guard let series = schema?.data else { failure(error ?? .unknownError) return } success(series) } } func actors(seriesId: Int, success: @escaping ([Actor]) -> Void, failure: @escaping (APIError) -> Void) { let request = APIRequest(url: endpoint + "/\(seriesId)" + "/actors", method: .get, parameters: [:]) self.di.apiService.send(request: request, schema: DataArrayKeypathSchema<Actor>.self) { schema, error in guard let actors = schema?.data else { failure(error ?? .unknownError) return } success(actors) } } }
mit
7acd6d1b59f4c0a1d8a8121d76c0d755
27.461538
112
0.530405
4.66877
false
false
false
false
cuzv/ExtensionKit
Sources/Extension/CoreGraphics+Extension.swift
1
18342
// // CoreGraphics+Extension.swift // Copyright (c) 2015-2016 Red Rain (http://mochxiao.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 Foundation import CoreGraphics import UIKit // MARK: - public extension Double { public var radian: CGFloat { return CGFloat(self / 180.0 * Double.pi) } public var angle: CGFloat { return CGFloat(self / Double.pi * 180.0) } public var pointToPixel: CGFloat { return CGFloat(self) * UIScreen.main.scale } public var pixelToPoint: CGFloat { return CGFloat(self) / UIScreen.main.scale } } public extension CGFloat { public var radian: CGFloat { return CGFloat(Double(native / 180.0) * Double.pi) } public var angle: CGFloat { return CGFloat(Double(native) / Double.pi * 180.0) } public var pointToPixel: CGFloat { return self * UIScreen.main.scale } public var pixelToPoint: CGFloat { return self / UIScreen.main.scale } } public extension CGFloat { public var ceilling: CGFloat { return ceil(self) } public var flooring: CGFloat { return floor(self) } } public extension CGPoint { public var ceilling: CGPoint { return CGPoint(x: ceil(x), y: ceil(y)) } public var flooring: CGPoint { return CGPoint(x: floor(x), y: floor(y)) } public func makeVector(to other: CGPoint) -> CGVector { return CGVector(dx: other.x - x, dy: y - other.y) } } public let CGPointZert = CGPoint.zero public func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint { return CGPoint(x: x, y: y) } public func CGPointMake(_ x: Double, _ y: Double) -> CGPoint { return CGPoint(x: x, y: y) } public func CGPointMake(_ x: Int, _ y: Int) -> CGPoint { return CGPoint(x: x, y: y) } // MARK: - public extension CGSize { public var ceilling: CGSize { return CGSize(width: ceil(width), height: ceil(height)) } public var flooring: CGSize { return CGSize(width: floor(width), height: floor(height)) } /// Multiply the size components by the factor public func scale(factor: CGFloat) -> CGSize { return CGSize(width: width * factor, height: height * factor) } /// Calculate scale for fitting a size to a destination size public func scale(aspectToFit size: CGSize) -> CGSize { return scale(factor: min(size.width / width, size.height / height)) } // Calculate scale for filling a destination size public func scale(aspectToFill size: CGSize) -> CGSize { return scale(factor: max(size.width / width, size.height / height)) } } public let CGSizeZert = CGSize.zero public func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize { return CGSize(width: width, height: height) } public func CGSizeMake(_ width: Double, _ height: Double) -> CGSize { return CGSize(width: width, height: height) } public func CGSizeMake(_ width: Int, _ height: Int) -> CGSize { return CGSize(width: width, height: height) } public func CGSizeEqualToSize(_ lhs: CGSize, _ rhs: CGSize) -> Bool { return lhs.equalTo(rhs) } // MARK: - public extension CGVector { public var ceilling: CGVector { return CGVector(dx: ceil(dx), dy: ceil(dy)) } public var flooring: CGVector { return CGVector(dx: floor(dx), dy: floor(dy)) } } public func CGVectorMake(_ dx: CGFloat, dy: CGFloat) -> CGVector { return CGVector(dx: dx, dy: dy) } public func CGVectorMake(_ dx: Double, dy: Double) -> CGVector { return CGVector(dx: dx, dy: dy) } public func CGVectorMake(_ dx: Int, dy: Int) -> CGVector { return CGVector(dx: dx, dy: dy) } // MARK: - public extension CGRect { public var ceilling: CGRect { return CGRectMake(size: size.ceilling) } public var flooring: CGRect { return CGRectMake(size: size.flooring) } /// Return a rect centered a source to a destination public func centering(in destination: CGRect) -> CGRect { let dx: CGFloat = destination.midX - midX let dy: CGFloat = destination.midY - midY return offsetBy(dx: dx, dy: dy) } /// Return a rect fitting a source to a destination public func fitting(in destination: CGRect) -> CGRect { let targetSize = size.scale(aspectToFit: destination.size) return CGRectMake(center: destination.center, size: targetSize) } /// Return a rect that fills the destination public func filling(in destination: CGRect) -> CGRect { let targetSize = size.scale(aspectToFill: destination.size) return CGRectMake(center: destination.center, size: targetSize) } public var left: CGFloat { set { var newOrigin = origin newOrigin.x = newValue origin = newOrigin } get { return origin.x } } public var centerX: CGFloat { set { let diff = newValue - midX var newOrigin = origin newOrigin.x += diff origin = newOrigin } get { return origin.x + size.width / 2.0 } } public var right: CGFloat { set { let diff = newValue - maxX var newOrigin = origin newOrigin.x += diff origin = newOrigin } get { return origin.x + size.width } } public var top: CGFloat { set { var newOrigin = origin newOrigin.y = newValue origin = newOrigin } get { return origin.y } } public var centerY: CGFloat { set { let diff = newValue - midY var newOrigin = origin newOrigin.y += diff origin = newOrigin } get { return origin.y + size.height / 2.0 } } public var bottom: CGFloat { set { let diff = newValue - maxY var newOrigin = origin newOrigin.y += diff origin = newOrigin } get { return origin.y + size.height } } public var center: CGPoint { set { var frame = self frame.origin.x = newValue.x - frame.size.width * 0.5 frame.origin.y = newValue.y - frame.size.height * 0.5 self = frame } get { return CGPoint(x: origin.x + size.width * 0.5, y: origin.y + size.height * 0.5) } } public var lengthX: CGFloat { set { var newSize = size newSize.width = newValue size = newSize } get { return size.width } } public var lengthY: CGFloat { set { var newSize = size newSize.height = newValue size = newSize } get { return size.height } } } public let CGRectZero = CGRect.zero public let CGRectNull = CGRect.null public let CGRectInfinite = CGRect.infinite /// Return center for rect public func CGRectGetCenter(_ rect: CGRect) -> CGPoint { return rect.center } public func CGRectMake(origin: CGPoint = CGPoint.zero, size: CGSize) -> CGRect { return CGRect(x: origin.x, y: origin.y, width: size.width, height: size.height) } public func CGRectMake(center: CGPoint, size: CGSize) -> CGRect { let halfWidth = size.width / 2.0 let halfHeight = size.height / 2.0 return CGRect( x: center.x - halfWidth, y: center.y - halfHeight, width: size.width, height: size.height ) } public func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect { return CGRect(x: x, y: y, width: width, height: height) } public func CGRectMake(_ x: Double, _ y: Double, _ width: Double, _ height: Double) -> CGRect { return CGRect(x: x, y: y, width: width, height: height) } public func CGRectMake(_ x: Int, _ y: Int, _ width: Int, _ height: Int) -> CGRect { return CGRect(x: x, y: y, width: width, height: height) } public func CGRectGetMinX(_ rect: CGRect) -> CGFloat { return rect.minX } public func CGRectGetMidX(_ rect: CGRect) -> CGFloat { return rect.midX } public func CGRectGetMaxX(_ rect: CGRect) -> CGFloat { return rect.maxX } public func CGRectGetMinY(_ rect: CGRect) -> CGFloat { return rect.minY } public func CGRectGetMidY(_ rect: CGRect) -> CGFloat { return rect.midY } public func CGRectGetMaxY(_ rect: CGRect) -> CGFloat { return rect.maxY } public func CGRectGetWidth(_ rect: CGRect) -> CGFloat { return rect.width } public func CGRectGetHeight(_ rect: CGRect) -> CGFloat { return rect.height } public func CGRectEqualToRect(_ lhs: CGRect, _ rhs: CGRect) -> Bool { return lhs.equalTo(rhs) } public func CGRectStandardize(_ rect: CGRect) -> CGRect { return CGRect(x: abs(rect.minX), y: abs(rect.minY), width: abs(rect.width), height: abs(rect.height)) } public func CGRectIsEmpty(_ rect: CGRect) -> Bool { return rect.isEmpty } public func CGRectIsNull(_ rect: CGRect) -> Bool { return rect.isNull } public func CGRectIsInfinite(_ rect: CGRect) -> Bool { return rect.isInfinite } public func CGRectInset(_ rect: CGRect, _ dx: CGFloat, _ dy: CGFloat) -> CGRect { return rect.insetBy(dx: dx, dy: dy) } public func CGRectOffset(_ rect: CGRect, _ dx: CGFloat, _ dy: CGFloat) -> CGRect { return rect.offsetBy(dx: dx, dy: dy) } public func CGRectIntegral(_ rect: CGRect) -> CGRect { return rect.integral } public func CGRectUnion(_ rect1: CGRect, _ rect2: CGRect) -> CGRect { return rect1.union(rect2) } public func CGRectIntersection(_ rect1: CGRect, _ rect2: CGRect) -> CGRect { return rect2.intersection(rect2) } public func CGRectDivide(_ rect: CGRect, _ atDistance: CGFloat, _ from: CGRectEdge) -> (slice: CGRect, remainder: CGRect) { return rect.divided(atDistance: atDistance, from: from) } public func CGRectContainsPoint(_ rect: CGRect, _ point: CGPoint) -> Bool { return rect.contains(point) } public func CGRectContainsRect(_ rect1: CGRect, _ rect2: CGRect) -> Bool { return rect1.contains(rect2) } public func CGRectIntersectsRect(_ rect1: CGRect, _ rect2: CGRect) -> Bool { return rect1.intersects(rect2) } // MARK: - public extension CGAffineTransform { /// X scale from transform public var xScale: CGFloat { return sqrt(a * a + c * c) } /// Y scale from transform public var yScale: CGFloat { return sqrt(b * b + d * d) } /// Rotation in radians public var rotation: CGFloat { return CGFloat(atan2f(Float(b), Float(a))) } } // MARK: - public extension UIBezierPath { /// The path bounding box of `path'. public var boundingBox: CGRect { return cgPath.boundingBoxOfPath } /// The calculated bounds taking line width into account public var boundingWithLineBox: CGRect { return boundingBox.insetBy(dx: -lineWidth / 2.0, dy: -lineWidth / 2.0) } /// The center point for the path bounding box of `path'. public var boundingCenter: CGPoint { return CGRectGetCenter(boundingBox) } /// Translate path’s origin to its center before applying the transform public func centering(transform: CGAffineTransform) { let center = boundingCenter var t = CGAffineTransform.identity t = t.translatedBy(x: center.x, y: center.y) t = transform.concatenating(t) t = t.translatedBy(x: -center.x, y: -center.y) apply(t) } public func offset(vector: CGVector) { centering(transform: CGAffineTransform(translationX: vector.dx, y: vector.dy)) } public func rotate(theta: CGFloat) { centering(transform: CGAffineTransform(rotationAngle: theta)) } /// Move to a new center public func moveCenter(to position: CGPoint) { let bounds = boundingBox var vector = bounds.origin.makeVector(to: position) vector.dx -= bounds.size.width / 2.0 vector.dy -= bounds.size.height / 2.0 offset(vector: vector) } public func scale(xFactor: CGFloat, yFactor: CGFloat) { centering(transform: CGAffineTransform(scaleX: xFactor, y: yFactor)) } public func fit(to destRect: CGRect) { let bounds = boundingBox let fitRect = bounds.filling(in: destRect) let factor = min(destRect.size.width / bounds.size.width, destRect.size.height / bounds.size.height) moveCenter(to: fitRect.center) scale(xFactor: factor, yFactor: factor) } public func horizontalInverst() { centering(transform: CGAffineTransform(scaleX: -1, y: 1)) } public func verticalInverst() { centering(transform: CGAffineTransform(scaleX: 1, y: -1)) } public class func make(string: NSString, font: UIFont) -> UIBezierPath? { // Initialize path let path = UIBezierPath() if (0 == string.length) { return path } // Create font ref let fontRef = CTFontCreateWithName((font.fontName as CFString?)!, font.pointSize, nil) // Create glyphs (that is, individual letter shapes) var characters = [UniChar]() let length = (string as NSString).length for i in stride(from: 0, to: length, by: 1) { characters.append((string as NSString).character(at: i)) } let glyphs = UnsafeMutablePointer<CGGlyph>.allocate(capacity: length) glyphs.initialize(to: 0) let success = CTFontGetGlyphsForCharacters(font, characters, glyphs, length) if (!success) { logging("Error retrieving string glyphs") free(glyphs) return nil } // Draw each char into path for i in 0 ..< string.length { // Glyph to CGPath let glyph = glyphs[i] guard let pathRef = CTFontCreatePathForGlyph(fontRef, glyph, nil) else { return nil } // Append CGPath path.append(UIBezierPath(cgPath: pathRef)) // Offset by size let size = (string.substring(with: NSRange( i ..< i + 1)) as NSString).size(withAttributes: [NSAttributedStringKey.font: font]) path.offset(vector: CGVector(dx: -size.width, dy: 0)) } // Clean up free(glyphs) // Return the path to the UIKit coordinate system MirrorPathVertically(path); return path } public class func makePolygon(numberOfSides: Int) -> UIBezierPath? { if numberOfSides < 3 { logging("Error: Please supply at least 3 sides") return nil } let path = UIBezierPath() // Use a unit rectangle as the destination let destinationRect = CGRect(x: 0, y: 0, width: 1, height: 1) let center = CGRectGetCenter(destinationRect) let radius: CGFloat = 0.5 var firstPoint = true for i in 0 ..< numberOfSides - 1 { let theta: Double = Double.pi + Double(i) * 2 * Double.pi / Double(numberOfSides) let dTheta: Double = 2 * Double.pi / Double(numberOfSides) var point = CGPoint.zero if firstPoint { point.x = center.x + radius * CGFloat(sin(theta)) point.y = center.y + radius * CGFloat(cos(dTheta)) firstPoint = false } point.x = center.x + radius * CGFloat(sin(theta + dTheta)) point.y = center.y + radius * CGFloat(cos(theta + dTheta)) path.addLine(to: point) } path.close() return path } } /// Query context for size and use screen scale to map from Quartz pixels to UIKit points public func UIKitGetContextSize() -> CGSize { guard let context = UIGraphicsGetCurrentContext() else { return CGSize.zero } let size = CGSize( width: CGFloat(context.width), height: CGFloat(context.height) ) let scale: CGFloat = UIScreen.main.scale return CGSize( width: size.width / scale, height: size.height / scale ) } public extension CGContext { /// Horizontal flip context by supplying the size public func horizontalInverst(size: CGSize) { textMatrix = CGAffineTransform.identity translateBy(x: size.width, y: 0) scaleBy(x: -1.0, y: 1.0) } /// Vertical flip context by supplying the size public func verticalInverst(size: CGSize) { textMatrix = CGAffineTransform.identity translateBy(x: 0, y: size.height) scaleBy(x: 1.0, y: -1.0) } /// Flip context by retrieving image @discardableResult public func horizontalInverstImage() -> Bool { if let image = UIGraphicsGetImageFromCurrentImageContext() { horizontalInverst(size: image.size) return true } return false } /// Flip context by retrieving image @discardableResult public func verticalInverstImage() -> Bool { if let image = UIGraphicsGetImageFromCurrentImageContext() { verticalInverst(size: image.size) return true } return false } }
mit
c2dc4a526e16a84789703b930ddc1f4a
29.465116
139
0.618321
4.172924
false
false
false
false
rishi420/SearchTableView
SearchTable/SearchTableView.swift
1
4278
// // SearchTableView.swift // Genops // // Created by Warif Akhand Rishi on 4/11/16. // Copyright © 2016 Genweb2. All rights reserved. // import UIKit public protocol SearchTableViewDataSource : NSObjectProtocol { func searchPropertyName() -> String } class SearchTableView : UITableView { var itemList : [AnyObject] { get { return getDataSource() } set { items = newValue } } var searchDataSource: SearchTableViewDataSource? fileprivate var items = [AnyObject]() fileprivate var searchProperty : String { guard let searchDataSource = searchDataSource else { return "" } return searchDataSource.searchPropertyName() } fileprivate var filteredItems = [AnyObject]() fileprivate let searchController = UISearchController(searchResultsController: .none) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { DispatchQueue.main.async { () -> Void in self.searchController.dimsBackgroundDuringPresentation = false self.searchController.searchResultsUpdater = self self.searchController.searchBar.sizeToFit() self.tableHeaderView = self.searchController.searchBar let contentOffset = CGPoint(x: 0.0, y: self.contentOffset.y + self.searchController.searchBar.frame.height) self.setContentOffset(contentOffset, animated: false) } } fileprivate func getDataSource() -> [AnyObject] { return (searchController.isActive) ? filteredItems : items } } extension SearchTableView: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { // Update the filtered array based on the search text. let searchResults = items // Strip out all the leading and trailing spaces. let whitespaceCharacterSet = CharacterSet.whitespaces let strippedString = searchController.searchBar.text!.trimmingCharacters(in: whitespaceCharacterSet) let searchItems = strippedString.components(separatedBy: " ") as [String] // Build all the "AND" expressions for each value in the searchString. let andMatchPredicates: [NSPredicate] = searchItems.map { searchString in // Each searchString creates an OR predicate for: name, yearIntroduced, introPrice. var searchItemsPredicate = [NSPredicate]() // Below we use NSExpression represent expressions in our predicates. // NSPredicate is made up of smaller, atomic parts: two NSExpressions (a left-hand value and a right-hand value). // Name field matching. let titleExpression = NSExpression(forKeyPath: searchProperty) let searchStringExpression = NSExpression(forConstantValue: searchString) let titleSearchComparisonPredicate = NSComparisonPredicate(leftExpression: titleExpression, rightExpression: searchStringExpression, modifier: .direct, type: .contains, options: .caseInsensitive) searchItemsPredicate.append(titleSearchComparisonPredicate) let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .none numberFormatter.formatterBehavior = .default // Add this OR predicate to our master AND predicate. let orMatchPredicate = NSCompoundPredicate(orPredicateWithSubpredicates:searchItemsPredicate) return orMatchPredicate } // Match up the fields of the Product object. let finalCompoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: andMatchPredicates) let filteredResults = searchResults.filter { finalCompoundPredicate.evaluate(with: $0) } // Hand over the filtered results to our search results table. //let resultsController = searchController.searchResultsController as! ProjectListViewController filteredItems = filteredResults reloadData() } }
mit
41060e8e58471b3217e1dc41b078b5b8
37.531532
207
0.663082
5.965132
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.RelativeHumidityHumidifierThreshold.swift
1
2199
import Foundation public extension AnyCharacteristic { static func relativeHumidityHumidifierThreshold( _ value: Float = 0, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Relative Humidity Humidifier Threshold", format: CharacteristicFormat? = .float, unit: CharacteristicUnit? = .percentage, maxLength: Int? = nil, maxValue: Double? = 100, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.relativeHumidityHumidifierThreshold( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func relativeHumidityHumidifierThreshold( _ value: Float = 0, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Relative Humidity Humidifier Threshold", format: CharacteristicFormat? = .float, unit: CharacteristicUnit? = .percentage, maxLength: Int? = nil, maxValue: Double? = 100, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Float> { GenericCharacteristic<Float>( type: .relativeHumidityHumidifierThreshold, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
585828b918c69b1c3d2480c30c9defdd
35.04918
75
0.602092
5.389706
false
false
false
false
icecrystal23/ios-charts
ChartsDemo-iOS/Swift/Demos/LineChart2ViewController.swift
2
7625
// // LineChart2ViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import UIKit import Charts class LineChart2ViewController: DemoBaseViewController { @IBOutlet var chartView: LineChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Line Chart 2" self.options = [.toggleValues, .toggleFilled, .toggleCircles, .toggleCubic, .toggleHorizontalCubic, .toggleStepped, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.dragEnabled = true chartView.setScaleEnabled(true) chartView.pinchZoomEnabled = true let l = chartView.legend l.form = .line l.font = UIFont(name: "HelveticaNeue-Light", size: 11)! l.textColor = .white l.horizontalAlignment = .left l.verticalAlignment = .bottom l.orientation = .horizontal l.drawInside = false let xAxis = chartView.xAxis xAxis.labelFont = .systemFont(ofSize: 11) xAxis.labelTextColor = .white xAxis.drawAxisLineEnabled = false let leftAxis = chartView.leftAxis leftAxis.labelTextColor = UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1) leftAxis.axisMaximum = 200 leftAxis.axisMinimum = 0 leftAxis.drawGridLinesEnabled = true leftAxis.granularityEnabled = true let rightAxis = chartView.rightAxis rightAxis.labelTextColor = .red rightAxis.axisMaximum = 900 rightAxis.axisMinimum = -200 rightAxis.granularityEnabled = false sliderX.value = 20 sliderY.value = 30 slidersValueChanged(nil) chartView.animate(xAxisDuration: 2.5) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value + 1), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let yVals1 = (0..<count).map { (i) -> ChartDataEntry in let mult = range / 2 let val = Double(arc4random_uniform(mult) + 50) return ChartDataEntry(x: Double(i), y: val) } let yVals2 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 450) return ChartDataEntry(x: Double(i), y: val) } let yVals3 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 500) return ChartDataEntry(x: Double(i), y: val) } let set1 = LineChartDataSet(values: yVals1, label: "DataSet 1") set1.axisDependency = .left set1.setColor(UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)) set1.setCircleColor(.white) set1.lineWidth = 2 set1.circleRadius = 3 set1.fillAlpha = 65/255 set1.fillColor = UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1) set1.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1) set1.drawCircleHoleEnabled = false let set2 = LineChartDataSet(values: yVals2, label: "DataSet 2") set2.axisDependency = .right set2.setColor(.red) set2.setCircleColor(.white) set2.lineWidth = 2 set2.circleRadius = 3 set2.fillAlpha = 65/255 set2.fillColor = .red set2.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1) set2.drawCircleHoleEnabled = false let set3 = LineChartDataSet(values: yVals3, label: "DataSet 3") set3.axisDependency = .right set3.setColor(.yellow) set3.setCircleColor(.white) set3.lineWidth = 2 set3.circleRadius = 3 set3.fillAlpha = 65/255 set3.fillColor = UIColor.yellow.withAlphaComponent(200/255) set3.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1) set3.drawCircleHoleEnabled = false let data = LineChartData(dataSets: [set1, set2, set3]) data.setValueTextColor(.white) data.setValueFont(.systemFont(ofSize: 9)) chartView.data = data } override func optionTapped(_ option: Option) { switch option { case .toggleFilled: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.drawFilledEnabled = !set.drawFilledEnabled } chartView.setNeedsDisplay() case .toggleCircles: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.drawCirclesEnabled = !set.drawCirclesEnabled } chartView.setNeedsDisplay() case .toggleCubic: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier } chartView.setNeedsDisplay() case .toggleStepped: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .stepped) ? .linear : .stepped } chartView.setNeedsDisplay() case .toggleHorizontalCubic: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .cubicBezier) ? .horizontalBezier : .cubicBezier } chartView.setNeedsDisplay() default: super.handleOption(option, forChartView: chartView) } } @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } //} // TODO: Declarations in extensions cannot override yet. //extension LineChart2ViewController { override func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) { super.chartValueSelected(chartView, entry: entry, highlight: highlight) self.chartView.centerViewToAnimated(xValue: entry.x, yValue: entry.y, axis: self.chartView.data!.getDataSetByIndex(highlight.dataSetIndex).axisDependency, duration: 1) //[_chartView moveViewToAnimatedWithXValue:entry.x yValue:entry.y axis:[_chartView.data getDataSetByIndex:dataSetIndex].axisDependency duration:1.0]; //[_chartView zoomAndCenterViewAnimatedWithScaleX:1.8 scaleY:1.8 xValue:entry.x yValue:entry.y axis:[_chartView.data getDataSetByIndex:dataSetIndex].axisDependency duration:1.0]; } }
apache-2.0
c5299778dc9f3773b96eeb1a27865ce4
37.12
186
0.585519
4.791955
false
false
false
false
FoodMob/FoodMob-iOS
FoodMob/Networking/FoodMobService.swift
1
11923
// // FoodMobService.swift // FoodMob // // Created by Jonathan Jemson on 2/5/16. // Copyright © 2016 Jonathan Jemson. All rights reserved. // import Foundation import Alamofire import SwiftyJSON import UIKit.UIImage import AlamofireImage /** The actual FoodMob service data source. Requires network access in order to function properly. */ public struct FoodMobService: FoodMobDataSource { private struct ServiceEndpoint : Endpoint { static var root: String { return "https://fm.fluf.me" } } public func login(emailAddress: String, password: String, completion: ((User?) -> ())? = nil) { guard validateEmailAddress(emailAddress) && validatePassword(password) else { completion?(nil) return } Alamofire.request(ServiceEndpoint.loginMethod, ServiceEndpoint.login, parameters: [UserField.emailAddress: emailAddress, UserField.password: password], encoding: .JSON).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) if let firstName = json[UserField.profile][UserField.firstName].string, lastName = json[UserField.profile][UserField.lastName].string, emailAddress = json[UserField.emailAddress].string, authToken = json[UserField.authToken].string { let user = User(firstName: firstName, lastName: lastName, emailAddress: emailAddress, authToken: authToken) completion?(user) } else { completion?(nil) } } case .Failure(let error): print(error) completion?(nil) } } } @warn_unused_result public func register(firstName firstName: String, lastName: String, emailAddress: String, password: String, completion: ((Bool) -> ())? = nil) { guard validateName(firstName) && validateName(lastName) && validateEmailAddress(emailAddress) && validatePassword(password) else { completion?(false) return } let parameters = [ UserField.emailAddress : emailAddress, UserField.password : password, UserField.firstName : firstName, UserField.lastName : lastName ] Alamofire.request(ServiceEndpoint.registerMethod, ServiceEndpoint.register, parameters: parameters, encoding: .JSON).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) completion?(json["success"].boolValue) print(json) } case .Failure(let error): print(error) completion?(false) } } } public func logout(user: User, completion: ((Bool) -> ())? = nil) { Alamofire.request(ServiceEndpoint.logoutMethod, ServiceEndpoint.logout, parameters: [UserField.emailAddress: user.emailAddress, UserField.authToken: user.authToken], encoding: .JSON).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) completion?(json["success"].boolValue) } case .Failure(let error): print(error) completion?(false) } } // We should probably log the user out of the local app anyway. user.eraseUser() } public func updateCategoriesForUser(user: User) { var likes = [String]() var dislikes = [String]() var restrictions = [String]() for (cat, pref) in user.categories { switch pref { case .Like: likes += [cat.yelpIdentifier] case .Dislike: dislikes += [cat.yelpIdentifier] case .Restriction: restrictions += [cat.yelpIdentifier] default: print("Ignoring pref \(cat.yelpIdentifier)") } } let foodProfile = [UserField.FoodProfile.likes: likes, UserField.FoodProfile.dislikes: dislikes, UserField.FoodProfile.restrictions : restrictions] Alamofire.request(ServiceEndpoint.updateFoodProfileMethod, ServiceEndpoint.foodProfile(user), parameters: [UserField.authToken: user.authToken, UserField.foodProfile: foodProfile], encoding: .JSON).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) } case .Failure(let error): print(error) } } } public func fetchCategoriesForUser(user: User, completion: ((Bool)->())? = nil) { Alamofire.request(ServiceEndpoint.getFoodProfileMethod, ServiceEndpoint.foodProfile(user), parameters: [UserField.authToken: user.authToken], encoding: .URL).validate().responseJSON { response in debugPrint(response.request) switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) let profile = json[UserField.foodProfile].dictionaryValue var categories = [FoodCategory : Preference]() self.fetchCategoryListing({ (catListing) in if let likes = profile[UserField.FoodProfile.likes]?.arrayValue, dislikes = profile[UserField.FoodProfile.dislikes]?.arrayValue, restrictions = profile[UserField.FoodProfile.restrictions]?.arrayValue { for like in likes { if let cat = catListing[like.stringValue] { categories[cat] = Preference.Like } } for dislike in dislikes { if let cat = catListing[dislike.stringValue] { categories[cat] = Preference.Dislike } } for restriction in restrictions { if let coolCat = catListing[restriction.stringValue] { categories[coolCat] = Preference.Restriction } } user.categories = categories } completion?(json["success"].boolValue) }) } case .Failure(let error): print(error) } } } public func fetchRestaurantsForSearch(search: RestaurantSearch, withUser user: User, completion: (([Restaurant]) -> ())?) { var parameters: [String: AnyObject] = [ UserField.authToken: user.authToken, UserField.emailAddress: user.emailAddress, ] search.jsonDictionary.forEach { (tuple) in parameters[tuple.0] = tuple.1 } Alamofire.request(ServiceEndpoint.searchMethod, ServiceEndpoint.search, parameters: parameters, encoding: .JSON).validate().responseJSON { response in switch response.result { case .Success: var restaurants = [Restaurant]() if let value = response.result.value { let json = JSON(value) for restaurant in json[RestaurantField.root].arrayValue { var cats = restaurant[RestaurantField.categories].arrayValue.reduce("", combine: { (str, json) -> String in return "\(str), \(json.arrayValue[0].stringValue)" }) cats = cats.substringFromIndex(cats.startIndex.advancedBy(2)) let location = restaurant[RestaurantField.location].dictionaryValue let address = location[RestaurantField.address]?.arrayValue.reduce("", combine: { (s, json) -> String in return "\(s)\(json.stringValue)\n" }).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) var rst = Restaurant(name: restaurant[RestaurantField.name].stringValue, categories: cats, stars: restaurant[RestaurantField.stars].doubleValue, numReviews: restaurant[RestaurantField.reviewCount].intValue, hours: "", phoneNumber: restaurant[RestaurantField.phoneNumber].stringValue, address: address ?? "") rst.yelpURL = restaurant[RestaurantField.yelpURL].URL rst.imageURL = restaurant[RestaurantField.imageURL].URL restaurants.append(rst) } } completion?(restaurants) case .Failure(let error): print(error) completion?([]) } } } public func fetchFriendsListing(forUser user: User, completion: (([User])->())? = nil) { let parameters: [String: AnyObject] = [ UserField.authToken: user.authToken ] var friendList: [User] = [] Alamofire.request(ServiceEndpoint.getFriendsMethod, ServiceEndpoint.friends(user), parameters: parameters, encoding: .URL).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) for friend in json[UserField.friends].arrayValue { if let firstName = friend[UserField.firstName].string, lastName = friend[UserField.lastName].string, email = friend[UserField.emailAddress].string { friendList.append(User(firstName: firstName, lastName: lastName, emailAddress: email)) } } } case .Failure(let error): print(response.result.value) print(error) } completion?(friendList) } } public func addFriendWithEmail(emailAddress: String, forUser user: User, completion: ((Bool, String)->())? = nil) { let parameters: [String: AnyObject] = [ UserField.authToken: user.authToken, UserField.friendEmail: emailAddress ] Alamofire.request(ServiceEndpoint.setFriendsMethod, ServiceEndpoint.friends(user), parameters: parameters, encoding: .JSON).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if json["success"].boolValue { completion?(true, "") } else { completion?(false, json["error"].stringValue) } } case .Failure(_): completion?(false, "Network Error") } } } }
mit
6557457fd08c22225440031dcd6b821e
43.823308
331
0.539004
5.578849
false
false
false
false
abstractmachine/Automatic.Writer
AutomaticWriter/Views/OutlineView/FileSystemItem.swift
1
4740
// // FileSystemItem.swift // AutomaticWriter // // Created by Raphael on 19.01.15. // Copyright (c) 2015 HEAD Geneva. All rights reserved. // import Cocoa let leafNode:[FileSystemItem] = [] /* func ==(left:FileSystemItem, right:FileSystemItem) -> Bool { return left.relativePath == right.relativePath } */ class FileSystemItem: NSObject { var relativePath:String var parent:FileSystemItem? var children:[FileSystemItem] = [] init(path:String, parentItem:FileSystemItem?) { relativePath = path parent = parentItem super.init() } func isRoot() -> Bool { return parent == nil } func isDirectory() -> Bool { return numberOfChildren() > -1 } func numberOfChildren() -> Int { reloadChildren() return (children == leafNode) ? -1 : children.count } func getParent() -> FileSystemItem? { return parent } func isFileInChildren(path:String) -> Bool { for child in children { if child.relativePath == path { return true } } return false } func cleanChildren() { let childrenCount = children.count for (var i = childrenCount-1; i >= 0; i--) { if !NSFileManager.defaultManager().fileExistsAtPath(children[i].fullPath()) { children.removeAtIndex(i) } } } func fullPath() -> String { let fullPath = parent?.fullPath() if let tmpFullPath = fullPath { return (tmpFullPath as NSString).stringByAppendingPathComponent(relativePath) } return relativePath } func sortChildren() { children.sortInPlace(childrenSorter) } func childrenSorter(this:FileSystemItem, that:FileSystemItem) -> Bool { switch this.relativePath.localizedCaseInsensitiveCompare(that.relativePath) { case .OrderedAscending: return true case .OrderedDescending: return false case .OrderedSame: return false } } func reloadChildren() { let path = fullPath() var valid : Bool = false var isDir : ObjCBool = false valid = NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDir) if valid == true && isDir.boolValue == true { cleanChildren() let directoryContent:[AnyObject]? = try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(path) if let content = directoryContent { //let numChildren:Int = content.count for (_, child) in content.enumerate() { let fileName:String? = child as? String if let name = fileName { if name.characters.count < 1 { continue; } if name[name.startIndex] == "." { continue; } if !isFileInChildren(name) { let newChild = FileSystemItem(path: name, parentItem: self) children += [newChild] } } } sortChildren() } } else { children = leafNode } } func getChildOfItem(item:FileSystemItem, path:String) -> FileSystemItem? { if (item.numberOfChildren() > 0) { for child in item.children { if (child.relativePath as NSString).lastPathComponent == path { return child } } } return nil } func getItemWithPath(path:String) -> FileSystemItem? { // work only from rootItem, so we look for it within a while loop var rootItem : FileSystemItem = self while !rootItem.isRoot() { rootItem = rootItem.parent! } let relativeItemPath : String = path.stringByReplacingOccurrencesOfString(rootItem.fullPath(), withString: "") let pathComponents = (relativeItemPath as NSString).pathComponents var returnedItem:FileSystemItem? = rootItem for component:String in pathComponents { if component == "/" { continue; } // we don't consider a "/" as a path component for the search returnedItem = getChildOfItem(returnedItem!, path: component) if (returnedItem == nil) { return nil } } return returnedItem } func childAtIndex(index:Int) -> AnyObject? { if index > children.count-1 { return nil } return children[index] } }
mit
0913dfbf51ed9627a082da68fe24bf18
29.191083
118
0.551266
5.313901
false
false
false
false
lemberg/connfa-ios
Connfa/Stores/Firebase/UserFirebase.swift
1
6509
// // UserFirebaseManager.swift // Connfa // // Created by Marian Fedyk on 12/15/17. // Copyright © 2017 Lemberg Solution. All rights reserved. // import Foundation import Firebase import SVProgressHUD extension UserDefaults { private var timezoneAlertHasBeenShownKey: String { return "com.connfa.timezoneAlertHasBeenShown" } var timezoneAlertHasBeenShown: Bool { get { return self.bool(forKey: timezoneAlertHasBeenShownKey) } set { set(newValue, forKey: timezoneAlertHasBeenShownKey) synchronize() } } } class UserFirebase { static let shared = UserFirebase() private init() { NotificationCenter.default.addObserver(self, selector: #selector(showLocalizationDiferenceAlertIfNeeded), name: .dismissedPreloader , object: nil) } typealias ErrorBlock = (_ error : FirebaseError?) -> () typealias CompletionBlock = () -> () private let ref = Database.database().reference() private var userSnapshot: DataSnapshot? private var usersReference: DatabaseReference { return ref.child(Keys.users) } private var currentUser: User? { return Auth.auth().currentUser } private var isAuthenticated: Bool { return currentUser != nil } var ownPinId: String? var userId: String? { return currentUser?.uid } var ownPin: Pin? { guard let id = ownPinId else { return nil } return Pin(pinId: id, displayName: Constants.Text.myInterested) } var pins: [Pin] { var summ: [Pin] = [] if let snapshots = userSnapshot?.childSnapshot(forPath: Keys.pins).children.allObjects as? [DataSnapshot] { summ = snapshots.map({ (snapshot) -> Pin in let dict = snapshot.value as? [String: Any] let key = snapshot.key return Pin(dictionary: dict, key: key) }) } if let pin = ownPin { summ.append(pin) } return summ } private(set) var isReachable: Bool = true func addPin(pin: Pin,_ block: @escaping ErrorBlock) { guard isReachable else { block(.noInternet) return } guard let id = UserFirebase.shared.userId else { block(.noCurrentUser) return } guard InterestedFirebase.shared.isValid(pin.pinId) else { block(.invalidPin) return } let refPins = UserFirebase.shared.ref.child(Keys.pins) refPins.observeSingleEvent(of: .value) { (snapshot) in if snapshot.hasChild(pin.pinId) { ///user is here let ref = self.usersReference.child(id).child(Keys.pins).child(pin.pinId) if pin.displayName == nil { ref.setValue(true) } else { ref.setValue([Keys.displayName: pin.displayName]) } block(nil) } else { ///no user for this pin block(.noPin) return } } } func sharePinByPresentingActivity(on vc: UIViewController) { guard let pin = ownPin?.pinId else { SVProgressHUD.showError(withStatus: FirebaseError.noPin.description) return } if isReachable { var longDynamicLink: URL? = nil if let url = URL(string: "https://www.connfa.com/incomingParams?\(Keys.User.pinId)=\(pin)") { longDynamicLink = DynamicLinkComponents(link: url, domain: Constants.Links.dynamicDomain).url } var invitation = Constants.Text.invitation + pin if let link = longDynamicLink { invitation += "\nTap to proceed: \(link)" } let activityVC = UIActivityViewController(activityItems: [invitation], applicationActivities: nil) .withDefaultExcludedActivity() activityVC.popoverPresentationController?.sourceView = vc.view vc.present(activityVC, animated: true) } else { SVProgressHUD.showError(withStatus: "Internet connections is not available at this moment. Please, try later.") } } func deletePin(pin: Pin, _ block: @escaping ErrorBlock) { guard let id = userId else { block(.noCurrentUser) return } guard pin != ownPin else { block(.invalidPin) return } let ref = usersReference.child(id).child(Keys.pins).child(pin.pinId) ref.removeValue() block(nil) } func signIn() { guard !isAuthenticated else { print("You are already signed in") setupAuthRelatedObservers() observeConnection {} return } Auth.auth().signInAnonymously(completion: { (user, error) in if let error = error { SVProgressHUD.showError(withStatus: error.localizedDescription) guard !self.isAuthenticated, self.isReachable else { return } DispatchQueue.main.asyncAfter(deadline: .now() + 15, execute: { print("sign in") self.signIn() }) print("Anonymous auth failed") } else { self.setupAuthRelatedObservers() print("Sign in succesful") } }) } @objc private func showLocalizationDiferenceAlertIfNeeded() { let config = Configurations() if !UserDefaults.standard.timezoneAlertHasBeenShown && TimeZone.current.identifier != config.timeZoneIdentifier { let alert = UIAlertController(title: "Timezone", message: "Event dates are provided in (time zone of event): \(config.timeZoneIdentifier)", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .cancel) alert.addAction(okAction) UIApplication.topViewController()?.present(alert, animated: true) UserDefaults.standard.timezoneAlertHasBeenShown = true } } private func signOut() { do { try Auth.auth().signOut() NotificationCenter.default.post(name: .signedOut, object: nil, userInfo: nil) } catch { SVProgressHUD.showError(withStatus: error.localizedDescription) } } func observeConnection(_ block: @escaping CompletionBlock) { ref.child(".info/connected").observe(.value, with: { snapshot in if snapshot.value as? Bool ?? false { self.isReachable = true block() } else { self.isReachable = false } }) } private func setupAuthRelatedObservers() { guard let id = userId else { return } usersReference.child(id).observe(.value) { (snapshot) in self.userSnapshot = snapshot } usersReference.child(id).child(Keys.User.ownPin).observe(.value) { (snapshot) in if let pin = snapshot.value as? String { self.ownPinId = pin NotificationCenter.default.post(name: .signedIn, object: nil, userInfo: nil) } } } }
apache-2.0
22d7ad7957634487fcbdbe3d247244d2
28.447964
169
0.650738
4.267541
false
false
false
false
narner/AudioKit
AudioKit/Common/Nodes/Generators/Oscillators/Phase Distortion Oscillator/AKPhaseDistortionOscillator.swift
1
6940
// // AKPhaseDistortionOscillator.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// Phase Distortion Oscillator /// open class AKPhaseDistortionOscillator: AKNode, AKToggleable, AKComponent { public typealias AKAudioUnitType = AKPhaseDistortionOscillatorAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(generator: "phdo") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var waveform: AKTable? fileprivate var frequencyParameter: AUParameter? fileprivate var amplitudeParameter: AUParameter? fileprivate var phaseDistortionParameter: AUParameter? fileprivate var detuningOffsetParameter: AUParameter? fileprivate var detuningMultiplierParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// In cycles per second, or Hz. @objc open dynamic var frequency: Double = 440 { willSet { if frequency != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { frequencyParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.frequency = Float(newValue) } } } } /// Output amplitude @objc open dynamic var amplitude: Double = 1.0 { willSet { if amplitude != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { amplitudeParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.amplitude = Float(newValue) } } } } /// Frequency offset in Hz. @objc open dynamic var detuningOffset: Double = 0 { willSet { if detuningOffset != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { detuningOffsetParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.detuningOffset = Float(newValue) } } } } /// Frequency detuning multiplier @objc open dynamic var detuningMultiplier: Double = 1 { willSet { if detuningMultiplier != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { detuningMultiplierParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.detuningMultiplier = Float(newValue) } } } } /// Duty cycle width (range -1 - 1). @objc open dynamic var phaseDistortion: Double = 0.0 { willSet { if phaseDistortion != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { phaseDistortionParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.phaseDistortion = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize the oscillator with defaults public convenience override init() { self.init(waveform: AKTable(.sine)) } /// Initialize this oscillator node /// /// - Parameters: /// - waveform: The waveform of oscillation /// - frequency: In cycles per second, or Hz. /// - amplitude: Output amplitude /// - phaseDistortion: Duty cycle width (range -1 - 1). /// - detuningOffset: Frequency offset in Hz. /// - detuningMultiplier: Frequency detuning multiplier /// @objc public init( waveform: AKTable, frequency: Double = 440, amplitude: Double = 1.0, phaseDistortion: Double = 0.0, detuningOffset: Double = 0, detuningMultiplier: Double = 1) { self.waveform = waveform self.frequency = frequency self.amplitude = amplitude self.phaseDistortion = phaseDistortion self.detuningOffset = detuningOffset self.detuningMultiplier = detuningMultiplier _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType self?.internalAU?.setupWaveform(Int32(waveform.count)) for (i, sample) in waveform.enumerated() { self?.internalAU?.setWaveformValue(sample, at: UInt32(i)) } } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } frequencyParameter = tree["frequency"] amplitudeParameter = tree["amplitude"] phaseDistortionParameter = tree["phaseDistortion"] detuningOffsetParameter = tree["detuningOffset"] detuningMultiplierParameter = tree["detuningMultiplier"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.frequency = Float(frequency) internalAU?.amplitude = Float(amplitude) internalAU?.phaseDistortion = Float(phaseDistortion) internalAU?.detuningOffset = Float(detuningOffset) internalAU?.detuningMultiplier = Float(detuningMultiplier) } /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
mit
7ca97d445edb9024eaf6903f6ee23b9c
33.695
105
0.583946
5.66449
false
false
false
false
stephentyrone/swift
stdlib/public/core/StringObject.swift
6
40706
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // StringObject abstracts the bit-level interpretation and creation of the // String struct. // // TODO(String docs): Word-level diagram /* On 64-bit platforms, the discriminator is the most significant 4 bits of the bridge object. ┌─────────────────────╥─────┬─────┬─────┬─────┐ │ Form ║ b63 │ b62 │ b61 │ b60 │ ╞═════════════════════╬═════╪═════╪═════╪═════╡ │ Immortal, Small ║ 1 │ASCII│ 1 │ 0 │ ├─────────────────────╫─────┼─────┼─────┼─────┤ │ Immortal, Large ║ 1 │ 0 │ 0 │ 0 │ ╞═════════════════════╬═════╪═════╪═════╪═════╡ │ Native ║ 0 │ 0 │ 0 │ 0 │ ├─────────────────────╫─────┼─────┼─────┼─────┤ │ Shared ║ x │ 0 │ 0 │ 0 │ ├─────────────────────╫─────┼─────┼─────┼─────┤ │ Shared, Bridged ║ 0 │ 1 │ 0 │ 0 │ ╞═════════════════════╬═════╪═════╪═════╪═════╡ │ Foreign ║ x │ 0 │ 0 │ 1 │ ├─────────────────────╫─────┼─────┼─────┼─────┤ │ Foreign, Bridged ║ 0 │ 1 │ 0 │ 1 │ └─────────────────────╨─────┴─────┴─────┴─────┘ b63: isImmortal: Should the Swift runtime skip ARC - Small strings are just values, always immortal - Large strings can sometimes be immortal, e.g. literals b62: (large) isBridged / (small) isASCII - For large strings, this means lazily-bridged NSString: perform ObjC ARC - Small strings repurpose this as a dedicated bit to remember ASCII-ness b61: isSmall: Dedicated bit to denote small strings b60: isForeign: aka isSlow, cannot provide access to contiguous UTF-8 The canonical empty string is the zero-sized small string. It has a leading nibble of 1110, and all other bits are 0. A "dedicated" bit is used for the most frequent fast-path queries so that they can compile to a fused check-and-branch, even if that burns part of the encoding space. On 32-bit platforms, we store an explicit discriminator (as a UInt8) with the same encoding as above, placed in the high bits. E.g. `b62` above is in `_discriminator`'s `b6`. */ @frozen @usableFromInline internal struct _StringObject { // Namespace to hold magic numbers @usableFromInline @frozen enum Nibbles {} // Abstract the count and performance-flags containing word @frozen @usableFromInline struct CountAndFlags { @usableFromInline var _storage: UInt64 @inlinable @inline(__always) internal init(zero: ()) { self._storage = 0 } } #if arch(i386) || arch(arm) || arch(wasm32) @usableFromInline @frozen internal enum Variant { case immortal(UInt) case native(AnyObject) case bridged(_CocoaString) @inlinable @inline(__always) internal static func immortal(start: UnsafePointer<UInt8>) -> Variant { let biased = UInt(bitPattern: start) &- _StringObject.nativeBias return .immortal(biased) } @inlinable @inline(__always) internal var isImmortal: Bool { if case .immortal = self { return true } return false } } @usableFromInline internal var _count: Int @usableFromInline internal var _variant: Variant @usableFromInline internal var _discriminator: UInt8 @usableFromInline internal var _flags: UInt16 @inlinable @inline(__always) init(count: Int, variant: Variant, discriminator: UInt64, flags: UInt16) { _internalInvariant(discriminator & 0xFF00_0000_0000_0000 == discriminator, "only the top byte can carry the discriminator and small count") self._count = count self._variant = variant self._discriminator = UInt8(truncatingIfNeeded: discriminator &>> 56) self._flags = flags self._invariantCheck() } @inlinable @inline(__always) init(variant: Variant, discriminator: UInt64, countAndFlags: CountAndFlags) { self.init( count: countAndFlags.count, variant: variant, discriminator: discriminator, flags: countAndFlags.flags) } @inlinable @inline(__always) internal var _countAndFlagsBits: UInt64 { let rawBits = UInt64(truncatingIfNeeded: _flags) &<< 48 | UInt64(truncatingIfNeeded: _count) return rawBits } #else // // Laid out as (_countAndFlags, _object), which allows small string contents // to naturally start on vector-alignment. // @usableFromInline internal var _countAndFlagsBits: UInt64 @usableFromInline internal var _object: Builtin.BridgeObject @inlinable @inline(__always) internal init(zero: ()) { self._countAndFlagsBits = 0 self._object = Builtin.valueToBridgeObject(UInt64(0)._value) } #endif @inlinable @inline(__always) internal var _countAndFlags: CountAndFlags { _internalInvariant(!isSmall) return CountAndFlags(rawUnchecked: _countAndFlagsBits) } } // Raw extension _StringObject { @usableFromInline internal typealias RawBitPattern = (UInt64, UInt64) #if arch(i386) || arch(arm) || arch(wasm32) // On 32-bit platforms, raw bit conversion is one-way only and uses the same // layout as on 64-bit platforms. @usableFromInline internal var rawBits: RawBitPattern { @inline(__always) get { let count = UInt64(truncatingIfNeeded: UInt(bitPattern: _count)) let payload = UInt64(truncatingIfNeeded: discriminatedObjectRawBits) & _StringObject.Nibbles.largeAddressMask let flags = UInt64(truncatingIfNeeded: _flags) let discr = UInt64(truncatingIfNeeded: _discriminator) if isSmall { // Rearrange small strings in a different way, compacting bytes into a // contiguous sequence. See comment on small string layout below. return (count | (payload &<< 32), flags | (discr &<< 56)) } return (count | (flags &<< 48), payload | (discr &<< 56)) } } #else @inlinable @inline(__always) internal var rawBits: RawBitPattern { return (_countAndFlagsBits, discriminatedObjectRawBits) } @inlinable @inline(__always) internal init( bridgeObject: Builtin.BridgeObject, countAndFlags: CountAndFlags ) { self._object = bridgeObject self._countAndFlagsBits = countAndFlags._storage _invariantCheck() } @inlinable @inline(__always) internal init( object: AnyObject, discriminator: UInt64, countAndFlags: CountAndFlags ) { let builtinRawObject: Builtin.Int64 = Builtin.reinterpretCast(object) let builtinDiscrim: Builtin.Int64 = discriminator._value self.init( bridgeObject: Builtin.reinterpretCast( Builtin.stringObjectOr_Int64(builtinRawObject, builtinDiscrim)), countAndFlags: countAndFlags) } // Initializer to use for tagged (unmanaged) values @inlinable @inline(__always) internal init( pointerBits: UInt64, discriminator: UInt64, countAndFlags: CountAndFlags ) { let builtinValueBits: Builtin.Int64 = pointerBits._value let builtinDiscrim: Builtin.Int64 = discriminator._value self.init( bridgeObject: Builtin.valueToBridgeObject(Builtin.stringObjectOr_Int64( builtinValueBits, builtinDiscrim)), countAndFlags: countAndFlags) } @inlinable @inline(__always) internal init(rawUncheckedValue bits: RawBitPattern) { self.init(zero:()) self._countAndFlagsBits = bits.0 self._object = Builtin.valueToBridgeObject(bits.1._value) _internalInvariant(self.rawBits == bits) } @inlinable @inline(__always) internal init(rawValue bits: RawBitPattern) { self.init(rawUncheckedValue: bits) _invariantCheck() } #endif @inlinable @_transparent internal var discriminatedObjectRawBits: UInt64 { #if arch(i386) || arch(arm) || arch(wasm32) let low32: UInt switch _variant { case .immortal(let bitPattern): low32 = bitPattern case .native(let storage): low32 = Builtin.reinterpretCast(storage) case .bridged(let object): low32 = Builtin.reinterpretCast(object) } return UInt64(truncatingIfNeeded: _discriminator) &<< 56 | UInt64(truncatingIfNeeded: low32) #else return Builtin.reinterpretCast(_object) #endif } } // From/to raw bits for CountAndFlags extension _StringObject.CountAndFlags { @usableFromInline internal typealias RawBitPattern = UInt64 @inlinable @inline(__always) internal var rawBits: RawBitPattern { return _storage } @inlinable @inline(__always) internal init(rawUnchecked bits: RawBitPattern) { self._storage = bits } @inlinable @inline(__always) internal init(raw bits: RawBitPattern) { self.init(rawUnchecked: bits) _invariantCheck() } } /* Encoding is optimized for common fast creation. The canonical empty string, ASCII small strings, as well as most literals, have all consecutive 1s in their high nibble mask, and thus can all be encoded as a logical immediate operand on arm64. */ extension _StringObject.Nibbles { // The canonical empty sting is an empty small string @inlinable @inline(__always) internal static var emptyString: UInt64 { return _StringObject.Nibbles.small(isASCII: true) } } /* Large strings can either be "native", "shared", or "foreign". Native strings have tail-allocated storage, which begins at an offset of `nativeBias` from the storage object's address. String literals, which reside in the constant section, are encoded as their start address minus `nativeBias`, unifying code paths for both literals ("immortal native") and native strings. Native Strings are always managed by the Swift runtime. Shared strings do not have tail-allocated storage, but can provide access upon query to contiguous UTF-8 code units. Lazily-bridged NSStrings capable of providing access to contiguous ASCII/UTF-8 set the ObjC bit. Accessing shared string's pointer should always be behind a resilience barrier, permitting future evolution. Foreign strings cannot provide access to contiguous UTF-8. Currently, this only encompasses lazily-bridged NSStrings that cannot be treated as "shared". Such strings may provide access to contiguous UTF-16, or may be discontiguous in storage. Accessing foreign strings should remain behind a resilience barrier for future evolution. Other foreign forms are reserved for the future. Shared and foreign strings are always created and accessed behind a resilience barrier, providing flexibility for the future. ┌────────────┐ │ nativeBias │ ├────────────┤ │ 32 │ └────────────┘ ┌───────────────┬────────────┐ │ b63:b60 │ b60:b0 │ ├───────────────┼────────────┤ │ discriminator │ objectAddr │ └───────────────┴────────────┘ discriminator: See comment for _StringObject.Discriminator objectAddr: The address of the beginning of the potentially-managed object. TODO(Future): For Foreign strings, consider allocating a bit for whether they can provide contiguous UTF-16 code units, which would allow us to avoid doing the full call for non-contiguous NSString. */ extension _StringObject.Nibbles { // Mask for address bits, i.e. non-discriminator and non-extra high bits @inlinable @inline(__always) static internal var largeAddressMask: UInt64 { return 0x0FFF_FFFF_FFFF_FFFF } // Mask for address bits, i.e. non-discriminator and non-extra high bits @inlinable @inline(__always) static internal var discriminatorMask: UInt64 { return ~largeAddressMask } } extension _StringObject.Nibbles { // Discriminator for small strings @inlinable @inline(__always) internal static func small(isASCII: Bool) -> UInt64 { return isASCII ? 0xE000_0000_0000_0000 : 0xA000_0000_0000_0000 } // Discriminator for small strings @inlinable @inline(__always) internal static func small(withCount count: Int, isASCII: Bool) -> UInt64 { _internalInvariant(count <= _SmallString.capacity) return small(isASCII: isASCII) | UInt64(truncatingIfNeeded: count) &<< 56 } // Discriminator for large, immortal, swift-native strings @inlinable @inline(__always) internal static func largeImmortal() -> UInt64 { return 0x8000_0000_0000_0000 } // Discriminator for large, mortal (i.e. managed), swift-native strings @inlinable @inline(__always) internal static func largeMortal() -> UInt64 { return 0x0000_0000_0000_0000 } internal static func largeCocoa(providesFastUTF8: Bool) -> UInt64 { return providesFastUTF8 ? 0x4000_0000_0000_0000 : 0x5000_0000_0000_0000 } } extension _StringObject { @inlinable @inline(__always) internal static var nativeBias: UInt { #if arch(i386) || arch(arm) || arch(wasm32) return 20 #else return 32 #endif } @inlinable @inline(__always) internal var isImmortal: Bool { return (discriminatedObjectRawBits & 0x8000_0000_0000_0000) != 0 } @inlinable @inline(__always) internal var isMortal: Bool { return !isImmortal } @inlinable @inline(__always) internal var isSmall: Bool { return (discriminatedObjectRawBits & 0x2000_0000_0000_0000) != 0 } @inlinable @inline(__always) internal var isLarge: Bool { return !isSmall } // Whether this string can provide access to contiguous UTF-8 code units: // - Small strings can by spilling to the stack // - Large native strings can through an offset // - Shared strings can: // - Cocoa strings which respond to e.g. CFStringGetCStringPtr() // - Non-Cocoa shared strings @inlinable @inline(__always) internal var providesFastUTF8: Bool { return (discriminatedObjectRawBits & 0x1000_0000_0000_0000) == 0 } @inlinable @inline(__always) internal var isForeign: Bool { return !providesFastUTF8 } // Whether we are native or shared, i.e. we have a backing class which // conforms to `_AbstractStringStorage` @inline(__always) internal var hasStorage: Bool { return (discriminatedObjectRawBits & 0xF000_0000_0000_0000) == 0 } // Whether we are a mortal, native (tail-allocated) string @inline(__always) internal var hasNativeStorage: Bool { // b61 on the object means isSmall, and on countAndFlags means // isNativelyStored. We just need to check that b61 is 0 on the object and 1 // on countAndFlags. let bits = ~discriminatedObjectRawBits & self._countAndFlagsBits let result = bits & 0x2000_0000_0000_0000 != 0 _internalInvariant(!result || hasStorage, "native storage needs storage") return result } // Whether we are a mortal, shared string (managed by Swift runtime) internal var hasSharedStorage: Bool { return hasStorage && !hasNativeStorage } } // Queries conditional on being in a large or fast form. extension _StringObject { // Whether this string is native, i.e. tail-allocated and nul-terminated, // presupposing it is both large and fast @inlinable @inline(__always) internal var largeFastIsTailAllocated: Bool { _internalInvariant(isLarge && providesFastUTF8) return _countAndFlags.isTailAllocated } // Whether this string is shared, presupposing it is both large and fast @inline(__always) internal var largeFastIsShared: Bool { return !largeFastIsTailAllocated } // Whether this string is a lazily-bridged NSString, presupposing it is large @inline(__always) internal var largeIsCocoa: Bool { _internalInvariant(isLarge) return (discriminatedObjectRawBits & 0x4000_0000_0000_0000) != 0 } // Whether this string is in one of our fastest representations: // small or tail-allocated (i.e. mortal/immortal native) @_alwaysEmitIntoClient @inline(__always) internal var isPreferredRepresentation: Bool { return _fastPath(isSmall || _countAndFlags.isTailAllocated) } } /* On 64-bit platforms, small strings have the following per-byte layout. When stored in memory (little-endian), their first character ('a') is in the lowest address and their top-nibble and count is in the highest address. ┌───────────────────────────────┬─────────────────────────────────────────────┐ │ _countAndFlags │ _object │ ├───┬───┬───┬───┬───┬───┬───┬───┼───┬───┬────┬────┬────┬────┬────┬────────────┤ │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10 │ 11 │ 12 │ 13 │ 14 │ 15 │ ├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼────┼────┼────┼────┼────┼────────────┤ │ a │ b │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │ m │ n │ o │ 1x10 count │ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴────┴────┴────┴────┴────┴────────────┘ On 32-bit platforms, we have less space to store code units, and it isn't contiguous. However, we still use the above layout for the RawBitPattern representation. ┌───────────────┬───────────────────┬────────┬─────────┐ │ _count │_variant .immortal │ _discr │ _flags │ ├───┬───┬───┬───┼───┬───┬───┬───┬───┼────────┼────┬────┤ │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10 │ 11 │ ├───┼───┼───┼───┼───┴───┴───┴───┴───┼────────┼────┼────┤ │ a │ b │ c │ d │ e f g h │1x10 cnt│ i │ j │ └───┴───┴───┴───┴───────────────────┴────────┴────┴────┘ */ extension _StringObject { @inlinable @inline(__always) internal init(_ small: _SmallString) { // Small strings are encoded as _StringObjects in reverse byte order // on big-endian platforms. This is to match the discriminator to the // spare bits (the most significant nibble) in a pointer. let word1 = small.rawBits.0.littleEndian let word2 = small.rawBits.1.littleEndian #if arch(i386) || arch(arm) || arch(wasm32) // On 32-bit, we need to unpack the small string. let smallStringDiscriminatorAndCount: UInt64 = 0xFF00_0000_0000_0000 let leadingFour = Int(truncatingIfNeeded: word1) let nextFour = UInt(truncatingIfNeeded: word1 &>> 32) let smallDiscriminatorAndCount = word2 & smallStringDiscriminatorAndCount let trailingTwo = UInt16(truncatingIfNeeded: word2) self.init( count: leadingFour, variant: .immortal(nextFour), discriminator: smallDiscriminatorAndCount, flags: trailingTwo) #else // On 64-bit, we copy the raw bits (to host byte order). self.init(rawValue: (word1, word2)) #endif _internalInvariant(isSmall) } @inlinable internal static func getSmallCount(fromRaw x: UInt64) -> Int { return Int(truncatingIfNeeded: (x & 0x0F00_0000_0000_0000) &>> 56) } @inlinable @inline(__always) internal var smallCount: Int { _internalInvariant(isSmall) return _StringObject.getSmallCount(fromRaw: discriminatedObjectRawBits) } @inlinable internal static func getSmallIsASCII(fromRaw x: UInt64) -> Bool { return x & 0x4000_0000_0000_0000 != 0 } @inlinable @inline(__always) internal var smallIsASCII: Bool { _internalInvariant(isSmall) return _StringObject.getSmallIsASCII(fromRaw: discriminatedObjectRawBits) } @inlinable @inline(__always) internal init(empty:()) { // Canonical empty pattern: small zero-length string #if arch(i386) || arch(arm) || arch(wasm32) self.init( count: 0, variant: .immortal(0), discriminator: Nibbles.emptyString, flags: 0) #else self._countAndFlagsBits = 0 self._object = Builtin.valueToBridgeObject(Nibbles.emptyString._value) #endif _internalInvariant(self.smallCount == 0) _invariantCheck() } } /* // TODO(String docs): Combine this with Nibbles table, and perhaps small string // table, into something that describes the higher-level structure of // _StringObject. All non-small forms share the same structure for the other half of the bits (i.e. non-object bits) as a word containing code unit count and various performance flags. The top 16 bits are for performance flags, which are not semantically relevant but communicate that some operations can be done more efficiently on this particular string, and the lower 48 are the code unit count (aka endIndex). ┌─────────┬───────┬──────────────────┬─────────────────┬────────┬───────┐ │ b63 │ b62 │ b61 │ b60 │ b59:48 │ b47:0 │ ├─────────┼───────┼──────────────────┼─────────────────┼────────┼───────┤ │ isASCII │ isNFC │ isNativelyStored │ isTailAllocated │ TBD │ count │ └─────────┴───────┴──────────────────┴─────────────────┴────────┴───────┘ isASCII: set when all code units are known to be ASCII, enabling: - Trivial Unicode scalars, they're just the code units - Trivial UTF-16 transcoding (just bit-extend) - Also, isASCII always implies isNFC isNFC: set when the contents are in normal form C - Enables trivial lexicographical comparisons: just memcmp - `isASCII` always implies `isNFC`, but not vice versa isNativelyStored: set for native stored strings - `largeAddressBits` holds an instance of `_StringStorage`. - I.e. the start of the code units is at the stored address + `nativeBias` isTailAllocated: contiguous UTF-8 code units starts at address + `nativeBias` - `isNativelyStored` always implies `isTailAllocated`, but not vice versa (e.g. literals) - `isTailAllocated` always implies `isFastUTF8` TBD: Reserved for future usage - Setting a TBD bit to 1 must be semantically equivalent to 0 - I.e. it can only be used to "cache" fast-path information in the future count: stores the number of code units, corresponds to `endIndex`. NOTE: isNativelyStored is *specifically* allocated to b61 to align with the bit-position of isSmall on the BridgeObject. This allows us to check for native storage without an extra branch guarding against smallness. See `_StringObject.hasNativeStorage` for this usage. */ extension _StringObject.CountAndFlags { @inlinable @inline(__always) internal static var countMask: UInt64 { return 0x0000_FFFF_FFFF_FFFF } @inlinable @inline(__always) internal static var flagsMask: UInt64 { return ~countMask } @inlinable @inline(__always) internal static var isASCIIMask: UInt64 { return 0x8000_0000_0000_0000 } @inlinable @inline(__always) internal static var isNFCMask: UInt64 { return 0x4000_0000_0000_0000 } @inlinable @inline(__always) internal static var isNativelyStoredMask: UInt64 { return 0x2000_0000_0000_0000 } @inlinable @inline(__always) internal static var isTailAllocatedMask: UInt64 { return 0x1000_0000_0000_0000 } // General purpose bottom initializer @inlinable @inline(__always) internal init( count: Int, isASCII: Bool, isNFC: Bool, isNativelyStored: Bool, isTailAllocated: Bool ) { var rawBits = UInt64(truncatingIfNeeded: count) _internalInvariant(rawBits <= _StringObject.CountAndFlags.countMask) if isASCII { _internalInvariant(isNFC) rawBits |= _StringObject.CountAndFlags.isASCIIMask } if isNFC { rawBits |= _StringObject.CountAndFlags.isNFCMask } if isNativelyStored { _internalInvariant(isTailAllocated) rawBits |= _StringObject.CountAndFlags.isNativelyStoredMask } if isTailAllocated { rawBits |= _StringObject.CountAndFlags.isTailAllocatedMask } self.init(raw: rawBits) _internalInvariant(count == self.count) _internalInvariant(isASCII == self.isASCII) _internalInvariant(isNFC == self.isNFC) _internalInvariant(isNativelyStored == self.isNativelyStored) _internalInvariant(isTailAllocated == self.isTailAllocated) } @inlinable @inline(__always) internal init(count: Int, flags: UInt16) { // Currently, we only use top 4 flags _internalInvariant(flags & 0xF000 == flags) let rawBits = UInt64(truncatingIfNeeded: flags) &<< 48 | UInt64(truncatingIfNeeded: count) self.init(raw: rawBits) _internalInvariant(self.count == count && self.flags == flags) } // // Specialized initializers // @inlinable @inline(__always) internal init(immortalCount: Int, isASCII: Bool) { self.init( count: immortalCount, isASCII: isASCII, isNFC: isASCII, isNativelyStored: false, isTailAllocated: true) } @inline(__always) internal init(mortalCount: Int, isASCII: Bool) { self.init( count: mortalCount, isASCII: isASCII, isNFC: isASCII, isNativelyStored: true, isTailAllocated: true) } @inline(__always) internal init(sharedCount: Int, isASCII: Bool) { self.init( count: sharedCount, isASCII: isASCII, isNFC: isASCII, isNativelyStored: false, isTailAllocated: false) } // // Queries and accessors // @inlinable @inline(__always) internal var count: Int { return Int( truncatingIfNeeded: _storage & _StringObject.CountAndFlags.countMask) } @inlinable @inline(__always) internal var flags: UInt16 { return UInt16(truncatingIfNeeded: _storage &>> 48) } @inlinable @inline(__always) internal var isASCII: Bool { return 0 != _storage & _StringObject.CountAndFlags.isASCIIMask } @inlinable @inline(__always) internal var isNFC: Bool { return 0 != _storage & _StringObject.CountAndFlags.isNFCMask } @inlinable @inline(__always) internal var isNativelyStored: Bool { return 0 != _storage & _StringObject.CountAndFlags.isNativelyStoredMask } @inlinable @inline(__always) internal var isTailAllocated: Bool { return 0 != _storage & _StringObject.CountAndFlags.isTailAllocatedMask } #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { if isASCII { _internalInvariant(isNFC) } if isNativelyStored { _internalInvariant(isTailAllocated) } } #endif // INTERNAL_CHECKS_ENABLED } // Extract extension _StringObject { @inlinable @inline(__always) internal var largeCount: Int { _internalInvariant(isLarge) return _countAndFlags.count } @inlinable @inline(__always) internal var largeAddressBits: UInt { _internalInvariant(isLarge) return UInt(truncatingIfNeeded: discriminatedObjectRawBits & Nibbles.largeAddressMask) } @inlinable @inline(__always) internal var nativeUTF8Start: UnsafePointer<UInt8> { _internalInvariant(largeFastIsTailAllocated) return UnsafePointer( bitPattern: largeAddressBits &+ _StringObject.nativeBias )._unsafelyUnwrappedUnchecked } @inlinable @inline(__always) internal var nativeUTF8: UnsafeBufferPointer<UInt8> { _internalInvariant(largeFastIsTailAllocated) return UnsafeBufferPointer(start: nativeUTF8Start, count: largeCount) } // Resilient way to fetch a pointer @usableFromInline @inline(never) @_effects(releasenone) internal func getSharedUTF8Start() -> UnsafePointer<UInt8> { _internalInvariant(largeFastIsShared) #if _runtime(_ObjC) if largeIsCocoa { return stableCocoaASCIIPointer(cocoaObject)._unsafelyUnwrappedUnchecked } #endif return sharedStorage.start } @usableFromInline internal var sharedUTF8: UnsafeBufferPointer<UInt8> { @_effects(releasenone) @inline(never) get { _internalInvariant(largeFastIsShared) let start = self.getSharedUTF8Start() return UnsafeBufferPointer(start: start, count: largeCount) } } @inline(__always) internal var nativeStorage: __StringStorage { #if arch(i386) || arch(arm) || arch(wasm32) guard case .native(let storage) = _variant else { _internalInvariantFailure() } return _unsafeUncheckedDowncast(storage, to: __StringStorage.self) #else _internalInvariant(hasNativeStorage) return Builtin.reinterpretCast(largeAddressBits) #endif } @inline(__always) internal var sharedStorage: __SharedStringStorage { #if arch(i386) || arch(arm) || arch(wasm32) guard case .native(let storage) = _variant else { _internalInvariantFailure() } return _unsafeUncheckedDowncast(storage, to: __SharedStringStorage.self) #else _internalInvariant(largeFastIsShared && !largeIsCocoa) _internalInvariant(hasSharedStorage) return Builtin.reinterpretCast(largeAddressBits) #endif } @inline(__always) internal var cocoaObject: AnyObject { #if arch(i386) || arch(arm) || arch(wasm32) guard case .bridged(let object) = _variant else { _internalInvariantFailure() } return object #else _internalInvariant(largeIsCocoa && !isImmortal) return Builtin.reinterpretCast(largeAddressBits) #endif } @_alwaysEmitIntoClient @inlinable @inline(__always) internal var owner: AnyObject? { guard self.isMortal else { return nil } return Builtin.reinterpretCast(largeAddressBits) } } // Aggregate queries / abstractions extension _StringObject { // The number of code units stored // // TODO(String micro-performance): Check generated code @inlinable @inline(__always) internal var count: Int { return isSmall ? smallCount : largeCount } // // Whether the string is all ASCII // @inlinable @inline(__always) internal var isASCII: Bool { if isSmall { return smallIsASCII } return _countAndFlags.isASCII } @inline(__always) internal var isNFC: Bool { if isSmall { // TODO(String performance): Worth implementing more sophisiticated // check, or else performing normalization on- construction. For now, // approximate it with isASCII return smallIsASCII } return _countAndFlags.isNFC } // Get access to fast UTF-8 contents for large strings which provide it. @inlinable @inline(__always) internal var fastUTF8: UnsafeBufferPointer<UInt8> { _internalInvariant(self.isLarge && self.providesFastUTF8) guard _fastPath(self.largeFastIsTailAllocated) else { return sharedUTF8 } return UnsafeBufferPointer( start: self.nativeUTF8Start, count: self.largeCount) } // Whether the object stored can be bridged directly as a NSString @usableFromInline // @opaque internal var hasObjCBridgeableObject: Bool { @_effects(releasenone) get { // Currently, all mortal objects can zero-cost bridge return !self.isImmortal } } // Fetch the stored subclass of NSString for bridging @inline(__always) internal var objCBridgeableObject: AnyObject { _internalInvariant(hasObjCBridgeableObject) return Builtin.reinterpretCast(largeAddressBits) } // Whether the object provides fast UTF-8 contents that are nul-terminated @inlinable internal var isFastZeroTerminated: Bool { if _slowPath(!providesFastUTF8) { return false } // Small strings nul-terminate when spilling for contiguous access if isSmall { return true } // TODO(String performance): Use performance flag, which could be more // inclusive. For now, we only know native strings and small strings (when // accessed) are. We could also know about some shared strings. return largeFastIsTailAllocated } } // Object creation extension _StringObject { @inlinable @inline(__always) internal init(immortal bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) { let countAndFlags = CountAndFlags( immortalCount: bufPtr.count, isASCII: isASCII) #if arch(i386) || arch(arm) || arch(wasm32) self.init( variant: .immortal(start: bufPtr.baseAddress._unsafelyUnwrappedUnchecked), discriminator: Nibbles.largeImmortal(), countAndFlags: countAndFlags) #else // We bias to align code paths for mortal and immortal strings let biasedAddress = UInt( bitPattern: bufPtr.baseAddress._unsafelyUnwrappedUnchecked ) &- _StringObject.nativeBias self.init( pointerBits: UInt64(truncatingIfNeeded: biasedAddress), discriminator: Nibbles.largeImmortal(), countAndFlags: countAndFlags) #endif } @inline(__always) internal init(_ storage: __StringStorage) { #if arch(i386) || arch(arm) || arch(wasm32) self.init( variant: .native(storage), discriminator: Nibbles.largeMortal(), countAndFlags: storage._countAndFlags) #else self.init( object: storage, discriminator: Nibbles.largeMortal(), countAndFlags: storage._countAndFlags) #endif } internal init(_ storage: __SharedStringStorage) { #if arch(i386) || arch(arm) || arch(wasm32) self.init( variant: .native(storage), discriminator: Nibbles.largeMortal(), countAndFlags: storage._countAndFlags) #else self.init( object: storage, discriminator: Nibbles.largeMortal(), countAndFlags: storage._countAndFlags) #endif } internal init( cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int ) { let countAndFlags = CountAndFlags(sharedCount: length, isASCII: isASCII) let discriminator = Nibbles.largeCocoa(providesFastUTF8: providesFastUTF8) #if arch(i386) || arch(arm) || arch(wasm32) self.init( variant: .bridged(cocoa), discriminator: discriminator, countAndFlags: countAndFlags) #else self.init( object: cocoa, discriminator: discriminator, countAndFlags: countAndFlags) _internalInvariant(self.largeAddressBits == Builtin.reinterpretCast(cocoa)) _internalInvariant(self.providesFastUTF8 == providesFastUTF8) _internalInvariant(self.largeCount == length) #endif } } // Internal invariants extension _StringObject { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { #if arch(i386) || arch(arm) || arch(wasm32) _internalInvariant(MemoryLayout<_StringObject>.size == 12) _internalInvariant(MemoryLayout<_StringObject>.stride == 12) _internalInvariant(MemoryLayout<_StringObject>.alignment == 4) _internalInvariant(MemoryLayout<_StringObject?>.size == 12) _internalInvariant(MemoryLayout<_StringObject?>.stride == 12) _internalInvariant(MemoryLayout<_StringObject?>.alignment == 4) // Non-small-string discriminators are 4 high bits only. Small strings use // the next 4 for count. if isSmall { _internalInvariant(_discriminator & 0xA0 == 0xA0) } else { _internalInvariant(_discriminator & 0x0F == 0) } #else _internalInvariant(MemoryLayout<_StringObject>.size == 16) _internalInvariant(MemoryLayout<_StringObject?>.size == 16) #endif if isForeign { _internalInvariant(largeIsCocoa, "No other foreign forms yet") } if isSmall { _internalInvariant(isImmortal) _internalInvariant(smallCount <= 15) _internalInvariant(smallCount == count) _internalInvariant(!hasObjCBridgeableObject) } else { _internalInvariant(isLarge) _internalInvariant(largeCount == count) if _countAndFlags.isTailAllocated { _internalInvariant(providesFastUTF8) } if providesFastUTF8 && largeFastIsTailAllocated { _internalInvariant(!isSmall) _internalInvariant(!largeIsCocoa) _internalInvariant(_countAndFlags.isTailAllocated) if isImmortal { _internalInvariant(!hasNativeStorage) _internalInvariant(!hasObjCBridgeableObject) _internalInvariant(!_countAndFlags.isNativelyStored) } else { _internalInvariant(hasNativeStorage) _internalInvariant(_countAndFlags.isNativelyStored) _internalInvariant(hasObjCBridgeableObject) _internalInvariant(nativeStorage.count == self.count) } } if largeIsCocoa { _internalInvariant(hasObjCBridgeableObject) _internalInvariant(!isSmall) _internalInvariant(!_countAndFlags.isNativelyStored) _internalInvariant(!_countAndFlags.isTailAllocated) if isForeign { } else { _internalInvariant(largeFastIsShared) } } if _countAndFlags.isNativelyStored { let anyObj = Builtin.reinterpretCast(largeAddressBits) as AnyObject _internalInvariant(anyObj is __StringStorage) } } #if arch(i386) || arch(arm) || arch(wasm32) switch _variant { case .immortal: _internalInvariant(isImmortal) case .native: _internalInvariant(hasNativeStorage || hasSharedStorage) case .bridged: _internalInvariant(isLarge) _internalInvariant(largeIsCocoa) } #endif } #endif // INTERNAL_CHECKS_ENABLED @inline(never) internal func _dump() { #if INTERNAL_CHECKS_ENABLED let raw = self.rawBits let word0 = ("0000000000000000" + String(raw.0, radix: 16)).suffix(16) let word1 = ("0000000000000000" + String(raw.1, radix: 16)).suffix(16) #if arch(i386) || arch(arm) || arch(wasm32) print(""" StringObject(\ <\(word0) \(word1)> \ count: \(String(_count, radix: 16)), \ variant: \(_variant), \ discriminator: \(_discriminator), \ flags: \(_flags)) """) #else print("StringObject(<\(word0) \(word1)>)") #endif let repr = _StringGuts(self)._classify() switch repr._form { case ._small: _SmallString(self)._dump() case ._immortal(address: let address): print(""" Immortal(\ start: \(UnsafeRawPointer(bitPattern: address)!), \ count: \(repr._count)) """) case ._native(_): print(""" Native(\ owner: \(repr._objectIdentifier!), \ count: \(repr._count), \ capacity: \(repr._capacity)) """) case ._cocoa(object: let object): let address: UnsafeRawPointer = Builtin.reinterpretCast(object) print("Cocoa(address: \(address))") } #endif // INTERNAL_CHECKS_ENABLED } }
apache-2.0
be009c62dd1e38175c7c4813752f8303
32.018341
80
0.669418
4.066036
false
false
false
false
congncif/SiFUtilities
Foundation/Data/DataConvert.swift
1
1418
// // DataConvert.swift // // // Created by NGUYEN CHI CONG on 12/18/20. // import Foundation extension String { public func data() -> Data? { data(using: .utf8) } public func jsonDictionary(encoding: String.Encoding = .utf8) -> [String: Any]? { data(using: encoding)?.jsonDictionary() } public func jsonArray(encoding: String.Encoding = .utf8) -> [Any]? { data(using: encoding)?.jsonArray() } } extension Data { public func string(encoding: String.Encoding = .utf8) -> String? { String(data: self, encoding: encoding) } public func jsonDictionary() -> [String: Any]? { try? JSONSerialization.jsonObject(with: self, options: []) as? [String: Any] } public func jsonArray() -> [Any]? { try? JSONSerialization.jsonObject(with: self, options: []) as? [Any] } } extension Array { public func jsonData() throws -> Data { try JSONSerialization.data(withJSONObject: self, options: []) } public func jsonString(encoding: String.Encoding = .utf8) -> String? { try? jsonData().string(encoding: encoding) } } extension Dictionary { public func jsonData() throws -> Data { try JSONSerialization.data(withJSONObject: self, options: []) } public func jsonString(encoding: String.Encoding = .utf8) -> String? { try? jsonData().string(encoding: encoding) } }
mit
8220ea6b1b98eeb38a8d6a64e3c2e46b
24.321429
85
0.621298
3.960894
false
false
false
false
exyte/Macaw
Source/MCAMediaTimingFunctionName_macOS.swift
1
565
// // MCAMediaTimingFunctionName_macOS.swift // MacawOSX // // Created by Anton Marunko on 27/09/2018. // Copyright © 2018 Exyte. All rights reserved. // import Foundation #if os(OSX) import AppKit public struct MCAMediaTimingFunctionName { static let linear = CAMediaTimingFunctionName.default static let easeIn = CAMediaTimingFunctionName.easeIn static let easeOut = CAMediaTimingFunctionName.easeOut static let easeInEaseOut = CAMediaTimingFunctionName.easeInEaseOut static let `default` = CAMediaTimingFunctionName.default } #endif
mit
397f40c12cc1f2d32961d55fcd3aef41
24.636364
70
0.774823
4.7
false
false
false
false
blinker13/Canvas
Sources/Text/Text+Nesting.swift
2
763
public extension Text { // // init(attributes:Attributes, separator:String? = " ", _ texts:[Text]) { // // var string = "" // var runs = [Run]() // // for text in texts { // // if let separation = separator && !separation.isEmpty && !string.isEmpty { // let location = string.characters.count // let length = separation.characters.count // let range = Range(location:location, length:length) // let run = Run(attributes: attributes, range:range) // string += separation // runs.append(run) // } // // // make union from attributes and text. // } // // self.init(string, runs:) // } // // init(attributes:Attributes, separator:String? = " ", _ texts:Text ...) { // self.init(attributes:attributes, separator:separator, texts) // } }
mit
d165f350e3f0dc975659ee305f7be02c
25.310345
78
0.623853
3.076613
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitInterApp/TKInterAppCommunicator+TurnByTurn.swift
1
9400
// // TKInterAppCommunicator+TurnByTurn.swift // TripKitInterApp-iOS // // Created by Adrian Schönig on 05.04.18. // Copyright © 2018 SkedGo. All rights reserved. // import UIKit import TripKit import MapKit extension TKInterAppCommunicator { @objc(canOpenInMapsApp:) public static func canOpenInMapsApp(_ segment: TKSegment) -> Bool { return segment.turnByTurnMode != nil } } extension TKInterAppCommunicator { // MARK: - Device Capability static func deviceHasGoogleMaps() -> Bool { let testURL = URL(string: "comgooglemaps-x-callback://")! return UIApplication.shared.canOpenURL(testURL) } static func deviceHasWaze() -> Bool { let testURL = URL(string: "waze://")! return UIApplication.shared.canOpenURL(testURL) } // MARK: - Open Maps Apps From Trip Segment /// Opens the segment in a maps app. Either directly in Apple Maps if nothing else is installed, or it will /// prompt for using Google Maps or Waze. /// /// - warning: Checking for Google Maps and Waze only works the appropriate URL schemes are /// added to the `LSApplicationQueriesSchemes`of your app's `Info.plist`: /// /// ``` /// <key>LSApplicationQueriesSchemes</key> /// <array> /// <string>comgooglemaps-x-callback</string> /// <string>waze</string> /// ... /// </array> /// ``` /// /// - Parameter segment: A segment for which `canOpenInMapsApp` returns `true` /// - Parameter controller: A controller to present the optional action sheet on /// - Parameter sender: A controller to present the optional action sheet on /// - Parameter currentLocationHandler: Will be called to check if turn-by-turn navigation /// should start at the current location or at the segment's start location. If `nil` it will /// start at the current location. @objc(openSegmentInMapsApp:forViewController:initiatedBy:currentLocationHandler:) public static func openSegmentInMapsApp( _ segment: TKSegment, forViewController controller: UIViewController, initiatedBy sender: Any, currentLocationHandler: ((TKSegment) -> Bool)? ) { let hasGoogleMaps = deviceHasGoogleMaps() let hasWaze = deviceHasWaze() if !hasGoogleMaps && !hasWaze { // Confirm to open Apple Maps let alert = UIAlertController(title: Loc.GetDirections, message: Loc.ConfirmOpen(appName: Loc.AppleMaps), preferredStyle: .alert) alert.addAction(.init(title: Loc.Cancel, style: .cancel)) alert.addAction(.init(title: Loc.Open(appName: Loc.AppleMaps), style: .default) { _ in openSegmentInAppleMaps(segment, currentLocationHandler: currentLocationHandler) }) controller.present(alert, animated: true) } else { let actions = UIAlertController(title: Loc.GetDirections, message: nil, preferredStyle: .actionSheet) actions.addAction(.init(title: Loc.AppleMaps, style: .default) { _ in openSegmentInAppleMaps(segment, currentLocationHandler: currentLocationHandler) }) // Google Maps if (hasGoogleMaps) { actions.addAction(.init(title: Loc.GoogleMaps, style: .default) { _ in openSegmentInGoogleMaps(segment, currentLocationHandler: currentLocationHandler) }) } // Waze if (hasWaze) { actions.addAction(.init(title: "Waze", style: .default) { _ in openSegmentInWaze(segment) }) } actions.addAction(.init(title: Loc.Cancel, style: .cancel)) controller.present(actions, animated: true) } } private static func openSegmentInAppleMaps(_ segment: TKSegment, currentLocationHandler: ((TKSegment) -> Bool)?) { guard let mode = segment.turnByTurnMode, let destination = segment.end else { assertionFailure("Turn by turn navigation does not apply to this segment OR segment does not have a destination") return } var origin: MKAnnotation? if currentLocationHandler?(segment) == false { origin = segment.start } openAppleMaps(in: mode, routeFrom: origin, to: destination) } private static func openSegmentInGoogleMaps(_ segment: TKSegment, currentLocationHandler: ((TKSegment) -> Bool)?) { guard let mode = segment.turnByTurnMode, let destination = segment.end else { assertionFailure("Turn by turn navigation does not apply to this segment OR segment does not have a destination") return } var origin: MKAnnotation? if currentLocationHandler?(segment) == false { origin = segment.start } openGoogleMaps(in: mode, routeFrom: origin, to: destination) } private static func openSegmentInWaze(_ segment: TKSegment) { guard let destination = segment.end, let mode = segment.turnByTurnMode, mode == .driving else { assertionFailure("Trying to open Waze without a destination OR the segment isn't a driving.") return } openWaze(routeTo: destination) } // MARK: - Open Maps Apps public static func openMapsApp( in mode: TKTurnByTurnMode, routeFrom origin: MKAnnotation?, to destination: MKAnnotation, viewController controller: UIViewController, initiatedBy sender: Any? ) { let hasGoogleMaps = deviceHasGoogleMaps() let hasWaze = deviceHasWaze() if !hasGoogleMaps && !hasWaze { // Confirm to open Apple Maps let alert = UIAlertController(title: Loc.GetDirections, message: Loc.ConfirmOpen(appName: Loc.AppleMaps), preferredStyle: .alert) alert.addAction(.init(title: Loc.Cancel, style: .cancel)) alert.addAction(.init(title: Loc.Open(appName: Loc.AppleMaps), style: .default) { _ in openAppleMaps(in: mode, routeFrom: origin, to: destination) }) controller.present(alert, animated: true) } else { let actions = UIAlertController(title: Loc.GetDirections, message: nil, preferredStyle: .actionSheet) actions.addAction(.init(title: Loc.AppleMaps, style: .default) { _ in openAppleMaps(in: mode, routeFrom: origin, to: destination) }) // Google Maps if (hasGoogleMaps) { actions.addAction(.init(title: Loc.GoogleMaps, style: .default) { _ in openGoogleMaps(in: mode, routeFrom: origin, to: destination) }) } // Waze if (hasWaze) { actions.addAction(.init(title: "Waze", style: .default) { _ in assert(mode == .driving, "Waze only supports driving turn by turn mode") openWaze(routeTo: destination) }) } actions.addAction(.init(title: Loc.Cancel, style: .cancel)) controller.present(actions, animated: true) } } private static func openAppleMaps(in mode: TKTurnByTurnMode, routeFrom origin: MKAnnotation?, to destination: MKAnnotation) { let originMapItem: MKMapItem if let unwrapped = origin { let originPlacemark = MKPlacemark(coordinate: unwrapped.coordinate, addressDictionary: nil) originMapItem = MKMapItem(placemark: originPlacemark) originMapItem.name = unwrapped.title ?? "" } else { originMapItem = MKMapItem.forCurrentLocation() } let destinationPlacemark = MKPlacemark(coordinate: destination.coordinate, addressDictionary: nil) let destinationMapItem = MKMapItem(placemark: destinationPlacemark) destinationMapItem.name = destination.title ?? "" let directionMode: String switch mode { case .walking: directionMode = MKLaunchOptionsDirectionsModeWalking case .driving: directionMode = MKLaunchOptionsDirectionsModeDriving default: directionMode = MKLaunchOptionsDirectionsModeDefault } let options = [MKLaunchOptionsDirectionsModeKey: directionMode] MKMapItem.openMaps(with: [originMapItem, destinationMapItem], launchOptions: options ) } private static func openGoogleMaps(in mode: TKTurnByTurnMode, routeFrom origin: MKAnnotation?, to destination: MKAnnotation) { // https://developers.google.com/maps/documentation/ios/urlscheme var request = "comgooglemaps-x-callback://?" // Origin is optional if let unwrapped = origin { request.append(String(format: "saddr=%.5f,%.5f&", unwrapped.coordinate.latitude, unwrapped.coordinate.longitude)) } request.append(String(format: "daddr=%.5f,%.5f&", destination.coordinate.latitude, destination.coordinate.longitude)) switch mode { case .walking: request.append("directionsmode=walking") case .driving: request.append("directionsmode=driving") case .cycling: request.append("directionsmode=bicycling") } if let callback = TKConfig.shared.googleMapsCallback { request.append(String(format: "x-success=%@", callback)) } guard let requestURL = URL(string: request) else { assertionFailure(); return } UIApplication.shared.open(requestURL) } private static func openWaze(routeTo destination: MKAnnotation) { // https://www.waze.com/about/dev let request = String(format: "waze://?ll=%f,%f&navigate=yes", destination.coordinate.latitude, destination.coordinate.longitude) if let url = URL(string: request) { UIApplication.shared.open(url) } } }
apache-2.0
6235ab543a8d7e265c9c900a4108b636
34.330827
135
0.673228
4.348913
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Rank/RankSongViewController.swift
1
4330
// // RankSongViewController.swift // MusicApp // // Created by Hưng Đỗ on 6/30/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import RxSwift import RxCocoa import Action import RxDataSources import NSObject_Rx class RankSongViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var headerView: RankHeaderView! fileprivate var initialIndicatorView = InitialActivityIndicatorView() private let headerCell = UITableViewCell(style: .default, reuseIdentifier: "HeaderCell") var store: RankSongStore! var action: RankSongAction! // MARK: Properties var country: String! // MARK: Life Cycles override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = [] tableView.delegate = self headerView.configure(country: country, type: kRankTypeSong) headerView.configureAnimation(with: tableView) bindStore() bindAction() } private var headerViewNeedsToUpdate = true override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() if headerViewNeedsToUpdate { headerView.frame.size.height = tableView.bounds.size.height / 4 headerViewNeedsToUpdate = false } } // MARK: Target Actions @IBAction func backButtonTapped(_ backButton: UIButton) { navigationController?.popViewController(animated: true) } // MARK: Data Sources fileprivate lazy var dataSource: RxTableViewSectionedReloadDataSource<SectionModel<String, Track>> = { let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Track>>() dataSource.configureCell = { dataSource, tableView, indexPath, track in if indexPath.section == 0 { return self.headerCell } let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: RankSongCell.self), for: indexPath) if let cell = cell as? RankSongCell { let contextAction = CocoaAction { [weak self] _ in guard let this = self else { return .empty() } return this.action.onContextButtonTap.execute((track.song, this)).map { _ in } } cell.configure(name: track.name, singer: track.singer, contextAction: contextAction) cell.rank = indexPath.row + 1 } return cell } return dataSource }() } extension RankSongViewController: UITableViewDelegate { private var headerHeight: CGFloat { return tableView.bounds.height / 4 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return headerHeight } return 44 } } extension RankSongViewController { func bindStore() { store.tracks.asObservable() .filter { $0.count > 0 } .do(onNext: { [weak self] _ in self?.initialIndicatorView.stopAnimating() }) .map { tracks in [ SectionModel(model: "Header", items: [ Track(id: "header", name: "Header", singer: "header", avatar: "not_found", lyric: "not_found", url: "not_found") ]), SectionModel(model: "Tracks", items: tracks) ]} .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(rx_disposeBag) store.tracks.asObservable() .filter { $0.count == 0 } .subscribe(onNext: { [weak self] _ in self?.initialIndicatorView.startAnimating(in: self?.view) }) .addDisposableTo(rx_disposeBag) } } extension RankSongViewController { func bindAction() { action.onLoad.execute(country) headerView.action = action.onPlayButtonPress() tableView.rx.modelSelected(Track.self) .subscribe(action.onTrackDidSelect.inputs) .addDisposableTo(rx_disposeBag) } }
mit
eb2e0f3d15ae2230574a7e90928e0399
29.034722
132
0.600231
5.192077
false
false
false
false
Davidde94/StemCode_iOS
StemCode/StemCode/Code/Window/File Editor/FileStrategyStem.swift
1
1029
// // FileStrategyStem.swift // StemCode // // Created by David Evans on 14/07/2018. // Copyright © 2018 BlackPoint LTD. All rights reserved. // import UIKit import StemProjectKit class FileStrategyStem: UIView, FileStrategy { @IBOutlet var iconImageView: UIImageView! @IBOutlet var nameTextField: UITextField! var file: StemFile! var project: Stem? func openFile(_ file: StemFile) { self.file = file loadProject() loadDetails() } func save() { } // MARK: - func loadProject() { do { let data = try Data(contentsOf: URL(fileURLWithPath: file.absolutePath)) project = try JSONDecoder().decode(Stem.self, from: data) } catch { } } func loadDetails() { iconImageView.image = project?.image nameTextField.text = project?.name } @IBAction func changeIcon(gesture: UITapGestureRecognizer) { } }
mit
34f1c613a263278202a349d992f6ba9a
18.769231
84
0.571012
4.528634
false
false
false
false
xedin/swift
test/NameBinding/scope_map_top_level.swift
1
3916
// Note: test of the scope map. All of these tests are line- and // column-sensitive, so any additions should go at the end. struct S0 { } let a: Int? = 1 guard let b = a else { } func foo() {} // to interrupt the TopLevelCodeDecl let c = b typealias T = Int extension Int { func my_identity() -> Int { return self } } var i: Int = b.my_identity() // RUN: %target-swift-frontend -dump-scope-maps expanded %s 2> %t.expanded // RUN: %FileCheck -check-prefix CHECK-EXPANDED %s < %t.expanded // CHECK-EXPANDED: ***Complete scope map*** // CHECK-EXPANDED-NEXT: ASTSourceFileScope {{.*}}, [1:1 - 65:1] 'SOURCE_DIR{{[/\\]}}test{{[/\\]}}NameBinding{{[/\\]}}scope_map_top_level.swift' // CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [4:1 - 4:13] 'S0' // CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [4:11 - 4:13] 'S0' // CHECK-EXPANDED-NEXT: `-TopLevelCodeScope {{.*}}, [6:1 - 21:28] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [6:1 - 21:28] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [6:5 - 21:28] entry 0 'a' // CHECK-EXPANDED-NEXT: |-PatternEntryInitializerScope {{.*}}, [6:15 - 6:15] entry 0 'a' // CHECK-EXPANDED-NEXT: `-PatternEntryUseScope {{.*}}, [6:15 - 21:28] entry 0 'a' // CHECK-EXPANDED-NEXT: `-TopLevelCodeScope {{.*}}, [8:1 - 21:28] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [8:1 - 21:28] // CHECK-EXPANDED-NEXT: `-GuardStmtScope {{.*}}, [8:1 - 21:28] // CHECK-EXPANDED-NEXT: |-ConditionalClauseScope, [8:7 - 8:22] index 0 // CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [8:22 - 8:22] let b? // CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [8:22 - 9:1] // CHECK-EXPANDED-NEXT: `-GuardStmtUseScope, [9:1 - 21:28] // CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [11:1 - 11:13] 'foo()' // CHECK-EXPANDED-NEXT: `-AbstractFunctionParamsScope {{.*}}, [11:9 - 11:13] // CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [11:12 - 11:13] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [11:12 - 11:13] // CHECK-EXPANDED-NEXT: `-TopLevelCodeScope {{.*}}, [13:1 - 21:28] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [13:1 - 21:28] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [13:5 - 21:28] entry 0 'c' // CHECK-EXPANDED-NEXT: |-PatternEntryInitializerScope {{.*}}, [13:9 - 13:9] entry 0 'c' // CHECK-EXPANDED-NEXT: `-PatternEntryUseScope {{.*}}, [13:9 - 21:28] entry 0 'c' // CHECK-EXPANDED-NEXT: |-TypeAliasDeclScope {{.*}}, [15:1 - 15:15] <no extended nominal?!> // CHECK-EXPANDED-NEXT: |-ExtensionDeclScope {{.*}}, [17:1 - 19:1] 'Int' // CHECK-EXPANDED-NEXT: `-ExtensionBodyScope {{.*}}, [17:15 - 19:1] 'Int' // CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [18:3 - 18:43] 'my_identity()' // CHECK-EXPANDED-NEXT: `-AbstractFunctionParamsScope {{.*}}, [18:19 - 18:43] // CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [18:29 - 18:43] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [18:29 - 18:43] // CHECK-EXPANDED-NEXT: `-TopLevelCodeScope {{.*}}, [21:1 - 21:28] // CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [21:1 - 21:28] // CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [21:5 - 21:28] entry 0 'i' // CHECK-EXPANDED-NEXT: |-PatternEntryInitializerScope {{.*}}, [21:14 - 21:28] entry 0 'i' // CHECK-EXPANDED-NEXT: `-PatternEntryUseScope {{.*}}, [21:28 - 21:28] entry 0 'i'
apache-2.0
c63695f46f5d1469afff2833179135bd
60.1875
143
0.53141
3.701323
false
false
false
false
eCrowdMedia/MooApi
Sources/Response/TagResponse.swift
1
3234
import Foundation public struct TagResponse: Codable { public let meta : Meta? public let links : Links? public let data : [Data] public let included: [Included]? } // MARK: - Meta extension TagResponse { public struct Meta: Codable { public struct Page: Codable { public let count : Int public let offset: Int } public let total_count: Int public let sort : String? public let page : Page? } } // MARK: - Links extension TagResponse { public struct Links: Codable { public let first : String? public let prev : String? public let selfLink: String public let next : String? public let last : String? enum CodingKeys: String, CodingKey { case first = "first" case prev = "prev" case selfLink = "self" case next = "next" case last = "last" } } } // MARK: - Data extension TagResponse { public struct Data: Codable { public struct Attributes: Codable { public let name : String public let count: Int } public struct Relationships: Codable { public struct LibraryBooks: Codable { public struct Data: Codable { public let type: String public let id : String } public struct Links: Codable { public let selfLink: String? public let related : String public enum CodingKeys: String, CodingKey { case selfLink = "self" case related = "related" } } public let data : [Data]? public let meta : Meta? public let links: Links? } public let libraryBooks: LibraryBooks? public enum CodingKeys: String, CodingKey { case libraryBooks = "library_books" } } public let type : String public let id : String public let attributes : Attributes public let relationships: Relationships } } // MARK: - Included extension TagResponse { public struct Included: Codable { public struct Attributes: Codable { public struct Cover: Codable { public let small: String } public let cover: Cover } public struct Links: Codable { public let selfLink: String public let related : String? public enum CodingKeys: String, CodingKey { case selfLink = "self" case related = "related" } } public let type : String? public let id : String? public let attributes: Attributes? public let links : Links? } } // Get Parameters extension TagResponse { static func getParams() -> [String : String] { let fieldsParamKey = "fields[books]" let libraryBooksParamKey = TagResponse.Data.Relationships.CodingKeys.libraryBooks.stringValue let pageParamKey = "page[\(libraryBooksParamKey)][count]" return [ fieldsParamKey : "cover", pageParamKey : "6" ] } }
mit
426a883c5e58cc8b546e50a04c9e1e2c
19.730769
97
0.55504
4.769912
false
false
false
false
barrymcandrews/aurora-ios
Aurora/ContextManager.swift
1
1069
// // ContextManager.swift // Aurora // // Created by Barry McAndrews on 5/21/17. // Copyright © 2017 Barry McAndrews. All rights reserved. // import UIKit public class ContextManager: NSObject { static var context: [String: Any] { get { let context = [ "hostname": Request.hostname!, "port": Request.port!, "requests": NSKeyedArchiver.archivedData(withRootObject: RequestContainer.shared.requests) ] as [String : Any] print(context) return context } set { if let hostname = newValue["hostname"] as? String { Request.hostname = hostname } if let port = newValue["port"] as? String { Request.port = port } if let requests = newValue["requests"] as? Data { RequestContainer.shared.requests = NSKeyedUnarchiver.unarchiveObject(with: requests) as! [Request] } } } }
bsd-2-clause
799dd6040a1efe103bbbbec39c4b0f2a
26.384615
114
0.523408
4.876712
false
false
false
false
davidhariri/done
Done/RootViewController.swift
1
3200
// // ViewController.swift // Done // // Created by David Hariri on 2017-03-08. // Copyright © 2017 David Hariri. All rights reserved. // /* RootViewController handles: - Scrolling through TodoLists - Mounting the TodoListProvider - Mounting TodoListViewControllers with their TodoLists - Creating the placeholder "New" TodoListView - Basic styling of the base of the app */ import UIKit class ViewController: UIViewController, UIScrollViewDelegate { let provider = TodoListProvider() var todoListsScrollView = UIScrollView() var SCREEN = CGSize() override func viewDidLoad() { super.viewDidLoad() SCREEN = view.frame.size view.backgroundColor = .black setUpTodoListsScrollView() } func setUpTodoListsScrollView() { todoListsScrollView = UIScrollView( frame: CGRect( x: 0, y: 0, width: SCREEN.width, height: SCREEN.height ) ) todoListsScrollView.backgroundColor = .clear todoListsScrollView.isPagingEnabled = true todoListsScrollView.bounces = true todoListsScrollView.alwaysBounceHorizontal = true todoListsScrollView.delegate = self view.addSubview(todoListsScrollView) drawTodoLists() } func makeTodoListView(withXCoord x: CGFloat) -> TodoListView { let todoView = TodoListView( frame: CGRect( x: x, y: 0, width: SCREEN.width, height: SCREEN.height ) ) return todoView } func drawTodoLists() { // Draw all the built todo lists for (index, _) in provider.todoLists.enumerated() { let todoViewXCoord = (CGFloat(index) * SCREEN.width) let todoView = makeTodoListView(withXCoord: todoViewXCoord) todoListsScrollView.addSubview(todoView) } // Draw the placeholder new todolist let placeHolderView = makeTodoListView( withXCoord: CGFloat(provider.todoLists.count) * SCREEN.width) todoListsScrollView.addSubview(placeHolderView) todoListsScrollView.contentSize = CGSize( width: (CGFloat(provider.todoLists.count + 1) * SCREEN.width), height: SCREEN.height ) } // When todoListsScrollView overscrolls past 64 points we // should add another todoList func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let bottomEdge = scrollView.contentOffset.x + scrollView.frame.size.width if (bottomEdge >= scrollView.contentSize.width) && (provider.todoLists[provider.todoLists.count-1].name != nil) { provider.add() drawTodoLists() } } // When the scrollview is swiped we should dismiss any keyboards func scrollViewDidScroll(_ scrollView: UIScrollView) { view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
dd0cc596fbe457a7183f3aaa1bd27e48
27.5625
81
0.60769
5.077778
false
false
false
false
icanzilb/EventBlankApp
EventBlank/EventBlank/Shared.swift
2
409
// // Shared.swift // EventBlank // // Created by Marin Todorov on 9/23/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit let shortStyleDateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeStyle = .ShortStyle formatter.dateFormat = .None return formatter }()
mit
9f888722ad6241ff834886de7a56d4eb
21.722222
64
0.696822
4.049505
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Library/MonkeyKing/AnyActivity.swift
2
1242
// // AnyActivity.swift // MonkeyKing // // Created by NIX on 15/9/11. // Copyright © 2015年 nixWork. All rights reserved. // import UIKit public class AnyActivity: UIActivity { let type: String let title: String let image: UIImage let message: MonkeyKing.Message let finish: MonkeyKing.Finish public init(type: String, title: String, image: UIImage, message: MonkeyKing.Message, finish: MonkeyKing.Finish) { self.type = type self.title = title self.image = image self.message = message self.finish = finish super.init() } override public class func activityCategory() -> UIActivityCategory { return .Share } override public func activityType() -> String? { return type } override public func activityTitle() -> String? { return title } override public func activityImage() -> UIImage? { return image } override public func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool { return message.canBeDelivered } override public func performActivity() { MonkeyKing.shareMessage(message, finish: finish) activityDidFinish(true) } }
apache-2.0
cd4477672b1c113659cf1dded06007d3
20.736842
118
0.642454
4.605948
false
false
false
false
knchst0704/Walhalla
Pod/Classes/Walhalla.swift
1
12861
// // Walhalla.swift // Walhalla // // Created by Kenichi Saito on 2/5/15. // Copyright (c) 2015 Kenichi Saito. All rights reserved. // import UIKit public class Walhalla { public enum AnimationType { case BounceLeft case BounceRight case BounceUp case BounceDown case FadeIn case FadeOut case ZoomIn case ZoomOut case Pop case Stretch case Shake } public static func performAnimation(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval, type: AnimationType) { switch type { case .BounceLeft: bounceLeft(view, duration: duration, delay: delay) case .BounceRight: bounceRight(view, duration: duration, delay: delay) case .BounceUp: bounceUp(view, duration: duration, delay: delay) case .BounceDown: bounceDown(view, duration: duration, delay: delay) case .FadeIn: fadeIn(view, duration: duration, delay: delay) case .FadeOut: fadeOut(view, duration: duration, delay: delay) case .ZoomIn: zoomIn(view, duration: duration, delay: delay) case .ZoomOut: zoomOut(view, duration: duration, delay: delay) case .Pop: pop(view, duration: duration, delay: delay) case .Stretch: stretch(view, duration: duration, delay: delay) case .Shake: shake(view, duration: duration, delay: delay) } } } public extension Walhalla { private static func bounceLeft(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeTranslation(CGRectGetWidth(UIScreen.mainScreen().bounds), 0) UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(-10, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(5, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(-2, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, 0) }, completion: {(finished: Bool) in }) }) }) }) } private static func bounceRight(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeTranslation(-CGRectGetWidth(UIScreen.mainScreen().bounds), 0) UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(10, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(-5, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(2, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, 0) }, completion: {(finished: Bool) in }) }) }) }) } private static func bounceUp(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeTranslation(0, CGRectGetWidth(UIScreen.mainScreen().bounds)) UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, 10) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, -5) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, 2) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, 0) }, completion: {(finished: Bool) in }) }) }) }) } private static func bounceDown(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeTranslation(0, -CGRectGetWidth(UIScreen.mainScreen().bounds)) UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, -10) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, 5) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, -2) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, 0) }, completion: {(finished: Bool) in }) }) }) }) } private static func fadeIn(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.alpha = 0 UIView.animateKeyframesWithDuration(duration, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.alpha = 1 }, completion: {(finished: Bool) in }) } private static func fadeOut(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.alpha = 1 UIView.animateKeyframesWithDuration(duration, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.alpha = 0 }, completion: {(finished: Bool) in }) } private static func zoomIn(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeScale(1, 1) view.alpha = 1 UIView.animateKeyframesWithDuration(duration, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(2, 2) view.alpha = 0 }, completion: {(finished: Bool) in }) } private static func zoomOut(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeScale(2, 2) view.alpha = 0 UIView.animateKeyframesWithDuration(duration, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(1, 1) view.alpha = 1 }, completion: {(finished: Bool) in }) } private static func pop(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeScale(1, 1) UIView.animateKeyframesWithDuration(duration/3, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(1.2, 1.2) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/3, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(0.9, 0.9) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/3, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(1, 1) }, completion: {(finished: Bool) in }) }) }) } private static func stretch(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeScale(1, 1) UIView.animateKeyframesWithDuration(duration/4, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(1, 1.2) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(1.2, 0.9) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(0.9, 0.9) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/4, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeScale(1, 1) }, completion: {(finished: Bool) in }) }) }) }) } private static func shake(view: UIView, duration: NSTimeInterval, delay: NSTimeInterval) { view.transform = CGAffineTransformMakeTranslation(0, 0) UIView.animateKeyframesWithDuration(duration/5, delay: delay, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(30, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(-30, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(15, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(-15, 0) }, completion: {(finished: Bool) in UIView.animateKeyframesWithDuration(duration/5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { view.transform = CGAffineTransformMakeTranslation(0, 0) }, completion: {(finished: Bool) in }) }) }) }) }) } }
mit
2a76d921c2a35085ab5eaec942a24390
57.199095
154
0.594277
5.965213
false
false
false
false
WhisperSystems/Signal-iOS
SignalMessaging/ViewControllers/Stickers/StickerPackViewController.swift
1
17481
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import SignalServiceKit import YYImage @objc public class StickerPackViewController: OWSViewController { // MARK: - Dependencies private var databaseStorage: SDSDatabaseStorage { return SDSDatabaseStorage.shared } // MARK: Properties private let stickerPackInfo: StickerPackInfo private let stickerCollectionView = StickerPackCollectionView() private let dataSource: StickerPackDataSource // MARK: Initializers @available(*, unavailable, message:"use other constructor instead.") required public init?(coder aDecoder: NSCoder) { notImplemented() } @objc public required init(stickerPackInfo: StickerPackInfo) { self.stickerPackInfo = stickerPackInfo self.dataSource = TransientStickerPackDataSource(stickerPackInfo: stickerPackInfo, shouldDownloadAllStickers: true) super.init(nibName: nil, bundle: nil) if #available(iOS 13, *) { // do nothing, use automatic style } else { modalPresentationStyle = .overFullScreen } stickerCollectionView.stickerDelegate = self stickerCollectionView.show(dataSource: dataSource) dataSource.add(delegate: self) NotificationCenter.default.addObserver(self, selector: #selector(callDidChange), name: .OWSWindowManagerCallDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(didChangeStatusBarFrame), name: UIApplication.didChangeStatusBarFrameNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(stickersOrPacksDidChange), name: StickerManager.stickersOrPacksDidChange, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - View Lifecycle override public func loadView() { super.loadView() if UIAccessibility.isReduceTransparencyEnabled { view.backgroundColor = Theme.darkThemeBackgroundColor } else { view.backgroundColor = UIColor(white: 0, alpha: 0.6) view.isOpaque = false let blurEffect = Theme.barBlurEffect let blurEffectView = UIVisualEffectView(effect: blurEffect) view.addSubview(blurEffectView) blurEffectView.autoPinEdgesToSuperviewEdges() } let hMargin: CGFloat = 16 dismissButton.setTemplateImageName("x-24", tintColor: Theme.darkThemePrimaryColor) dismissButton.addTarget(self, action: #selector(dismissButtonPressed(sender:)), for: .touchUpInside) dismissButton.contentEdgeInsets = UIEdgeInsets(top: 20, leading: hMargin, bottom: 20, trailing: hMargin) dismissButton.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: "dismissButton") coverView.autoSetDimensions(to: CGSize(width: 48, height: 48)) coverView.setCompressionResistanceHigh() coverView.setContentHuggingHigh() titleLabel.textColor = Theme.darkThemePrimaryColor titleLabel.font = UIFont.ows_dynamicTypeTitle1.ows_mediumWeight() authorLabel.textColor = Theme.darkThemePrimaryColor authorLabel.font = UIFont.ows_dynamicTypeBody defaultPackIconView.setTemplateImageName("check-circle-filled-16", tintColor: UIColor.ows_signalBrandBlue) defaultPackIconView.isHidden = true if FeatureFlags.stickerSharing { shareButton.setTemplateImageName("forward-outline-24", tintColor: Theme.darkThemePrimaryColor) shareButton.addTarget(self, action: #selector(shareButtonPressed(sender:)), for: .touchUpInside) shareButton.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: "shareButton") } view.addSubview(dismissButton) dismissButton.autoPinEdge(toSuperviewEdge: .leading) dismissButton.autoPin(toTopLayoutGuideOf: self, withInset: 0) let bottomRowView = UIStackView(arrangedSubviews: [ defaultPackIconView, authorLabel ]) bottomRowView.axis = .horizontal bottomRowView.alignment = .center bottomRowView.spacing = 5 defaultPackIconView.setCompressionResistanceHigh() defaultPackIconView.setContentHuggingHigh() let textRowsView = UIStackView(arrangedSubviews: [ titleLabel, bottomRowView ]) textRowsView.axis = .vertical textRowsView.alignment = .leading let headerStack = UIStackView(arrangedSubviews: [ coverView, textRowsView, shareButton ]) headerStack.axis = .horizontal headerStack.alignment = .center headerStack.spacing = 10 headerStack.layoutMargins = UIEdgeInsets(top: 10, leading: hMargin, bottom: 10, trailing: hMargin) headerStack.isLayoutMarginsRelativeArrangement = true textRowsView.setCompressionResistanceHorizontalLow() textRowsView.setContentHuggingHorizontalLow() self.view.addSubview(headerStack) headerStack.autoPinEdge(.top, to: .bottom, of: dismissButton) headerStack.autoPinWidthToSuperview() stickerCollectionView.backgroundColor = .clear self.view.addSubview(stickerCollectionView) stickerCollectionView.autoPinWidthToSuperview() stickerCollectionView.autoPinEdge(.top, to: .bottom, of: headerStack) let installButton = OWSFlatButton.button(title: NSLocalizedString("STICKERS_INSTALL_BUTTON", comment: "Label for the 'install sticker pack' button."), font: UIFont.ows_dynamicTypeBody.ows_mediumWeight(), titleColor: UIColor.ows_materialBlue, backgroundColor: UIColor.white, target: self, selector: #selector(didTapInstall)) self.installButton = installButton installButton.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: "installButton") let uninstallButton = OWSFlatButton.button(title: NSLocalizedString("STICKERS_UNINSTALL_BUTTON", comment: "Label for the 'uninstall sticker pack' button."), font: UIFont.ows_dynamicTypeBody.ows_mediumWeight(), titleColor: UIColor.ows_materialBlue, backgroundColor: UIColor.white, target: self, selector: #selector(didTapUninstall)) self.uninstallButton = uninstallButton uninstallButton.accessibilityIdentifier = UIView.accessibilityIdentifier(in: self, name: "uninstallButton") for button in [installButton, uninstallButton] { view.addSubview(button) button.autoPin(toBottomLayoutGuideOf: self, withInset: 10) button.autoPinEdge(.top, to: .bottom, of: stickerCollectionView) button.autoPinWidthToSuperview(withMargin: hMargin) button.autoSetHeightUsingFont() } view.addSubview(loadingIndicator) loadingIndicator.autoCenterInSuperview() loadFailedLabel.text = NSLocalizedString("STICKERS_PACK_VIEW_FAILED_TO_LOAD", comment: "Label indicating that the sticker pack failed to load.") loadFailedLabel.font = UIFont.ows_dynamicTypeBody loadFailedLabel.textColor = Theme.darkThemePrimaryColor loadFailedLabel.textAlignment = .center loadFailedLabel.numberOfLines = 0 loadFailedLabel.lineBreakMode = .byWordWrapping view.addSubview(loadFailedLabel) loadFailedLabel.autoPinWidthToSuperview(withMargin: hMargin) loadFailedLabel.autoVCenterInSuperview() updateContent() loadTimer = WeakTimer.scheduledTimer(timeInterval: 1, target: self, userInfo: nil, repeats: false) { [weak self] _ in guard let strongSelf = self else { return } strongSelf.loadTimerHasFired = true strongSelf.loadTimer?.invalidate() strongSelf.loadTimer = nil strongSelf.updateContent() } } private let dismissButton = UIButton() private let coverView = YYAnimatedImageView() private let titleLabel = UILabel() private let authorLabel = UILabel() private let defaultPackIconView = UIImageView() private let shareButton = UIButton() private var installButton: OWSFlatButton? private var uninstallButton: OWSFlatButton? private var loadingIndicator = UIActivityIndicatorView(style: .whiteLarge) private var loadFailedLabel = UILabel() // We use this timer to ensure that we don't show the // loading indicator for N seconds, to prevent a "flash" // when presenting the view. private var loadTimer: Timer? private var loadTimerHasFired = false private func updateContent() { updateCover() updateInsets() guard let stickerPack = dataSource.getStickerPack() else { installButton?.isHidden = true uninstallButton?.isHidden = true shareButton.isHidden = true if StickerManager.isStickerPackMissing(stickerPackInfo: stickerPackInfo) { loadFailedLabel.isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimating() } else if loadTimerHasFired { loadFailedLabel.isHidden = true loadingIndicator.isHidden = false loadingIndicator.startAnimating() } else { loadFailedLabel.isHidden = true loadingIndicator.isHidden = true loadingIndicator.stopAnimating() } return } let defaultTitle = NSLocalizedString("STICKERS_PACK_VIEW_DEFAULT_TITLE", comment: "The default title for the 'sticker pack' view.") if let title = stickerPack.title?.ows_stripped(), title.count > 0 { titleLabel.text = title.filterForDisplay } else { titleLabel.text = defaultTitle } authorLabel.text = stickerPack.author?.filterForDisplay defaultPackIconView.isHidden = !StickerManager.isDefaultStickerPack(stickerPack.info) // We need to consult StickerManager for the latest "isInstalled" // state, since the data source may be caching stale state. let isInstalled = StickerManager.isStickerPackInstalled(stickerPackInfo: stickerPack.info) installButton?.isHidden = isInstalled uninstallButton?.isHidden = !isInstalled shareButton.isHidden = false loadFailedLabel.isHidden = true loadingIndicator.isHidden = true loadingIndicator.stopAnimating() } private func updateCover() { guard let stickerPack = dataSource.getStickerPack() else { coverView.isHidden = true return } let coverInfo = stickerPack.coverInfo guard let filePath = dataSource.filePath(forSticker: coverInfo) else { // This can happen if the pack hasn't been saved yet, e.g. // this view was opened from a sticker pack URL or share. Logger.warn("Missing sticker data file path.") coverView.isHidden = true return } guard NSData.ows_isValidImage(atPath: filePath, mimeType: OWSMimeTypeImageWebp) else { owsFailDebug("Invalid sticker.") coverView.isHidden = true return } guard let stickerImage = YYImage(contentsOfFile: filePath) else { owsFailDebug("Sticker could not be parsed.") coverView.isHidden = true return } coverView.image = stickerImage coverView.isHidden = false } private func updateInsets() { UIView.setAnimationsEnabled(false) if #available(iOS 11.0, *) { if (!CurrentAppContext().isMainApp) { self.additionalSafeAreaInsets = .zero } else if (OWSWindowManager.shared().hasCall()) { self.additionalSafeAreaInsets = UIEdgeInsets(top: 20, leading: 0, bottom: 0, trailing: 0) } else { self.additionalSafeAreaInsets = .zero } } UIView.setAnimationsEnabled(true) } override public func viewDidLoad() { super.viewDidLoad() StickerManager.refreshContents() } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.becomeFirstResponder() } override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.becomeFirstResponder() } override public var canBecomeFirstResponder: Bool { return true } override public var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // - MARK: Events @objc private func didTapInstall(sender: UIButton) { AssertIsOnMainThread() Logger.verbose("") guard let stickerPack = dataSource.getStickerPack() else { owsFailDebug("Missing sticker pack.") return } databaseStorage.write { (transaction) in StickerManager.installStickerPack(stickerPack: stickerPack, transaction: transaction) } updateContent() ModalActivityIndicatorViewController.present(fromViewController: self, canCancel: false) { modal in // Downloads for this sticker pack will already be enqueued by // StickerManager.saveStickerPack above. We just use this // method to determine whether all sticker downloads succeeded. // Re-enqueuing should be cheap since already-downloaded stickers // will succeed immediately and failed stickers will fail again // quickly... or succeed this time. StickerManager.ensureDownloadsAsync(forStickerPack: stickerPack) .done { modal.dismiss { // Do nothing. } }.catch { (_) in modal.dismiss { OWSAlerts.showErrorAlert(message: NSLocalizedString("STICKERS_PACK_INSTALL_FAILED", comment: "Error message shown when a sticker pack failed to install.")) } }.retainUntilComplete() } } @objc private func didTapUninstall(sender: UIButton) { AssertIsOnMainThread() Logger.verbose("") databaseStorage.write { (transaction) in StickerManager.uninstallStickerPack(stickerPackInfo: self.stickerPackInfo, transaction: transaction) } updateContent() } @objc private func dismissButtonPressed(sender: UIButton) { AssertIsOnMainThread() dismiss(animated: true) } @objc func shareButtonPressed(sender: UIButton) { AssertIsOnMainThread() guard let stickerPack = dataSource.getStickerPack() else { owsFailDebug("Missing sticker pack.") return } StickerSharingViewController.shareStickerPack(stickerPack.info, from: self) } @objc public func callDidChange() { Logger.debug("") updateContent() } @objc public func didChangeStatusBarFrame() { Logger.debug("") updateContent() } @objc func stickersOrPacksDidChange() { AssertIsOnMainThread() Logger.verbose("") updateContent() } } // MARK: - extension StickerPackViewController: StickerPackDataSourceDelegate { public func stickerPackDataDidChange() { AssertIsOnMainThread() updateContent() } } // MARK: - extension StickerPackViewController: StickerPackCollectionViewDelegate { public func didTapSticker(stickerInfo: StickerInfo) { AssertIsOnMainThread() Logger.verbose("") } public func stickerPreviewHostView() -> UIView? { AssertIsOnMainThread() return view } public func stickerPreviewHasOverlay() -> Bool { return true } }
gpl-3.0
1fa73be2774c3d3dd59b332d7d1f9926
38.020089
223
0.611292
6.048789
false
false
false
false
EZ-NET/ESSwim
Sources/State.swift
1
7125
// // State.swift // ESSwim // // Created by 熊谷 友宏 on H26/12/25. // // // MARK: - Comparison State /** A Type that means comparison state of two values. The type can convert from SignedIntegerType. value == 0: .Same value < 0: .Ascending value > 0: .Descending */ public enum CompareState : IntegerLiteralConvertible { case Same case Ascending case Descending public init<T:SignedNumberType>(_ value:T) { switch value { case 0: self = .Same default: self = (value < 0 ? .Ascending : .Descending) } } public init(integerLiteral value: IntegerLiteralType) { self.init(value) } /** Returns a Int value which means order-state. -1: .Ascending 0: .Same 1: .Descending */ public var toInt:Int { switch self { case .Ascending: return -1 case .Same: return 0 case .Descending: return 1 } } /** Returns a Boolean value that indicates whether the value is equal to .Same. */ public var isSame:Bool { switch self { case .Same: return true case .Ascending, .Descending: return false } } /** Returns a Boolean value that indicates whether the value is equal to .Ascending. */ public var isAscending:Bool { switch self { case .Ascending: return true case .Same, .Descending: return false } } /** Returns a Boolean value that indicates whether the value is equal to .Descending. */ public var isDescending:Bool { switch self { case .Descending: return true case .Same, .Ascending: return false } } /** Returns a Boolean value that indicates whether the value is equal to .Ascending or equal to .Same. */ public var isAscendingOrSame:Bool { switch self { case .Same, .Ascending: return true case .Descending: return false } } /** Returns a Boolean value that indicates whether the value is equal to .Descending or equal to .Same. */ public var isDescendingOrSame:Bool { switch self { case .Same, .Descending: return true case .Ascending: return false } } } public func isSame(state:Swim.CompareState) -> Bool { return state.isSame } public func isAscending(state:Swim.CompareState) -> Bool { return state.isAscending } public func isDescending(state:Swim.CompareState) -> Bool { return state.isDescending } public func isAscendingOrSame(state:Swim.CompareState) -> Bool { return state.isAscendingOrSame } public func isDescendingOrSame(state:Swim.CompareState) -> Bool { return state.isDescendingOrSame } public func isSame<T:SignedIntegerType>(state:T) -> Bool { return Swim.isSame(Swim.CompareState(state)) } public func isAscending<T:SignedIntegerType>(state:T) -> Bool { return Swim.isAscending(Swim.CompareState(state)) } public func isDescending<T:SignedIntegerType>(state:T) -> Bool { return Swim.isDescending(Swim.CompareState(state)) } public func isAscendingOrSame<T:SignedIntegerType>(state:T) -> Bool { return Swim.isAscendingOrSame(Swim.CompareState(state)) } public func isDescendingOrSame<T:SignedIntegerType>(state:T) -> Bool { return Swim.isDescendingOrSame(Swim.CompareState(state)) } extension SignedIntegerType { public var compareState:CompareState { return CompareState(self) } } // MARK: - Yes/No State /** A Type that means following state, Yes or No. The type can convert from IntegerType. value != 0: .Yes value == 0: .No */ public enum YesNoState : IntegerLiteralConvertible, BooleanLiteralConvertible, BooleanType { case Yes case No public init<T:IntegerType>(_ yesIfNonZero: T) { self = (yesIfNonZero != 0 ? .Yes : .No) } public init<T:BooleanType>(_ value:T) { self = (value ? .Yes : .No) } public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } public init(integerLiteral value: IntegerLiteralType) { self.init(value) } /** Returns a Boolean value that indicates whether the value is equal to .Yes. :return: True if the value is equal to .Yes, otherwise false. */ public var boolValue:Bool { switch self { case .Yes: return true case .No: return false } } } public func isYes(state:Swim.YesNoState) -> Bool { return state.boolValue } public func isNo(state:Swim.YesNoState) -> Bool { return !state.boolValue } public func isYes<T:IntegerType>(state:T) -> Bool { return Swim.isYes(Swim.YesNoState(state)) } public func isNo<T:IntegerType>(state:T) -> Bool { return Swim.isNo(Swim.YesNoState(state)) } // MARK: - Processing State /** A Type that means a process is Continue or Abort. */ public enum ContinuousState : BooleanType { case Continue case Abort /** Create a instance values .Continue. This initializer is useful when you want to consider non-result function as always .Continue. */ public init() { self = .Continue } public var boolValue:Bool { switch self { case .Continue: return true case .Abort: return false } } public var toProcessingState:Swim.ProcessingState { switch self { case .Continue: return .Passed case .Abort: return .Aborted } } } /** A Type that means someone Found or NotFound. */ public enum FindState { case Found case NotFound public var found:Bool { switch self { case .Found: return true case .NotFound: return false } } public var notFound:Bool { switch self { case .Found: return false case .NotFound: return true } } } /** A Type that means a process was passed or failed. The type can convert from IntegerType. value == 0: .Passed value != 0: .Aborted */ public enum ProcessingState : IntegerLiteralConvertible, BooleanType { case Passed case Aborted /** Create a instance values .Passed. This initializer is useful when you want to consider non-result function as always .Passed. */ public init() { self = .Passed } public init<T:IntegerType>(_ passedIfZero: T) { self = (passedIfZero == 0 ? .Passed : .Aborted) } public init(integerLiteral value: IntegerLiteralType) { self.init(value) } public var boolValue:Bool { return self.passed } /** Returns a Boolean value that indicates whether the value is equal to .Passed. */ public var passed:Bool { switch self { case .Passed: return true case .Aborted: return false } } /** Returns a Boolean value that indicates whether the value is equal to .Aborted. */ public var aborted:Bool { switch self { case .Passed: return false case .Aborted: return true } } } public func passed(state:Swim.ProcessingState) -> Bool { return state.passed } public func aborted(state:Swim.ProcessingState) -> Bool { return state.aborted } public func passed<T:IntegerType>(state:T) -> Bool { return Swim.passed(Swim.ProcessingState(state)) } public func aborted<T:IntegerType>(state:T) -> Bool { return Swim.aborted(Swim.ProcessingState(state)) } extension IntegerType { public var processed:ProcessingState { return ProcessingState(self) } }
mit
85edf7a51ec035c19c9886591a87ed36
15.248858
100
0.678376
3.366604
false
false
false
false
boxcast/boxcast-sdk-apple
Source/Models/Broadcast.swift
1
2823
// // Broadcast.swift // BoxCast // // Created by Camden Fullmer on 5/13/17. // Copyright © 2017 BoxCast, Inc. All rights reserved. // import Foundation /// The struct that represents a BoxCast broadcast. public struct Broadcast { /// The unique identifier for the broadcast. public let id: String /// The name of the broadcast. public let name: String /// The description of the broadcast. public let description: String /// The image URL for the thumbnail of the broadcast. public let thumbnailURL: URL? /// The channel's unique identifier that includes this broadcast. public let channelId: String /// The start date of the broadcast. public let startDate: Date /// The stop date of the broadcast. public let stopDate: Date let accountId: String? init(id: String, name: String, description: String, thumbnailURL: URL, startDate: Date, stopDate: Date, channelId: String, accountId: String?=nil) { self.id = id self.name = name self.description = description self.thumbnailURL = thumbnailURL self.startDate = startDate self.stopDate = stopDate self.channelId = channelId self.accountId = accountId } init(channelId: String, json: Any) throws { guard let dict = json as? Dictionary<String, Any> else { throw BoxCastError.serializationError } guard let id = dict["id"] as? String, let name = dict["name"] as? String, let description = dict["description"] as? String, let startDateString = dict["starts_at"] as? String, let stopDateString = dict["stops_at"] as? String else { throw BoxCastError.serializationError } guard let startDate = _BoxCastDateFormatter.date(from: startDateString), let stopDate = _BoxCastDateFormatter.date(from: stopDateString) else { throw BoxCastError.serializationError } self.id = id self.accountId = dict["account_id"] as? String self.channelId = channelId self.name = name self.description = description self.startDate = startDate self.stopDate = stopDate self.thumbnailURL = URL(string: (dict["preview"] as? String ?? "")) } } public typealias BroadcastList = [Broadcast] extension Array where Element == Broadcast { init(channelId: String, json: Any) throws { guard let array = json as? Array<Any> else { throw BoxCastError.serializationError } let broadcasts = try array.compactMap { json in return try Broadcast(channelId: channelId, json: json) } self.init(broadcasts) } }
mit
1327bd16608ddcc4eeea36a4bb348c6a
30.707865
152
0.620128
4.679934
false
false
false
false
nikriek/gesundheit.space
Carthage/Checkouts/RxDataSources/Example/Example1_CustomizationUsingTableViewDelegate.swift
2
2359
// // CustomizationUsingTableViewDelegate.swift // RxDataSources // // Created by Krunoslav Zaher on 4/19/16. // Copyright © 2016 kzaher. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa import RxDataSources struct MySection { var header: String var items: [Item] } extension MySection : AnimatableSectionModelType { typealias Item = Int var identity: String { return header } init(original: MySection, items: [Item]) { self = original self.items = items } } class CustomizationUsingTableViewDelegate : UIViewController { @IBOutlet var tableView: UITableView! let disposeBag = DisposeBag() var dataSource: RxTableViewSectionedAnimatedDataSource<MySection>? override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") let dataSource = RxTableViewSectionedAnimatedDataSource<MySection>() dataSource.configureCell = { ds, tv, ip, item in let cell = tv.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style: .default, reuseIdentifier: "Cell") cell.textLabel?.text = "Item \(item)" return cell } dataSource.titleForHeaderInSection = { ds, index in return ds.sectionModels[index].header } let sections = [ MySection(header: "First section", items: [ 1, 2 ]), MySection(header: "Second section", items: [ 3, 4 ]) ] Observable.just(sections) .bindTo(tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) tableView.rx.setDelegate(self) .addDisposableTo(disposeBag) self.dataSource = dataSource } } extension CustomizationUsingTableViewDelegate : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // you can also fetch item guard let item = dataSource?[indexPath], // .. or section and customize what you like let _ = dataSource?[indexPath.section] else { return 0.0 } return CGFloat(40 + item) } }
mit
e7204775a56bc1a247f76c41512490b6
24.354839
130
0.621713
5.092873
false
false
false
false
KIPPapp/KIPPapp
kippapp/Student.swift
1
965
// // Student.swift // kippapp // // Created by isai on 10/12/14. // Copyright (c) 2014 kippgroup. All rights reserved. // import Foundation class Student { var name: String = "" var id: String = "" var grade: String = "" var teacher: String = "" var mastery: Float = 0.0 var progress: Float = 0.0 var currentNumTries: Int = 0 var groupName: String = "" var homeLogins: Int = 0 var labLogins: Int = 0 var minLastWeek: Int = 0 var imagePath:String = "monika_square.png" var attendance:String = "notset" var celebrated:Bool = false var subjects: [Subject]? var groups: [Group]? var checkedIn:Bool = false init() { } func assignGroupForWeek() { } func getGroups() { } func assignParent() { } func getParent() { } func getSubjects() { } }
mit
25975c29dc6f8b21fd644250b469a52f
14.836066
54
0.52228
3.754864
false
false
false
false
VirgilSecurity/virgil-sdk-pfs-x
Source/SecureChat/Models/InitiationMessage.swift
1
2971
// // InitiationMessage.swift // VirgilSDKPFS // // Created by Oleksandr Deundiak on 6/20/17. // Copyright © 2017 VirgilSecurity. All rights reserved. // import Foundation struct InitiationMessage { let initiatorIcId: String let responderIcId: String let responderLtcId: String let responderOtcId: String? let ephPublicKey: Data let ephPublicKeySignature: Data let salt: Data let cipherText: Data } extension InitiationMessage { fileprivate enum Keys: String { case initiatorIcId = "initiator_ic_id" case responderIcId = "responder_ic_id" case responderLtcId = "responder_ltc_id" case responderOtcId = "responder_otc_id" case eph = "eph" case sign = "sign" case salt = "salt" case cipherText = "ciphertext" } } extension InitiationMessage: Serializable { func serialize() -> NSObject { let dict: NSMutableDictionary = [ Keys.initiatorIcId.rawValue: self.initiatorIcId, Keys.responderIcId.rawValue: self.responderIcId, Keys.responderLtcId.rawValue: self.responderLtcId, Keys.eph.rawValue: self.ephPublicKey.base64EncodedString(), Keys.sign.rawValue: self.ephPublicKeySignature.base64EncodedString(), Keys.salt.rawValue: self.salt.base64EncodedString(), Keys.cipherText.rawValue: self.cipherText.base64EncodedString() ] if let otcId = self.responderOtcId { dict[Keys.responderOtcId.rawValue] = otcId } return dict } } extension InitiationMessage: Deserializable { init?(dictionary: Any) { guard let dict = dictionary as? [AnyHashable: Any] else { return nil } guard let initiatorIcId = dict[Keys.initiatorIcId.rawValue] as? String, let responderIcId = dict[Keys.responderIcId.rawValue] as? String, let responderLtcId = dict[Keys.responderLtcId.rawValue] as? String, let ephPublicKeyStr = dict[Keys.eph.rawValue] as? String, let ephPublicKey = Data(base64Encoded: ephPublicKeyStr), let ephPublicKeySignatureStr = dict[Keys.sign.rawValue] as? String, let ephPublicKeySignature = Data(base64Encoded: ephPublicKeySignatureStr), let saltStr = dict[Keys.salt.rawValue] as? String, let salt = Data(base64Encoded: saltStr), let cipherTextStr = dict[Keys.cipherText.rawValue] as? String, let cipherText = Data(base64Encoded: cipherTextStr) else { return nil } let responderOtcId = dict[Keys.responderOtcId.rawValue] as? String self.init(initiatorIcId: initiatorIcId, responderIcId: responderIcId, responderLtcId: responderLtcId, responderOtcId: responderOtcId, ephPublicKey: ephPublicKey, ephPublicKeySignature: ephPublicKeySignature, salt: salt, cipherText: cipherText) } }
bsd-3-clause
03b8459dc8a0f4e2312b7e9fab050adb
36.594937
251
0.662626
4.261119
false
false
false
false
boolkybear/iOS-Challenge
CatViewer/CatViewer/xml/CategoryParserDelegate.swift
1
3760
// // CategoryParserDelegate.swift // CatViewer // // Created by Boolky Bear on 6/2/15. // Copyright (c) 2015 ByBDesigns. All rights reserved. // import UIKit class CategoryParserDelegate: NSObject { private enum Tag: String { case Response = "response" case Data = "data" case Categories = "categories" case Category = "category" case Identifier = "id" case Name = "name" } private enum ParseStatus { case NotParsed case ParsedResponse case ParsedData case ParsedCategories case Ok case Error func nextStatus(tag: Tag) -> ParseStatus { switch tag { case .Response: return self == .NotParsed ? .ParsedResponse : .Error case .Data: return self == .ParsedResponse ? .ParsedData : .Error case .Categories: return self == .ParsedData ? .ParsedCategories : .Error case .Category: switch self { case .ParsedCategories: return .Ok case .Ok: return .Ok case .NotParsed: fallthrough case .ParsedResponse: fallthrough case .ParsedData: fallthrough case .Error: return .Error } case .Identifier: fallthrough case .Name: return self == .Ok ? .Ok : .Error } } } private var categories: [CategoryModel] // temporary private var temporaryCategory: CategoryModel! private var tagStack: Stack<Tag> private var status: ParseStatus override init() { self.tagStack = Stack<Tag>() self.categories = [CategoryModel]() self.status = .NotParsed } func isParsed() -> Bool { return self.status == .Ok } func count() -> Int { return self.categories.count } subscript(index: Int) -> CategoryModel { return self.categories[index] } } extension CategoryParserDelegate: NSXMLParserDelegate { func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) { if let tag = Tag(rawValue: elementName) { self.tagStack.push(tag) self.status = self.status.nextStatus(tag) switch tag { case .Category: self.temporaryCategory = CategoryModel() case .Identifier: self.temporaryCategory.identifier = "" case .Name: self.temporaryCategory.name = "" case .Response: fallthrough case .Data: fallthrough case .Categories: break } } else { // TODO: log parser error parser.abortParsing() } } func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) { if let tag = Tag(rawValue: elementName) { if tag == .Category { self.categories.append(self.temporaryCategory) self.temporaryCategory = nil } self.tagStack.pop() } else { // TODO: log parser error parser.abortParsing() } } func parser(parser: NSXMLParser!, foundCharacters string: String!) { if let currentTag = self.tagStack.top() { switch currentTag { case .Identifier: self.temporaryCategory.identifier?.extend(string) case .Name: self.temporaryCategory.name?.extend(string) case .Response: fallthrough case .Data: fallthrough case .Categories: fallthrough case .Category: break } } } func parser(parser: NSXMLParser!, foundCDATA CDATABlock: NSData!) { if let currentTag = self.tagStack.top() { switch currentTag { case .Identifier: fallthrough case .Name: if let string = NSString(data: CDATABlock, encoding: NSUTF8StringEncoding) { self.parser(parser, foundCharacters: string) } case .Response: fallthrough case .Data: fallthrough case .Categories: fallthrough case .Category: break } } } }
mit
3dfd56e6b0ba116732fdcf84c451c002
18.899471
178
0.661702
3.577545
false
false
false
false
PrajeetShrestha/ioshubgsheetwrite
ioshubSheets/AppDelegate.swift
1
3158
// // AppDelegate.swift // ioshubSheets // // Created by Eeposit1 on 8/12/16. // Copyright © 2016 eeposit. All rights reserved. // import UIKit import IQKeyboardManagerSwift import GoogleAPIClient import GTMOAuth2 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private let service = GlobalGTLService.sharedInstance.service func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { IQKeyboardManager.sharedManager().enable = true self.checkForAppAuthorization() return true } func checkForAppAuthorization() { if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName( kKeychainItemName, clientID: kClientID, clientSecret: nil) { service.authorizer = auth } let storyboard = UIStoryboard(name: "Main", bundle: nil) if let authorizer = service.authorizer, canAuth = authorizer.canAuthorize where canAuth { let controller = storyboard.instantiateViewControllerWithIdentifier("tabBarController") self.window?.rootViewController = controller } else { let controller = storyboard.instantiateViewControllerWithIdentifier("LoginController") self.window?.rootViewController = controller } } 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:. } }
apache-2.0
bcf3db032c4f6c86b7a3c594a00cc6ee
43.464789
285
0.717453
5.750455
false
false
false
false
Shedward/SwiftyNotificationCenter
Example/SwiftyNotificationCenter/ViewController.swift
1
2274
// // ViewController.swift // SwiftyNotificationCenter // // Created by Vladislav Maltsev on 12/04/2016. // Copyright (c) 2016 Vladislav Maltsev. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import SwiftyNotificationCenter class ViewController: UIViewController { @IBOutlet weak var subsciptionStateLabel: UILabel! private var subscriptionObserver: NotificationObserver<SubscriptionStateChanged>? override func viewDidLoad() { subscriptionObserver = NotificationCenter.default.observe { [unowned self] event in let message: String switch event { case .free: message = "free" case .premium: message = "premium" case .promo("new year"): message = "happy new year" case .promo(let text): message = "Promo \(text)" } self.subsciptionStateLabel.text = message } } @IBAction func logoutDidPressed() { NotificationCenter.default.post(event: LoginStateChanged(userIsLoggedIn: false)) } @IBAction func unwindToMainPage(segue: UIStoryboardSegue) { } }
mit
1bf9e7ca434b32c2e0da51cc89d87e39
35.677419
91
0.6781
4.807611
false
false
false
false
Kamaros/ELDeveloperKeyboard
Keyboard/Custom Views/Buttons/KeyButton.swift
1
2052
// // KeyButton.swift // ELDeveloperKeyboard // // Created by Eric Lin on 2014-07-02. // Copyright (c) 2014 Eric Lin. All rights reserved. // import Foundation import UIKit import QuartzCore /** KeyButton is a UIButton subclass with keyboard button styling. */ class KeyButton: UIButton { // MARK: Constructors override init(frame: CGRect) { super.init(frame: frame) titleLabel?.font = UIFont(name: "HelveticaNeue", size: 18.0) titleLabel?.textAlignment = .Center setTitleColor(UIColor(white: 238.0/255, alpha: 1.0), forState: UIControlState.Normal) titleLabel?.sizeToFit() let gradient = CAGradientLayer() gradient.frame = bounds let gradientColors: [AnyObject] = [UIColor(red: 80.0/255, green: 80.0/255, blue: 80.0/255, alpha: 1.0).CGColor, UIColor(red: 60.0/255, green: 60.0/255, blue: 60.0/255, alpha: 1.0).CGColor] gradient.colors = gradientColors // Declaration broken into two lines to prevent 'unable to bridge to Objective C' error. setBackgroundImage(gradient.UIImageFromCALayer(), forState: .Normal) let selectedGradient = CAGradientLayer() selectedGradient.frame = bounds let selectedGradientColors: [AnyObject] = [UIColor(red: 67.0/255, green: 116.0/255, blue: 224.0/255, alpha: 1.0).CGColor, UIColor(red: 32.0/255, green: 90.0/255, blue: 214.0/255, alpha: 1.0).CGColor] selectedGradient.colors = selectedGradientColors // Declaration broken into two lines to prevent 'unable to bridge to Objective C' error. setBackgroundImage(selectedGradient.UIImageFromCALayer(), forState: .Selected) layer.masksToBounds = true layer.cornerRadius = 3.0 contentVerticalAlignment = .Center contentHorizontalAlignment = .Center contentEdgeInsets = UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 0) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
f0690ef278e8ba26da091578eb09f02b
39.254902
207
0.666179
4.170732
false
false
false
false
ello/ello-ios
Sources/Extensions/NumberExtensions.swift
1
1457
//// /// NumberExtensions.swift // let billion = 1_000_000_000.0 let million = 1_000_000.0 let thousand = 1_000.0 extension Int { func numberToHuman(rounding: Int = 1, showZero: Bool = false) -> String { if self == 0 && !showZero { return "" } let roundingFactor: Double = pow(10, Double(rounding)) let double = Double(self) let num: Float let suffix: String if double >= billion { num = Float(round(double / billion * roundingFactor) / roundingFactor) suffix = "B" } else if double >= million { num = Float(round(double / million * roundingFactor) / roundingFactor) suffix = "M" } else if double >= thousand { num = Float(round(double / thousand * roundingFactor) / roundingFactor) suffix = "K" } else { num = Float(round(double * roundingFactor) / roundingFactor) suffix = "" } var strNum = "\(num)" let strArr = strNum.split { $0 == "." }.map { String($0) } if strArr.last == "0" { strNum = strArr.first! } return "\(strNum)\(suffix)" } } public extension Double { func roundTo(decimals: Int = 2) -> Double { let roundingFactor: Double = pow(10, Double(decimals)) let double = Double(self) return (double * roundingFactor).rounded() / roundingFactor } }
mit
2c1b253c019472514c348c17356e3f00
27.568627
83
0.543583
4.024862
false
false
false
false
immanuel/radio-scanner
RadioScanner/Station.swift
1
2092
// // Station.swift // RadioScanner // // Created by Immanuel Thomas on 9/3/16. // Copyright © 2016 Immanuel Thomas. All rights reserved. // import UIKit class Station { var name: String var url: String var artistXPath: String var songXPath: String var currentSong: String? var currentArtist: String? var photo: UIImage init?(name: String, photo: UIImage, url: String, artistXPath: String, songXPath: String){ self.name = name self.photo = photo self.url = url self.artistXPath = artistXPath self.songXPath = songXPath if (name.isEmpty || url.isEmpty || artistXPath.isEmpty || songXPath.isEmpty){ return nil } } func fetchCurrentSongAndArtist() -> (song: String?, artist: String?){ var myHTMLString:String = "" guard let myURL = NSURL(string: url) else { print("Error: \(url) doesn't seem to be a valid URL") return (self.currentSong, self.currentArtist) } do { myHTMLString = try String(contentsOfURL: myURL) } catch let error as NSError { print("Error: \(error)") } if let doc = XML(xml: myHTMLString, encoding: NSUTF8StringEncoding) { let songElement = doc.xpath(songXPath) let artistElement = doc.xpath(artistXPath) switch songElement { case .None: print("Error - parsing failed") default: switch artistElement{ case .None: print("Error - parsing failed") default: self.currentSong = songElement[0].content self.currentArtist = artistElement[0].content } } } return (self.currentSong, self.currentArtist) } func getCurrentSongAndArtist() ->(song: String?, artist: String?) { return (self.currentSong, self.currentArtist) } }
mit
206d760f0c4987c0485c966587bffd1a
28.041667
93
0.545672
4.667411
false
false
false
false
PrashantMangukiya/SwiftUIDemo
Demo33-UIScreenEdgePanGesture/Demo33-UIScreenEdgePanGesture/ViewController.swift
1
1930
// // ViewController.swift // Demo33-UIScreenEdgePanGesture // // Created by Prashant on 15/10/15. // Copyright © 2015 PrashantKumar Mangukiya. All rights reserved. // import UIKit class ViewController: UIViewController { // outlet - status label @IBOutlet var statusLabel: UILabel! // create left edge and right edge gesture let leftEdgePanGesture = UIScreenEdgePanGestureRecognizer() let rightEdgePanGesture = UIScreenEdgePanGestureRecognizer() // Mark: - View functions override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // add target for gesture self.leftEdgePanGesture.addTarget(self, action: #selector(ViewController.handleLeftEdge(_:))) self.rightEdgePanGesture.addTarget(self, action: #selector(ViewController.handleRightEdge(_:))) // set detection edge self.leftEdgePanGesture.edges = UIRectEdge.left self.rightEdgePanGesture.edges = UIRectEdge.right // add gesture into view self.view.addGestureRecognizer(self.leftEdgePanGesture) self.view.addGestureRecognizer(self.rightEdgePanGesture) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Mark: - Utility functions // perform operation when left edge gesture detected func handleLeftEdge( _ gesture: UIScreenEdgePanGestureRecognizer ) { self.statusLabel.text = "Left Edge" self.statusLabel.textColor = UIColor.black } // perform operation when right edge gesture detected func handleRightEdge( _ gesture: UIScreenEdgePanGestureRecognizer ) { self.statusLabel.text = "Right Edge" self.statusLabel.textColor = UIColor.blue } }
mit
433de281edfead69c2f49a023cd06ff6
27.791045
103
0.680145
5.464589
false
false
false
false
Noders/NodersCL-App
StrongLoopForiOS/ConversionUtility.swift
1
1384
// // ConversionUtility.swift // Noders // // Created by Jose Vildosola on 22-05-15. // Copyright (c) 2015 DevIn. All rights reserved. // import UIKit class ConversionUtility: NSObject { class func parseISO8601Time(duration: String) -> NSString{ var dur:NSString = duration var hours:NSInteger = 0 var minutes:NSInteger = 0 var seconds:NSInteger = 0 dur = dur.substringFromIndex(dur.rangeOfString("T").location) while dur.length > 1 { dur = dur.substringFromIndex(1) let scanner:NSScanner = NSScanner(string: dur as String) var durationPart:NSString? scanner.scanCharactersFromSet(NSCharacterSet(charactersInString: "0123456789"), intoString: &durationPart) let rangeOfDurationPart:NSRange = dur.rangeOfString(durationPart as! String) dur = dur.substringFromIndex(rangeOfDurationPart.location + rangeOfDurationPart.length) if dur.substringToIndex(1) == "H" { hours = durationPart!.integerValue } if dur.substringToIndex(1) == "M" { minutes = durationPart!.integerValue } if dur.substringToIndex(1) == "S" { seconds = durationPart!.integerValue } } return String(format: "%02d:%02d:%02d",hours,minutes,seconds) } }
gpl-2.0
9f222e200ab81b4f8ff2245f72fefbbb
36.405405
118
0.619942
4.493506
false
false
false
false
DylanModesitt/Verb
Verb/Verb/Extensions.swift
1
4409
// // Extensions.swift // Verb // // Created by dcm on 12/24/15. // Copyright © 2015 Verb. All rights reserved. // import Foundation import UIKit extension UITableViewController { func setupAutomaticCellSizing() { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 200 } func createHeader(headerView: UIView!, headerHeight: CGFloat, headerMaskLayer: CAShapeLayer) { tableView.tableHeaderView = nil tableView.addSubview(headerView!) tableView.contentInset = UIEdgeInsets(top: headerHeight, left: 0, bottom: 0, right: 0) tableView.contentOffset = CGPoint(x:0,y: -headerHeight) headerMaskLayer.fillColor = UIColor.blackColor().CGColor headerView.layer.mask = headerMaskLayer } func updateNavigationBar(color: UIColor!) { if let navigationController = self.navigationController { navigationController.navigationBar.hideBottomHairline() navigationController.navigationBar.barTintColor = color navigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] navigationController.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) navigationController.navigationBar.tintColor = UIModel().getCompliment(color) self.tabBarController?.tabBar.barTintColor = color self.tabBarController?.tabBar.tintColor = UIModel().getCompliment(color) self.tabBarController?.tabBar.translucent = false UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } } func updateHeader(headerView: UIView!, headerHeight: CGFloat, headerMaskLayer: CAShapeLayer) { var headerRect = CGRect(x: 0, y: -headerHeight, width: tableView.bounds.width, height: headerHeight) if tableView.contentOffset.y < -headerHeight { headerRect.origin.y = tableView.contentOffset.y headerRect.size.height = -tableView.contentOffset.y } headerView.frame = headerRect let cutawayValue: CGFloat = 25 let path = UIBezierPath() path.moveToPoint(CGPoint(x: 0, y: 0)) path.addLineToPoint(CGPoint(x: headerRect.width, y: 0)) path.addLineToPoint(CGPoint(x: headerRect.width, y: headerRect.height)) path.addLineToPoint(CGPoint(x: 0, y: headerRect.height-cutawayValue)) headerMaskLayer.path = path.CGPath } } extension UINavigationBar { func hideBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(self) navigationBarImageView!.hidden = true } func showBottomHairline() { let navigationBarImageView = hairlineImageViewInNavigationBar(self) navigationBarImageView!.hidden = false } private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? { if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 { return (view as! UIImageView) } let subviews = (view.subviews as [UIView]) for subview: UIView in subviews { if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) { return imageView } } return nil } } extension UIToolbar { func hideHairline() { let navigationBarImageView = hairlineImageViewInToolbar(self) navigationBarImageView!.hidden = true } func showHairline() { let navigationBarImageView = hairlineImageViewInToolbar(self) navigationBarImageView!.hidden = false } private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? { if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 { return (view as! UIImageView) } let subviews = (view.subviews as [UIView]) for subview: UIView in subviews { if let imageView: UIImageView = hairlineImageViewInToolbar(subview) { return imageView } } return nil } }
apache-2.0
d45c2ba29ab00d1cedf3758f674ddd85
30.71223
155
0.645644
5.37561
false
false
false
false
sathyavijayan/SchemaValidator
Pod/Classes/Utils.swift
1
1130
// // Utils.swift // SchemaValidator // // Created by Sathyavijayan Vittal on 05/06/2015. // Copyright (c) 2015 CocoaPods. All rights reserved. // import Foundation internal func < (left: NSNumber, right: NSNumber) -> Bool { var comparisonResult:NSComparisonResult = left.compare(right) return (comparisonResult == NSComparisonResult.OrderedAscending) ? true: false } internal func <= (left: NSNumber, right: NSNumber) -> Bool { var comparisonResult:NSComparisonResult = left.compare(right) return (comparisonResult == NSComparisonResult.OrderedAscending || comparisonResult == NSComparisonResult.OrderedSame) ? true: false } internal func > (left: NSNumber, right: NSNumber) -> Bool { var comparisonResult:NSComparisonResult = left.compare(right) return (comparisonResult == NSComparisonResult.OrderedDescending) ? true: false } internal func >= (left: NSNumber, right: NSNumber) -> Bool { var comparisonResult:NSComparisonResult = left.compare(right) return (comparisonResult == NSComparisonResult.OrderedDescending || comparisonResult == NSComparisonResult.OrderedSame) ? true: false }
mit
0b76ba8013d3e0d6dcf11240afd91c86
37.965517
137
0.749558
4.574899
false
false
false
false
bhajian/raspi-remote
Carthage/Checkouts/ios-sdk/Examples/SpeechToText/SpeechToText/ViewController.swift
1
13594
/** * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import UIKit import AVFoundation import SpeechToTextV1 class ViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var startStopRecordingButton: UIButton! @IBOutlet weak var playRecordingButton: UIButton! @IBOutlet weak var transcribeButton: UIButton! @IBOutlet weak var startStopStreamingDefaultButton: UIButton! @IBOutlet weak var startStopStreamingCustomButton: UIButton! @IBOutlet weak var transcriptionField: UITextView! var stt: SpeechToText? var player: AVAudioPlayer? = nil var recorder: AVAudioRecorder! var isStreamingDefault = false var stopStreamingDefault: (Void -> Void)? = nil var isStreamingCustom = false var stopStreamingCustom: (Void -> Void)? = nil var captureSession: AVCaptureSession? = nil override func viewDidLoad() { super.viewDidLoad() // create file to store recordings let documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let filename = "SpeechToTextRecording.wav" let filepath = NSURL(fileURLWithPath: documents + "/" + filename) // set up session and recorder let session = AVAudioSession.sharedInstance() var settings = [String: AnyObject]() settings[AVSampleRateKey] = NSNumber(float: 44100.0) settings[AVNumberOfChannelsKey] = NSNumber(int: 1) do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord) recorder = try AVAudioRecorder(URL: filepath, settings: settings) } catch { failure("Audio Recording", message: "Error setting up session/recorder.") } // ensure recorder is set up guard let recorder = recorder else { failure("AVAudioRecorder", message: "Could not set up recorder.") return } // prepare recorder to record recorder.delegate = self recorder.meteringEnabled = true recorder.prepareToRecord() // disable play and transcribe buttons playRecordingButton.enabled = false transcribeButton.enabled = false instantiateSTT() } func instantiateSTT() { // identify credentials file let bundle = NSBundle(forClass: self.dynamicType) guard let credentialsURL = bundle.pathForResource("Credentials", ofType: "plist") else { failure("Loading Credentials", message: "Unable to locate credentials file.") return } // load credentials file let dict = NSDictionary(contentsOfFile: credentialsURL) guard let credentials = dict as? Dictionary<String, String> else { failure("Loading Credentials", message: "Unable to read credentials file.") return } // read SpeechToText username guard let user = credentials["SpeechToTextUsername"] else { failure("Loading Credentials", message: "Unable to read Speech to Text username.") return } // read SpeechToText password guard let password = credentials["SpeechToTextPassword"] else { failure("Loading Credentials", message: "Unable to read Speech to Text password.") return } stt = SpeechToText(username: user, password: password) } @IBAction func startStopRecording() { // ensure recorder is set up guard let recorder = recorder else { failure("Start/Stop Recording", message: "Recorder not properly set up.") return } // stop playing previous recording if let player = player { if (player.playing) { player.stop() } } // start/stop recording if (!recorder.recording) { do { let session = AVAudioSession.sharedInstance() try session.setActive(true) recorder.record() startStopRecordingButton.setTitle("Stop Recording", forState: .Normal) playRecordingButton.enabled = false transcribeButton.enabled = false } catch { failure("Start/Stop Recording", message: "Error setting session active.") } } else { do { recorder.stop() let session = AVAudioSession.sharedInstance() try session.setActive(false) startStopRecordingButton.setTitle("Start Recording", forState: .Normal) playRecordingButton.enabled = true transcribeButton.enabled = true } catch { failure("Start/Stop Recording", message: "Error setting session inactive.") } } } @IBAction func playRecording() { // ensure recorder is set up guard let recorder = recorder else { failure("Play Recording", message: "Recorder not properly set up") return } // play saved recording if (!recorder.recording) { do { player = try AVAudioPlayer(contentsOfURL: recorder.url) player?.play() } catch { failure("Play Recording", message: "Error creating audio player.") } } } @IBAction func transcribe() { // ensure recorder is set up guard let recorder = recorder else { failure("Transcribe", message: "Recorder not properly set up.") return } // ensure SpeechToText service is set up guard let stt = stt else { failure("Transcribe", message: "SpeechToText not properly set up.") return } // load data from saved recording guard let data = NSData(contentsOfURL: recorder.url) else { failure("Transcribe", message: "Error retrieving saved recording data.") return } // transcribe recording let settings = TranscriptionSettings(contentType: .WAV) stt.transcribe(data, settings: settings, failure: failureData) { results in self.showResults(results) } } @IBAction func startStopStreamingDefault(sender: UIButton) { // stop if already streaming if (isStreamingDefault) { stopStreamingDefault?() startStopStreamingDefaultButton.setTitle("Start Streaming (Default)", forState: .Normal) isStreamingDefault = false return } // set streaming isStreamingDefault = true // change button title startStopStreamingDefaultButton.setTitle("Stop Streaming (Default)", forState: .Normal) // ensure SpeechToText service is up guard let stt = stt else { failure("STT Streaming (Default)", message: "SpeechToText not properly set up.") return } // configure settings for streaming var settings = TranscriptionSettings(contentType: .L16(rate: 44100, channels: 1)) settings.continuous = true settings.interimResults = true // start streaming from microphone stopStreamingDefault = stt.transcribe(settings, failure: failureDefault) { results in self.showResults(results) } } @IBAction func startStopStreamingCustom(sender: UIButton) { // stop if already streaming if (isStreamingCustom) { captureSession?.stopRunning() stopStreamingCustom?() startStopStreamingCustomButton.setTitle("Start Streaming (Custom)", forState: .Normal) isStreamingCustom = false return } // set streaming isStreamingCustom = true // change button title startStopStreamingCustomButton.setTitle("Stop Streaming (Custom)", forState: .Normal) // ensure SpeechToText service is up guard let stt = stt else { failure("STT Streaming (Custom)", message: "SpeechToText not properly set up.") return } // ensure there is at least one audio input device available let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeAudio) guard !devices.isEmpty else { let domain = "swift.ViewController" let code = -1 let description = "Unable to access the microphone." let userInfo = [NSLocalizedDescriptionKey: description] let error = NSError(domain: domain, code: code, userInfo: userInfo) failureCustom(error) return } // create capture session captureSession = AVCaptureSession() guard let captureSession = captureSession else { return } // add microphone as input to capture session let microphoneDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio) let microphoneInput = try? AVCaptureDeviceInput(device: microphoneDevice) if captureSession.canAddInput(microphoneInput) { captureSession.addInput(microphoneInput) } // configure settings for streaming var settings = TranscriptionSettings(contentType: .L16(rate: 44100, channels: 1)) settings.continuous = true settings.interimResults = true // create a transcription output let outputOpt = stt.createTranscriptionOutput(settings, failure: failureCustom) { results in self.showResults(results) } // access tuple elements guard let output = outputOpt else { isStreamingCustom = false startStopStreamingCustomButton.setTitle("Start Streaming (Custom)", forState: .Normal) return } let transcriptionOutput = output.0 stopStreamingCustom = output.1 // add transcription output to capture session if captureSession.canAddOutput(transcriptionOutput) { captureSession.addOutput(transcriptionOutput) } // start streaming captureSession.startRunning() } func failure(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default) { action in } alert.addAction(ok) presentViewController(alert, animated: true) { } } func failureData(error: NSError) { let title = "Speech to Text Error:\nTranscribe" let message = error.localizedDescription failure(title, message: message) } func failureDefault(error: NSError) { let title = "Speech to Text Error:\nStreaming (Default)" let message = error.localizedDescription let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default) { action in self.stopStreamingDefault?() self.startStopStreamingDefaultButton.enabled = true self.startStopStreamingDefaultButton.setTitle("Start Streaming (Default)", forState: .Normal) self.isStreamingDefault = false } alert.addAction(ok) presentViewController(alert, animated: true) { } } func failureCustom(error: NSError) { let title = "Speech to Text Error:\nStreaming (Custom)" let message = error.localizedDescription let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default) { action in self.startStopStreamingCustomButton.enabled = true self.startStopStreamingCustomButton.setTitle("Start Streaming (Custom)", forState: .Normal) self.isStreamingCustom = false } alert.addAction(ok) presentViewController(alert, animated: true) { } } func showResults(results: [TranscriptionResult]) { var text = "" for result in results { if let transcript = result.alternatives.last?.transcript where result.final == true { let title = titleCase(transcript) text += String(title.characters.dropLast()) + "." + " " } } if results.last?.final == false { if let transcript = results.last?.alternatives.last?.transcript { text += titleCase(transcript) } } self.transcriptionField.text = text } func titleCase(s: String) -> String { let first = String(s.characters.prefix(1)).uppercaseString return first + String(s.characters.dropFirst()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
2c87ad1c63bc6767bc37218e94c41282
35.154255
100
0.621304
5.343553
false
false
false
false
machelix/ios9-splitscreen-sample
ios9/MainViewController_iPhone.swift
2
1777
// // MainViewController_iPhone.swift // ios9 // // Created by Ono Masashi on 2015/06/15. // Copyright © 2015年 akisute. All rights reserved. // import UIKit class MainViewController_iPhone: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var layoutSize: CGSize = CGSizeZero override func viewDidLoad() { super.viewDidLoad() self.view.translatesAutoresizingMaskIntoConstraints = false } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.layoutSize = self.view.bounds.size } // MARK: - UITableViewDelegate, UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) cell.textLabel?.text = "Compact" cell.detailTextLabel?.text = (self.layoutSize.width < self.layoutSize.height) ? "Portrait" : "Landscape" return cell } // MARK: - UIContentContainer override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) self.layoutSize = size self.tableView.beginUpdates() self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Fade) self.tableView.endUpdates() } }
mit
11c0bc2bbdd7fd00b9b0a5b6da0c1846
32.471698
136
0.699549
5.425076
false
false
false
false
hydrantwiki/hwIOSApp
hwIOSApp/hwIOSApp/PositionDTO.swift
1
1302
// // PositionDTO.swift // hwIOSApp // // Created by Brian Nelson on 11/2/15. // Copyright © 2015 Brian Nelson. All rights reserved. // import Foundation import ObjectMapper public struct PositionDTO : Mappable { var Latitude:Double? var Longitude:Double? var Altitude:Double? var Accuracy:Double? var DeviceDateTime:NSDate? var WasAveraged:Bool = false public init?(_ map: Map) { } init(location:Location, wasAveraged:Bool) { self.Latitude = location.latitude; self.Longitude = location.longitude; self.Altitude = location.elevation; self.Accuracy = location.accuracy; self.DeviceDateTime = NSDate(); self.WasAveraged = wasAveraged; } mutating public func mapping(map: Map) { Latitude <- map["Latitude"]; Longitude <- map["Longitude"]; Altitude <- map["Altitude"]; Accuracy <- map["Accuracy"]; WasAveraged <- map["WasAveraged"]; DeviceDateTime <- (map["DeviceDateTime"], ISO8601DateTransform()); } public func GetLocationString() -> String { return "Latitude: " + String(self.Latitude) + ", Longitude: " + String(self.Longitude); } }
mit
ee8d854f023cad0d9c8a53b3b66a9553
25.04
95
0.588778
4.251634
false
false
false
false
ozpopolam/DoctorBeaver
DoctorBeaver/ImagePickerOptionsPopoverController.swift
1
2052
// // ImagePickerOptionsPopoverController.swift // // Created by Anastasia Stepanova-Kolupakhina on 23.04.16. // Copyright © 2016 Anastasia Stepanova-Kolupakhina. All rights reserved. // import UIKit protocol ImagePickerOptionsPopoverControllerDelegate: class { func popoverDidPickTakingPhotoWithCamera() func popoverDidPickGettingPhotoFromLibrary() } class ImagePickerOptionsPopoverController: UIViewController { @IBOutlet weak var cameraButton: UIButton! @IBOutlet weak var photoLibraryButton: UIButton! weak var delegate: ImagePickerOptionsPopoverControllerDelegate? var filledWidth: CGFloat? var filledHeight: CGFloat? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() cameraButton.setTitle("Сделать фото", forState: .Normal) photoLibraryButton.setTitle("Выбрать из галереи", forState: .Normal) calculateFilledWidthAndHeight() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func calculateFilledWidthAndHeight() { let margin: CGFloat = 8.0 var widestControlWidth: CGFloat = 0.0 var lowestControlButton: CGFloat = 0.0 let controls: [UIView] = [cameraButton, photoLibraryButton] for control in controls { if control.frame.size.width > widestControlWidth { widestControlWidth = control.frame.size.width } let controlBottomY = control.frame.origin.y + control.frame.size.height - 1 if controlBottomY > lowestControlButton { lowestControlButton = controlBottomY } } filledWidth = widestControlWidth filledHeight = margin + cameraButton.frame.height + margin + photoLibraryButton.frame.height + margin } @IBAction func takePhotoWithCamera(sender: UIButton) { delegate?.popoverDidPickTakingPhotoWithCamera() } @IBAction func getPhotoFromLibrary(sender: UIButton) { delegate?.popoverDidPickGettingPhotoFromLibrary() } }
mit
9dea977b6c0c42fe433dadf760cd6a47
26.739726
105
0.725296
4.819048
false
false
false
false
bestwpw/VoiceMemos
VoiceMemos/View/KMVoiceRecordHUD.swift
2
1559
// // KMVoiceRecordHUD.swift // VoiceMemos // // Created by Zhouqi Mo on 2/24/15. // Copyright (c) 2015 Zhouqi Mo. All rights reserved. // import UIKit @IBDesignable class KMVoiceRecordHUD: UIView { @IBInspectable var rate: CGFloat = 0.0 @IBInspectable var fillColor: UIColor = UIColor.greenColor() { didSet { setNeedsDisplay() } } var image: UIImage! { didSet { setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) image = UIImage(named: "Mic") } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) image = UIImage(named: "Mic") } func update(rate: CGFloat) { self.rate = rate setNeedsDisplay() } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextTranslateCTM(context, 0, bounds.size.height) CGContextScaleCTM(context, 1, -1) CGContextDrawImage(context, bounds, image.CGImage) CGContextClipToMask(context, bounds, image.CGImage) CGContextSetFillColor(context, CGColorGetComponents(fillColor.CGColor)) CGContextFillRect(context, CGRectMake(0, 0, bounds.width, bounds.height * rate)) } override func prepareForInterfaceBuilder() { let bundle = NSBundle(forClass: self.dynamicType) image = UIImage(named: "Mic", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) } }
mit
ccc4779fa76cda1687ef2b796ff8ab70
26.350877
108
0.625401
4.653731
false
false
false
false
yujinjcho/movie_recommendations
ios_ui/MovieRec/Classes/Modules/Recommend/Application Logic/Manager/RecommendDataManager.swift
1
3207
// // RecommendDataManager.swift // MovieRec // // Created by Yujin Cho on 10/8/17. // Copyright © 2017 Yujin Cho. All rights reserved. // import Foundation class RecommendDataManager : NSObject { var rateDataManager : RateDataManager? var networkManager : NetworkManager? let host = "https://movie-rec-project.herokuapp.com" let defaultUser = "test_user_03" var currentUser: String { if let userID = UserDefaults.standard.string(forKey: "userID") { return userID } else { return defaultUser } } var recommendationStorePath = RecommendationStore.ArchiveURL.path func fetchRatings() -> [Rating] { if let rateDataManager = rateDataManager { return rateDataManager.ratings } else { return [] } } func fetchRecommendations() -> [Recommendation] { if let recommendationsFromDisk = loadRecommendationsFromDisk(path: recommendationStorePath) { return recommendationsFromDisk.map { Recommendation(movieTitle: $0.movieTitle) } } else { return [] } } private func loadRecommendationsFromDisk(path: String) -> [RecommendationStore]? { return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [RecommendationStore] } func fetchJobStatus(jobID: String, completion: @escaping (Data) -> Void) { let url = "\(host)/api/job_poll/\(jobID)" if let networkManager = networkManager { networkManager.getRequest(endPoint: url, completionHandler: completion) } } func uploadRatings(ratings: [Rating], completion: @escaping (String) -> Void) { let url = "\(host)/api/recommendations" let uploadData = formatPostData(ratings: ratings) if let networkManager = networkManager { networkManager.postRequest(endPoint: url, postData: uploadData) { (data : Data) in let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) if let responseJSON = responseJSON as? [String: String] { print("job id: \(responseJSON["job_id"]!)") completion(responseJSON["job_id"]!) } } } } func storeRecommendations(recommendations: [Recommendation]) { saveCurrentRecommendationsStateToDisk(recommendations: recommendations, path: recommendationStorePath) } private func saveCurrentRecommendationsStateToDisk(recommendations: [Recommendation], path: String) { let recommendationsToStore = recommendations.map { RecommendationStore(movieTitle: $0.movieTitle) } NSKeyedArchiver.archiveRootObject(recommendationsToStore, toFile: path) } private func formatPostData(ratings : [Rating]) -> [String : Any] { let uploadRatings = ratings.map({ (rating:Rating) -> [String:String] in [ "movie_id": rating.movieID, "rating": rating.rating] }) let postData : [String: Any] = [ "user_id": currentUser, "ratings": uploadRatings ] return postData } }
mit
b59db8bcfd6bb57b13800782a292dcb1
35.022472
110
0.626014
4.835596
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/roman-to-integer.swift
2
887
/** * Problem Link: https://leetcode.com/problems/roman-to-integer/ * * */ class Solution { func romanToInt(_ s: String) -> Int { let currency = [ "M" : 1000, "CM" : 900, "D" : 500, "CD" : 400, "C" : 100, "XC" : 90, "L" : 50, "XL" : 40, "X" : 10, "IX" : 9, "V" : 5, "IV" : 4, "I" : 1] let list = s.characters.map() {"\($0)"} var num = 0 var i = 0 while i < list.count { if i + 1 < list.count, let x = currency[list[i]], let y = currency[list[i+1]], x < y { num += currency[list[i] + list[i+1]]! i += 2 } else { num += currency[list[i]]! i += 1 } } return num } }
mit
be90dbb37221ebde328882b6d41c9db8
23.638889
98
0.335964
3.505929
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/Create/Sections/ConversationCreateGuestsSectionController.swift
1
1600
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit class ConversationCreateGuestsSectionController: ConversationCreateSectionController { typealias Cell = ConversationCreateGuestsCell var toggleAction: ((Bool) -> Void)? override func prepareForUse(in collectionView: UICollectionView?) { super.prepareForUse(in: collectionView) collectionView.flatMap(Cell.register) headerHeight = 40 footerText = "conversation.create.guests.subtitle".localized } } extension ConversationCreateGuestsSectionController { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(ofType: Cell.self, for: indexPath) self.cell = cell cell.setUp() cell.configure(with: values) cell.action = toggleAction return cell } }
gpl-3.0
cc45a6335bd6ae791c0ab135fe4ae532
34.555556
130
0.735625
4.804805
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/GoldenQuranSwift/Constants.swift
1
5487
// // Constants.swift // GoldenQuranSwift // // Created by Omar Fraiwan on 2/12/17. // Copyright © 2017 Omar Fraiwan. All rights reserved. // import Foundation import UIKit struct Constants { static let iOS_LANGUAGES_KEY = "AppleLanguages" static let CURRENT_MUSHAF_KEY = "CurrentMushafGUID" struct color { static let GQBrown = UIColor(red:152.0/255.0 , green:111.0/255.0 , blue:65.0/255.0 , alpha:1.0) as UIColor } struct path { static let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String static let library = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as String static let tmp = NSTemporaryDirectory() } struct db { static let defaultMus7afList = "Mus7af" static var defaultMus7afListDBPath:String{ get{ return Bundle.main.path(forResource: Constants.db.defaultMus7afList, ofType: "db")!} } static var userMus7afListDBPath:String{ get{ return Constants.path.library.appending("/\(Constants.db.defaultMus7afList).db")} } static func mushafWithDBName(name:String) -> String{ var verifiedName:String = name var dbExtenstion:String = "db" if name.lowercased().hasSuffix(".db") { let range = name.lowercased().range(of: ".db") verifiedName = name.replacingCharacters(in: range!, with: "") dbExtenstion = name.components(separatedBy: ".").last! } return Bundle.main.path(forResource: verifiedName, ofType: dbExtenstion, inDirectory: "GoldenQuranRes/db")! } static var mushafByTopicDBPath:String{ get{ return Bundle.main.path(forResource: "QuranMawdoo3", ofType: "db", inDirectory: "GoldenQuranRes/db/Additions")!} } static var mushafTextDBPath:String{ get{ return Bundle.main.path(forResource: "quran_text_ar", ofType: "db", inDirectory: "GoldenQuranRes/db")!} } static var mushafMo3jamDBPath:String{ get{ return Bundle.main.path(forResource: "QuranMo3jm", ofType: "db", inDirectory: "GoldenQuranRes/db/Additions")!} } static var hadithFortyDBPath:String{ get{ return Bundle.main.path(forResource: "HadithContent", ofType: "db", inDirectory: "GoldenQuranRes/db")!} } static var mushafRecitationAndTafseerDBPath:String{ get{return Bundle.main.path(forResource: "TafseerAndRecitation", ofType: "db")!} } } struct storyboard { static let main = UIStoryboard(name:"main" , bundle:nil) static let mushaf = UIStoryboard(name:"Mushaf" , bundle:nil) } struct notifiers { static let pageColorChanged = "PAGE_COLOR_CHANGED" static let pageHighlightTopicsChanged = "PAGE_HIGHLIGHT_TOPICS_CHANGED" } struct userDefaultsKeys { //Notifications static let notificationsFridayDisabled = "NOTIFICATIONS_FRIDAY_DISABLED" static let notificationsLongTimeReadingDisabled = "NOTIFICATIONS_LONG_TIME_READING_DISABLED" static let notificationsDailyDisabled = "NOTIFICATIONS_DAILY_DISABLED" static let notificationsAthanDisabled = "NOTIFICATIONS_ATHAN_DISABLED" //Notifications Athan (notification by time) static let notificationsAthanFajrDisabled = "NOTIFICATIONS_ATHAN_DISABLED_FAJR" static let notificationsAthanDouhrDisabled = "NOTIFICATIONS_ATHAN_DISABLED_DUHOR" static let notificationsAthanAsrDisabled = "NOTIFICATIONS_ATHAN_DISABLED_ASR" static let notificationsAthanMaghribDisabled = "NOTIFICATIONS_ATHAN_DISABLED_MAGHRIB" static let notificationsAthanIshaDisabled = "NOTIFICATIONS_ATHAN_DISABLED_ISHA" ///Location Manager static let lastKnownLocationLat = "LOCATION_LAST_KNOWN_LAT" static let lastKnownLocationLon = "LOCATION_LAST_KNOWN_LON" //Prayer Times static let prayerTimesAdjustmentFajr = "PrayerTimesAdjustments_fajr" static let prayerTimesAdjustmentSunrise = "PrayerTimesAdjustments_sunrise" static let prayerTimesAdjustmentDhuhr = "PrayerTimesAdjustments_dhuhr" static let prayerTimesAdjustmentAsr = "PrayerTimesAdjustments_asr" static let prayerTimesAdjustmentMagrib = "PrayerTimesAdjustments_maghrib" static let prayerTimesAdjustmentIsha = "PrayerTimesAdjustments_isha" static let prayerTimesSettingsCalculationMethod = "PrayerTimesSettingsCalcultionMethod" static let prayerTimesSettingsCalculationMadhab = "PrayerTimesSettingsCalcultionMadhab" static let prayerTimesSettingsNotificationSound = "PrayerTimesSettingsNotificationSound" //// Features menu static let highlightMushafByTopicsEnabled = "highlightMushafByTopicsEnabled" /////Page color static let preferedPageBackgroundColor = "PreferedPageBackgroundColor" /////Font size static let preferedFontSize = "PreferedFontSize" //Recitations static let favouriteRecitations = "FavoriteRecitations" //Tafseers static let favouriteTafseers = "FavoriteTafseers" static let activeTafseer = "ActiveTafseer" } }
mit
7263b1a3c9f3747b10335877620a30f6
41.527132
129
0.671163
4.427764
false
false
false
false
wireapp/wire-ios-sync-engine
Source/Synchronization/Strategies/LabelDownstreamRequestStrategy.swift
1
6049
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation struct LabelUpdate: Codable, Equatable { let id: UUID let type: Int16 let name: String? let conversations: [UUID] init(id: UUID, type: Int16, name: String?, conversations: [UUID]) { self.id = id self.type = type self.name = name self.conversations = conversations } init?(_ label: Label) { guard let remoteIdentifier = label.remoteIdentifier else { return nil } self = .init(id: remoteIdentifier, type: label.kind.rawValue, name: label.name, conversations: label.conversations.compactMap(\.remoteIdentifier)) } } struct LabelPayload: Codable, Equatable { var labels: [LabelUpdate] } public class LabelDownstreamRequestStrategy: AbstractRequestStrategy, ZMEventConsumer, ZMSingleRequestTranscoder { fileprivate let syncStatus: SyncStatus fileprivate var slowSync: ZMSingleRequestSync! fileprivate let jsonDecoder = JSONDecoder() public init(withManagedObjectContext managedObjectContext: NSManagedObjectContext, applicationStatus: ApplicationStatus, syncStatus: SyncStatus) { self.syncStatus = syncStatus super.init(withManagedObjectContext: managedObjectContext, applicationStatus: applicationStatus) self.configuration = [.allowsRequestsDuringSlowSync, .allowsRequestsDuringQuickSync, .allowsRequestsWhileWaitingForWebsocket, .allowsRequestsWhileOnline] self.slowSync = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: managedObjectContext) } override public func nextRequestIfAllowed(for apiVersion: APIVersion) -> ZMTransportRequest? { guard syncStatus.currentSyncPhase == .fetchingLabels || ZMUser.selfUser(in: managedObjectContext).needsToRefetchLabels else { return nil } slowSync.readyForNextRequestIfNotBusy() return slowSync.nextRequest(for: apiVersion) } func update(with transportData: Data) { guard let labelResponse = try? jsonDecoder.decode(LabelPayload.self, from: transportData) else { Logging.eventProcessing.error("Can't apply label update due to malformed JSON") return } update(with: labelResponse) } func update(with response: LabelPayload) { updateLabels(with: response) deleteLabels(with: response) } fileprivate func updateLabels(with response: LabelPayload) { for labelUpdate in response.labels { var created = false let label: Label? if labelUpdate.type == Label.Kind.favorite.rawValue { label = Label.fetchFavoriteLabel(in: managedObjectContext) } else { label = Label.fetchOrCreate(remoteIdentifier: labelUpdate.id, create: true, in: managedObjectContext, created: &created) } label?.kind = Label.Kind(rawValue: labelUpdate.type) ?? .folder label?.name = labelUpdate.name label?.conversations = ZMConversation.fetchObjects(withRemoteIdentifiers: Set(labelUpdate.conversations), in: managedObjectContext) as? Set<ZMConversation> ?? Set() label?.modifiedKeys = nil } } fileprivate func deleteLabels(with response: LabelPayload) { let uuids: [NSData] = response.labels.map({ $0.id.uuidData as NSData }) let predicate = NSPredicate(format: "type == \(Label.Kind.folder.rawValue) AND NOT remoteIdentifier_data IN %@", uuids as CVarArg) let fetchRequest = NSFetchRequest<Label>(entityName: Label.entityName()) fetchRequest.predicate = predicate let deletedLabels = managedObjectContext.fetchOrAssert(request: fetchRequest) deletedLabels.forEach { managedObjectContext.delete($0) } // TODO jacob consider doing a batch delete managedObjectContext.saveOrRollback() } // MARK: - ZMEventConsumer public func processEvents(_ events: [ZMUpdateEvent], liveEvents: Bool, prefetchResult: ZMFetchRequestBatchResult?) { for event in events { guard event.type == .userPropertiesSet, (event.payload["key"] as? String) == "labels" else { continue } guard let value = event.payload["value"], let data = try? JSONSerialization.data(withJSONObject: value, options: []) else { Logging.eventProcessing.error("Skipping label update due to missing value field") continue } update(with: data) } } // MARK: - ZMSingleRequestTranscoder public func request(for sync: ZMSingleRequestSync, apiVersion: APIVersion) -> ZMTransportRequest? { return ZMTransportRequest(getFromPath: "/properties/labels", apiVersion: apiVersion.rawValue) } public func didReceive(_ response: ZMTransportResponse, forSingleRequest sync: ZMSingleRequestSync) { guard response.result == .permanentError || response.result == .success else { return } if response.result == .success, let rawData = response.rawData { update(with: rawData) } if syncStatus.currentSyncPhase == .fetchingLabels { syncStatus.finishCurrentSyncPhase(phase: .fetchingLabels) } ZMUser.selfUser(in: managedObjectContext).needsToRefetchLabels = false } }
gpl-3.0
f7cf5d89f1eefbc6b36dcdf98b435fb8
38.796053
176
0.685403
4.999174
false
false
false
false
victorpimentel/SwiftLint
Source/SwiftLintFramework/Rules/RuleConfigurations/PrivateUnitTestConfiguration.swift
2
2796
// // PrivateUnitTestConfiguration.swift // SwiftLint // // Created by Cristian Filipov on 8/5/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct PrivateUnitTestConfiguration: RuleConfiguration, Equatable, CacheDescriptionProvider { public let identifier: String public var name: String? public var message = "Regex matched." public var regex: NSRegularExpression! public var included: NSRegularExpression? public var severityConfiguration = SeverityConfiguration(.warning) public var severity: ViolationSeverity { return severityConfiguration.severity } public var consoleDescription: String { return "\(severity.rawValue): \(regex.pattern)" } internal var cacheDescription: String { var dict = [String: Any]() dict["identifier"] = identifier dict["name"] = name dict["message"] = message dict["regex"] = regex.pattern dict["included"] = included?.pattern dict["severity"] = severityConfiguration.consoleDescription if let jsonData = try? JSONSerialization.data(withJSONObject: dict), let jsonString = String(data: jsonData, encoding: .utf8) { return jsonString } fatalError("Could not serialize private unit test configuration for cache") } public var description: RuleDescription { return RuleDescription(identifier: identifier, name: name ?? identifier, description: "") } public init(identifier: String) { self.identifier = identifier } public mutating func apply(configuration: Any) throws { guard let configurationDict = configuration as? [String: Any] else { throw ConfigurationError.unknownConfiguration } if let regexString = configurationDict["regex"] as? String { regex = try .cached(pattern: regexString) } if let includedString = configurationDict["included"] as? String { included = try .cached(pattern: includedString) } if let name = configurationDict["name"] as? String { self.name = name } if let message = configurationDict["message"] as? String { self.message = message } if let severityString = configurationDict["severity"] as? String { try severityConfiguration.apply(configuration: severityString) } } } public func == (lhs: PrivateUnitTestConfiguration, rhs: PrivateUnitTestConfiguration) -> Bool { return lhs.identifier == rhs.identifier && lhs.message == rhs.message && lhs.regex == rhs.regex && lhs.included?.pattern == rhs.included?.pattern && lhs.severity == rhs.severity }
mit
d448bec3837638f4523bfa7d9aae8769
34.379747
100
0.658318
5.008961
false
true
false
false
BackNotGod/localizationCommand
Sources/localizationCommand/main.swift
1
3241
import Foundation import CommandLineKit import PathKit import Spectre import Rainbow import commandService /** Description - exceptPath: drop path without scan - projectPath: path - help: help infomataion - version: version - a / -r : defalut is -r (append or replace) */ let cli = CommandLineKit.CommandLine() let help = BoolOption(shortFlag: "h", longFlag: "help", helpMessage: "Prints a help message.") let exceptPath = MultiStringOption(shortFlag: "e", longFlag: "exceptPath", helpMessage: "exceptPath paths which should not search in.") let projectPath = StringOption(shortFlag: "p", longFlag: "projectPath", helpMessage: "projectPath paths which should search in.") let version = BoolOption(shortFlag: "v", longFlag: "version", helpMessage: "version.") let localizationName = StringOption(shortFlag: "n", longFlag: "localizationName", helpMessage: "Your localizatoin.string name (may be differential)") //let swift = BoolOption(shortFlag: "s", longFlag: "swift", // helpMessage: "will scan code files of *.swift.") //let oc = BoolOption(shortFlag: "m", longFlag: "oc", // helpMessage: "will scan code files of *.m.") // not in this time let appendOpt = BoolOption(shortFlag: "a", longFlag: "append", helpMessage: "append to the file context.") let replaceOpt = BoolOption(shortFlag: "r", longFlag: "replace", helpMessage: "replace to the file context.") cli.setOptions(help,exceptPath,projectPath,version,appendOpt,replaceOpt,localizationName) cli.formatOutput = { s,type in var str: String switch(type) { case .error: str = s.red.bold case .optionFlag: str = s.green.underline case .optionHelp: str = s.lightBlue default: str = s } return cli.defaultFormat(s: str, type: type) } do { try cli.parse() } catch { cli.printUsage(error) exit(EX_USAGE) } if version.value { print("1.0.3".blue) exit(EX_USAGE) } if help.value{ cli.printUsage() exit(EX_USAGE) } if localizationName.value == nil { print("Sorry,Your localizationName is empty,Please enter your localizationName on your root proj path.".red) exit(EX_USAGE) } if projectPath.value == nil { print("your projectPath input empty , if you want to do this , projectPath will be current path!".yellow) print("you wan to do this ? (y/n) or enter to skip.".red) let respond = readLine() if let res = respond { if res == "n"{ exit(EX_USAGE) } } } if exceptPath.value == nil { print("your exceptPath input empty , if you want to do this , we will scan all of this directory and extract the localization str.".yellow) print("you wan to do this (y/n) or enter to skip?".red) let respond = readLine() if let res = respond { if res == "n"{ exit(EX_USAGE) } } } var commandService = localizationCommand.init(projPath: projectPath.value ?? FileManager.default.currentDirectoryPath, except: exceptPath.value ?? [],localizationName: localizationName.value ?? "") writeAppend = appendOpt.value writeReplace = replaceOpt.value commandService.findTargetPath()
mit
4062e1798a1be027d5f8cf01344cb3c3
29.866667
197
0.663684
3.881437
false
false
false
false
dclelland/Ursus
Ursus/Models/Serialization/UrsusDecoder.swift
1
2608
// // UrsusDecoder.swift // Alamofire // // Created by Daniel Clelland on 13/06/20. // import Foundation public class UrsusDecoder: JSONDecoder { public override init() { super.init() self.dateDecodingStrategy = .millisecondsSince1970 self.dataDecodingStrategy = .jsonObject self.keyDecodingStrategy = .convertFromKebabCase } public override func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable { userInfo[.jsonObject] = try JSONSerialization.jsonObject(with: data) let result = try super.decode(type, from: data) userInfo[.jsonObject] = nil return result } } extension JSONDecoder.DataDecodingStrategy { public static var jsonObject: JSONDecoder.DataDecodingStrategy { return .custom { decoder -> Data in let jsonObject: Any? = decoder.codingPath.reduce(decoder.userInfo[.jsonObject]) { result, codingKey in switch codingKey.intValue { case .some(let intValue): return (result as? [Any])?[intValue] case .none: return (result as? [String: Any])?[codingKey.stringValue] } } return try JSONSerialization.data(withJSONObject: jsonObject as Any) } } } extension JSONDecoder.KeyDecodingStrategy { public static var convertFromKebabCase: JSONDecoder.KeyDecodingStrategy { return .custom { codingKeys -> CodingKey in let codingKey = codingKeys.last! switch codingKey.intValue { case .some(let intValue): return CamelCasedCodingKey(intValue: intValue)! case .none: return CamelCasedCodingKey(stringValue: codingKey.stringValue)! } } } } private struct CamelCasedCodingKey: CodingKey { var stringValue: String var intValue: Int? init?(stringValue: String) { self.stringValue = stringValue.convertFromKebabCase self.intValue = nil } init?(intValue: Int) { self.stringValue = String(intValue) self.intValue = intValue } } extension String { internal var convertFromKebabCase: String { let pascalCase = capitalized.replacingOccurrences(of: "-", with: "") return pascalCase.first?.lowercased().appending(pascalCase.dropFirst()) ?? "" } } extension CodingUserInfoKey { internal static let jsonObject = CodingUserInfoKey(rawValue: "jsonObject")! }
mit
657ac42027044ed83b6102b4fbc18460
26.744681
114
0.616181
4.958175
false
false
false
false
elationfoundation/Reporta-iOS
IWMF/Modal/Circle.swift
1
1858
// // Circle.swift // IWMF // // This class is used for Store circle detail. // // import Foundation enum CircleType: Int { case Private = 1 case Public = 2 case Social = 3 } class Circle: NSObject { var circleName: String! var circleType: CircleType! var contactsList: NSMutableArray! override init() { circleName = "" circleType = .Private contactsList = NSMutableArray() super.init() } init(name:String, type:CircleType, contactList:NSMutableArray ){ self.circleName = name; circleType = type; contactsList = contactList super.init() } required init(coder aDecoder: NSCoder) { self.circleName = aDecoder.decodeObjectForKey("circleName") as! String self.contactsList = aDecoder.decodeObjectForKey("contactsList") as! NSMutableArray let circleTypeValue = Int(aDecoder.decodeObjectForKey("circleType") as! NSNumber) if circleTypeValue == 1 { self.circleType = CircleType.Private } else if circleTypeValue == 2 { self.circleType = CircleType.Public } else if circleTypeValue == 3 { self.circleType = CircleType.Social } } func encodeWithCoder(aCoder: NSCoder) { if let circleName = self.circleName{ aCoder.encodeObject(circleName, forKey: "circleName") } if let contactsList = self.contactsList{ aCoder.encodeObject(contactsList, forKey: "contactsList") } let circleTypeValue = NSNumber(integer: self.circleType.rawValue) aCoder.encodeObject(circleTypeValue, forKey: "circleType") } func insertContactsListInCircle(conList: ContactList){ self.contactsList.addObject(conList) } }
gpl-3.0
beb603eae722021aa535c58f9f28859e
26.746269
91
0.617869
4.487923
false
false
false
false
ioscreator/ioscreator
SwiftUIPreviewDevicesTutorial/SwiftUIPreviewDevicesTutorial/SceneDelegate.swift
1
2788
// // SceneDelegate.swift // SwiftUIPreviewDevicesTutorial // // Created by Arthur Knopper on 18/09/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
0a051e8cf441be1d2dfc6ebeefb8ee8e
42.546875
147
0.706494
5.359615
false
false
false
false
coderQuanjun/PigTV
GYJTV/GYJTV/Classes/Main/TQJPageView/TQJCollectionView.swift
1
6719
// // TQJCollectionView.swift // GYJTV // // Created by 田全军 on 2017/5/15. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit protocol TQJCollectionViewDateSource : class { func numberOfSections(in pageCollectionView : TQJCollectionView) -> Int func pageCollectionView(_ collectionView : TQJCollectionView, numberOfItemsInSection section : Int) -> Int func pageCollectionView(_ pageCollectionView : TQJCollectionView, _ collectionView : UICollectionView, cellForItemAt indexPath : IndexPath) -> UICollectionViewCell } protocol TQJCollectionViewDelegate : class { func pageCollectionView(_ pageCollectionView : TQJCollectionView, didSelectorItemAt indexPath : IndexPath) } private let kCollectionViewCell = "kCollectionViewCell" class TQJCollectionView: UIView { // MARK: 代理 weak var dataSource : TQJCollectionViewDateSource? weak var delegate : TQJCollectionViewDelegate? // MARK: 页面属性 fileprivate var style : TQJTitleStyle fileprivate var titles : [String] fileprivate var isTitleInTop : Bool fileprivate var layout : TQJPageCollectionLayout fileprivate var collectionView : UICollectionView! fileprivate var pageControl : UIPageControl! fileprivate var titleView : TQJTitleView! fileprivate var sourceIndexPath : IndexPath = IndexPath(item: 0, section: 0) init(frame: CGRect, style : TQJTitleStyle, titles : [String], isTitleInTop : Bool, layout : TQJPageCollectionLayout) { self.style = style self.titles = titles self.isTitleInTop = isTitleInTop self.layout = layout super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: 界面搭建 extension TQJCollectionView{ fileprivate func setupUI(){ //1.创建titleView let titleViewY = isTitleInTop ? 0 : bounds.height - style.titleHeight titleView = TQJTitleView(frame: CGRect(x: 0, y: titleViewY, width: bounds.width, height: style.titleHeight), titles: titles, style: style) titleView.delegate = self addSubview(titleView) //2.创建pageControl let pageControllHeight : CGFloat = 20 let pageControlY = isTitleInTop ? bounds.height - pageControllHeight : bounds.height - pageControllHeight - style.titleHeight pageControl = UIPageControl(frame: CGRect(x: 0, y: pageControlY , width: bounds.width, height: pageControllHeight)) pageControl.pageIndicatorTintColor = UIColor.lightGray pageControl.currentPageIndicatorTintColor = UIColor.orange addSubview(pageControl) //3.创建collectionView let collectionViewY = isTitleInTop ? style.titleHeight : 0 collectionView = UICollectionView(frame: CGRect(x: 0, y: collectionViewY, width: bounds.width, height: bounds.height - style.titleHeight - pageControllHeight), collectionViewLayout: layout) collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCollectionViewCell) addSubview(collectionView) pageControl.backgroundColor = collectionView.backgroundColor } } // MARK: 对外暴露的方法 extension TQJCollectionView{ func register(cell : AnyClass?, identifier : String) { collectionView.register(cell, forCellWithReuseIdentifier: identifier) } func register(nib : UINib, identifier : String) { collectionView.register(nib, forCellWithReuseIdentifier: identifier) } func reloadData() { collectionView.reloadData() } } // MARK: UICollectionViewDataSource extension TQJCollectionView : UICollectionViewDataSource{ func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource?.numberOfSections(in: self) ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let itemCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: section) ?? 0 if section == 0 { pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1 } return itemCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return dataSource!.pageCollectionView(self, collectionView, cellForItemAt: indexPath) } } // MARK: UICollectionVIewDelegate extension TQJCollectionView : UICollectionViewDelegate{ //结束减速 func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewEndScroll() } //结束滑动 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { scrollViewEndScroll() } fileprivate func scrollViewEndScroll(){ //取出在屏幕中显示的cell let point = CGPoint(x: layout.sectionInset.left + collectionView.contentOffset.x + 1, y: layout.sectionInset.top + 1) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } //判断分组是否发生改变 if sourceIndexPath.section != indexPath.section { //修改pageController的个数 let itemCOunt = dataSource?.pageCollectionView(self, numberOfItemsInSection: indexPath.section) ?? 0 pageControl.numberOfPages = (itemCOunt - 1) / (layout.cols * layout.rows) + 1 //设置titleView的位置 titleView.setTitleWithProgress(1.0, sourceIndex: sourceIndexPath.section, targetIndex: indexPath.section) //记录 sourceIndexPath = indexPath } // 3.根据indexPath设置pageControl pageControl.currentPage = indexPath.item / (layout.cols * layout.rows) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.pageCollectionView(self, didSelectorItemAt: indexPath) } } // MARK: TQJTitleViewDelegate extension TQJCollectionView : TQJTitleViewDelegate{ func titleView(_ titleView: TQJTitleView, selectedIndex index: Int) { let indexPath = IndexPath(item: 0, section: index) //此处若为true,则会重新调用EndDecelerating和EndDragging方法 collectionView.scrollToItem(at: indexPath, at: .left, animated: false) collectionView.contentOffset.x -= layout.sectionInset.left scrollViewEndScroll() } }
mit
7e38fe4b3f8901e6ad53264dac0ead26
40.468354
197
0.709707
4.98251
false
false
false
false
wangjianquan/wjq-weibo
weibo_wjq/Tool/Common.swift
1
994
// // Common.swift // weibo_wjq // // Created by landixing on 2017/5/28. // Copyright © 2017年 WJQ. All rights reserved. // import Foundation /// OAuth授权需要的key let WB_App_Key = "53729570" /// OAuth授权需要的Secret let WB_App_Secret = "cc23ae6e7f115b52c6c944a0d81057c0" /// OAuth授权需要的重定向地址 let WB_Redirect_uri = "http://www.baidu.com" let accossToken = "2.00S2yPcC0yV8dDddc8ac5f76xEIoDC" // MARK: - 本地通知 /// 自定转场展现 let XMGPresentationManagerDidPresented = "XMGPresentationManagerDidPresented" /// 自定义转场消失 let XMGPresentationManagerDidDismissed = "XMGPresentationManagerDismissed" // 跳转viewController let SwitchRootViewController = "SwitchRootViewController" // 通知常量 let showPhotoBrowserNotification = "showPhotoBrowserNotification" let showPhotoBrowserNotificationURLs = "showPhotoBrowserNotificationURLs" let showPhotoBrowserNotificationIndexPath = "showPhotoBrowserNotificationIndexPath"
apache-2.0
f0ca8ce083b4f87d0d2aba2bc4c21ac2
19.568182
83
0.790055
3.351852
false
false
false
false
leotao2014/RTPhotoBrowser
RTPhotoBrowser/RTPhotoModel.swift
1
1148
// // RTPhotoModel.swift // RTPhotoBrowser // // Created by leotao on 2017/2/26. // Copyright © 2017年 leotao. All rights reserved. // import UIKit enum RTImageDownloadPriority { case high case low case cancel } class RTPhotoModel: NSObject { var picUrl:String = ""; // 图片地址 var originalPicUrl:String? var downloadPriority = RTImageDownloadPriority.high var index:Int = 0; var viewOriginalPic:Bool { get { guard let ogUrl = originalPicUrl else { return false } let cacheKey = UserDefaults.standard.object(forKey: ogUrl); return cacheKey != nil; } set { if let url = originalPicUrl { if newValue { UserDefaults.standard.set("true", forKey: url); } else { UserDefaults.standard.removeObject(forKey: url); } } } } init(picUrls: (picUrl:String, originalPicUrl:String?)) { super.init(); picUrl = picUrls.picUrl; originalPicUrl = picUrls.originalPicUrl; } }
apache-2.0
5d11e2d9962e8dad6ebaf8afe79a3c4b
23.717391
71
0.557608
4.424125
false
false
false
false
CosmicMind/Algorithm
Tests/SortedDictionaryTests.swift
1
5758
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import XCTest @testable import Algorithm class SortedDictionaryTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testInt() { var s = SortedDictionary<Int, Int>() XCTAssert(0 == s.count, "Test failed, got \(s.count).") for _ in 0..<1000 { s.insert((1, 1)) s.insert((2, 2)) s.insert((3, 3)) } XCTAssert(3 == s.count, "Test failed.") XCTAssert(1 == s[0].value, "Test failed.") XCTAssert(2 == s[1].value, "Test failed.") XCTAssert(3 == s[2].value, "Test failed.") for _ in 0..<500 { s.removeValue(for: 1) s.removeValue(for: 3) } XCTAssert(1 == s.count, "Test failed.") s.removeValue(for: 2) s.insert((2, 10)) XCTAssert(1 == s.count, "Test failed.") XCTAssert(10 == s.findValue(for: 2), "Test failed.") XCTAssert(10 == s[0].value!, "Test failed.") s.removeValue(for: 2) XCTAssert(0 == s.count, "Test failed.") s.insert((1, 1)) s.insert((2, 2)) s.insert((3, 3)) s.insert((3, 3)) s.update(value: 5, for: 3) let subs: SortedDictionary<Int, Int> = s.search(for: 3) XCTAssert(1 == subs.count, "Test failed.") let generator = subs.makeIterator() while let x = generator.next() { XCTAssert(5 == x.value, "Test failed.") } for i in 0..<s.endIndex { s[i] = (s[i].key, 100) XCTAssert(100 == s[i].value, "Test failed.") } s.removeAll() XCTAssert(0 == s.count, "Test failed.") } func testIndexOf() { var d1 = SortedDictionary<Int, Int>() d1.insert(value: 1, for: 1) d1.insert(value: 2, for: 2) d1.insert(value: 3, for: 3) d1.insert(value: 4, for: 4) d1.insert(value: 5, for: 5) d1.insert(value: 5, for: 5) d1.insert(value: 6, for: 6) XCTAssert(0 == d1.index(of: 1), "Test failed.") XCTAssert(5 == d1.index(of: 6), "Test failed.") XCTAssert(-1 == d1.index(of: 100), "Test failed.") } func testKeys() { let s = SortedDictionary<String, Int>(elements: ("adam", 1), ("daniel", 2), ("mike", 3), ("natalie", 4)) XCTAssert(["adam", "daniel", "mike", "natalie"] == s.keys, "Test failed.") } func testValues() { let s = SortedDictionary<String, Int>(elements: ("adam", 1), ("daniel", 2), ("mike", 3), ("natalie", 4)) let values = [1, 2, 3, 4] XCTAssert(values == s.values, "Test failed.") } func testLowerEntry() { let s = SortedDictionary<Int, Int>(elements: (1, 1), (2, 2), (3, 3), (5, 5), (8, 8), (13, 13), (21, 21), (34, 34)) XCTAssert(s.findLowerEntry(for: -15) == nil, "Test failed.") XCTAssert(s.findLowerEntry(for: 0) == nil, "Test failed.") XCTAssert(s.findLowerEntry(for: 1) == 1, "Test failed.") XCTAssert(s.findLowerEntry(for: 2) == 2, "Test failed.") XCTAssert(s.findLowerEntry(for: 3) == 3, "Test failed.") XCTAssert(s.findLowerEntry(for: 4) == 3, "Test failed.") XCTAssert(s.findLowerEntry(for: 5) == 5, "Test failed.") XCTAssert(s.findLowerEntry(for: 6) == 5, "Test failed.") XCTAssert(s.findLowerEntry(for: 7) == 5, "Test failed.") XCTAssert(s.findLowerEntry(for: 8) == 8, "Test failed.") XCTAssert(s.findLowerEntry(for: 9) == 8, "Test failed.") XCTAssert(s.findLowerEntry(for: 10) == 8, "Test failed.") XCTAssert(s.findLowerEntry(for: 40) == 34, "Test failed.") XCTAssert(s.findLowerEntry(for: 50) == 34, "Test failed.") } func testCeilingEntry() { let s = SortedDictionary<Int, Int>(elements: (1, 1), (2, 2), (3, 3), (5, 5), (8, 8), (13, 13), (21, 21), (34, 34)) XCTAssert(s.findCeilingEntry(for: -15) == 1, "Test failed.") XCTAssert(s.findCeilingEntry(for: 0) == 1, "Test failed.") XCTAssert(s.findCeilingEntry(for: 1) == 1, "Test failed.") XCTAssert(s.findCeilingEntry(for: 2) == 2, "Test failed.") XCTAssert(s.findCeilingEntry(for: 3) == 3, "Test failed.") XCTAssert(s.findCeilingEntry(for: 4) == 5, "Test failed.") XCTAssert(s.findCeilingEntry(for: 5) == 5, "Test failed.") XCTAssert(s.findCeilingEntry(for: 6) == 8, "Test failed.") XCTAssert(s.findCeilingEntry(for: 7) == 8, "Test failed.") XCTAssert(s.findCeilingEntry(for: 8) == 8, "Test failed.") XCTAssert(s.findCeilingEntry(for: 9) == 13, "Test failed.") XCTAssert(s.findCeilingEntry(for: 10) == 13, "Test failed.") XCTAssert(s.findCeilingEntry(for: 40) == nil, "Test failed.") XCTAssert(s.findCeilingEntry(for: 50) == nil, "Test failed.") } }
mit
71b17d62d61755ea0c35949222e16b37
35.675159
118
0.617055
3.290286
false
true
false
false
laszlokorte/reform-swift
ReformCore/ReformCore/DefaultAnalyzer.swift
1
3415
// // DefaultAnalyzer.swift // ReformCore // // Created by Laszlo Korte on 17.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformExpression public struct InstructionOutlineRow { public let node : InstructionNode public let label : String public let depth : Int public let isGroup : Bool } final class AnalyzerStringifier : Stringifier { fileprivate var forms = [FormIdentifier:Form]() fileprivate let expressionPrinter : ExpressionPrinter init(expressionPrinter : ExpressionPrinter) { self.expressionPrinter = expressionPrinter } func labelFor(_ formId: FormIdentifier) -> String? { return forms[formId].map{ $0.name } } func labelFor(_ formId: FormIdentifier, pointId: ExposedPointIdentifier) -> String? { return forms[formId].flatMap { $0.getPoints()[pointId].map { $0.getDescription(self) } } } func labelFor(_ formId: FormIdentifier, anchorId: AnchorIdentifier) -> String? { return forms[formId].flatMap{ ($0 as? Morphable).flatMap { $0.getAnchors()[anchorId].map { $0.name } } } } func stringFor(_ expression: ReformExpression.Expression) -> String? { return expressionPrinter.toString(expression) } } final public class DefaultAnalyzer : Analyzer { public fileprivate(set) var instructions = [InstructionOutlineRow]() public fileprivate(set) var instructionsDblBuf = [InstructionOutlineRow]() private let nameAllocator : NameAllocator private let analyzerStringifier : AnalyzerStringifier public var stringifier : Stringifier { return analyzerStringifier } private var depth: Int = 0 public init(expressionPrinter: ExpressionPrinter, nameAllocator : NameAllocator) { self.analyzerStringifier = AnalyzerStringifier(expressionPrinter: expressionPrinter) self.nameAllocator = nameAllocator } public func analyze(_ block: () -> ()) { analyzerStringifier.forms.removeAll(keepingCapacity: true) instructionsDblBuf.removeAll(keepingCapacity: true) nameAllocator.reset() depth = 0 block() swap(&instructionsDblBuf, &instructions) } public func publish(_ instruction: Analyzable, label: String) { guard let node = instruction as? InstructionNode else { return } instructionsDblBuf.append(InstructionOutlineRow(node: node, label: label, depth: depth, isGroup: false)) } public func publish(_ instruction: Analyzable, label: String, block: () -> ()) { guard let node = instruction as? InstructionNode else { return } // skip root if depth > 0 { instructionsDblBuf.append(InstructionOutlineRow(node: node, label: label, depth: depth, isGroup: true)) } defer { if depth > 0 { instructionsDblBuf.append(InstructionOutlineRow(node: node, label: "", depth: depth, isGroup: true)) } } depth += 1 defer { depth -= 1 } block() } public func announceForm(_ form: Form) { analyzerStringifier.forms[form.identifier] = form nameAllocator.announce(form.name) } public func announceDepencency(_ id: PictureIdentifier) { } }
mit
35e062f308cb8f3d3d87086f6654bf09
29.482143
115
0.640305
4.676712
false
false
false
false
avalanched/Rex
Source/Foundation/NSUserDefaults.swift
2
1273
// // NSUserDefaults.swift // Rex // // Created by Neil Pankey on 5/28/15. // Copyright (c) 2015 Neil Pankey. All rights reserved. // import Foundation import ReactiveCocoa extension NSUserDefaults { /// Sends value of `key` whenever it changes. Attempts to filter out repeats /// by casting to NSObject and checking for equality. If the values aren't /// convertible this will generate events whenever _any_ value in NSUserDefaults /// changes. public func rex_valueForKey(key: String) -> SignalProducer<AnyObject?, NoError> { let center = NSNotificationCenter.defaultCenter() let initial = objectForKey(key) let changes = center.rac_notifications(NSUserDefaultsDidChangeNotification) .map { _ in // The notification doesn't provide what changed so we have to look // it up every time self.objectForKey(key) } return SignalProducer<AnyObject?, NoError>(value: initial) .concat(changes) .skipRepeats { previous, next in if let previous = previous as? NSObject, next = next as? NSObject { return previous == next } return false } } }
mit
4888421949d5720e5d5d58923c441e2e
33.405405
85
0.616654
5.071713
false
false
false
false
LightweightInTouch/LITSwiftToolkit
LITSwiftToolkit/Tools/Extensions/UIKit/UIViewControllerExtensions.swift
2
1438
// // UIViewControllerExtensions.swift // LITSwiftToolkit // // Created by Lobanov Dmitry on 02.11.15. // Copyright © 2015 LightweightInTouch. All rights reserved. // import Foundation import UIKit public extension UIViewController { //MARK: Initialization public static func nibName() -> String { return NSStringFromClass(self) } public static func controllerWithDefaultNibName() -> Self { return self.init(nibName: self.nibName(), bundle: nil) } //MARK: Show/Hide public func showAlert(message: String?, cancel: String?) { let controller = UIAlertController(title: nil, message: message, preferredStyle: .Alert) let cancel = UIAlertAction(title: cancel, style: .Cancel, handler: nil) controller.addAction(cancel) self.presentViewController(controller, animated: true, completion: nil) } //MARK: Navigation public func safeDismiss(animated: Bool = true) { if let presentedViewController = self.presentedViewController { presentedViewController.dismissViewControllerAnimated(animated, completion: nil) } } public func safeBack(animated: Bool = true) { if let navigationController = self.navigationController { navigationController.popViewControllerAnimated(animated) } else if let presentingViewController = self.presentingViewController { presentingViewController.dismissViewControllerAnimated(animated, completion: nil) } } }
mit
cb974bd9c39ce85979a28a415fc5181b
30.955556
92
0.738344
4.938144
false
false
false
false
barteljan/VISPER
Example/VISPER-Sourcery-Example/States/UserState.swift
1
782
// // UserState.swift // VISPER-Redux-Sourcery-Example // // Created by bartel on 24.03.18. // Copyright © 2018 Jan Bartel. All rights reserved. // import Foundation import VISPER_Sourcery struct UserState: WithAutoInitializers, WithAutoGeneralInitializer, AutoReducer, Equatable { var firstName: String? var lastName: String? var userName: String var email: String? // sourcery:inline:auto:UserState.GenerateInitializers // auto generated init function for UserState internal init(firstName: String? = nil, lastName: String? = nil, userName: String, email: String? = nil){ self.firstName = firstName self.lastName = lastName self.userName = userName self.email = email } // sourcery:end }
mit
e411d20bc8b5d6929c41c076d2db6d8d
25.033333
105
0.679898
4.221622
false
false
false
false
austinzheng/swift
stdlib/public/core/SetVariant.swift
2
10154
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 protocol is only used for compile-time checks that /// every buffer type implements all required operations. internal protocol _SetBuffer { associatedtype Element associatedtype Index var startIndex: Index { get } var endIndex: Index { get } func index(after i: Index) -> Index func index(for element: Element) -> Index? var count: Int { get } func contains(_ member: Element) -> Bool func element(at i: Index) -> Element } extension Set { @usableFromInline @_fixed_layout internal struct _Variant { @usableFromInline internal var object: _BridgeStorage<_RawSetStorage> @inlinable @inline(__always) init(dummy: ()) { #if arch(i386) || arch(arm) self.init(native: _NativeSet()) #else self.object = _BridgeStorage(taggedPayload: 0) #endif } @inlinable @inline(__always) init(native: __owned _NativeSet<Element>) { self.object = _BridgeStorage(native: native._storage) } #if _runtime(_ObjC) @inlinable @inline(__always) init(cocoa: __owned _CocoaSet) { self.object = _BridgeStorage(objC: cocoa.object) } #endif } } extension Set._Variant { #if _runtime(_ObjC) @usableFromInline @_transparent internal var guaranteedNative: Bool { return _canBeClass(Element.self) == 0 } #endif @inlinable internal mutating func isUniquelyReferenced() -> Bool { return object.isUniquelyReferencedUnflaggedNative() } #if _runtime(_ObjC) @usableFromInline @_transparent internal var isNative: Bool { if guaranteedNative { return true } return object.isUnflaggedNative } #endif @usableFromInline @_transparent internal var asNative: _NativeSet<Element> { get { return _NativeSet(object.unflaggedNativeInstance) } set { self = .init(native: newValue) } _modify { var native = _NativeSet<Element>(object.unflaggedNativeInstance) self = .init(dummy: ()) defer { // This is in a defer block because yield might throw, and we need to // preserve Set's storage invariants when that happens. object = .init(native: native._storage) } yield &native } } #if _runtime(_ObjC) @inlinable internal var asCocoa: _CocoaSet { return _CocoaSet(object.objCInstance) } #endif /// Reserves enough space for the specified number of elements to be stored /// without reallocating additional storage. internal mutating func reserveCapacity(_ capacity: Int) { #if _runtime(_ObjC) guard isNative else { let cocoa = asCocoa let capacity = Swift.max(cocoa.count, capacity) self = .init(native: _NativeSet(cocoa, capacity: capacity)) return } #endif let isUnique = isUniquelyReferenced() asNative.reserveCapacity(capacity, isUnique: isUnique) } /// The number of elements that can be stored without expanding the current /// storage. /// /// For bridged storage, this is equal to the current count of the /// collection, since any addition will trigger a copy of the elements into /// newly allocated storage. For native storage, this is the element count /// at which adding any more elements will exceed the load factor. @inlinable internal var capacity: Int { #if _runtime(_ObjC) guard isNative else { return asCocoa.count } #endif return asNative.capacity } } extension Set._Variant: _SetBuffer { @usableFromInline internal typealias Index = Set<Element>.Index @inlinable internal var startIndex: Index { #if _runtime(_ObjC) guard isNative else { return Index(_cocoa: asCocoa.startIndex) } #endif return asNative.startIndex } @inlinable internal var endIndex: Index { #if _runtime(_ObjC) guard isNative else { return Index(_cocoa: asCocoa.endIndex) } #endif return asNative.endIndex } @inlinable internal func index(after index: Index) -> Index { #if _runtime(_ObjC) guard isNative else { return Index(_cocoa: asCocoa.index(after: index._asCocoa)) } #endif return asNative.index(after: index) } @inlinable internal func formIndex(after index: inout Index) { #if _runtime(_ObjC) guard isNative else { let isUnique = index._isUniquelyReferenced() asCocoa.formIndex(after: &index._asCocoa, isUnique: isUnique) return } #endif index = asNative.index(after: index) } @inlinable @inline(__always) internal func index(for element: Element) -> Index? { #if _runtime(_ObjC) guard isNative else { let cocoaElement = _bridgeAnythingToObjectiveC(element) guard let index = asCocoa.index(for: cocoaElement) else { return nil } return Index(_cocoa: index) } #endif return asNative.index(for: element) } @inlinable internal var count: Int { @inline(__always) get { #if _runtime(_ObjC) guard isNative else { return asCocoa.count } #endif return asNative.count } } @inlinable @inline(__always) internal func contains(_ member: Element) -> Bool { #if _runtime(_ObjC) guard isNative else { return asCocoa.contains(_bridgeAnythingToObjectiveC(member)) } #endif return asNative.contains(member) } @inlinable @inline(__always) internal func element(at index: Index) -> Element { #if _runtime(_ObjC) guard isNative else { let cocoaMember = asCocoa.element(at: index._asCocoa) return _forceBridgeFromObjectiveC(cocoaMember, Element.self) } #endif return asNative.element(at: index) } } extension Set._Variant { @inlinable internal mutating func update(with value: __owned Element) -> Element? { #if _runtime(_ObjC) guard isNative else { // Make sure we have space for an extra element. var native = _NativeSet<Element>(asCocoa, capacity: asCocoa.count + 1) let old = native.update(with: value, isUnique: true) self = .init(native: native) return old } #endif let isUnique = self.isUniquelyReferenced() return asNative.update(with: value, isUnique: isUnique) } @inlinable internal mutating func insert( _ element: __owned Element ) -> (inserted: Bool, memberAfterInsert: Element) { #if _runtime(_ObjC) guard isNative else { // Make sure we have space for an extra element. let cocoaMember = _bridgeAnythingToObjectiveC(element) let cocoa = asCocoa if let m = cocoa.member(for: cocoaMember) { return (false, _forceBridgeFromObjectiveC(m, Element.self)) } var native = _NativeSet<Element>(cocoa, capacity: cocoa.count + 1) native.insertNew(element, isUnique: true) self = .init(native: native) return (true, element) } #endif let (bucket, found) = asNative.find(element) if found { return (false, asNative.uncheckedElement(at: bucket)) } let isUnique = self.isUniquelyReferenced() asNative.insertNew(element, at: bucket, isUnique: isUnique) return (true, element) } @inlinable @discardableResult internal mutating func remove(at index: Index) -> Element { #if _runtime(_ObjC) guard isNative else { // We have to migrate the data first. But after we do so, the Cocoa // index becomes useless, so get the element first. let cocoa = asCocoa let cocoaMember = cocoa.member(for: index._asCocoa) let nativeMember = _forceBridgeFromObjectiveC(cocoaMember, Element.self) return _migrateToNative(cocoa, removing: nativeMember) } #endif let isUnique = isUniquelyReferenced() let bucket = asNative.validatedBucket(for: index) return asNative.uncheckedRemove(at: bucket, isUnique: isUnique) } @inlinable @discardableResult internal mutating func remove(_ member: Element) -> Element? { #if _runtime(_ObjC) guard isNative else { let cocoa = asCocoa let cocoaMember = _bridgeAnythingToObjectiveC(member) guard cocoa.contains(cocoaMember) else { return nil } return _migrateToNative(cocoa, removing: member) } #endif let (bucket, found) = asNative.find(member) guard found else { return nil } let isUnique = isUniquelyReferenced() return asNative.uncheckedRemove(at: bucket, isUnique: isUnique) } #if _runtime(_ObjC) @inlinable internal mutating func _migrateToNative( _ cocoa: _CocoaSet, removing member: Element ) -> Element { // FIXME(performance): fuse data migration and element deletion into one // operation. var native = _NativeSet<Element>(cocoa) let (bucket, found) = native.find(member) _precondition(found, "Bridging did not preserve equality") let old = native.uncheckedRemove(at: bucket, isUnique: true) _precondition(member == old, "Bridging did not preserve equality") self = .init(native: native) return old } #endif @inlinable internal mutating func removeAll(keepingCapacity keepCapacity: Bool) { if !keepCapacity { self = .init(native: _NativeSet<Element>()) return } guard count > 0 else { return } #if _runtime(_ObjC) guard isNative else { self = .init(native: _NativeSet(capacity: asCocoa.count)) return } #endif let isUnique = isUniquelyReferenced() asNative.removeAll(isUnique: isUnique) } } extension Set._Variant { /// Returns an iterator over the elements. /// /// - Complexity: O(1). @inlinable @inline(__always) internal __consuming func makeIterator() -> Set<Element>.Iterator { #if _runtime(_ObjC) guard isNative else { return Set.Iterator(_cocoa: asCocoa.makeIterator()) } #endif return Set.Iterator(_native: asNative.makeIterator()) } }
apache-2.0
c56c0de57edad2edc1ea6ce4181a6699
26.443243
80
0.665747
4.168309
false
false
false
false
kang77649119/DouYuDemo
DouYuDemo/DouYuDemo/Classes/Home/View/RecommendCarouselView.swift
1
4162
// // RecommendCarouselView.swift // DouYuDemo // // Created by 也许、 on 16/10/12. // Copyright © 2016年 K. All rights reserved. // import UIKit private let carouselCellId = "carouselCellId" class RecommendCarouselView: UIView { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! var carouseTimer : Timer? // 轮播数据 var carouselModels:[CarouselModel]? { didSet { // 显示轮播数据 self.pageControl.numberOfPages = self.carouselModels?.count ?? 0 self.pageControl.isHidden = (self.carouselModels?.count ?? 0) <= 1 // 开启轮播 stopTimer() startTimer() self.collectionView.reloadData() } } // 加载视图 class func initView() -> RecommendCarouselView { return Bundle.main.loadNibNamed("RecommendCarouselView", owner: nil, options: nil)?.first as! RecommendCarouselView } override func awakeFromNib() { super.awakeFromNib() // 表示这个控件不受父控件的大小变化而变化 !!!!!! self.autoresizingMask = UIViewAutoresizing.init(rawValue: 0) } override func layoutSubviews() { super.layoutSubviews() let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = self.collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.isPagingEnabled = true self.collectionView.bounces = false self.collectionView.showsHorizontalScrollIndicator = false self.collectionView.register(UINib(nibName: "CarouselViewCell", bundle: nil), forCellWithReuseIdentifier: carouselCellId) } } extension RecommendCarouselView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let count = self.carouselModels?.count ?? 0 // 实现无限轮播(可以确保无限向后滑动) return count * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: carouselCellId, for: indexPath) as! CarouselViewCell let index = indexPath.item % (self.carouselModels!.count) cell.carouseModel = self.carouselModels![index] return cell } } extension RecommendCarouselView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { // 对轮播数据个数取模 计算出当前pageControl选中的索引 self.pageControl.currentPage = Int((scrollView.contentOffset.x / scrollView.bounds.width)) % self.carouselModels!.count } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { stopTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { startTimer() } } extension RecommendCarouselView { // 开启定时器,自动开始轮播 func startTimer() { self.carouseTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.settingCarouse), userInfo: nil, repeats: true) RunLoop.main.add(self.carouseTimer!, forMode: .commonModes) } // 停止定时器 func stopTimer() { self.carouseTimer?.invalidate() self.carouseTimer = nil } // 设置轮播 @objc func settingCarouse() { let offsetX = self.collectionView.contentOffset.x + self.collectionView.bounds.width let offset = CGPoint(x: offsetX, y: 0) self.collectionView.setContentOffset(offset, animated: true) } }
mit
06b1e4d1968502127a98b1b60d8cb79c
27.148936
151
0.649534
5.154545
false
false
false
false
jonathanhogan/receptionkit
ReceptionKit/Helpers/Text.swift
3
2057
// // Text.swift // ReceptionKit // // Created by Andy Cho on 2015-04-23. // Copyright (c) 2015 Andy Cho. All rights reserved. // let TextEnglish = [ "delivery": "delivery", "signature": "i need a signature", "left at reception": "i left a package at the reception", "visitor": "i'm a visitor", "i know": "i know the name\nof the person i am\nhere to see", "i don't know": "i don't know", "looking for": "Who are you looking for?", "wizard of oz": "The Wonderful Wizard of Oz", "no contact info": "no contact info", "your name": "What is your name?", "thank you": "thank you! :)", "please wait": "please wait", "nice day": "and have a nice day", "please wait message": "someone will be here shortly to meet you", "back": "Back", "other": "other" ] let TextFrench = [ "delivery": "livraison", "signature": "j'ai besoin d' une signature", "left at reception": "j'ai laissé un paquet à la réception", "visitor": "visiteur", "i know": "je connais le nom\nde la personne que\nje viens voir", "i don't know": "je ne sais pas", "looking for": "Quel est le nom de la personne?", "wizard of oz": "Le Magicien d'Oz", "no contact info": "pas d'info de contact", "your name": "Quel est votre nom?", "thank you": "merci! :)", "please wait": "veuillez patienter", "nice day": "et bonne journée", "please wait message": "quelqu'un sera avec vous sous peu", "back": "Retour", "other": "autre" ] // Apologies to whoever has to maintain this class Text { static var language = "English" // Get text from a key word static func get(text: String) -> String { if (language == "English") { return TextEnglish[text]! } else { return TextFrench[text]! } } // Switch between English and French static func swapLanguage() { if (language == "English") { language = "French" } else { language = "English" } } }
mit
e24ea9b59944ee118e31fa06697b5f30
28.753623
70
0.581588
3.3711
false
false
false
false
tuyenbq/Moya
Demo/DemoTests/RxSwiftMoyaProviderTests.swift
1
5184
import Quick import Nimble import RxMoya import RxSwift import Alamofire class RxSwiftMoyaProviderSpec: QuickSpec { override func spec() { var provider: RxMoyaProvider<GitHub>! beforeEach { provider = RxMoyaProvider(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns a MoyaResponse object") { var called = false provider.request(.Zen).subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target).subscribeNext { (response) -> Void in message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String } let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding) expect(message).to(equal(sampleString)) } it("returns correct data for user profile request") { var receivedResponse: NSDictionary? let target: GitHub = .UserProfile("ashfurrow") provider.request(target).subscribeNext { (response) -> Void in receivedResponse = try! NSJSONSerialization.JSONObjectWithData(response.data, options: []) as? NSDictionary } let sampleData = target.sampleData as NSData let sampleResponse: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(sampleData, options: []) as! NSDictionary expect(receivedResponse).toNot(beNil()) } it("returns identical observables for inflight requests") { let target: GitHub = .Zen var response: MoyaResponse! let parallelCount = 10 let observables = Array(0..<parallelCount).map { _ in provider.request(target) } var completions = Array(0..<parallelCount).map { _ in false } let queue = dispatch_queue_create("testing", DISPATCH_QUEUE_CONCURRENT) dispatch_apply(observables.count, queue) { idx in let i = idx observables[i].subscribeNext { _ -> Void in if i == 5 { // We only need to check it once. expect(provider.inflightRequests.count).to(equal(1)) } completions[i] = true } } func allTrue(cs: [Bool]) -> Bool { return cs.reduce(true) { (a,b) -> Bool in a && b } } expect(allTrue(completions)).toEventually(beTrue()) expect(provider.inflightRequests.count).to(equal(0)) } } } private extension String { var URLEscapedString: String { return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())! } } private enum GitHub { case Zen case UserProfile(String) } extension GitHub : MoyaTarget { var baseURL: NSURL { return NSURL(string: "https://api.github.com")! } var path: String { switch self { case .Zen: return "/zen" case .UserProfile(let name): return "/users/\(name.URLEscapedString)" } } var method: Moya.Method { return .GET } var parameters: [String: AnyObject] { return [:] } var sampleData: NSData { switch self { case .Zen: return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)! case .UserProfile(let name): return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)! } } } private func url(route: MoyaTarget) -> String { return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString } private let lazyEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in return Endpoint<GitHub>(URL: url(target), sampleResponse: .Closure({.Success(200, {target.sampleData})}), method: target.method, parameters: target.parameters) } private let failureEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in let errorData = "Houston, we have a problem".dataUsingEncoding(NSUTF8StringEncoding)! return Endpoint<GitHub>(URL: url(target), sampleResponse: .Error(401, NSError(domain: "com.moya.error", code: 0, userInfo: nil), {errorData}), method: target.method, parameters: target.parameters) } private enum HTTPBin: MoyaTarget { case BasicAuth var baseURL: NSURL { return NSURL(string: "http://httpbin.org")! } var path: String { switch self { case .BasicAuth: return "/basic-auth/user/passwd" } } var method: Moya.Method { return .GET } var parameters: [String: AnyObject] { switch self { default: return [:] } } var sampleData: NSData { switch self { case .BasicAuth: return "{\"authenticated\": true, \"user\": \"user\"}".dataUsingEncoding(NSUTF8StringEncoding)! } } }
mit
5f6403337cf2d524fe8842a117bb7942
32.230769
200
0.602816
4.858482
false
false
false
false
kalvish21/AndroidMessenger
AndroidMessengerMacDesktopClient/AndroidMessenger/Classes/LeftMessageHandler.swift
1
13526
// // LeftMessageHandler.swift // AndroidMessenger // // Created by Kalyan Vishnubhatla on 3/29/16. // Copyright © 2016 Kalyan Vishnubhatla. All rights reserved. // import Cocoa class LeftMessageHandler: NSObject, NSTableViewDataSource, NSTableViewDelegate, NSSearchFieldDelegate { var compose_results: Array<AnyObject> = Array<AnyObject>() var results: Array<AnyObject> = Array<AnyObject>() var original_results: Array<AnyObject> = Array<AnyObject>() var filter_value: String = "" var chatHandler: ChatMessageHandler! weak var leftTableView: NSTableView! lazy var messageHandler: MessageHandler = { return MessageHandler() }() lazy var contactsHandler: ContactsHandler = { return ContactsHandler() }() init(leftTableView: NSTableView, chatHandler: ChatMessageHandler) { super.init() self.leftTableView = leftTableView self.chatHandler = chatHandler self.leftTableView.backgroundColor = NSColor.clearColor() } func filterTableData(filter_string: String) { filter_value = filter_string.lowercaseString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if filter_value.characters.count > 0 { results = original_results.filter( { (result: AnyObject) -> Bool in let msg_title = (result as! Dictionary<String, AnyObject>)["row_title"] as! String let number = (result as! Dictionary<String, AnyObject>)["number"] as! String return msg_title.lowercaseString.rangeOfString(filter_value) != nil || number.lowercaseString.rangeOfString(filter_value) != nil }) } else { results = original_results } self.leftTableView.reloadData() } override func controlTextDidChange(obj: NSNotification) { let textField = obj.object as! NSTextField let text = textField.stringValue filterTableData(text) } func getDataForLeftTableView(new_selection: Bool) { let row = self.leftTableView.selectedRow NSLog("SELECTED_ROW %i", row) var row_data: Dictionary<String, AnyObject>? if row > -1 { row_data = results[row] as? Dictionary<String, AnyObject> } let delegate = NSApplication.sharedApplication().delegate as! AppDelegate original_results = self.messageHandler.getLeftMessagePaneWithLatestMessages(delegate.coreDataHandler.managedObjectContext) results = original_results if filter_value.characters.count > 0 { filterTableData(filter_value) } else { self.leftTableView.reloadData() } if row_data != nil && !new_selection { for row_id in 0...results.count - 1 { let row_dict = results[row_id] if self.chatHandler.thread_id == row_dict["thread_id"] as? Int { // Select previously selected row self.leftTableView.selectRowIndexes(NSIndexSet(index: row_id + compose_results.count), byExtendingSelection: false) break } } } } func navigateToThread(thread_id: Int) { for value in 0...results.count-1 { let msg = results[value] as! Dictionary<String, AnyObject> let thread_id_row = msg["thread_id"] as! Int if thread_id_row == thread_id { self.leftTableView.selectRowIndexes(NSIndexSet(index: value + compose_results.count), byExtendingSelection: false) break } } } func numberOfRowsInTableView(tableView: NSTableView) -> Int { return results.count + compose_results.count } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { // Get an existing cell with the MyView identifier if it exists let result: MessageCell = { let result: MessageCell? = tableView.makeViewWithIdentifier("MessageCell", owner: nil) as? MessageCell result?.nextKeyView = self.chatHandler.messageTextField return result! } () if (row <= compose_results.count-1) { let msg = compose_results[row] as! Dictionary<String, AnyObject> result.nameLabel.stringValue = msg["row_title"] as! String result.descriptionLabel.stringValue = msg["msg"] as! String } else { let calculatedRow = row - compose_results.count let msg = results[calculatedRow] as! Dictionary<String, AnyObject> result.nameLabel.stringValue = msg["row_title"] as! String result.descriptionLabel.stringValue = msg["msg"] as! String if (msg["read"] as! Bool == false && self.chatHandler.thread_id != msg["thread_id"] as? Int) { result.descriptionLabel.font = NSFont.boldSystemFontOfSize(13) } else { result.descriptionLabel.font = NSFont.systemFontOfSize(13) } } // Return the result return result } func tableView(tableView: NSTableView, selectionIndexesForProposedSelection proposedSelectionIndexes: NSIndexSet) -> NSIndexSet { // Prevent users from deseleting rows for no rows if self.leftTableView.selectedRowIndexes.count > 0 { let currentSelection = tableView.selectedRow let currentViewCell = tableView.viewAtColumn(0, row: currentSelection, makeIfNecessary: false) as? MessageCell if (currentViewCell != nil) { currentViewCell!.nameLabel.textColor = NSColor.blackColor() } } if (proposedSelectionIndexes.count == 0) { return tableView.selectedRowIndexes } // Delay textField color change let newViewCell = tableView.viewAtColumn(0, row: proposedSelectionIndexes.firstIndex, makeIfNecessary: false) as? MessageCell if (newViewCell != nil) { newViewCell!.nameLabel.textColor = NSColor.whiteColor() } return proposedSelectionIndexes } func tableView(tableView: NSTableView, shouldEditTableColumn tableColumn: NSTableColumn?, row: Int) -> Bool { return false } func tableView(tableView: NSTableView, shouldShowCellExpansionForTableColumn tableColumn: NSTableColumn?, row: Int) -> Bool { return false } func tableView(tableView: NSTableView, nextTypeSelectMatchFromRow startRow: Int, toRow endRow: Int, forString searchString: String) -> Int { self.chatHandler.messageTextField.stringValue = searchString self.chatHandler.messageTextField.becomeFirstResponder() return self.leftTableView.selectedRow } func tableViewSelectionDidChange(notification: NSNotification) { self.chatHandler.tokenField.hidden = false self.chatHandler.chatTableView.superview!.superview!.hidden = false self.chatHandler.messageTextField.hidden = false self.chatHandler.messageTextField.enabled = true if self.leftTableView.selectedRow <= compose_results.count-1 && self.leftTableView.selectedRow >= 0 { let row = self.leftTableView.selectedRow let msg = compose_results[row] as! Dictionary<String, AnyObject> self.chatHandler.getAllDataForGroupId(msg["thread_id"] as! Int) self.chatHandler.tokenField.editable = true } else { userSelectedANewRowRefresh() self.chatHandler.tokenField.editable = false } self.messageHandler.setBadgeCount() } func userSelectedANewRowRefresh() { // User selected a new row let row = self.leftTableView.selectedRow - compose_results.count if (row < 0) { return } let msg = results[row] as! Dictionary<String, AnyObject> if (msg["read"] as! Bool == false && self.chatHandler.thread_id != msg["thread_id"] as? Int) { self.markMessagesAsReadForCurrentThread(row, threadId: msg["thread_id"] as! Int) getDataForLeftTableView(false) } else { // Set the chat data thread self.chatHandler.getAllDataForGroupId(msg["thread_id"] as! Int) self.chatHandler.chatTableView.scrollRowToVisible(self.chatHandler.chatTableView.numberOfRows - 1) } } func markMessagesAsReadForCurrentThread(row: Int, threadId: Int) { let delegate = NSApplication.sharedApplication().delegate as! AppDelegate let context = delegate.coreDataHandler.managedObjectContext let request = NSFetchRequest(entityName: "Message") request.predicate = NSPredicate(format: "thread_id = %i and read = %@", threadId, false) var objs: [Message]? do { try objs = context.executeFetchRequest(request) as? [Message] } catch let error as NSError { NSLog("Unresolved error: %@, %@", error, error.userInfo) } // Set the chat data thread self.chatHandler.getAllDataForGroupId(threadId) self.chatHandler.chatTableView.scrollRowToVisible(self.chatHandler.chatTableView.numberOfRows - 1) if (objs?.count > 0) { let selectedRow = self.leftTableView.selectedRow NSLog("SELECTED ROW -- %i", selectedRow) self.chatHandler.performActionsForIncomingMessages(self.leftTableView, threadId: threadId) // Update table let rowSet = NSIndexSet(index: row) let col = NSIndexSet(index: 0) // Refresh the index paths necesary for this. self.chatHandler.chatTableView.beginUpdates() self.chatHandler.chatTableView.reloadDataForRowIndexes(rowSet, columnIndexes: col) self.chatHandler.chatTableView.endUpdates() // Reset badge count after marking messages as read self.messageHandler.setBadgeCount() } } func askToDeleteThread(row: Int, window: NSWindow) { let alert = NSAlert() alert.messageText = "Are you sure you want to delete this thread?" alert.addButtonWithTitle("Okay") alert.addButtonWithTitle("Cancel") alert.beginSheetModalForWindow(window) { (response) in if response == NSAlertFirstButtonReturn { // User wants to delete NSLog("User wants to delete") NSLog("%i", row) if row < 0 { return } if row <= self.compose_results.count-1 { // Delete a new message the user was composing self.compose_results.removeAtIndex(row) self.leftTableView.beginUpdates() self.leftTableView.removeRowsAtIndexes(NSIndexSet(index: row), withAnimation: .SlideLeft) self.leftTableView.endUpdates() } else { // Delete the thread that we have stored locally let delegate = NSApplication.sharedApplication().delegate as! AppDelegate let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) context.parentContext = delegate.coreDataHandler.managedObjectContext let msg = self.results[row] as! Dictionary<String, AnyObject> let threadId = msg["thread_id"] as! Int let request = NSFetchRequest(entityName: "Message") request.predicate = NSPredicate(format: "thread_id = %i", threadId) var objs: [Message]? do { // Delete each message try objs = context.executeFetchRequest(request) as? [Message] if objs?.count > 0 { for obj in objs! { context.deleteObject(obj) } } // Save the context try context.save() delegate.coreDataHandler.managedObjectContext.performBlock({ do { try delegate.coreDataHandler.managedObjectContext.save() } catch { fatalError("Failure to save context: \(error)") } }) } catch let error as NSError { NSLog("Unresolved error: %@, %@", error, error.userInfo) } // Remove from the left message pane self.results.removeAtIndex(row) self.leftTableView.beginUpdates() self.leftTableView.removeRowsAtIndexes(NSIndexSet(index: row), withAnimation: .SlideLeft) self.leftTableView.endUpdates() } self.chatHandler.unselectAllAndClearMessageView() } } } }
mit
8733c5d89a82ed7577eecd61d131a502
42.770227
144
0.592754
5.322708
false
false
false
false
eure/ReceptionApp
iOS/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift
34
1341
// // BinaryDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 6/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents two disposable resources that are disposed together. */ public final class BinaryDisposable : DisposeBase, Cancelable { private var _disposed: AtomicInt = 0 // state private var _disposable1: Disposable? private var _disposable2: Disposable? /** - returns: Was resource disposed. */ public var disposed: Bool { get { return _disposed > 0 } } /** Constructs new binary disposable from two disposables. - parameter disposable1: First disposable - parameter disposable2: Second disposable */ init(_ disposable1: Disposable, _ disposable2: Disposable) { _disposable1 = disposable1 _disposable2 = disposable2 super.init() } /** Calls the disposal action if and only if the current instance hasn't been disposed yet. After invoking disposal action, disposal action will be dereferenced. */ public func dispose() { if AtomicCompareAndSwap(0, 1, &_disposed) { _disposable1?.dispose() _disposable2?.dispose() _disposable1 = nil _disposable2 = nil } } }
mit
6c0cb610e52a8b47f53f4b805bdb06c5
22.928571
91
0.631343
4.66899
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Common/UI/Style/Styles.swift
2
1437
// // Styles.swift // SmartReceipts // // Created by Bogdan Evsenev on 01/08/2019. // Copyright © 2019 Will Baumann. All rights reserved. // import UIKit // MARK: - View struct ViewStyle: Making, BaseViewStyle { var backgroundColor: UIColor = .black var cornerRadius: CGFloat = 4 var shadowColor: UIColor = .black var shadowOpacity: Float = 0 var masksToBounds: Bool = true var shadowOffset: CGSize = .zero var shadowRadius: CGFloat = 0 static let card = ViewStyle().making { $0.backgroundColor = .white $0.masksToBounds = false $0.shadowOpacity = 1 $0.shadowOffset = .init(width: 0, height: 16) $0.shadowColor = #colorLiteral(red: 0.03921568627, green: 0.003921568627, blue: 0.07843137255, alpha: 0.04) $0.shadowRadius = 16 $0.cornerRadius = 14 } } // MARK: - Button extension ButtonStyle { static let main = ButtonStyle().making { $0.backgroundColor = .violetAccent $0.titleColor = .white $0.cornerRadius = 5 $0.font = .semibold15 $0.edgeInsets = .init(top: 2, left: 6, bottom: 2, right: 6) } static let mainBig = main.making { $0.cornerRadius = 8 } static let mainTextOnly = main.making { $0.backgroundColor = .clear $0.titleColor = .violetAccent $0.font = .systemFont(ofSize: 15, weight: .semibold) } }
agpl-3.0
ed8b700926200d7e287de07e4abf8028
23.758621
115
0.60585
3.819149
false
false
false
false
welbesw/BigcommerceApi
Example/BigcommerceApi/ProductDetailsViewController.swift
1
2496
// // ProductDetailsViewController.swift // BigcommerceApi // // Created by William Welbes on 10/1/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit import BigcommerceApi class ProductDetailsViewController: UIViewController { @IBOutlet weak var textView:UITextView! var product:BigcommerceProduct! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. loadProductImages() loadProductSkus() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.textView.text = product.description } 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. if segue.identifier == "ModalEditInventorySegue" { if let navController = segue.destination as? UINavigationController { if let editInventoryViewController = navController.topViewController as? EditInvetoryViewController { editInventoryViewController.product = product } } } } func loadProductImages() { if let productId = product.productId?.stringValue { BigcommerceApi.sharedInstance.getProductImages(productId) { (productImages, error) -> () in if(error == nil) { for productImage in productImages { print("Loaded \(productImage.standardUrl ?? "") product images") } } } } } func loadProductSkus() { if let productId = product.productId?.stringValue { BigcommerceApi.sharedInstance.getProductSkus(productId, completion: { (productSkus, error) in if(error == nil) { for productSku in productSkus { print("Loaded product sku: \(productSku.productSkuId?.stringValue ?? "")") } } }) } } }
mit
b51df3cef2b51c15fe281eb372fafa15
30.582278
117
0.600401
5.342612
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/Profiles/UART/LoggViewController/CheckmarkTableViewCell.swift
1
2826
/* * Copyright (c) 2020, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import UIKit class CheckmarkTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) imageView?.tintColor = .nordicBlue selectionStyle = .none } required init?(coder: NSCoder) { super.init(coder: coder) imageView?.tintColor = .nordicBlue selectionStyle = .none } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) let image = (selected ? selectedImg : img)?.withRenderingMode(.alwaysTemplate) imageView?.image = image } private let img: UIImage? = { if #available(iOS 13, *) { return ModernIcon.circle.image } else { return UIImage(named: "circle") } }() private let selectedImg: UIImage? = { if #available(iOS 13, *) { return ModernIcon.checkmark(.circle)(.fill).image } else { return UIImage(named: "baseline_check_circle_white_36pt")?.withRenderingMode(.alwaysTemplate) } }() }
bsd-3-clause
8d59a2e389067d3e29e83cc438c3986c
36.184211
105
0.701699
4.797963
false
false
false
false
malczak/hashids
Hashids.swift
1
10774
// // HashIds.swift // http://hashids.org // // Author https://github.com/malczak // Licensed under the MIT license. // import Foundation // MARK: Hashids options public struct HashidsOptions { static let VERSION = "1.1.0" static var MIN_ALPHABET_LENGTH: Int = 16 static var SEP_DIV: Double = 3.5 static var GUARD_DIV: Double = 12 static var ALPHABET: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" static var SEPARATORS: String = "cfhistuCFHISTU" } // MARK: Hashids protocol public protocol HashidsGenerator { associatedtype Char func encode(_ value: Int64...) -> String? func encode(_ values: [Int64]) -> String? func encode(_ value: Int...) -> String? func encode(_ values: [Int]) -> String? func decode(_ value: String!) -> [Int] func decode(_ value: [Char]) -> [Int] func decode64(_ value: String) -> [Int64] func decode64(_ value: [Char]) -> [Int64] } // MARK: Hashids class public typealias Hashids = Hashids_<UInt32> // MARK: Hashids generic class open class Hashids_<T>: HashidsGenerator where T:UnsignedInteger { public typealias Char = T fileprivate var minHashLength: UInt fileprivate var alphabet: [Char] fileprivate var seps: [Char] fileprivate var salt: [Char] fileprivate var guards: [Char] public init(salt: String!, minHashLength: UInt = 0, alphabet: String? = nil) { var _alphabet = (alphabet != nil) ? alphabet! : HashidsOptions.ALPHABET var _seps = HashidsOptions.SEPARATORS self.minHashLength = minHashLength self.guards = [Char]() self.salt = salt.unicodeScalars.map() { numericCast($0.value) } self.seps = _seps.unicodeScalars.map() { numericCast($0.value) } self.alphabet = unique(_alphabet.unicodeScalars.map() { numericCast($0.value) }) self.seps = intersection(self.seps, self.alphabet) self.alphabet = difference(self.alphabet, self.seps) shuffle(&self.seps, self.salt) let sepsLength = self.seps.count let alphabetLength = self.alphabet.count if (0 == sepsLength) || (Double(alphabetLength) / Double(sepsLength) > HashidsOptions.SEP_DIV) { var newSepsLength = Int(ceil(Double(alphabetLength) / HashidsOptions.SEP_DIV)) if 1 == newSepsLength { newSepsLength += 1 } if newSepsLength > sepsLength { let diff = self.alphabet.startIndex.advanced(by: newSepsLength - sepsLength) let range = 0 ..< diff self.seps += self.alphabet[range] self.alphabet.removeSubrange(range) } else { let pos = self.seps.startIndex.advanced(by: newSepsLength) self.seps.removeSubrange(pos + 1 ..< self.seps.count) } } shuffle(&self.alphabet, self.salt) let guard_i = Int(ceil(Double(alphabetLength) / HashidsOptions.GUARD_DIV)) if alphabetLength < 3 { let seps_guard = self.seps.startIndex.advanced(by: guard_i) let range = 0 ..< seps_guard self.guards += self.seps[range] self.seps.removeSubrange(range) } else { let alphabet_guard = self.alphabet.startIndex.advanced(by: guard_i) let range = 0 ..< alphabet_guard self.guards += self.alphabet[range] self.alphabet.removeSubrange(range) } } // MARK: public api open func encode(_ value: Int64...) -> String? { return encode(value) } open func encode(_ values: [Int64]) -> String? { return encode(values.map { Int($0) }) } open func encode(_ value: Int...) -> String? { return encode(value) } open func encode(_ values: [Int]) -> String? { let ret = _encode(values) return ret.reduce(String(), { ( so, i) in var so = so let scalar: UInt32 = numericCast(i) if let uniscalar = UnicodeScalar(scalar) { so.append(String(describing: uniscalar)) } return so }) } open func decode(_ value: String!) -> [Int] { let trimmed = value.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let hash: [Char] = trimmed.unicodeScalars.map() { numericCast($0.value) } return self.decode(hash) } open func decode(_ value: [Char]) -> [Int] { return self._decode(value) } open func decode64(_ value: String) -> [Int64] { return self.decode(value).map { Int64($0) } } open func decode64(_ value: [Char]) -> [Int64] { return self.decode(value).map { Int64($0) } } // MARK: private funcitons fileprivate func _encode(_ numbers: [Int]) -> [Char] { var alphabet = self.alphabet var numbers_hash_int = 0 for (index, value) in numbers.enumerated() { numbers_hash_int += (value % (index + 100)) } let lottery = alphabet[numbers_hash_int % alphabet.count] var hash = [lottery] var lsalt = [Char]() let (lsaltARange, lsaltRange) = _saltify(&lsalt, lottery, alphabet) for (index, value) in numbers.enumerated() { shuffle(&alphabet, lsalt, lsaltRange) let lastIndex = hash.endIndex _hash(&hash, value, alphabet) if index + 1 < numbers.count { let number = value % (numericCast(hash[lastIndex]) + index) let seps_index = number % self.seps.count hash.append(self.seps[seps_index]) } lsalt.replaceSubrange(lsaltARange, with: alphabet) } let minLength: Int = numericCast(self.minHashLength) if hash.count < minLength { let guard_index = (numbers_hash_int + numericCast(hash[0])) % self.guards.count let guard_t = self.guards[guard_index] hash.insert(guard_t, at: 0) if hash.count < minLength { let guard_index = (numbers_hash_int + numericCast(hash[2])) % self.guards.count let guard_t = self.guards[guard_index] hash.append(guard_t) } } let half_length = alphabet.count >> 1 while hash.count < minLength { shuffle(&alphabet, alphabet) let lrange = 0 ..< half_length let rrange = half_length ..< (alphabet.count) let alphabet_right = alphabet[rrange] let alphabet_left = alphabet[lrange] hash = Array<Char>(alphabet_right) + hash + Array<Char>(alphabet_left) let excess = hash.count - minLength if excess > 0 { let start = excess >> 1 hash = [Char](hash[start ..< (start + minLength)]) } } return hash } fileprivate func _decode(_ hash: [Char]) -> [Int] { var ret = [Int]() var alphabet = self.alphabet var hashes = hash.split(maxSplits: hash.count, omittingEmptySubsequences: false) { contains(self.guards, $0) } let hashesCount = hashes.count, i = ((hashesCount == 2) || (hashesCount == 3)) ? 1 : 0 let hash = hashes[i] let hashStartIndex = hash.startIndex if hash.count > 0 { let lottery = hash[hashStartIndex] let valuesHashes = hash[(hashStartIndex + 1) ..< (hashStartIndex + hash.count)] let valueHashes = valuesHashes.split(maxSplits: valuesHashes.count, omittingEmptySubsequences: false) { contains(self.seps, $0) } var lsalt = [Char]() let (lsaltARange, lsaltRange) = _saltify(&lsalt, lottery, alphabet) for subHash in valueHashes { shuffle(&alphabet, lsalt, lsaltRange) ret.append(self._unhash(subHash, alphabet)) lsalt.replaceSubrange(lsaltARange, with: alphabet) } } return ret } fileprivate func _hash(_ hash: inout [Char], _ number: Int, _ alphabet: [Char]) { var number = number let length = alphabet.count, index = hash.count repeat { hash.insert(alphabet[number % length], at: index) number = number / length } while (number != 0) } fileprivate func _unhash<U:Collection>(_ hash: U, _ alphabet: [Char]) -> Int where U.Index == Int, U.Iterator.Element == Char { var value: Double = 0 var hashLength: Int = numericCast(hash.count) if hashLength > 0 { let alphabetLength = alphabet.count value = hash.reduce(0) { value, token in var tokenValue = 0.0 if let token_index = alphabet.firstIndex(of: token as Char) { hashLength = hashLength - 1 let mul = pow(Double(alphabetLength), Double(hashLength)) tokenValue = Double(token_index) * mul } return value + tokenValue } } return Int(trunc(value)) } fileprivate func _saltify(_ salt: inout [Char], _ lottery: Char, _ alphabet: [Char]) -> (Range<Int>, Range<Int>) { salt.append(lottery) salt = salt + self.salt salt = salt + alphabet let lsaltARange = (self.salt.count + 1) ..< salt.count let lsaltRange = 0 ..< alphabet.count return (lsaltARange, lsaltRange) } } // MARK: Internal functions internal func contains<T:Collection>(_ a: T, _ e: T.Iterator.Element) -> Bool where T.Iterator.Element:Equatable { return (a.firstIndex(of: e) != nil) } internal func transform<T:Collection>(_ a: T, _ b: T, _ cmpr: (inout Array<T.Iterator.Element>, T, T, T.Iterator.Element) -> Void) -> [T.Iterator.Element] where T.Iterator.Element:Equatable { typealias U = T.Iterator.Element var c = [U]() for i in a { cmpr(&c, a, b, i) } return c } internal func unique<T:Collection>(_ a: T) -> [T.Iterator.Element] where T.Iterator.Element:Equatable { return transform(a, a) { ( c, a, b, e) in if !contains(c, e) { c.append(e) } } } internal func intersection<T:Collection>(_ a: T, _ b: T) -> [T.Iterator.Element] where T.Iterator.Element:Equatable { return transform(a, b) { ( c, a, b, e) in if contains(b, e) { c.append(e) } } } internal func difference<T:Collection>(_ a: T, _ b: T) -> [T.Iterator.Element] where T.Iterator.Element:Equatable { return transform(a, b) { ( c, a, b, e) in if !contains(b, e) { c.append(e) } } } internal func shuffle<T:MutableCollection, U:Collection>(_ source: inout T, _ salt: U) where T.Index == Int, T.Iterator.Element:UnsignedInteger, T.Iterator.Element == U.Iterator.Element, T.Index == U.Index { let saltCount: Int = numericCast(salt.count) shuffle(&source, salt, 0 ..< saltCount) } internal func shuffle<T:MutableCollection, U:Collection>(_ source: inout T, _ salt: U, _ saltRange: Range<Int>) where T.Index == Int, T.Iterator.Element:UnsignedInteger, T.Iterator.Element == U.Iterator.Element, T.Index == U.Index { let sidx0 = saltRange.lowerBound, scnt = (saltRange.upperBound - saltRange.lowerBound) guard scnt != 0 else { return } var sidx: Int = numericCast(source.count) - 1, v = 0, _p = 0 while sidx > 0 { v = v % scnt let _i: Int = numericCast(salt[sidx0 + v]) _p += _i let _j: Int = (_i + v + _p) % sidx let tmp = source[sidx] source[sidx] = source[_j] source[_j] = tmp v += 1 sidx = sidx - 1 } }
mit
7ab7d342e45688955c4f24b706f49eee
27.578249
232
0.628457
3.493515
false
false
false
false
leaderWangShaoming/SimpleNetwork
SimpleNetwork.swift
1
10731
// // SimpleNetwork.swift // SimpleNetwork // // Created by apple on 15/3/2. // Copyright (c) 2015年 All rights reserved. // import Foundation /// 常用的网络访问方法 enum HTTPMethod: String { case GET = "GET" case POST = "POST" } class SimpleNetwork { // 定义闭包类型,类型别名-> 首字母一定要大写 typealias Completion = (result: AnyObject?, error: NSError?) -> () /// 异步下载网路图像 /// /// :param: urlString urlString /// :param: completion 完成回调 func requestImage(urlString: String, _ completion: Completion) { // 1. 调用 download 下载图像,如果图片已经被缓存过,就不会再次下载 downloadImage(urlString) { (_, error) -> () in // 2.1 错误处理 if error != nil { completion(result: nil, error: error) } else { // 2.2 图像是保存在沙盒路径中的,文件名是 url + md5 let path = self.fullImageCachePath(urlString) // 将图像从沙盒加载到内存 var image = UIImage(contentsOfFile: path) // 提示:尾随闭包,如果没有参数,没有返回值,都可以省略! dispatch_async(dispatch_get_main_queue()) { completion(result: image, error: nil) } } } } /// 完整的 URL 缓存路径 func fullImageCachePath(urlString: String) -> String { var path = urlString.md5 return cachePath!.stringByAppendingPathComponent(path) } /// 下载多张图片 - 对于多张图片下载,并不处理错误! /// /// :param: urls 图片 URL 数组 /// :param: completion 所有图片下载完成后的回调 func downloadImages(urls: [String], _ completion: Completion) { // 希望所有图片下载完成,统一回调! // 利用调度组统一监听一组异步任务执行完毕 let group = dispatch_group_create() // 遍历数组 for url in urls { // 进入调度组 dispatch_group_enter(group) downloadImage(url) { (result, error) -> () in // 离开调度组 dispatch_group_leave(group) } } // 在主线程回调 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in // 所有任务完成后的回调 completion(result: nil, error: nil) } } /// 下载图像并且保存到沙盒 /// /// :param: urlString urlString /// :param: completion 完成回调 func downloadImage(urlString: String, _ completion: Completion) { // 1. 目标路径 let path = fullImageCachePath(urlString) // 2. 缓存检测,如果文件已经下载完成直接返回 if NSFileManager.defaultManager().fileExistsAtPath(path) { // println("\(urlString) 图片已经被缓存") completion(result: nil, error: nil) return } // 3. 下载图像 - 如果 url 真的无法从字符串创建 // 不会调用 completion 的回调 if let url = NSURL(string: urlString) { self.session!.downloadTaskWithURL(url) { (location, _, error) -> Void in // 错误处理 if error != nil { completion(result: nil, error: error) return } // 将文件复制到缓存路径 NSFileManager.defaultManager().copyItemAtPath(location.path!, toPath: path, error: nil) // 直接回调,不传递任何参数 completion(result: nil, error: nil) }.resume() } else { let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error": "无法创建 URL"]) completion(result: nil, error: error) } } // 在 swift 中,一个命名空间内部,几乎都是开放的,彼此可以互相访问 // 如果不想开发的内容,可以使用 private 保护起来 /// 完整图像缓存路径 private lazy var cachePath: String? = { // 1. cache var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String path = path.stringByAppendingPathComponent(imageCachePath) // 2. 检查缓存路径是否存在 - 注意:必须准确地指出类型 ObjCBool var isDirectory: ObjCBool = true // 无论存在目录还是文件,都会返回 true,是否是路径由 isDirectory 来决定 let exists = NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) // println("isDirectory: \(isDirectory) exists \(exists) path: \(path)") // 3. 如果有同名的文件-干掉 // 一定需要判断是否是文件,否则目录也同样会被删除 if exists && !isDirectory { NSFileManager.defaultManager().removeItemAtPath(path, error: nil) } // 4. 直接创建目录,如果目录已经存在,就什么都不做 // withIntermediateDirectories -> 是否智能创建层级目录 NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil, error: nil) return path }() /// 缓存路径的常量 - 类变量不能存储内容,但是可以返回数值 private static var imageCachePath = "com.itheima.imagecache" // MARK: - 请求 JSON /// 请求 JSON /// /// :param: method HTTP 访问方法 /// :param: urlString urlString /// :param: params 可选参数字典 /// :param: completion 完成回调 func requestJSON(method: HTTPMethod, _ urlString: String, _ params: [String: String]?, _ completion: Completion) { // 实例化网络请求 if let request = request(method, urlString, params) { // 访问网络 - 本身的回调方法是异步的 session!.dataTaskWithRequest(request, completionHandler: { (data, _, error) -> Void in println(request) // 如果有错误,直接回调,将网络访问的错误传回 if error != nil { completion(result: nil, error: error) return } // 反序列化 -> 字典或者数组 let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) // 判断是否反序列化成功 if json == nil { let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error": "反序列化失败"]) completion(result: nil, error: error) } else { // 有结果 dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(result: json, error: nil) }) } }).resume() return } // 如果网络请求没有创建成功,应该生成一个错误,提供给其他的开发者 /** domain: 错误所属领域字符串 com.itheima.error code: 如果是复杂的系统,可以自己定义错误编号 userInfo: 错误信息字典 */ let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error": "请求建立失败"]) completion(result: nil, error: error) } // 静态属性,在 Swift 中类属性可以返回值但是不能存储数值 private static let errorDomain = "com.itheima.error" /// 返回网络访问的请求 /// /// :param: method HTTP 访问方法 /// :param: urlString urlString /// :param: params 可选参数字典 /// /// :returns: 可选网络请求 private func request(method: HTTPMethod, _ urlString: String, _ params: [String: String]?) -> NSURLRequest? { // isEmpty 是 "" & nil if urlString.isEmpty { return nil } // 记录 urlString,因为传入的参数是不可变的 var urlStr = urlString var r: NSMutableURLRequest? if method == .GET { // URL 的参数是拼接在URL字符串中的 // 1. 生成查询字符串 let query = queryString(params) // 2. 如果有拼接参数 if query != nil { urlStr += "?" + query! } // 3. 实例化请求 r = NSMutableURLRequest(URL: NSURL(string: urlStr)!) } else { // 设置请求体,提问:post 访问,能没有请求体吗?=> 必须要提交数据给服务器 if let query = queryString(params) { r = NSMutableURLRequest(URL: NSURL(string: urlStr)!) // 设置请求方法 // swift 语言中,枚举类型,如果要去的返回值,需要使用一个 rawValue r!.HTTPMethod = method.rawValue // 设置数据提 r!.HTTPBody = query.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) } } return r } /// 生成查询字符串 /// /// :param: params 可选字典 /// /// :returns: 拼接完成的字符串 private func queryString(params: [String: String]?) -> String? { // 0. 判断参数 if params == nil { return nil } // 涉及到数组的使用技巧 // 1. 定义一个数组 var array = [String]() // 2. 遍历字典 for (k, v) in params! { let str = k + "=" + v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! array.append(str) } return join("&", array) } /// 全局网络会话,提示,可以利用构造函数,设置不同的网络会话配置 private lazy var session: NSURLSession? = { return NSURLSession.sharedSession() }() }
mit
1250cefc6e98ce4340371cca58549dcc
30.824373
154
0.517063
4.369587
false
false
false
false
badoo/Chatto
ChattoAdditions/sources/Chat Items/BaseMessage/BaseMessageViewModel.swift
1
6049
/* 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 Chatto import UIKit public enum MessageViewModelStatus { case success case sending case failed } public extension MessageStatus { func viewModelStatus() -> MessageViewModelStatus { switch self { case .success: return MessageViewModelStatus.success case .failed: return MessageViewModelStatus.failed case .sending: return MessageViewModelStatus.sending } } } public protocol MessageViewModelProtocol: AnyObject { // why class? https://gist.github.com/diegosanchezr/29979d22c995b4180830 var decorationAttributes: BaseMessageDecorationAttributes { get set } var isIncoming: Bool { get } var isUserInteractionEnabled: Bool { get set } var isShowingFailedIcon: Bool { get } var date: String { get } var status: MessageViewModelStatus { get } var avatarImage: Observable<UIImage?> { get set } var messageContentTransferStatus: TransferStatus? { get set } var canReply: Bool { get } func willBeShown() // Optional func wasHidden() // Optional } extension MessageViewModelProtocol { public func willBeShown() {} public func wasHidden() {} } public protocol DecoratedMessageViewModelProtocol: MessageViewModelProtocol { var messageViewModel: MessageViewModelProtocol { get } } extension DecoratedMessageViewModelProtocol { public var decorationAttributes: BaseMessageDecorationAttributes { get { return self.messageViewModel.decorationAttributes } set { self.messageViewModel.decorationAttributes = newValue } } public var canReply: Bool { self.messageViewModel.canReply } public var isIncoming: Bool { return self.messageViewModel.isIncoming } public var isUserInteractionEnabled: Bool { get { return self.messageViewModel.isUserInteractionEnabled } set { self.messageViewModel.isUserInteractionEnabled = newValue } } public var date: String { return self.messageViewModel.date } public var messageContentTransferStatus: TransferStatus? { get { return nil } set { } } public var status: MessageViewModelStatus { return self.messageViewModel.status } public var isShowingFailedIcon: Bool { return self.messageViewModel.isShowingFailedIcon } public var avatarImage: Observable<UIImage?> { get { return self.messageViewModel.avatarImage } set { self.messageViewModel.avatarImage = newValue } } } open class MessageViewModel: MessageViewModelProtocol { open var canReply: Bool { self.messageModel.canReply } open var isIncoming: Bool { return self.messageModel.isIncoming } open var decorationAttributes: BaseMessageDecorationAttributes open var isUserInteractionEnabled: Bool = true public var messageContentTransferStatus: TransferStatus? open var status: MessageViewModelStatus { let deliveryStatus = self.messageModel.status.viewModelStatus() guard let contentLoadStatus = self.messageContentTransferStatus else { return deliveryStatus } if contentLoadStatus == .failed { return .failed } return deliveryStatus } open lazy var date: String = { return self.dateFormatter.string(from: self.messageModel.date as Date) }() public let dateFormatter: DateFormatter public private(set) var messageModel: MessageModelProtocol public init(dateFormatter: DateFormatter, messageModel: MessageModelProtocol, avatarImage: UIImage?, decorationAttributes: BaseMessageDecorationAttributes) { self.dateFormatter = dateFormatter self.messageModel = messageModel self.avatarImage = Observable<UIImage?>(avatarImage) self.decorationAttributes = decorationAttributes } open var isShowingFailedIcon: Bool { return self.status == .failed } public var avatarImage: Observable<UIImage?> } public class MessageViewModelDefaultBuilder { public init() {} static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale.current formatter.dateStyle = .none formatter.timeStyle = .short return formatter }() public func createMessageViewModel(_ message: MessageModelProtocol) -> MessageViewModelProtocol { // Override to use default avatarImage return MessageViewModel(dateFormatter: MessageViewModelDefaultBuilder.dateFormatter, messageModel: message, avatarImage: nil, decorationAttributes: BaseMessageDecorationAttributes()) } }
mit
b24f96d28fa2ac8fd5410c99274deb2b
30.670157
126
0.693172
5.444644
false
false
false
false
arkuhn/SkiFree-iOS
SkiFreeiOS/SkiFreeiOS/Obstacle.swift
1
2078
// // Obstacle.swift // SkiFreeiOS // // Created by ark9719 on 2/7/17. // Copyright © 2017 ark9719. All rights reserved. // import Foundation import SpriteKit class Obstacle: SKSpriteNode{ let textureArray: [SKTexture] = [SKTexture(imageNamed: "skifreetree"), SKTexture(imageNamed: "skifreetree2"), SKTexture(imageNamed: "skifreetree3"), SKTexture(imageNamed: "skifreetree4"), SKTexture(imageNamed: "skifreestump"), SKTexture(imageNamed: "skifreemushroom"), SKTexture(imageNamed: "skifreerock") ] init (frame: CGRect) { super.init(texture: nil, color: UIColor.clear, size: CGSize(width: 40, height: 40)) getTexture() getSize() getLocation(frameOriginal: frame) initPhysics() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initPhysics(){ self.physicsBody = SKPhysicsBody(texture: self.texture!, size: self.texture!.size()) self.physicsBody?.isDynamic = false self.physicsBody?.collisionBitMask = 0 self.physicsBody?.contactTestBitMask = 2 } func getTexture(){ let randomTexture = Int(arc4random_uniform(UInt32(textureArray.count))) self.texture = textureArray[randomTexture] } func getSize(){ //static for now self.size = (self.texture?.size())! } func getLocation(frameOriginal: CGRect){ let randomX = Int(arc4random_uniform(UInt32(frameOriginal.width))) let randomY = Int(arc4random_uniform(UInt32(frameOriginal.height * 2))) self.position = CGPoint(x: randomX, y: -randomY ) } func update(scrollSpeed: Double){ self.position = CGPoint(x: self.position.x, y: self.position.y + CGFloat(scrollSpeed)) } }
mit
74005495243a82a9fc2bd8c636da44a6
29.101449
94
0.571016
4.466667
false
false
false
false
devlucky/Kakapo
Tests/SerializationTransformerTests.swift
1
8717
// // SerializationTransformerTests.swift // Kakapo // // Created by Alex Manzella on 27/06/16. // Copyright © 2016 devlucky. All rights reserved. // import Foundation import Quick import Nimble import SwiftyJSON @testable import Kakapo struct UppercaseTransformer<Wrapped: Serializable>: SerializationTransformer { let wrapped: Wrapped func transform(key: String) -> String { return key.uppercased() } } struct LowercaseFirstCharacterTransformer<Wrapped: Serializable>: SerializationTransformer { let wrapped: Wrapped func transform(key: String) -> String { let characters = key.characters let first = String(characters.prefix(1)).lowercased() let other = String(characters.dropFirst()) return first + other } } class SerializationTransformerSpec: QuickSpec { private struct Dog: JSONAPIEntity { let id: String let dogName: String } private struct JUser: JSONAPIEntity { let id: String let userName: String let doggyDog: Dog } struct User: Serializable { let name: String } struct Friend: Serializable { let friends: [User] init(friends: [User]) { self.friends = friends } } struct Snake: Serializable { let theSnakeCamelFriend: String } override func spec() { let user = User(name: "Alex") let friend = Friend(friends: [user]) describe("Serialization Transformers") { it("transforms the keys of a Serializable objects") { let serialized = UppercaseTransformer(wrapped: friend).serialized() as! [String: AnyObject] let friends = serialized["FRIENDS"] as? [AnyObject] let first = friends?.first as? [String: AnyObject] expect(first?.keys.first).to(equal("NAME")) } it("should apply transformations in the right order") { do { let wrapped = UppercaseTransformer(wrapped: friend) let serialized = LowercaseFirstCharacterTransformer(wrapped: wrapped).serialized() as! [String: AnyObject] let friends = serialized["fRIENDS"] as? [AnyObject] let first = friends?.first as? [String: AnyObject] expect(first?.keys.first).to(equal("nAME")) } do { let wrapped = LowercaseFirstCharacterTransformer(wrapped: friend) let serialized = UppercaseTransformer(wrapped: wrapped).serialized() as! [String: AnyObject] let friends = serialized["FRIENDS"] as? [AnyObject] let first = friends?.first as? [String: AnyObject] expect(first?.keys.first).to(equal("NAME")) } } } describe("Snake Case Transformer") { let user = User(name: "Alex") let transformer = SnakecaseTransformer(user) it("should prefix uppercase characters with _") { expect(transformer.transform(key: "userNameOfALuckyUser")).to(equal("user_name_of_a_lucky_user")) } it("should lowercase all characters") { expect(transformer.transform(key: "aLuckyUser")).to(equal("a_lucky_user")) } it("should not prepend _ to the first character when is uppercase") { expect(transformer.transform(key: "ALuckyUser")).to(equal("a_lucky_user")) } it("should not append _ to the last character when is uppercase") { expect(transformer.transform(key: "ALuckyUseR")).to(equal("a_lucky_use_r")) } it("should not touch non-camelCase strings") { expect(transformer.transform(key: "something")).to(equal("something")) } it("should transform correctly the wrapped object's keys") { let snake = Snake(theSnakeCamelFriend: "abc") let serialized = SnakecaseTransformer(snake).serialized() as? [String: AnyObject] expect(serialized?.keys.first).to(equal("the_snake_camel_friend")) } } // CustomSerializable objects need to handle key transformer themselves // every CustomSerializable in Kakapo must be tested here. describe("CustomSerializable needs to handle (or forward) key transformer themselves") { context("Optional") { it("should transform the keys") { let object = Optional.some(friend) let serialized = UppercaseTransformer(wrapped: object).serialized() as! [String: AnyObject] expect(serialized["FRIENDS"]).toNot(beNil()) } } context("PropertyPolicy") { it("should transform the keys") { let object = PropertyPolicy.some(friend) let serialized = UppercaseTransformer(wrapped: object).serialized() as! [String: AnyObject] expect(serialized["FRIENDS"]).toNot(beNil()) } } context("ResponseFieldsProvider") { it("should transform the keys") { let object = Response(statusCode: 200, body: friend) let serialized = UppercaseTransformer(wrapped: object).serialized() as! [String: AnyObject] expect(serialized["FRIENDS"]).toNot(beNil()) } } context("Array") { it("should transform the keys") { let object = [friend] let serialized = UppercaseTransformer(wrapped: object).serialized() as! [[String: AnyObject]] expect(serialized.first?["FRIENDS"]).toNot(beNil()) } } context("Dictionary") { it("should transform the keys") { let object = ["lowercase": friend] let serialized = UppercaseTransformer(wrapped: object).serialized() as! [String: [String: AnyObject]] expect(serialized["LOWERCASE"]?["FRIENDS"]).toNot(beNil()) } } context("JSON API") { it("should transform the keys") { let dog = Dog(id: "22", dogName: "Joan") let user = JUser(id: "11", userName: "Alex", doggyDog: dog) let serialized = SnakecaseTransformer(JSONAPISerializer(user)).serialized() as! [String: AnyObject] let json = JSON(serialized) let data = json["data"].dictionaryValue do { let attributes = data["attributes"]!.dictionaryValue expect(attributes["user_name"]?.string).to(equal("Alex")) } do { let relationships = data["relationships"]?.dictionaryValue let dog = relationships?["doggy_dog"]?.dictionaryValue let dogData = dog?["data"]?.dictionaryValue expect(dogData?["id"]?.string).to(equal("22")) expect(dogData?["type"]?.string).to(equal(Dog.type)) } do { let included = json["included"].arrayValue let dog = included.first?.dictionaryValue expect(dog?["id"]?.string).to(equal("22")) let attributes = dog?["attributes"]?.dictionaryValue expect(attributes?["dog_name"]?.string).to(equal("Joan")) } } } context("JSON API Links") { it("should transform the keys") { let object = JSONAPILink.object(href: "test", meta: friend) let serialized = UppercaseTransformer(wrapped: object).serialized() as! [String: AnyObject] expect(serialized["href"]).toNot(beNil()) let meta = serialized["meta"] as? [String: AnyObject] expect(meta?["FRIENDS"]).toNot(beNil()) } } } } }
mit
6fbf185811c5c29a9e2ccb1d9e59c083
39.165899
126
0.519734
5.327628
false
false
false
false
MillmanY/MMPlayerView
Example/MMPlayerView/Swift/DetailViewController.swift
1
4382
// // DetailViewController.swift // MMPlayerView // // Created by Millman YANG on 2017/8/23. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import MMPlayerView import AVFoundation class DetailViewController: UIViewController { var downloadObservation: MMPlayerObservation? var data: DataObj? { didSet { self.loadViewIfNeeded() if let d = data { self.title = d.title textView.text = d.content } self.addDownloadObservation() } } fileprivate var playerLayer: MMPlayerLayer? @IBOutlet weak var textView: UITextView! @IBOutlet weak var playerContainer: UIView! @IBOutlet weak var downloadBtn: UIButton! @IBOutlet weak var progress: UIProgressView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.mmPlayerTransition.present.pass { (config) in config.duration = 0.3 } } override func viewDidLoad() { super.viewDidLoad() progress.isHidden = true self.automaticallyAdjustsScrollViewInsets = false self.addDownloadObservation() } fileprivate func addDownloadObservation() { guard let downloadURL = self.data?.play_Url else { return } downloadObservation = MMPlayerDownloader.shared.observe(downloadURL: downloadURL) { [weak self] (status) in DispatchQueue.main.async { self?.setWith(status: status) } } } func setWith(status: MMPlayerDownloader.DownloadStatus) { switch status { case .downloadWillStart: self.downloadBtn.isHidden = true self.progress.isHidden = false self.progress.progress = 0 case .cancelled: print("Canceld") case .completed: self.downloadBtn.setTitle("Delete", for: .normal) self.downloadBtn.isHidden = false self.progress.isHidden = true case .downloading(let value): self.downloadBtn.isHidden = true self.progress.isHidden = false self.progress.progress = value case .failed(let err): self.downloadBtn.setTitle("Download", for: .normal) let alert = UIAlertController(title: err, message: "", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) self.downloadBtn.isHidden = false self.progress.isHidden = true case .none: self.downloadBtn.setTitle("Download", for: .normal) self.downloadBtn.isHidden = false self.progress.isHidden = true case .exist: self.downloadBtn.setTitle("Delete", for: .normal) self.downloadBtn.isHidden = false self.progress.isHidden = true } } @IBAction func shrinkVideoAction() { self.playerLayer?.shrinkView(onVC: self, isHiddenVC: true, completedToView: nil) // (self.presentationController as? MMPlayerPassViewPresentatinController)?.shrinkView() } @IBAction func dismiss() { self.dismiss(animated: true, completion: nil) } @IBAction func downloadAction() { guard let downloadURL = self.data?.play_Url else { return } if let info = MMPlayerDownloader.shared.localFileFrom(url: downloadURL) { MMPlayerDownloader.shared.deleteVideo(info) let alert = UIAlertController(title: "Delete completed", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) return } DispatchQueue.main.async { MMPlayerDownloader.shared.download(asset: AVURLAsset(url: downloadURL)) } } deinit { print("DetailViewController deinit") } } extension DetailViewController: MMPlayerToProtocol { func transitionCompleted(player: MMPlayerLayer) { self.playerLayer = player } var containerView: UIView { get { return playerContainer } } }
mit
dd41796ad39fb2f9007c2ae127354183
31.924812
115
0.609272
4.887277
false
false
false
false
xedin/swift
validation-test/stdlib/StringMemoryTest.swift
21
1784
// RUN: %empty-directory(%t) // RUN: %target-build-swift -O %s -o %t/StringMemoryTest // RUN: %target-codesign %t/StringMemoryTest // RUN: %target-run %t/StringMemoryTest | %FileCheck %s // REQUIRES: optimized_stdlib // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation let str = "abcdefg\u{A758}hijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\u{A759}" let str2 = "abcdefg\u{A759}hijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\u{A758}" @inline(never) func getMemoryUsage() -> Int { var usage = rusage() getrusage(RUSAGE_SELF, &usage) return usage.ru_maxrss } @inline(never) func lookup(_ str: String, _ dict: [String: Int]) -> Bool { if let _ = dict[str] { return true } return false } @inline(never) func uppercase(_ str: String) -> String { return str.uppercased() } @inline(never) func lowercase(_ str: String) -> String { return str.lowercased() } @inline(never) func runTest() { for _ in 0 ..< 15_0000 { if lookup("\u{1F1E7}\u{1F1E7}", dict) { print("Found?!") } if uppercase(str) == "A" { print("Found?!") } if lowercase(str2) == "A" { print("Found?!") } } } /// Make sure the hash function does not leak. let dict = [ "foo" : 1] let baseUsage = getMemoryUsage() runTest() let firstRun = getMemoryUsage () - baseUsage runTest() runTest() runTest() let secondRun = getMemoryUsage () - baseUsage // CHECK-NOT: Found?! // CHECK: Not found print("Not found") // CHECK: success // CHECK-NOT: failure if firstRun * 3 < secondRun && firstRun > 10_000 { print("failure - should not linearly increase firstRun: \(firstRun) secondRun: \(secondRun)") } else { print("success firstRun: \(firstRun) secondRun: \(secondRun)") }
apache-2.0
2c168a74627d4110307fa97fd028c6cb
21.024691
107
0.667601
3.261426
false
true
false
false
Moya/Moya
Tests/MoyaTests/Single+MoyaSpec.swift
1
26010
import Quick import Moya import RxSwift import Nimble import Foundation final class SingleMoyaSpec: QuickSpec { override func spec() { describe("status codes filtering") { it("filters out unrequested status codes closed range upperbound") { let data = Data() let single = Response(statusCode: 10, data: data).asSingle() var errored = false _ = single.filter(statusCodes: 0...9).subscribe { event in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes closed range lowerbound") { let data = Data() let single = Response(statusCode: -1, data: data).asSingle() var errored = false _ = single.filter(statusCodes: 0...9).subscribe { event in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes with range upperbound") { let data = Data() let single = Response(statusCode: 10, data: data).asSingle() var errored = false _ = single.filter(statusCodes: 0..<10).subscribe { event in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out unrequested status codes with range lowerbound") { let data = Data() let single = Response(statusCode: -1, data: data).asSingle() var errored = false _ = single.filter(statusCodes: 0..<10).subscribe { event in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out non-successful status codes") { let data = Data() let single = Response(statusCode: 404, data: data).asSingle() var errored = false _ = single.filterSuccessfulStatusCodes().subscribe { event in switch event { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = Data() let single = Response(statusCode: 200, data: data).asSingle() var called = false _ = single.filterSuccessfulStatusCodes().subscribe(onSuccess: { _ in called = true }) expect(called).to(beTruthy()) } it("filters out non-successful status and redirect codes") { let data = Data() let single = Response(statusCode: 404, data: data).asSingle() var errored = false _ = single.filterSuccessfulStatusAndRedirectCodes().subscribe { event in switch event { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = Data() let single = Response(statusCode: 200, data: data).asSingle() var called = false _ = single.filterSuccessfulStatusAndRedirectCodes().subscribe(onSuccess: { _ in called = true }) expect(called).to(beTruthy()) } it("passes through correct redirect codes") { let data = Data() let single = Response(statusCode: 304, data: data).asSingle() var called = false _ = single.filterSuccessfulStatusAndRedirectCodes().subscribe(onSuccess: { _ in called = true }) expect(called).to(beTruthy()) } it("knows how to filter individual status code") { let data = Data() let single = Response(statusCode: 42, data: data).asSingle() var called = false _ = single.filter(statusCode: 42).subscribe(onSuccess: { _ in called = true }) expect(called).to(beTruthy()) } it("filters out different individual status code") { let data = Data() let single = Response(statusCode: 43, data: data).asSingle() var errored = false _ = single.filter(statusCode: 42).subscribe { event in switch event { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } } describe("image maping") { it("maps data representing an image to an image") { let image = Image.testImage guard let data = image.asJPEGRepresentation(0.75) else { fatalError("Failed creating Data from Image") } let single = Response(statusCode: 200, data: data).asSingle() var size: CGSize? _ = single.mapImage().subscribe(onSuccess: { image in size = image.size }) expect(size).to(equal(image.size)) } it("ignores invalid data") { let data = Data() let single = Response(statusCode: 200, data: data).asSingle() var receivedError: MoyaError? _ = single.mapImage().subscribe { event in switch event { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error as? MoyaError } } expect(receivedError).toNot(beNil()) let expectedError = MoyaError.imageMapping(Response(statusCode: 200, data: Data(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } describe("JSON mapping") { it("maps data representing some JSON to that JSON") { let json = ["name": "John Crighton", "occupation": "Astronaut"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { fatalError("Failed creating Data from JSON dictionary") } let single = Response(statusCode: 200, data: data).asSingle() var receivedJSON: [String: String]? _ = single.mapJSON().subscribe(onSuccess: { json in if let json = json as? [String: String] { receivedJSON = json } }) expect(receivedJSON?["name"]).to(equal(json["name"])) expect(receivedJSON?["occupation"]).to(equal(json["occupation"])) } it("returns a Cocoa error domain for invalid JSON") { let json = "{ \"name\": \"john }" guard let data = json.data(using: .utf8) else { fatalError("Failed creating Data from JSON String") } let single = Response(statusCode: 200, data: data).asSingle() var receivedError: MoyaError? _ = single.mapJSON().subscribe { event in switch event { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error as? MoyaError } } expect(receivedError).toNot(beNil()) switch receivedError { case .some(.jsonMapping): break default: fail("expected NSError with \(NSCocoaErrorDomain) domain") } } } describe("string mapping") { it("maps data representing a string to a string") { let string = "You have the rights to the remains of a silent attorney." guard let data = string.data(using: .utf8) else { fatalError("Failed creating Data from String") } let single = Response(statusCode: 200, data: data).asSingle() var receivedString: String? _ = single.mapString().subscribe(onSuccess: { string in receivedString = string }) expect(receivedString).to(equal(string)) } it("maps data representing a string at a key path to a string") { let string = "You have the rights to the remains of a silent attorney." let json = ["words_to_live_by": string] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { fatalError("Failed creating Data from JSON dictionary") } let single = Response(statusCode: 200, data: data).asSingle() var receivedString: String? _ = single.mapString(atKeyPath: "words_to_live_by").subscribe(onSuccess: { string in receivedString = string }) expect(receivedString).to(equal(string)) } it("ignores invalid data") { let data = Data(bytes: [0x11FFFF] as [UInt32], count: 1) //Byte exceeding UTF8 let single = Response(statusCode: 200, data: data).asSingle() var receivedError: MoyaError? _ = single.mapString().subscribe { event in switch event { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error as? MoyaError } } expect(receivedError).toNot(beNil()) let expectedError = MoyaError.stringMapping(Response(statusCode: 200, data: Data(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } describe("object mapping") { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(formatter) let json: [String: Any] = [ "title": "Hello, Moya!", "createdAt": "1995-01-14T12:34:56" ] it("maps data representing a json to a decodable object") { guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let single = Response(statusCode: 200, data: data).asSingle() var receivedObject: Issue? _ = single.map(Issue.self, using: decoder).subscribe(onSuccess: { object in receivedObject = object }) expect(receivedObject).notTo(beNil()) expect(receivedObject?.title) == "Hello, Moya!" expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps data representing a json array to an array of decodable objects") { let jsonArray = [json, json, json] guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let single = Response(statusCode: 200, data: data).asSingle() var receivedObjects: [Issue]? _ = single.map([Issue].self, using: decoder).subscribe(onSuccess: { objects in receivedObjects = objects }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 3 expect(receivedObjects?.map { $0.title }) == ["Hello, Moya!", "Hello, Moya!", "Hello, Moya!"] } it("maps empty data to a decodable object with optional properties") { let single = Response(statusCode: 200, data: Data()).asSingle() var receivedObjects: OptionalIssue? _ = single.map(OptionalIssue.self, using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.title).to(beNil()) expect(receivedObjects?.createdAt).to(beNil()) } it("maps empty data to a decodable array with optional properties") { let single = Response(statusCode: 200, data: Data()).asSingle() var receivedObjects: [OptionalIssue]? _ = single.map([OptionalIssue].self, using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title).to(beNil()) expect(receivedObjects?.first?.createdAt).to(beNil()) } context("when using key path mapping") { it("maps data representing a json to a decodable object") { let json: [String: Any] = ["issue": json] // nested json guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let single = Response(statusCode: 200, data: data).asSingle() var receivedObject: Issue? _ = single.map(Issue.self, atKeyPath: "issue", using: decoder).subscribe(onSuccess: { object in receivedObject = object }) expect(receivedObject).notTo(beNil()) expect(receivedObject?.title) == "Hello, Moya!" expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps data representing a json array to a decodable object (#1311)") { let json: [String: Any] = ["issues": [json]] // nested json array guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let single = Response(statusCode: 200, data: data).asSingle() var receivedObjects: [Issue]? _ = single.map([Issue].self, atKeyPath: "issues", using: decoder).subscribe(onSuccess: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title) == "Hello, Moya!" expect(receivedObjects?.first?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")! } it("maps empty data to a decodable object with optional properties") { let single = Response(statusCode: 200, data: Data()).asSingle() var receivedObjects: OptionalIssue? _ = single.map(OptionalIssue.self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.title).to(beNil()) expect(receivedObjects?.createdAt).to(beNil()) } it("maps empty data to a decodable array with optional properties") { let single = Response(statusCode: 200, data: Data()).asSingle() var receivedObjects: [OptionalIssue]? _ = single.map([OptionalIssue].self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in receivedObjects = object }) expect(receivedObjects).notTo(beNil()) expect(receivedObjects?.count) == 1 expect(receivedObjects?.first?.title).to(beNil()) expect(receivedObjects?.first?.createdAt).to(beNil()) } it("map Int data to an Int value") { let json: [String: Any] = ["count": 1] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asSingle() var count: Int? _ = observable.map(Int.self, atKeyPath: "count", using: decoder).subscribe(onSuccess: { value in count = value }) expect(count).notTo(beNil()) expect(count) == 1 } it("map Bool data to a Bool value") { let json: [String: Any] = ["isNew": true] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asSingle() var isNew: Bool? _ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onSuccess: { value in isNew = value }) expect(isNew).notTo(beNil()) expect(isNew) == true } it("map String data to a String value") { let json: [String: Any] = ["description": "Something interesting"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asSingle() var description: String? _ = observable.map(String.self, atKeyPath: "description", using: decoder).subscribe(onSuccess: { value in description = value }) expect(description).notTo(beNil()) expect(description) == "Something interesting" } it("map String data to a URL value") { let json: [String: Any] = ["url": "http://www.example.com/test"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asSingle() var url: URL? _ = observable.map(URL.self, atKeyPath: "url", using: decoder).subscribe(onSuccess: { value in url = value }) expect(url).notTo(beNil()) expect(url) == URL(string: "http://www.example.com/test") } it("shouldn't map Int data to a Bool value") { let json: [String: Any] = ["isNew": 1] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asSingle() var isNew: Bool? _ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onSuccess: { value in isNew = value }) expect(isNew).to(beNil()) } it("shouldn't map String data to an Int value") { let json: [String: Any] = ["test": "123"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asSingle() var test: Int? _ = observable.map(Int.self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in test = value }) expect(test).to(beNil()) } it("shouldn't map Array<String> data to an String value") { let json: [String: Any] = ["test": ["123", "456"]] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asSingle() var test: String? _ = observable.map(String.self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in test = value }) expect(test).to(beNil()) } it("shouldn't map String data to an Array<String> value") { let json: [String: Any] = ["test": "123"] guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let observable = Response(statusCode: 200, data: data).asSingle() var test: [String]? _ = observable.map([String].self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in test = value }) expect(test).to(beNil()) } } it("ignores invalid data") { var json = json json["createdAt"] = "Hahaha" // invalid date string guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else { preconditionFailure("Failed creating Data from JSON dictionary") } let single = Response(statusCode: 200, data: data).asSingle() var receivedError: Error? _ = single.map(Issue.self, using: decoder).subscribe { event in switch event { case .success: fail("success called for invalid data") case .failure(let error): receivedError = error } } if case let MoyaError.objectMapping(nestedError, _)? = receivedError { expect(nestedError).to(beAKindOf(DecodingError.self)) } else { fail("expected <MoyaError.objectMapping>, got <\(String(describing: receivedError))>") } } } } }
mit
0892e3c1d26778d5a3af81ea2cd2c479
43.385666
150
0.495771
5.695205
false
false
false
false
dimitardanailov/Stanford-CS193P-Spring-2015-Cassini
Cassini/ViewController.swift
1
859
// // ViewController.swift // Cassini // // Created by dimitar on 9/3/15. // Copyright (c) 2015 dimityr.danailov. All rights reserved. // import UIKit class ViewController: UIViewController { override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let ivc = segue.destinationViewController as? ImageViewController { if let identifier = segue.identifier { ivc.title = identifier switch identifier { case "Earth": ivc.imageURL = DemoURL.NASA.Earth case "Cassini": ivc.imageURL = DemoURL.NASA.Cassini case "Saturn": ivc.imageURL = DemoURL.NASA.Saturn default: break } } } } }
mit
b4cb3cf48a57e850708e23de9930cf9d
25.84375
81
0.527357
4.880682
false
false
false
false
ibm-bluemix-mobile-services/bms-clientsdk-swift-analytics
Tests/Test Apps/TestApp iOS/LoggerViewController.swift
1
14194
/* *     Copyright 2016 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ import UIKit import BMSCore import BMSAnalytics import CoreLocation #if swift(>=3.0) class LoggerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var currentLogLevel = "Debug" var currentLogLevelFilter = "Debug" let locationManager = CLLocationManager() // MARK: Outlets @IBOutlet var logLevelPicker: UIPickerView! @IBOutlet var logLevelFilterPicker: UIPickerView! @IBOutlet var loggerNameField: UITextField! @IBOutlet var logMessageField: UITextField! @IBOutlet var maxStoreSizeField: UITextField! @IBOutlet var logStorageEnabledSwitch: UISwitch! @IBOutlet var internalSdkLoggingSwitch: UISwitch! // MARK: Button presses // Ignore the warning on the extraneous underscore in Swift 2. It is there for Swift 3. // This logs the message written in the `logMessageField` and separately logs the user's current location. @IBAction func recordLog(_ sender: UIButton) { Analytics.log(metadata: ["buttonPressed": "recordLog"]) if let maxStoreSize = maxStoreSizeField.text { Logger.maxLogStoreSize = UInt64(maxStoreSize) ?? 100000 } Logger.isLogStorageEnabled = logStorageEnabledSwitch.isOn Logger.isInternalDebugLoggingEnabled = internalSdkLoggingSwitch.isOn switch currentLogLevelFilter { case "None": Logger.logLevelFilter = LogLevel.none case "Analytics": Logger.logLevelFilter = LogLevel.analytics case "Fatal": Logger.logLevelFilter = LogLevel.fatal case "Error": Logger.logLevelFilter = LogLevel.error case "Warn": Logger.logLevelFilter = LogLevel.warn case "Info": Logger.logLevelFilter = LogLevel.info case "Debug": Logger.logLevelFilter = LogLevel.debug default: break } let logger = Logger.logger(name:loggerNameField.text ?? "TestAppiOS") switch currentLogLevel { case "None": print("Cannot log at the 'None' level") case "Analytics": print("Cannot log at the 'Analytics' level") case "Fatal": logger.fatal(message: logMessageField.text ?? "") case "Error": logger.error(message: logMessageField.text ?? "") case "Warn": logger.warn(message: logMessageField.text ?? "") case "Info": logger.info(message: logMessageField.text ?? "") case "Debug": logger.debug(message: logMessageField.text ?? "") default: break } Analytics.logLocation() } @IBAction func recordLocation(_ sender: UIButton) { Analytics.logLocation() } // Ignore the warning on the extraneous underscore in Swift 2. It is there for Swift 3. @IBAction func sendLogs(_ sender: UIButton) { func completionHandler(sentUsing sendType: String) -> BMSCompletionHandler { return { (response: Response?, error: Error?) -> Void in if let response = response { print("\n\(sendType) sent successfully: " + String(response.isSuccessful)) print("Status code: " + String(describing: response.statusCode)) if let responseText = response.responseText { print("Response text: " + responseText) } print("\n") } } } Logger.send(completionHandler: completionHandler(sentUsing: "Logs")) Analytics.send(completionHandler: completionHandler(sentUsing: "Analytics")) } // Ignore the warning on the extraneous underscore in Swift 2. It is there for Swift 3. @IBAction func deleteLogs(_ sender: UIButton) { Analytics.log(metadata: ["buttonPressed": "deleteLogs"]) let filePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/" let fileName = "bmssdk.logger.log" do { try FileManager().removeItem(atPath: filePath + fileName) print("Successfully deleted logs!") } catch { print("Failed to delete logs!") } } @IBAction func changeUserId(_ sender: UIButton) { Analytics.userIdentity = String(Date().timeIntervalSince1970) } // Ignore the warning on the extraneous underscore in Swift 2. It is there for Swift 3. @IBAction func triggerUncaughtException(_ sender: UIButton) { Analytics.log(metadata: ["buttonPressed": "triggerUncaughtException"]) NSException(name: NSExceptionName("Test crash"), reason: "Ensure that BMSAnalytics framework is catching uncaught exceptions", userInfo: nil).raise() } // Ignore the warning on the extraneous underscore in Swift 2. It is there for Swift 3. @IBAction func triggerFeedbackMode(_ sender: UIButton) { Analytics.triggerFeedbackMode() } // MARK: UIPickerViewDelegate protocol let logLevels = ["Debug", "Info", "Warn", "Error", "Fatal", "Analytics", "None"] func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return logLevels.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return logLevels[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch pickerView.tag { case 0: currentLogLevel = logLevels[row] case 1: currentLogLevelFilter = logLevels[row] default: break } } // MARK: UIViewController protocol override func viewDidLoad() { super.viewDidLoad() self.logLevelPicker.dataSource = self self.logLevelPicker.delegate = self self.logLevelFilterPicker.dataSource = self self.logLevelFilterPicker.delegate = self // Should print true if the "Trigger Uncaught Exception" button was pressed in the last app session print("Uncaught Exception Detected: \(Logger.isUncaughtExceptionDetected)") // Get user permission to use location services if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined { self.locationManager.requestWhenInUseAuthorization() } } } /**************************************************************************************************/ // MARK: - Swift 2 #else class LoggerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var currentLogLevel = "Debug" var currentLogLevelFilter = "Debug" let locationManager = CLLocationManager() // MARK: Outlets @IBOutlet var logLevelPicker: UIPickerView! @IBOutlet var logLevelFilterPicker: UIPickerView! @IBOutlet var loggerNameField: UITextField! @IBOutlet var logMessageField: UITextField! @IBOutlet var maxStoreSizeField: UITextField! @IBOutlet var logStorageEnabledSwitch: UISwitch! @IBOutlet var internalSdkLoggingSwitch: UISwitch! // MARK: Button presses // This logs the message written in the `logMessageField` and separately logs the user's current location. @IBAction func recordLog(sender: UIButton) { Analytics.log(metadata: ["buttonPressed": "recordLog"]) if let maxStoreSize = maxStoreSizeField.text { Logger.maxLogStoreSize = UInt64(maxStoreSize) ?? 100000 } Logger.isLogStorageEnabled = logStorageEnabledSwitch.on Logger.isInternalDebugLoggingEnabled = internalSdkLoggingSwitch.on switch currentLogLevelFilter { case "None": Logger.logLevelFilter = LogLevel.none case "Analytics": Logger.logLevelFilter = LogLevel.analytics case "Fatal": Logger.logLevelFilter = LogLevel.fatal case "Error": Logger.logLevelFilter = LogLevel.error case "Warn": Logger.logLevelFilter = LogLevel.warn case "Info": Logger.logLevelFilter = LogLevel.info case "Debug": Logger.logLevelFilter = LogLevel.debug default: break } let logger = Logger.logger(name:loggerNameField.text ?? "TestAppiOS") switch currentLogLevel { case "None": print("Cannot log at the 'None' level") case "Analytics": print("Cannot log at the 'Analytics' level") case "Fatal": logger.fatal(message: logMessageField.text ?? "") case "Error": logger.error(message: logMessageField.text ?? "") case "Warn": logger.warn(message: logMessageField.text ?? "") case "Info": logger.info(message: logMessageField.text ?? "") case "Debug": logger.debug(message: logMessageField.text ?? "") default: break } Analytics.logLocation() } @IBAction func recordLocation(sender: UIButton) { Analytics.logLocation() } @IBAction func sendLogs(sender: UIButton) { func completionHandler(sentUsing sendType: String) -> BMSCompletionHandler { return { (response: Response?, error: NSError?) -> Void in if let response = response { print("\n\(sendType) sent successfully: " + String(response.isSuccessful)) print("Status code: " + String(response.statusCode)) if let responseText = response.responseText { print("Response text: " + responseText) } print("\n") } } } Logger.send(completionHandler: completionHandler(sentUsing: "Logs")) Analytics.send(completionHandler: completionHandler(sentUsing: "Analytics")) } @IBAction func deleteLogs(sender: UIButton) { Analytics.log(metadata: ["buttonPressed": "deleteLogs"]) let filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] + "/" let fileName = "bmssdk.logger.log" do { try NSFileManager().removeItemAtPath(filePath + fileName) print("Successfully deleted logs!") } catch { print("Failed to delete logs!") } } @IBAction func changeUserId(sender: UIButton) { Analytics.userIdentity = String(NSDate().timeIntervalSince1970) } @IBAction func triggerUncaughtException(sender: UIButton) { Analytics.log(metadata: ["buttonPressed": "triggerUncaughtException"]) NSException(name: "Test crash", reason: "Ensure that BMSAnalytics framework is catching uncaught exceptions", userInfo: nil).raise() } // MARK: UIPickerViewDelegate protocol let logLevels = ["Debug", "Info", "Warn", "Error", "Fatal", "Analytics", "None"] func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return logLevels.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return logLevels[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch pickerView.tag { case 0: currentLogLevel = logLevels[row] case 1: currentLogLevelFilter = logLevels[row] default: break } } // MARK: UIViewController protocol override func viewDidLoad() { super.viewDidLoad() self.logLevelPicker.dataSource = self self.logLevelPicker.delegate = self self.logLevelFilterPicker.dataSource = self self.logLevelFilterPicker.delegate = self // Should print true if the "Trigger Uncaught Exception" button was pressed in the last app session print("Uncaught Exception Detected: \(Logger.isUncaughtExceptionDetected)") // Get user permission to use location services if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined { self.locationManager.requestWhenInUseAuthorization() } } } #endif
apache-2.0
4dcc58c4306b52e5bd2e6778aee02124
30.405765
157
0.596089
5.498447
false
false
false
false
vinsan/presteasymo
presteasymo/presteasymo/Login.swift
1
602
// // Login.swift // presteasymo // // Created by Fabio Mazzotta on 06/04/17. // Copyright © 2017 Team 2.4. All rights reserved. // import UIKit class Login: NSObject { var gestoreprelievi:GestoreCoreDataPrelievo=GestoreCoreDataPrelievo() var gestAccess: CoreDataController=CoreDataController() func login(username: String,password:String)->User?{ let users=gestoreprelievi.getUser() for utente in users{ if((utente.username!==username)&&(utente.password!==password)){ return utente } } return nil } }
apache-2.0
adac218d0d6c3123e5e32bebc13382d4
24.041667
75
0.637271
3.687117
false
false
false
false
llwei/LWPickerView
LWPickerView/PickerView.swift
1
32086
// // PickerView.swift // PickerView // // Created by lailingwei on 16/4/28. // Copyright © 2016年 lailingwei. All rights reserved. // import UIKit typealias PickerAllCancelHandler = (() -> Void) typealias PickerTypeDataSourceDoneHandler = ((_ selectedRows: [Int], _ results: [String]) -> Void) typealias PickerTypeDateDoneHandler = ((_ selectedDate: Date, _ dateString: String?) -> Void) typealias PickerTypeAreaDoneHandler = ((_ province: String?, _ city: String?, _ district: String?) -> Void) typealias PickerColors = (toolbarColor: UIColor, itemColor: UIColor, pickerColor: UIColor) typealias PickerItemTitles = (cancelTitle: String?, centerTitle: String?, doneTitle: String?) /** 当前控件类型 - DataSource: 数据源类型Picker - Date: 系统日期Picker - Area: 国内地区Picker */ @objc private enum PickerType: Int { case dataSource = 1 case date = 2 case area = 3 } /** 地区选择器类型 - ProvinceCityDistrict: 省市区三级 - ProvinceCity: 省市二级 */ @objc enum AreaType: Int { case provinceCityDistrict = 1 case provinceCity = 2 } class PickerView: UIView, UIPickerViewDataSource, UIPickerViewDelegate, UIGestureRecognizerDelegate { fileprivate struct DefaultValue { static let pickerHeight: CGFloat = 216 static let toolBarHeight: CGFloat = 44 static let dismissDuration: TimeInterval = 0.3 static let showDuration: TimeInterval = 0.4 static var itemTitles: PickerItemTitles = (" 取消", nil, "确定 ") static var pickerColors: PickerColors = (UIColor.groupTableViewBackground, UIColor.darkGray, UIColor.white) } // MARK: - Properties fileprivate var pickerType = PickerType.dataSource fileprivate var contentView = UIView() fileprivate var pickerView: UIView! fileprivate var cancelHandler: PickerAllCancelHandler? fileprivate var contentBottomConstraint: NSLayoutConstraint! fileprivate var windowHoriConstraints: [NSLayoutConstraint]? fileprivate var windowVertConstraints: [NSLayoutConstraint]? /* ******************************************** @Type: PickerType.DataSource ******************************************** */ fileprivate lazy var dataSourceAry: [[String]] = { return [[String]]() }() fileprivate var selectedRowAry: [Int] = { return [Int]() }() fileprivate var selectedResultAry: [String] = { return [String]() }() fileprivate var maxValueInRowsAry: [Int]? fileprivate var dataSourceTypeDoneHandler: PickerTypeDataSourceDoneHandler? /* ******************************************** @Type: PickerType.DateMode ******************************************** */ fileprivate lazy var dateFormatter: DateFormatter = { return DateFormatter() }() fileprivate var datePickerMode: UIDatePickerMode = .date fileprivate var dateModeTypeDoneHandler: PickerTypeDateDoneHandler? /* ******************************************** @Type: PickerType.AreaMode ******************************************** */ fileprivate var areaType: AreaType = .provinceCityDistrict fileprivate lazy var areaSource: [[String : Any]] = { return [[String : Any]]() }() fileprivate var cities = [[String : Any]]() fileprivate var districts = [String]() fileprivate var province: String? fileprivate var city: String? fileprivate var district: String? fileprivate var areaTypeDoneHandler: PickerTypeAreaDoneHandler? // MARK: - Life cycle fileprivate override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { print("\(NSStringFromClass(PickerView.self)).deinit") } // 配置底层遮罩视图 fileprivate func setupMaskView() { isUserInteractionEnabled = true // Add tap gesture to dismiss Self let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PickerView.dismiss)) tapGestureRecognizer.delegate = self addGestureRecognizer(tapGestureRecognizer) } // 配置内容部分底视图 fileprivate func setupContentView() { contentView.backgroundColor = UIColor.white let toolBar = setupToolBar() pickerView = setupPickerView() addSubview(contentView) contentView.addSubview(toolBar) contentView.addSubview(pickerView) // add constraints contentViewAddConstraints() addConstraintsWithToolBar(toolBar: toolBar, pickerView: pickerView) } // 配置工具条 fileprivate func setupToolBar() -> UIToolbar { // space Item let spaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) // Cancel Item let cancelTitle = DefaultValue.itemTitles.cancelTitle let leftItem = UIBarButtonItem(title: cancelTitle, style: .done, target: self, action: (cancelTitle?.isEmpty == false) ? #selector(PickerView.dismiss) : nil) leftItem.tintColor = DefaultValue.pickerColors.itemColor // Title Item let centerLabel = UILabel() centerLabel.text = DefaultValue.itemTitles.centerTitle centerLabel.textColor = DefaultValue.pickerColors.itemColor let titleItem = UIBarButtonItem(customView: centerLabel) // Done Item let rightItem = UIBarButtonItem(title: DefaultValue.itemTitles.doneTitle, style: .done, target: self, action: #selector(PickerView.done)) rightItem.tintColor = DefaultValue.pickerColors.itemColor // ToolBar let toolBar = UIToolbar(frame: CGRect.zero) toolBar.barTintColor = DefaultValue.pickerColors.toolbarColor toolBar.items = [leftItem, spaceItem, titleItem, spaceItem, rightItem] return toolBar } // 配置PickerView fileprivate func setupPickerView() -> UIView { var picker: UIView! switch pickerType { case .date: picker = UIDatePicker(frame: CGRect.zero) (picker as! UIDatePicker).datePickerMode = datePickerMode default: picker = UIPickerView(frame: CGRect.zero) (picker as! UIPickerView).dataSource = self (picker as! UIPickerView).delegate = self break } picker.backgroundColor = DefaultValue.pickerColors.pickerColor return picker } // MARK: - Target actions @objc func dismiss() { dismissSelf() cancelHandler?() } @objc func done() { dismissSelf() switch pickerType { case .dataSource: guard dataSourceAry.count > 0 else { print("当前Picker数据源数量为0") return } dataSourceTypeDoneHandler?(selectedRowAry, selectedResultAry) case .area: areaTypeDoneHandler?(province, city, district) case .date: if let datePicker = pickerView as? UIDatePicker { dateModeTypeDoneHandler?(datePicker.date, dateFormatter.string(from: datePicker.date)) } } } // MARK: - Helper methods fileprivate func dismissSelf() { UIView.animate(withDuration: DefaultValue.dismissDuration, animations: { self.backgroundColor = UIColor.black.withAlphaComponent(0.0) self.contentBottomConstraint.constant = DefaultValue.pickerHeight + DefaultValue.toolBarHeight self.layoutIfNeeded() }) { (flag:Bool) in if flag { self.windowRemoveConstraints() self.removeFromSuperview() } } } // MARK: - Helper for constraints fileprivate func contentViewAddConstraints() { contentView.translatesAutoresizingMaskIntoConstraints = false let horiConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[contentView]|", options: .directionLeadingToTrailing, metrics: nil, views: ["contentView" : contentView]) contentBottomConstraint = NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0) let heightConstraint = NSLayoutConstraint(item: contentView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: DefaultValue.pickerHeight + DefaultValue.toolBarHeight) if #available(iOS 8.0, *) { NSLayoutConstraint.activate(horiConstraints) NSLayoutConstraint.activate([contentBottomConstraint, heightConstraint]) } else { addConstraints(horiConstraints) addConstraint(contentBottomConstraint) addConstraint(heightConstraint) } } fileprivate func windowAddConstraints() { translatesAutoresizingMaskIntoConstraints = false windowHoriConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[self]|", options: .directionLeadingToTrailing, metrics: nil, views: ["self" : self]) windowVertConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[self]|", options: .directionLeadingToTrailing, metrics: nil, views: ["self" : self]) if #available(iOS 8.0, *) { NSLayoutConstraint.activate(windowHoriConstraints!) NSLayoutConstraint.activate(windowVertConstraints!) } else { addConstraints(windowHoriConstraints!) addConstraints(windowVertConstraints!) } } fileprivate func windowRemoveConstraints() { if let horiConstraints = windowHoriConstraints { removeConstraints(horiConstraints) } if let vertConstraints = windowVertConstraints { removeConstraints(vertConstraints) } } private func addConstraintsWithToolBar(toolBar: UIToolbar, pickerView: UIView) { // ToolBar toolBar.translatesAutoresizingMaskIntoConstraints = false let horiForToolBarConstrants = NSLayoutConstraint.constraints(withVisualFormat: "H:|[toolBar]|", options: .directionLeadingToTrailing, metrics: nil, views: ["toolBar" : toolBar]) let heightForToolBarConstrant = NSLayoutConstraint(item: toolBar, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: DefaultValue.toolBarHeight) // PickerView pickerView.translatesAutoresizingMaskIntoConstraints = false let horiForPickerConstrants = NSLayoutConstraint.constraints(withVisualFormat: "H:|[pickerView]|", options: .directionLeadingToTrailing, metrics: nil, views: ["pickerView" : pickerView]) let heightForPickerConstrant = NSLayoutConstraint(item: pickerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: DefaultValue.pickerHeight) // Vert let vertConstrants = NSLayoutConstraint.constraints(withVisualFormat: "V:|[toolBar][pickerView]|", options: .directionLeadingToTrailing, metrics: nil, views: ["toolBar" : toolBar, "pickerView" : pickerView]) contentView.addConstraints(horiForToolBarConstrants) contentView.addConstraint(heightForToolBarConstrant) contentView.addConstraints(horiForPickerConstrants) contentView.addConstraint(heightForPickerConstrant) contentView.addConstraints(vertConstrants) } private func handleMaxValueInRowsWithCurrentRow(row: Int, compont: Int) { guard let maxValueInRowsAry = self.maxValueInRowsAry else { return; } for index in 0..<dataSourceAry.count { let selectedRow = selectedRowAry[index] let maxRow = maxValueInRowsAry[index] if selectedRow < maxRow { return } (pickerView as! UIPickerView).selectRow(maxRow, inComponent: index, animated: true) selectedRowAry[index] = maxRow selectedResultAry[index] = dataSourceAry[index][maxRow] } } // MARK: - UIPicker dataSource / delegate func numberOfComponents(in pickerView: UIPickerView) -> Int { switch pickerType { case .dataSource: return dataSourceAry.count case .area: return areaType == .provinceCityDistrict ? 3 : 2; case .date: return 0 } } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch pickerType { case .dataSource: return dataSourceAry[component].count case .area: switch areaType { case .provinceCityDistrict: switch component { case 0: // 省 return areaSource.count case 1: // 市 return cities.count case 2: // 区 return districts.count default: return 0 } case .provinceCity: switch component { case 0: // 省 return areaSource.count case 1: // 市 return cities.count default: return 0 } } case .date: return 0 } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch pickerType { case .dataSource: return dataSourceAry[component][row] case .area: switch areaType { case .provinceCityDistrict: switch component { case 0: // 省 return areaSource[row]["state"] as? String case 1: // 市 return cities[row]["city"] as? String case 2: // 区 return districts[row] default: return nil } case .provinceCity: switch component { case 0: // 省 return areaSource[row]["state"] as? String case 1: // 市 return cities[row]["city"] as? String default: return nil } } case .date: return nil } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch pickerType { case .dataSource: selectedRowAry[component] = row selectedResultAry[component] = dataSourceAry[component][row] if let _ = self.maxValueInRowsAry { // 处理每列最大值 handleMaxValueInRowsWithCurrentRow(row: row, compont: component) } case .area: switch areaType { case .provinceCityDistrict: switch component { case 0: // 省 guard areaSource.count > 0 else { return } province = areaSource[row]["state"] as? String if let theCities = areaSource[row]["cities"] as? [[String : Any]] { cities = theCities city = cities.first?["city"] as? String if let theDistricts = cities.first?["areas"] as? [String] { districts = theDistricts district = theDistricts.first } else { district = nil } } else { city = nil district = nil } pickerView.selectRow(0, inComponent: 1, animated: true) pickerView.reloadComponent(1) pickerView.selectRow(0, inComponent: 2, animated: true) pickerView.reloadComponent(2) case 1: // 市 guard cities.count > 0 else { return } city = cities[row]["city"] as? String if let theDistricts = cities[row]["areas"] as? [String] { districts = theDistricts district = theDistricts.first } else { district = nil } pickerView.selectRow(0, inComponent: 2, animated: true) pickerView.reloadComponent(2) case 2: // 区 guard districts.count > 0 else { return } district = districts[row] default: break } case .provinceCity: switch component { case 0: // 省 guard areaSource.count > 0 else { return } province = areaSource[row]["state"] as? String if let theCities = areaSource[row]["cities"] as? [[String : Any]] { cities = theCities city = cities.first?["city"] as? String } else { city = nil } pickerView.selectRow(0, inComponent: 1, animated: true) pickerView.reloadComponent(1) case 1: // 市 guard cities.count > 0 else { return } city = cities[row]["city"] as? String default: break } } case .date: break } } // MARK: - UIGesture delegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { // 确保点击dismiss时,手势区域在有效区域 guard let touchView = touch.view else { return false } return touchView.isKind(of: PickerView.self) } // MARK: - ================== Public methods ================== /** 显示PickerView */ func show() { guard let window = UIApplication.shared.keyWindow else { print("当前window为空") return } backgroundColor = UIColor.black.withAlphaComponent(0.4) window.addSubview(self) windowAddConstraints() contentBottomConstraint.constant = DefaultValue.pickerHeight + DefaultValue.toolBarHeight layoutIfNeeded() UIView.animate(withDuration: DefaultValue.showDuration, delay: 0.1, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: .curveEaseOut, animations: { self.contentBottomConstraint.constant = 0 self.layoutIfNeeded() }, completion: nil) } /** 取消回调 */ func didClickCancelHandler(handler: PickerAllCancelHandler?) { cancelHandler = handler } } // MARK: - DataSource extension PickerView { /** 初始化一个数据源类型的Picker - parameter dataSource: 数据源 - parameter itemTitles: 标题 - parameter pickerColors: 颜色 */ convenience init(aDataSources: [[String]], itemTitles: PickerItemTitles? = nil, pickerColors: PickerColors? = nil) { self.init(frame: CGRect.zero) if aDataSources.count == 0 { print("\(NSStringFromClass(PickerView.self))数据源数量不应为空") } if let titles = itemTitles { DefaultValue.itemTitles = titles } if let colors = pickerColors { DefaultValue.pickerColors = colors } pickerType = .dataSource dataSourceAry = aDataSources selectedRowAry = Array(repeatElement(0, count: aDataSources.count)) selectedResultAry = [String]() for index in 0..<aDataSources.count { guard let result = aDataSources[index].first else { assertionFailure("picker中第\(index)组数据为空数据") return } selectedResultAry.append(result) } setupMaskView() setupContentView() } /** 滚动到对应的行 - parameter aRows: 对应的行数组 - parameter animated: 是否动画滚动 */ func showSelectedRows(aRows: [Int], animated: Bool) { guard pickerType == .dataSource else { print("当前PickerType不为DataSource") return } guard aRows.count == dataSourceAry.count else { print("目标row的数量与dataSourceAry数量不一致") return } // 更新选择的行和值 for index in 0..<aRows.count { let selectedRow: Int = aRows[index] guard selectedRow >= 0 else { print("目标行为负数"); return } let selectedResult: String = dataSourceAry[index][selectedRow] (pickerView as! UIPickerView).selectRow(selectedRow, inComponent: index, animated: animated) selectedRowAry[index] = selectedRow selectedResultAry[index] = selectedResult } } /** dataSource类型Picker点击确定回调 */ func didClickDoneForTypeDataSourceHandler(handler: PickerTypeDataSourceDoneHandler?) { guard pickerType == .dataSource else { print("当前PickerType不为dataSource") return } dataSourceTypeDoneHandler = handler } /** 设置最大值时,对应各个row的值 */ func setMaxValuesInRows(maxValueInRowAry: [Int]) { guard pickerType == .dataSource else { print("当前PickerType不为DataSource") return; } guard maxValueInRowAry.count == dataSourceAry.count else { print("设置最大值的列数,与数据源列数不一致") return; } self.maxValueInRowsAry = maxValueInRowAry } } // MARK: - Date extension PickerView { /** 初始化一个日期Picker - parameter aDatePickerMode: 日期类型 - parameter itemTitles: 标题 - parameter pickerColors: 颜色 */ convenience init(aDatePickerMode: UIDatePickerMode, itemTitles: PickerItemTitles? = nil, pickerColors: PickerColors? = nil) { self.init(frame: CGRect.zero) if let titles = itemTitles { DefaultValue.itemTitles = titles } if let colors = pickerColors { DefaultValue.pickerColors = colors } pickerType = .date datePickerMode = aDatePickerMode setupMaskView() setupContentView() } /** 设置当前时间 */ func setDate(date: Date, animated: Bool) { guard pickerType == .date else { print("当前Picker并非Date类型,所以无法设置") return } if let picker = pickerView as? UIDatePicker { picker.setDate(date, animated: animated) } } func didClickDoneForTypeDateWithFormat(dateFormat: String?, handler: PickerTypeDateDoneHandler?) { guard pickerType == .date else { print("当前PickerType不为Date") return } dateFormatter.dateFormat = dateFormat dateModeTypeDoneHandler = handler } /** 设置datePicker的最大最小时间 When min > max, the values are ignored. Ignored in countdown timer mode - parameter minimumDate: 最小时间 - parameter maximumDate: 最大时间 */ func setMinimumDate(minimumDate: Date?, maximumDate: Date?) { guard pickerType == .date else { print("当前Picker并非Date类型,所以无法设置") return } if let picker = pickerView as? UIDatePicker { guard datePickerMode != .dateAndTime else { return } picker.minimumDate = minimumDate picker.maximumDate = maximumDate } } /** 设置倒计时 - parameter countDownDuration: for UIDatePickerModeCountDownTimer, ignored otherwise. default is 0.0. limit is 23:59 - parameter minuteInterval: interval must be evenly divided into 60. default is 1. min is 1, max is 30 */ func setCountDownDuration(countDownDuration: TimeInterval, minuteInterval: Int) { guard pickerType == .date else { print("当前Picker并非Date类型,所以无法设置") return } if let picker = pickerView as? UIDatePicker { guard datePickerMode == .dateAndTime else { return } picker.countDownDuration = countDownDuration picker.minuteInterval = minuteInterval } } } // MARK: - Area extension PickerView { /** 初始化一个地区选择器 - parameter anAreaType: 地区选择器目录类型 - parameter itemTitles: 标题 - parameter pickerColors: 颜色 */ convenience init(anAreaType: AreaType, itemTitles: PickerItemTitles? = nil, pickerColors: PickerColors? = nil) { self.init(frame: CGRect.zero) if let titles = itemTitles { DefaultValue.itemTitles = titles } if let colors = pickerColors { DefaultValue.pickerColors = colors } pickerType = .area areaType = anAreaType // 获取数据 let fileName = areaType == .provinceCityDistrict ? "area1" : "area2" print(fileName) if let filePath = Bundle.main.path(forResource: fileName, ofType: "plist") { areaSource = NSArray(contentsOfFile: filePath) as! [[String : Any]] if let theState = areaSource.first { province = theState["state"] as? String if let theCities = theState["cities"] as? [[String : Any]] { cities = theCities if let theCity = theCities.first { city = theCity["city"] as? String if areaType == .provinceCityDistrict { if let theDistricts = theCity["areas"] as? [String] { districts = theDistricts district = theDistricts.first } } } } } } else { fatalError("没找到地区数据\(fileName)源文件") } setupMaskView() setupContentView() } /** Area类型Picker点击确定回调击 */ func didClickDoneForTypeAreaHandler(handler: PickerTypeAreaDoneHandler?) { guard pickerType == .area else { print("当前PickerType不为Area") return } areaTypeDoneHandler = handler } }
gpl-3.0
3296860f4038cfd497339511b1c94341
32.48984
129
0.492799
6.037987
false
false
false
false
Gregsen/okapi
MXStatusMenu/StatusController.swift
1
1440
import Cocoa /// The StatusController manages the status item in the menu bar class StatusController { /// The cpu stats let cpu = CPU() /// The latest cpu load var cpuLoad: [Double] /// The network stats let network = Network(maximumThroughput: MaximumNetworkThroughput) /// The latest network load var networkLoad = Network.Load(input: 0, output: 0) /// The status item in the menu bar let statusItem: NSStatusItem /// The timer updates the statusView var timer: Timer? /// Lazy load the statusView. We can't do this in init() because the statusView needs a reference to the StatusController. lazy var statusView: StatusView = StatusView(frame: NSZeroRect, statusController: self) /// Initialize the values, add the statusItem to the menu bar, and start the timer init() { let statusItemWidth = StatusView.widthOfCPUCount(cpu.numberOfThreads + Int(2)) //number of bars cpuLoad = cpu.load() networkLoad = network.load() statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(statusItemWidth) statusItem.view = statusView timer = Timer.repeatEvery(UpdateInterval) { [weak self] inTimer in if let strongSelf = self { strongSelf.updateStatusItem() } } } /// Get the current load values and update the statusView func updateStatusItem() { cpuLoad = cpu.load() networkLoad = network.load() statusView.setNeedsDisplayInRect(statusView.bounds) } }
mit
69cc1ee3bf3eee8b696aab0f652e9c8b
29
123
0.725
4.044944
false
true
false
false
iAugux/Zoom-Contacts
Phonetic/AppIconImageView.swift
1
954
// // AppIconImageView.swift // Phonetic // // Created by Augus on 1/30/16. // Copyright © 2016 iAugus. All rights reserved. // import UIKit class AppIconImageView: UIImageView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) image = UIImage(named: "iTranslator") clipsToBounds = true layer.cornerRadius = frame.width * 0.23 let recognizer = UITapGestureRecognizer(target: self, action: #selector(iconDidTap)) addGestureRecognizer(recognizer) } func iconDidTap() { parentViewController?.dismissViewControllerAnimated(true, completion: { () -> Void in let appURL = NSURL(string: "https://itunes.apple.com/app/id1063627763") if UIApplication.sharedApplication().canOpenURL(appURL!) { UIApplication.sharedApplication().openURL(appURL!) } }) } }
mit
a0c11fc7415b1ce4a883ae804ea720a7
28.78125
93
0.613851
4.64878
false
false
false
false
SnowdogApps/Project-Needs-Partner
CooperationFinder/Controllers/SDWelcomeViewController.swift
1
4072
// // SDWelcomeViewController.swift // CooperationFinder // // Created by Radoslaw Szeja on 25.02.2015. // Copyright (c) 2015 Snowdog. All rights reserved. // import UIKit class SDWelcomeViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var searchField: UITextField? @IBOutlet weak var _scrollView: UIScrollView? @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var browseAllButton: UIButton! var _restorationContentOffset: CGPoint? var showAddNewProject : Bool = false override var scrollView: UIScrollView! { get { return _scrollView! } set { } } override var restorationContentOffset: CGPoint { get { if let offset = _restorationContentOffset { return offset } return CGPointZero } set { _restorationContentOffset = newValue } } override func viewDidLoad() { super.viewDidLoad() if let placeholder = searchField?.placeholder { var color = UIColor(red: 113/255.0, green: 145/255.0, blue: 145/255.0, alpha: 1.0) searchField?.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color]) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.refreshSignInButton() } func refreshSignInButton() { if let userID = Defaults["user_id"].string { self.signInButton.setTitle(NSLocalizedString("Sign out", comment:""), forState:UIControlState.Normal) } else { self.signInButton.setTitle(NSLocalizedString("Sign in", comment:""), forState:UIControlState.Normal) } } func textFieldDidBeginEditing(textField: UITextField) { self.moveUpForTextfield(textField) } func textFieldDidEndEditing(textField: UITextField) { self.moveToOriginalPosition() } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField.text.isEmpty == false { self.performSegueWithIdentifier("projectsSegue", sender: self) return true } return false } @IBAction func browseAllButtonTapped(sender: UIButton) { searchField?.text = nil self.performSegueWithIdentifier("projectsSegue", sender: self) } @IBAction func addNewOneTapped(sender: UIButton) { if let userID = Defaults["user_id"].string { self.performSegueWithIdentifier("addNewProjectSegue", sender: self) } else { self.showAddNewProject = true self.performSegueWithIdentifier("loginSegue", sender: self) } } @IBAction func signInButtonTapped(sender: AnyObject) { if let userID = Defaults["user_id"].string { Defaults["user_id"] = nil self.refreshSignInButton() } else { self.showAddNewProject = false self.performSegueWithIdentifier("loginSegue", sender: self) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "projectsSegue" { if let tabBarVC = segue.destinationViewController as? UITabBarController { if let navVC = tabBarVC.viewControllers?.first as? UINavigationController { if let controller = navVC.viewControllers.first as? SDProjectsListViewController { controller.searchPhrase = searchField?.text } } } } else if segue.identifier == "loginSegue" { if let controller = segue.destinationViewController as? SDLoginPageViewController { if self.showAddNewProject { controller.completion = { self.performSegueWithIdentifier("addNewProjectSegue", sender: self) } } } } } }
apache-2.0
11772789be2526210535075ee1d02e7f
33.508475
141
0.615668
5.386243
false
false
false
false
nferocious76/NFImageView
Example/Pods/NFImageView/NFImageView/Classes/NFImageViewConfiguration.swift
1
1964
// // NFImageViewConfiguration.swift // Pods // // Created by Neil Francis Hipona on 23/07/2016. // Copyright (c) 2016 Neil Francis Ramirez Hipona. All rights reserved. // import Foundation import UIKit extension NFImageView { // MARK: - UIActivityIndicatorView Configuration /** * Set loading spinner's spinner color */ public func setLoadingSpinnerColor(color: UIColor) { loadingIndicator.color = color } /** * Set loading spinner's spinner style */ public func setLoadingSpinnerViewStyle(activityIndicatorViewStyle style: UIActivityIndicatorViewStyle) { loadingIndicator.activityIndicatorViewStyle = style } /** * Set loading spinner's background color */ public func setLoadingSpinnerBackgroundColor(color: UIColor) { loadingIndicator.backgroundColor = color } // MARK: - UIProgressView Configuration /** * Set loading progress view style */ public func setLoadingProgressViewStyle(progressViewStyle style: UIProgressViewStyle) { loadingProgressView.progressViewStyle = style } /** * Set loading progress tint color */ public func setLoadingProgressViewTintColor(progressTintColor: UIColor?, trackTintColor: UIColor?) { loadingProgressView.progressTintColor = progressTintColor loadingProgressView.trackTintColor = trackTintColor } /** * Set loading progress image */ public func setLoadingProgressViewProgressImage(progressImage: UIImage?, trackImage: UIImage?) { loadingProgressView.progressImage = progressImage loadingProgressView.trackImage = trackImage } /** * Set loading progress's progress value */ public func setLoadingProgressViewProgress(progress: Float, animated: Bool) { loadingProgressView.setProgress(progress, animated: animated) } }
mit
0a18a68756b91c564095c29e51192120
26.291667
108
0.680244
5.516854
false
false
false
false
russbishop/swift
stdlib/public/SDK/Foundation/AffineTransform.swift
1
9711
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module #if os(OSX) private let ε: CGFloat = 2.22045e-16 extension AffineTransform : ReferenceConvertible, Hashable, CustomStringConvertible { public typealias ReferenceType = NSAffineTransform private init(reference: NSAffineTransform) { self = reference.transformStruct } private var reference : NSAffineTransform { let ref = NSAffineTransform() ref.transformStruct = self return ref } /** Creates an affine transformation matrix from translation values. The matrix takes the following form: [ 1 0 0 ] [ 0 1 0 ] [ x y 1 ] */ public init(translationByX x: CGFloat, byY y: CGFloat) { self.init(m11: CGFloat(1.0), m12: CGFloat(0.0), m21: CGFloat(0.0), m22: CGFloat(1.0), tX: x, tY: y) } /** Creates an affine transformation matrix from scaling values. The matrix takes the following form: [ x 0 0 ] [ 0 y 0 ] [ 0 0 1 ] */ public init(scaleByX x: CGFloat, byY y: CGFloat) { self.init(m11: x, m12: CGFloat(0.0), m21: CGFloat(0.0), m22: y, tX: CGFloat(0.0), tY: CGFloat(0.0)) } /** Creates an affine transformation matrix from scaling a single value. The matrix takes the following form: [ f 0 0 ] [ 0 f 0 ] [ 0 0 1 ] */ public init(scale factor: CGFloat) { self.init(scaleByX: factor, byY: factor) } /** Creates an affine transformation matrix from rotation value (angle in radians). The matrix takes the following form: [ cos α sin α 0 ] [ -sin α cos α 0 ] [ 0 0 1 ] */ public init(rotationByRadians angle: CGFloat) { let α = Double(angle) let sine = CGFloat(sin(α)) let cosine = CGFloat(cos(α)) self.init(m11: cosine, m12: sine, m21: -sine, m22: cosine, tX: 0, tY: 0) } /** Creates an affine transformation matrix from a rotation value (angle in degrees). The matrix takes the following form: [ cos α sin α 0 ] [ -sin α cos α 0 ] [ 0 0 1 ] */ public init(rotationByDegrees angle: CGFloat) { let α = Double(angle) * M_PI / 180.0 self.init(rotationByRadians: CGFloat(α)) } /** An identity affine transformation matrix [ 1 0 0 ] [ 0 1 0 ] [ 0 0 1 ] */ public static let identity = AffineTransform(m11: 1, m12: 0, m21: 0, m22: 1, tX: 0, tY: 0) // Translating public mutating func translate(x: CGFloat, y: CGFloat) { tX += m11 * x + m21 * y tY += m12 * x + m22 * y } /** Mutates an affine transformation matrix from a rotation value (angle α in degrees). The matrix takes the following form: [ cos α sin α 0 ] [ -sin α cos α 0 ] [ 0 0 1 ] */ public mutating func rotate(byDegrees angle: CGFloat) { let α = Double(angle) * M_PI / 180.0 return rotate(byRadians: CGFloat(α)) } /** Mutates an affine transformation matrix from a rotation value (angle α in radians). The matrix takes the following form: [ cos α sin α 0 ] [ -sin α cos α 0 ] [ 0 0 1 ] */ public mutating func rotate(byRadians angle: CGFloat) { let α = Double(angle) let sine = CGFloat(sin(α)) let cosine = CGFloat(cos(α)) m11 = cosine m12 = sine m21 = -sine m22 = cosine } /** Creates an affine transformation matrix by combining the receiver with `transformStruct`. That is, it computes `T * M` and returns the result, where `T` is the receiver's and `M` is the `transformStruct`'s affine transformation matrix. The resulting matrix takes the following form: [ m11_T m12_T 0 ] [ m11_M m12_M 0 ] T * M = [ m21_T m22_T 0 ] [ m21_M m22_M 0 ] [ tX_T tY_T 1 ] [ tX_M tY_M 1 ] [ (m11_T*m11_M + m12_T*m21_M) (m11_T*m12_M + m12_T*m22_M) 0 ] = [ (m21_T*m11_M + m22_T*m21_M) (m21_T*m12_M + m22_T*m22_M) 0 ] [ (tX_T*m11_M + tY_T*m21_M + tX_M) (tX_T*m12_M + tY_T*m22_M + tY_M) 1 ] */ private func concatenated(_ other: AffineTransform) -> AffineTransform { let (t, m) = (self, other) // this could be optimized with a vector version return AffineTransform( m11: (t.m11 * m.m11) + (t.m12 * m.m21), m12: (t.m11 * m.m12) + (t.m12 * m.m22), m21: (t.m21 * m.m11) + (t.m22 * m.m21), m22: (t.m21 * m.m12) + (t.m22 * m.m22), tX: (t.tX * m.m11) + (t.tY * m.m21) + m.tX, tY: (t.tX * m.m12) + (t.tY * m.m22) + m.tY ) } // Scaling public mutating func scale(_ scale: CGFloat) { self.scale(x: scale, y: scale) } public mutating func scale(x: CGFloat, y: CGFloat) { m11 *= x m12 *= x m21 *= y m22 *= y } /** Inverts the transformation matrix if possible. Matrices with a determinant that is less than the smallest valid representation of a double value greater than zero are considered to be invalid for representing as an inverse. If the input AffineTransform can potentially fall into this case then the inverted() method is suggested to be used instead since that will return an optional value that will be nil in the case that the matrix cannot be inverted. D = (m11 * m22) - (m12 * m21) D < ε the inverse is undefined and will be nil */ public mutating func invert() { guard let inverse = inverted() else { fatalError("Transform has no inverse") } self = inverse } public func inverted() -> AffineTransform? { let determinant = (m11 * m22) - (m12 * m21) if fabs(determinant) <= ε { return nil } var inverse = AffineTransform() inverse.m11 = m22 / determinant inverse.m12 = -m12 / determinant inverse.m21 = -m21 / determinant inverse.m22 = m11 / determinant inverse.tX = (m21 * tY - m22 * tX) / determinant inverse.tY = (m12 * tX - m11 * tY) / determinant return inverse } // Transforming with transform public mutating func append(_ transform: AffineTransform) { self = concatenated(transform) } public mutating func prepend(_ transform: AffineTransform) { self = transform.concatenated(self) } // Transforming points and sizes public func transform(_ point: NSPoint) -> NSPoint { var newPoint = NSPoint() newPoint.x = (m11 * point.x) + (m21 * point.y) + tX newPoint.y = (m12 * point.x) + (m22 * point.y) + tY return newPoint } public func transform(_ size: NSSize) -> NSSize { var newSize = NSSize() newSize.width = (m11 * size.width) + (m21 * size.height) newSize.height = (m12 * size.width) + (m22 * size.height) return newSize } public var hashValue : Int { return Int(m11 + m12 + m21 + m22 + tX + tY) } public var description: String { return "{m11:\(m11), m12:\(m12), m21:\(m21), m22:\(m22), tX:\(tX), tY:\(tY)}" } public var debugDescription: String { return description } } public func ==(lhs: AffineTransform, rhs: AffineTransform) -> Bool { return lhs.m11 == rhs.m11 && lhs.m12 == rhs.m12 && lhs.m21 == rhs.m21 && lhs.m22 == rhs.m22 && lhs.tX == rhs.tX && lhs.tY == rhs.tY } extension AffineTransform : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSAffineTransform.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSAffineTransform { let t = NSAffineTransform() t.transformStruct = self return t } public static func _forceBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge type") } } public static func _conditionallyBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) -> Bool { result = x.transformStruct return true // Can't fail } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSAffineTransform?) -> AffineTransform { var result: AffineTransform? _forceBridgeFromObjectiveC(x!, result: &result) return result! } } #endif
apache-2.0
86e4be80260b28c77d0d7b440b0141ac
31.374582
123
0.546798
3.919028
false
false
false
false
bencochran/LLVM.swift
LLVM/Type.swift
1
7603
// // Created by Ben Cochran on 11/13/15. // Copyright © 2015 Ben Cochran. All rights reserved. // public protocol TypeType { var ref: LLVMValueRef { get } init(ref: LLVMValueRef) var kind: LLVMTypeKind { get } var isSized: Bool { get } var string: String? { get } } extension TypeType { public var kind: LLVMTypeKind { return LLVMGetTypeKind(ref) } public var isSized: Bool { return LLVMTypeIsSized(ref) != 0 } public var string: String? { let string = LLVMPrintTypeToString(ref) defer { LLVMDisposeMessage(string) } return .fromCString(string) } } public struct AnyType : TypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } } public struct IntType : TypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public static func int1(inContext context: Context) -> IntType { return IntType(ref: LLVMInt1TypeInContext(context.ref)) } public static func int8(inContext context: Context) -> IntType { return IntType(ref: LLVMInt8TypeInContext(context.ref)) } public static func int16(inContext context: Context) -> IntType { return IntType(ref: LLVMInt16TypeInContext(context.ref)) } public static func int32(inContext context: Context) -> IntType { return IntType(ref: LLVMInt32TypeInContext(context.ref)) } public static func int64(inContext context: Context) -> IntType { return IntType(ref: LLVMInt64TypeInContext(context.ref)) } public static func int(inContext context: Context, numBits: UInt32) -> IntType { return IntType(ref: LLVMIntTypeInContext(context.ref, numBits)) } public var width: UInt32 { return LLVMGetIntTypeWidth(ref) } } public struct RealType : TypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public static func half(inContext context: Context) -> RealType { return RealType(ref: LLVMHalfTypeInContext(context.ref)) } public static func float(inContext context: Context) -> RealType { return RealType(ref: LLVMFloatTypeInContext(context.ref)) } public static func double(inContext context: Context) -> RealType { return RealType(ref: LLVMDoubleTypeInContext(context.ref)) } public static func x86fp80(inContext context: Context) -> RealType { return RealType(ref: LLVMX86FP80TypeInContext(context.ref)) } public static func fp128(inContext context: Context) -> RealType { return RealType(ref: LLVMFP128TypeInContext(context.ref)) } public static func ppcfp128(inContext context: Context) -> RealType { return RealType(ref: LLVMPPCFP128TypeInContext(context.ref)) } } public struct FunctionType : TypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(returnType: TypeType, paramTypes: [TypeType], isVarArg: Bool) { var paramTypeValues = paramTypes.map { $0.ref } ref = LLVMFunctionType(returnType.ref, &paramTypeValues, UInt32(paramTypeValues.count), isVarArg ? 1 : 0) } public var isVarArg: Bool { return LLVMIsFunctionVarArg(ref) != 0 } public var paramTypesCount: UInt32 { return LLVMCountParamTypes(ref) } public var paramTypes: [TypeType] { let count = Int(paramTypesCount) let refs = UnsafeMutablePointer<LLVMTypeRef>.alloc(count) defer { refs.dealloc(count) } LLVMGetParamTypes(ref, refs) return UnsafeMutableBufferPointer(start: refs, count: count).map(AnyType.init) } } public protocol CompositeTypeType : TypeType { } public struct StructType : CompositeTypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(elementTypes: [TypeType], packed: Bool, inContext context: Context) { var elementTypeValues = elementTypes.map { $0.ref } ref = LLVMStructTypeInContext(context.ref, &elementTypeValues, UInt32(elementTypeValues.count), packed ? 1 : 0) } public init(named name: String, inContext context: Context) { ref = LLVMStructCreateNamed(context.ref, name) } public var name: String? { let name = LLVMGetStructName(ref) return .fromCString(name) } public var structure: ([TypeType], packed: Bool) { get { let count = Int(LLVMCountStructElementTypes(ref)) let refs = UnsafeMutablePointer<LLVMTypeRef>.alloc(count) defer { refs.dealloc(count) } LLVMGetParamTypes(ref, refs) let types = UnsafeMutableBufferPointer(start: refs, count: count).map({ AnyType(ref: $0) as TypeType }) let packed = LLVMIsPackedStruct(ref) != 0 return (types, packed) } set { var elementTypeValues = structure.0.map { $0.ref } LLVMStructSetBody(ref, &elementTypeValues, UInt32(elementTypeValues.count), structure.packed ? 1 : 0) } } public var isOpaque: Bool { return LLVMIsOpaqueStruct(ref) != 0 } } public protocol SequentialTypeType : CompositeTypeType { var type: TypeType { get } } public extension SequentialTypeType { var type: TypeType { return AnyType(ref: LLVMGetElementType(ref)) } } public struct ArrayType : SequentialTypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(type: TypeType, count: UInt32) { ref = LLVMArrayType(type.ref, count) } public var length: UInt32 { return LLVMGetArrayLength(ref) } } public struct PointerType : SequentialTypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(type: TypeType, addressSpace: UInt32) { ref = LLVMPointerType(type.ref, addressSpace) } public var addressSpace: UInt32 { return LLVMGetPointerAddressSpace(ref) } } public struct VectorType : SequentialTypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(type: TypeType, count: UInt32) { ref = LLVMVectorType(type.ref, count) } public var size: UInt32 { return LLVMGetVectorSize(ref) } } public struct VoidType : TypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(inContext context: Context) { ref = LLVMVoidTypeInContext(context.ref) } } public struct LabelType : TypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(inContext context: Context) { ref = LLVMLabelTypeInContext(context.ref) } } public struct X86MMXType : TypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(inContext context: Context) { ref = LLVMX86MMXTypeInContext(context.ref) } } public struct MetadataType : TypeType { public let ref: LLVMValueRef public init(ref: LLVMValueRef) { self.ref = ref } public init(inContext context: Context) { ref = LLVMX86MMXTypeInContext(context.ref) } }
mit
4244f4c601cf1599239928ebf73575cd
26.543478
119
0.644699
4.100324
false
false
false
false
lcepy/Mockingbird
MockingbirdDemo/ViewController.swift
2
1709
// // ViewController.swift // Mockingbird // // Created by xiangwenwen on 15/6/15. // Copyright (c) 2015年 xiangwenwen. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var scancode: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "mockingbird:", name:MOKNotifiScanResult, object: nil) } func mockingbird(note:NSNotification)->Void{ if let userInfo:Dictionary<NSObject,AnyObject> = note.userInfo{ self.scancode.text = userInfo["value"] as? String } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func scancodeinfo(sender: UIButton) { let storyboard:UIStoryboard = UIStoryboard(name: "Mockingbird", bundle: NSBundle.mainBundle()) let navC:UINavigationController = storyboard.instantiateViewControllerWithIdentifier("MockingbirdNavigationID") as! UINavigationController let mockingbird:MockingbirdScanCodeManager = navC.topViewController as! MockingbirdScanCodeManager mockingbird.globalTitle = "扫描条码" mockingbird.globalColor = MOKTeal mockingbird.mockingbirdResult = {(value:String?)->Void in println(value) println("回调函数") if let _value = value{ self.scancode.text = _value } } self.presentViewController(navC, animated: true, completion: nil) } }
mit
81461cc4bf4154eb6aea91c847b6e12c
34.229167
146
0.673566
4.671271
false
false
false
false
max9631/Piskvorky
Piškvorky/Policko.swift
1
5956
// // Policko.swift // Piškvorky // // Created by Adam Salih on 10/03/15. // Copyright (c) 2015 Adam Salih. All rights reserved. // import UIKit class Policko: UIView { var database:PlayedFieldDatabase! var cross:Bool? var osaX:Int! var osaY:Int! var img:UIView! // var label:UILabel! init(x:Int, y:Int, database db:PlayedFieldDatabase, cross crs:Bool?) { super.init() self.osaX = x self.osaY = y self.cross = crs self.backgroundColor = UIColor.whiteColor() self.layer.borderColor = UIColor.blackColor().CGColor self.layer.borderWidth = 0.5 self.database = db let tapGesture = UITapGestureRecognizer(target: self, action: "gestureRecognized:") self.addGestureRecognizer(tapGesture) // let lbl = UILabel() // lbl.frame.size = CGSize(width: 50, height: 10) // lbl.frame.origin = self.frame.origin // lbl.text = "\(x), \(y)" // lbl.adjustsFontSizeToFitWidth = false // lbl.font = lbl.font.fontWithSize(10) // self.label = lbl // self.addSubview(lbl) } func set(cross cros:Bool) -> Bool{ if self.cross == nil{ self.cross = cros if cros{ let UICross = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) self.database.addPolicko(self.osaX, y: self.osaY, cross: true) let upperLine = UIView() //– upperLine.backgroundColor = UIColor.blackColor() upperLine.frame.size.width = self.frame.width upperLine.frame.size.height = 1 UICross.addSubview(upperLine) upperLine.frame.origin.y = self.frame.width / 2 upperLine.transform = CGAffineTransformMakeRotation(CGFloat(45) * CGFloat(M_PI/180)) let lowerLine = UIView()// | lowerLine.backgroundColor = UIColor.blackColor() lowerLine.frame.size.height = self.frame.width lowerLine.frame.size.width = 1 UICross.addSubview(lowerLine) lowerLine.frame.origin.x = self.frame.width / 2 lowerLine.transform = CGAffineTransformMakeRotation(CGFloat(45) * CGFloat(M_PI/180)) self.addSubview(UICross) self.img = UICross }else{ self.database.addPolicko(self.osaX, y: self.osaY, cross: false) let side = (self.frame.width / 3)*2 let circle = UIView() circle.frame.size.width = side circle.frame.size.height = side circle.layer.cornerRadius = side / 2 circle.layer.masksToBounds = true circle.layer.borderColor = UIColor.blackColor().CGColor circle.layer.borderWidth = 1 self.addSubview(circle) circle.frame.origin.x = (self.frame.width / 3) / 2 circle.frame.origin.y = (self.frame.width / 3) / 2 self.img = circle } return true }else{ return false } } func refresh(){ // self.label.text = "\(self.osaX), \(self.osaY)" if let cros = self.database.polickoProOsu(x: self.osaX, y: self.osaY){ if self.cross == nil{ self.cross = cros if cros{ let UICross = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) let upperLine = UIView() //– upperLine.backgroundColor = UIColor.blackColor() upperLine.frame.size.width = self.frame.width upperLine.frame.size.height = 1 UICross.addSubview(upperLine) upperLine.frame.origin.y = self.frame.width / 2 upperLine.transform = CGAffineTransformMakeRotation(CGFloat(45) * CGFloat(M_PI/180)) let lowerLine = UIView()// | lowerLine.backgroundColor = UIColor.blackColor() lowerLine.frame.size.height = self.frame.width lowerLine.frame.size.width = 1 UICross.addSubview(lowerLine) lowerLine.frame.origin.x = self.frame.width / 2 lowerLine.transform = CGAffineTransformMakeRotation(CGFloat(45) * CGFloat(M_PI/180)) self.addSubview(UICross) self.img = UICross }else{ let side = (self.frame.width / 3)*2 let circle = UIView() circle.frame.size.width = side circle.frame.size.height = side circle.layer.cornerRadius = side / 2 circle.layer.masksToBounds = true circle.layer.borderColor = UIColor.blackColor().CGColor circle.layer.borderWidth = 1 self.addSubview(circle) circle.frame.origin.x = (self.frame.width / 3) / 2 circle.frame.origin.y = (self.frame.width / 3) / 2 self.img = circle } } }else{ if self.img != nil{ self.img.removeFromSuperview() self.img = nil self.cross = nil } } // self.set(cross:self.database.polickoProOsu(x: self.osaX, y: self.osaY)) } func gestureRecognized(tap:UIGestureRecognizer){ self.set(cross: self.database.tmpCross) self.database.tmpCross = !self.database.tmpCross } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
gpl-2.0
33c2326c1a49df10089ca18c4bb8e1b5
38.673333
119
0.53386
4.238604
false
false
false
false
andyshep/GROCloudStore
Sources/GROChangeToken.swift
1
3417
// // GROChangeToken.swift // GROCloudStore // // Created by Andrew Shepard on 6/22/16. // Copyright © 2016 Andrew Shepard. All rights reserved. // import CoreData import CloudKit @objc(GROChangeToken) internal class GROChangeToken: NSManagedObject { @NSManaged var content: Data @NSManaged var zoneName: String? } internal func changeTokens(forZoneIds zoneIds: [CKRecordZone.ID], in context: NSManagedObjectContext) -> [CKRecordZone.ID: CKServerChangeToken]? { let request = NSFetchRequest<GROChangeToken>(entityName: GROChangeToken.entityName) do { let zoneNames = zoneIds.map { return $0.zoneName } let results = try context.fetch(request) let savedChanges = results.filter { return zoneNames.contains($0.zoneName!) } var tokens: [CKRecordZone.ID: CKServerChangeToken] = [:] for change in savedChanges { let zoneName = change.zoneName let zoneId = CKRecordZone.ID(zoneName: zoneName!, ownerName: CKCurrentUserDefaultName) if let token = NSKeyedUnarchiver.unarchiveObject(with: change.content) as? CKServerChangeToken { tokens[zoneId] = token } } return tokens.count > 0 ? tokens : nil } catch { fatalError("error fetching change tokens: \(error)") } } internal func changeToken(forRecordZoneId zoneId: CKRecordZone.ID, in context: NSManagedObjectContext) -> GROChangeToken { if let tokens = existingChangeTokens(in: context) { let matches = tokens.filter { return $0.zoneName == zoneId.zoneName } if let token = matches.first { return token } } return newChangeToken(in: context) } internal func existingChangeTokens(in context: NSManagedObjectContext) -> [GROChangeToken]? { let request = NSFetchRequest<GROChangeToken>(entityName: GROChangeToken.entityName) do { return try context.fetch(request) } catch { print("unhandled error: \(error)") } return nil } internal func newChangeToken(in context: NSManagedObjectContext) -> GROChangeToken { let object = GROChangeToken.newObject(in: context) guard let token = object as? GROChangeToken else { fatalError() } return token } internal func save(token: CKServerChangeToken?, forRecordZoneId zoneId: CKRecordZone.ID, in context: NSManagedObjectContext) { if let token = token { context.performAndWait { let savedChangeToken = changeToken(forRecordZoneId: zoneId, in: context) savedChangeToken.content = NSKeyedArchiver.archivedData(withRootObject: token) savedChangeToken.zoneName = zoneId.zoneName context.saveOrLogError() } } } internal func databaseChangeToken(in context: NSManagedObjectContext) -> CKServerChangeToken? { let request = NSFetchRequest<GROChangeToken>(entityName: GROChangeToken.entityName) do { let results = try context.fetch(request) let matches = results.filter { return $0.zoneName == "" } guard let match = matches.first else { return nil } guard let token = NSKeyedUnarchiver.unarchiveObject(with: match.content) as? CKServerChangeToken else { return nil } return token } catch { print("error fetching change token: \(error)") return nil } }
mit
8cfeedee14d313bbb708b122eaf9bcc8
33.16
146
0.669204
4.77095
false
false
false
false
thombles/Flyweight
Flyweight/Views/ContentView.swift
1
3920
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit class ContentView: UILabel { private var links: [LinkAttribute] = [] override func awakeFromNib() { let tap = UITapGestureRecognizer(target: self, action: #selector(tapOnLabel)) self.isUserInteractionEnabled = true self.addGestureRecognizer(tap) self.lineBreakMode = .byWordWrapping self.numberOfLines = 0 } func tapOnLabel(recognizer: UITapGestureRecognizer) { guard let attributedText = self.attributedText else { return } if recognizer.state == .ended { // Set up a text container matching the properties and contents of this label let location = recognizer.location(in: self) let formatted = NSMutableAttributedString(attributedString: attributedText) formatted.addAttributes([NSFontAttributeName: self.font], range: NSMakeRange(0, formatted.string.characters.count)) let layoutManager = NSLayoutManager() let textStorage = NSTextStorage(attributedString: formatted) textStorage.addLayoutManager(layoutManager) let textContainer = NSTextContainer(size: self.bounds.size) textContainer.maximumNumberOfLines = self.numberOfLines textContainer.lineBreakMode = self.lineBreakMode textContainer.lineFragmentPadding = 0 layoutManager.addTextContainer(textContainer) // Ask what the corresponding character would be at the point we click on // Note that this will get "stuck" on the end of the string for the remainder of the label // To prevent terminating links leaking into empty space we append a zero width space when we set the string let characterIndex = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) // If the touch corresponds to any of the contained links, open the URL for l in links { if characterIndex >= l.range.startIndex && characterIndex < l.range.endIndex { // Open the URL in Safari if let url = URL(string: l.url) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } } } // TODO probably need to let the touch fall through somehow when I have tap-for-conversation // Also TODO someday some of these links will be special and do in-app functions instead // TODO use the started and ended to visibly show the press on the URL } } var htmlContent: String? { get { return self.text } set { guard let html = newValue else { return } // Add an zero width space to the end because this will allow the URL character matching to terminate let parser = HtmlDisplayParser(html: html + "\u{200B}", fontSize: self.font.pointSize) let (att, links) = parser.makeAttributedString() self.attributedText = att self.links = links } } }
apache-2.0
a3d5b1b24f7273b5a9e23fab1de3cc62
44.581395
142
0.633673
5.384615
false
false
false
false
thongtran715/Find-Friends
MapKitTutorial/FriendSearchTableViewCell.swift
1
1474
// // FriendSearchTableViewCell.swift // MapKitTutorial // // Created by Thong Tran on 7/8/16. // Copyright © 2016 Thorn Technologies. All rights reserved. // import UIKit import Parse class FriendSearchTableViewCell: UITableViewCell { @IBOutlet var userName: UILabel! @IBOutlet var sendMessageOutlet: UIButton! @IBAction func sendMessageButton(sender: AnyObject) { if let canAdd = canAdd where canAdd == true { delegate?.cell(self, didSelectFollowUser: user!) self.canAdd = false } else { delegate?.cell(self, didSelectUnfollowUser: user!) self.canAdd = true } } weak var delegate: FriendSearchTableViewCellDelegate? var canAdd: Bool? = true { didSet { /* Change the state of the follow button based on whether or not it is possible to follow a user. */ if let canAdd = canAdd { sendMessageOutlet.selected = !canAdd } } } var user: PFUser? { didSet { userName.text = user?.username } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
844688c800bc403e11de1b7e5de6c3e5
23.966102
74
0.577733
4.976351
false
false
false
false
tinpay/BeaconAttendanceManagement
BeaconAttendanceManagement/OreKin/ViewController.swift
1
8511
// // ViewController.swift // OreOre Kintai // // Created by tinpay on 2014/11/24. // Copyright (c) 2014年 ChatWork. All rights reserved. // import UIKit import Foundation import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate{ @IBOutlet weak var timeLabel: UILabel! let proximityUUID = NSUUID(UUIDString:"<proximity UUID>") let chatworkToken = "<ChatWork AccessToken>" let flatBlueColor:UIColor = UIColor(red: 0.1607843137254902, green: 0.5019607843137255, blue: 0.7254901960784313, alpha: 1.0) let flatGreyColor:UIColor = UIColor(red: 0.5843137254901961, green: 0.6470588235294118, blue: 0.6509803921568628, alpha: 1.0) var dateFormatter = NSDateFormatter() var region = CLBeaconRegion() var manager = CLLocationManager() enum BeaconDistance { case Unknown case Immediate case Near case Far } var beaconDistance : BeaconDistance = BeaconDistance.Unknown override func viewDidLoad() { super.viewDidLoad() var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("onTimer"), userInfo: nil, repeats: true) self.dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle self.dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle self.changeScreenColor() if (CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion)) { self.manager.delegate = self self.region = CLBeaconRegion(proximityUUID:proximityUUID,identifier:"com.chatwork.OreKin") self.manager.startMonitoringForRegion(self.region) } else { //iBeaconが使えないiOSや端末の場合 } switch CLLocationManager.authorizationStatus() { case .Authorized, .AuthorizedWhenInUse: self.manager.startRangingBeaconsInRegion(self.region) case .NotDetermined: if(self.manager.respondsToSelector("requestAlwaysAuthorization")) { self.manager.requestAlwaysAuthorization() }else{ self.manager.startRangingBeaconsInRegion(self.region) } case .Restricted, .Denied: break default: break } } //MARK: - CLLocationManagerDelegate method func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) { NSLog("start monitoring.") manager.requestStateForRegion(region) } func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion inRegion: CLRegion!) { NSLog("determine state.") switch (state) { case .Inside: NSLog("Region State : inside"); self.startRangingBeaconsforRegion(inRegion) break; case .Outside: NSLog("Region State : outside"); break; case .Unknown: NSLog("Region State : unknown"); break; default: break; } } func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) { NSLog("monitoringDidFailForRegion \(error)") } //通信失敗 func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { NSLog("didFailWithError \(error)") } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { self.startRangingBeaconsforRegion(region) self.postChatWorkToMyChat("出勤しました(F)") } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { manager.stopRangingBeaconsInRegion(region as CLBeaconRegion) self.postChatWorkToMyChat("退勤しました(beer)") } func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: NSArray!, inRegion region: CLBeaconRegion!) { println(beacons) if(beacons.count == 0) { return } //一つ目 var beacon = beacons[0] as CLBeacon switch (beacon.proximity){ case .Unknown: self.beaconDistance = BeaconDistance.Unknown case .Immediate: self.beaconDistance = BeaconDistance.Immediate case .Near: self.beaconDistance = BeaconDistance.Near case .Far: self.beaconDistance = BeaconDistance.Far } self.changeScreenColor() } //MARK: - for timer method func onTimer(){ self.timeLabel.text = self.dateFormatter.stringFromDate(NSDate()) } //MARK: - private method override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func startRangingBeaconsforRegion(inRegion: CLRegion!){ if(inRegion.isMemberOfClass(CLBeaconRegion) && CLLocationManager .isRangingAvailable()){ manager.startRangingBeaconsInRegion(self.region) } } func changeScreenColor() { var color:UIColor if self.beaconDistance == BeaconDistance.Immediate || self.beaconDistance == BeaconDistance.Near || self.beaconDistance == BeaconDistance.Far{ color = flatBlueColor }else{ color = flatGreyColor } self.view.backgroundColor = color self.timeLabel.textColor = UIColor.whiteColor() } func localNotificate(message : String) { var notification : UILocalNotification = UILocalNotification() notification.fireDate = NSDate() notification.timeZone = NSTimeZone.defaultTimeZone() notification.alertBody = message notification.alertAction = "OK" notification.soundName = UILocalNotificationDefaultSoundName UIApplication.sharedApplication().scheduleLocalNotification(notification) } func postChatWorkToMyChat(msg : String){ let postMsg = "\(msg) (" + self.dateFormatter.stringFromDate(NSDate()) + ")" let request = NSURLRequest(URL:NSURL(string: "https://api.chatwork.com/v1/rooms")!) var configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = ["X-ChatWorkToken" : self.chatworkToken] let session = NSURLSession(configuration: configuration) var task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in if error == nil { var error:NSError? let rooms = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSArray rooms.enumerateObjectsUsingBlock({ (room, idx, stop) -> Void in let roomtype = room["type"]! as String let roomid = room["room_id"]! as Int if (roomtype == "my") { //マイチャットの場合 var urlstring = "https://api.chatwork.com/v1/rooms/" + String(roomid) + "/messages" var requestMessage = NSMutableURLRequest(URL:NSURL(string: urlstring)!) requestMessage.HTTPMethod = "POST" let params:String = "body=\(postMsg)" requestMessage.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) var taskMessage = session.dataTaskWithRequest(requestMessage){ (data, response, er) -> Void in var error:NSError? let arr = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSDictionary //いろいろ処理 self.localNotificate(postMsg) } taskMessage.resume() } }) } } task.resume() } }
mit
f7a02599631c6520f721d14be781627d
33.363265
150
0.594251
5.557096
false
false
false
false
grandiere/box
box/View/Boards/VBoards.swift
1
4325
import UIKit class VBoards:VView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private weak var controller:CBoards! private weak var viewBar:VBoardsBar! private weak var collectionView:VCollection! private weak var spinner:VSpinner! private let kBarHeight:CGFloat = 130 private let kCollectionBottom:CGFloat = 20 private let kCellHeight:CGFloat = 50 override init(controller:CController) { super.init(controller:controller) self.controller = controller as? CBoards let spinner:VSpinner = VSpinner() self.spinner = spinner let viewBar:VBoardsBar = VBoardsBar( controller:self.controller) self.viewBar = viewBar let collectionView:VCollection = VCollection() collectionView.isHidden = true collectionView.alwaysBounceVertical = true collectionView.delegate = self collectionView.dataSource = self collectionView.registerCell(cell:VBoardsCellScore.self) collectionView.registerCell(cell:VBoardsCellKills.self) self.collectionView = collectionView if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow { flow.sectionInset = UIEdgeInsets( top:kBarHeight, left:0, bottom:kCollectionBottom, right:0) } addSubview(spinner) addSubview(collectionView) addSubview(viewBar) NSLayoutConstraint.equals( view:spinner, toView:self) NSLayoutConstraint.topToTop( view:viewBar, toView:self) NSLayoutConstraint.height( view:viewBar, constant:kBarHeight) NSLayoutConstraint.equalsHorizontal( view:viewBar, toView:self) NSLayoutConstraint.equals( view:collectionView, toView:self) } required init?(coder:NSCoder) { return nil } deinit { spinner.stopAnimating() } //MARK: private private func modelAtIndex(index:IndexPath) -> MBoardsItem { let item:MBoardsItem = controller.model.items[index.item] return item } //MARK: public func startLoading() { spinner.startAnimating() collectionView.isHidden = true viewBar.viewSelector.isUserInteractionEnabled = false } func stopLoading() { spinner.stopAnimating() collectionView.isHidden = false collectionView.reloadData() collectionView.scrollRectToVisible( CGRect(x:0, y:0, width:1, height:1), animated:false) viewBar.viewSelector.isUserInteractionEnabled = true } //MARK: collectionView delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let width:CGFloat = bounds.maxX let size:CGSize = CGSize(width:width, height:kCellHeight) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let count:Int = controller.model.items.count return count } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MBoardsItem = modelAtIndex(index:indexPath) let cell:VBoardsCell = collectionView.dequeueReusableCell( withReuseIdentifier: controller.model.sort.reusableIdentifier, for:indexPath) as! VBoardsCell cell.config(item:item) return cell } func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool { return false } func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool { return false } }
mit
3befca36d4be9b0e67ab6d5663627233
28.222973
155
0.631676
5.587855
false
false
false
false
rudkx/swift
test/type/opaque_generic_superclass_constraint.swift
1
504
// RUN: %target-swift-frontend -disable-availability-checking -emit-ir -verify -requirement-machine-abstract-signatures=verify %s // rdar://problem/53318811 class Foo<T> { var x: T { fatalError() } } func foo<T>(_: T) -> some Foo<T> { let localProp: some Foo<T> = Foo() return localProp } class C<T> { func bar() -> some Foo<T> { return Foo() } var prop: some Foo<T> = Foo() } func bar() -> Int { var x = 0 x = foo(0).x x = C<Int>().bar().x x = C<Int>().prop.x return x }
apache-2.0
5083ddf034a16aae1480b991f04d2ded
17
129
0.59127
2.754098
false
false
false
false