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
gnachman/iTerm2
sources/VT100ConductorParser.swift
2
21092
// // VT100ConductorParser.swift // iTerm2SharedARC // // Created by George Nachman on 5/9/22. // import Foundation @objc class VT100ConductorParser: NSObject, VT100DCSParserHook { private var recoveryMode = false private var line = Data() private let uniqueID: String private enum State { case initial case ground case body(String) case output(builder: SSHOutputTokenBuilder) case autopoll(builder: SSHOutputTokenBuilder) } private var state = State.initial var hookDescription: String { return "[SSH CONDUCTOR]" } private func DLog(_ messageBlock: @autoclosure () -> String, file: String = #file, line: Int = #line, function: String = #function) { if gDebugLogging.boolValue { let message = messageBlock() DebugLogImpl("\(file.lastPathComponent)", Int32(line), "\(function)", "[\(self.it_addressString)] \(message)") } } @objc(initWithUniqueID:) init(uniqueID: String) { self.uniqueID = uniqueID } @objc static func newRecoveryModeInstance(uniqueID: String) -> VT100ConductorParser { let instance = VT100ConductorParser(uniqueID: uniqueID) instance.recoveryMode = true instance.state = .ground return instance } // Return true to unhook. func handleInput(_ context: UnsafeMutablePointer<iTermParserContext>, support8BitControlCharacters: Bool, token result: VT100Token) -> VT100DCSParserHookResult { DLog("handleInput in \(state)") result.type = VT100_WAIT switch state { case .initial: return parseInitial(context, into: result) case .ground: return parseGround(context, token: result) case .body(let id): return parseBody(context, identifier: id, token: result) case .output(builder: let builder), .autopoll(builder: let builder): return parseOutput(context, builder: builder, token: result) } } enum OSCParserResult { case notOSC case osc(Int, String) case blocked } private func parseNextOSC(_ context: UnsafeMutablePointer<iTermParserContext>, skipInitialGarbage: Bool) -> OSCParserResult { enum State { case ground case esc case osc(String) case oscParam(Int, String) case oscEsc(Int, String) } let esc = 27 let closeBracket = Character("]").asciiValue! let zero = Character("0").asciiValue! let nine = Character("9").asciiValue! let semicolon = Character(";").asciiValue! let backslash = Character("\\").asciiValue! var checkpoint = iTermParserNumberOfBytesConsumed(context) var state: State = State.ground { didSet { switch state { case .ground: checkpoint = iTermParserNumberOfBytesConsumed(context) default: break } } } while iTermParserCanAdvance(context) { let c = iTermParserConsume(context) switch state { case .ground: if c == esc { state = .esc } else { if !skipInitialGarbage { iTermParserBacktrack(context, offset: checkpoint) return .notOSC } checkpoint = iTermParserNumberOfBytesConsumed(context) } case .esc: if c == closeBracket { state = .osc("") } else { if !skipInitialGarbage { iTermParserBacktrack(context, offset: checkpoint) return .notOSC } state = .ground } case .osc(let param): if c >= zero && c <= nine { state = .osc(param + String(ascii: c)) } else if c == semicolon, let code = Int(param) { state = .oscParam(code, "") } else { if !skipInitialGarbage { iTermParserBacktrack(context, offset: checkpoint) return .notOSC } state = .ground } case .oscParam(let code, let payload): if c == esc { state = .oscEsc(code, payload) } else { state = .oscParam(code, payload + String(ascii: c)) } case .oscEsc(let code, let payload): if c == backslash { // Ignore any unrecognized paramters which may come before the colon and then // ignore the colon itself. return .osc(code, String(payload.substringAfterFirst(":"))) } else { // esc followed by anything but a backslash inside an OSC means the OSC was // interrupted by another OSC. For example (newlines for clarity): // \e]134;:%output 456\e\\ // \e]134; <- start parsing with this line having truncated output from child // \e]134;%end 123\e\\ <- this is a well formed osc, which is what we ought to find if !skipInitialGarbage { iTermParserBacktrack(context, offset: checkpoint) return .notOSC } // Move back one character and re-parse the preceding OSC. iTermParserBacktrackBy(context, 1) state = .ground } } } iTermParserBacktrack(context, offset: checkpoint) return .blocked } private func parseNextLine(_ context: UnsafeMutablePointer<iTermParserContext>) -> Data? { let bytesTilNewline = iTermParserNumberOfBytesUntilCharacter(context, "\n".firstASCIICharacter) if bytesTilNewline == -1 { DLog("No newline found") return nil } let bytes = iTermParserPeekRawBytes(context, bytesTilNewline) let buffer = UnsafeBufferPointer(start: bytes, count: Int(bytesTilNewline)) iTermParserAdvanceMultiple(context, bytesTilNewline) return Data(buffer: buffer) } private enum ProcessingResult { case keepGoing case unhook } private func parseInitial(_ context: UnsafeMutablePointer<iTermParserContext>, into token: VT100Token) -> VT100DCSParserHookResult { // Read initial payload of DCS 2000p // Space-delimited args of at least token, unique ID, boolean args, [possible future args], hyphen, ssh args. guard let lineData = parseNextLine(context) else { return .blocked } guard let line = String(data: lineData, encoding: .utf8) else { DLog("non-utf8 data \((lineData as NSData).it_hexEncoded())") return .unhook } DLog("In initial state. Accept line as SSH_INIT.") token.type = SSH_INIT token.string = line + " " + uniqueID state = .ground return .canReadAgain } private func parsePreFramerPayload(_ string: String, into token: VT100Token) -> VT100DCSParserHookResult { if string.hasPrefix("begin ") { let parts = string.components(separatedBy: " ") guard parts.count >= 2 else { DLog("Malformed begin token, unhook") return .unhook } DLog("In ground state: Found valid begin token") state = .body(parts[1]) // No need to expose this to clients. token.type = SSH_BEGIN token.string = parts[1] return .canReadAgain } if string == "unhook" { DLog("In ground state: Found valid unhook token") token.type = SSH_UNHOOK return .unhook } DLog("In ground state: Found unrecognized token") return .unhook } private func parseFramerBegin(_ string: String, into token: VT100Token) -> VT100DCSParserHookResult { let parts = string.components(separatedBy: " ") guard parts.count >= 2 else { DLog("Malformed begin token, unhook") return .unhook } DLog("In ground state: Found valid begin token") state = .body(parts[1]) // No need to expose this to clients. token.type = SSH_BEGIN token.string = parts[1] return .canReadAgain } private func parseFramerOutput(_ string: String, into token: VT100Token) -> VT100DCSParserHookResult { if let builder = SSHOutputTokenBuilder(string) { DLog("create builder with identifier \(builder.identifier)") state = .output(builder: builder) return .canReadAgain } DLog("Malformed %output/%autopoll, unhook") return .unhook } private func parseFramerTerminate(_ string: String, into token: VT100Token) -> VT100DCSParserHookResult { let parts = string.components(separatedBy: " ") guard parts.count >= 3, let pid = Int32(parts[1]), let rc = Int32(parts[2]) else { DLog("Malformed %terminate, unhook") return .unhook } DLog("%terminate \(parts)") token.type = SSH_TERMINATE iTermAddCSIParameter(token.csi, pid) iTermAddCSIParameter(token.csi, rc) return .canReadAgain } private func parseFramerPayload(_ string: String, into token: VT100Token) -> VT100DCSParserHookResult { let wasInRecoveryMode = recoveryMode recoveryMode = false if string.hasPrefix("begin ") { return parseFramerBegin(string, into: token) } if string.hasPrefix("%output ") || string.hasPrefix("%autopoll ") { return parseFramerOutput(string, into: token) } if string.hasPrefix("%terminate ") { return parseFramerTerminate(string, into: token) } if string.hasPrefix("%") { DLog("Ignore unrecognized notification \(string)") return .canReadAgain } if wasInRecoveryMode { DLog("Ignore unrecognized line in recovery mode") recoveryMode = true return .canReadAgain } DLog("In ground state: Found unrecognized token") return .unhook } struct ConditionalPeekResult { let context: UnsafeMutablePointer<iTermParserContext> var offset: Int var result: OSCParserResult func backtrack() { iTermParserBacktrack(context, offset: offset) } } private func conditionallyPeekOSC(_ context: UnsafeMutablePointer<iTermParserContext>) -> ConditionalPeekResult { let startingOffset = iTermParserNumberOfBytesConsumed(context) let result = parseNextOSC(context, skipInitialGarbage: false) return ConditionalPeekResult(context: context, offset: startingOffset, result: result) } enum DataOrOSC { case data(Data) case eof } // If the context starts with an OSC, it's not one we care about. Stop before an osc beginning // after the first bytes. private func consumeUntilStartOfNextOSCOrEnd(_ context: UnsafeMutablePointer<iTermParserContext>) -> DataOrOSC { if !iTermParserCanAdvance(context) { return .eof } let esc = UInt8(VT100CC_ESC.rawValue) let count = iTermParserNumberOfBytesUntilCharacter(context, esc) let bytesToConsume: Int32 if count == 0 { bytesToConsume = 1 } else if count < 0 { // no esc, consume everything. bytesToConsume = iTermParserLength(context) } else { precondition(count > 0) // stuff before esc, consume up to it bytesToConsume = count } precondition(bytesToConsume > 0) let buffer = UnsafeBufferPointer(start: iTermParserPeekRawBytes(context, bytesToConsume)!, count: Int(bytesToConsume)) let data = Data(buffer: buffer) iTermParserAdvanceMultiple(context, bytesToConsume) return .data(data) } private func parseGround(_ context: UnsafeMutablePointer<iTermParserContext>, token result: VT100Token) -> VT100DCSParserHookResult { // Base state, possibly pre-framer. Everything should be wrapped in OSC 134 or 135. while iTermParserCanAdvance(context) { switch parseNextOSC(context, skipInitialGarbage: true) { case .osc(134, let payload): return parseFramerPayload(payload, into: result) case .osc(135, let payload): return parsePreFramerPayload(payload, into: result) case .blocked: return .blocked case .notOSC: fatalError() case .osc(let code, let payload): DLog("Ignore unrecognized osc with code \(code) and payload \(payload)") // Ignore unrecognized OSC } } return .canReadAgain } private func parseBody(_ context: UnsafeMutablePointer<iTermParserContext>, identifier id: String, token result: VT100Token) -> VT100DCSParserHookResult { if !iTermParserCanAdvance(context) { return .canReadAgain } let peek = conditionallyPeekOSC(context) switch peek.result { case .osc(134, let payload), .osc(135, let payload): DLog("While parsing body, found osc with payload \(payload.semiVerboseDescription)") let expectedPrefix = "end \(id) " if payload.hasPrefix(expectedPrefix) { DLog("In body state: found valid end token") state = .ground result.type = SSH_END result.string = id + " " + String(payload.dropFirst(expectedPrefix.count)) return .canReadAgain } DLog("In body state: found valid line \(payload)") result.type = SSH_LINE result.string = payload return .canReadAgain case .osc(_, _), .notOSC: DLog("non-OSC 134/135 output: \(context.dump)") peek.backtrack() return .unhook case .blocked: DLog("Need to keep reading body, blocked at \(context.dump)") peek.backtrack() return .blocked } } private func parseOutput(_ context: UnsafeMutablePointer<iTermParserContext>, builder: SSHOutputTokenBuilder, token: VT100Token) -> VT100DCSParserHookResult { let terminator = "%end \(builder.identifier)" let peek = conditionallyPeekOSC(context) switch peek.result { case .osc(134, terminator): DLog("found terminator for identifier \(builder.identifier)") if builder.populate(token) { DLog("emit token") state = .ground return .canReadAgain } DLog("Failed to build \(builder)") return .unhook case .blocked: DLog("blocked") peek.backtrack() return .blocked case .notOSC, .osc(_, _): peek.backtrack() switch consumeUntilStartOfNextOSCOrEnd(context) { case .eof: break case .data(let text): DLog("consume \(text.semiVerboseDescription) for \(builder.identifier)") builder.append(text) } return .canReadAgain } } } extension String { var firstASCIICharacter: UInt8 { return UInt8(utf8.first!) } } extension Data { mutating func appendBytes(_ pointer: UnsafePointer<UInt8>, length: Int, excludingCharacter: UInt8) { let buffer = UnsafeBufferPointer(start: pointer, count: length) let exclusion = Data([excludingCharacter]) var rangeToSearch = 0..<length while rangeToSearch.lowerBound < rangeToSearch.upperBound { if let excludeRange = buffer.firstRange(of: exclusion, in: rangeToSearch) { append(from: pointer, range: rangeToSearch.lowerBound ..< excludeRange.lowerBound) rangeToSearch = excludeRange.upperBound..<length } else { append(from: pointer, range: rangeToSearch.lowerBound ..< length) return } } } mutating func append(from pointer: UnsafePointer<UInt8>, range: Range<Int>) { append(pointer.advanced(by: range.lowerBound), count: range.count) } } private class SSHOutputTokenBuilder { let pid: Int32 let channel: Int8 let identifier: String let depth: Int enum Flavor: String { case output = "%output" case autopoll = "%autopoll" } @objc private(set) var rawData = Data() init?(_ string: String) { let parts = string.components(separatedBy: " ") guard let flavor = Flavor(rawValue: parts[0]) else { return nil } switch flavor { case .output: guard parts.count >= 5, let pid = Int32(parts[2]), let channel = Int8(parts[3]), let depth = Int(parts[4]) else { return nil } self.pid = pid self.channel = channel self.depth = depth case .autopoll: guard parts.count >= 2 else { return nil } self.pid = SSH_OUTPUT_AUTOPOLL_PID self.channel = 1 self.depth = 0 } self.identifier = parts[1] } func append(_ data: Data) { rawData.append(data) } private var decoded: Data? { if pid == SSH_OUTPUT_AUTOPOLL_PID { return ((String(data: rawData, encoding: .utf8) ?? "") + "\nEOF\n").data(using: .utf8) } else { return rawData } } func populate(_ token: VT100Token) -> Bool { guard let data = decoded else { return false } token.csi.pointee.p.0 = pid token.csi.pointee.p.1 = Int32(channel) token.csi.pointee.count = 2 token.savedData = data token.type = SSH_OUTPUT return true } } @objc class ParsedSSHOutput: NSObject { @objc let pid: Int32 @objc let channel: Int32 @objc let data: Data @objc init?(_ token: VT100Token) { guard token.type == SSH_OUTPUT else { return nil } guard token.csi.pointee.count >= 2 else { return nil } pid = token.csi.pointee.p.0 channel = token.csi.pointee.p.1 data = token.savedData } } extension String { func removing(prefix: String) -> Substring { guard hasPrefix(prefix) else { return Substring(self) } return dropFirst(prefix.count) } fileprivate static let VT100CC_ST = "\u{1b}\\" } extension Substring { var removingOSC134Prefix: Substring { let osc134 = "\u{1b}]134;" guard hasPrefix(osc134) else { return Substring(self) } guard let colon = range(of: ":") else { return "" } return self[colon.upperBound...] } } extension Data { func ends(with possibleSuffix: Data) -> Bool { if count < possibleSuffix.count { return false } let i = count - possibleSuffix.count return self[i...] == possibleSuffix } } func iTermParserBacktrack(_ context: UnsafeMutablePointer<iTermParserContext>, offset: Int) { iTermParserBacktrackBy(context, Int32(iTermParserNumberOfBytesConsumed(context) - offset)) } extension UnsafeMutablePointer where Pointee == iTermParserContext { var dump: String { let length = iTermParserLength(self) let bytes = iTermParserPeekRawBytes(self, length)! return "count=\(length) " + (0..<length).map { i -> String in let c = bytes[Int(i)] if c < 32 || c >= 127 { let hex: String = String(format: "%02x", Int(c)) return "<0x" + hex + ">" } return String(ascii: UInt8(c)) }.joined(separator: "") } }
gpl-2.0
ebb0262f103f1caac05271b23edf51cc
34.993174
117
0.555282
4.722794
false
false
false
false
guowilling/iOSExamples
Swift/PictureProcessing/SampleCodeGPUImage/美颜相机/ViewController.swift
2
1216
// // ViewController.swift // 美颜相机 // // Created by 郭伟林 on 2017/9/6. // Copyright © 2017年 SR. All rights reserved. // import UIKit import GPUImage class ViewController: UIViewController { @IBOutlet var imageView : UIImageView! fileprivate lazy var camera : GPUImageStillCamera = GPUImageStillCamera(sessionPreset: AVCaptureSessionPresetHigh, cameraPosition: .front) fileprivate lazy var filter = GPUImageBrightnessFilter() override func viewDidLoad() { super.viewDidLoad() camera.outputImageOrientation = .portrait filter.brightness = 0.1 camera.addTarget(filter) let preImageView = GPUImageView(frame: view.bounds) view.insertSubview(preImageView, at: 0) filter.addTarget(preImageView) camera.startCapture() } @IBAction func takePhoto() { camera.capturePhotoAsImageProcessedUp(toFilter: filter, withCompletionHandler: { (image, error) in UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil) self.imageView.image = image self.camera.stopCapture() }) } }
mit
8a7a5703d7c1d49e34f2f9953beb4d14
24.510638
142
0.633862
4.954545
false
false
false
false
xmartlabs/XLActionController
Example/CustomActionControllers/Spotify/Spotify.swift
1
7943
// Spotify.swift // Spotify ( https://github.com/xmartlabs/XLActionController ) // // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit #if IMPORT_BASE_XLACTIONCONTROLLER import XLActionController #endif open class SpotifyCell: ActionCell { public override init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func awakeFromNib() { super.awakeFromNib() initialize() } func initialize() { backgroundColor = .clear let backgroundView = UIView() backgroundView.backgroundColor = UIColor.white.withAlphaComponent(0.3) selectedBackgroundView = backgroundView actionTitleLabel?.textColor = .white actionTitleLabel?.textAlignment = .left } } public struct SpotifyHeaderData { var title: String var subtitle: String var image: UIImage public init(title: String, subtitle: String, image: UIImage) { self.title = title self.subtitle = subtitle self.image = image } } open class SpotifyHeaderView: UICollectionReusableView { open lazy var imageView: UIImageView = { let imageView = UIImageView(frame: CGRect.zero) imageView.image = UIImage(named: "sp-header-icon") imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() open lazy var title: UILabel = { let title = UILabel(frame: CGRect.zero) title.font = UIFont(name: "HelveticaNeue-Bold", size: 18) title.text = "The Fast And ... The Furious Soundtrack Collection" title.textColor = UIColor.white title.translatesAutoresizingMaskIntoConstraints = false title.sizeToFit() return title }() open lazy var artist: UILabel = { let discArtist = UILabel(frame: CGRect.zero) discArtist.font = UIFont(name: "HelveticaNeue", size: 16) discArtist.text = "Various..." discArtist.textColor = UIColor.white.withAlphaComponent(0.8) discArtist.translatesAutoresizingMaskIntoConstraints = false discArtist.sizeToFit() return discArtist }() public override init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func awakeFromNib() { super.awakeFromNib() initialize() } func initialize() { translatesAutoresizingMaskIntoConstraints = false backgroundColor = .clear addSubview(imageView) addSubview(title) addSubview(artist) let separator: UIView = { let separator = UIView(frame: CGRect.zero) separator.backgroundColor = UIColor.white.withAlphaComponent(0.3) separator.translatesAutoresizingMaskIntoConstraints = false return separator }() addSubview(separator) let views = [ "ico": imageView, "title": title, "artist": artist, "separator": separator ] let metrics = [ "icow": 54, "icoh": 54 ] let options = NSLayoutConstraint.FormatOptions() addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[ico(icow)]-10-[title]-15-|", options: options, metrics: metrics, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[separator]|", options: options, metrics: metrics, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[ico(icoh)]", options: options, metrics: metrics, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-18-[title][artist]", options: .alignAllLeft, metrics: metrics, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[separator(1)]|", options: options, metrics: metrics, views: views)) } } open class SpotifyActionController: ActionController<SpotifyCell, ActionData, SpotifyHeaderView, SpotifyHeaderData, UICollectionReusableView, Void> { fileprivate lazy var blurView: UIVisualEffectView = { let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] return blurView }() open override func viewDidLoad() { super.viewDidLoad() backgroundView.addSubview(blurView) cancelView?.frame.origin.y = view.bounds.size.height // Starts hidden below screen cancelView?.layer.shadowColor = UIColor.black.cgColor cancelView?.layer.shadowOffset = CGSize( width: 0, height: -4) cancelView?.layer.shadowRadius = 2 cancelView?.layer.shadowOpacity = 0.8 } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) blurView.frame = backgroundView.bounds } public override init(nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) settings.behavior.bounces = true settings.behavior.scrollEnabled = true settings.cancelView.showCancel = true settings.animation.scale = nil settings.animation.present.springVelocity = 0.0 settings.cancelView.hideCollectionViewBehindCancelView = true cellSpec = .nibFile(nibName: "SpotifyCell", bundle: Bundle(for: SpotifyCell.self), height: { _ in 60 }) headerSpec = .cellClass( height: { _ in 84 }) onConfigureCellForAction = { [weak self] cell, action, indexPath in cell.setup(action.data?.title, detail: action.data?.subtitle, image: action.data?.image) cell.separatorView?.isHidden = indexPath.item == (self?.collectionView.numberOfItems(inSection: indexPath.section))! - 1 cell.alpha = action.enabled ? 1.0 : 0.5 } onConfigureHeader = { (header: SpotifyHeaderView, data: SpotifyHeaderData) in header.title.text = data.title header.artist.text = data.subtitle header.imageView.image = data.image } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func performCustomDismissingAnimation(_ presentedView: UIView, presentingView: UIView) { super.performCustomDismissingAnimation(presentedView, presentingView: presentingView) cancelView?.frame.origin.y = view.bounds.size.height + 10 } open override func onWillPresentView() { cancelView?.frame.origin.y = view.bounds.size.height } }
mit
3e2257d13eb9612823f99e045fe5edb3
38.715
160
0.674053
4.888
false
false
false
false
Donny8028/Swift-Animation
TumblrMenu/TumblrMenu/EffectView.swift
1
898
// // EffectView.swift // TumblrMenu // // Created by 賢瑭 何 on 2016/5/23. // Copyright © 2016年 Donny. All rights reserved. // import UIKit class EffectView: UIView { var view: UIView? override init(frame: CGRect) { super.init(frame: frame) view = setupView() view?.frame = bounds addSubview(view!) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) view = setupView() view?.frame = bounds addSubview(view!) fatalError("init(coder:) has not been implemented") } func setupView() -> UIView? { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "EffectView", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as? UIView return view } }
mit
5223828a46f5cd223acf3fc8e05890d3
20.682927
77
0.572553
4.154206
false
false
false
false
arietis/codility-swift
13.2.swift
1
489
public func solution(inout A : [Int], inout _ B : [Int]) -> [Int] { // write your code in Swift 2.2 (Linux) let n = A.count var fibs = Array(count: n + 2, repeatedValue: 0) fibs[1] = 1 fibs[2] = 2 if n > 2 { for i in 3...n { fibs[i] = (fibs[i - 1] + fibs[i - 2]) % (1 << 30) } } var result = Array(count: A.count, repeatedValue: 0) for i in 0..<n { result[i] = fibs[A[i]] % (1 << B[i]) } return result }
mit
9556b2fba0e0968fa67f78ffd31ea035
21.227273
67
0.466258
2.794286
false
false
false
false
codepgq/LearningSwift
CollectionViewAndVisualEffectView/CollectionViewAndVisualEffectView/ScreenView.swift
1
1383
// // ScreenView.swift // CollectionViewAndVisualEffectView // // Created by ios on 16/9/9. // Copyright © 2016年 ios. All rights reserved. // import UIKit class ScreenView: UIView { var image : UIImageView! var title : UILabel? var desTitle :UILabel? var block:(view : ScreenView) -> (); init(frame: CGRect, model : CellModel,tapBlock : (view : ScreenView) -> ()){ block = tapBlock super.init(frame: frame) createUI(model) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createUI(model : CellModel){ image = UIImageView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height - 50)) image.image = model.image title = UILabel(frame: CGRect(x: 0, y: self.frame.height - 45, width: self.frame.width, height: 20)) title?.text = model.title desTitle = UILabel(frame: CGRect(x: 0, y: self.frame.height-25, width: self.frame.width, height: 20)) desTitle?.text = model.descriptionStr self.addSubview(image) self.addSubview(title!) self.addSubview(desTitle!) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) block(view: self) } }
apache-2.0
5c18ac7c888cb443b49d825a3562a683
29
111
0.622464
3.854749
false
false
false
false
lilongcnc/Swift-weibo2015
ILWEIBO04/ILWEIBO04/Classes/BusinessModel/StatusesModel.swift
1
16224
// // StatusesModel.swift // ILWEIBO04 // // Created by 李龙 on 15/3/6. // Copyright (c) 2015年 Lauren. All rights reserved. // /** 模型自己封装了 获取模型数据的方法 ,这样减轻了视图控制器的负担 */ import UIKit /// 加载微博数据 URL private let WB_Home_Timeline_URL = "https://api.weibo.com/2/statuses/home_timeline.json" /// 微博数据列表模型 class StatusesModel: NSObject, DictModelProtocol { /// 微博记录数组 var statuses: [StatusModel]? /// 微博总数 var total_number: Int = 0 /// 未读数量 var has_unread: Int = 0 //字典转模型方法 static func customClassMapping() -> [String: String]? { return ["statuses": "\(StatusModel.self)"] } /// 刷新微博数据 - 专门加载网络数据以及错误处理的回调 /// 一旦加载成功,负责字典转模型,回调传回转换过的模型数据 //MARK: 这个方法供外界调用,一定要写class,否则调用到方法不会自己提示出 completiom 闭包 //MARK: 函数中,可以直接给形参设置初始值为 maxId : Int = 0 /// topId: 是视图控制器中 statues 的第一条微博的 id,topId 和 maxId 之间就是 statuses 中的所有数据 class func loadStatusesModel(maxId : Int = 0,topId : Int, completiom:(data : StatusesModel?, error :NSError?) -> ()){ //上拉加载,判断是否可以从本地缓存加在数据 if maxId > 0 { //检查本地数据,如果存在本地数据,那么就从本地加载 if let result = checkLocalData(maxId){ println("))))))))))))))) 加载本地数据...") //从本地加载了数据,直接回调 let data = StatusesModel() data.statuses = result completiom(data: data, error: nil) return } } //下边是直接从网络上加载模型数据 println("=====> 从网络加载数据") let net = NetWorkManager.instance //获取access_token if let token = AccessTokenModel.loadAccessToken()?.access_token { let params = ["access_token" : token, "max_id" : "\(maxId)"] //发送网络请求,获取模型数据 net.requestJSON(.GET, WB_Home_Timeline_URL, params) { (result, error) -> () in //处理错误 if error != nil{ // println(error) // SVProgressHUD.showErrorWithStatus("\(error)") //直接回调报错 completiom(data: nil, error: error!) return } //字典转模型 let data = DictModelManager.sharedManager.objectWithDictionary(result as! NSDictionary, cls: StatusesModel.self) as? StatusesModel //保存微博数据 self.saveStatusData(data?.statuses) // MARK: 如果 maxId > 0,表示是上拉刷新,将 maxId & topId 之间的所有数据的 refresh 状态修改成 1 self.updateRefreshState(maxId, topId: topId) // 如果有下载图像的 url,就先下载图像 if let urls = StatusesModel.pictureURLs(data?.statuses) { //获取 图像链接数组 net.downloadImages(urls) { (result, error) -> () in //这里我们不处理(result, error) 参数,可以换成( _ ,_ ) // 回调通知视图控制器刷新数据 completiom(data: data, error: nil) } }else{ //回调,将结果发送给视图控制器 /** 报错:fatal error: unexpectedly found nil while unwrapping an Optional value 因为 completiom(data: data, error: error!) error加了 ! */ completiom(data: data, error: nil) } } } } //检查本地是否存在小于maxId的连续数据,存在则返回本地数据,不存在则返回nil,然后调用加载网络方法 class func checkLocalData(maxId: Int) -> [StatusModel]?{ // 1. 判断 refresh 标记 let sql = "SELECT count(*) FROM T_Status \n" + "WHERE id = (\(maxId) + 1) AND refresh = 1" if SQLite.sharedSQLite.execCount(sql) == 0 { return nil } println("--> 加载本地缓存数据") // TODO: 生成应用程序需要的结果集合直接返回即可! // 结果集合中包含微博的数组,同时,需要把分散保存在数据表中的数据,再次整合! let resultSQL = "SELECT id, text, source, created_at, reposts_count, \n" + "comments_count, attitudes_count, userId, retweetedId FROM T_Status \n" + "WHERE id < \(maxId) \n" + "ORDER BY id DESC \n" + "LIMIT 20" // 实例化微博数据数组 var statuses = [StatusModel]() /// 查询返回结果集合 let recordSet = SQLite.sharedSQLite.execRecordSet(resultSQL) /// 遍历数组,建立目标微博数据数组 for record in recordSet { // TODO: - 建立微博数据 statuses.append(StatusModel(record: record as! [AnyObject])) println("你好啊啊") } if statuses.count == 0 { return nil }else{ return statuses } } //修改模型数据的refresh属性 为 1 class func updateRefreshState(maxId : Int,topId : Int){ let sql = "UPDATE T_Status SET refresh = 1 \n" + "WHERE id BETWEEN \(maxId) AND \(topId);" SQLite.sharedSQLite.execSQL(sql) } //保存微博数据到数据库 class func saveStatusData(statuses : [StatusModel]?) { if statuses == nil { return } //MARK: 1.事物,可以在存储过程中,把结果回回滚到最开始“ BEGIN TRANSACTION ”的位置 SQLite.sharedSQLite.execSQL("BEGIN TRANSACTION") //遍历数据 for s in statuses! { //2. 存储配图记录 if !StatusPictureURLModel.savePictures(s.id, pictures: s.pic_urls){ //这里不要随便加 !号 // 一旦出现错误就“回滚” - 放弃自“BEGIN”以来所有的操作 println("配图记录插入错误") SQLite.sharedSQLite.execSQL("ROLLBACK TRANSACTION") //这里要特别注意出错直接跳出 break } //3.存储用户记录 - 用户不能左右服务器返回的数据 if s.user != nil { if !s.user!.insertDB(){ println("插入用户数据错误") SQLite.sharedSQLite.execSQL("ROLLBACK TRANSACTION") break } } //4.存储微博数据 if !s.insertDB(){ //保存微博数据 //到这里说明保存失败 println("保存微博数据失败") SQLite.sharedSQLite.execSQL("ROLLBACK TRANSACTION") } //5.存储转发的微博数据(用户数据/配图) if s.retweeted_status != nil { //或者let a = s.retweeted_status. //说明存在转发微博,判断是否存储成功 if !s.retweeted_status!.insertDB(){ println("插入转发微博数据错误") SQLite.sharedSQLite.execSQL("ROLLBACK TRANSACTION") break } } } //提交事务(到这里说明前边没让回滚) SQLite.sharedSQLite.execSQL("COMMIT TRANSACTION") } /// 取出给定的微博数据中 正文的所有图片的 URL 数组 /// /// :param: statuses 微博数据数组,可以为空 /// /// :returns: 微博数组中的 url 完整数组,可以为空(为纯文本数据的话,那么就没有图片的url) class func pictureURLs(statues : [StatusModel]?) -> [String]?{ // 判断 微博数组是否有值 if statues == nil { return nil } // 遍历微博模型数组,保存到中间数组 var list = [String]() for statue in statues! { // 遍历微博模型数组中的 图像链接数组 if let pictureURLS = statue.pictureUrls{ for pictureURL in pictureURLS{ // println(pictureURL.thumbnail_pic) list.append(pictureURL.thumbnail_pic!) } } } // 判断 图像链接数组 是否有值 if list.count > 0 { return list }else{ return nil } } } /// 微博模型 class StatusModel: NSObject,DictModelProtocol { /// 微博创建时间 var created_at: String? /// 微博ID var id: Int = 0 /// 微博信息内容 var text: String? /// 微博来源 var source: String? //自定义属性: 过滤后的微博来源 var sourceStr : String { return source?.removeHref() ?? "" } /// 转发数 var reposts_count: Int = 0 /// 评论数 var comments_count: Int = 0 /// 表态数 var attitudes_count: Int = 0 /// 用户信息 var user: UserInfoModel? /// 配图数组 var pic_urls: [StatusPictureURLModel]? /// 转发微博,如果这个参数有值,就说明有转发的微博。没有就说明是自己发的微博。可以用这个属性来判断 是否转发 var retweeted_status: StatusModel? /// 要显示的配图数组 /// 如果是原创微博,就使用 pic_urls /// 如果是转发微博,使用 retweeted_status.pic_urls var pictureUrls: [StatusPictureURLModel]? { if retweeted_status != nil { return retweeted_status?.pic_urls } else { return pic_urls } } /// 自定义属性: 返回所有的大图链接URL var large_pic_Urls : [String]? { //MARK : 写get { } 严谨???待验证 get{ // 使用KVC直接获取 所有的大图链接URL let allurls = self.valueForKeyPath("pictureUrls.large_pic") as! [String] return allurls } } //字典转模型方法 static func customClassMapping() -> [String : String]? { return ["pic_urls":"\(StatusPictureURLModel.self)","user":"\(UserInfoModel.self)","retweeted_status":"\(StatusModel.self)"] } /// 使用数据库的结果集合,实例化微博数据 /// 构造函数,实例化并且返回对象 init(record: [AnyObject]) { // id, text, source, created_at, reposts_count, comments_count, attitudes_count, userId, retweetedId id = record[0] as! Int text = record[1] as? String source = record[2] as? String created_at = record[3] as? String reposts_count = record[4] as! Int comments_count = record[5] as! Int attitudes_count = record[6] as! Int // 用户对象 let userId = record[7] as! Int user = UserInfoModel(pkId: userId) // 转发微博对象 let retId = record[8] as! Int // 如果存在转发数据 if retId > 0 { retweeted_status = StatusModel(pkId: retId) } // 配图数组 pic_urls = StatusPictureURLModel.pictureUrls(id) } /// 使用数据库的主键实例化对象 /// MARK:convenience 不是主构造函数,简化的构造函数,必须调用默认的构造函数 convenience init(pkId: Int) { // 使用主键查询数据库 let sql = "SELECT id, text, source, created_at, reposts_count, \n" + "comments_count, attitudes_count, userId, retweetedId FROM T_Status \n" + "WHERE id = \(pkId) " let record = SQLite.sharedSQLite.execRow(sql) self.init(record: record!) //MARK: 这里切记要调用默认的主要的构造函数 } /// 保存微博数据 func insertDB() -> Bool{ //用户id或者转发微博的id 是否有值 let userID = user?.id ?? 0 let retID = retweeted_status?.id ?? 0 //判断是否数据已经存在,存在的话,就不插入 var sql = "SELECT count(*) FROM T_Status WHERE id = \(id);" if SQLite.sharedSQLite.execCount(sql) > 0{ return true //有数据 } //这里存入微博数据,只使用 INSERT,是因为 INSERT AND REPLACE 会在更新数据的时候,直接将 refresh 重新设置为 0 sql = "INSERT INTO T_Status \n" + "(id, text, source, created_at, reposts_count, comments_count, attitudes_count, userId, retweetedId) \n" + "VALUES \n" + "(\(id), '\(text!)', '\(source!)', '\(created_at!)', \(reposts_count), \(comments_count), \(attitudes_count), \(userID), \(retID));" return SQLite.sharedSQLite.execSQL(sql) } } /// 微博配图模型 class StatusPictureURLModel: NSObject { /// 缩略图 URL var thumbnail_pic: String? { didSet{ let largeURL = thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "large") large_pic = largeURL } } /// 大图 URl var large_pic: String? /// 使用数据库结果集合实例化对象,并且赋值 init(record: [AnyObject]) { println("\(record[0] as? String)") thumbnail_pic = record[0] as? String } /// 如果要返回对象的数组,可以使用类函数 /// 给定一个微博代号,返回改微博代号对应配图数组,0~9张配图 class func pictureUrls(statusId: Int) -> [StatusPictureURLModel]? { let sql = "SELECT thumbnail_pic FROM T_StatusPic WHERE status_id = \(statusId)" let recordSet = SQLite.sharedSQLite.execRecordSet(sql) // 实例化数组 var list = [StatusPictureURLModel]() for record in recordSet { list.append(StatusPictureURLModel(record: record as! [AnyObject])) } if list.count == 0 { return nil } else { return list } } ///将配图数组存入数据库 class func savePictures(statusID : Int,pictures:[StatusPictureURLModel]?) -> Bool{ if pictures == nil { //没有图需要保存,继续后边的存储工作 return true } //避免图片数据被重复插入,在插入数据前需要先判断一下 //依据 已存的statusID 是否等于 要存的 statusID let sql = "SELECT count(*) FROM T_StatusPic WHERE statusId = \(statusID);" if SQLite.sharedSQLite.execCount(sql) > 0{ //TODO ..... return true } //更新微博图片 for p in pictures! { //保存图片 if !p.insertToDB(statusID){ //这里说明 图片保存失败,直接返回 return false } } return true } /// 插入到数据库的方法 func insertToDB(statusID :Int) -> Bool{ //把微博id和对应的图片存入,数据库中出现同一个id对应这不同的地址的图片地址 let sql = "INSERT INTO T_StatusPic (statusId, thumbnail_pic) VALUES (\(statusID), '\(thumbnail_pic!)');" // println("--------·\(statusID)----\(thumbnail_pic)") return SQLite.sharedSQLite.execSQL(sql) } }
mit
aaccc5124d440b79a7a9d92a107c6d3e
29.221461
146
0.516129
3.938411
false
false
false
false
devpunk/cartesian
cartesian/Data/DNodePolygonExtension.swift
1
2428
import UIKit import CoreData extension DNodePolygon { //MARK: public final func drawPolygon( rect:CGRect, context:CGContext, initialAngle:CGFloat, zoom:CGFloat, sides:Int) { var modelWidth:CGFloat = CGFloat(self.width) var modelHeight:CGFloat = CGFloat(self.height) let originX:CGFloat = rect.origin.x let originY:CGFloat = rect.origin.y let width:CGFloat = rect.size.width let height:CGFloat = rect.size.height let width_2:CGFloat = width / 2.0 let height_2:CGFloat = height / 2.0 let centerX:CGFloat = width_2 + originX let centerY:CGFloat = height_2 + originY let deltaSpaceWidth:CGFloat = modelWidth - width let deltaSpaceHeight:CGFloat = modelHeight - height if deltaSpaceWidth > 0 || deltaSpaceHeight > 0 { let ratio:CGFloat if deltaSpaceWidth >= deltaSpaceHeight { ratio = modelWidth / width } else { ratio = modelHeight / height } modelWidth = modelWidth / ratio modelHeight = modelHeight / ratio } let zoomedWidth:CGFloat = modelWidth * zoom let zoomedHeight:CGFloat = modelHeight * zoom let radiusWidth:CGFloat = zoomedWidth / 2.0 let radiusHeight:CGFloat = zoomedHeight / 2.0 let rotationFactor:CGFloat = DNode.kPi2 / CGFloat(sides) for index:Int in 0 ..< sides { let thisIndex:CGFloat = CGFloat(index) + 1 let thisAngle:CGFloat = (thisIndex * rotationFactor) + initialAngle let cosineRotation:CGFloat = cos(thisAngle) * radiusWidth let sineRotation:CGFloat = sin(thisAngle) * radiusHeight let positionX:CGFloat = centerX + cosineRotation let positionY:CGFloat = centerY + sineRotation let positionPoint:CGPoint = CGPoint( x:positionX, y:positionY) if index == 0 { context.move(to:positionPoint) } else { context.addLine(to:positionPoint) } } context.closePath() context.drawPath(using:CGPathDrawingMode.fillStroke) } }
mit
b8b92d8d9b574bd87a8e6087a00ff96c
30.947368
79
0.553542
4.865731
false
false
false
false
KiiPlatform/thing-if-iOSSample
SampleProject/TriggeredServerCodeResultViewController.swift
1
2555
import UIKit import ThingIFSDK class TriggeredServerCodeResultViewController: KiiBaseTableViewController { var serverCodeResults = [TriggeredServerCodeResult]() var trigger: Trigger? = nil override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) serverCodeResults.removeAll() self.tableView.reloadData() self.showActivityView(true) getServerCodeResults(nil) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return serverCodeResults.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ServerCodeResultCell") let result = serverCodeResults[indexPath.row] if result.succeeded { cell!.textLabel?.text = "Succeeded" }else { cell!.textLabel?.text = "Failed:" + (result.error!.errorMessage ?? "") } let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss" cell!.detailTextLabel?.text = dateFormatter.stringFromDate(result.executedAt) return cell! } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func getServerCodeResults(nextPaginationKey: String?){ if iotAPI != nil && target != nil { showActivityView(true) // use default bestEffortLimit iotAPI!.listTriggeredServerCodeResults((self.trigger?.triggerID)!, bestEffortLimit: 0, paginationKey: nextPaginationKey, completionHandler: { (results, paginationKey, error) -> Void in self.showActivityView(false) if results != nil { for result in results! { self.serverCodeResults.append(result) } // paginationKey is nil, then there is not more triggers, reload table if paginationKey == nil { self.tableView.reloadData() self.showActivityView(false) }else { self.getServerCodeResults(paginationKey) } }else { self.showAlert("Get ServerCodeResults Failed", error: error, completion: nil) } }) } } }
mit
ec3a4dd6bebc7f8dfd30bb81aaa48069
38.9375
196
0.609002
5.554348
false
false
false
false
OscarSwanros/swift
test/SILGen/objc_enum.swift
4
2252
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership > %t.out // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize %s < %t.out // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.out // REQUIRES: objc_interop import gizmo // CHECK-DAG: sil shared [serializable] @_T0SC16NSRuncingOptionsO{{[_0-9a-zA-Z]*}}fC // CHECK-DAG: sil shared [serializable] @_T0SC16NSRuncingOptionsO8rawValueSivg // CHECK-DAG: sil shared [serializable] @_T0SC16NSRuncingOptionsO9hashValueSivg // Non-payload enum ctors don't need to be instantiated at all. // NEGATIVE-NOT: sil shared [transparent] @_T0SC16NSRuncingOptionsO5MinceAbBmF // NEGATIVE-NOT: sil shared [transparent] @_T0SC16NSRuncingOptionsO12QuinceSlicedAbBmF // NEGATIVE-NOT: sil shared [transparent] @_T0SC16NSRuncingOptionsO15QuinceJuliennedAbBmF // NEGATIVE-NOT: sil shared [transparent] @_T0SC16NSRuncingOptionsO11QuinceDicedAbBmF var runcing: NSRuncingOptions = .mince var raw = runcing.rawValue var eq = runcing == .quinceSliced var hash = runcing.hashValue func testEm<E: Equatable>(_ x: E, _ y: E) {} func hashEm<H: Hashable>(_ x: H) {} func rawEm<R: RawRepresentable>(_ x: R) {} testEm(NSRuncingOptions.mince, .quinceSliced) hashEm(NSRuncingOptions.mince) rawEm(NSRuncingOptions.mince) rawEm(NSFungingMask.asset) protocol Bub {} extension NSRuncingOptions: Bub {} // CHECK-32-DAG: integer_literal $Builtin.Int2048, -2147483648 // CHECK-64-DAG: integer_literal $Builtin.Int2048, 2147483648 _ = NSFungingMask.toTheMax // CHECK-DAG: sil_witness_table shared [serialized] NSRuncingOptions: RawRepresentable module gizmo // CHECK-DAG: sil_witness_table shared [serialized] NSRuncingOptions: Equatable module gizmo // CHECK-DAG: sil_witness_table shared [serialized] NSRuncingOptions: Hashable module gizmo // CHECK-DAG: sil_witness_table shared [serialized] NSFungingMask: RawRepresentable module gizmo // CHECK-DAG: sil shared [transparent] [serialized] [thunk] @_T0SC16NSRuncingOptionsOs16RawRepresentable5gizmosACP{{[_0-9a-zA-Z]*}}fCTW // Extension conformances get linkage according to the protocol's accessibility, as normal. // CHECK-DAG: sil_witness_table hidden NSRuncingOptions: Bub module objc_enum
apache-2.0
473c106cd9be4f6cf1779b3c41b085ea
42.307692
135
0.772202
3.361194
false
false
false
false
BGDigital/mckuai2.0
mckuai/mckuai/login/Password.swift
1
4452
// // Password.swift // mckuai // // Created by 夕阳 on 15/2/2. // Copyright (c) 2015年 XingfuQiu. All rights reserved. // import Foundation import UIKit class Profile_Password:UIViewController,UIGestureRecognizerDelegate { var manager = AFHTTPRequestOperationManager() @IBOutlet weak var old_pass: UITextField! @IBOutlet weak var new_pass: UITextField! @IBOutlet weak var ensure_pass: UITextField! override func viewDidLoad() { self.navigationController?.navigationBar.tintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) var barSize = self.navigationController?.navigationBar.frame initNavigation() } func initNavigation() { self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() let navigationTitleAttribute : NSDictionary = NSDictionary(objectsAndKeys: UIColor.whiteColor(),NSForegroundColorAttributeName) self.navigationController?.navigationBar.titleTextAttributes = navigationTitleAttribute as [NSObject : AnyObject] self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor(red: 0.247, green: 0.812, blue: 0.333, alpha: 1.00)) var back = UIBarButtonItem(image: UIImage(named: "nav_back"), style: UIBarButtonItemStyle.Bordered, target: self, action: "backToPage") back.tintColor = UIColor.whiteColor() self.navigationItem.leftBarButtonItem = back self.navigationController?.interactivePopGestureRecognizer.delegate = self // 启用 swipe back var sendButton = UIBarButtonItem() sendButton.title = "保存" sendButton.target = self sendButton.action = Selector("save") self.navigationItem.rightBarButtonItem = sendButton } func backToPage() { self.navigationController?.popViewControllerAnimated(true) } func save(){ let oldpass = old_pass.text let newpass = new_pass.text let ensure = ensure_pass.text if oldpass == "" || newpass == "" || ensure == ""{ MCUtils.showCustomHUD("密码不能为空", aType: .Warning) return } if newpass != ensure { MCUtils.showCustomHUD("两次密码输入不一致", aType: .Warning) return } let dic = [ "flag":NSString(string: "password"), "userId":appUserIdSave, "old_password":oldpass, "new_password":newpass ] var hud = MBProgressHUD.showHUDAddedTo(view, animated: true) hud.labelText = "保存中" manager.POST(saveUser_url, parameters: dic, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in var json = JSON(responseObject) if "ok" == json["state"].stringValue { hud.hide(true) MCUtils.showCustomHUD("保存信息成功", aType: .Success) isLoginout = true self.navigationController?.popViewControllerAnimated(true) }else{ hud.hide(true) MCUtils.showCustomHUD("保存信息失败", aType: .Error) } }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in println("Error: " + error.localizedDescription) hud.hide(true) MCUtils.showCustomHUD("保存信息失败", aType: .Error) }) // APIClient.sharedInstance.modifiyUserInfo(self.view, ctl: self.navigationController, param: dic, success: { // (res:JSON?) in // }, failure: { // (NSError) in // }) } class func changePass(ctl:UINavigationController){ var edit_pass = UIStoryboard(name: "profile_layout", bundle: nil).instantiateViewControllerWithIdentifier("pass_edit") as! Profile_Password ctl.pushViewController(edit_pass, animated: true) } override func viewWillAppear(animated: Bool) { MobClick.beginLogPageView("userInfoSetPassWord") self.tabBarController?.tabBar.hidden = true } override func viewWillDisappear(animated: Bool) { MobClick.endLogPageView("userInfoSetPassWord") self.tabBarController?.tabBar.hidden = false } }
mit
6122bb411e26f9ea63c88389cc55b220
36.646552
147
0.610628
4.840355
false
false
false
false
rahul-apple/XMPP-Zom_iOS
Zom/Zom/Classes/View Controllers/Messages View Controller/ZomMessagesViewController.swift
1
16893
// // ZomMessagesViewController.swift // Zom // // Created by N-Pex on 2015-11-11. // // import UIKit import JSQMessagesViewController import OTRAssets import BButton var ZomMessagesViewController_associatedObject1: UInt8 = 0 extension OTRMessagesViewController { public override class func initialize() { struct Static { static var token: dispatch_once_t = 0 } // make sure this isn't a subclass if self !== OTRMessagesViewController.self { return } dispatch_once(&Static.token) { ZomUtil.swizzle(self, originalSelector: #selector(OTRMessagesViewController.collectionView(_:messageDataForItemAtIndexPath:)), swizzledSelector:#selector(OTRMessagesViewController.zom_collectionView(_:messageDataForItemAtIndexPath:))) ZomUtil.swizzle(self, originalSelector: #selector(OTRMessagesViewController.collectionView(_:attributedTextForCellBottomLabelAtIndexPath:)), swizzledSelector: #selector(OTRMessagesViewController.zom_collectionView(_:attributedTextForCellBottomLabelAtIndexPath:))) } } var shieldIcon:UIImage? { get { return objc_getAssociatedObject(self, &ZomMessagesViewController_associatedObject1) as? UIImage ?? nil } set { objc_setAssociatedObject(self, &ZomMessagesViewController_associatedObject1, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func zom_collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> ChatSecureCore.JSQMessageData! { let ret = self.zom_collectionView(collectionView, messageDataForItemAtIndexPath: indexPath) if (ret != nil && ZomStickerMessage.isValidStickerShortCode(ret.text!())) { return ZomStickerMessage(message: ret) } return ret } public func zom_collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { let string:NSMutableAttributedString = self.zom_collectionView(collectionView, attributedTextForCellBottomLabelAtIndexPath: indexPath) as! NSMutableAttributedString let lock = NSString.fa_stringForFontAwesomeIcon(FAIcon.FALock); let unlock = NSString.fa_stringForFontAwesomeIcon(FAIcon.FAUnlock); let asd:NSString = string.string let rangeLock:NSRange = asd.rangeOfString(lock); if (rangeLock.location != NSNotFound) { let attachment = textAttachment(12) let newLock = NSAttributedString.init(attachment: attachment); string.replaceCharactersInRange(rangeLock, withAttributedString: newLock) } let rangeUnLock:NSRange = asd.rangeOfString(unlock); if (rangeUnLock.location != NSNotFound) { let nothing = NSAttributedString.init(string: ""); string.replaceCharactersInRange(rangeUnLock, withAttributedString: nothing) } return string; } func textAttachment(fontSize: CGFloat) -> NSTextAttachment { var font:UIFont? = UIFont(name: kFontAwesomeFont, size: fontSize) if (font == nil) { font = UIFont.systemFontOfSize(fontSize) } let textAttachment = NSTextAttachment() let image = getTintedShieldIcon() textAttachment.image = image let aspect = image.size.width / image.size.height let height = font?.capHeight textAttachment.bounds = CGRectIntegral(CGRect(x:0,y:0,width:(height! * aspect),height:height!)) return textAttachment } func getTintedShieldIcon() -> UIImage { if (self.shieldIcon == nil) { let image = UIImage.init(named: "ic_security_white_36pt") self.shieldIcon = image?.tint(UIColor.lightGrayColor(), blendMode: CGBlendMode.Multiply) } return shieldIcon! } } public class ZomMessagesViewController: OTRMessagesHoldTalkViewController, UIGestureRecognizerDelegate, ZomPickStickerViewControllerDelegate { private var hasFixedTitleViewConstraints:Bool = false private var attachmentPickerController:OTRAttachmentPicker? = nil private var attachmentPickerView:AttachmentPicker? = nil private var attachmentPickerTapRecognizer:UITapGestureRecognizer? = nil var outgoingImage: JSQMessagesBubbleImage? = nil var incomingImage: JSQMessagesBubbleImage? = nil override public func viewDidLoad() { super.viewDidLoad() self.cameraButton?.setTitle(NSString.fa_stringForFontAwesomeIcon(FAIcon.FAPlusSquareO), forState: UIControlState.Normal) let bubbleImageFactory = JSQMessagesBubbleImageFactory() let greenColor = ZomTheme.colorWithHexString(DEFAULT_ZOM_COLOR) outgoingImage = bubbleImageFactory.outgoingMessagesBubbleImageWithColor(greenColor) incomingImage = bubbleImageFactory.incomingMessagesBubbleImageWithColor(UIColor.lightGrayColor()) self.collectionView.collectionViewLayout.messageBubbleFont = UIFont.init(name: "Calibri", size: self.collectionView.collectionViewLayout.messageBubbleFont.pointSize + 2) self.collectionView.loadEarlierMessagesHeaderTextColor = greenColor self.collectionView.typingIndicatorEllipsisColor = UIColor.whiteColor() self.collectionView.typingIndicatorMessageBubbleColor = greenColor self.inputToolbar.contentView.textView.layer.cornerRadius = self.inputToolbar.contentView.textView.frame.height/2 if let font = self.inputToolbar.contentView.textView.font { self.inputToolbar.contentView.textView.font = UIFont.init(name: "Calibri", size: font.pointSize) } if let font = self.sendButton?.titleLabel?.font { self.sendButton?.titleLabel?.font = UIFont.init(name: "Calibri", size: font.pointSize) } } public override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! { let message = self.messageAtIndexPath(indexPath) return message?.messageIncoming() == true ? incomingImage : outgoingImage } public override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { let message = self.messageAtIndexPath(indexPath) let timestampFormatter = JSQMessagesTimestampFormatter.sharedFormatter() timestampFormatter.dateTextAttributes[NSFontAttributeName] = UIFont.init(name: "Calibri", size: 12)! timestampFormatter.timeTextAttributes[NSFontAttributeName] = UIFont.init(name: "Calibri", size: 12)! return timestampFormatter.attributedTimestampForDate(message?.date()) } public func attachmentPicker(attachmentPicker: OTRAttachmentPicker!, addAdditionalOptions alertController: UIAlertController!) { let sendStickerAction: UIAlertAction = UIAlertAction(title: NSLocalizedString("Sticker", comment: "Label for button to open up sticker library and choose sticker"), style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in let storyboard = UIStoryboard(name: "StickerShare", bundle: NSBundle.mainBundle()) let vc = storyboard.instantiateInitialViewController() self.presentViewController(vc!, animated: true, completion: nil) }) alertController.addAction(sendStickerAction) } @IBAction func unwindPickSticker(unwindSegue: UIStoryboardSegue) { } public func didPickSticker(sticker: String, inPack pack: String) { super.didPressSendButton(super.sendButton, withMessageText: ":" + pack + "-" + sticker + ":", senderId: super.senderId, senderDisplayName: super.senderDisplayName, date: NSDate()) } override public func refreshTitleView() -> Void { super.refreshTitleView() if (OTRAccountsManager.allAccountsAbleToAddBuddies().count < 2) { // Hide the account name if only one if let view = self.navigationItem.titleView as? OTRTitleSubtitleView { view.subtitleLabel.hidden = true view.subtitleImageView.hidden = true if (!hasFixedTitleViewConstraints && view.constraints.count > 0) { var removeThese:[NSLayoutConstraint] = [NSLayoutConstraint]() for constraint:NSLayoutConstraint in view.constraints { if ((constraint.firstItem as? NSObject != nil && constraint.firstItem as! NSObject == view.titleLabel) || (constraint.secondItem as? NSObject != nil && constraint.secondItem as! NSObject == view.titleLabel)) { if (constraint.active && (constraint.firstAttribute == NSLayoutAttribute.Top || constraint.firstAttribute == NSLayoutAttribute.Bottom)) { removeThese.append(constraint) } } } view.removeConstraints(removeThese) let c:NSLayoutConstraint = NSLayoutConstraint(item: view.titleLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view.titleLabel.superview, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) view.addConstraint(c); hasFixedTitleViewConstraints = true } } } } override public func setupDefaultSendButton() { // Override this to always show Camera and Mic icons. We never get here // in a "knock" scenario. self.inputToolbar?.contentView?.leftBarButtonItem = self.cameraButton self.inputToolbar?.contentView?.leftBarButtonItem.enabled = false if (self.state.hasText) { self.inputToolbar?.contentView?.rightBarButtonItem = self.sendButton self.inputToolbar?.sendButtonLocation = JSQMessagesInputSendButtonLocation.Right self.inputToolbar?.contentView?.rightBarButtonItem.enabled = self.state.isThreadOnline } else { self.inputToolbar?.contentView?.rightBarButtonItem = self.microphoneButton self.inputToolbar?.contentView?.rightBarButtonItem.enabled = false } } override public func didPressAccessoryButton(sender: UIButton!) { if (sender == self.cameraButton) { let pickerView = getPickerView() self.view.addSubview(pickerView) var newFrame = pickerView.frame; let toolbarBottom = self.inputToolbar.frame.origin.y + self.inputToolbar.frame.size.height newFrame.origin.y = toolbarBottom - newFrame.size.height; UIView.animateWithDuration(0.3) { pickerView.frame = newFrame; } } else { super.didPressAccessoryButton(sender) } } func getPickerView() -> UIView { if (self.attachmentPickerView == nil) { self.attachmentPickerView = UINib(nibName: "AttachmentPicker", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as? AttachmentPicker self.attachmentPickerView!.frame.size.width = self.view.frame.width self.attachmentPickerView!.frame.size.height = 100 let toolbarBottom = self.inputToolbar.frame.origin.y + self.inputToolbar.frame.size.height self.attachmentPickerView!.frame.origin.y = toolbarBottom // Start hidden (below screen) if (!UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) { self.attachmentPickerView!.removePhotoButton() } if (!UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) { self.attachmentPickerView!.removeCameraButton() } self.attachmentPickerTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onTap(_:))) self.attachmentPickerTapRecognizer!.cancelsTouchesInView = true self.attachmentPickerTapRecognizer!.delegate = self self.view.addGestureRecognizer(self.attachmentPickerTapRecognizer!) } return self.attachmentPickerView! } func onTap(sender: UIGestureRecognizer) { closePickerView() } func closePickerView() { // Tapped outside attachment picker. Close it. if (self.attachmentPickerTapRecognizer != nil) { self.view.removeGestureRecognizer(self.attachmentPickerTapRecognizer!) self.attachmentPickerTapRecognizer = nil } if (self.attachmentPickerView != nil) { var newFrame = self.attachmentPickerView!.frame; let toolbarBottom = self.inputToolbar.frame.origin.y + self.inputToolbar.frame.size.height newFrame.origin.y = toolbarBottom UIView.animateWithDuration(0.3, animations: { self.attachmentPickerView!.frame = newFrame; }, completion: { (success) in self.attachmentPickerView?.removeFromSuperview() self.attachmentPickerView = nil }) } } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } @IBAction func attachmentPickerSelectPhotoWithSender(sender: AnyObject) { closePickerView() attachmentPicker().showImagePickerForSourceType(UIImagePickerControllerSourceType.PhotoLibrary) } @IBAction func attachmentPickerTakePhotoWithSender(sender: AnyObject) { closePickerView() attachmentPicker().showImagePickerForSourceType(UIImagePickerControllerSourceType.Camera) } func attachmentPicker() -> OTRAttachmentPicker { if (self.attachmentPickerController == nil) { self.attachmentPickerController = OTRAttachmentPicker(parentViewController: self.parentViewController?.parentViewController, delegate: (self as! OTRAttachmentPickerDelegate)) } return self.attachmentPickerController! } @IBAction func attachmentPickerStickerWithSender(sender: AnyObject) { closePickerView() let storyboard = UIStoryboard(name: "StickerShare", bundle: NSBundle.mainBundle()) let vc = storyboard.instantiateInitialViewController() self.presentViewController(vc!, animated: true, completion: nil) } public func setupInfoButton() { let image = UIImage(named: "OTRInfoIcon", inBundle: OTRAssets.resourcesBundle(), compatibleWithTraitCollection: nil) let item = UIBarButtonItem(image: image, style: .Plain, target: self, action: #selector(infoButtonPressed(_:))) self.navigationItem.rightBarButtonItem = item } @objc public override func infoButtonPressed(sender: AnyObject?) { var threadOwner: OTRThreadOwner? = nil var _account: OTRAccount? = nil self.readOnlyDatabaseConnection.readWithBlock { (t) in threadOwner = self.threadObjectWithTransaction(t) _account = self.accountWithTransaction(t) } guard let buddy = threadOwner as? OTRBuddy, account = _account else { return } let profileVC = ZomProfileViewController(nibName: nil, bundle: nil) let otrKit = OTRProtocolManager.sharedInstance().encryptionManager.otrKit profileVC.info = ZomProfileViewControllerInfo.createInfo(buddy, accountName: account.username, protocolString: account.protocolTypeString(), otrKit: otrKit, qrAction: profileVC.qrAction!, shareAction: profileVC.shareAction, hasSession: true) self.navigationController?.pushViewController(profileVC, animated: true) } } extension UIImage { func tint(color: UIColor, blendMode: CGBlendMode) -> UIImage { let drawRect = CGRectMake(0.0, 0.0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext() CGContextScaleCTM(context!, 1.0, -1.0) CGContextTranslateCTM(context!, 0.0, -self.size.height) CGContextClipToMask(context!, drawRect, CGImage!) color.setFill() UIRectFill(drawRect) drawInRect(drawRect, blendMode: blendMode, alpha: 1.0) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage! } }
mpl-2.0
e06fca5f94de92469cb1eb9a8d4c936b
49.426866
275
0.687681
5.57157
false
false
false
false
coodly/swlogger
Sources/SWLogger/Data+Extensions.swift
1
1122
/* * Copyright 2021 Coodly LLC * * 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 extension Data { internal func tail(lines: Int) -> Data { let newLine = "\n".data(using: .utf8)! var lineNo = 0 var pos = self.count - 1 repeat { // Find next newline character: guard let range = self.range(of: newLine, options: [ .backwards ], in: 0..<pos) else { return self } lineNo += 1 pos = range.lowerBound } while lineNo < lines return self.subdata(in: pos..<self.count) } }
apache-2.0
8e6e63310b3c5cd8fc9d32d9d7f13986
29.324324
98
0.636364
4.171004
false
false
false
false
JohnEstropia/CoreStore
Sources/Field.Virtual.swift
1
15239
// // Field.Virtual.swift // CoreStore // // Copyright © 2020 John Rommel Estropia // // 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 CoreData import Foundation // MARK: - FieldContainer extension FieldContainer { // MARK: - Virtual /** The containing type for computed property values. Because this value is not persisted to the backing store, any type is supported. `Field.Virtual` properties are not allowed to have initial values, including `nil` for optional types. ``` class Animal: CoreStoreObject { @Field.Virtual( "pluralName", customGetter: { (object, field) in return object.$species.value + "s" } ) var pluralName: String @Field.Stored("species") var species: String = "" } ``` - Important: `Field` properties are required to be used as `@propertyWrapper`s. Any other declaration not using the `@Field.Virtual(...) var` syntax will be ignored. */ @propertyWrapper public struct Virtual<V>: AttributeKeyPathStringConvertible, FieldAttributeProtocol { /** Initializes the metadata for the property. `Field.Virtual` properties are not allowed to have initial values, including `nil` for optional types. ``` class Person: CoreStoreObject { @Field.Virtual( "pluralName", customGetter: { (object, field) in return object.$species.value + "s" } ) var pluralName: String @Field.Stored("species") var species: String = "" } ``` - parameter keyPath: the permanent attribute name for this property. - parameter customGetter: use this closure as an "override" for the default property getter. The closure receives a `ObjectProxy<O>`, which acts as a type-safe proxy for the receiver. When accessing the property value from `ObjectProxy<O>`, make sure to use `field.primitiveValue` instead of `field.value`, which would unintentionally execute the same closure again recursively. Do not make assumptions on the thread/queue that the closure is executed on; accessors may be called from `NSError` logs for example. - parameter customSetter: use this closure as an "override" for the default property setter. The closure receives a `ObjectProxy<O>`, which acts as a fast, type-safe KVC interface for `CoreStoreObject`. The reason a `CoreStoreObject` instance is not passed directly is because the Core Data runtime is not aware of `CoreStoreObject` properties' static typing, and so loading those info everytime KVO invokes this accessor method incurs a cumulative performance hit (especially in KVO-heavy operations such as `ListMonitor` observing.) When accessing the property value from `ObjectProxy<O>`, make sure to use `field.primitiveValue` instead of `field.value`, which would unintentionally execute the same closure again recursively. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public init( _ keyPath: KeyPathString, customGetter: @escaping (_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>) -> V, customSetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>, _ newValue: V) -> Void)? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<KeyPathString> = []) { self.init( keyPath: keyPath, customGetter: customGetter, customSetter: customSetter, affectedByKeyPaths: affectedByKeyPaths ) } /** Overload for compiler error message only */ @available(*, unavailable, message: "Field.Virtual properties are not allowed to have initial values, including `nil`.") public init( wrappedValue initial: @autoclosure @escaping () -> V, _ keyPath: KeyPathString, versionHashModifier: @autoclosure @escaping () -> String? = nil, customGetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>) -> V)? = nil, customSetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>, _ newValue: V) -> Void)? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<KeyPathString> = []) { fatalError() } // MARK: @propertyWrapper @available(*, unavailable) public var wrappedValue: V { get { fatalError() } set { fatalError() } } public var projectedValue: Self { return self } public static subscript( _enclosingInstance instance: O, wrapped wrappedKeyPath: ReferenceWritableKeyPath<O, V>, storage storageKeyPath: ReferenceWritableKeyPath<O, Self> ) -> V { get { Internals.assert( instance.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) Internals.assert( instance.rawObject?.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) return self.read(field: instance[keyPath: storageKeyPath], for: instance.rawObject!) as! V } set { Internals.assert( instance.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) Internals.assert( instance.rawObject?.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) return self.modify(field: instance[keyPath: storageKeyPath], for: instance.rawObject!, newValue: newValue) } } // MARK: AnyKeyPathStringConvertible public var cs_keyPathString: String { return self.keyPath } // MARK: KeyPathStringConvertible public typealias ObjectType = O public typealias DestinationValueType = V // MARK: AttributeKeyPathStringConvertible public typealias ReturnValueType = DestinationValueType // MARK: PropertyProtocol internal let keyPath: KeyPathString // MARK: FieldProtocol internal static var dynamicObjectType: CoreStoreObject.Type { return ObjectType.self } internal static func read(field: FieldProtocol, for rawObject: CoreStoreManagedObject) -> Any? { let field = field as! Self if let customGetter = field.customGetter { return customGetter( ObjectProxy<O>(rawObject), ObjectProxy<O>.FieldProxy<V>(rawObject: rawObject, field: field) ) } let keyPath = field.keyPath switch rawObject.value(forKey: keyPath) { case let rawValue as V: return rawValue default: return nil } } internal static func modify(field: FieldProtocol, for rawObject: CoreStoreManagedObject, newValue: Any?) { Internals.assert( rawObject.isEditableInContext() == true, "Attempted to update a \(Internals.typeName(O.self))'s value from outside a transaction." ) let newValue = newValue as! V let field = field as! Self let keyPath = field.keyPath if let customSetter = field.customSetter { return customSetter( ObjectProxy<O>(rawObject), ObjectProxy<O>.FieldProxy<V>(rawObject: rawObject, field: field), newValue ) } return rawObject.setValue(newValue, forKey: keyPath) } // MARK: FieldAttributeProtocol internal let entityDescriptionValues: () -> FieldAttributeProtocol.EntityDescriptionValues internal var getter: CoreStoreManagedObject.CustomGetter? { guard let customGetter = self.customGetter else { return nil } let keyPath = self.keyPath return { (_ id: Any) -> Any? in let rawObject = id as! CoreStoreManagedObject rawObject.willAccessValue(forKey: keyPath) defer { rawObject.didAccessValue(forKey: keyPath) } return customGetter( ObjectProxy<O>(rawObject), ObjectProxy<O>.FieldProxy<V>(rawObject: rawObject, field: self) ) } } internal var setter: CoreStoreManagedObject.CustomSetter? { guard let customSetter = self.customSetter else { return nil } let keyPath = self.keyPath return { (_ id: Any, _ newValue: Any?) -> Void in let rawObject = id as! CoreStoreManagedObject rawObject.willChangeValue(forKey: keyPath) defer { rawObject.didChangeValue(forKey: keyPath) } return customSetter( ObjectProxy<O>(rawObject), ObjectProxy<O>.FieldProxy<V>(rawObject: rawObject, field: self), newValue as! V ) } } let initializer: CoreStoreManagedObject.CustomInitializer? = nil // MARK: FilePrivate fileprivate init( keyPath: KeyPathString, customGetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>) -> V)?, customSetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>, _ newValue: V) -> Void)? , affectedByKeyPaths: @escaping () -> Set<KeyPathString>) { self.keyPath = keyPath self.entityDescriptionValues = { ( attributeType: .undefinedAttributeType, isOptional: true, isTransient: true, allowsExternalBinaryDataStorage: false, versionHashModifier: nil, renamingIdentifier: nil, valueTransformer: nil, affectedByKeyPaths: affectedByKeyPaths(), defaultValue: nil ) } self.customGetter = customGetter self.customSetter = customSetter } // MARK: Private private let customGetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>) -> V)? private let customSetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>, _ newValue: V) -> Void)? } } // MARK: - FieldContainer.Virtual where V: FieldOptionalType extension FieldContainer.Virtual where V: FieldOptionalType { /** Initializes the metadata for the property. `Field.Virtual` properties are not allowed to have initial values, including `nil` for optional types. ``` class Person: CoreStoreObject { @Field.Virtual( "pluralName", customGetter: { (object, field) in return object.$species.value + "s" } ) var pluralName: String? @Field.Stored("species") var species: String = "" } ``` - parameter keyPath: the permanent attribute name for this property. - parameter customGetter: use this closure as an "override" for the default property getter. The closure receives a `ObjectProxy<O>`, which acts as a type-safe proxy for the receiver. When accessing the property value from `ObjectProxy<O>`, make sure to use `field.primitiveValue` instead of `field.value`, which would unintentionally execute the same closure again recursively. Do not make assumptions on the thread/queue that the closure is executed on; accessors may be called from `NSError` logs for example. - parameter customSetter: use this closure as an "override" for the default property setter. The closure receives a `ObjectProxy<O>`, which acts as a fast, type-safe KVC interface for `CoreStoreObject`. The reason a `CoreStoreObject` instance is not passed directly is because the Core Data runtime is not aware of `CoreStoreObject` properties' static typing, and so loading those info everytime KVO invokes this accessor method incurs a cumulative performance hit (especially in KVO-heavy operations such as `ListMonitor` observing.) When accessing the property value from `ObjectProxy<O>`, make sure to use `field.primitiveValue` instead of `field.value`, which would unintentionally execute the same closure again recursively. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public init( _ keyPath: KeyPathString, customGetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>) -> V)? = nil, customSetter: ((_ object: ObjectProxy<O>, _ field: ObjectProxy<O>.FieldProxy<V>, _ newValue: V) -> Void)? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<KeyPathString> = []) { self.init( keyPath: keyPath, customGetter: customGetter, customSetter: customSetter, affectedByKeyPaths: affectedByKeyPaths ) } }
mit
a40417e5dde7488c74b60e7c406c8635
41.803371
738
0.617207
5.188287
false
false
false
false
rectinajh/leetCode_Swift
RotateImage/RotateImage.swift
1
2239
// // RotateImage.swift // RotateImage // // Created by hua on 16/9/2. // Copyright © 2016年 212. All rights reserved. // import Foundation /** 原题: 翻译: 思路: 程序: 扩展: * Question Link: https://leetcode.com/problems/rotate-image/ Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place? 旋转图像  您将得到一个n×n的2D矩阵表示图像。  通过90度(顺时针方向)旋转的图像。 其实题目更好理解为旋转一个矩阵的下标90°。实际问题实际分析,这里不用图形学的选择矩阵的计算方法了。 关键是要把下标计算好,原矩阵的数值应该对应到新的旋转矩阵的那个位置,设计好公式就很容易计算了。 有图好理解,矩阵如下图: 有两个思路: 1 原矩阵计算出各个数值在新矩阵中的位置,然后一步到位转换成新的旋转矩阵 2 原矩阵到转置矩阵是很容易计算的,那么从转置矩阵到选择矩阵就只需要reverse每行的元素就可。 * Primary idea: Go from clockwise and from outside to inside, use offset for convenience * * Time Complexity: O(n^2), Space Complexity: O(1) */ class RotateImage { static func rotate(inout matrix: [[Int]]) { let n = matrix.count guard n > 0 else { return } var start = 0 var end = 0 var offset = 0 var temp = 0 for layer in 0 ..< n / 2 { start = layer end = n - 1 - layer for i in start ..< end { offset = i - start temp = matrix[start][i] // left -> top matrix[start][i] = matrix[end - offset][start] // bottom -> left matrix[end - offset][start] = matrix[end][end - offset] // right -> bottom matrix[end][end - offset] = matrix[i][end] // top -> right matrix[i][end] = temp } } } }
mit
60fb90967e60622b34de806e78650e41
21.602564
89
0.527809
3.113074
false
false
false
false
shyamalschandra/Design-Patterns-In-Swift
source/structural/_title.swift
13
383
//: [Behavioral](Behavioral) | //: [Creational](Creational) | //: Structural /*: Structural ========== >In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities. > >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Structural_pattern) */ import Swift import Foundation
gpl-3.0
113901c2ea55bb4ec202512ff24a5b18
28.461538
164
0.738903
4.074468
false
false
false
false
kdawgwilk/vapor
Sources/Vapor/Router/BranchRouter.swift
1
2373
public typealias Host = String public final class BranchRouter: Router { // MARK: Private Tree Representation private final var tree: [Host: [Method: Branch]] = [:] // MARK: Routing public final func route(_ request: Request) -> Responder? { let path = request.uri.path ?? "" let host = request.uri.host ?? "" //get root from hostname, or * route let root = tree[host] ?? tree["*"] //ensure branch for current method exists guard let branch = root?[request.method] else { return nil } //search branch with query path generator let generator = path.pathComponentGenerator() return branch.handle(request: request, comps: generator) } // MARK: Registration public final func register(_ route: Route) { let generator = route.path.pathComponentGenerator() //get the current root for the host, or create one if none let host = route.hostname var base = self.tree[host] ?? [:] //look for a branch for the method, or create one if none let method = route.method let branch = base[method] ?? Branch(name: "") //extend the branch branch.extendBranch(generator, handler: route.responder) //assign the branch and root to the tree base[method] = branch self.tree[host] = base } } /** Until Swift api is stable for AnyGenerator, using this in interim to allow compiling Swift 2 and 2.2+ */ public struct CompatibilityGenerator<T>: IteratorProtocol { public typealias Element = T private let closure: () -> T? init(closure: () -> T?) { self.closure = closure } public func next() -> Element? { return closure() } } extension String { private func pathComponentGenerator() -> CompatibilityGenerator<String> { let components = self.characters.split { character in //split on slashes return character == "/" }.map { item in //convert to string array return String(item) } var idx = 0 return CompatibilityGenerator<String> { guard idx < components.count else { return nil } let next = components[idx] idx += 1 return next } } }
mit
9a731fa2ab7eda5757f624994d4d217a
26.275862
105
0.587442
4.717694
false
false
false
false
niekang/WeiBo
WeiBo/Class/View/WBNavigationController.swift
1
1284
// // WBNavigationController.swift // WeiBo // // Created by 聂康 on 2017/6/19. // Copyright © 2017年 com.nk. All rights reserved. // import UIKit class WBNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() /// 导航栏设置 setupNavigationBarAppearance() } func setupNavigationBarAppearance() { navigationBar.barTintColor = UIColor.hexColor(hex: 0xF6F6F6) } /// 重载push函数 添加统一‘返回’按钮 override func pushViewController(_ viewController: UIViewController, animated: Bool) { if children.count > 0 { viewController.hidesBottomBarWhenPushed = true let fixItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: self, action: #selector(backAction)) fixItem.width = -10 let leftItem = UIBarButtonItem(title: "返回", target: self, action: #selector(backAction)) viewController.navigationItem.leftBarButtonItems = [fixItem, leftItem] } super.pushViewController(viewController, animated: animated) } /// 返回按钮事件 @objc func backAction() { popViewController(animated: true) } }
apache-2.0
cc30684234958be2959259ad52d22bcc
26.177778
120
0.641864
4.777344
false
false
false
false
chrislzm/TimeAnalytics
Time Analytics/TATableViewController.swift
1
10293
// // TATableViewController.swift // Time Analytics // // Heavily modified version of CoreDataViewControler originally created by Fernando Rodríguez Romero on 2/22/16 // Implements a tableView linked with a Core Data fetched results controller. // // Abstract class. Has three concrete subclasses: TAPlaceTableViewController, TACommuteTableViewController, TAActivityTableViewController // // Copyright © 2017 Chris Leung. All rights reserved. // import UIKit import CoreData // MARK: - CoreDataTableViewController: UITableViewController class TATableViewController: TAViewController, UITableViewDelegate, UITableViewDataSource { // MARK: Properties let activityIndicatoryXY = 0 let activityIndicatorPixelSize = 20 let activityIndicatorStyle = UIActivityIndicatorViewStyle.gray let tableSectionHeaderHeight = CGFloat(30) let tableSectionFontSize = CGFloat(13) let tableSectionFontWeight = UIFontWeightBold let tableSectionFontColor = UIColor.black let tableSectionBackgroundColor = UIColor.groupTableViewBackground let tabBarImageInsets = UIEdgeInsetsMake(6, 0, -6, 0) var tableView:UITableView! = nil var activityIndicatorView:UIActivityIndicatorView! // Shown in navbar when updating data in the background var fetchedResultsController : NSFetchedResultsController<NSFetchRequestResult>? { didSet { // Whenever the frc changes, we execute the search and // reload the table fetchedResultsController?.delegate = self executeSearch() tableView.reloadData() } } // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() // Setup table style tableView.separatorStyle = .none // Remove titles from Tabbar for tabBarItem in (tabBarController?.tabBar.items)! { tabBarItem.title = "" tabBarItem.imageInsets = tabBarImageInsets } // Setup activity view in navigation bar activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: activityIndicatorStyle) activityIndicatorView.frame = CGRect(x: activityIndicatoryXY, y: activityIndicatoryXY, width: activityIndicatorPixelSize, height: activityIndicatorPixelSize) let activityIndicatorBarButtonItem = UIBarButtonItem(customView: activityIndicatorView) navigationItem.setLeftBarButton(activityIndicatorBarButtonItem, animated: false) // Observe notifications so we can animate activityView when downloading/processing NotificationCenter.default.addObserver(self, selector: #selector(TATableViewController.willDownloadData(_:)), name: Notification.Name("willDownloadMovesData"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(TATableViewController.didCompleteUpdate(_:)), name: Notification.Name("didCompleteAllUpdates"), object: nil) } // MARK: View Methods func showSettingsMenu() { let controller = storyboard?.instantiateViewController(withIdentifier: "TASettingsView") as! TASettingsViewController navigationController?.pushViewController(controller, animated: true) } func startActivityIndicator() { DispatchQueue.main.async { self.activityIndicatorView.startAnimating() } } func stopActivityIndicator() { DispatchQueue.main.async { self.activityIndicatorView.stopAnimating() } } // MARK: Notification Observers func willDownloadData(_ notification:Notification) { startActivityIndicator() } func didCompleteUpdate(_ notification:Notification) { stopActivityIndicator() } // Error handling -- Fail gracefully by stopping the activity indicator. We don't need to let the user know here, since this error is most likely from a background auto-update that will attempt again after a short time. If the user initiates a refresh manually in the settings panel, it will display an alert to notify the user of any errors. override func downloadMovesDataError(_ notification:Notification) { super.downloadMovesDataError(notification) handleError() } override func movesDataParsingError(_ notification:Notification) { super.movesDataParsingError(notification) handleError() } override func healthDataReadError(_ notification:Notification) { super.healthDataReadError(notification) handleError() } func handleError() { stopActivityIndicator() } } // MARK: - CoreDataTableViewController (Subclass Must Implement) extension TATableViewController { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { fatalError("This method MUST be implemented by a subclass of CoreDataTableViewController") } } // MARK: - CoreDataTableViewController (Table Data Source) extension TATableViewController { func numberOfSections(in tableView: UITableView) -> Int { if let fc = fetchedResultsController { return (fc.sections?.count)! } return 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let fc = fetchedResultsController { return fc.sections![section].numberOfObjects } return 0 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var sectionTitle: String? if let sectionIdentifier = fetchedResultsController!.sections?[section].name { if let numericSection = Int(sectionIdentifier) { // Parse the numericSection into its year/month/day components. let year = numericSection / 10000 let month = (numericSection / 100) % 100 let day = numericSection % 100 // Reconstruct the date from these components. var components = DateComponents() components.calendar = Calendar.current components.day = day components.month = month components.year = year let today = Date() let calendar = Calendar.current let todayDay = calendar.component(.day, from: today) let todayMonth = calendar.component(.month, from: today) let todayYear = calendar.component(.year, from: today) // Set the section title with this date if let date = components.date { sectionTitle = DateFormatter.localizedString(from: date, dateStyle: .full, timeStyle: .none) if month==todayMonth,year==todayYear { if day==todayDay { sectionTitle = "Today - \(sectionTitle!)" } else if day == todayDay-1 { sectionTitle = "Yesterday - \(sectionTitle!)" } } } } } return sectionTitle } func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { if let fc = fetchedResultsController { return fc.section(forSectionIndexTitle: title, at: index) } return 0 } func sectionIndexTitles(for tableView: UITableView) -> [String]? { return nil } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { view.tintColor = tableSectionBackgroundColor let header = view as! UITableViewHeaderFooterView header.textLabel?.textColor = tableSectionFontColor header.textLabel?.font = UIFont.systemFont(ofSize: tableSectionFontSize, weight: tableSectionFontWeight) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return tableSectionHeaderHeight } } // MARK: - CoreDataTableViewController (Fetches) extension TATableViewController { func executeSearch() { if let fc = fetchedResultsController { do { try fc.performFetch() } catch let e as NSError { fatalError(("Error while trying to perform a search: \n\(e)\n\(String(describing: fetchedResultsController))")) } } } } // MARK: - CoreDataTableViewController: NSFetchedResultsControllerDelegate extension TATableViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { let set = IndexSet(integer: sectionIndex) switch (type) { case .insert: tableView.insertSections(set, with: .fade) case .delete: tableView.deleteSections(set, with: .fade) default: // irrelevant in our case break } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch(type) { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: tableView.reloadRows(at: [indexPath!], with: .fade) case .move: tableView.deleteRows(at: [indexPath!], with: .fade) tableView.insertRows(at: [newIndexPath!], with: .fade) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } }
mit
17d6d9a4ca42bdabb4a1ae870fb187a1
37.543071
346
0.657468
5.867161
false
false
false
false
BGDigital/mcwa
mcwa/mcwa/rankinglistCell.swift
1
1421
// // rankinglistCell.swift // mcwa // // Created by XingfuQiu on 15/10/21. // Copyright © 2015年 XingfuQiu. All rights reserved. // import UIKit class rankinglistCell: UITableViewCell { @IBOutlet weak var iv_left_bg: UIImageView! @IBOutlet weak var iv_Avatar: UIImageView! @IBOutlet weak var lb_userName: UILabel! @IBOutlet weak var lb_source: UILabel! @IBOutlet weak var lb_No: UILabel! override func awakeFromNib() { super.awakeFromNib() self.iv_Avatar.layer.masksToBounds = true self.iv_Avatar.layer.cornerRadius = 20 // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) selectionStyle = .None // Configure the view for the selected state } func update(json: JSON) { // println(json) let avatar_url = json["headImg"].stringValue self.iv_Avatar.yy_imageURL = NSURL(string: avatar_url) self.lb_userName.text = json["nickName"].stringValue self.lb_source.text = json["allScore"].stringValue+"分" self.lb_No.text = json["scoreRank"].stringValue if lb_No.text == "1" { self.iv_left_bg.backgroundColor = UIColor(hexString: "#5BB524") } else { self.iv_left_bg.backgroundColor = UIColor(hexString: "#8581C7") } } }
mit
07d7a67e6a7ad0f9dd524669e27d7d38
29.12766
75
0.629237
3.933333
false
false
false
false
Zewo/HTTP
Sources/HTTP/Message/Message.swift
5
1954
public protocol Message { var version: Version { get set } var headers: Headers { get set } var body: Body { get set } var storage: [String: Any] { get set } } extension Message { public var contentType: MediaType? { get { return headers["Content-Type"].flatMap({try? MediaType(string: $0)}) } set(contentType) { headers["Content-Type"] = contentType?.description } } public var contentLength: Int? { get { return headers["Content-Length"].flatMap({Int($0)}) } set(contentLength) { headers["Content-Length"] = contentLength?.description } } public var transferEncoding: String? { get { return headers["Transfer-Encoding"] } set(transferEncoding) { headers["Transfer-Encoding"] = transferEncoding } } public var isChunkEncoded: Bool { return transferEncoding == "chunked" } public var connection: String? { get { return headers["Connection"] } set(connection) { headers["Connection"] = connection } } public var isKeepAlive: Bool { if version.minor == 0 { return connection?.lowercased() == "keep-alive" } return connection?.lowercased() != "close" } public var isUpgrade: Bool { return connection?.lowercased() == "upgrade" } public var upgrade: String? { get { return headers["Upgrade"] } set(upgrade) { headers["Upgrade"] = upgrade } } } extension Message { public var storageDescription: String { var string = "Storage:\n" if storage.isEmpty { string += "-" } for (key, value) in storage { string += "\(key): \(value)\n" } return string } }
mit
7c4ffe0f4fba41255e8cec6c63786dd9
20.711111
80
0.524565
4.754258
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Cells/Directory/DirectoryUserCell.swift
1
1534
// // DirectoryUserCell.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 14/03/19. // Copyright © 2019 Rocket.Chat. All rights reserved. // import UIKit final class DirectoryUserCell: UITableViewCell { static let identifier = String(describing: DirectoryUserCell.self) var user: UnmanagedUser? { didSet { if user != nil { updateUserInformation() } } } @IBOutlet weak var imageViewAvatar: UIImageView! @IBOutlet weak var labelName: UILabel! @IBOutlet weak var labelUsername: UILabel! @IBOutlet weak var labelServer: UILabel! override func prepareForReuse() { super.prepareForReuse() user = nil imageViewAvatar.image = nil labelName.text = nil labelUsername.text = nil labelServer.text = nil } // MARK: Data Management func updateUserInformation() { if let avatarURL = user?.avatarURL { ImageManager.loadImage(with: avatarURL, into: imageViewAvatar) { _, _ in } } labelName.text = user?.name labelUsername.text = user?.username labelServer.text = user?.federatedServerName } } // MARK: Themeable extension DirectoryUserCell { override func applyTheme() { super.applyTheme() guard let theme = theme else { return } labelName.textColor = theme.bodyText labelUsername.textColor = theme.auxiliaryText labelServer.textColor = theme.auxiliaryText } }
mit
abe3eafe0687686786342c274004abfb
22.227273
86
0.634703
4.702454
false
false
false
false
chromium/chromium
ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_destination_list.swift
6
8381
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import SwiftUI /// A view displaying a list of destinations. @available(iOS 15, *) struct OverflowMenuDestinationList: View { enum Constants { /// Padding breakpoints for each width. The ranges should be inclusive of /// the larger number. That is, a width of 320 should fall in the /// `(230, 320]` bucket. static let widthBreakpoints: [CGFloat] = [ 180, 230, 320, 400, 470, 560, 650, ] /// Array of the lower end of each breakpoint range. static let lowerWidthBreakpoints = [nil] + widthBreakpoints /// Array of the higher end of each breakpoint range. static let upperWidthBreakpoints = widthBreakpoints + [nil] /// Leading space on the first icon. static let iconInitialSpace: CGFloat = 16 /// Range of spacing around icons; varies based on view width. static let iconSpacingRange: ClosedRange<CGFloat> = 9...13 /// Range of icon paddings; varies based on view width. static let iconPaddingRange: ClosedRange<CGFloat> = 0...3 /// When the dynamic text size is large, the width of each item is the /// screen width minus a fixed space. static let largeTextSizeSpace: CGFloat = 120 /// Space above the list pushing them down from the grabber. static let topMargin: CGFloat = 20 /// The name for the coordinate space of the scroll view, so children can /// find their positioning in the scroll view. static let coordinateSpaceName = "destinations" } /// `PreferenceKey` to track the leading offset of the scroll view. struct ScrollViewLeadingOffset: PreferenceKey { static var defaultValue: CGFloat = .greatestFiniteMagnitude static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = min(value, nextValue()) } } /// The current dynamic type size. @Environment(\.sizeCategory) var sizeCategory /// The current environment layout direction. @Environment(\.layoutDirection) var layoutDirection: LayoutDirection /// The destinations for this view. var destinations: [OverflowMenuDestination] weak var metricsHandler: PopupMenuMetricsHandler? @ObservedObject var uiConfiguration: OverflowMenuUIConfiguration /// Tracks the list's current offset, to see when it scrolls. When the offset /// is `nil`, scroll tracking is not set up yet. This is necessary because /// in RTL languages, the scroll view has to manually scroll to the right edge /// of the list first. @State var listOffset: CGFloat? = nil var body: some View { VStack { Spacer(minLength: Constants.topMargin) GeometryReader { geometry in scrollView(in: geometry) .coordinateSpace(name: Constants.coordinateSpaceName) .accessibilityIdentifier(kPopupMenuToolsMenuTableViewId) } } .animation(nil) .background( Color("destination_highlight_color").opacity(uiConfiguration.highlightDestinationsRow ? 1 : 0) ) .animation(.linear(duration: kMaterialDuration3)) .onPreferenceChange(ScrollViewLeadingOffset.self) { newOffset in // Only alert the handler if scroll tracking has started. if let listOffset = listOffset, newOffset != listOffset { metricsHandler?.popupMenuScrolledHorizontally() } // Only update the offset if scroll tracking has started or the newOffset // is approximately 0 (this starts scroll tracking). In RTL mode, the // offset is not exactly 0, so a strict comparison won't work. if listOffset != nil || (listOffset == nil && abs(newOffset) < 1e-9) { listOffset = newOffset } } } @ViewBuilder private func scrollView(in geometry: GeometryProxy) -> some View { ScrollViewReader { proxy in ScrollView(.horizontal, showsIndicators: false) { let spacing = destinationSpacing(forScreenWidth: geometry.size.width) let layoutParameters: OverflowMenuDestinationView.LayoutParameters = sizeCategory >= .accessibilityMedium ? .horizontal(itemWidth: geometry.size.width - Constants.largeTextSizeSpace) : .vertical( iconSpacing: spacing.iconSpacing, iconPadding: spacing.iconPadding) let alignment: VerticalAlignment = sizeCategory >= .accessibilityMedium ? .center : .top ZStack { HStack(alignment: alignment, spacing: 0) { // Make sure the space to the first icon is constant, so add extra // spacing before the first item. Spacer().frame(width: Constants.iconInitialSpace - spacing.iconSpacing) ForEach(destinations) { destination in OverflowMenuDestinationView( destination: destination, layoutParameters: layoutParameters, metricsHandler: metricsHandler ).id(destination.destinationName) } } GeometryReader { innerGeometry in let frame = innerGeometry.frame(in: .named(Constants.coordinateSpaceName)) let parentWidth = geometry.size.width // When the view is RTL, the offset should be calculated from the // right edge. let offset = layoutDirection == .leftToRight ? frame.minX : parentWidth - frame.maxX Color.clear .preference(key: ScrollViewLeadingOffset.self, value: offset) } } } .onAppear { if layoutDirection == .rightToLeft { proxy.scrollTo(destinations.first?.destinationName) } uiConfiguration.destinationListScreenFrame = geometry.frame(in: .global) } } } /// Finds the lower and upper breakpoint above and below `width`. /// /// Returns `nil` for either end if `width` is above or below the largest or /// smallest breakpoint. private func findBreakpoints(forScreenWidth width: CGFloat) -> (CGFloat?, CGFloat?) { // Add extra sentinel values to either end of the breakpoint array. let x = zip( Constants.lowerWidthBreakpoints, Constants.upperWidthBreakpoints ) // There should only be one item where the provided width is both greater // than the lower end and less than the upper end. .filter { (low, high) in // Check if width is above the low value, or default to true if low is // nil. let aboveLow = low.map { value in width > value } ?? true let belowHigh = high.map { value in width <= value } ?? true return aboveLow && belowHigh }.first return x ?? (nil, nil) } /// Calculates the icon spacing and padding for the given `width`. private func destinationSpacing(forScreenWidth width: CGFloat) -> ( iconSpacing: CGFloat, iconPadding: CGFloat ) { let (lowerBreakpoint, upperBreakpoint) = findBreakpoints( forScreenWidth: width) // If there's no lower breakpoint, `width` is lower than the lowest, so // default to the lower bound of the ranges. guard let lowerBreakpoint = lowerBreakpoint else { return ( iconSpacing: Constants.iconSpacingRange.lowerBound, iconPadding: Constants.iconPaddingRange.lowerBound ) } // If there's no upper breakpoint, `width` is higher than the highest, so // default to the higher bound of the ranges. guard let upperBreakpoint = upperBreakpoint else { return ( iconSpacing: Constants.iconSpacingRange.upperBound, iconPadding: Constants.iconPaddingRange.upperBound ) } let breakpointRange = lowerBreakpoint...upperBreakpoint let iconSpacing = mapNumber( width, from: breakpointRange, to: Constants.iconSpacingRange) let iconPadding = mapNumber( width, from: breakpointRange, to: Constants.iconPaddingRange) return (iconSpacing: iconSpacing, iconPadding: iconPadding) } /// Maps the given `number` from its relative position in `inRange` to its /// relative position in `outRange`. private func mapNumber<F: FloatingPoint>( _ number: F, from inRange: ClosedRange<F>, to outRange: ClosedRange<F> ) -> F { let scalingFactor = (outRange.upperBound - outRange.lowerBound) / (inRange.upperBound - inRange.lowerBound) return (number - inRange.lowerBound) * scalingFactor + outRange.lowerBound } }
bsd-3-clause
fcb6e75f5884b7b204ba27385bec4118
37.800926
100
0.680468
4.716376
false
false
false
false
mapsme/omim
iphone/Maps/Core/Subscriptions/SubscriptionGroup.swift
4
2907
@objc enum SubscriptionGroupType: Int { case allPass case city init?(serverId: String) { switch serverId { case MWMPurchaseManager.bookmarksSubscriptionServerId(): self = .city case MWMPurchaseManager.allPassSubscriptionServerId(): self = .allPass default: return nil } } init(catalogURL: URL) { guard let urlComponents = URLComponents(url: catalogURL, resolvingAgainstBaseURL: false) else { self = .allPass return } let subscriptionGroups = urlComponents.queryItems? .filter { $0.name == "groups" } .map { $0.value ?? "" } if subscriptionGroups?.first(where: { $0 == MWMPurchaseManager.allPassSubscriptionServerId() }) != nil { self = .allPass } else if subscriptionGroups?.first(where: { $0 == MWMPurchaseManager.bookmarksSubscriptionServerId() }) != nil { self = .city } else { self = .allPass } } var serverId: String { switch self { case .city: return MWMPurchaseManager.bookmarksSubscriptionServerId() case .allPass: return MWMPurchaseManager.allPassSubscriptionServerId() } } } protocol ISubscriptionGroup { var count: Int { get } subscript(period: SubscriptionPeriod) -> ISubscriptionGroupItem? { get } } class SubscriptionGroup: ISubscriptionGroup { private var subscriptions: [ISubscriptionGroupItem] var count: Int { return subscriptions.count } init(subscriptions: [ISubscription]) { let formatter = NumberFormatter() formatter.locale = subscriptions.first?.priceLocale formatter.numberStyle = .currency let weekCycle = NSDecimalNumber(value: 7.0) let mounthCycle = NSDecimalNumber(value: 30.0) let yearCycle = NSDecimalNumber(value: 12.0 * 30.0) var rates: [NSDecimalNumber] = [] var maxPriceRate: NSDecimalNumber = NSDecimalNumber.minimum maxPriceRate = subscriptions.reduce(into: maxPriceRate) { result, item in let price = item.price var rate: NSDecimalNumber = NSDecimalNumber() switch item.period { case .year: rate = price.dividing(by: yearCycle) case .month: rate = price.dividing(by: mounthCycle) case .week: rate = price.dividing(by: weekCycle) case .unknown: rate = price } result = rate.compare(result) == .orderedDescending ? rate : result rates.append(rate) } self.subscriptions = [] for (idx, subscription) in subscriptions.enumerated() { let rate = rates[idx] let discount = NSDecimalNumber(value: 1).subtracting(rate.dividing(by: maxPriceRate)).multiplying(by: 100) self.subscriptions.append(SubscriptionGroupItem(subscription, discount: discount, formatter: formatter)) } } subscript(period: SubscriptionPeriod) -> ISubscriptionGroupItem? { return subscriptions.first { (item) -> Bool in item.period == period } } }
apache-2.0
e4fccd701342bc7dee265d33888f441d
29.28125
117
0.674235
4.472308
false
false
false
false
Urinx/Device-9
Device 9/Device 9/MainViewController.swift
1
5343
// // ViewController.swift // Device 9 // // Created by Eular on 9/17/15. // Copyright © 2015 Eular. All rights reserved. // import UIKit import WatchConnectivity import Device9Kit class MainViewController: UIViewController { @IBOutlet weak var chart: Chart! @IBOutlet weak var shareFBtn: UIButton! @IBOutlet weak var shareCBtn: UIButton! @IBOutlet weak var dataLB: UILabel! let defaults = NSUserDefaults(suiteName: UserDefaultSuiteName)! let device9 = Device9() var totalStr = "" override func viewDidLoad() { super.viewDidLoad() // chart let series1 = ChartSeries(random(10, 60, arrLen: 7)) series1.color = ChartColors.cyanColor() series1.area = true let series2 = ChartSeries(random(1, 10, arrLen: 7)) series2.color = ChartColors.redColor() series2.area = true chart.addSeries([series1, series2]) shareFBtn.layer.borderColor = UIColor.whiteColor().CGColor shareFBtn.layer.borderWidth = 1.0 shareFBtn.addTarget(self, action: "shareF", forControlEvents: .TouchUpInside) shareCBtn.layer.borderColor = UIColor.whiteColor().CGColor shareCBtn.layer.borderWidth = 1.0 shareCBtn.addTarget(self, action: "shareC", forControlEvents: .TouchUpInside) NSNotificationCenter.defaultCenter().addObserver(self, selector:"shortcutItem1:", name: ShareFriendNotif, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"shortcutItem2:", name: ShareTimelineNotif, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"shortcutItem3:", name: SettingNotif, object: nil) } override func viewDidAppear(animated: Bool) { // show helper // why not put this in viewDidLoad? Because the HelpViewController can't be instanted in viewDidLoad if !defaults.boolForKey("firstBlood") { if let helpVC = storyboard?.instantiateViewControllerWithIdentifier("HelpViewController") as? HelpViewController { self.presentViewController(helpVC, animated: true, completion: nil) } defaults.setBool(true, forKey: "firstBlood") defaults.synchronize() // set initial data device9.dataFlow.cellularUsed = device9.dataFlow.upGPRS + device9.dataFlow.downGPRS device9.dataFlow.wifiUsed = device9.dataFlow.upWiFi + device9.dataFlow.downWiFi } updateUI() } func updateUI() { let cellularUsed = defaults.doubleForKey("CellularUsed") let wifiUsed = defaults.doubleForKey("WiFiUsed") let total = cellularUsed + wifiUsed if total.GB > 1 { totalStr = "\(total.GB.afterPoint(1)) GB" } else { totalStr = "\(Int(total.MB)) MB" } dataLB.text = totalStr // send data to apple watch do { let cellularLeft = defaults.doubleForKey("CellularTotal") - cellularUsed try WCSession.defaultSession().updateApplicationContext(["msg": "data", "cellularUsed": "\(cellularUsed.MB.afterPoint(1)) MB", "cellularLeft": "\(cellularLeft.MB.afterPoint(1)) MB", "wifiUsed": wifiUsed.GB > 1 ? "\(wifiUsed.GB.afterPoint(1)) GB":"\(Int(wifiUsed.MB)) MB"]) } catch {} } func random(a: UInt32, _ b: UInt32) -> Float? { guard a < b else { return nil } return Float(arc4random_uniform(b - a) + a) } func random(a: UInt32, _ b: UInt32, arrLen: Int) -> Array<Float> { guard a < b else { return [] } var arr = [Float]() for _ in 0..<arrLen { arr.append(random(a, b)!) } return arr } // btn event func shareF() { weixinShare(WXSceneSession) } func shareC() { weixinShare(WXSceneTimeline) } func weixinShare(scene: WXScene) { if WXApi.isWXAppInstalled() { let message = WXMediaMessage() message.title = "今生我消耗了\(totalStr)的流量,不服來戰!" message.description = WXShareDescription message.setThumbImage(UIImage(named: "d9")) let ext = WXWebpageObject() ext.webpageUrl = AppDownload message.mediaObject = ext let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = Int32(scene.rawValue) WXApi.sendReq(req) } else { let alert = UIAlertController(title: "Share Fail", message: "Wechat app is not installed!", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } } // short cut func shortcutItem1(notification: NSNotification) { weixinShare(WXSceneSession) } func shortcutItem2(notification: NSNotification) { weixinShare(WXSceneTimeline) } func shortcutItem3(notification: NSNotification) { self.performSegueWithIdentifier("settingSegue", sender: self) } override func prefersStatusBarHidden() -> Bool { return true } }
apache-2.0
e2cc562da774d07ab28c237516c962e2
35.136054
284
0.618411
4.386457
false
false
false
false
Higgcz/Buildasaur
BuildaGitServer/Repo.swift
8
890
// // Repo.swift // Buildasaur // // Created by Honza Dvorsky on 13/12/2014. // Copyright (c) 2014 Honza Dvorsky. All rights reserved. // import Foundation public class Repo : GitHubEntity { public let name: String public let fullName: String public let repoUrlHTTPS: String public let repoUrlSSH: String public let permissions: NSDictionary public required init(json: NSDictionary) { self.name = json.stringForKey("name") self.fullName = json.stringForKey("full_name") self.repoUrlHTTPS = json.stringForKey("clone_url") self.repoUrlSSH = json.stringForKey("ssh_url") if let permissions = json.optionalDictionaryForKey("permissions") { self.permissions = permissions } else { self.permissions = NSDictionary() } super.init(json: json) } }
mit
fd42970081bceb0eecfe766a0a981c7b
25.176471
75
0.634831
4.45
false
false
false
false
1aurabrown/eidolon
Kiosk/Bid Fulfillment/Models/RegistrationCoordinator.swift
1
2505
import UIKit enum RegistrationIndex { case MobileVC case EmailVC case PasswordVC case CreditCardVC case ZipCodeVC case ConfirmVC func toInt() -> Int { switch (self) { case MobileVC: return 0 case EmailVC: return 1 case PasswordVC: return 1 case CreditCardVC: return 2 case ZipCodeVC: return 3 case ConfirmVC: return 4 } } static func fromInt(index:Int) -> RegistrationIndex { switch (index) { case 0: return .MobileVC case 1: return .EmailVC case 1: return .PasswordVC case 2: return .CreditCardVC case 3: return .ZipCodeVC default : return .ConfirmVC } } } class RegistrationCoordinator: NSObject { dynamic var currentIndex: Int = 0 var storyboard:UIStoryboard! func viewControllerForIndex(index: RegistrationIndex) -> UIViewController { currentIndex = index.toInt() switch index { case .MobileVC: return storyboard.viewControllerWithID(.RegisterMobile) case .EmailVC: return storyboard.viewControllerWithID(.RegisterEmail) case .PasswordVC: return storyboard.viewControllerWithID(.RegisterPassword) case .CreditCardVC: return storyboard.viewControllerWithID(.RegisterCreditCard) case .ZipCodeVC: return storyboard.viewControllerWithID(.RegisterPostalorZip) case .ConfirmVC: return storyboard.viewControllerWithID(.RegisterConfirm) } } func nextViewControllerForBidDetails(details: BidDetails) -> UIViewController { if notSet(details.newUser.phoneNumber) { return viewControllerForIndex(.MobileVC) } if notSet(details.newUser.email) { return viewControllerForIndex(.EmailVC) } if notSet(details.newUser.password) { return viewControllerForIndex(.PasswordVC) } if notSet(details.newUser.creditCardToken) { return viewControllerForIndex(.CreditCardVC) } if notSet(details.newUser.zipCode) { return viewControllerForIndex(.ZipCodeVC) } return viewControllerForIndex(.ConfirmVC) } } private func notSet(string:String?) -> Bool { if let realString = string { return (countElements(realString as String) == 0) } return true }
mit
b5c126655756ce0b72cfc17c71043f83
25.648936
83
0.61996
5.081136
false
false
false
false
kusl/swift
stdlib/private/StdlibUnittest/StdlibCoreExtras.swift
10
4890
//===--- StdlibCoreExtras.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftPrivate import SwiftPrivateDarwinExtras #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif #if _runtime(_ObjC) import Foundation #endif // // These APIs don't really belong in a unit testing library, but they are // useful in tests, and stdlib does not have such facilities yet. // func findSubstring(string: String, _ substring: String) -> String.Index? { if substring.isEmpty { return string.startIndex } #if _runtime(_ObjC) return string.rangeOfString(substring)?.startIndex #else // FIXME(performance): This is a very non-optimal algorithm, with a worst // case of O((n-m)*m). When non-objc String has a match function that's better, // this should be removed in favour of using that. // Operate on unicode scalars rather than codeunits. let haystack = string.unicodeScalars let needle = substring.unicodeScalars for matchStartIndex in haystack.indices { var matchIndex = matchStartIndex var needleIndex = needle.startIndex while true { if needleIndex == needle.endIndex { // if we hit the end of the search string, we found the needle return matchStartIndex.samePositionIn(string) } if matchIndex == haystack.endIndex { // if we hit the end of the string before finding the end of the needle, // we aren't going to find the needle after that. return nil } if needle[needleIndex] == haystack[matchIndex] { // keep advancing through both the string and search string on match ++matchIndex ++needleIndex } else { // no match, go back to finding a starting match in the string. break } } } return nil #endif } public func createTemporaryFile( fileNamePrefix: String, _ fileNameSuffix: String, _ contents: String ) -> String { #if _runtime(_ObjC) let tempDir: NSString = NSTemporaryDirectory() var fileName = tempDir.stringByAppendingPathComponent( fileNamePrefix + "XXXXXX" + fileNameSuffix) #else var fileName = fileNamePrefix + "XXXXXX" + fileNameSuffix #endif let fd = _stdlib_mkstemps( &fileName, CInt(fileNameSuffix.utf8.count)) if fd < 0 { fatalError("mkstemps() returned an error") } var stream = _FDOutputStream(fd: fd) stream.write(contents) if close(fd) != 0 { fatalError("close() return an error") } return fileName } public final class Box<T> { public init(_ value: T) { self.value = value } public var value: T } infix operator <=> {} public func <=> <T: Comparable>(lhs: T, rhs: T) -> ExpectedComparisonResult { return lhs < rhs ? .LT : lhs > rhs ? .GT : .EQ } public struct TypeIdentifier : Hashable, Comparable { public init(_ value: Any.Type) { self.value = value } public var hashValue: Int { return objectID.hashValue } public var value: Any.Type internal var objectID : ObjectIdentifier { return ObjectIdentifier(value) } } public func < (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool { return lhs.objectID < rhs.objectID } public func == (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool { return lhs.objectID == rhs.objectID } extension TypeIdentifier : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return String(value) } public var debugDescription: String { return "TypeIdentifier(\(description))" } } func _forAllPermutationsImpl( index: Int, _ size: Int, inout _ perm: [Int], inout _ visited: [Bool], _ body: ([Int]) -> Void ) { if index == size { body(perm) return } for i in 0..<size { if visited[i] { continue } visited[i] = true perm[index] = i _forAllPermutationsImpl(index + 1, size, &perm, &visited, body) visited[i] = false } } /// Generate all permutations. public func forAllPermutations(size: Int, body: ([Int]) -> Void) { if size == 0 { return } var permutation = [Int](count: size, repeatedValue: 0) var visited = [Bool](count: size, repeatedValue: false) _forAllPermutationsImpl(0, size, &permutation, &visited, body) } /// Generate all permutations. public func forAllPermutations<S : SequenceType>( sequence: S, body: ([S.Generator.Element]) -> Void ) { let data = Array(sequence) forAllPermutations(data.count) { (indices: [Int]) in body(indices.map { data[$0] }) return () } }
apache-2.0
552f5816baf7eec934634fd59a5f4d1d
26.166667
81
0.660736
4.048013
false
false
false
false
KrishMunot/swift
stdlib/public/SDK/CoreGraphics/CoreGraphics.swift
3
5956
//===----------------------------------------------------------------------===// // // 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 CoreGraphics import Darwin //===----------------------------------------------------------------------===// // CGGeometry //===----------------------------------------------------------------------===// public extension CGPoint { static var zero: CGPoint { @_transparent // @fragile get { return CGPoint(x: 0, y: 0) } } @_transparent // @fragile init(x: Int, y: Int) { self.init(x: CGFloat(x), y: CGFloat(y)) } @_transparent // @fragile init(x: Double, y: Double) { self.init(x: CGFloat(x), y: CGFloat(y)) } } extension CGPoint : CustomReflectable, CustomPlaygroundQuickLookable { public var customMirror: Mirror { return Mirror(self, children: ["x": x, "y": y], displayStyle: .`struct`) } public var customPlaygroundQuickLook: PlaygroundQuickLook { return .point(Double(x), Double(y)) } } extension CGPoint : CustomDebugStringConvertible { public var debugDescription: String { return "(\(x), \(y))" } } extension CGPoint : Equatable {} @_transparent // @fragile @warn_unused_result public func == (lhs: CGPoint, rhs: CGPoint) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } public extension CGSize { static var zero: CGSize { @_transparent // @fragile get { return CGSize(width: 0, height: 0) } } @_transparent // @fragile init(width: Int, height: Int) { self.init(width: CGFloat(width), height: CGFloat(height)) } @_transparent // @fragile init(width: Double, height: Double) { self.init(width: CGFloat(width), height: CGFloat(height)) } } extension CGSize : CustomReflectable, CustomPlaygroundQuickLookable { public var customMirror: Mirror { return Mirror( self, children: ["width": width, "height": height], displayStyle: .`struct`) } public var customPlaygroundQuickLook: PlaygroundQuickLook { return .size(Double(width), Double(height)) } } extension CGSize : CustomDebugStringConvertible { public var debugDescription : String { return "(\(width), \(height))" } } extension CGSize : Equatable {} @_transparent // @fragile @warn_unused_result public func == (lhs: CGSize, rhs: CGSize) -> Bool { return lhs.width == rhs.width && lhs.height == rhs.height } public extension CGVector { static var zero: CGVector { @_transparent // @fragile get { return CGVector(dx: 0, dy: 0) } } @_transparent // @fragile init(dx: Int, dy: Int) { self.init(dx: CGFloat(dx), dy: CGFloat(dy)) } @_transparent // @fragile init(dx: Double, dy: Double) { self.init(dx: CGFloat(dx), dy: CGFloat(dy)) } } extension CGVector : Equatable {} @_transparent // @fragile @warn_unused_result public func == (lhs: CGVector, rhs: CGVector) -> Bool { return lhs.dx == rhs.dx && lhs.dy == rhs.dy } public extension CGRect { static var zero: CGRect { @_transparent // @fragile get { return CGRect(x: 0, y: 0, width: 0, height: 0) } } @_transparent // @fragile init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { self.init(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height)) } @_transparent // @fragile init(x: Double, y: Double, width: Double, height: Double) { self.init(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height)) } @_transparent // @fragile init(x: Int, y: Int, width: Int, height: Int) { self.init(origin: CGPoint(x: x, y: y), size: CGSize(width: width, height: height)) } @_transparent // @fragile mutating func standardizeInPlace() { self = standardized } @_transparent // @fragile mutating func makeIntegralInPlace() { self = integral } @_transparent // @fragile mutating func insetInPlace(dx: CGFloat, dy: CGFloat) { self = insetBy(dx: dx, dy: dy) } @_transparent // @fragile mutating func offsetInPlace(dx: CGFloat, dy: CGFloat) { self = offsetBy(dx: dx, dy: dy) } @_transparent // @fragile mutating func unionInPlace(_ rect: CGRect) { self = union(rect) } @_transparent // @fragile mutating func intersectInPlace(_ rect: CGRect) { self = intersect(rect) } @_transparent // @fragile @warn_unused_result func divide(_ atDistance: CGFloat, fromEdge: CGRectEdge) -> (slice: CGRect, remainder: CGRect) { var slice = CGRect.zero var remainder = CGRect.zero divide(slice: &slice, remainder: &remainder, amount: atDistance, edge: fromEdge) return (slice, remainder) } } extension CGRect : CustomReflectable, CustomPlaygroundQuickLookable { public var customMirror: Mirror { return Mirror( self, children: ["origin": origin, "size": size], displayStyle: .`struct`) } public var customPlaygroundQuickLook: PlaygroundQuickLook { return .rectangle( Double(origin.x), Double(origin.y), Double(size.width), Double(size.height)) } } extension CGRect : CustomDebugStringConvertible { public var debugDescription : String { return "(\(origin.x), \(origin.y), \(size.width), \(size.height))" } } extension CGRect : Equatable {} @_transparent // @fragile @warn_unused_result public func == (lhs: CGRect, rhs: CGRect) -> Bool { return lhs.equalTo(rhs) } extension CGAffineTransform { public static var identity: CGAffineTransform { @_transparent // @fragile get { return CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) } } }
apache-2.0
110acad31f5dc76ed42825271fdecb28
25.008734
80
0.617193
3.975968
false
false
false
false
chanhx/iGithub
iGithub/Views/Cell/ReleaseCell.swift
2
2749
// // ReleaseCell.swift // iGithub // // Created by Chan Hocheung on 10/6/16. // Copyright © 2016 Hocheung. All rights reserved. // import Foundation class ReleaseCell: UITableViewCell { private let nameLabel = UILabel() private let tagLabel = UILabel() private let timeLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.configureSubviews() self.layout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureSubviews() { nameLabel.numberOfLines = 3 nameLabel.lineBreakMode = .byTruncatingTail nameLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) nameLabel.layer.isOpaque = true nameLabel.backgroundColor = .white [tagLabel, timeLabel].forEach { $0.font = .systemFont(ofSize: 14) $0.textColor = UIColor(netHex: 0x767676) $0.layer.isOpaque = true $0.backgroundColor = .white } } func layout() { let hStackView = UIStackView(arrangedSubviews: [tagLabel, timeLabel]) hStackView.axis = .horizontal hStackView.distribution = .fill hStackView.alignment = .fill hStackView.spacing = 12 let vStackView = UIStackView(arrangedSubviews: [nameLabel, hStackView]) vStackView.axis = .vertical vStackView.distribution = .fill vStackView.alignment = .leading vStackView.spacing = 8 contentView.addSubviews([vStackView]) let margins = contentView.layoutMarginsGuide NSLayoutConstraint.activate([ vStackView.topAnchor.constraint(equalTo: margins.topAnchor), vStackView.leadingAnchor.constraint(equalTo: margins.leadingAnchor), vStackView.trailingAnchor.constraint(equalTo: margins.trailingAnchor), vStackView.bottomAnchor.constraint(equalTo: margins.bottomAnchor) ]) } var entity: Release! { didSet { if let name = entity.name, name.trimmingCharacters(in: .whitespacesAndNewlines).count > 0 { nameLabel.text = entity.name } else { nameLabel.text = entity.tagName } tagLabel.attributedText = Octicon.tag.iconString(entity.tagName!, iconColor: UIColor(netHex: 0x767676)) timeLabel.attributedText = Octicon.clock.iconString(entity.publishedAt!.naturalString(), iconColor: UIColor(netHex: 0x767676)) } } }
gpl-3.0
d50a5dc984b52c285ddf51267e712746
32.925926
138
0.624818
5.117318
false
false
false
false
JellyDevelopment/JDSlider
Pod/Classes/JDSlider.swift
1
5545
// // JDSlider.swift // Pods // // Created by David López Carrascal on 22/2/16. // Copyright ©2016 David López Carrascal. All rights reserved. // // import UIKit //MARK: JDSliderDataSource public protocol JDSliderDataSource: class { func slider(jdSliderNumberOfSlides slider: JDSliderView) -> Int func slider(_ slider: JDSliderView, viewForSlideAtIndex index: Int) -> UIView } //MARK: JDSliderDelegate public protocol JDSliderDelegate: class { func slider(_ slider: JDSliderView, didSelectSlideAtIndex index: Int) } //MARK: JDSliderView open class JDSliderView: UIView { //MARK: Enum public enum StatePageIndicator{ case normal case highlight } //MARK:Public Properties open weak var delegate : JDSliderDelegate? open weak var datasource : JDSliderDataSource? //MARK:Private Properties fileprivate var numbersOfSlides : Int = 0 fileprivate var jdSliderScrollView : UIScrollView! open var pageControl : UIPageControl! //MARK: Init public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self._setUpUI() } override public init(frame: CGRect) { super.init(frame: frame) self._setUpUI() } //MARK: LifeCycle open override func layoutSubviews() { super.layoutSubviews() self._adapterUI() self._prepareDataSource() } //MARK: Selector func handleTap(_ sender: UITapGestureRecognizer){ self.delegate?.slider(self, didSelectSlideAtIndex: self.pageControl.currentPage) } //MARK: Public Methods open func tintPageIndicator(_ color: UIColor, state: StatePageIndicator){ switch state { case .normal: self.pageControl.pageIndicatorTintColor = color break case .highlight: self.pageControl.currentPageIndicatorTintColor = color break } } open func setCurrentPageIndicator(tintColor color: UIColor){ self.pageControl.currentPageIndicatorTintColor = color } open func reloadData(){ self._adapterUI() self._prepareDataSource() } //MARK: Private Methods fileprivate func _prepareDataSource(){ if let dataSource = self.datasource { //Set number of slides self.numbersOfSlides = dataSource.slider(jdSliderNumberOfSlides: self) self.pageControl.numberOfPages = self.numbersOfSlides //Set widht and height let scrollViewWidth : CGFloat = self.jdSliderScrollView.frame.width let scrollViewHeight : CGFloat = self.jdSliderScrollView.frame.height if self.numbersOfSlides == 0 { self.pageControl.isHidden = true self.jdSliderScrollView.isHidden = true } else if self.numbersOfSlides > 0{ for i in 0...(self.numbersOfSlides - 1) { let x = CGFloat(i) * scrollViewWidth let view = dataSource.slider(self, viewForSlideAtIndex: i) view.frame = CGRect(x: x, y: 0, width: scrollViewWidth, height: scrollViewHeight) self.jdSliderScrollView.addSubview(view) } self.jdSliderScrollView.contentSize = CGSize(width: self.jdSliderScrollView.frame.width * CGFloat(self.numbersOfSlides), height: self.jdSliderScrollView.frame.height) self.jdSliderScrollView.delegate = self self.pageControl.currentPage = 0 } let singleTap = UITapGestureRecognizer(target: self, action: #selector(JDSliderView.handleTap(_:))) singleTap.cancelsTouchesInView = false self.jdSliderScrollView.addGestureRecognizer(singleTap) } } fileprivate func _setUpUI(){ //Setup ScrollView self.jdSliderScrollView = UIScrollView() self.jdSliderScrollView.isScrollEnabled = true self.jdSliderScrollView.isPagingEnabled = true self.jdSliderScrollView.bounces = false self.jdSliderScrollView.showsHorizontalScrollIndicator = false self.jdSliderScrollView.showsVerticalScrollIndicator = false self.addSubview(self.jdSliderScrollView) //Setup PageControl self.pageControl = UIPageControl() self.addSubview(self.pageControl) } fileprivate func _adapterUI(){ self.jdSliderScrollView.frame = self.frame self.pageControl.frame.origin.x = self.center.x - self.pageControl.frame.width/2 self.pageControl.frame.origin.y = self.frame.size.height - 20 } } //MARK: UIScrollViewDelegate extension JDSliderView: UIScrollViewDelegate { public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.jdSliderScrollView { // Test the offset and calculate the current page after scrolling ends let pageWidth:CGFloat = self.jdSliderScrollView.frame.size.width let currentPage:CGFloat = floor((self.jdSliderScrollView.contentOffset.x-pageWidth/2)/pageWidth)+1 self.pageControl.currentPage = Int(currentPage); } } }
mit
dc3adac2028a486cf9519cd15a97b5b1
31.6
182
0.618188
5.198874
false
false
false
false
michael-yuji/spartanX
Sources/Transmittable.swift
2
2532
// Copyright (c) 2016, Yuji // 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. // // 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 OWNER 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. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // // Created by yuuji on 9/27/16. // Copyright © 2016 yuuji. All rights reserved. // public struct SendMethods : OptionSet { public typealias RawValue = UInt32 public var rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } /// accepts send(), write(), writev() system call public static let send = SendMethods(rawValue: 0) /// accepts sendfile() system call public static let sendfile = SendMethods(rawValue: 1) /// accepts sendto() system call public static let sendto = SendMethods(rawValue: 1 << 1) /// accepts sendmsg() system call public static let sendmsg = SendMethods(rawValue: 1 << 2) /// accepts write(), writev() system call public static let write = SendMethods(rawValue: 1 << 3) } public protocol Transmittable { var sendOptions: SendMethods { get } func send(with method: SendMethods, using agent: Writable) throws }
bsd-2-clause
5523c6692709a437f559bb246b402ea2
43.403509
83
0.733307
4.417103
false
false
false
false
oleander/bitbar
Sources/Config/Params/Dictionary.swift
1
527
import Toml typealias Dict = [String: String] final class DictParam: Param<Toml, Dict> { override internal func extract(_ top: Toml) throws -> Dict? { guard let toml = top.table(key) else { return nil } var output = [String: String]() for key in toml.keyNames { guard let value = toml.string(key.components) else { continue } if value.isEmpty { continue } let path = key.components.joined(separator: ".") output[path] = value } return output } }
mit
5c7dbd9fc7254eb9021aca06a4f8c40c
20.958333
63
0.607211
3.875
false
false
false
false
cailingyun2010/swift-weibo
微博-S/Classes/Home/User.swift
1
2018
// // User.swift // 微博-S // // Created by nimingM on 16/3/21. // Copyright © 2016年 蔡凌云. All rights reserved. // import UIKit class User: NSObject { /// 用户ID var id: Int = 0 /// 友好显示名称 var name: String? /// 用户头像地址(中图),50×50像素 var profile_image_url: String? { didSet { if let urlStr = profile_image_url { imageURL = NSURL(string: urlStr) } } } /// 时候是认证, true是, false不是 var verified: Bool = false /// 用户的认证类型,-1:没有认证,0,认证用户,2,3,5: 企业认证,220: 达人 var verified_type: Int = -1 { didSet { switch verified_type { case 0: verifiedImage = UIImage(named: "avatar_vip") case 2, 3, 5: verifiedImage = UIImage(named: "avatar_enterprise_vip") case 220: verifiedImage = UIImage(named: "avatar_grassroot") default: verifiedImage = nil } } } var mbrank:Int = 0 { didSet { if mbrank > 0 && mbrank < 7 { mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)") } } } /// 会员突变 var mbrankImage: UIImage? /// 用于保存用户头像的URL var imageURL: NSURL? /// 保存当前用户的认证图片 var verifiedImage: UIImage? // 字典转模型 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } // 打印当前模型 var properties = ["id", "name", "profile_image_url", "verified", "verified_type"] override var description: String { let dict = dictionaryWithValuesForKeys(properties) return "\(dict)" } }
apache-2.0
6e74eebbc883f885f2ba16f7d929f5df
21.219512
85
0.515917
3.893162
false
false
false
false
TakuSemba/DribbbleSwiftApp
Carthage/Checkouts/RxSwift/RxExample/RxExample/Services/Randomizer.swift
1
7076
// // Randomizer.swift // RxExample // // Created by Krunoslav Zaher on 6/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation typealias NumberSection = AnimatableSectionModel<String, Int> extension String : IdentifiableType { public typealias Identity = String public var identity: String { return self } } extension Int : IdentifiableType { public typealias Identity = Int public var identity: Int { return self } } let insertItems = true let deleteItems = true let moveItems = true let reloadItems = true let deleteSections = true let insertSections = true let explicitlyMoveSections = true let reloadSections = true class Randomizer { var sections: [NumberSection] var rng: PseudoRandomGenerator var unusedItems: [Int] var unusedSections: [String] init(rng: PseudoRandomGenerator, sections: [NumberSection]) { self.rng = rng self.sections = sections self.unusedSections = [] self.unusedItems = [] } func countTotalItemsInSections(sections: [NumberSection]) -> Int { return sections.reduce(0) { p, s in return p + s.items.count } } func randomize() { var nextUnusedSections = [String]() var nextUnusedItems = [Int]() let sectionCount = sections.count let itemCount = countTotalItemsInSections(sections) let startItemCount = itemCount + unusedItems.count let startSectionCount = sections.count + unusedSections.count // insert sections for section in unusedSections { let index = rng.get_random() % (sections.count + 1) if insertSections { sections.insert(NumberSection(model: section, items: []), atIndex: index) } else { nextUnusedSections.append(section) } } // insert/reload items for unusedValue in unusedItems { let sectionIndex = rng.get_random() % sections.count let section = sections[sectionIndex] let itemCount = section.items.count // insert if rng.get_random() % 2 == 0 { let itemIndex = rng.get_random() % (itemCount + 1) if insertItems { sections[sectionIndex].items.insert(unusedValue, atIndex: itemIndex) } else { nextUnusedItems.append(unusedValue) } } // update else { if itemCount == 0 { sections[sectionIndex].items.insert(unusedValue, atIndex: 0) continue } let itemIndex = rng.get_random() % itemCount if reloadItems { nextUnusedItems.append(sections[sectionIndex].items.removeAtIndex(itemIndex)) sections[sectionIndex].items.insert(unusedValue, atIndex: itemIndex) } else { nextUnusedItems.append(unusedValue) } } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) let itemActionCount = itemCount / 7 let sectionActionCount = sectionCount / 3 // move items for _ in 0 ..< itemActionCount { if self.sections.count == 0 { continue } let sourceSectionIndex = rng.get_random() % self.sections.count let destinationSectionIndex = rng.get_random() % self.sections.count let sectionItemCount = sections[sourceSectionIndex].items.count if sectionItemCount == 0 { continue } let sourceItemIndex = rng.get_random() % sectionItemCount let nextRandom = rng.get_random() if moveItems { let item = sections[sourceSectionIndex].items.removeAtIndex(sourceItemIndex) let targetItemIndex = nextRandom % (self.sections[destinationSectionIndex].items.count + 1) sections[destinationSectionIndex].items.insert(item, atIndex: targetItemIndex) } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) // delete items for _ in 0 ..< itemActionCount { if self.sections.count == 0 { continue } let sourceSectionIndex = rng.get_random() % self.sections.count let sectionItemCount = sections[sourceSectionIndex].items.count if sectionItemCount == 0 { continue } let sourceItemIndex = rng.get_random() % sectionItemCount if deleteItems { nextUnusedItems.append(sections[sourceSectionIndex].items.removeAtIndex(sourceItemIndex)) } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) // move sections for _ in 0 ..< sectionActionCount { if sections.count == 0 { continue } let sectionIndex = rng.get_random() % sections.count let targetIndex = rng.get_random() % sections.count if explicitlyMoveSections { let section = sections.removeAtIndex(sectionIndex) sections.insert(section, atIndex: targetIndex) } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) // delete sections for _ in 0 ..< sectionActionCount { if sections.count == 0 { continue } let sectionIndex = rng.get_random() % sections.count if deleteSections { let section = sections.removeAtIndex(sectionIndex) for item in section.items { nextUnusedItems.append(item) } nextUnusedSections.append(section.model) } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) unusedSections = nextUnusedSections unusedItems = nextUnusedItems } }
apache-2.0
37c6845f744c37d300e150abafeb4738
31.163636
107
0.559293
5.425613
false
false
false
false
sugar2010/arcgis-runtime-samples-ios
GeocodingSample/swift/Geocoding/Geocoding/ViewController.swift
4
6803
// // Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // import UIKit import ArcGIS //The map service let kMapServiceURL = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer" //The geocode service let kGeoLocatorURL = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer" class ViewController: UIViewController, AGSCalloutDelegate, AGSLocatorDelegate, UISearchBarDelegate { @IBOutlet weak var mapView:AGSMapView! @IBOutlet weak var searchBar:UISearchBar! var graphicsLayer:AGSGraphicsLayer! var locator:AGSLocator! var calloutTemplate:AGSCalloutTemplate! var selectedGraphic:AGSGraphic! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() //set the delegate on the mapView so we get notifications for user interaction with the callout self.mapView.callout.delegate = self //create an instance of a tiled map service layer //Add it to the map view let serviceUrl = NSURL(string: kMapServiceURL) let tiledMapServiceLayer = AGSTiledMapServiceLayer(URL: serviceUrl) self.mapView.addMapLayer(tiledMapServiceLayer, withName:"World Street Map") //create the graphics layer that the geocoding result //will be stored in and add it to the map self.graphicsLayer = AGSGraphicsLayer() self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer") //set the text and detail text based on 'Name' and 'Descr' fields in the results //create the callout template, used when the user displays the callout self.calloutTemplate = AGSCalloutTemplate() self.calloutTemplate.titleTemplate = "${Match_addr}" self.calloutTemplate.detailTemplate = "${Place_addr}" self.graphicsLayer.calloutDelegate = self.calloutTemplate } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func startGeocoding() { //clear out previous results self.graphicsLayer.removeAllGraphics() //create the AGSLocator with the geo locator URL //and set the delegate to self, so we get AGSLocatorDelegate notifications self.locator = AGSLocator(URL: NSURL(string: kGeoLocatorURL)) self.locator.delegate = self //Note that the "*" for out fields is supported for geocode services of //ArcGIS Server 10 and above let parameters = AGSLocatorFindParameters() parameters.text = self.searchBar.text parameters.outSpatialReference = self.mapView.spatialReference parameters.outFields = ["*"] self.locator.findWithParameters(parameters) } //MARK: - AGSCalloutDelegate func didClickAccessoryButtonForCallout(callout: AGSCallout!) { self.selectedGraphic = callout.representedObject as! AGSGraphic //The user clicked the callout button, so display the complete set of results self.performSegueWithIdentifier("ResultsSegue", sender: self) } //MARK - AGSLocatorDelegate func locator(locator: AGSLocator!, operation op: NSOperation!, didFind results: [AnyObject]!) { //check and see if we didn't get any results if results == nil || results.count == 0 { //show alert if we didn't get results UIAlertView(title: "No Results", message: "No Results Found By Locator", delegate: nil, cancelButtonTitle: "OK").show() } else { //loop through all candidates/results and add to graphics layer for candidate in results as! [AGSLocatorFindResult] { //get the location from the candidate let pt = candidate.graphic.geometry as! AGSPoint //create a marker symbol to use in our graphic let marker = AGSPictureMarkerSymbol(imageNamed: "BluePushpin") marker.offset = CGPointMake(9,16) marker.leaderPoint = CGPointMake(-9, 11) candidate.graphic.symbol = marker //add the graphic to the graphics layer self.graphicsLayer.addGraphic(candidate.graphic) if results.count == 1 { //we have one result, center at that point self.mapView.centerAtPoint(pt, animated:false) // set the width of the callout self.mapView.callout.width = 250 //show the callout self.mapView.callout.showCalloutAtPoint(candidate.graphic.geometry as! AGSPoint, forFeature: candidate.graphic, layer:candidate.graphic.layer, animated:true) } } //if we have more than one result, zoom to the extent of all results if results.count > 1 { self.mapView.zoomToEnvelope(self.graphicsLayer.fullEnvelope, animated:true) } } } func locator(locator: AGSLocator!, operation op: NSOperation!, didFailToFindWithError error: NSError!) { //The location operation failed, display the error UIAlertView(title: "Locator failed", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK").show() } //MARK: - UISearchBarDelegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { //hide the callout self.mapView.callout.hidden = true //First, hide the keyboard, then starGeocoding searchBar.resignFirstResponder() self.startGeocoding() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { //hide the keyboard searchBar.resignFirstResponder() } //MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "ResultsSegue" { let controller = segue.destinationViewController as! GeocodingResultsViewController controller.results = self.selectedGraphic.allAttributes() } } }
apache-2.0
f1622f339badc5bb9c3ac3ba4d18cc40
38.783626
177
0.643099
5.294163
false
false
false
false
renatogg/iOSTamagochi
Tamagochi/MonsterImg.swift
1
1151
// // MonsterImg.swift // Tamagochi // // Created by Renato Gasoto on 5/12/16. // Copyright © 2016 Renato Gasoto. All rights reserved. // import Foundation import UIKit extension Array{ var last: Element{ return self[self.endIndex - 1] } } class MonsterImg : UIImageView{ override init(frame: CGRect){ super.init(frame: frame) } required init?(coder aDecoder :NSCoder){ super.init(coder: aDecoder) playAnimation(false) } func playAnimation(dead: Bool){ var imgArray = [UIImage]() self.animationImages = nil if !dead{ for i in 1..<5 { let img = UIImage(named: "idle\(i).png") imgArray.append(img!) } }else{ for i in 1..<6 { let img = UIImage(named: "dead\(i).png") imgArray.append(img!) } } self.image = imgArray.last self.animationImages = imgArray self.animationDuration = 0.8 print (Int(dead)) self.animationRepeatCount = Int(dead) self.startAnimating() } }
cc0-1.0
7f89b84e7ea99f95555a8a418f89e79e
21.568627
56
0.54
4.19708
false
false
false
false
codercd/xmppChat
Chat/General/WXMessage.swift
1
1596
// // WXMessage.swift // Chat // // Created by lcd on 15/9/16. // Copyright © 2015年 lcd. All rights reserved. // import Foundation //好友消息结构 struct WXMessage { var body = "" var from = "" var isComposing = false var isDelay = false var isMe = false } //状态结构 struct Zhuangtai { var name = "" var isOnline = false } //获取正确的删除索引 func getRemoveIndex(value: String, aArray: [WXMessage]) -> [Int] { var indexArray = [Int]() var correctArray = [Int]() // 获取指定值在数组中的索引并保存 for (index, _) in aArray.enumerate() { if ( value == aArray[index].from ) { //如果在数组中找到指定的值,则把索引添加到 索引数组 indexArray.append(index) } } // 计算正确的删除索引 for (index, originIndex) in indexArray.enumerate() { // 正确的索引 var y = 0 //用指定值在原数组中的索引,减去 索引数组中的索引 y = originIndex - index //添加到正确索引数组中 correctArray.append(y) } // 返回正确的删除索引 return correctArray } // 从数组中删除指定的元素 func removeValueFromArray(value: String, inout aArray: [WXMessage]) { var correctArray = [Int]() correctArray = getRemoveIndex(value, aArray: aArray) // 从原数组中删除指定元素(用正确的索引) for index in correctArray { aArray.removeAtIndex(index) } }
apache-2.0
9060c89de27e45594067dfde226f7a70
18.308824
69
0.571211
3.46438
false
false
false
false
JohnCoates/Aerial
Aerial/Source/Models/Downloads/FileHelpers.swift
1
1110
// // FileHelpers.swift // Aerial // // Created by Guillaume Louel on 08/07/2020. // Copyright © 2020 Guillaume Louel. All rights reserved. // import Foundation struct FileHelpers { static func createDirectory(atPath: String) { let fileManager = FileManager.default if fileManager.fileExists(atPath: atPath) == false { do { try fileManager.createDirectory(atPath: atPath, withIntermediateDirectories: true, attributes: nil) } catch let error { errorLog("Couldn't create directory at \(atPath) : \(error)") errorLog("FATAL : There's nothing more we can do at this point, please report") } } } static func unTar(file: String, atPath: String) { let process: Process = Process() debugLog("untaring \(file) at \(atPath)") process.currentDirectoryPath = atPath process.launchPath = "/usr/bin/tar" process.arguments = ["-xvf", file] process.launch() process.waitUntilExit() } }
mit
0c5b956e6998b871eb9d0c107c216dfa
28.972973
99
0.58431
4.821739
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/Discovery/Views/Cells/DiscoveryOnboardingCell.swift
1
2590
import Library import Prelude import UIKit internal protocol DiscoveryOnboardingCellDelegate: AnyObject { func discoveryOnboardingTappedSignUpLoginButton() } internal final class DiscoveryOnboardingCell: UITableViewCell, ValueCell { internal weak var delegate: DiscoveryOnboardingCellDelegate? @IBOutlet fileprivate var loginButton: UIButton! @IBOutlet fileprivate var logoImageView: UIImageView! @IBOutlet fileprivate var onboardingTitleLabel: UILabel! @IBOutlet fileprivate var stackView: UIStackView! override func awakeFromNib() { super.awakeFromNib() self.loginButton.addTarget(self, action: #selector(self.loginButtonTapped), for: .touchUpInside) } internal func configureWith(value _: Void) {} internal override func bindStyles() { _ = self |> baseTableViewCellStyle() |> \.backgroundColor .~ discoveryPageBackgroundColor() |> DiscoveryOnboardingCell.lens.contentView.layoutMargins %~~ { layoutMargins, cell in cell.traitCollection.isRegularRegular ? .init(top: Styles.grid(5), left: Styles.grid(30), bottom: 0, right: Styles.grid(30)) : .init(top: Styles.grid(3), left: layoutMargins.left, bottom: 0, right: layoutMargins.left) } _ = self.loginButton |> greenButtonStyle |> UIButton.lens.title(for: .normal) %~ { _ in Strings.discovery_onboarding_buttons_signup_or_login() } _ = self.logoImageView |> discoveryOnboardingLogoStyle _ = self.onboardingTitleLabel |> discoveryOnboardingTitleStyle _ = self.stackView |> discoveryOnboardingStackViewStyle } @objc fileprivate func loginButtonTapped() { self.delegate?.discoveryOnboardingTappedSignUpLoginButton() } } // MARK: - Styles private let discoveryOnboardingTitleStyle: LabelStyle = { label in label |> \.font .~ .ksr_title3() |> \.backgroundColor .~ .clear |> \.textAlignment .~ .center |> \.numberOfLines .~ 2 |> \.text %~ { _ in Strings.discovery_onboarding_title_bring_creative_projects_to_life() } } private let discoveryOnboardingLogoStyle: ImageViewStyle = { imageView in imageView |> \.contentMode .~ .scaleAspectFit |> \.tintColor .~ .ksr_create_500 |> \.backgroundColor .~ .clear |> UIImageView.lens.contentHuggingPriority(for: .vertical) .~ .required |> UIImageView.lens.contentCompressionResistancePriority(for: .vertical) .~ .required } private let discoveryOnboardingStackViewStyle: StackViewStyle = { stackView in stackView |> \.spacing .~ Styles.grid(3) |> \.distribution .~ .fill |> \.alignment .~ .fill }
apache-2.0
66d172b18ea82a8d8f4e3cffb76af05a
33.078947
102
0.713514
4.683544
false
false
false
false
jakecraige/SwiftLint
Source/SwiftLintFramework/StyleViolationType.swift
4
945
// // StyleViolationType.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // public enum StyleViolationType: String, CustomStringConvertible { case NameFormat = "Name Format" case Length = "Length" case TrailingNewline = "Trailing Newline" case LeadingWhitespace = "Leading Whitespace" case TrailingWhitespace = "Trailing Whitespace" case ReturnArrowWhitespace = "Return Arrow Whitespace" case OperatorFunctionWhitespace = "Operator Function Whitespace" case ForceCast = "Force Cast" case TODO = "TODO or FIXME" case Colon = "Colon" case Nesting = "Nesting" case ControlStatement = "Control Statement Parentheses" public var description: String { return rawValue } }
mit
c4bc01b3b4e65b30d0fd5115c2ce0cce
38.375
69
0.598942
5
false
false
false
false
gitkong/FLTableViewComponent
FLTableComponent/FLTableComponentController.swift
2
2055
// // FLTableComponentController.swift // FLComponentDemo // // Created by gitKong on 2017/5/11. // Copyright © 2017年 gitKong. All rights reserved. // import UIKit class FLTableComponentController: UIViewController { private(set) var handler : FLTableViewHandler = FLTableViewHandler() lazy var tableView : UITableView = { let tableView : UITableView = UITableView.init(frame: self.customRect, style: self.tableViewStyle) return tableView }() var components : Array<FLTableBaseComponent> = [] { didSet { handler.components = components } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.frame = self.customRect } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white handler.delegate = self view.addSubview(tableView) self.tableView.tableHeaderView = headerView(of: tableView) self.tableView.tableFooterView = footerView(of: tableView) } func headerView(of tableView : UITableView) -> UIView? { return nil } func footerView(of tableView : UITableView) -> UIView? { return nil } } extension FLTableComponentController : FLTableComponentConfiguration { var tableViewStyle: UITableViewStyle { return UITableViewStyle.plain } var customRect: CGRect { return self.view.bounds } func reloadComponent() { handler.reloadComponents() } } extension FLTableComponentController : FLTableViewHandlerDelegate { func tableViewDidClick(_ handler: FLTableViewHandler, cellAt indexPath: IndexPath) { // subclass override it } func tableViewDidClick(_ handler: FLTableViewHandler, headerAt section: NSInteger) { // subclass override it } func tableViewDidClick(_ handler: FLTableViewHandler, footerAt section: NSInteger) { // subclass override it } }
mit
8eb42c3059712e06ffdd53e4c81d8447
24.02439
106
0.655458
5.004878
false
false
false
false
edoohwang/EDLoader
EDLoader/EDLoader/UIView+EDLoader.swift
1
1754
import Foundation import UIKit extension UIView { var ed_x: CGFloat { get { return frame.origin.x } set { frame.origin.x = newValue } } var ed_y: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } var ed_height: CGFloat { get { return frame.size.height } set { frame.size.height = newValue } } var ed_width: CGFloat { get { return frame.size.width } set { frame.size.width = newValue } } var ed_center_x: CGFloat { get { return center.x } set { center.x = newValue } } var ed_center_y: CGFloat { get { return center.y } set { center.y = newValue } } var ed_top: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } var ed_left: CGFloat { get { return frame.origin.x } set { frame.origin.x = newValue } } var ed_right: CGFloat { get { return frame.origin.x + frame.size.width } set { frame.origin.x = newValue - frame.size.width } } var ed_bottom: CGFloat { get { return frame.origin.y + frame.size.height } set { frame.origin.y = newValue - frame.size.height } } }
mit
887bab9e7b7746922edc0da3a65e8125
14.660714
58
0.396237
4.555844
false
false
false
false
maxim-pervushin/simplenotes
SimpleNotes/SimpleNotes/Src/Screens/Edit Note/EditNoteViewController.swift
1
2308
// // Created by Maxim Pervushin on 07/08/15. // Copyright (c) 2015 Maxim Pervushin. All rights reserved. // import UIKit class EditNoteViewController: UIViewController, UITextViewDelegate { @IBOutlet var toggleFavoriteButton: UIBarButtonItem! @IBOutlet var textView: UITextView! @IBAction func toggleFavoriteButtonAction(sender: AnyObject) { if let isFavorite = validator.isFavorite { validator.isFavorite = !isFavorite } else { validator.isFavorite = true } updateUI() } var note: Note? { get { return validator.note } set { validator.originalNote = newValue validator.identifier = newValue?.identifier validator.text = newValue?.text validator.isFavorite = newValue?.isFavorite validator.notebookIdentifier = newValue?.notebookIdentifier updateUI() } } var notebook: Notebook? { didSet { validator.notebookIdentifier = notebook?.identifier updateUI() } } private let dataSource = EditNoteDataSource() private let validator = EditNoteValidator() private func updateUI() { if !isViewLoaded() { return } textView.text = validator.text if let isFavorite = validator.isFavorite { toggleFavoriteButton.image = UIImage(named: isFavorite ? "Star" : "StarEmpty") } else { toggleFavoriteButton.image = UIImage(named: "StarEmpty") } } override func viewDidLoad() { super.viewDidLoad() updateUI() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // TODO: Move this logic to EditNoteValidator if validator.originalNote == validator.note { } else if validator.note != nil { if let note = validator.note { dataSource.saveNote(note) } } else { if let originalNote = validator.originalNote { dataSource.deleteNote(originalNote) } } } // MARK: - UITextViewDelegate func textViewDidChange(textView: UITextView) { validator.text = textView.text } }
mit
92bcde2eecd9eb42a661063c8bf25348
25.837209
90
0.595754
5.330254
false
false
false
false
cojoj/XcodeServerSDK
XcodeServerSDK/API Routes/XcodeServer+LiveUpdates.swift
1
4360
// // XcodeServer+LiveUpdates.swift // XcodeServerSDK // // Created by Honza Dvorsky on 25/09/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils // MARK: - XcodeSever API Routes for Live Updates extension XcodeServer { public typealias MessageHandler = (messages: [LiveUpdateMessage]) -> () public typealias StopHandler = () -> () public typealias ErrorHandler = (error: ErrorType) -> () private class LiveUpdateState { var task: NSURLSessionTask? var messageHandler: MessageHandler? var errorHandler: ErrorHandler? var pollId: String? var terminated: Bool = false func cancel() { self.task?.cancel() self.task = nil self.terminated = true } func error(error: ErrorType) { self.cancel() self.errorHandler?(error: error) } deinit { self.cancel() } } /** * Returns StopHandler - call it when you want to stop receiving updates. */ public func startListeningForLiveUpdates(message: MessageHandler, error: ErrorHandler? = nil) -> StopHandler { let state = LiveUpdateState() state.errorHandler = error state.messageHandler = message self.startPolling(state) return { state.cancel() } } private func queryWithTimestamp() -> [String: String] { let timestamp = Int(NSDate().timeIntervalSince1970)*1000 return [ "t": "\(timestamp)" ] } private func sendRequest(state: LiveUpdateState, params: [String: String]?, completion: (message: String) -> ()) { let query = queryWithTimestamp() let task = self.sendRequestWithMethod(.GET, endpoint: .LiveUpdates, params: params, query: query, body: nil, portOverride: 443) { (response, body, error) -> () in if let error = error { state.error(error) return } guard let message = body as? String else { let e = Error.withInfo("Wrong body: \(body)") state.error(e) return } completion(message: message) } state.task = task } private func startPolling(state: LiveUpdateState) { self.sendRequest(state, params: nil) { [weak self] (message) -> () in self?.processInitialResponse(message, state: state) } } private func processInitialResponse(initial: String, state: LiveUpdateState) { if let pollId = initial.componentsSeparatedByString(":").first { state.pollId = pollId self.poll(state) } else { state.error(Error.withInfo("Unexpected initial poll message: \(initial)")) } } private func poll(state: LiveUpdateState) { precondition(state.pollId != nil) let params = [ "poll_id": state.pollId! ] self.sendRequest(state, params: params) { [weak self] (message) -> () in let packets = SocketIOHelper.parsePackets(message) self?.handlePackets(packets, state: state) } } private func handlePackets(packets: [SocketIOPacket], state: LiveUpdateState) { //check for errors if let lastPacket = packets.last where lastPacket.type == .Error { let (_, advice) = lastPacket.parseError() if let advice = advice, case .Reconnect = advice { //reconnect! self.startPolling(state) return } print("Unrecognized socket.io error: \(lastPacket.stringPayload)") } //we good? let events = packets.filter { $0.type == .Event } let validEvents = events.filter { $0.jsonPayload != nil } let messages = validEvents.map { LiveUpdateMessage(json: $0.jsonPayload!) } if messages.count > 0 { state.messageHandler?(messages: messages) } if !state.terminated { self.poll(state) } } }
mit
6c23be4fe3c688f9144e0373703c0b96
29.914894
137
0.547832
4.816575
false
false
false
false
Otbivnoe/Routing
Routing/FadeAnimator.swift
1
2009
// // FadeAnimator.swift // Routing // // Created by Nikita Ermolenko on 29/09/2017. // import Foundation import UIKit final class FadeAnimator: NSObject, Animator { var isPresenting: Bool = true func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.4 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if isPresenting { present(using: transitionContext) } else { dismiss(using: transitionContext) } } private func present(using transitionContext: UIViewControllerContextTransitioning) { guard let toViewController = transitionContext.viewController(forKey: .to) else { return } let containerView = transitionContext.containerView toViewController.view.alpha = 0 containerView.addSubview(toViewController.view) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { toViewController.view.alpha = 1.0 }, completion: { _ in transitionContext.completeTransition(true) }) } private func dismiss(using transitionContext: UIViewControllerContextTransitioning) { guard let toViewController = transitionContext.viewController(forKey: .to) else { return } guard let fromViewController = transitionContext.viewController(forKey: .from) else { return } let containerView = transitionContext.containerView containerView.addSubview(toViewController.view) containerView.addSubview(fromViewController.view) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { fromViewController.view.alpha = 0.0 }, completion: { _ in transitionContext.completeTransition(true) }) } }
mit
87d16eb589faa3b93b41abb3d6f47529
31.403226
109
0.663514
6.033033
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
Source/Keyknox/CloudKeyStorage/CloudEntry.swift
1
3477
// // Copyright (C) 2015-2020 Virgil Security Inc. // // 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 AUTHOR ''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 AUTHOR 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. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation /// Class representing entry in cloud @objc(VSSCloudEntry) public final class CloudEntry: NSObject, Codable { /// Entry name @objc public let name: String /// Entry data @objc public let data: Data /// Entry creation date @objc public let creationDate: Date /// Entry modification date @objc public let modificationDate: Date /// Entry meta @objc public let meta: [String: String]? /// Init /// /// - Parameters: /// - name: name /// - data: data /// - creationDate: creationDate /// - modificationDate: modificationDate /// - meta: meta @objc public init(name: String, data: Data, creationDate: Date, modificationDate: Date, meta: [String: String]?) { self.name = name self.data = data self.creationDate = creationDate self.modificationDate = modificationDate self.meta = meta super.init() } // swiftlint:disable explicit_enum_raw_value /// CodingKeys /// /// - name: name /// - data: data /// - creationDate: creationDate /// - modificationDate: modificationDate /// - meta: meta public enum CodingKeys: String, CodingKey { case name case data case creationDate = "creation_date" case modificationDate = "modification_date" case meta } // swiftlint:enable explicit_enum_raw_value } // swiftlint:disable missing_docs // MARK: - Equatable implementation public extension CloudEntry { static func == (lhs: CloudEntry, rhs: CloudEntry) -> Bool { return lhs.name == rhs.name && lhs.data == rhs.data && lhs.creationDate == rhs.creationDate && lhs.modificationDate == rhs.modificationDate && lhs.meta == rhs.meta } }
bsd-3-clause
e65c6216e68c51065e200d241b23226d
32.432692
118
0.672419
4.599206
false
false
false
false
urbn/URBNSwiftAlert
URBNSwiftAlert/Classes/AlertController.swift
1
3940
// // AlertController.swift // Pods // // Created by Kevin Taniguchi on 5/22/17. // // import Foundation public class AlertController: NSObject { public static let shared = AlertController() public var alertStyler = AlertStyler() private var alertIsVisible = false private var queue: [AlertViewController] = [] private var alertWindow: UIWindow? public var presentingWindow = UIApplication.shared.windows.first ?? UIWindow(frame: UIScreen.main.bounds) // MARK: Queueing public func addAlertToQueue(avc: AlertViewController) { queue.append(avc) showNextAlert() } public func showNextAlert() { guard let nextAVC = queue.first, !alertIsVisible else { return } nextAVC.dismissingHandler = {[weak self] wasTouchedOutside in guard let strongSelf = self else { return } if wasTouchedOutside { strongSelf.dismiss(alertViewController: nextAVC) } if strongSelf.queue.isEmpty { strongSelf.presentingWindow.makeKeyAndVisible() strongSelf.alertWindow?.isHidden = true strongSelf.alertWindow = nil } if nextAVC.alertConfiguration.presentationView != nil { nextAVC.view.removeFromSuperview() } } if let presentationView = nextAVC.alertConfiguration.presentationView { var rect = nextAVC.view.frame rect.size.width = presentationView.frame.size.width rect.size.height = presentationView.frame.size.height nextAVC.view.frame = rect nextAVC.alertConfiguration.presentationView?.addSubview(nextAVC.view) } else { NotificationCenter.default.addObserver(self, selector: #selector(resignActive(note:)), name: Notification.Name(rawValue: "UIWindowDidBecomeKeyNotification"), object: nil) setupAlertWindow() alertWindow?.rootViewController = nextAVC alertWindow?.makeKeyAndVisible() } NSObject.cancelPreviousPerformRequests(withTarget: self) if !nextAVC.alertConfiguration.isActiveAlert, let duration = nextAVC.alertConfiguration.duration { perform(#selector(dismiss(alertViewController:)), with: nextAVC, afterDelay: TimeInterval(duration)) } } private func setupAlertWindow() { if alertWindow == nil { alertWindow = UIWindow(frame: UIScreen.main.bounds) } alertWindow?.windowLevel = UIWindowLevelAlert alertWindow?.isHidden = false alertWindow?.accessibilityIdentifier = "alertWindow" NotificationCenter.default.addObserver(self, selector: #selector(resignActive) , name: Notification.Name(rawValue: "UIWindowDidBecomeKeyNotification") , object: nil) } func popQueueAndShowNextIfNecessary() { alertIsVisible = false if !queue.isEmpty { _ = queue.removeFirst() } showNextAlert() } /// Conveinence to close alerts that are visible or in queue public func dismissAllAlerts() { queue.forEach { (avc) in avc.dismissAlert(sender: self) } } @objc func dismiss(alertViewController: AlertViewController) { alertIsVisible = false alertViewController.dismissAlert(sender: self) } /** * Called when a new window becomes active. * Specifically used to detect new alertViews or actionSheets so we can dismiss ourselves **/ @objc func resignActive(note: Notification) { guard let noteWindow = note.object as? UIWindow, noteWindow != alertWindow, noteWindow != presentingWindow else { return } if let nextAVC = queue.first { dismiss(alertViewController: nextAVC) } } }
mit
0fd0fa0d0a730fc5cc75b2dbe977385e
35.146789
183
0.63401
5.191041
false
false
false
false
mihyaeru21/RxTwift
Pod/Classes/Internal/Dictionary+Extension.swift
1
750
// // Dictionary+Extension.swift // Pods // // Created by Mihyaeru on 2/11/16. // // import Foundation internal extension Dictionary { internal static func merge(dict dict: [Key: Value], other: [Key: Value]) -> [Key: Value] { var new = Dictionary<Key, Value>() for (key, value) in dict { new[key] = value } for (key, value) in other { new[key] = value } return new } internal static func createWithNotNil(taples: (Key, Value?)...) -> Dictionary<Key, Value> { var dict = Dictionary<Key, Value>() for tuple in taples { if let value = tuple.1 { dict[tuple.0] = value } } return dict } }
mit
8f3aea05af829a774e96b447b10a814e
22.4375
95
0.524
3.787879
false
false
false
false
JakubTudruj/SweetCherry
SweetCherry/Config/SweetCherryConfig.swift
1
1664
// // SweetCherryConfig.swift // SweetCherry // // Created by Jakub Tudruj on 23/02/2017. // Copyright © 2017 Jakub Tudruj. All rights reserved. // import Foundation import Alamofire import ObjectMapper open class SweetCherryConfig: SweetCherryConfigurable { public static let shared = SweetCherryConfig() public var url: String? public var standardHeaders: HTTPHeaders? public var authHeaders: HTTPHeaders? public var logger: SweetCherryLoggable? public var validResponse: SweetCherryValidResponseConfigurable = ValidResponse() @available(*, deprecated: 2.0, message: "Don't use this anymore. Use mainCompletion: ((Result<Mappable>, DataResponse<Any>) -> () instead") public var mainSuccess: ((DataResponse<Any>) -> ())? @available(*, deprecated: 2.0, message: "Don't use this anymore. Use mainCompletion: ((Result<Mappable>, DataResponse<Any>) -> () instead") public var mainFailure: SweetCherry.FailureHandler? public var mainCompletion: SweetCherry.CompletionHandler<Mappable>? public func register(logger: SweetCherryLoggable) { self.logger = logger } private init() { /* makes SweetCherryLogger as default */ logger = SweetCherryLogger() } //TODO: as struct(?) internal class ValidResponse: SweetCherryValidResponseConfigurable { var statusCodes = Array(200..<300) var contentType = ["application/json"] //TODO: one from array & everything from array (closure like array filter?) var jsonContainsKeyValuePairs: [String: Any]? var jsonContainsKeys: [String]? } }
mit
48d2600149a6c7a2802c35bab580eb78
30.980769
143
0.683704
4.751429
false
true
false
false
Tyrant2013/LeetCodePractice
LeetCodePractice/Easy/38_Count_And_Say.swift
1
1218
// // Count_And_Say.swift // LeetCodePractice // // Created by 庄晓伟 on 2018/2/11. // Copyright © 2018年 Zhuang Xiaowei. All rights reserved. // import UIKit class Count_And_Say: Solution { override func ExampleTest() { [ 1, 2, 3, 4, 5, 6, 7, ].forEach { num in print("num: \(num), res: \(self.countAndSay(num))") } } func countAndSay(_ n: Int) -> String { var countDown = n - 1 var numArr = [1] while countDown > 0 { var countNum = numArr.first! var count = 0 var res = [Int]() for index in 0..<numArr.count { if countNum == numArr[index] { count += 1 } else { res.append(count) res.append(countNum) countNum = numArr[index] count = 1 } } res.append(count) res.append(countNum) numArr = res countDown -= 1 } return numArr.map({ String($0) }).joined() } }
mit
287821756da026fd654fefeb359f2b95
21.811321
63
0.411084
4.183391
false
false
false
false
a736220388/FinestFood
FinestFood/FinestFood/classes/Mine/homePage/controllers/MineViewController.swift
1
11633
// // MineViewController.swift // FinestFood // // Created by qianfeng on 16/8/16. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class MineViewController: HomeTarbarViewController { private var tbView:UITableView? lazy var postArray = NSMutableArray() lazy var listArray = NSMutableArray() var isLogined = false var selectPostBtn = false var userInfoModel: UserInfoModel?{ didSet{ tbView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navigationController?.navigationBarHidden = true createTableView() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBarHidden = true tbView?.reloadData() } func createTableView(){ tbView = UITableView(frame: CGRectMake(0, -20, kScreenWidth, kScreenHeight - 49 + 20), style: .Plain) view.addSubview(tbView!) tbView?.delegate = self tbView?.dataSource = self tbView?.scrollEnabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //下载用户Post信息 func downloadUserPostData(){ let urlString = String(format: UserInfoListUrl, limit,offset) let downloader = MyDownloader() downloader.downloadWithUrlString(urlString) downloader.didFailWithError = { error in print(error) } downloader.didFinishWithData = { [weak self] data in let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) if jsonData.isKindOfClass(NSDictionary.self){ let dict = jsonData as! Dictionary<String,AnyObject> let dataDict = dict["data"] as! Dictionary<String,AnyObject> let listArray = dataDict["favorite_lists"] as! Array<Dictionary<String,AnyObject>> for list in listArray{ let model = MineUserListModel() model.setValuesForKeysWithDictionary(list) self!.listArray.addObject(model) } dispatch_async(dispatch_get_main_queue(), { self!.tbView?.reloadData() print("listArray = \(self?.listArray.count)") }) } } } func downloadUserListData(){ let urlString = String(format: UserInfoPostUrl, limit,offset) let downloader = MyDownloader() downloader.downloadWithUrlString(urlString) print(urlString) downloader.didFailWithError = { error in print(error) } downloader.didFinishWithData = { [weak self] data in let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) if jsonData.isKindOfClass(NSDictionary.self){ let dict = jsonData as! Dictionary<String,AnyObject> let dataDict = dict["data"] as! Dictionary<String,AnyObject> let postsArray = dataDict["favorite_lists"] as! Array<Dictionary<String,AnyObject>> for post in postsArray{ let model = FSFoodListModel() model.setValuesForKeysWithDictionary(post) self!.postArray.addObject(model) } dispatch_async(dispatch_get_main_queue(), { print("postarray = \(self?.postArray.count)") self!.tbView?.reloadData() }) } } } } extension MineViewController:UITableViewDelegate,UITableViewDataSource{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 && self.isLogined == true && self.selectPostBtn == false && self.postArray.count > 0{ return self.postArray.count } return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0{ let cellId = "mineProfileCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? MineProfileCell if cell == nil{ cell = NSBundle.mainBundle().loadNibNamed("MineProfileCell", owner: nil, options: nil).first as? MineProfileCell } cell?.selectionStyle = .None cell?.delegate = self print(self.userInfoModel) if (self.userInfoModel != nil) { cell!.configModel(self.userInfoModel!) } return cell! }else{ if self.isLogined == false{ let cellId = "mineListCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? MineProfileCell if cell == nil{ cell = NSBundle.mainBundle().loadNibNamed("MineProfileCell", owner: nil, options: nil).last as? MineProfileCell } cell?.selectionStyle = .None cell?.delegate = self return cell! }else if self.isLogined == true{ if self.selectPostBtn == true{ let cellId = "userListCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) if cell == nil { cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellId) } if self.postArray.count > 0{ let model = self.listArray[indexPath.row] as! FSFoodListModel let url = NSURL(string: model.cover_image_url!) cell?.imageView?.kf_setImageWithURL(url) cell?.textLabel?.text = model.title! cell?.detailTextLabel?.text = model.short_title! cell?.accessoryType = .DisclosureIndicator } return cell! }else if self.selectPostBtn == false{ let cellId = "userListCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) if cell == nil { cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellId) } if self.listArray.count>0{ let model = self.listArray[indexPath.row] as! MineUserListModel let url = NSURL(string: model.cover_image_url! as String) cell?.imageView?.kf_setImageWithURL(url) cell?.textLabel?.text = model.name! as String cell?.detailTextLabel?.text = "\(model.items_count!)个" } return cell! } } } return UITableViewCell() } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if isLogined == true && section == 1{ let view = UIView() view.backgroundColor = UIColor(white: 0.9, alpha: 1.0) if section == 1{ let detailBtn = UIButton() detailBtn.layer.borderWidth = 1 detailBtn.layer.borderColor = UIColor.blackColor().CGColor if selectPostBtn{ detailBtn.backgroundColor = UIColor.whiteColor() }else{ detailBtn.backgroundColor = UIColor.orangeColor() } detailBtn.setTitleColor(UIColor.blackColor(), forState: .Normal) detailBtn.setTitle("喜欢的专题", forState: .Normal) view.addSubview(detailBtn) detailBtn.snp_makeConstraints { (make) in make.bottom.left.equalTo(view) make.width.equalTo(kScreenWidth/2) make.top.equalTo(view).offset(5) } let commentBtn = UIButton() if selectPostBtn { commentBtn.backgroundColor = UIColor.orangeColor() }else{ commentBtn.backgroundColor = UIColor.whiteColor() } commentBtn.layer.borderWidth = 1 commentBtn.layer.borderColor = UIColor.blackColor().CGColor commentBtn.setTitle("喜欢的商品", forState: .Normal) commentBtn.setTitleColor(UIColor.blackColor(), forState: .Normal) view.addSubview(commentBtn) commentBtn.snp_makeConstraints { (make) in make.bottom.right.equalTo(view) make.width.equalTo(kScreenWidth/2) make.top.equalTo(view).offset(5) } detailBtn.tag = 550 commentBtn.tag = 551 detailBtn.addTarget(self, action: #selector(commentAction(_:)), forControlEvents: .TouchUpInside) commentBtn.addTarget(self, action: #selector(commentAction(_:)), forControlEvents: .TouchUpInside) } return view } return nil } func commentAction(btn:UIButton){ if btn.tag == 550{ btn.backgroundColor = UIColor.orangeColor() let btn1 = btn.superview?.viewWithTag(551) as! UIButton btn1.backgroundColor = UIColor.whiteColor() selectPostBtn = false }else if btn.tag == 551{ btn.backgroundColor = UIColor.orangeColor() let btn1 = btn.superview?.viewWithTag(550) as! UIButton btn1.backgroundColor = UIColor.whiteColor() selectPostBtn = true } tbView?.reloadData() } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0{ return 250 }else if indexPath.section == 1 && isLogined == true && selectPostBtn == false{ return 50 } return 350 } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 0{ return 20 } return 0 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if isLogined == true && section == 1{ return 40 } return 0 } } extension MineViewController:MineProfileCellDelegate{ func convertBtnSelectedWith(btn: UIButton, withType type: String) { if type == "setting"{ let mineSettingCtrl = MineSettingViewController() self.navigationController?.pushViewController(mineSettingCtrl, animated: true) }else if type == "login"{ let loginCtrl = MineLoginViewController() self.navigationController?.pushViewController(loginCtrl, animated: true) loginCtrl.convertUserInfoClosure = { [weak self] model in self!.userInfoModel = model self?.isLogined = true self?.downloadUserListData() self?.downloadUserPostData() } } } }
mit
fdcc91e6dabd7446bc982e4214d8251e
40.120567
131
0.563125
5.416161
false
false
false
false
RandalliLama/CorpDirectory
Corp Directory/Corp Directory/RequestFactory.swift
1
6071
// // RequestFactory.swift // Proto1 // // Created by Rich Randall on 10/3/14. // Copyright (c) 2014 Rich Randall. All rights reserved. // import Foundation private var _requestFactory : RequestFactory? class RequestFactory { class func sharedRequestFactory() -> RequestFactory? { return _requestFactory } class func setSharedRequestFactory(requestFactory: RequestFactory) { _requestFactory = requestFactory } private func createRequest(url: String, completionBlock: (NSURLRequest?)->()) { Token.instance.getToken({(success, token) in if !success { NSLog("Failed to acquire token") completionBlock(nil) return } NSLog("Creating request for: \(url)") let urlObject = NSURL(string: url) let request = NSMutableURLRequest(URL: urlObject) completionBlock(request) }) } var managedObjectStore: RKManagedObjectStore? private var baseUrl: String init(baseUrl: String) { self.baseUrl = baseUrl setupRestKit() AADUser.setupObjectMapping(self.managedObjectStore!) } private func setupNSManagedObjectModel() -> NSManagedObjectModel { var bundle = NSBundle.mainBundle() var resourcePath = bundle.pathForResource("Corp_Directory", ofType: "momd")! var modelURL = NSURL.fileURLWithPath(resourcePath)! var managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL).mutableCopy() as NSManagedObjectModel var entities = managedObjectModel.entitiesByName var userEntity = entities["AADUser"] as NSEntityDescription var className = NSStringFromClass(AADUser) userEntity.managedObjectClassName = className return managedObjectModel } private func setupObjectManager() { var route = RestKitBridge.createRouteWithType(AADUser.self as NSObject.Type, pathPattern: "/:tenant/users", method: RKRequestMethod.GET) var objectManager = RKObjectManager(baseURL: NSURL(string: "https://graph.windows.net")) RKObjectManager.setSharedManager(objectManager) objectManager.router.routeSet.addRoute(route) objectManager.managedObjectStore = self.managedObjectStore } private func setupRestKit() { var error : NSError? var managedObjectModel = self.setupNSManagedObjectModel() self.managedObjectStore = RKManagedObjectStore(managedObjectModel: managedObjectModel) self.managedObjectStore?.createPersistentStoreCoordinator() self.managedObjectStore?.addInMemoryPersistentStore(&error) self.managedObjectStore?.createManagedObjectContexts() self.managedObjectStore?.managedObjectCache = RKInMemoryManagedObjectCache(managedObjectContext: self.managedObjectStore?.mainQueueManagedObjectContext) RKManagedObjectStore.setDefaultStore(managedObjectStore) setupObjectManager() } func fetchObjectsAtUrl(path: String, parameters: Dictionary<String,String>) { var request : NSMutableURLRequest = RKObjectManager.sharedManager().requestWithObject(AADUser.self, method: RKRequestMethod.GET, path: path, parameters: parameters) Token.instance.getToken({(success: Bool, token: String?) in request.setValue(token!, forHTTPHeaderField: "Authorization") var operation = RKObjectManager.sharedManager().managedObjectRequestOperationWithRequest( request, managedObjectContext: self.managedObjectStore!.mainQueueManagedObjectContext, success: {(op: RKObjectRequestOperation?, result: RKMappingResult?) in }, failure: {(op: RKObjectRequestOperation?, error: NSError?) in }) NSOperationQueue.currentQueue()?.addOperation(operation) }) } func getFetchedResultsControllerForType(type: NSObject.Type) -> NSFetchedResultsController { var typeName = NSStringFromClass(type) var entityName = typeName.componentsSeparatedByString(".")[1] var managedObjectContext = self.managedObjectStore!.mainQueueManagedObjectContext let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: managedObjectContext) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "displayName", ascending: false) let sortDescriptors = [sortDescriptor] fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") return fetchedResultsController } func getThumbnail(imageView: UIImageView, objectId: String, parameters: Dictionary<String, String>, completionBlock: () -> ()) { Token.instance.getToken({(success: Bool, token: String?) in var url = NSURL(string: "https://graph.windows.net/\(Token.instance.tenant)/users/\(objectId)/thumbnailPhoto") var request = NSMutableURLRequest(URL: url) request.setValue(token!, forHTTPHeaderField: "Authorization") imageView.setImageWithURLRequest( request, placeholderImage: nil, success: {(urlRequest: NSURLRequest?, urlResponse: NSHTTPURLResponse?, image: UIImage?) in NSLog("image download success") }, failure: {(urlRequest: NSURLRequest?, urlResponse: NSHTTPURLResponse?, error: NSError?) in NSLog("image download failure") } ) }) } }
apache-2.0
3595ccc83881f73da1cc03367339ccf2
39.211921
184
0.686048
5.700469
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPConstant.swift
1
8628
// // KPConstant.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/4/10. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import Foundation import UIKit import BenzeneFoundation struct KPAnalyticsEvent { static let ads_click = "ads_click" // 紀錄點開來的店相關的屬性(可以知道哪間店被點開次數最多/評分,透過哪個管道)--> 知道從哪一頁點進去的 Map/List/Search/Profile static let cell_click = "cell_click" // 頁面 static let page_event = "page_event" // 按鈕 static let button_click = "button_click" } struct KPAnalyticsEventProperty { static let name = "name" static let source = "source" static let store_name = "store_name" static let store_rate = "store_rate" } struct KPAnalyticsEventValue { static let unknown = "unknown" struct source { static let source_list = "list" static let source_map = "map" static let source_search = "search" static let source_profile = "profile" static let source_recommend = "recommend" } struct page { static let list_page = "list_page" static let map_page = "map_page" static let detail_page = "datail_page" static let search_page = "search_page" static let profile_page = "profile_page" static let setting_page = "setting_page" static let aboutus_page = "aboutus_page" } struct button { // Main static let main_menu_button = "main_menu_button" static let main_filter_button = "main_filter_button" static let main_fast_filter_button = "main_fast_filter_button" static let main_switch_mode_button = "main_switch_mode_button" static let main_search_button = "main_search_button" static let list_add_store_button = "list_add_store_button" static let map_add_store_button = "map_add_store_button" static let map_navigation_button = "map_navigation_button" static let map_near_button = "map_near_button" // New static let new_send_button = "new_send_button" static let new_dismiss_button = "new_dismiss_button" // Store static let store_more_button = "store_more_button" static let store_favorite_button = "store_favorite_button" static let store_visit_button = "store_visit_button" static let store_rate_button = "store_rate_button" static let store_comment_button = "store_comment_button" static let store_streetview_button = "store_streetview_button" static let store_navigation_button = "store_navigation_button" // Quick Search static let quick_wifi_button = "quick_wifi_button" static let quick_socket_button = "quick_socket_button" static let quick_time_button = "quick_time_button" static let quick_open_button = "quick_open_button" static let quick_rate_button = "quick_rate_button" static let quick_clear_button = "quick_clear_button" // Search static let condition_search_button = "condition_search_button" } } struct KPNotification { struct information { static let commentInformation = "commentInformation" static let rateInformation = "rateInformation" static let photoInformation = "photoInformation" } } struct KPColorPalette { struct KPMainColor { static let mainColor_light = UIColor(hexString: "#c8955e") static let mainColor = UIColor(hexString: "#784d1f") static let mainColor_sub = UIColor(hexString: "#9f9426") static let statusBarColor = UIColor(hexString: "#784d1f") static let borderColor = UIColor(hexString: "#e6e6e6") static let starColor = UIColor(hexString: "#f9c816") static let warningColor = UIColor(hexString: "#FF4040") static let tempButtonCOlor = UIColor(hexString: "#4DA0D3") static let grayColor_level1 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 1.0) static let grayColor_level2 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.7) static let grayColor_level3 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.5) static let grayColor_level4 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.3) static let grayColor_level5 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.2) static let grayColor_level6 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.1) static let grayColor_level7 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.05) static let whiteColor_level1 = UIColor(hexString: "#ffffffaa") } struct KPTextColor { static let grayColor = UIColor(hexString: "#333333") static let mainColor_light = UIColor(hexString: "#c8955e") static let mainColor = UIColor(hexString: "#784d1f") static let mainColor_60 = UIColor(hexString: "#784d1f99") // static let mainColor_light = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.5) // static let mainColor = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.7) static let whiteColor = UIColor(hexString: "#ffffff") static let warningColor = UIColor(hexString: "#FF4040") static let default_placeholder = UIColor(hexString: "#C7C7CD") static let grayColor_level1 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 1.0) static let grayColor_level2 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.7) static let grayColor_level3 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.5) static let grayColor_level4 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.3) static let grayColor_level5 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.2) static let grayColor_level6 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.1) static let grayColor_level7 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.05) } struct KPBackgroundColor { static let mainColor_light = UIColor(hexString: "#c8955e") static let mainColor_light_10 = UIColor(hexString: "#784d1f20") static let mainColor = UIColor(hexString: "#784d1f") static let mainColor_60 = UIColor(hexString: "#784d1f99") static let mainColor_20 = UIColor(hexString: "#784d1f33") static let mainColor_sub = UIColor(hexString: "#9f9426") static let cellScoreBgColor = UIColor(hexString: "#9f9426") static let scoreButtonColor = UIColor(hexString: "#9f9426") static let disabledScoreButtonColor = UIColor(hexString: "#C8C488") static let exp_background = UIColor(rgbaHexValue: 0xffffff33) static let mainColor_ripple = UIColor(rgbaHexValue: 0xc8955eaa) static let grayColor_level2 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.7) static let grayColor_level3 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.5) static let grayColor_level4 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.3) static let grayColor_level5 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.2) static let grayColor_level6 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.1) static let grayColor_level7 = UIColor(r: 0.2, g: 0.2, b: 0.2, a: 0.05) } struct KPShopStatusColor { static let opened = UIColor(hexString: "#6dd551") static let closed = UIColor(hexString: "#f05e32") } struct KPTestHintColor { static let redHintColor = UIColor(hexString: "#ff0000") } } struct KPFactorConstant { struct KPSpacing { static let introSpacing: CGFloat = 2.4 } } struct AppConstant { static let introShownKey = "KPIntroHasShownKey" static let cancelLogInKey = "KPCancelLogInKey" static let userDefaultsSuitName = "kapi-userdefault" } extension UIDevice { var iPhone: Bool { return UIDevice().userInterfaceIdiom == .phone } var isCompact: Bool { let size = UIScreen.main.bounds.size return size.width < 600 || size.height < 600 } var isSuperCompact: Bool { let size = UIScreen.main.bounds.size return size.width < 350 || size.height < 350 } enum ScreenType: String { case iPhone4 case iPhone5 case iPhone6 case iPhone6Plus case unknown } var screenType: ScreenType { guard iPhone else { return .unknown } switch UIScreen.main.nativeBounds.height { case 960: return .iPhone4 case 1136: return .iPhone5 case 1334: return .iPhone6 case 2208: return .iPhone6Plus default: return .unknown } } }
mit
2dba077cafd2acf66ea20b3602b73554
36.056522
83
0.614807
3.46182
false
false
false
false
CM-Studio/NotLonely-iOS
NotLonely-iOS/ViewController/Home/HomeViewController.swift
1
3178
// // HomeViewController.swift // NotLonely-iOS // // Created by plusub on 3/24/16. // Copyright © 2016 cm. All rights reserved. // import UIKit class HomeViewController: BaseViewController { enum TabIndex : Int { case FirstChildTab = 0 case SecondChildTab = 1 } var i = 0 var frame = CGRectMake(0, 0, 0, 0) @IBOutlet weak var contentView: UIView! var currentViewController: UIViewController? lazy var activityVC: ActivityViewController? = { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ActivityViewController") as! ActivityViewController return vc }() lazy var circleVC: CircleViewController? = { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CircleViewController") as! CircleViewController return vc }() @IBOutlet weak var segmentedControl: UISegmentedControl! @IBAction func switchTabs(sender: AnyObject) { self.currentViewController!.view.removeFromSuperview() self.currentViewController!.removeFromParentViewController() displayCurrentTab(sender.selectedSegmentIndex) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. segmentedControl.selectedSegmentIndex = TabIndex.FirstChildTab.rawValue displayCurrentTab(TabIndex.FirstChildTab.rawValue) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if let currentViewController = currentViewController { currentViewController.viewWillDisappear(animated) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } func displayCurrentTab(tabIndex: Int){ if let vc = viewControllerForSelectedSegmentIndex(tabIndex) { self.addChildViewController(vc) vc.didMoveToParentViewController(self) vc.view.frame = self.contentView.bounds frame = self.contentView.bounds self.contentView.addSubview(vc.view) self.currentViewController = vc self.tabBarController!.view.setNeedsLayout() self.navigationController!.view.setNeedsLayout() } } func viewControllerForSelectedSegmentIndex(index: Int) -> UIViewController? { var vc: UIViewController? switch index { case TabIndex.FirstChildTab.rawValue : vc = activityVC case TabIndex.SecondChildTab.rawValue : vc = circleVC default: return nil } return vc } }
mit
bc760968ddc8c8af6da00198995a66fa
30.455446
126
0.657224
5.745027
false
false
false
false
griotspeak/Rational
Carthage/Checkouts/SwiftCheck/Tests/SimpleSpec.swift
1
1781
// // SimpleSpec.swift // SwiftCheck // // Created by Robert Widmann on 8/3/14. // Copyright (c) 2015 TypeLift. All rights reserved. // import SwiftCheck import XCTest public struct ArbitraryFoo { let x : Int let y : Int public static func create(x : Int) -> Int -> ArbitraryFoo { return { y in ArbitraryFoo(x: x, y: y) } } public var description : String { return "Arbitrary Foo!" } } extension ArbitraryFoo : Arbitrary { public static var arbitrary : Gen<ArbitraryFoo> { return ArbitraryFoo.create <^> Int.arbitrary <*> Int.arbitrary } } class SimpleSpec : XCTestCase { func testAll() { property("Integer Equality is Reflexive") <- forAll { (i : Int8) in return i == i } property("Unsigned Integer Equality is Reflexive") <- forAll { (i : UInt8) in return i == i } property("Float Equality is Reflexive") <- forAll { (i : Float) in return i == i } property("Double Equality is Reflexive") <- forAll { (i : Double) in return i == i } property("String Equality is Reflexive") <- forAll { (s : String) in return s == s } property("ArbitraryFoo Properties are Reflexive") <- forAll { (i : ArbitraryFoo) in return i.x == i.x && i.y == i.y } property("All generated Charaters are valid Unicode") <- forAll { (c : Character) in return (c >= ("\u{0000}" as Character) && c <= ("\u{D7FF}" as Character)) || (c >= ("\u{E000}" as Character) && c <= ("\u{10FFFF}" as Character)) } let inverses = Gen<((UInt8, UInt8) -> Bool, (UInt8, UInt8) -> Bool)>.fromElementsOf([ ((>), (<=)), ((<), (>=)), ((==), (!=)), ]) property("Inverses work") <- forAllNoShrink(inverses) { (op, iop) in return forAll { (x : UInt8, y : UInt8) in return op(x, y) ==== !iop(x, y) } } } }
mit
7598b4c5581f03aec4e9165eb3e2e682
22.12987
87
0.599102
3.086655
false
false
false
false
RoverPlatform/rover-ios
Sources/Experiences/ExperienceConversionsManager.swift
1
1265
// // ExperienceConversionsManager.swift // RoverExperiences // // Created by Chris Recalis on 2020-06-25. // Copyright © 2020 Rover Labs Inc. All rights reserved. // import Foundation import os.log #if !COCOAPODS import RoverFoundation import RoverData #endif class ExperienceConversionsManager: ConversionsContextProvider { private let persistedConversions = PersistedValue<Set<Tag>>(storageKey: "io.rover.RoverExperiences.conversions") var conversions: [String]? { return self.persistedConversions.value?.filter{ $0.expiresAt > Date() }.map{ $0.rawValue } } func track(_ tag: String, _ expiresIn: TimeInterval) { var result = (self.persistedConversions.value ?? []).filter { $0.expiresAt > Date() } result.update(with: Tag( rawValue: tag, expiresAt: Date().addingTimeInterval(expiresIn) )) self.persistedConversions.value = result } } private struct Tag: Codable, Equatable, Hashable { public static func == (lhs: Tag, rhs: Tag) -> Bool { return lhs.rawValue == rhs.rawValue } public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } public var rawValue: String public var expiresAt: Date = Date() }
apache-2.0
24ccbff0d606353c85b9510ff5e2d6e1
29.095238
116
0.670886
4.213333
false
false
false
false
carabina/DDMathParser
MathParser/Operator.swift
2
1375
// // Operator.swift // DDMathParser // // Created by Dave DeLong on 8/7/15. // // import Foundation public class Operator: Equatable { public enum Arity { case Unary case Binary } public enum Associativity { case Left case Right } public let function: String public let arity: Arity public let associativity: Associativity public internal(set) var tokens: Set<String> public internal(set) var precedence: Int? public init(function: String, arity: Arity, associativity: Associativity, tokens: Set<String> = []) { self.function = function self.arity = arity self.associativity = associativity self.tokens = tokens } } extension Operator: CustomStringConvertible { public var description: String { let tokenInfo = tokens.joinWithSeparator(", ") let arityInfo = arity == .Unary ? "Unary" : "Binary" let assocInfo = associativity == .Left ? "Left" : "Right" let precedenceInfo = precedence?.description ?? "UNKNOWN" return "{[\(tokenInfo)] -> \(function)(), \(arityInfo) \(assocInfo), precedence: \(precedenceInfo)}" } } public func ==(lhs: Operator, rhs: Operator) -> Bool { return lhs.arity == rhs.arity && lhs.associativity == rhs.associativity && lhs.function == rhs.function }
mit
9d9ffb8a48563ccb087b56ec878d17eb
25.960784
108
0.626909
4.407051
false
false
false
false
alexanderedge/AlamofireImage
Source/Request+AlamofireImage.swift
1
9516
// Request+AlamofireImage.swift // // Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation #if os(iOS) import UIKit #elseif os(watchOS) import UIKit import WatchKit #elseif os(OSX) import Cocoa #endif extension Request { /// The completion handler closure used when an image response serializer completes. public typealias CompletionHandler = (NSURLRequest?, NSHTTPURLResponse?, Result<Image>) -> Void // MARK: - iOS and watchOS #if os(iOS) || os(watchOS) /** Creates a response serializer that returns an image initialized from the response data using the specified image options. - parameter imageScale: The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. `Screen.scale` by default. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. `true` by default. - returns: An image response serializer. */ public class func imageResponseSerializer( imageScale imageScale: CGFloat = Request.imageScale, inflateResponseImage: Bool = true) -> GenericResponseSerializer<UIImage> { return GenericResponseSerializer { request, response, data in guard let validData = data where validData.length > 0 else { return .Failure(data, Request.imageDataError()) } guard Request.validateResponse(request, response: response) else { return .Failure(data, Request.contentTypeValidationError()) } do { let image = try Request.imageFromResponseData(validData, imageScale: imageScale) if inflateResponseImage { image.af_inflate() } return .Success(image) } catch { return .Failure(data, error) } } } /** Adds a handler to be called once the request has finished. - parameter imageScale: The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. `Screen.scale` by default. - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. `true` by default. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the image, if one could be created from the URL response and data, and any error produced while creating the image. - returns: The request. */ public func responseImage( imageScale: CGFloat = Request.imageScale, inflateResponseImage: Bool = true, completionHandler: CompletionHandler) -> Self { return response( responseSerializer: Request.imageResponseSerializer( imageScale: imageScale, inflateResponseImage: inflateResponseImage ), completionHandler: completionHandler ) } private class func imageFromResponseData(data: NSData, imageScale: CGFloat) throws -> UIImage { if let image = UIImage(data: data, scale: imageScale) { return image } throw imageDataError() } private class var imageScale: CGFloat { #if os(iOS) return UIScreen.mainScreen().scale #elseif os(watchOS) return WKInterfaceDevice.currentDevice().screenScale #endif } #elseif os(OSX) // MARK: - OSX /** Creates a response serializer that returns an image initialized from the response data. - returns: An image response serializer. */ public class func imageResponseSerializer() -> GenericResponseSerializer<NSImage> { return GenericResponseSerializer { request, response, data in guard let validData = data where validData.length > 0 else { return .Failure(data, Request.imageDataError()) } guard Request.validateResponse(response) else { return .Failure(data, Request.contentTypeValidationError()) } guard let bitmapImage = NSBitmapImageRep(data: validData) else { return .Failure(data, Request.imageDataError()) } let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) image.addRepresentation(bitmapImage) return .Success(image) } } /** Adds a handler to be called once the request has finished. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the image, if one could be created from the URL response and data, and any error produced while creating the image. - returns: The request. */ public func responseImage(completionHandler: CompletionHandler) -> Self { return response( responseSerializer: Request.imageResponseSerializer(), completionHandler: completionHandler ) } #endif // MARK: - Private - Shared Helper Methods private class func validateResponse(request: NSURLRequest?, response: NSHTTPURLResponse?) -> Bool { // allow file URLs to pass validation if let url = request?.URL where url.fileURL == true { return true } let acceptableContentTypes: Set<String> = [ "image/tiff", "image/jpeg", "image/gif", "image/png", "image/ico", "image/x-icon", "image/bmp", "image/x-bmp", "image/x-xbitmap", "image/x-win-bitmap" ] if let mimeType = response?.MIMEType where acceptableContentTypes.contains(mimeType) { return true } return false } private class func contentTypeValidationError() -> NSError { let failureReason = "Failed to validate response due to unacceptable content type" return Error.errorWithCode(NSURLErrorCannotDecodeContentData, failureReason: failureReason) } private class func imageDataError() -> NSError { let failureReason = "Failed to create a valid Image from the response data" return Error.errorWithCode(NSURLErrorCannotDecodeContentData, failureReason: failureReason) } }
mit
3982f09f3028dabd570520f7f7326cea
41.672646
121
0.611812
5.711885
false
false
false
false
johnno1962d/swift
test/IDE/complete_operators.swift
3
14457
// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_1 | FileCheck %s -check-prefix=POSTFIX_1 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_2 > %t // RUN: FileCheck %s -check-prefix=POSTFIX_2 < %t // RUN: FileCheck %s -check-prefix=NEGATIVE_POSTFIX_2 < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_3 | FileCheck %s -check-prefix=POSTFIX_3 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_4 | FileCheck %s -check-prefix=POSTFIX_4 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_5 | FileCheck %s -check-prefix=POSTFIX_5 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_6 | FileCheck %s -check-prefix=POSTFIX_6 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_7 | FileCheck %s -check-prefix=POSTFIX_7 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_8 | FileCheck %s -check-prefix=POSTFIX_8 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_9 | FileCheck %s -check-prefix=POSTFIX_9 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=POSTFIX_10 | FileCheck %s -check-prefix=POSTFIX_10 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=S_POSTFIX_SPACE | FileCheck %s -check-prefix=S_POSTFIX_SPACE // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_1 > %t // RUN: FileCheck %s -check-prefix=S2_INFIX < %t // RUN: FileCheck %s -check-prefix=NEGATIVE_S2_INFIX < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_2 > %t // RUN: FileCheck %s -check-prefix=S2_INFIX_LVALUE < %t // RUN: FileCheck %s -check-prefix=NEGATIVE_S2_INFIX_LVALUE < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_3 | FileCheck %s -check-prefix=S2_INFIX_LVALUE // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_4 | FileCheck %s -check-prefix=S2_INFIX // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_5 | FileCheck %s -check-prefix=S2_INFIX // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_6 | FileCheck %s -check-prefix=S2_INFIX // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_7 > %t // RUN: FileCheck %s -check-prefix=S2_INFIX_OPTIONAL < %t // RUN: FileCheck %s -check-prefix=NEGATIVE_S2_INFIX_OPTIONAL < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_8 | FileCheck %s -check-prefix=S3_INFIX_OPTIONAL // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_9 | FileCheck %s -check-prefix=FOOABLE_INFIX // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_10 | FileCheck %s -check-prefix=FOOABLE_INFIX // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_11 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_12 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_13 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_14 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_15 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_16 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_17 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_18 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_19 | FileCheck %s -check-prefix=EMPTYCLASS_INFIX // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_20 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_21 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_22 | FileCheck %s -check-prefix=NO_OPERATORS // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=S2_INFIX_SPACE | FileCheck %s -check-prefix=S2_INFIX_SPACE // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=EXT_INFIX_1 | FileCheck %s -check-prefix=S2_INFIX // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=EXT_INFIX_2 > %t.ext_infix_2 // RUN: FileCheck %s -check-prefix=S4_EXT_INFIX < %t.ext_infix_2 // RUN: FileCheck %s -check-prefix=S4_EXT_INFIX_NEG < %t.ext_infix_2 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=EXT_INFIX_3 | FileCheck %s -check-prefix=S4_EXT_INFIX_SIMPLE // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=EXT_INFIX_4 | FileCheck %s -check-prefix=S4_EXT_INFIX_SIMPLE // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=ASSIGN_TUPLE_1| FileCheck %s -check-prefix=ASSIGN_TUPLE_1 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=ASSIGN_TUPLE_2| FileCheck %s -check-prefix=ASSIGN_TUPLE_2 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=ASSIGN_TUPLE_3| FileCheck %s -check-prefix=ASSIGN_TUPLE_1 struct S {} postfix operator ++ {} postfix func ++(x: inout S) -> S { return x } func testPostfix1(x: S) { x#^POSTFIX_1^# } // POSTFIX_1-NOT: ++ func testPostfix2(x: inout S) { x#^POSTFIX_2^# } // POSTFIX_2: Begin completions // POSTFIX_2-DAG: Decl[PostfixOperatorFunction]/CurrModule: ++[#S#] // POSTFIX_2: End completions // NEGATIVE_POSTFIX_2-NOT: -- postfix operator +- {} postfix func +-(x: S) -> S? { return x } func testPostfix3(x: S) { x#^POSTFIX_3^# } // POSTFIX_3: Decl[PostfixOperatorFunction]/CurrModule: +-[#S?#] func testPostfix4(x: S?) { x#^POSTFIX_4^# } // POSTFIX_4: Pattern/None: ![#S#] struct T {} postfix func +-<G>(x: [G]) -> G { return x! } func testPostfix5(x: [T]) { x#^POSTFIX_5^# } // POSTFIX_5: Decl[PostfixOperatorFunction]/CurrModule: +-[#T#] protocol Fooable {} extension Int : Fooable {} extension Double : Fooable {} postfix operator *** {} postfix func ***<G: Fooable>(x: G) -> G { return x } func testPostfix6() { 1 + 2 * 3#^POSTFIX_6^# } // POSTFIX_6: Decl[PostfixOperatorFunction]/CurrModule: ***[#Int#] func testPostfix7() { 1 + 2 * 3.0#^POSTFIX_7^# } // POSTFIX_7: Decl[PostfixOperatorFunction]/CurrModule: ***[#Double#] func testPostfix8(x: S) { x#^POSTFIX_8^# } // POSTFIX_8-NOT: *** protocol P { associatedtype T func foo() -> T } func testPostfix9<G: P where G.T == Int>(x: G) { x.foo()#^POSTFIX_9^# } // POSTFIX_9: Decl[PostfixOperatorFunction]/CurrModule: ***[#Int#] func testPostfix10<G: P where G.T : Fooable>(x: G) { x.foo()#^POSTFIX_10^# } // POSTFIX_10: Decl[PostfixOperatorFunction]/CurrModule: ***[#G.T#] func testPostfixSpace(x: inout S) { x #^S_POSTFIX_SPACE^# } // S_POSTFIX_SPACE: Decl[PostfixOperatorFunction]/CurrModule/Erase[1]: ++[#S#] // ===--- Infix operators struct S2 {} infix operator ** { associativity left precedence 123 } infix operator **= { associativity none precedence 123 } func +(x: S2, y: S2) -> S2 { return x } func **(x: S2, y: Int) -> S2 { return x } func **=(x: inout S2, y: Int) -> Void { return x } func testInfix1(x: S2) { x#^INFIX_1^# } // S2_INFIX: Begin completions // FIXME: rdar://problem/22997089 - should be CurrModule // S2_INFIX-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: + {#S2#}[#S2#] // S2_INFIX-DAG: Decl[InfixOperatorFunction]/CurrModule: ** {#Int#}[#S2#]; name=** // S2_INFIX: End completions // NEGATIVE_S2_INFIX-NOT: **= // NEGATIVE_S2_INFIX-NOT: += // NEGATIVE_S2_INFIX-NOT: \* {#Int#} // NEGATIVE_S2_INFIX-NOT: ?? // NEGATIVE_S2_INFIX-NOT: ~= // NEGATIVE_S2_INFIX-NOT: ~> // NEGATIVE_S2_INFIX-NOT: = {# func testInfix2(x: inout S2) { x#^INFIX_2^# } // S2_INFIX_LVALUE: Begin completions // FIXME: rdar://problem/22997089 - should be CurrModule // S2_INFIX_LVALUE-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: + {#S2#}[#S2#] // S2_INFIX_LVALUE-DAG: Decl[InfixOperatorFunction]/CurrModule: ** {#Int#}[#S2#] // S2_INFIX_LVALUE-DAG: Decl[InfixOperatorFunction]/CurrModule: **= {#Int#}[#Void#] // S2_INFIX_LVALUE-DAG: Pattern/None: = {#S2#}[#Void#] // S2_INFIX_LVALUE: End completions // NEGATIVE_S2_INFIX_LVALUE-NOT: += // NEGATIVE_S2_INFIX_LVALUE-NOT: \* {#Int#} // NEGATIVE_S2_INFIX_LVALUE-NOT: ?? // NEGATIVE_S2_INFIX_LVALUE-NOT: ~= // NEGATIVE_S2_INFIX_LVALUE-NOT: ~> func testInfix3(x: inout S2) { x#^INFIX_3^# } func testInfix4() { S2()#^INFIX_4^# } func testInfix5() { (S2() + S2())#^INFIX_5^# } func testInfix6<T: P where T.T == S2>(x: T) { x.foo()#^INFIX_6^# } func testInfix7(x: S2?) { x#^INFIX_7^# } // S2_INFIX_OPTIONAL: Begin completions // FIXME: rdar://problem/22996887 - shouldn't complete with optional LHS // S2_INFIX_OPTIONAL-DAG: Decl[InfixOperatorFunction]/CurrModule: ** {#Int#}[#S2#] // S2_INFIX_OPTIONAL-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: != {#{{.*}}#}[#Bool#] // S2_INFIX_OPTIONAL-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: == {#{{.*}}#}[#Bool#] // S2_INFIX_OPTIONAL-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: ?? {#S2#}[#S2#]; name=?? S2 // S2_INFIX_OPTIONAL: End completions // The equality operators don't come from equatable. // NEGATIVE_S2_INFIX_OPTIONAL-NOT: == {#S2 struct S3: Equatable {} func ==(x: S3, y: S3) -> Bool { return true } func !=(x: S3, y: S3) -> Bool { return false} func testInfix8(x: S3?) { x#^INFIX_8^# } // The equality operators come from equatable. // S3_INFIX_OPTIONAL: Begin completions // S3_INFIX_OPTIONAL-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: != {#S3?#}[#Bool#] // S3_INFIX_OPTIONAL-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: == {#S3?#}[#Bool#] // S3_INFIX_OPTIONAL: End completions infix operator **** { associativity left precedence 123 } func ****<T: Fooable>(x: T, y: T) -> T { return x } func testInfix9<T: P where T.T: Fooable>(x: T) { x.foo()#^INFIX_9^# } // FOOABLE_INFIX: Decl[InfixOperatorFunction]/CurrModule: **** {#T.T#}[#T.T#] func testInfix10<T: P where T.T: Fooable>(x: T) { (x.foo() **** x.foo())#^INFIX_10^# } func testInfix11() { S2#^INFIX_11^# } // NO_OPERATORS-NOT: Decl[InfixOperatorFunction] func testInfix12() { P#^INFIX_12^# } func testInfix13() { P.foo#^INFIX_13^# } func testInfix14() { P.T#^INFIX_14^# } func testInfix15<T: P where T.T == S2>() { T#^INFIX_15^# } func testInfix16<T: P where T.T == S2>() { T.foo#^INFIX_16^# } func testInfix17(x: Void) { x#^INFIX_17^# } func testInfix18(x: (S2, S2) { x#^INFIX_18^# } class EmptyClass {} func testInfix19(x: EmptyClass) { x#^INFIX_19^# } // EMPTYCLASS_INFIX: Begin completions // EMPTYCLASS_INFIX-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: === {#AnyObject?#}[#Bool#] // EMPTYCLASS_INFIX-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: !== {#AnyObject?#}[#Bool#] // EMPTYCLASS_INFIX: End completions enum E { case A case B(S2) } func testInfix20(x: E) { x#^INFIX_20^# } func testInfix21() { E.A#^INFIX_21^# } func testInfix22() { E.B#^INFIX_22^# } func testSpace(x: S2) { x #^S2_INFIX_SPACE^# } // S2_INFIX_SPACE: Begin completions // S2_INFIX_SPACE-DAG: Decl[InfixOperatorFunction]/CurrModule: [' ']** {#Int#}[#S2#] // S2_INFIX_SPACE-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: [' ']+ {#S2#}[#S2#] // S2_INFIX_SPACE: End completions func testExtInfix1(x: inout S2) { x + S2() + x + S2() + x + S2() + x#^EXT_INFIX_1^# } struct S4 {} func +(x: S4, y: S4) -> S4 { return x } func ==(x: S4, y: S4) -> Bool { return true } infix operator +++ { associativity left precedence 1 } func +++(x: S4, y: S4) -> S4 { return x } infix operator &&& { associativity left precedence 255 } func &&&(x: Bool, y: Bool) -> S4 { return x } func testExtInfix2(x: S4) { x + x == x + x#^EXT_INFIX_2^# } // S4_EXT_INFIX: Begin completions // S4_EXT_INFIX-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: != {#Bool#}[#Bool#] // S4_EXT_INFIX-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: + {#S4#}[#S4#] // S4_EXT_INFIX-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: == {#Bool#}[#Bool#] // S4_EXT_INFIX-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: && {#Bool#}[#Bool#] // S4_EXT_INFIX-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: || {#Bool#}[#Bool#] // S4_EXT_INFIX: End completions // S4_EXT_INFIX_NEG-NOT: +++ // S4_EXT_INFIX_NEG-NOT: &&& func testExtInfix3(x: S4) { x + x#^EXT_INFIX_3^# } // S4_EXT_INFIX_SIMPLE: Begin completions // S4_EXT_INFIX_SIMPLE-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: + {#S4#}[#S4#] // S4_EXT_INFIX_SIMPLE-DAG: Decl[InfixOperatorFunction]/CurrModule: +++ {#S4#}[#S4#] // S4_EXT_INFIX_SIMPLE: End completions func testExtInfix4(x: S4) { 1 + 1.0 + x#^EXT_INFIX_4^# } func testAssignTuple1() { ()#^ASSIGN_TUPLE_1^# } func testAssignTuple3() { func void() {} void()#^ASSIGN_TUPLE_3^# } // FIXME: technically this is sometimes legal, but we would need to // differentiate between cases like () = and print() =. Since it's not very // useful anyway, just omit the completion. // ASSIGN_TUPLE_1-NOT: Pattern/None: = { func testAssignTuple2() { var x: S2 var y: S2 (x, y)#^ASSIGN_TUPLE_2^# } // ASSIGN_TUPLE_2: Pattern/None: = {#(S2, S2)#}[#Void#];
apache-2.0
da9807b1197bf0986e9fbf4c8c1319e9
39.047091
151
0.68472
2.847548
false
true
false
false
SunLiner/Floral
Floral/Floral/Classes/Malls/Malls/Model/MallsGoods.swift
1
1270
// // MallsGoods.swift // Floral // // Created by 孙林 on 16/5/12. // Copyright © 2016年 ALin. All rights reserved. // 商城选项卡中的商品, 和精选中的不一样 // 应该是属于商品类别, 每个类别里面包含着商品 import UIKit class MallsGoods: NSObject { // 分类描述信息 var fnDesc : String? // 分类id var fnId : String? // 分类的 var fnName : String? // 商品列表 var goodsList : [Goods]? init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forKey key: String) { if key == "childrenList" { // 取出商品列表 let list = value as! [[String : AnyObject]] ALinLog(value) var goodses = [Goods]() for dict in list { // 遍历数组 // 取出商品详情 let pgoods = dict["pGoods"] as! [String:AnyObject] goodses.append(Goods(dict: pgoods)) } goodsList = goodses return } super.setValue(value, forKey: key) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } }
mit
962ed6b17c87ed677dbe4c559bd98f8c
22.978723
76
0.54126
3.707237
false
false
false
false
philipgreat/b2b-swift-app
B2BSimpleApp/B2BSimpleApp/LevelNCat.swift
1
1899
//Domain B2B/LevelNCat/ import Foundation import ObjectMapper //Use this to generate Object import SwiftyJSON //Use this to verify the JSON Object struct LevelNCat{ var id : String? var parentCat : LevelThreeCat? var displayName : String? var version : Int? var productList : [Product]? init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } static var CLASS_VERSION = "1" //This value is for serializer like message pack to identify the versions match between //local and remote object. } extension LevelNCat: Mappable{ //Confirming to the protocol Mappable of ObjectMapper //Reference on https://github.com/Hearst-DD/ObjectMapper/ init?(_ map: Map){ } mutating func mapping(map: Map) { //Map each field to json fields id <- map["id"] parentCat <- map["parentCat"] displayName <- map["displayName"] version <- map["version"] productList <- map["productList"] } } extension LevelNCat:CustomStringConvertible{ //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). var result = "level_n_cat{"; if id != nil { result += "\tid='\(id!)'" } if parentCat != nil { result += "\tparent_cat='\(parentCat!)'" } if displayName != nil { result += "\tdisplay_name='\(displayName!)'" } if version != nil { result += "\tversion='\(version!)'" } result += "}" return result } }
mit
c8136e174c0f8b413fc4c7cff1165773
21.7375
100
0.584518
3.760396
false
false
false
false
kesun421/firefox-ios
Client/Frontend/Widgets/AutocompleteTextField.swift
3
11012
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // This code is loosely based on https://github.com/Antol/APAutocompleteTextField import UIKit import Shared /// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate, /// callers must use this instead. protocol AutocompleteTextFieldDelegate: class { func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String) func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldDidBeginEditing(_ autocompleteTextField: AutocompleteTextField) } struct AutocompleteTextFieldUX { static let HighlightColor = UIColor(rgb: 0xccdded) } class AutocompleteTextField: UITextField, UITextFieldDelegate { var autocompleteDelegate: AutocompleteTextFieldDelegate? // AutocompleteTextLabel repersents the actual autocomplete text. // The textfields "text" property only contains the entered text, while this label holds the autocomplete text // This makes sure that the autocomplete doesnt mess with keyboard suggestions provided by third party keyboards. private var autocompleteTextLabel: UILabel? private var hideCursor: Bool = false var isSelectionActive: Bool { return autocompleteTextLabel != nil } // This variable is a solution to get the right behavior for refocusing // the AutocompleteTextField. The initial transition into Overlay Mode // doesn't involve the user interacting with AutocompleteTextField. // Thus, we update shouldApplyCompletion in touchesBegin() to reflect whether // the highlight is active and then the text field is updated accordingly // in touchesEnd() (eg. applyCompletion() is called or not) fileprivate var notifyTextChanged: (() -> Void)? private var lastReplacement: String? var highlightColor = AutocompleteTextFieldUX.HighlightColor override var text: String? { didSet { super.text = text self.textDidChange(self) } } override var accessibilityValue: String? { get { return (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "") } set(value) { super.accessibilityValue = value } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { super.delegate = self super.addTarget(self, action: #selector(AutocompleteTextField.textDidChange(_:)), for: UIControlEvents.editingChanged) notifyTextChanged = debounce(0.1, action: { if self.isEditing { self.autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.normalizeString(self.text ?? "")) } }) } override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: .init(rawValue: 0), action: #selector(self.handleKeyCommand(sender:))), UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: .init(rawValue: 0), action: #selector(self.handleKeyCommand(sender:))) ] } func handleKeyCommand(sender: UIKeyCommand) { switch sender.input { case UIKeyInputLeftArrow: if isSelectionActive { applyCompletion() // Set the current position to the beginning of the text. selectedTextRange = textRange(from: beginningOfDocument, to: beginningOfDocument) } else if let range = selectedTextRange { if range.start == beginningOfDocument { return } guard let cursorPosition = position(from: range.start, offset: -1) else { return } selectedTextRange = textRange(from: cursorPosition, to: cursorPosition) } return case UIKeyInputRightArrow: if isSelectionActive { applyCompletion() // Set the current position to the end of the text. selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } else if let range = selectedTextRange { if range.end == endOfDocument { return } guard let cursorPosition = position(from: range.end, offset: 1) else { return } selectedTextRange = textRange(from: cursorPosition, to: cursorPosition) } return default: return } } func highlightAll() { let text = self.text self.text = "" setAutocompleteSuggestion(text ?? "") selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } fileprivate func normalizeString(_ string: String) -> String { return string.lowercased().stringByTrimmingLeadingCharactersInSet(CharacterSet.whitespaces) } /// Commits the completion by setting the text and removing the highlight. fileprivate func applyCompletion() { // Clear the current completion, then set the text without the attributed style. let text = (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "") removeCompletion() self.text = text hideCursor = false // Move the cursor to the end of the completion. selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } /// Removes the autocomplete-highlighted fileprivate func removeCompletion() { autocompleteTextLabel?.removeFromSuperview() autocompleteTextLabel = nil } // `shouldChangeCharactersInRange` is called before the text changes, and textDidChange is called after. // Since the text has changed, remove the completion here, and textDidChange will fire the callback to // get the new autocompletion. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { lastReplacement = string return true } func setAutocompleteSuggestion(_ suggestion: String?) { let text = self.text ?? "" guard let suggestion = suggestion, isEditing && markedTextRange == nil else { hideCursor = false return } let normalized = normalizeString(text) guard suggestion.startsWith(normalized) && normalized.characters.count < suggestion.characters.count else { hideCursor = false return } let suggestionText = suggestion.substring(from: suggestion.characters.index(suggestion.startIndex, offsetBy: normalized.characters.count)) let autocompleteText = NSMutableAttributedString(string: suggestionText) autocompleteText.addAttribute(NSBackgroundColorAttributeName, value: highlightColor, range: NSRange(location: 0, length: suggestionText.characters.count)) autocompleteTextLabel?.removeFromSuperview() // should be nil. But just in case autocompleteTextLabel = createAutocompleteLabelWith(autocompleteText) if let l = autocompleteTextLabel { addSubview(l) hideCursor = true forceResetCursor() } } override func caretRect(for position: UITextPosition) -> CGRect { return hideCursor ? CGRect.zero : super.caretRect(for: position) } private func createAutocompleteLabelWith(_ autocompleteText: NSAttributedString) -> UILabel { let label = UILabel() var frame = self.bounds label.attributedText = autocompleteText label.font = self.font label.accessibilityIdentifier = "autocomplete" label.backgroundColor = self.backgroundColor label.textColor = self.textColor let enteredTextSize = self.attributedText?.boundingRect(with: self.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil) frame.origin.x = (enteredTextSize?.width.rounded() ?? 0) frame.size.width = self.frame.size.width - frame.origin.x frame.size.height = self.frame.size.height - 1 label.frame = frame return label } func textFieldDidBeginEditing(_ textField: UITextField) { autocompleteDelegate?.autocompleteTextFieldDidBeginEditing(self) } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { applyCompletion() return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { applyCompletion() return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true } func textFieldShouldClear(_ textField: UITextField) -> Bool { removeCompletion() return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true } override func setMarkedText(_ markedText: String?, selectedRange: NSRange) { // Clear the autocompletion if any provisionally inserted text has been // entered (e.g., a partial composition from a Japanese keyboard). removeCompletion() super.setMarkedText(markedText, selectedRange: selectedRange) } func textDidChange(_ textField: UITextField) { hideCursor = autocompleteTextLabel != nil removeCompletion() let isAtEnd = selectedTextRange?.start == endOfDocument let isEmpty = lastReplacement?.isEmpty ?? true if !isEmpty, isAtEnd, markedTextRange == nil { notifyTextChanged?() } else { hideCursor = false } } // Reset the cursor to the end of the text field. // This forces `caretRect(for position: UITextPosition)` to be called which will decide if we should show the cursor // This exists because ` caretRect(for position: UITextPosition)` is not called after we apply an autocompletion. private func forceResetCursor() { selectedTextRange = nil selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } override func deleteBackward() { lastReplacement = nil hideCursor = false if isSelectionActive { removeCompletion() forceResetCursor() } else { super.deleteBackward() } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { applyCompletion() super.touchesBegan(touches, with: event) } }
mpl-2.0
8473a3f637da73e845e24d96fbb1fd75
38.328571
162
0.659735
5.550403
false
false
false
false
wjk/MacBond
MacBond/Bond+Arrays.swift
1
13852
// // Bond+Arrays.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 // MARK: - Vector Dynamic // MARK: Array Bond public class ArrayBond<T>: Bond<Array<T>> { public var insertListener: (([Int]) -> Void)? public var removeListener: (([Int], [T]) -> Void)? public var updateListener: (([Int]) -> Void)? override public init() { super.init() } public init(insertListener: (([Int]) -> Void)?, removeListener: (([Int], [T]) -> Void)?, updateListener: (([Int]) -> Void)?) { self.insertListener = insertListener self.removeListener = removeListener self.updateListener = updateListener super.init() } override public func bind(dynamic: Dynamic<Array<T>>, fire: Bool = false) { super.bind(dynamic, fire: fire) } } // MARK: Dynamic array public class DynamicArray<T>: Dynamic<Array<T>>, SequenceType { public typealias Element = T public typealias Generator = DynamicArrayGenerator<T> public override init(_ v: Array<T>) { super.init(v) } public var count: Int { return value.count } public var capacity: Int { return value.capacity } public var isEmpty: Bool { return value.isEmpty } public var first: T? { return value.first } public var last: T? { return value.last } public func append(newElement: T) { value.append(newElement) dispatchInsertion([value.count-1]) } public func append(array: Array<T>) { if array.count > 0 { let count = value.count value += array dispatchInsertion(Array(count..<value.count)) } } public func removeLast() -> T { let last = value.removeLast() dispatchRemoval([value.count], objects: [last]) return last } public func insert(newElement: T, atIndex i: Int) { value.insert(newElement, atIndex: i) dispatchInsertion([i]) } public func splice(array: Array<T>, atIndex i: Int) { if array.count > 0 { value.splice(array, atIndex: i) dispatchInsertion(Array(i..<i+array.count)) } } public func removeAtIndex(index: Int) -> T { let object = value.removeAtIndex(index) dispatchRemoval([index], objects: [object]) return object } public func removeAll(keepCapacity: Bool) { let copy = value value.removeAll(keepCapacity: keepCapacity) dispatchRemoval(Array<Int>(0..<copy.count), objects: copy) } public subscript(index: Int) -> T { get { return value[index] } set(newObject) { value[index] = newObject if index == value.count { dispatchInsertion([index]) } else { dispatchUpdate([index]) } } } public func generate() -> DynamicArrayGenerator<T> { return DynamicArrayGenerator<T>(array: self) } private func dispatchInsertion(indices: [Int]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.insertListener?(indices) } } } private func dispatchRemoval(indices: [Int], objects: [T]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.removeListener?(indices, objects) } } } private func dispatchUpdate(indices: [Int]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.updateListener?(indices) } } } } public struct DynamicArrayGenerator<T>: GeneratorType { private var index = -1 private let array: DynamicArray<T> init(array: DynamicArray<T>) { self.array = array } typealias Element = T public mutating func next() -> T? { index++ return index < array.count ? array[index] : nil } } // MARK: Dynamic Array Map Proxy public class DynamicArrayMapProxy<T, U>: DynamicArray<U> { private unowned var sourceArray: DynamicArray<T> private var mapf: T -> U private let bond: ArrayBond<T> public init(sourceArray: DynamicArray<T>, mapf: T -> U) { self.sourceArray = sourceArray self.mapf = mapf self.bond = ArrayBond<T>() self.bond.bind(sourceArray, fire: false) super.init([]) bond.insertListener = { [unowned self] i in self.dispatchInsertion(i) } bond.removeListener = { [unowned self] i, o in self.dispatchRemoval(i, objects: o.map(mapf)) } bond.updateListener = { [unowned self] i in self.dispatchUpdate(i) } } override public var value: Array<U> { get { return sourceArray.value.map(mapf) } set { // not supported } } override public var count: Int { return sourceArray.count } override public var capacity: Int { return sourceArray.capacity } override public var isEmpty: Bool { return sourceArray.isEmpty } override public var first: U? { if let first = sourceArray.first { return mapf(first) } else { return nil } } override public var last: U? { if let last = sourceArray.last { return mapf(last) } else { return nil } } override public func append(newElement: U) { fatalError("Modifying proxy array is not supported!") } public override func append(array: Array<U>) { fatalError("Modifying proxy array is not supported!") } override public func removeLast() -> U { fatalError("Modifying proxy array is not supported!") } override public func insert(newElement: U, atIndex i: Int) { fatalError("Modifying proxy array is not supported!") } public override func splice(array: Array<U>, atIndex i: Int) { fatalError("Modifying proxy array is not supported!") } override public func removeAtIndex(index: Int) -> U { fatalError("Modifying proxy array is not supported!") } override public func removeAll(keepCapacity: Bool) { fatalError("Modifying proxy array is not supported!") } override public subscript(index: Int) -> U { get { return mapf(sourceArray[index]) } set(newObject) { fatalError("Modifying proxy array is not supported!") } } } // MARK: Dynamic Array Filter Proxy public class DynamicArrayFilterProxy<T>: DynamicArray<T> { private unowned var sourceArray: DynamicArray<T> private var positions: [Int] private var filterf: T -> Bool private let bond: ArrayBond<T> public init(sourceArray: DynamicArray<T>, filterf: T -> Bool) { self.sourceArray = sourceArray self.filterf = filterf self.bond = ArrayBond<T>() self.bond.bind(sourceArray, fire: false) self.positions = Array<Int>(count: sourceArray.count, repeatedValue: -1) super.init([]) var newValue = Array<T>() for idx in 0..<sourceArray.count { let element = sourceArray[idx] if filterf(element) { positions[idx] = newValue.count newValue.append(element) } } value = newValue bond.insertListener = { [unowned self] indices in var mappedIndices: [Int] = [] for idx in indices { self.positions.insert(-1, atIndex: idx) } for idx in indices { let element = self.sourceArray[idx] if filterf(element) { // find position where to insert element to var pos = -1 for var i = idx; i >= 0 && pos < 0; i-- { pos = self.positions[i] } pos += 1 // insert element self.value.insert(element, atIndex: pos) mappedIndices.append(pos) // update positions self.positions[idx] = pos for var i = idx + 1; i < self.positions.count; i++ { if self.positions[i] >= 0 { self.positions[i]++ } } } } if mappedIndices.count > 0 { self.dispatchInsertion(mappedIndices) } } bond.removeListener = { [unowned self] indices, objects in var mappedIndices: [Int] = [] var mappedObjects: [T] = [] for idx in indices { var pos = self.positions[idx] if pos >= 0 { self.value.removeAtIndex(pos) mappedIndices.append(pos) } self.positions.removeAtIndex(idx) for var i = idx; i < self.positions.count; i++ { if self.positions[i] >= 0 { self.positions[i]-- } } } if mappedIndices.count > 0 { self.dispatchRemoval(mappedIndices, objects: objects.filter(filterf)) } } bond.updateListener = { [unowned self] indices in var mappedIndices: [Int] = [] var mappedInsertionIndices: [Int] = [] var mappedRemovalIndices: [Int] = [] var mappedRemovalObjects: [T] = [] for idx in indices { let element = self.sourceArray[idx] var pos = self.positions[idx] if filterf(element) { if pos >= 0 { self.value[pos] = element mappedIndices.append(pos) } else { for var i = idx; i >= 0 && pos < 0; i-- { pos = self.positions[i] } pos += 1 // insert element self.value.insert(element, atIndex: pos) mappedInsertionIndices.append(pos) // update positions self.positions[idx] = pos for var i = idx + 1; i < self.positions.count; i++ { if self.positions[i] >= 0 { self.positions[i]++ } } } } else { if pos >= 0 { mappedRemovalIndices.append(pos) mappedRemovalObjects.append(element) self.value.removeAtIndex(pos) // update positions self.positions[idx] = -1 for var i = idx + 1; i < self.positions.count; i++ { if self.positions[i] >= 0 { self.positions[i]-- } } } } } if mappedIndices.count > 0 { self.dispatchUpdate(mappedIndices) } if mappedInsertionIndices.count > 0 { self.dispatchInsertion(mappedInsertionIndices) } if mappedRemovalIndices.count > 0 { self.dispatchRemoval(mappedRemovalIndices, objects: mappedRemovalObjects) } } } override public func append(newElement: T) { fatalError("Modifying proxy array is not supported!") } public override func append(array: Array<T>) { fatalError("Modifying proxy array is not supported!") } override public func removeLast() -> T { fatalError("Modifying proxy array is not supported!") } override public func insert(newElement: T, atIndex i: Int) { fatalError("Modifying proxy array is not supported!") } public override func splice(array: Array<T>, atIndex i: Int) { fatalError("Modifying proxy array is not supported!") } override public func removeAtIndex(index: Int) -> T { fatalError("Modifying proxy array is not supported!") } override public func removeAll(keepCapacity: Bool) { fatalError("Modifying proxy array is not supported!") } override public subscript(index: Int) -> T { get { return super[index] } set { fatalError("Modifying proxy array is not supported!") } } private override func dispatchInsertion(indices: [Int]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.insertListener?(indices) } } } private override func dispatchRemoval(indices: [Int], objects: [T]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.removeListener?(indices, objects) } } } override private func dispatchUpdate(indices: [Int]) { for bondBox in bonds { if let arrayBond = bondBox.bond as? ArrayBond { arrayBond.updateListener?(indices) } } } } // MARK: Dynamic Array additions public extension DynamicArray { public func map<U>(f: T -> U) -> DynamicArrayMapProxy<T, U> { return _map(self, f) } public func filter(f: T -> Bool) -> DynamicArray<T> { return _filter(self, f) } } // MARK: Map public func _map<T, U>(dynamicArray: DynamicArray<T>, f: T -> U) -> DynamicArrayMapProxy<T, U> { return DynamicArrayMapProxy(sourceArray: dynamicArray, mapf: f) } // MARK: Filter private func _filter<T>(dynamicArray: DynamicArray<T>, f: T -> Bool) -> DynamicArray<T> { return DynamicArrayFilterProxy(sourceArray: dynamicArray, filterf: f) }
mit
2a8b957171f5be6d9687ef7993d5acd3
25.185255
128
0.607133
4.098225
false
false
false
false
wdkk/CAIM
Metal/caimmetal04/CAIM/CAIMUtil.swift
29
3354
// // CAIMUtil.swift // CAIM Project // https://kengolab.net/CreApp/wiki/ // // Copyright (c) Watanabe-DENKI Inc. // https://wdkk.co.jp/ // // This software is released under the MIT License. // https://opensource.org/licenses/mit-license.php // import Foundation import UIKit // init()を必ず持つようにするためのプロトコル protocol Initializable { init() } public class CAIM { // バンドル画像のパスを返す public static func bundle(_ file_path:String) -> String { let path:String! = Bundle.main.resourcePath return (path! + "/" + file_path) } // 現在のシステム時間のmsを返す public static var now:Int64 { var now_time:timeval = timeval() var tzp:timezone = timezone() gettimeofday(&now_time, &tzp) return (Int64(now_time.tv_sec) * 1000 + Int64(now_time.tv_usec) / 1000) } // 秒間のFPSを計測する(ループ内で使う) public static func fps() { struct variables { static var is_started:Bool = false static var time_span:Int64 = 0 static var fps:UInt32 = 0 } if (!variables.is_started) { variables.is_started = true variables.time_span = CAIM.now variables.fps = 0 } let dt:Int64 = CAIM.now - variables.time_span if (dt >= 1000) { print("CAIM: \(variables.fps)(fps)") variables.time_span = CAIM.now variables.fps = 0 } variables.fps += 1 } // ランダム値の計算 public static func random(_ max:Float=1.0) -> Float { return Float(arc4random() % 1000) / 1000.0 * max } public static func random(_ max:Int32) -> Float { return Float(arc4random() % 1000) / 1000.0 * Float(max) } public static func random(_ max:Int) -> Float { return Float(arc4random() % 1000) / 1000.0 * Float(max) } // スクリーンサイズの取得 public static var screenPointSize:CGSize { return UIScreen.main.bounds.size } // スクリーンピクセルサイズの取得 public static var screenPixelSize:CGSize { let sc:CGFloat = UIScreen.main.scale let size:CGSize = UIScreen.main.bounds.size let wid = size.width * sc let hgt = size.height * sc return CGSize(width:wid, height:hgt) } // スクリーンサイズの取得 public static var screenPointRect:CGRect { return UIScreen.main.bounds } // スクリーンピクセルサイズの取得 public static var screenPixelRect:CGRect { let sc:CGFloat = UIScreen.main.scale let rc:CGRect = UIScreen.main.bounds let wid = rc.width * sc let hgt = rc.height * sc return CGRect(x:0, y:0, width:wid, height:hgt) } } public extension Float { var toRadian:Float { return self * Float.pi / 180.0 } var toDegree:Float { return self * 180.0 / Float.pi } } public extension Double { var toRadian:Double { return self * Double.pi / 180.0 } var toDegree:Double { return self * 180.0 / Double.pi } } public extension Int { var toRadian:Float { return Float(self) * Float.pi / 180.0 } var toDegree:Float { return Float(self) * 180.0 / Float.pi } }
mit
295df345df5ff80d7263814ee9ae0b34
27.054054
111
0.594091
3.53462
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Models/Shepard/Shepard.swift
1
23224
// // Shepard.swift // MEGameTracker // // Created by Emily Ivie on 7/19/15. // Copyright © 2015 urdnot. All rights reserved. // import UIKit // swiftlint:disable file_length public struct Shepard: Codable, Photographical, PhotoEditable { enum CodingKeys: String, CodingKey { case uuid case gameSequenceUuid case gameVersion case gender case appearance case name case duplicationCount case origin case reputation case classTalent = "class" case isLegendary case level case paragon case renegade case photo case loveInterestId } // MARK: Constants public static let DefaultSurname = "Shepard" // MARK: Properties public var rawData: Data? // transient public var id: UUID { return uuid } public internal(set) var uuid: UUID /// (GameModifying Protocol) /// This value's game identifier. public var gameSequenceUuid: UUID /// (DateModifiable Protocol) /// Date when value was created. public var createdDate = Date() /// (DateModifiable Protocol) /// Date when value was last changed. public var modifiedDate = Date() /// (CloudDataStorable Protocol) /// Flag for whether the local object has changes not saved to the cloud. public var isSavedToCloud = false /// (CloudDataStorable Protocol) /// A set of any changes to the local object since the last cloud sync. public var pendingCloudChanges = CodableDictionary() /// (CloudDataStorable Protocol) /// A copy of the last cloud kit record. public var lastRecordData: Data? public private(set) var gameVersion: GameVersion public private(set) var duplicationCount = 1 public private(set) var gender = Gender.male public private(set) var name = Name.defaultMaleName public private(set) var photo: Photo? public private(set) var appearance: Appearance public private(set) var origin = Origin.earthborn public private(set) var reputation = Reputation.soleSurvivor public private(set) var classTalent = ClassTalent.soldier public private(set) var isLegendary = false public private(set) var loveInterestId: String? public private(set) var level: Int = 1 public private(set) var paragon: Int = 0 public private(set) var renegade: Int = 0 // Interface Builder public var isDummyData = false // MARK: Computed Properties public var title: String { return "\(origin.stringValue) \(reputation.stringValue) \(classTalent.stringValue)" } public var fullName: String { return "\(name.stringValue!) Shepard" + (duplicationCount > 1 ? " \(duplicationCount)" : "") } public var photoFileNameIdentifier: String { return Shepard.getPhotoFileNameIdentifier(uuid: uuid) } public static func getPhotoFileNameIdentifier(uuid: UUID) -> String { return "MyShepardPhoto\(uuid.uuidString)" } // MARK: Change Listeners And Change Status Flags public var isNew: Bool = false /// (DateModifiable) Flag to indicate that there are changes pending a core data sync. public var hasUnsavedChanges = false /// Don't use this. Use App.onCurrentShepardChange instead. public static let onChange = Signal<(id: String, object: Shepard)>() // MARK: Initialization /// Created by App public init( gameSequenceUuid: UUID, uuid: UUID = UUID(), gender: Shepard.Gender = .male, gameVersion: GameVersion = .game1 ) { self.uuid = uuid self.gameSequenceUuid = gameSequenceUuid self.gender = gender self.gameVersion = gameVersion appearance = Appearance(gameVersion: Shepard.Appearance.gameVersion(isLegendary: isLegendary, gameVersion: gameVersion)) photo = DefaultPhoto(gender: .male, gameVersion: gameVersion).photo markChanged() } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) uuid = try container.decode(UUID.self, forKey: .uuid) gameSequenceUuid = try container.decode(UUID.self, forKey: .gameSequenceUuid) gameVersion = try container.decode(GameVersion.self, forKey: .gameVersion) gender = try container.decode(Shepard.Gender.self, forKey: .gender) isLegendary = try container.decodeIfPresent(Bool.self, forKey: .isLegendary) ?? false let appearanceGameVersion = Shepard.Appearance.gameVersion(isLegendary: isLegendary, gameVersion: gameVersion) if let appearanceString = try container.decodeIfPresent(String.self, forKey: .appearance) { appearance = Appearance(appearanceString, fromGame: appearanceGameVersion, withGender: gender) } else { appearance = Appearance(gameVersion: appearanceGameVersion) } let nameString = try container.decode(String.self, forKey: .name) name = Shepard.Name(name: nameString, gender: gender) ?? name duplicationCount = try container.decodeIfPresent(Int.self, forKey: .duplicationCount) ?? duplicationCount origin = try container.decode(Shepard.Origin.self, forKey: .origin) reputation = try container.decode(Shepard.Reputation.self, forKey: .reputation) classTalent = try container.decode(Shepard.ClassTalent.self, forKey: .classTalent) level = (try container.decodeIfPresent(Int.self, forKey: .level)) ?? level paragon = (try container.decodeIfPresent(Int.self, forKey: .paragon)) ?? paragon renegade = (try container.decodeIfPresent(Int.self, forKey: .renegade)) ?? renegade if let photoPath = try container.decodeIfPresent(String.self, forKey: .photo), let photo = Photo(filePath: photoPath) { self.photo = photo } else { photo = DefaultPhoto(gender: gender, gameVersion: gameVersion).photo } loveInterestId = try container.decodeIfPresent(String.self, forKey: .loveInterestId) try unserializeDateModifiableData(decoder: decoder) try unserializeLocalCloudData(decoder: decoder) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(uuid, forKey: .uuid) try container.encode(gameSequenceUuid, forKey: .gameSequenceUuid) try container.encode(gameVersion, forKey: .gameVersion) try container.encode(gender, forKey: .gender) try container.encode(appearance.format(), forKey: .appearance) try container.encode(name.stringValue, forKey: .name) try container.encode(duplicationCount, forKey: .duplicationCount) try container.encode(origin, forKey: .origin) try container.encode(reputation, forKey: .reputation) try container.encode(classTalent, forKey: .classTalent) try container.encode(isLegendary, forKey: .isLegendary) try container.encode(level, forKey: .level) try container.encode(paragon, forKey: .paragon) try container.encode(renegade, forKey: .renegade) try container.encode(photo?.isCustomSavedPhoto == true ? photo?.stringValue : nil, forKey: .photo) try container.encode(loveInterestId, forKey: .loveInterestId) try serializeDateModifiableData(encoder: encoder) try serializeLocalCloudData(encoder: encoder) } } // MARK: Retrieval Functions of Related Data extension Shepard { /// - Returns: Current Person love interest for the shepard and gameVersion public mutating func getLoveInterest() -> Person? { if let loveInterestId = self.loveInterestId { return Person.get(id: loveInterestId, gameVersion: gameVersion) } return nil } /// Notesable source data public func getNotes(completion: @escaping (([Note]) -> Void) = { _ in }) { DispatchQueue.global(qos: .background).async { completion(Note.getAll(identifyingObject: .shepard)) } } } // MARK: Basic Actions extension Shepard { /// - Returns: A new note object tied to this object public func newNote() -> Note { return Note(identifyingObject: .shepard) } } // MARK: Data Change Actions extension Shepard { /// **Warning**: this changes a lot of data and takes a long time /// Return a copy of this Shepard with gender changed public func changed( gender: Gender, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard gender != self.gender else { return self } var shepard = self shepard.gender = gender var cloudChanges: [String: Any?] = ["gender": gender == .male ? "M" : "F"] let gameVersion: GameVersion = shepard.gameVersion let loveInterest: Person? = shepard.getLoveInterest() switch gender { case .male: if shepard.name == .defaultFemaleName { shepard.name = .defaultMaleName cloudChanges["name"] = name.stringValue } if shepard.photo?.isCustomSavedPhoto != true { shepard.photo = DefaultPhoto(gender: gender, gameVersion: gameVersion).photo cloudChanges["photo"] = photo?.stringValue } shepard.appearance.gender = gender cloudChanges["appearance"] = shepard.appearance.format() if loveInterest?.isMaleLoveInterest != true { // pass to love interest method to handle other side effects shepard = shepard.changed(loveInterestId: nil, isSave: false, isNotify: false) cloudChanges["loveInterestId"] = nil } case .female: if shepard.name == .defaultMaleName { shepard.name = .defaultFemaleName cloudChanges["name"] = name.stringValue } if shepard.photo?.isCustomSavedPhoto != true { shepard.photo = DefaultPhoto(gender: gender, gameVersion: gameVersion).photo cloudChanges["photo"] = photo?.stringValue } shepard.appearance.gender = gender cloudChanges["appearance"] = shepard.appearance.format() if loveInterest?.isFemaleLoveInterest != true { // pass to love interest method to handle other side effects shepard = shepard.changed(loveInterestId: nil, isSave: false, isNotify: false) cloudChanges["loveInterestId"] = nil } } shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: cloudChanges ) return shepard } /// Return a copy of this Shepard with name changed public func changed( name: String?, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard name != self.name.stringValue else { return self } var shepard = self shepard.name = Name(name: name, gender: gender) ?? self.name shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["name": name] ) return shepard } /// PhotoEditable Protocol /// Return a copy of this Shepard with photo changed public func changed(photo: Photo) -> Shepard { return changed(photo: photo, isSave: true) } /// Return a copy of this Shepard with photo changed public func changed(photo: Photo, isSave: Bool) -> Shepard { return changed(photo: photo, isSave: isSave, isNotify: true) } /// Return a copy of this Shepard with photo changed public func changed( photo: Photo, isSave: Bool, isNotify: Bool ) -> Shepard { guard photo != self.photo else { return self } var shepard = self // We use old filename, so don't delete shepard.photo = photo shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["photo": photo.stringValue] ) return shepard } /// Return a copy of this Shepard with appearance changed public func changed( appearance: Appearance, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard appearance != self.appearance else { return self } var shepard = self shepard.appearance = appearance shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["appearance": appearance.format()] ) return shepard } /// Return a copy of this Shepard with origin changed public func changed( origin: Origin, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard origin != self.origin else { return self } var shepard = self shepard.origin = origin shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["origin": origin.stringValue] ) return shepard } /// Return a copy of this Shepard with reputation changed public func changed( reputation: Reputation, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard reputation != self.reputation else { return self } var shepard = self shepard.reputation = reputation shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["reputation": reputation.stringValue] ) return shepard } /// Return a copy of this Shepard with classTalent changed public func changed( class classTalent: ClassTalent, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard classTalent != self.classTalent else { return self } var shepard = self shepard.classTalent = classTalent shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["class": classTalent.stringValue] ) return shepard } /// Return a copy of this Shepard with isLegendary changed public func changed( isLegendary: Bool, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard isLegendary != self.isLegendary else { return self } var shepard = self shepard.isLegendary = isLegendary shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["isLegendary": isLegendary] ) return shepard } /// Return a copy of this Shepard with loveInterestId changed public func changed( loveInterestId: String?, isSave: Bool = true, isNotify: Bool = true, isCascadeChanges: EventDirection = .all ) -> Shepard { guard loveInterestId != self.loveInterestId else { return self } var shepard = self // cascade change to decision if isCascadeChanges != .none && !GamesDataBackup.current.isSyncing { if let loveInterestId = loveInterestId, let person = Person.get(id: loveInterestId), let decisionId = person.loveInterestDecisionId { // switch selected love interest _ = Decision.get(id: decisionId)?.changed( isSelected: true, isSave: isSave, isNotify: isNotify, isCascadeChanges: .none ) } else if loveInterestId == nil, let loveInterestId = self.loveInterestId, let person = Person.get(id: loveInterestId), let decisionId = person.loveInterestDecisionId { // erase unselected love interest _ = Decision.get(id: decisionId)?.changed( isSelected: false, isSave: isSave, isNotify: isNotify, isCascadeChanges: .none ) } } shepard.loveInterestId = loveInterestId shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["loveInterestId": loveInterestId] ) return shepard } /// Return a copy of this Shepard with level changed public func changed( level: Int, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard level != self.level else { return self } var shepard = self shepard.level = level shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["level": level] ) return shepard } /// Return a copy of this Shepard with paragon changed public func changed( paragon: Int, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard paragon != self.paragon else { return self } var shepard = self shepard.paragon = paragon shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["paragon": paragon] ) return shepard } /// Return a copy of this Shepard with renegade changed public func changed( renegade: Int, isSave: Bool = true, isNotify: Bool = true ) -> Shepard { guard renegade != self.renegade else { return self } var shepard = self shepard.renegade = renegade shepard.changeEffects( isSave: isSave, isNotify: isNotify, cloudChanges: ["renegade": renegade] ) return shepard } /// Return a copy of this Shepard with duplicationCount changed public func incrementDuplicationCount( isSave: Bool = true, isNotify: Bool = true ) -> Shepard { var shepard = self shepard.duplicationCount = duplicationCount + 1 shepard.changeEffects( isSave: isSave, isNotify: isNotify ) return shepard } /// Performs common behaviors after an object change private mutating func changeEffects( isSave: Bool = true, isNotify: Bool = true, cloudChanges: [String: Any?] = [:] ) { markChanged() notifySaveToCloud(fields: cloudChanges) if isSave { _ = saveAnyChanges(isAllowDelay: false) } if isNotify { Shepard.onChange.fire((id: uuid.uuidString, object: self)) } } mutating func restart(uuid: UUID, gameSequenceUuid: UUID) { self.uuid = uuid self.gameSequenceUuid = gameSequenceUuid loveInterestId = nil level = 0 paragon = 0 renegade = 0 rawData = nil hasUnsavedChanges = true } } // MARK: Dummy data for Interface Builder extension Shepard { public static func getDummy(json: String? = nil) -> Shepard? { // swiftlint:disable line_length let json = json ?? "{\"uuid\" : \"BC0D3009-3385-4132-851A-DF472CBF9EFD\",\"gameVersion\" : \"1\",\"paragon\" : 0,\"createdDate\" : \"2017-02-15 07:40:32\",\"level\" : 1,\"gameSequenceUuid\" : \"7BF05BF6-386A-4429-BC18-2A60F2D29519\",\"reputation\" : \"Sole Survivor\",\"renegade\" : 0,\"modifiedDate\" : \"2017-02-23 07:13:39\",\"origin\" : \"Earthborn\",\"isSavedToCloud\" : false,\"appearance\" : \"XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.X\",\"class\" : \"Soldier\",\"gender\" : \"F\",\"name\" : \"Xoe\"}" // swiftlint:enable line_length return try? defaultManager.decoder.decode(Shepard.self, from: json.data(using: .utf8)!) } } // MARK: Shared Data extension Shepard { public func getSharedData() -> [String: Any?] { var list: [String: Any?] = [:] list["gameVersion"] = gameVersion list["gender"] = gender list["name"] = name list["duplicationCount"] = duplicationCount list["origin"] = origin list["reputation"] = reputation list["class"] = classTalent list["isLegendary"] = isLegendary list["appearance"] = appearance list["photo"] = photo?.isCustomSavedPhoto == true ? photo : nil return list } /// Called by app when creating a new gameVersion of an existing shepard - copy over all the general shared choices. public mutating func setNewData(oldData: [String: Any?]) { setCommonData(oldData) // only do when converting to a new game version: if var oldAppearance = oldData["appearance"] as? Appearance { if (!isLegendary) { // appearance has to be converted to gameVersion let appearanceGameVersion = Shepard.Appearance.gameVersion(isLegendary: isLegendary, gameVersion: gameVersion) oldAppearance.convert(toGame: appearanceGameVersion) // TODO: immutable chained convert } appearance = oldAppearance } classTalent = (oldData["class"] as? ClassTalent) ?? classTalent photo = (oldData["photo"] as? Photo) ?? photo } public mutating func setCommonData(_ data: [String: Any?], isInternal: Bool = false) { // make sure to notify these changes to cloud var changed: [String: Any?] = [:] if let gender = data["gender"] as? Gender, gender != self.gender { self.gender = gender changed["gender"] = gender.stringValue } if let name = data["name"] as? Name, name != self.name { self.name = name changed["name"] = name.stringValue } if let duplicationCount = data["duplicationCount"] as? Int, duplicationCount != self.duplicationCount { self.duplicationCount = duplicationCount changed["duplicationCount"] = duplicationCount } if let origin = data["origin"] as? Origin, origin != self.origin { self.origin = origin changed["origin"] = origin.stringValue } if let reputation = data["reputation"] as? Reputation, reputation != self.reputation { self.reputation = reputation changed["reputation"] = reputation.stringValue } if let isLegendary = data["isLegendary"] as? Bool, isLegendary != self.isLegendary { self.isLegendary = isLegendary changed["isLegendary"] = isLegendary } if let photo = data["photo"] as? Photo, photo.isCustomSavedPhoto && self.photo?.isCustomSavedPhoto == false && photo != self.photo { // only do this if we aren't replacing a custom photo // or, if it is a gender change self.photo = photo changed["photo"] = photo.stringValue } if !isInternal && !changed.isEmpty { markChanged() notifySaveToCloud(fields: changed) } } } // MARK: DateModifiable extension Shepard: DateModifiable {} // MARK: Equatable extension Shepard: Equatable { public static func == (_ lhs: Shepard, _ rhs: Shepard) -> Bool { // not true equality, just same db row return lhs.uuid == rhs.uuid } } //// MARK: Hashable //extension Shepard: Hashable { // public var hashValue: Int { return uuid.hashValue } //} // swiftlint:enable file_length
mit
b3a33f1920925fa859f2cec9ae466ab3
36.1568
518
0.623649
4.472843
false
false
false
false
zimcherDev/ios
Zimcher/UIKit Objects/BaseViewController/TopTabbarViewController.swift
1
1501
// // TopTabbarViewController.swift // Zimcher // // Created by Tianhang Yang on 1/16/16. // Copyright © 2016 Zimcher. All rights reserved. // import UIKit class TopTabbarViewController: ZCViewController, TopTabbarDatasource, TopTabbarDelegate { private(set) var topTabbar:TopTabbar? override func viewDidLoad() { super.viewDidLoad() self.setUpTopTabbar() } private func setUpTopTabbar() { let topTabbarTemp = TopTabbar.init(frame: CGRectZero) self.topTabbar = topTabbarTemp self.topTabbar!.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.topTabbar!) self.topTabbar!.pinHeight() NSLayoutConstraint.pinSubView(self.topTabbar!, superView: self.view, topPin: false, botPin: false, leadingPin: true, trailingPin: true) let topPin = NSLayoutConstraint.init(item: self.topTabbar!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) topPin.active = true self.topTabbar!.datasource = self self.topTabbar!.delegate = self } //for overide purpose func numberOfItems() -> Int { return 0 } func topTabbar(topTabbar: TopTabbar, didSelectItemAtIndex index: Int) { } func topTabbar(topTabbar: TopTabbar, titleForItemAtIndex index: Int) -> String? { return "" } }
apache-2.0
56c4e621ab3a9ff906be68767198c8e4
30.25
230
0.679333
4.385965
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/Login/LoginPresenterTests.swift
1
9194
import EurofurenceApplication import EurofurenceModel import XCTest import XCTEurofurenceModel class LoginPresenterTests: XCTestCase { var context: LoginPresenterTestBuilder.Context! override func setUp() { super.setUp() context = LoginPresenterTestBuilder().build() } func testTheSceneFromTheFactoryIsReturned() { XCTAssertEqual(context.scene, context.loginSceneFactory.stubScene) } func testTheSceneIsToldToDisplayTheLoginTitle() { XCTAssertEqual(.login, context.loginSceneFactory.stubScene.capturedTitle) } func testTappingTheCancelButtonTellsDelegateLoginCancelled() { context.loginSceneFactory.stubScene.delegate?.loginSceneDidTapCancelButton() XCTAssertTrue(context.delegate.loginCancelled) } func testTheDelegateIsNotToldLoginCancelledUntilUserTapsButton() { XCTAssertFalse(context.delegate.loginCancelled) } func testTheLoginButtonIsDisabled() { context.loginSceneFactory.stubScene.delegate?.loginSceneWillAppear() XCTAssertTrue(context.loginSceneFactory.stubScene.loginButtonWasDisabled) } func testTheLoginButtonIsNotDisabledUntilTheSceneWillAppear() { XCTAssertFalse(context.loginSceneFactory.stubScene.loginButtonWasDisabled) } func testWhenSceneSuppliesAllDetailsTheLoginButtonIsEnabled() { context.updateRegistrationNumber("1") context.updateUsername("User") context.updatePassword("Password") XCTAssertTrue(context.loginSceneFactory.stubScene.loginButtonWasEnabled) } func testWhenSceneSuppliesAllDetailsWithoutRegistrationNumberTheLoginButtonShouldNotBeEnabled() { context.updateRegistrationNumber("") context.updateUsername("User") context.updatePassword("Password") XCTAssertFalse(context.loginSceneFactory.stubScene.loginButtonWasEnabled) } func testWhenSceneSuppliesAllDetailsWithInvalidRegistrationNumberTheLoginButtonShouldNotBeEnabled() { context.updateRegistrationNumber("?") context.updateUsername("User") context.updatePassword("Password") XCTAssertFalse(context.loginSceneFactory.stubScene.loginButtonWasEnabled) } func testWhenSceneSuppliesAllDetailsWithInvalidUsernameTheLoginButtonShouldNotBeEnabled() { context.updateRegistrationNumber("1") context.updateUsername("") context.updatePassword("Password") XCTAssertFalse(context.loginSceneFactory.stubScene.loginButtonWasEnabled) } func testWhenSceneSuppliesAllDetailsWithInvalidPasswordTheLoginButtonShouldNotBeEnabled() { context.updateRegistrationNumber("1") context.updateUsername("User") context.updatePassword("") XCTAssertFalse(context.loginSceneFactory.stubScene.loginButtonWasEnabled) } func testWhenSceneSuppliesAllDetailsWithInvalidPasswordTheLoginButtonShouldBeDisabled() { context.updateRegistrationNumber("1") context.updateUsername("User") context.loginSceneFactory.stubScene.loginButtonWasDisabled = false context.updatePassword("") XCTAssertTrue(context.loginSceneFactory.stubScene.loginButtonWasDisabled) } func testWhenSceneSuppliesAllDetailsWithPasswordEnteredLastTheLoginButtonNotBeDisabled() { context.updateRegistrationNumber("1") context.updateUsername("User") context.loginSceneFactory.stubScene.loginButtonWasDisabled = false context.updatePassword("Password") XCTAssertFalse(context.loginSceneFactory.stubScene.loginButtonWasDisabled) } func testWhenSceneSuppliesAllDetailsWithInvalidRegistrationNumberTheLoginButtonShouldBeDisabled() { context.updateUsername("User") context.updatePassword("Password") context.loginSceneFactory.stubScene.loginButtonWasDisabled = false context.updateRegistrationNumber("?") XCTAssertTrue(context.loginSceneFactory.stubScene.loginButtonWasDisabled) } func testWhenSceneSuppliesAllDetailsWithRegistrationNumberEnteredLastTheLoginButtonShouldNotBeDisabled() { context.updateUsername("User") context.updatePassword("Password") context.loginSceneFactory.stubScene.loginButtonWasDisabled = false context.updateRegistrationNumber("42") XCTAssertFalse(context.loginSceneFactory.stubScene.loginButtonWasDisabled) } func testWhenSceneSuppliesAllDetailsWithInvalidUsernameTheLoginButtonShouldBeDisabled() { context.updateRegistrationNumber("1") context.updatePassword("Password") context.loginSceneFactory.stubScene.loginButtonWasDisabled = false context.updateUsername("") XCTAssertTrue(context.loginSceneFactory.stubScene.loginButtonWasDisabled) } func testWhenSceneSuppliesAllDetailsWithUsernameEnteredLastTheLoginButtonShouldNotBeDisabled() { context.updateRegistrationNumber("1") context.updatePassword("Password") context.loginSceneFactory.stubScene.loginButtonWasDisabled = false context.updateUsername("User") XCTAssertFalse(context.loginSceneFactory.stubScene.loginButtonWasDisabled) } func testTappingLoginButtonTellsLoginServiceToPerformLoginWithEnteredValues() { let regNo = 1 let username = "User" let password = "Password" context.updateRegistrationNumber("\(regNo)") context.updateUsername(username) context.updatePassword(password) context.loginSceneFactory.stubScene.tapLoginButton() context.completeAlertPresentation() let actual: LoginArguments? = context.authenticationService.capturedRequest XCTAssertEqual(regNo, actual?.registrationNumber) XCTAssertEqual(username, actual?.username) XCTAssertEqual(password, actual?.password) } func testAlertWithLoggingInTitleDisplayedWhenLoginServiceBeginsLoginProcedure() { context.inputValidCredentials() context.tapLoginButton() XCTAssertEqual(.loggingIn, context.alertRouter.presentedAlertTitle) } func testTappingLoginButtonWaitsForAlertPresentationToFinishBeforeAskingServiceToLogin() { context.alertRouter.automaticallyPresentAlerts = false context.inputValidCredentials() context.tapLoginButton() XCTAssertNil(context.authenticationService.capturedRequest) } func testAlertWithLogginInDescriptionDisplayedWhenLoginServiceBeginsLoginProcedure() { context.inputValidCredentials() context.tapLoginButton() XCTAssertEqual(.loggingInDetail, context.alertRouter.presentedAlertMessage) } func testLoginServiceSucceedsWithLoginTellsAlertToDismiss() { context.inputValidCredentials() context.tapLoginButton() let alert = context.alertRouter.lastAlert context.simulateLoginSuccess() XCTAssertEqual(true, alert?.dismissed) } func testAlertNotDismissedBeforeServiceReturns() { context.inputValidCredentials() context.tapLoginButton() XCTAssertEqual(false, context.alertRouter.lastAlert?.dismissed) } func testLoginServiceFailsToLoginShowsAlertWithLoginErrorTitle() { context.inputValidCredentials() context.tapLoginButton() context.simulateLoginFailure() context.dismissLastAlert() XCTAssertEqual(.loginError, context.alertRouter.presentedAlertTitle) } func testLoginSucceedsDoesNotShowLoginFailedAlert() { context.inputValidCredentials() context.tapLoginButton() context.simulateLoginSuccess() context.dismissLastAlert() XCTAssertNotEqual(.loginError, context.alertRouter.presentedAlertTitle) } func testLoginErrorAlertIsNotShownUntilPreviousAlertIsDismissed() { context.inputValidCredentials() context.tapLoginButton() context.simulateLoginFailure() XCTAssertNotEqual(.loginError, context.alertRouter.presentedAlertTitle) } func testLoginServiceFailsToLoginShowsAlertWithLoginErrorDetail() { context.inputValidCredentials() context.tapLoginButton() context.simulateLoginFailure() context.dismissLastAlert() XCTAssertEqual(.loginErrorDetail, context.alertRouter.presentedAlertMessage) } func testLoginServiceFailsToLoginShowsAlertWithOKAction() { context.inputValidCredentials() context.tapLoginButton() context.simulateLoginFailure() context.dismissLastAlert() XCTAssertNotNil(context.alertRouter.capturedAction(title: "OK")) } func testLoginServiceSucceedsTellsDelegateLoginSucceeded() { context.inputValidCredentials() context.tapLoginButton() context.simulateLoginSuccess() context.dismissLastAlert() XCTAssertTrue(context.delegate.loginFinishedSuccessfully) } func testLoginServiceFailsDoesNotTellDelegateLoginSucceeded() { context.inputValidCredentials() context.tapLoginButton() context.simulateLoginFailure() context.dismissLastAlert() XCTAssertFalse(context.delegate.loginFinishedSuccessfully) } }
mit
152fabad57e274fb1cdbb8dc8cc53c28
35.339921
110
0.751686
5.430597
false
true
false
false
jjluebke/pigeon
Pigeon/Pigeon.swift
1
4708
// // Pigeon.swift // Pigeon // // Created by Jason Luebke on 4/29/15. // Copyright (c) 2015 Jason Luebke. All rights reserved. // import Foundation import CoreMotion class Pigeon: HardwareInterfaceDelegate { let host: String = "jasonluebke.local:3000" let flightControl: FlightController! var socket: SocketIOClient! var delegate: PigeonDelegate! var rssiTimer: NSTimer! var currentState: SystemState! var controlState: ControlType! var paramGetters = Dictionary<String, ParamGetter>() var paramSetters = Dictionary<String, ParamSetter>() init() { flightControl = FlightController() flightControl.delegate = self flightControl.setupPIDs() socket = SocketIOClient(socketURL: host) socket.connect() socket.on("connect", callback: self.connected) socket.on("getSystemStatus", callback: self.sendSystemStatus) socket.on("getParam", callback: self.getParam) socket.on("setParam", callback: self.setParam) socket.on("directControl", callback: flightControl.processInput) socket.on("armBoard", callback: flightControl.arm) socket.on("disarmBoard", callback: flightControl.disarm) currentState = SystemState.Disconnnected controlState = ControlType.Direct } /* -------------------------------------------------------------------- socket callbacks ------------------------------------------------------ -------------------------------------------------------------------- */ func connected (data: Array<AnyObject>, ack: SocketAckEmitter?) { delegate?.serviceConnected() } func sendSystemStatus (data: Array<AnyObject>, ack: SocketAckEmitter?) { self.sendSystemStatus() } func getParam (data: Array<AnyObject>, ack: SocketAckEmitter?) { let paramNames = data[0] as! Array<String> var paramCollection = Params() var getter: ParamGetter! for paramName in paramNames { getter = self.paramGetters[self.getParamClass(paramName)] if getter != nil { paramCollection += getter(self.getParamScope(paramName)) } } self.sendParam(paramCollection) } func setParam (data: Array<AnyObject>, ack: SocketAckEmitter?) { let params = data[0] as! Params var setter: ParamSetter! for (paramName, param) in params { setter = self.paramSetters[self.getParamClass(paramName)] if setter != nil { setter(self.getParamScope(paramName), param) } } } /* -------------------------------------------------------------------- emitters -------------------------------------------------------------- -------------------------------------------------------------------- */ func sendParam (params: Params) { socket?.emit("receivedParams", params) } func sendSystemStatus () { socket?.emit("systemStatus", ["armed": flightControl.gyroStable]) } func sendPayload (attitude: Attitude, motors: Outputs) { if socket != nil { socket.emit("receivedPayload", [attitude.pitch, attitude.roll, attitude.yaw], motors) } } func armed (isArmed: Bool) { delegate?.armed(isArmed) if socket != nil { socket.emit("armed", isArmed) } } /* -------------------------------------------------------------------- helpers --------------------------------------------------------------- -------------------------------------------------------------------- */ func getParamScope (name: String) -> String { let composite = name.characters.split{$0 == "_"}.map(String.init) let scope = (composite.count == 2) ? composite[1] : name return scope } func getParamClass (name: String) -> String { let composite = name.characters.split{$0 == "_"}.map(String.init) return composite[0] } func registerParam (name: String, getter: ParamGetter, setter: ParamSetter) { self.paramGetters[getParamClass(name)] = getter self.paramSetters[getParamScope(name)] = setter } } protocol PigeonDelegate { // socket states // func serviceConnected() func serviceDisconnected() // armed states func armed(isArmed: Bool) }
apache-2.0
68ef68b735e2cafa806aded479076ea7
27.029762
81
0.504248
5.073276
false
false
false
false
buscarini/vitemo
vitemo/Carthage/Checkouts/GRMustache.swift/Mustache/Compiling/TemplateCompiler.swift
4
22912
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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. final class TemplateCompiler: TemplateTokenConsumer { private var state: CompilerState private let repository: TemplateRepository private let templateID: TemplateID? init(contentType: ContentType, repository: TemplateRepository, templateID: TemplateID?) { self.state = .Compiling(CompilationState(contentType: contentType)) self.repository = repository self.templateID = templateID } func templateAST(#error: NSErrorPointer) -> TemplateAST? { switch(state) { case .Compiling(let compilationState): switch compilationState.currentScope.type { case .Root: return TemplateAST(nodes: compilationState.currentScope.templateASTNodes, contentType: compilationState.contentType) case .Section(openingToken: let openingToken, expression: _): if error != nil { error.memory = parseErrorAtToken(openingToken, description: "Unclosed Mustache tag") } return nil case .InvertedSection(openingToken: let openingToken, expression: _): if error != nil { error.memory = parseErrorAtToken(openingToken, description: "Unclosed Mustache tag") } return nil case .InheritedPartial(openingToken: let openingToken, partialName: _): if error != nil { error.memory = parseErrorAtToken(openingToken, description: "Unclosed Mustache tag") } return nil case .InheritableSection(openingToken: let openingToken, inheritableSectionName: _): if error != nil { error.memory = parseErrorAtToken(openingToken, description: "Unclosed Mustache tag") } return nil } case .Error(let compilationError): if error != nil { error.memory = compilationError } return nil } } // MARK: - TemplateTokenConsumer func parser(parser: TemplateParser, didFailWithError error: NSError) { state = .Error(error) } func parser(parser: TemplateParser, shouldContinueAfterParsingToken token: TemplateToken) -> Bool { switch(state) { case .Error: return false case .Compiling(let compilationState): switch(token.type) { case .SetDelimiters: // noop return true case .Comment: // noop return true case .Pragma(content: let content): let pragma = content.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if NSRegularExpression(pattern: "^CONTENT_TYPE\\s*:\\s*TEXT$", options: NSRegularExpressionOptions(0), error: nil)!.firstMatchInString(pragma, options: NSMatchingOptions(0), range: NSMakeRange(0, (pragma as NSString).length)) != nil { switch compilationState.compilerContentType { case .Unlocked: compilationState.compilerContentType = .Unlocked(.Text) case .Locked(let contentType): state = .Error(parseErrorAtToken(token, description: "CONTENT_TYPE:TEXT pragma tag must prepend any Mustache variable, section, or partial tag.")) return false } } else if NSRegularExpression(pattern: "^CONTENT_TYPE\\s*:\\s*HTML$", options: NSRegularExpressionOptions(0), error: nil)!.firstMatchInString(pragma, options: NSMatchingOptions(0), range: NSMakeRange(0, (pragma as NSString).length)) != nil { switch compilationState.compilerContentType { case .Unlocked: compilationState.compilerContentType = .Unlocked(.HTML) case .Locked(let contentType): state = .Error(parseErrorAtToken(token, description: "CONTENT_TYPE:HTML pragma tag must prepend any Mustache variable, section, or partial tag.")) return false } } return true case .Text(text: let text): compilationState.currentScope.appendNode(TemplateASTNode.text(text: text)) return true case .EscapedVariable(content: let content, tagDelimiterPair: _): var error: NSError? var empty = false if let expression = ExpressionParser().parse(content, empty: &empty, error: &error) { compilationState.currentScope.appendNode(TemplateASTNode.variable(expression: expression, contentType: compilationState.contentType, escapesHTML: true, token: token)) compilationState.compilerContentType = .Locked(compilationState.contentType) return true } else { state = .Error(parseErrorAtToken(token, description: error!.localizedDescription)) return false } case .UnescapedVariable(content: let content, tagDelimiterPair: _): var error: NSError? var empty = false if let expression = ExpressionParser().parse(content, empty: &empty, error: &error) { compilationState.currentScope.appendNode(TemplateASTNode.variable(expression: expression, contentType: compilationState.contentType, escapesHTML: false, token: token)) compilationState.compilerContentType = .Locked(compilationState.contentType) return true } else { state = .Error(parseErrorAtToken(token, description: error!.localizedDescription)) return false } case .Section(content: let content, tagDelimiterPair: _): var error: NSError? var empty = false if let expression = ExpressionParser().parse(content, empty: &empty, error: &error) { compilationState.pushScope(Scope(type: .Section(openingToken: token, expression: expression))) compilationState.compilerContentType = .Locked(compilationState.contentType) return true } else { state = .Error(parseErrorAtToken(token, description: error!.localizedDescription)) return false } case .InvertedSection(content: let content, tagDelimiterPair: _): var error: NSError? var empty = false if let expression = ExpressionParser().parse(content, empty: &empty, error: &error) { compilationState.pushScope(Scope(type: .InvertedSection(openingToken: token, expression: expression))) compilationState.compilerContentType = .Locked(compilationState.contentType) return true } else { state = .Error(parseErrorAtToken(token, description: error!.localizedDescription)) return false } case .InheritableSection(content: let content): var error: NSError? var empty: Bool = false if let inheritableSectionName = inheritableSectionNameFromString(content, inToken: token, empty: &empty, error: &error) { compilationState.pushScope(Scope(type: .InheritableSection(openingToken: token, inheritableSectionName: inheritableSectionName))) compilationState.compilerContentType = .Locked(compilationState.contentType) return true } else { state = .Error(error!) return false } case .InheritedPartial(content: let content): var error: NSError? var empty: Bool = false if let partialName = partialNameFromString(content, inToken: token, empty: &empty, error: &error) { compilationState.pushScope(Scope(type: .InheritedPartial(openingToken: token, partialName: partialName))) compilationState.compilerContentType = .Locked(compilationState.contentType) return true } else { state = .Error(error!) return false } case .Close(content: let content): switch compilationState.currentScope.type { case .Root: state = .Error(parseErrorAtToken(token, description: "Unmatched closing tag")) return false case .Section(openingToken: let openingToken, expression: let closedExpression): var error: NSError? var empty: Bool = false let expression = ExpressionParser().parse(content, empty: &empty, error: &error) switch (expression, empty) { case (nil, true): break case (nil, false): state = .Error(parseErrorAtToken(token, description: error!.localizedDescription)) return false default: if expression != closedExpression { state = .Error(parseErrorAtToken(token, description: "Unmatched closing tag")) return false } } let templateASTNodes = compilationState.currentScope.templateASTNodes let templateAST = TemplateAST(nodes: templateASTNodes, contentType: compilationState.contentType) // // TODO: uncomment and make it compile // if token.templateString !== openingToken.templateString { // fatalError("Not implemented") // } let templateString = token.templateString let innerContentRange = openingToken.range.endIndex..<token.range.startIndex let sectionTag = TemplateASTNode.section(templateAST: templateAST, expression: closedExpression, inverted: false, openingToken: openingToken, innerTemplateString: templateString[innerContentRange]) compilationState.popCurrentScope() compilationState.currentScope.appendNode(sectionTag) return true case .InvertedSection(openingToken: let openingToken, expression: let closedExpression): var error: NSError? var empty: Bool = false let expression = ExpressionParser().parse(content, empty: &empty, error: &error) switch (expression, empty) { case (nil, true): break case (nil, false): state = .Error(parseErrorAtToken(token, description: error!.localizedDescription)) return false default: if expression != closedExpression { state = .Error(parseErrorAtToken(token, description: "Unmatched closing tag")) return false } } let templateASTNodes = compilationState.currentScope.templateASTNodes let templateAST = TemplateAST(nodes: templateASTNodes, contentType: compilationState.contentType) // // TODO: uncomment and make it compile // if token.templateString !== openingToken.templateString { // fatalError("Not implemented") // } let templateString = token.templateString let innerContentRange = openingToken.range.endIndex..<token.range.startIndex let sectionTag = TemplateASTNode.section(templateAST: templateAST, expression: closedExpression, inverted: true, openingToken: openingToken, innerTemplateString: templateString[innerContentRange]) compilationState.popCurrentScope() compilationState.currentScope.appendNode(sectionTag) return true case .InheritedPartial(openingToken: let openingToken, partialName: let inheritedPartialName): var error: NSError? var empty: Bool = false let partialName = partialNameFromString(content, inToken: token, empty: &empty, error: &error) switch (partialName, empty) { case (nil, true): break case (nil, false): state = .Error(error!) return false default: if (partialName != inheritedPartialName) { state = .Error(parseErrorAtToken(token, description: "Unmatched closing tag")) return false } } if let inheritedTemplateAST = repository.templateAST(named: inheritedPartialName, relativeToTemplateID:templateID, error: &error) { switch inheritedTemplateAST.type { case .Undefined: break case .Defined(nodes: _, contentType: let partialContentType): if partialContentType != compilationState.contentType { state = .Error(parseErrorAtToken(token, description: "Content type mismatch")) return false } } let templateASTNodes = compilationState.currentScope.templateASTNodes let templateAST = TemplateAST(nodes: templateASTNodes, contentType: compilationState.contentType) let inheritedPartialNode = TemplateASTNode.inheritedPartial(overridingTemplateAST: templateAST, inheritedTemplateAST: inheritedTemplateAST, inheritedPartialName: inheritedPartialName) compilationState.popCurrentScope() compilationState.currentScope.appendNode(inheritedPartialNode) return true } else { state = .Error(error!) return false } case .InheritableSection(openingToken: let openingToken, inheritableSectionName: let closedInheritableSectionName): var error: NSError? var empty: Bool = false let inheritableSectionName = inheritableSectionNameFromString(content, inToken: token, empty: &empty, error: &error) switch (inheritableSectionName, empty) { case (nil, true): break case (nil, false): state = .Error(parseErrorAtToken(token, description: error!.localizedDescription)) return false default: if inheritableSectionName != closedInheritableSectionName { state = .Error(parseErrorAtToken(token, description: "Unmatched closing tag")) return false } } let templateASTNodes = compilationState.currentScope.templateASTNodes let templateAST = TemplateAST(nodes: templateASTNodes, contentType: compilationState.contentType) let inheritableSectionTag = TemplateASTNode.inheritableSection(innerTemplateAST: templateAST, name: closedInheritableSectionName) compilationState.popCurrentScope() compilationState.currentScope.appendNode(inheritableSectionTag) return true } case .Partial(content: let content): var error: NSError? var empty: Bool = false if let partialName = partialNameFromString(content, inToken: token, empty: &empty, error: &error), let partialTemplateAST = repository.templateAST(named: partialName, relativeToTemplateID: templateID, error: &error) { let partialNode = TemplateASTNode.partial(templateAST: partialTemplateAST, name: partialName) compilationState.currentScope.appendNode(partialNode) compilationState.compilerContentType = .Locked(compilationState.contentType) return true } else { state = .Error(error!) return false } } } } // MARK: - Private private class CompilationState { var currentScope: Scope { return scopeStack[scopeStack.endIndex - 1] } var contentType: ContentType { switch compilerContentType { case .Unlocked(let contentType): return contentType case .Locked(let contentType): return contentType } } init(contentType: ContentType) { self.compilerContentType = .Unlocked(contentType) self.scopeStack = [Scope(type: .Root)] } func popCurrentScope() { scopeStack.removeLast() } func pushScope(scope: Scope) { scopeStack.append(scope) } enum CompilerContentType { case Unlocked(ContentType) case Locked(ContentType) } var compilerContentType: CompilerContentType private var scopeStack: [Scope] } private enum CompilerState { case Compiling(CompilationState) case Error(NSError) } private class Scope { let type: Type var templateASTNodes: [TemplateASTNode] init(type:Type) { self.type = type self.templateASTNodes = [] } func appendNode(node: TemplateASTNode) { templateASTNodes.append(node) } enum Type { case Root case Section(openingToken: TemplateToken, expression: Expression) case InvertedSection(openingToken: TemplateToken, expression: Expression) case InheritedPartial(openingToken: TemplateToken, partialName: String) case InheritableSection(openingToken: TemplateToken, inheritableSectionName: String) } } private func inheritableSectionNameFromString(string: String, inToken token: TemplateToken, inout empty: Bool, error: NSErrorPointer) -> String? { let whiteSpace = NSCharacterSet.whitespaceAndNewlineCharacterSet() let inheritableSectionName = string.stringByTrimmingCharactersInSet(whiteSpace) if count(inheritableSectionName) == 0 { if error != nil { error.memory = parseErrorAtToken(token, description: "Missing inheritable section name") } empty = true return nil } else if (inheritableSectionName.rangeOfCharacterFromSet(whiteSpace) != nil) { if error != nil { error.memory = parseErrorAtToken(token, description: "Invalid inheritable section name") } empty = false return nil } return inheritableSectionName } private func partialNameFromString(string: String, inToken token: TemplateToken, inout empty: Bool, error: NSErrorPointer) -> String? { let whiteSpace = NSCharacterSet.whitespaceAndNewlineCharacterSet() let partialName = string.stringByTrimmingCharactersInSet(whiteSpace) if count(partialName) == 0 { if error != nil { error.memory = parseErrorAtToken(token, description: "Missing template name") } empty = true return nil } else if (partialName.rangeOfCharacterFromSet(whiteSpace) != nil) { if error != nil { error.memory = parseErrorAtToken(token, description: "Invalid template name") } empty = false return nil } return partialName } private func parseErrorAtToken(token: TemplateToken, description: String) -> NSError { var localizedDescription: String if let templateID = templateID { localizedDescription = "Parse error at line \(token.lineNumber) of template \(templateID): \(description)" } else { localizedDescription = "Parse error at line \(token.lineNumber): \(description)" } return NSError(domain: GRMustacheErrorDomain, code: GRMustacheErrorCodeParseError, userInfo: [NSLocalizedDescriptionKey: localizedDescription]) } }
mit
15764a8a7db12d0e1201a4b39f15865c
49.576159
257
0.569159
6.334255
false
false
false
false
fengchenlianlian/actor-platform
actor-apps/app-ios/Actor/Views/Cells/TitledCell.swift
31
1483
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit class TitledCell: CommonCell { private var titleLabel: UILabel = UILabel() private var contentLabel: UILabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) titleLabel.font = UIFont.systemFontOfSize(14.0) titleLabel.text = " " titleLabel.sizeToFit() titleLabel.textColor = MainAppTheme.list.actionColor contentView.addSubview(titleLabel) contentLabel.font = UIFont.systemFontOfSize(17.0) contentLabel.text = " " contentLabel.textColor = MainAppTheme.list.textColor contentLabel.sizeToFit() contentView.addSubview(contentLabel) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setTitle(title: String, content: String) { titleLabel.text = title contentLabel.text = content } override func layoutSubviews() { super.layoutSubviews() titleLabel.frame = CGRect(x: separatorInset.left, y: 7, width: contentView.bounds.width - separatorInset.left - 10, height: titleLabel.bounds.height) contentLabel.frame = CGRect(x: separatorInset.left, y: 27, width: contentView.bounds.width - separatorInset.left - 10, height: contentLabel.bounds.height) } }
mit
d45fd5a61d371ddb6dce369cbb1efa47
33.488372
162
0.665543
4.814935
false
false
false
false
jairoeli/Habit
Zero/Sources/Rx/UIViewController+Rx.swift
1
2173
// // UIViewController+Rx.swift // Zero // // Created by Jairo Eli de Leon on 5/8/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // import UIKit import RxCocoa import RxSwift extension Reactive where Base: UIViewController { var viewDidLoad: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewDidLoad)).map { _ in } return ControlEvent(events: source) } var viewWillAppear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewWillAppear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } var viewDidAppear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewDidAppear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } var viewWillDisappear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewWillDisappear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } var viewDidDisappear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewDidDisappear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } var viewWillLayoutSubviews: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewWillLayoutSubviews)).map { _ in } return ControlEvent(events: source) } var viewDidLayoutSubviews: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewDidLayoutSubviews)).map { _ in } return ControlEvent(events: source) } var willMoveToParentViewController: ControlEvent<UIViewController?> { let source = self.methodInvoked(#selector(Base.willMove)).map { $0.first as? UIViewController } return ControlEvent(events: source) } var didMoveToParentViewController: ControlEvent<UIViewController?> { let source = self.methodInvoked(#selector(Base.didMove)).map { $0.first as? UIViewController } return ControlEvent(events: source) } var didReceiveMemoryWarning: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.didReceiveMemoryWarning)).map { _ in } return ControlEvent(events: source) } }
mit
e5596d4580aa535b94adb11753b5181a
33.460317
105
0.725472
4.421589
false
false
false
false
pepibumur/Szimpla
Szimpla/Classes/Client/Client.swift
1
2297
import Foundation import SwiftyJSON @objc public class Client: NSObject { // MARK: - Instance public static var instance: Client = Client() // MARK: - Attributes private let requestsRemoteFetcher: RequestsRemoteFetcher private let requestsLocalFetcher: (path: String) -> RequestsLocalFetcher private let fileManager: FileManager private let requestsValidator: Validator private let asserter: XCAsserter // MARK: - Init internal init(requestsValidator: Validator, requestsRemoteFetcher: RequestsRemoteFetcher, requestsLocalFetcher: (String) -> RequestsLocalFetcher, fileManager: FileManager, asserter: XCAsserter = XCAsserter()) { self.requestsValidator = requestsValidator self.requestsRemoteFetcher = requestsRemoteFetcher self.requestsLocalFetcher = requestsLocalFetcher self.fileManager = fileManager self.asserter = asserter } public convenience override init() { self.init(requestsValidator: DefaultValidator(), requestsRemoteFetcher: RequestsRemoteFetcher(), requestsLocalFetcher: RequestsLocalFetcher.withPath, fileManager: FileManager.instance) } // MARK: - Public public func start() throws { try self.requestsRemoteFetcher.tearUp() } public func record(path path: String, filter: RequestFilter! = nil) throws { let requests = try self.requestsRemoteFetcher.tearDown(filter: filter) let requestsDicts = requests.map({$0.toDict()}) let requestsData = try NSJSONSerialization.dataWithJSONObject(requestsDicts, options: NSJSONWritingOptions.PrettyPrinted) try self.fileManager.save(data: requestsData, path: path) } public func validate(path path: String, filter: RequestFilter! = nil) throws { do { let recordedRequests = try self.requestsRemoteFetcher.tearDown(filter: filter) let localRequests = try self.requestsLocalFetcher(path: path).fetch() try self.requestsValidator.validate(recordedRequests: recordedRequests, localRequests: localRequests) } catch { self.asserter.assert(error) } } }
mit
a9b604b30e819954976eab1324261e8a
35.460317
192
0.675229
5.059471
false
false
false
false
einsteinx2/iSub
Classes/Server Loading/Loaders/New Model/CachedFolderLoader.swift
1
1294
// // CachedFolderLoader.swift // iSub // // Created by Benjamin Baron on 1/7/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation final class CachedFolderLoader: CachedDatabaseLoader { fileprivate static var operationQueues = [OperationQueue]() let folderId: Int64 var folders = [Folder]() var songs = [Song]() var songsDuration = 0 override var items: [Item] { return folders as [Item] + songs as [Item] } override var associatedItem: Item? { return FolderRepository.si.folder(folderId: folderId, serverId: serverId) } init(folderId: Int64, serverId: Int64) { self.folderId = folderId super.init(serverId: serverId) } @discardableResult override func loadModelsFromDatabase() -> Bool { folders = FolderRepository.si.folders(parentFolderId: folderId, serverId: serverId, isCachedTable: true) songs = SongRepository.si.songs(folderId: folderId, serverId: serverId, isCachedTable: true) songsDuration = songs.reduce(0) { totalDuration, song -> Int in if let duration = song.duration { return totalDuration + duration } return totalDuration } return true } }
gpl-3.0
eb7063e7a5b58aa69b8084159afdd351
28.386364
112
0.640371
4.601423
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0172.xcplaygroundpage/Contents.swift
1
8765
/*: # One-sided Ranges * Proposal: [SE-0172](0172-one-sided-ranges.md) * Authors: [Ben Cohen](https://github.com/airspeedswift), [Dave Abrahams](https://github.com/dabrahams), [Brent Royal-Gordon](https://github.com/brentdax) * Review Manager: [Doug Gregor](https://github.com/DougGregor) * Status: **Implemented (Swift 4)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170424/036125.html) ## Introduction This proposal introduces the concept of a "one-sided" range, created via prefix/postfix versions of the existing range operators. It also introduces a new protocol, `RangeExpression`, to simplify the creation of methods that take different kinds of ranges. ## Motivation It is common, given an index into a collection, to want a slice up to or from that index versus the start/end. For example (assuming `String` is once more a `Collection`): ```swift let s = "Hello, World!" let i = s.index(of: ",")! let greeting = s[s.startIndex..<i] ``` When performing lots of slicing like this, the verbosity of repeating `s.startIndex` is tiresome to write and harmful to readability. Swift 3’s solution to this is a family of methods: ```swift let greeting = s.prefix(upTo: i) let withComma = s.prefix(through: i) let location = s.suffix(from: i) ``` The two very different-looking ways to perform a similar task is jarring. And as methods, the result cannot be used as an l-value. A variant of the one-sided slicing syntax found in Python (i.e. `s[i:]`) is proposed to resolve this. ## Proposed solution Introduce a one-sided range syntax, where the "missing" side is inferred to be the start/end: ```swift // half-open right-handed range let greeting = s[..<i] // closed right-handed range let withComma = s[...i] // left-handed range (no need for half-open variant) let location = s[i...] ``` Additionally, when the index is a countable type, `i...` should form a `Sequence` that counts up from `i` indefinitely. This is useful in forming variants of `Sequence.enumerated()` when you either want them non-zero-based i.e. `zip(1..., greeting)`, or want to flip the order i.e. `zip(greeting, 0...)`. This syntax would supercede the existing `prefix` and `suffix` operations that take indices, which will be deprecated in a later release. Note that the versions that take distances are not covered by this proposal, and would remain. This will require the introduction of new range types (e.g. `PartialRangeThrough`). There are already multiple range types (e.g. `ClosedRange`, `CountableHalfOpenRange`), which require overloads to allow them to be used wherever a `Range` can be. To unify these different range types, a new protocol, `RangeExpression` will be created and all ranges conformed to it. Existing overloads taking concrete types other than `Range` can then be replaced with a single generic method that takes a `RangeExpression`, converts it to a `Range`, and then forward the method on. A generic version of `~=` will also be implemented for all range expressions: ```swift switch i { case 9001...: print("It’s over NINE THOUSAAAAAAAND") default: print("There's no way that can be right!") } ``` The existing concrete overloads that take ranges other than `Range` will be deprecated in favor of generic ones that take a `RangeExpression`. ## Detailed design Add the following to the standard library: (a fuller work-in-progress implementation can be found here: https://github.com/apple/swift/pull/8710) NOTE: The following is subject to change depending on pending compiler features. Methods may actually be on underscored protocols, and then moved once recursive protocols are implemented. Types may be collapsed using conditional conformance. This should not matter from a usage perspective – users are not expected to use these types directly or override any of the behaviors in their own types. Any final implementation will follow the below in spirit if not in practice. ```swift public protocol RangeExpression { associatedtype Bound: Comparable /// Returns `self` expressed as a range of indices within `collection`. /// /// -Parameter collection: The collection `self` should be /// relative to. /// /// -Returns: A `Range<Bound>` suitable for slicing `collection`. /// The return value is *not* guaranteed to be inside /// its bounds. Callers should apply the same preconditions /// to the return value as they would to a range provided /// directly by the user. func relative<C: _Indexable>(to collection: C) -> Range<Bound> where C.Index == Bound func contains(_ element: Bound) -> Bool } extension RangeExpression { public static func ~= (pattern: Self, value: Bound) -> Bool } prefix operator ..< public struct PartialRangeUpTo<T: Comparable>: RangeExpression { public init(_ upperBound: T) { self.upperBound = upperBound } public let upperBound: T } extension Comparable { public static prefix func ..<(x: Self) -> PartialRangeUpTo<Self> } prefix operator ... public struct PartialRangeThrough<T: Comparable>: RangeExpression { public init(_ upperBound: T) public let upperBound: T } extension Comparable { public static prefix func ...(x: Self) -> PartialRangeThrough<Self> } postfix operator ... public struct PartialRangeFrom<T: Comparable>: RangeExpression { public init(_ lowerBound: T) public let lowerBound: T } extension Comparable { public static postfix func ...(x: Self) -> PartialRangeFrom<Self> } // The below relies on Conditional Conformance. Pending that feature, // this may require an additional CountablePartialRangeFrom type temporarily. extension PartialRangeFrom: Sequence where Index: _Strideable, Index.Stride : SignedInteger extension Collection { public subscript<R: RangeExpression>(r: R) -> SubSequence where R.Bound == Index { get } } extension MutableCollection { public subscript<R: RangeExpression>(r: R) -> SubSequence where R.Bound == Index { get set } } extension RangeReplaceableColleciton { public mutating func replaceSubrange<C: Collection, R: RangeExpression>( _ subrange: ${Range}<Index>, with newElements: C ) where C.Iterator.Element == Iterator.Element, R.Bound == Index public mutating func removeSubrange<R: RangeExpression>( _ subrange: ${Range}<Index> ) where R.Bound == Index } ``` Additionally, these new ranges will implement appropriate protocols such as `CustomStringConvertible`. It is important to note that these new methods and range types are _extensions only_. They are not protocol requirements, as they should not need to be customized for specific collections. They exist only as shorthand to expand out to the full slicing operation. Where `PartialRangeFrom` is a `Sequence`, it is left up to the type of `Index` to control the behavior when the type is incremented past its bounds. In the case of an `Int`, the iterator will trap when iterating past `Int.max`. Other types, such as a `BigInt` that could be incremented indefinitely, would behave differently. The `prefix` and `suffix` methods that take an index _are_ currently protocol requirements, but should not be. This proposal will fix that as a side-effect. ## Source compatibility The new operators/types are purely additive so have no source compatibility consequences. Replacing the overloads taking concrete ranges other than `Range` with a single generic version is source compatible. `prefix` and `suffix` will be deprecated in Swift 4 and later removed. ## Effect on ABI stability The `prefix`/`suffix` methods being deprecated should be eliminated before declaring ABI stability. ## Effect on API resilience The new operators/types are purely additive so have no resilience consequences. ## Alternatives considered `i...` is favored over `i..<` because the latter is ugly. We have to pick one, two would be redundant and likely to cause confusion over which is the "right" one. Either would be reasonable on pedantic correctness grounds – `(i as Int)...` includes `Int.max` consistent with `...`, whereas `a[i...]` is interpreted as `a[i..<a.endIndex]` consistent with `i..<`. It might be nice to consider extend this domain-specific language inside the subscript in other ways. For example, to be able to incorporate the index distance versions of prefix, or add distance offsets to the indices used within the subscript. This proposal explicitly avoids proposals in this area. Such ideas would be considerably more complex to implement, and would make a good project for investigation by an interested community member, but would not fit within the timeline for Swift 4. ---------- [Previous](@previous) | [Next](@next) */
mit
46a35e34674d14f875b2872672232594
35.18595
154
0.744661
4.136514
false
false
false
false
lorentey/swift
stdlib/public/core/AnyHashable.swift
3
9185
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A value that has a custom representation in `AnyHashable`. /// /// `Self` should also conform to `Hashable`. public protocol _HasCustomAnyHashableRepresentation { /// Returns a custom representation of `self` as `AnyHashable`. /// If returns nil, the default representation is used. /// /// If your custom representation is a class instance, it /// needs to be boxed into `AnyHashable` using the static /// type that introduces the `Hashable` conformance. /// /// class Base: Hashable {} /// class Derived1: Base {} /// class Derived2: Base, _HasCustomAnyHashableRepresentation { /// func _toCustomAnyHashable() -> AnyHashable? { /// // `Derived2` is canonicalized to `Derived1`. /// let customRepresentation = Derived1() /// /// // Wrong: /// // return AnyHashable(customRepresentation) /// /// // Correct: /// return AnyHashable(customRepresentation as Base) /// } __consuming func _toCustomAnyHashable() -> AnyHashable? } @usableFromInline internal protocol _AnyHashableBox { var _canonicalBox: _AnyHashableBox { get } /// Determine whether values in the boxes are equivalent. /// /// - Precondition: `self` and `box` are in canonical form. /// - Returns: `nil` to indicate that the boxes store different types, so /// no comparison is possible. Otherwise, contains the result of `==`. func _isEqual(to box: _AnyHashableBox) -> Bool? var _hashValue: Int { get } func _hash(into hasher: inout Hasher) func _rawHashValue(_seed: Int) -> Int var _base: Any { get } func _unbox<T: Hashable>() -> T? func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool } extension _AnyHashableBox { var _canonicalBox: _AnyHashableBox { return self } } internal struct _ConcreteHashableBox<Base: Hashable>: _AnyHashableBox { internal var _baseHashable: Base internal init(_ base: Base) { self._baseHashable = base } internal func _unbox<T: Hashable>() -> T? { return (self as _AnyHashableBox as? _ConcreteHashableBox<T>)?._baseHashable } internal func _isEqual(to rhs: _AnyHashableBox) -> Bool? { if let rhs: Base = rhs._unbox() { return _baseHashable == rhs } return nil } internal var _hashValue: Int { return _baseHashable.hashValue } func _hash(into hasher: inout Hasher) { _baseHashable.hash(into: &hasher) } func _rawHashValue(_seed: Int) -> Int { return _baseHashable._rawHashValue(seed: _seed) } internal var _base: Any { return _baseHashable } internal func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool { guard let value = _baseHashable as? T else { return false } result.initialize(to: value) return true } } /// A type-erased hashable value. /// /// The `AnyHashable` type forwards equality comparisons and hashing operations /// to an underlying hashable value, hiding its specific underlying type. /// /// You can store mixed-type keys in dictionaries and other collections that /// require `Hashable` conformance by wrapping mixed-type keys in /// `AnyHashable` instances: /// /// let descriptions: [AnyHashable: Any] = [ /// AnyHashable("😄"): "emoji", /// AnyHashable(42): "an Int", /// AnyHashable(Int8(43)): "an Int8", /// AnyHashable(Set(["a", "b"])): "a set of strings" /// ] /// print(descriptions[AnyHashable(42)]!) // prints "an Int" /// print(descriptions[AnyHashable(45)]) // prints "nil" /// print(descriptions[AnyHashable(Int8(43))]!) // prints "an Int8" /// print(descriptions[AnyHashable(Set(["a", "b"]))]!) // prints "a set of strings" @frozen public struct AnyHashable { internal var _box: _AnyHashableBox internal init(_box box: _AnyHashableBox) { self._box = box } /// Creates a type-erased hashable value that wraps the given instance. /// /// - Parameter base: A hashable value to wrap. public init<H: Hashable>(_ base: H) { if let custom = (base as? _HasCustomAnyHashableRepresentation)?._toCustomAnyHashable() { self = custom return } self.init(_box: _ConcreteHashableBox(false)) // Dummy value _makeAnyHashableUpcastingToHashableBaseType( base, storingResultInto: &self) } internal init<H: Hashable>(_usingDefaultRepresentationOf base: H) { self._box = _ConcreteHashableBox(base) } /// The value wrapped by this instance. /// /// The `base` property can be cast back to its original type using one of /// the casting operators (`as?`, `as!`, or `as`). /// /// let anyMessage = AnyHashable("Hello world!") /// if let unwrappedMessage = anyMessage.base as? String { /// print(unwrappedMessage) /// } /// // Prints "Hello world!" public var base: Any { return _box._base } /// Perform a downcast directly on the internal boxed representation. /// /// This avoids the intermediate re-boxing we would get if we just did /// a downcast on `base`. internal func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool { // Attempt the downcast. if _box._downCastConditional(into: result) { return true } #if _runtime(_ObjC) // Bridge to Objective-C and then attempt the cast from there. // FIXME: This should also work without the Objective-C runtime. if let value = _bridgeAnythingToObjectiveC(_box._base) as? T { result.initialize(to: value) return true } #endif return false } } extension AnyHashable: Equatable { /// Returns a Boolean value indicating whether two type-erased hashable /// instances wrap the same type and value. /// /// Two instances of `AnyHashable` compare as equal if and only if the /// underlying types have the same conformance to the `Equatable` protocol /// and the underlying values compare as equal. /// /// - Parameters: /// - lhs: A type-erased hashable value. /// - rhs: Another type-erased hashable value. public static func == (lhs: AnyHashable, rhs: AnyHashable) -> Bool { return lhs._box._canonicalBox._isEqual(to: rhs._box._canonicalBox) ?? false } } extension AnyHashable: Hashable { /// The hash value. public var hashValue: Int { return _box._canonicalBox._hashValue } /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. public func hash(into hasher: inout Hasher) { _box._canonicalBox._hash(into: &hasher) } public func _rawHashValue(seed: Int) -> Int { return _box._canonicalBox._rawHashValue(_seed: seed) } } extension AnyHashable: CustomStringConvertible { public var description: String { return String(describing: base) } } extension AnyHashable: CustomDebugStringConvertible { public var debugDescription: String { return "AnyHashable(" + String(reflecting: base) + ")" } } extension AnyHashable: CustomReflectable { public var customMirror: Mirror { return Mirror( self, children: ["value": base]) } } /// Returns a default (non-custom) representation of `self` /// as `AnyHashable`. /// /// Completely ignores the `_HasCustomAnyHashableRepresentation` /// conformance, if it exists. /// Called by AnyHashableSupport.cpp. @_silgen_name("_swift_makeAnyHashableUsingDefaultRepresentation") internal func _makeAnyHashableUsingDefaultRepresentation<H: Hashable>( of value: H, storingResultInto result: UnsafeMutablePointer<AnyHashable> ) { result.pointee = AnyHashable(_usingDefaultRepresentationOf: value) } /// Provided by AnyHashable.cpp. @_silgen_name("_swift_makeAnyHashableUpcastingToHashableBaseType") internal func _makeAnyHashableUpcastingToHashableBaseType<H: Hashable>( _ value: H, storingResultInto result: UnsafeMutablePointer<AnyHashable> ) @inlinable public // COMPILER_INTRINSIC func _convertToAnyHashable<H: Hashable>(_ value: H) -> AnyHashable { return AnyHashable(value) } /// Called by the casting machinery. @_silgen_name("_swift_convertToAnyHashableIndirect") internal func _convertToAnyHashableIndirect<H: Hashable>( _ value: H, _ target: UnsafeMutablePointer<AnyHashable> ) { target.initialize(to: AnyHashable(value)) } /// Called by the casting machinery. @_silgen_name("_swift_anyHashableDownCastConditionalIndirect") internal func _anyHashableDownCastConditionalIndirect<T>( _ value: UnsafePointer<AnyHashable>, _ target: UnsafeMutablePointer<T> ) -> Bool { return value.pointee._downCastConditional(into: target) }
apache-2.0
9279b45ef1107b3341150a5e37ef1106
30.771626
87
0.668809
4.34548
false
false
false
false
alblue/swift
test/IRGen/protocol_resilience_descriptors.swift
1
6484
// RUN: %empty-directory(%t) // Resilient protocol definition // RUN: %target-swift-frontend -emit-ir -enable-resilience -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift | %FileCheck -DINT=i%target-ptrsize -check-prefix=CHECK-DEFINITION %s // Resilient protocol usage // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -assume-parsing-unqualified-ownership-sil %s | %FileCheck %s -DINT=i%target-ptrsize -check-prefix=CHECK-USAGE // ---------------------------------------------------------------------------- // Resilient protocol definition // ---------------------------------------------------------------------------- // CHECK: @"default assoc type x" = linkonce_odr hidden constant // CHECK-SAME: i8 -1, [1 x i8] c"x", i8 0 // CHECK: @"default assoc type \01____y2T118resilient_protocol29ProtocolWithAssocTypeDefaultsPQzG 18resilient_protocol7WrapperV" = // Protocol descriptor // CHECK-DEFINITION-LABEL: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsMp" ={{( protected)?}} constant // CHECK-DEFINITION-SAME: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0TN" // Associated type default + flags // CHECK-DEFINITION-SAME: [[INT]] add // CHECK-DEFINITION-SAME: @"default assoc type _____y2T1_____QzG 18resilient_protocol7WrapperV AA29ProtocolWithAssocTypeDefaultsP" // CHECK-DEFINITION-SAME: [[INT]] 1 // Protocol requirements base descriptor // CHECK-DEFINITION: @"$s18resilient_protocol21ResilientBaseProtocolTL" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr (%swift.protocol_requirement, %swift.protocol_requirement* getelementptr inbounds (<{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>, <{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>* @"$s18resilient_protocol21ResilientBaseProtocolMp", i32 0, i32 6), i32 -1) // Associated type and conformance // CHECK-DEFINITION: @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl" ={{( dllexport)?}}{{( protected)?}} alias // CHECK-DEFINITION: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn" ={{( dllexport)?}}{{( protected)?}} alias // Default associated conformance witnesses // CHECK-DEFINITION-LABEL: define internal swiftcc i8** @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0TN" import resilient_protocol // ---------------------------------------------------------------------------- // Resilient witness tables // ---------------------------------------------------------------------------- // CHECK-USAGE-LABEL: $s31protocol_resilience_descriptors34ConformsToProtocolWithRequirementsVyxG010resilient_A00fgH0AAMc" = // CHECK-USAGE-SAME: {{got.|__imp_}}$s1T18resilient_protocol24ProtocolWithRequirementsPTl // CHECK-USAGE-SAME: @"symbolic x" public struct ConformsToProtocolWithRequirements<Element> : ProtocolWithRequirements { public typealias T = Element public func first() { } public func second() { } } public protocol P { } public struct ConditionallyConforms<Element> { } public struct Y { } // CHECK-USAGE-LABEL: @"$s31protocol_resilience_descriptors1YV010resilient_A022OtherResilientProtocolAAMc" = // CHECK-USAGE-SAME: i32 131072, // CHECK-USAGE-SAME: i16 1, // CHECK-USAGE-SAME: i16 0 extension Y: OtherResilientProtocol { } // CHECK-USAGE: @"$s31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAAMc" = // CHECK-USAGE-SAME: $s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn // CHECK-USAGE-SAME: $s31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAA2T2AdEP_AD014OtherResilientI0PWT public struct ConformsWithAssocRequirements : ProtocolWithAssocTypeDefaults { } // CHECK-USAGE: @"$sx1T18resilient_protocol24ProtocolWithRequirementsP_MXA" = // CHECK-USAGE-SAME: i32 0 // CHECK-USAGE-SAME: @"{{got.|__imp_}}$s18resilient_protocol24ProtocolWithRequirementsMp" // CHECK-USAGE-SAME: @"$sx1T18resilient_protocol24ProtocolWithRequirementsP_MXA" // CHECK-USAGE-SAME: %swift.protocol_requirement** @"{{got.|__imp_}}$s1T18resilient_protocol24ProtocolWithRequirementsPTl" // CHECK-USAGE: @"$s31protocol_resilience_descriptors21ConditionallyConformsVyxG010resilient_A024ProtocolWithRequirementsAaeFRzAA1YV1TRtzlMc" extension ConditionallyConforms: ProtocolWithRequirements where Element: ProtocolWithRequirements, Element.T == Y { public typealias T = Element.T public func first() { } public func second() { } } // ---------------------------------------------------------------------------- // Resilient protocol usage // ---------------------------------------------------------------------------- // CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s31protocol_resilience_descriptors17assocTypeMetadatay1TQzmxm010resilient_A024ProtocolWithRequirementsRzlF"(%swift.type*, %swift.type* [[PWD:%.*]], i8** [[WTABLE:%.*]]) public func assocTypeMetadata<PWR: ProtocolWithRequirements>(_: PWR.Type) -> PWR.T.Type { // CHECK-USAGE: call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %PWR.ProtocolWithRequirements, %swift.type* %PWR, %swift.protocol_requirement* @"$s18resilient_protocol24ProtocolWithRequirementsTL", %swift.protocol_requirement* @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl") return PWR.T.self } func useOtherResilientProtocol<T: OtherResilientProtocol>(_: T.Type) { } // CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s31protocol_resilience_descriptors23extractAssocConformanceyyx010resilient_A0012ProtocolWithE12TypeDefaultsRzlF" public func extractAssocConformance<T: ProtocolWithAssocTypeDefaults>(_: T) { // CHECK-USAGE: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.ProtocolWithAssocTypeDefaults, [[INT]] udiv ([[INT]] sub ([[INT]] ptrtoint (%swift.protocol_requirement* @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn" to [[INT]]), [[INT]] ptrtoint (%swift.protocol_requirement* @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsTL" to [[INT]])), [[INT]] 8) // CHECK-USAGE: load i8*, i8** [[WITNESS_ADDR]] useOtherResilientProtocol(T.T2.self) }
apache-2.0
7175f1477906008be2c5eb4bde9d8f70
62.568627
444
0.724244
4.007417
false
false
false
false
pkl728/ZombieInjection
Pods/Differ/Sources/Differ/NestedDiff.swift
2
4646
public struct NestedDiff: DiffProtocol { public typealias Index = Int public enum Element { case deleteSection(Int) case insertSection(Int) case deleteElement(Int, section: Int) case insertElement(Int, section: Int) } /// Returns the position immediately after the given index. /// /// - Parameters: /// - i: A valid index of the collection. `i` must be less than `endIndex`. /// - Returns: The index value immediately after `i`. public func index(after i: Int) -> Int { return i + 1 } public let elements: [Element] } public extension Collection where Iterator.Element: Collection { /// Creates a diff between the callee and `other` collection. It diffs elements two levels deep (therefore "nested") /// /// - Parameters: /// - other: a collection to compare the calee to /// - Returns: a `NestedDiff` between the calee and `other` collection public func nestedDiff( to: Self, isEqualSection: EqualityChecker<Self>, isEqualElement: NestedElementEqualityChecker<Self> ) -> NestedDiff { let diffTraces = outputDiffPathTraces(to: to, isEqual: isEqualSection) // Diff sections let sectionDiff = Diff(traces: diffTraces).map { element -> NestedDiff.Element in switch element { case let .delete(at): return .deleteSection(at) case let .insert(at): return .insertSection(at) } } // Diff matching sections (moves, deletions, insertions) let filterMatchPoints = { (trace: Trace) -> Bool in if case .matchPoint = trace.type() { return true } return false } // offset & section let matchingSectionTraces = diffTraces .filter(filterMatchPoints) let fromSections = matchingSectionTraces.map { itemOnStartIndex(advancedBy: $0.from.x) } let toSections = matchingSectionTraces.map { to.itemOnStartIndex(advancedBy: $0.from.y) } let elementDiff = zip(zip(fromSections, toSections), matchingSectionTraces) .flatMap { (args) -> [NestedDiff.Element] in let (sections, trace) = args return sections.0.diff(sections.1, isEqual: isEqualElement).map { diffElement -> NestedDiff.Element in switch diffElement { case let .delete(at): return .deleteElement(at, section: trace.from.x) case let .insert(at): return .insertElement(at, section: trace.from.y) } } } return NestedDiff(elements: sectionDiff + elementDiff) } } public extension Collection where Iterator.Element: Collection, Iterator.Element.Iterator.Element: Equatable { /// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)` public func nestedDiff( to: Self, isEqualSection: EqualityChecker<Self> ) -> NestedDiff { return nestedDiff( to: to, isEqualSection: isEqualSection, isEqualElement: { $0 == $1 } ) } } public extension Collection where Iterator.Element: Collection, Iterator.Element: Equatable { /// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)` public func nestedDiff( to: Self, isEqualElement: NestedElementEqualityChecker<Self> ) -> NestedDiff { return nestedDiff( to: to, isEqualSection: { $0 == $1 }, isEqualElement: isEqualElement ) } } public extension Collection where Iterator.Element: Collection, Iterator.Element: Equatable, Iterator.Element.Iterator.Element: Equatable { /// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)` public func nestedDiff(to: Self) -> NestedDiff { return nestedDiff( to: to, isEqualSection: { $0 == $1 }, isEqualElement: { $0 == $1 } ) } } extension NestedDiff.Element: CustomDebugStringConvertible { public var debugDescription: String { switch self { case let .deleteElement(row, section): return "DE(\(row),\(section))" case let .deleteSection(section): return "DS(\(section))" case let .insertElement(row, section): return "IE(\(row),\(section))" case let .insertSection(section): return "IS(\(section))" } } }
mit
f881c154c4f1f5431443d53df486c69a
30.181208
120
0.586741
4.702429
false
false
false
false
wireapp/wire-ios
WireCommonComponents/AutomationHelper.swift
1
10599
// // Wire // Copyright (C) 2016 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 WireSystem import WireDataModel import WireSyncEngine final public class AutomationEmailCredentials: NSObject { public var email: String public var password: String init(email: String, password: String) { self.email = email self.password = password super.init() } } /// This class is used to retrieve specific arguments passed on the /// command line when running automation tests. /// These values typically do not need to be stored in `Settings`. public final class AutomationHelper: NSObject { static public let sharedHelper = AutomationHelper() private var useAppCenterLaunchOption: Bool? /// Whether AppCenter should be used /// Launch option `--use-app-center` overrides user defaults setting. public var useAppCenter: Bool { // useAppCenterLaunchOption has higher priority if let useAppCenterLaunchOption = useAppCenterLaunchOption { return useAppCenterLaunchOption } if UserDefaults.standard.object(forKey: "UseAppCenter") != nil { return UserDefaults.standard.bool(forKey: "UseAppCenter") } // When UserDefaults's useAppCenter is not set, default is true to allow app center start return true } /// Whether analytics should be used public var useAnalytics: Bool { // TODO: get it from xcconfig? // return UserDefaults.standard.bool(forKey: "UseAnalytics") return true } /// Whether to skip the first login alert public var skipFirstLoginAlerts: Bool { return self.automationEmailCredentials != nil } /// The login credentials provides by command line public let automationEmailCredentials: AutomationEmailCredentials? /// Whether we push notification permissions alert is disabled public let disablePushNotificationAlert: Bool /// Whether autocorrection is disabled public let disableAutocorrection: Bool /// Whether address book upload is enabled on simulator public let uploadAddressbookOnSimulator: Bool /// Whether we should disable the call quality survey. public let disableCallQualitySurvey: Bool /// Whether we should disable dismissing the conversation input bar keyboard by dragging it downwards. public let disableInteractiveKeyboardDismissal: Bool /// Delay in address book remote search override public let delayInAddressBookRemoteSearch: TimeInterval? /// Debug data to install in the share container public let debugDataToInstall: URL? /// The name of the arguments file in the /tmp directory private let fileArgumentsName = "wire_arguments.txt" /// Whether the backend environment type should be persisted as a setting. public let shouldPersistBackendType: Bool /// Whether the calling overlay should disappear automatically. public let keepCallingOverlayVisible: Bool override init() { let url = URL(string: NSTemporaryDirectory())?.appendingPathComponent(fileArgumentsName) let arguments: ArgumentsType = url.flatMap(FileArguments.init) ?? CommandLineArguments() disablePushNotificationAlert = arguments.hasFlag(AutomationKey.disablePushNotificationAlert) disableAutocorrection = arguments.hasFlag(AutomationKey.disableAutocorrection) uploadAddressbookOnSimulator = arguments.hasFlag(AutomationKey.enableAddressBookOnSimulator) disableCallQualitySurvey = arguments.hasFlag(AutomationKey.disableCallQualitySurvey) shouldPersistBackendType = arguments.hasFlag(AutomationKey.persistBackendType) disableInteractiveKeyboardDismissal = arguments.hasFlag(AutomationKey.disableInteractiveKeyboardDismissal) keepCallingOverlayVisible = arguments.hasFlag(AutomationKey.keepCallingOverlayVisible) if let value = arguments.flagValueIfPresent(AutomationKey.useAppCenter.rawValue) { useAppCenterLaunchOption = (value != "0") } automationEmailCredentials = AutomationHelper.credentials(arguments) if arguments.hasFlag(AutomationKey.logNetwork) { ZMSLog.set(level: .debug, tag: "Network") } if arguments.hasFlag(AutomationKey.logCalling) { ZMSLog.set(level: .debug, tag: "calling") } AutomationHelper.enableLogTags(arguments) if let debugDataPath = arguments.flagValueIfPresent(AutomationKey.debugDataToInstall.rawValue), FileManager.default.fileExists(atPath: debugDataPath) { self.debugDataToInstall = URL(fileURLWithPath: debugDataPath) } else { self.debugDataToInstall = nil } self.delayInAddressBookRemoteSearch = AutomationHelper.addressBookSearchDelay(arguments) if let value = arguments.flagValueIfPresent(AutomationKey.preferredAPIversion.rawValue), let apiVersion = Int32(value) { BackendInfo.preferredAPIVersion = APIVersion(rawValue: apiVersion) } super.init() } fileprivate enum AutomationKey: String { case email = "loginemail" case password = "loginpassword" case logNetwork = "debug-log-network" case logCalling = "debug-log-calling" case logTags = "debug-log" case disablePushNotificationAlert = "disable-push-alert" case disableAutocorrection = "disable-autocorrection" case enableAddressBookOnSimulator = "addressbook-on-simulator" case addressBookRemoteSearchDelay = "addressbook-search-delay" case debugDataToInstall = "debug-data-to-install" case disableCallQualitySurvey = "disable-call-quality-survey" case persistBackendType = "persist-backend-type" case disableInteractiveKeyboardDismissal = "disable-interactive-keyboard-dismissal" case useAppCenter = "use-app-center" case keepCallingOverlayVisible = "keep-calling-overlay-visible" case preferredAPIversion = "preferred-api-version" } /// Returns the login email and password credentials if set in the given arguments fileprivate static func credentials(_ arguments: ArgumentsType) -> AutomationEmailCredentials? { guard let email = arguments.flagValueIfPresent(AutomationKey.email.rawValue), let password = arguments.flagValueIfPresent(AutomationKey.password.rawValue) else { return nil } return AutomationEmailCredentials(email: email, password: password) } // Switches on all flags that you would like to log listed after `--debug-log=` tags should be separated by comma fileprivate static func enableLogTags(_ arguments: ArgumentsType) { guard let tagsString = arguments.flagValueIfPresent(AutomationKey.logTags.rawValue) else { return } let tags = tagsString.components(separatedBy: ",") tags.forEach { ZMSLog.set(level: .debug, tag: $0) } } /// Returns the custom time interval for address book search delay if it set in the given arguments fileprivate static func addressBookSearchDelay(_ arguments: ArgumentsType) -> TimeInterval? { guard let delayString = arguments.flagValueIfPresent(AutomationKey.addressBookRemoteSearchDelay.rawValue), let delay = Int(delayString) else { return nil } return TimeInterval(delay) } } // MARK: - Helpers protocol ArgumentsType { var flagPrefix: String { get } /// Argument strings var arguments: Set<String> { get } /// Returns whether the flag is set func hasFlag(_ name: String) -> Bool /// Returns the value of a flag, if present func flagValueIfPresent(_ commandLineArgument: String) -> String? } // MARK: - default implementation extension ArgumentsType { var flagPrefix: String { return "--" } func hasFlag(_ name: String) -> Bool { return self.arguments.contains(flagPrefix + name) } func hasFlag<Flag: RawRepresentable>(_ flag: Flag) -> Bool where Flag.RawValue == String { return hasFlag(flag.rawValue) } func flagValueIfPresent(_ commandLineArgument: String) -> String? { for argument in arguments { let searchString = flagPrefix + commandLineArgument + "=" if argument.hasPrefix(searchString) { return String(argument[searchString.index(searchString.startIndex, offsetBy: searchString.count)...]) } } return nil } } /// Command line arguments private struct CommandLineArguments: ArgumentsType { let arguments: Set<String> init() { arguments = Set(ProcessInfo.processInfo.arguments) } } /// Arguments read from a file on disk private struct FileArguments: ArgumentsType { let arguments: Set<String> init?(url: URL) { guard let argumentsString = try? String(contentsOfFile: url.path, encoding: .utf8) else { return nil } arguments = Set(argumentsString.components(separatedBy: .whitespaces)) } } // MARK: - Debug extension AutomationHelper { /// Takes all files in the folder pointed at by `debugDataToInstall` and installs them /// in the shared folder, erasing any other file in that folder. public func installDebugDataIfNeeded() { guard let packageURL = self.debugDataToInstall, let appGroupIdentifier = Bundle.main.applicationGroupIdentifier else { return } let sharedContainerURL = FileManager.sharedContainerDirectory(for: appGroupIdentifier) // DELETE let filesToDelete = try! FileManager.default.contentsOfDirectory(atPath: sharedContainerURL.path) filesToDelete.forEach { try! FileManager.default.removeItem(atPath: sharedContainerURL.appendingPathComponent($0).path) } // COPY try! FileManager.default.copyFolderRecursively(from: packageURL, to: sharedContainerURL, overwriteExistingFiles: true) } }
gpl-3.0
f113ea689a17f2b40126101ecaa0ae5a
41.396
126
0.711388
4.888838
false
false
false
false
Matthijn/swift8
Swift8/Chip8ViewController.swift
1
2228
// // ViewController.swift // Swift8 // // Created by Matthijn Dijkstra on 16/08/15. // Copyright © 2015 Matthijn Dijkstra. All rights reserved. // import Cocoa class Chip8ViewController: NSViewController { // Holds the chip 8 emulator system var chip : Chip8? // Current speed at which the emulator runs var currentSpeed : Double { get { return (self.chip?.speed)! } } var chip8View : Chip8View { get { return self.view as! Chip8View } } var canvasView : CanvasView { get { return self.chip8View.canvasView } } override func viewDidLoad() { super.viewDidLoad() // The UIView is the first responder, so hooking the keyboard up from there let keyboard = self.chip8View.keyboard; // Creating graphics through the UIView let graphics = Graphics(graphicsDelegate: self.chip8View.canvasView) // Create the chip system self.chip = Chip8(graphics: graphics, sound: Sound(), keyboard: keyboard) // Applying the default settings self.applySettings() } func load(rom: Data, autostart: Bool) { self.chip?.load(rom, autostart: true) } func resetRom() { self.chip?.resetRom(true) } func increaseSpeed() { self.setSpeed(with: min(self.currentSpeed + 0.1, 1)) } func decreaseSpeed() { self.setSpeed(with: max(self.currentSpeed - 0.1, 0.1)) } func changeTheme(with theme: Theme) { // Save the new theme in settings Settings.sharedSettings.theme = theme // Apply the theme self.canvasView.theme = theme } fileprivate func setSpeed(with speed: Double) { self.chip?.speed = speed Settings.sharedSettings.renderSpeed = speed } fileprivate func applySettings() { // Default to the settings speed self.chip?.speed = Settings.sharedSettings.renderSpeed // And start with the correct theme self.canvasView.theme = Settings.sharedSettings.theme } }
mit
19f41b45d22fc1ca6303666fbee455f2
21.72449
83
0.583745
4.375246
false
false
false
false
mihyaeru21/RxTwift
Example/Tests/CryptoSpec.swift
1
5744
// // Crypto.swift // RxTwift // // Created by Mihyaeru on 3/13/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Quick import Nimble import RxTwift class CryptoSpec: QuickSpec { override func spec() { describe("sha1") { it("empty") { expect(Crypto.sha1("")) == "2jmj7l5rSw0yVb/vlWAYkK/YBwk=" } it("example") { expect(Crypto.sha1("The quick brown fox jumps over the lazy dog")) == "L9ThxnotKPzthJ7hu3bnORuT6xI=" expect(Crypto.sha1("The quick brown fox jumps over the lazy cog")) == "3p8sf9JeGzr60+haC9F9mxANtLM=" } it("long message") { let message = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data" expect(Crypto.sha1(message)) == "trL9zWiHQGvVWtLlwZ4IzPX0ikU=" } context("border") { it("message.count == blockSize") { let message = String(count: 54, repeatedValue: "a" as Character) expect(Array(message.utf8Array).count) == 54 expect(Crypto.sha1(message)) == "sF1xxkl5y5X6dKM82zGkDSWK4C4=" } it("message.count == blockSize-1") { let message = String(count: 55, repeatedValue: "a" as Character) expect(Array(message.utf8Array).count) == 55 expect(Crypto.sha1(message)) == "wci73CJ5bijA4VFj0giZtlYh1lo=" } it("message.count == blockSize-1") { let message = String(count: 56, repeatedValue: "a" as Character) expect(Array(message.utf8Array).count) == 56 expect(Crypto.sha1(message)) == "wtszD2CDhUyZ1LW/tujynyAb5pk=" } } } describe("hmacSha1") { it("empty") { expect(Crypto.hmacSha1(key: "", message: "")) == "+9sdGxiqbAgyS31ktx+3Y3BpDh0=" } it("string wrapper") { let key = "key" let message = "The quick brown fox jumps over the lazy dog" expect(Crypto.hmacSha1(key: key, message: message)) == "3nybhbi3iqa8ino29wqQcBydtNk=" } // from https://www.ipa.go.jp/security/rfc/RFC2202JA.html context("IPA tests") { it("case 1") { let key = Array<UInt8>(count: 20, repeatedValue: 0x0b) let message = "Hi There".utf8Array let hmac: [UInt8] = [0xb6, 0x17, 0x31, 0x86, 0x55, 0x05, 0x72, 0x64, 0xe2, 0x8b, 0xc0, 0xb6, 0xfb, 0x37, 0x8c, 0x8e, 0xf1, 0x46, 0xbe, 0x00] expect(Crypto.hmacSha1(key: key, message: message)) == hmac } it("case 2") { let key = "Jefe".utf8Array let message = "what do ya want for nothing?".utf8Array let hmac: [UInt8] = [0xef, 0xfc, 0xdf, 0x6a, 0xe5, 0xeb, 0x2f, 0xa2, 0xd2, 0x74, 0x16, 0xd5, 0xf1, 0x84, 0xdf, 0x9c, 0x25, 0x9a, 0x7c, 0x79] expect(Crypto.hmacSha1(key: key, message: message)) == hmac } it("case 3") { let key = Array<UInt8>(count: 20, repeatedValue: 0xaa) let message = Array<UInt8>(count: 50, repeatedValue: 0xdd) let hmac: [UInt8] = [0x12, 0x5d, 0x73, 0x42, 0xb9, 0xac, 0x11, 0xcd, 0x91, 0xa3, 0x9a, 0xf4, 0x8a, 0xa1, 0x7b, 0x4f, 0x63, 0xf1, 0x75, 0xd3] expect(Crypto.hmacSha1(key: key, message: message)) == hmac } it("case 4") { let key: [UInt8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19] let message = Array<UInt8>(count: 50, repeatedValue: 0xcd) let hmac: [UInt8] = [0x4c, 0x90, 0x07, 0xf4, 0x02, 0x62, 0x50, 0xc6, 0xbc, 0x84, 0x14, 0xf9, 0xbf, 0x50, 0xc8, 0x6c, 0x2d, 0x72, 0x35, 0xda] expect(Crypto.hmacSha1(key: key, message: message)) == hmac } it("case 5") { let key = Array<UInt8>(count: 20, repeatedValue: 0x0c) let message = "Test With Truncation".utf8Array let hmac: [UInt8] = [0x4c, 0x1a, 0x03, 0x42, 0x4b, 0x55, 0xe0, 0x7f, 0xe7, 0xf2, 0x7b, 0xe1, 0xd5, 0x8b, 0xb9, 0x32, 0x4a, 0x9a, 0x5a, 0x04] expect(Crypto.hmacSha1(key: key, message: message)) == hmac } it("case 6") { let key = Array<UInt8>(count: 80, repeatedValue: 0xaa) let message = "Test Using Larger Than Block-Size Key - Hash Key First".utf8Array let hmac: [UInt8] = [0xaa, 0x4a, 0xe5, 0xe1, 0x52, 0x72, 0xd0, 0x0e, 0x95, 0x70, 0x56, 0x37, 0xce, 0x8a, 0x3b, 0x55, 0xed, 0x40, 0x21, 0x12] expect(Crypto.hmacSha1(key: key, message: message)) == hmac } it("case 7") { let key = Array<UInt8>(count: 80, repeatedValue: 0xaa) let message = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data".utf8Array let hmac: [UInt8] = [0xe8, 0xe9, 0x9d, 0x0f, 0x45, 0x23, 0x7d, 0x78, 0x6d, 0x6b, 0xba, 0xa7, 0x96, 0x5c, 0x78, 0x08, 0xbb, 0xff, 0x1a, 0x91] expect(Crypto.hmacSha1(key: key, message: message)) == hmac } } } } } private extension String { private var utf8Array: [UInt8] { return Array(self.utf8) } }
mit
9944afa00512a67cbc69dc67ac9f2aa1
46.46281
189
0.52133
3.033809
false
false
false
false
kellanburket/Passenger
Example/Passenger/Ravelry/Project.swift
1
2378
// // Project.swift // Passenger // // Created by Kellan Cummings on 6/26/15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import UIKit import Passenger class Project: BaseRavelryModel { var craft: Craft? var pattern: Pattern? var name: String? var permalink: NSURL? var queuePosition: Int = 0 var rating: String? var size: String? var user = BelongsTo<RavelryUser>() var comments = HasMany<Comment>() var progress: Int = 0 { didSet { if progress > 100 { progress = 100 } else if progress < 0 { progress = 0 } } } var started: NSDate? var completed: NSDate? var created: NSDate? var updated: NSDate? var toStart: NSDate? func reorderPhotos(sortOrder: [Int], onComplete: Bool -> Void) { } func createPhoto(images: [String: UIImage], onComplete: AnyObject? -> Void) { let upload = BaseRavelryResource("Upload") upload.create { data in if let json = data as? [String: AnyObject], token = json["upload_token"] as? String { //println("About to Upload Image") var data = [String: NSData]() for (name, image) in images { data[name] = Image.toJpg(image) } var params: [String: AnyObject] = [ "upload_token": token, "access_key": Api.shared("ravelry").key ] upload.resource("Image").upload(data, params: params, onComplete: { raw in if let medias = raw as? [String: AnyObject] { for (name, file) in medias { if let media = file as? [String: AnyObject] { self.doAction("create_photo", params: media, onComplete: onComplete) } else { onComplete(nil) } } } else { onComplete(nil) } }) } else { println("Upload Token does not exist. \(data)") onComplete(nil) } } } }
mit
de1e374f277c9492296177843ef10b88
28.37037
100
0.462994
4.843177
false
false
false
false
proxpero/Endgame
Sources/Event.swift
1
570
// // Event.swift // Endgame // // Created by Todd Olsen on 9/23/16. // // import Foundation /// A representation of a `PGN` event. public struct Event { /// The name of the event. let event: String? /// The name of the site. let site: String? /// The starting date of the event. let startingDate: Date } extension Event: Equatable { /// Equatable conformance public static func == (lhs: Event, rhs: Event) -> Bool { return lhs.event == rhs.event && lhs.site == rhs.site && lhs.startingDate == rhs.startingDate } }
mit
f3c69512b8e5dc0d6b5d307c289ff506
17.387097
101
0.614035
3.5625
false
false
false
false
carolrus/SongList
Song List/SongViewController.swift
1
1084
// // SongViewController.swift // // Controller for the view used to show details about one song // // Created by C Rus on 09/05/16. // Copyright © 2016 crus. All rights reserved. // import UIKit class SongViewController: UIViewController { @IBOutlet var imageView: UIImageView! @IBOutlet var titleLabel: UILabel! @IBOutlet var bandLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() if DataManager.shared.activeSong != -1 { // Set data for UI elements accordingly for the active song let song = DataManager.shared.songList[DataManager.shared.activeSong] imageView.image = UIImage(named: song.photoPath) titleLabel.text = song.title bandLabel.text = song.band descriptionLabel.text = song.description } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
43859564f8a7605c8e71f31af11bd76c
26.075
81
0.638966
4.834821
false
false
false
false
codepath-volunteer-app/VolunteerMe
VolunteerMe/Pods/ParseLiveQuery/Sources/ParseLiveQuery/Internal/ClientPrivate.swift
1
9740
/** * Copyright (c) 2016-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import Parse import Starscream import BoltsSwift private func parseObject<T: PFObject>(_ objectDictionary: [String:AnyObject]) throws -> T { guard let _ = objectDictionary["className"] as? String else { throw LiveQueryErrors.InvalidJSONError(json: objectDictionary, expectedKey: "parseClassName") } guard let _ = objectDictionary["objectId"] as? String else { throw LiveQueryErrors.InvalidJSONError(json: objectDictionary, expectedKey: "objectId") } guard let object = PFDecoder.object().decode(objectDictionary) as? T else { throw LiveQueryErrors.InvalidJSONObject(json: objectDictionary, details: "cannot decode json into \(T.self)") } return object } // --------------- // MARK: Subscriptions // --------------- extension Client { class SubscriptionRecord { weak var subscriptionHandler: AnyObject? // HandlerClosure captures the generic type info passed into the constructor of SubscriptionRecord, // and 'unwraps' it so that it can be used with just a 'PFObject' instance. // Technically, this should be a compiler no-op, as no witness tables should be used as 'PFObject' currently inherits from NSObject. // Should we make PFObject ever a native swift class without the backing Objective-C runtime however, // this becomes extremely important to have, and makes a ton more sense than just unsafeBitCast-ing everywhere. var eventHandlerClosure: (Event<PFObject>, Client) -> Void var errorHandlerClosure: (Error, Client) -> Void var subscribeHandlerClosure: (Client) -> Void var unsubscribeHandlerClosure: (Client) -> Void let query: PFQuery<PFObject> let requestId: RequestId init<T>(query: PFQuery<T.PFObjectSubclass>, requestId: RequestId, handler: T) where T:SubscriptionHandling { self.query = query as! PFQuery<PFObject> self.requestId = requestId subscriptionHandler = handler // This is needed because swift requires 'handlerClosure' to be fully initialized before we setup the // capture list for the closure. eventHandlerClosure = { _, _ in } errorHandlerClosure = { _, _ in } subscribeHandlerClosure = { _ in } unsubscribeHandlerClosure = { _ in } eventHandlerClosure = { [weak self] event, client in guard let handler = self?.subscriptionHandler as? T else { return } handler.didReceive(Event(event: event), forQuery: query, inClient: client) } errorHandlerClosure = { [weak self] error, client in guard let handler = self?.subscriptionHandler as? T else { return } handler.didEncounter(error, forQuery: query, inClient: client) } subscribeHandlerClosure = { [weak self] client in guard let handler = self?.subscriptionHandler as? T else { return } handler.didSubscribe(toQuery: query, inClient: client) } unsubscribeHandlerClosure = { [weak self] client in guard let handler = self?.subscriptionHandler as? T else { return } handler.didUnsubscribe(fromQuery: query, inClient: client) } } } } extension Client { // An opaque placeholder structed used to ensure that we type-safely create request IDs and don't shoot ourself in // the foot with array indexes. struct RequestId: Equatable { let value: Int init(value: Int) { self.value = value } } } func == (first: Client.RequestId, second: Client.RequestId) -> Bool { return first.value == second.value } // --------------- // MARK: Web Socket // --------------- extension Client: WebSocketDelegate { public func websocketDidReceiveData(socket: WebSocket, data: Data) { print("Received binary data but we don't handle it...") } public func websocketDidReceiveMessage(socket: WebSocket, text: String) { handleOperationAsync(text).continueWith { task in if let error = task.error { print("Error: \(error)") } } } public func websocketDidConnect(socket: WebSocket) { let sessionToken = PFUser.current()?.sessionToken ?? "" _ = self.sendOperationAsync(.connect(applicationId: applicationId, sessionToken: sessionToken)) } public func websocketDidDisconnect(socket: WebSocket, error: NSError?) { print("error: \(error)") // TODO: Better retry logic, unless `disconnect()` was explicitly called if !userDisconnected { reconnect() } } public func webSocket(_ webSocket: WebSocket, didCloseWithCode code: Int, reason: String?, wasClean: Bool) { print("code: \(code) reason: \(reason)") // TODO: Better retry logic, unless `disconnect()` was explicitly called if !userDisconnected { reconnect() } } } // ------------------- // MARK: Operations // ------------------- extension Event { init(serverResponse: ServerResponse, requestId: inout Client.RequestId) throws { switch serverResponse { case .enter(let reqId, let object): requestId = reqId self = .entered(try parseObject(object)) case .leave(let reqId, let object): requestId = reqId self = .left(try parseObject(object)) case .create(let reqId, let object): requestId = reqId self = .created(try parseObject(object)) case .update(let reqId, let object): requestId = reqId self = .updated(try parseObject(object)) case .delete(let reqId, let object): requestId = reqId self = .deleted(try parseObject(object)) default: fatalError("Invalid state reached") } } } extension Client { fileprivate func subscriptionRecord(_ requestId: RequestId) -> SubscriptionRecord? { guard let recordIndex = self.subscriptions.index(where: { $0.requestId == requestId }) else { return nil } let record = self.subscriptions[recordIndex] return record.subscriptionHandler != nil ? record : nil } func sendOperationAsync(_ operation: ClientOperation) -> Task<Void> { return Task(.queue(queue)) { let jsonEncoded = operation.JSONObjectRepresentation let jsonData = try JSONSerialization.data(withJSONObject: jsonEncoded, options: JSONSerialization.WritingOptions(rawValue: 0)) let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) self.socket?.write(string: jsonString!) } } func handleOperationAsync(_ string: String) -> Task<Void> { return Task(.queue(queue)) { guard let jsonData = string.data(using: String.Encoding.utf8), let jsonDecoded = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String:AnyObject], let response: ServerResponse = try? ServerResponse(json: jsonDecoded) else { throw LiveQueryErrors.InvalidResponseError(response: string) } switch response { case .connected: let sessionToken = PFUser.current()?.sessionToken self.subscriptions.forEach { _ = self.sendOperationAsync(.subscribe(requestId: $0.requestId, query: $0.query, sessionToken: sessionToken)) } case .redirect: // TODO: Handle redirect. break case .subscribed(let requestId): self.subscriptionRecord(requestId)?.subscribeHandlerClosure(self) case .unsubscribed(let requestId): guard let recordIndex = self.subscriptions.index(where: { $0.requestId == requestId }) else { break } let record: SubscriptionRecord = self.subscriptions[recordIndex] record.unsubscribeHandlerClosure(self) self.subscriptions.remove(at: recordIndex) case .create, .delete, .enter, .leave, .update: var requestId: RequestId = RequestId(value: 0) guard let event: Event<PFObject> = try? Event(serverResponse: response, requestId: &requestId), let record = self.subscriptionRecord(requestId) else { break } record.eventHandlerClosure(event, self) case .error(let requestId, let code, let error, let reconnect): let error = LiveQueryErrors.ServerReportedError(code: code, error: error, reconnect: reconnect) if let requestId = requestId { self.subscriptionRecord(requestId)?.errorHandlerClosure(error, self) } else { throw error } } } } }
mit
08574e440965361bfe58da7574c59ca7
36.034221
140
0.59846
5.129015
false
false
false
false
noppoMan/Slimane
Sources/Slimane/Slimane.swift
1
565
// // Slimane.swift // Slimane // // Created by Yuki Takei on 4/12/16. // Copyright © 2016 MikeTOKYO. All rights reserved. // @_exported import Skelton public class Slimane { internal var middlewares: [Middleware] = [] internal var router = Router() public var setNodelay = false public var keepAliveTimeout: UInt = 15 public var backlog: UInt = 1024 var catchHandler: (Error, Request, Response, (Chainer) -> Void) -> Void = { _ in } var finallyHandler: (Request, Response) -> Void = { _ in } public init(){} }
mit
73d07a73f0f6d96e51705f77098f80fb
19.888889
86
0.631206
3.662338
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/ContactWebsite.swift
1
3721
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Structure representing the website data elements of a contact. @author Francisco Javier Martin Bueno @since v2.0 @version 1.0 */ public class ContactWebsite : APIBean { /** The url of the website */ var url : String? /** Default constructor @since v2.0 */ public override init() { super.init() } /** Constructor used by the implementation @param url Url of the website @since v2.0 */ public init(url: String) { super.init() self.url = url } /** Returns the url of the website @return website url @since v2.0 */ public func getUrl() -> String? { return self.url } /** Set the url of the website @param url Url of the website @since v2.0 */ public func setUrl(url: String) { self.url = url } /** JSON Serialization and deserialization support. */ public struct Serializer { public static func fromJSON(json : String) -> ContactWebsite { let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)! let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary return fromDictionary(dict!) } static func fromDictionary(dict : NSDictionary) -> ContactWebsite { let resultObject : ContactWebsite = ContactWebsite() if let value : AnyObject = dict.objectForKey("url") { if "\(value)" as NSString != "<null>" { resultObject.url = (value as! String) } } return resultObject } public static func toJSON(object: ContactWebsite) -> String { let jsonString : NSMutableString = NSMutableString() // Start Object to JSON jsonString.appendString("{ ") // Fields. object.url != nil ? jsonString.appendString("\"url\": \"\(JSONUtil.escapeString(object.url!))\"") : jsonString.appendString("\"url\": null") // End Object to JSON jsonString.appendString(" }") return jsonString as String } } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
7c702566741e9bf64cca5c9ee6c7aece
27.389313
152
0.567895
4.971925
false
false
false
false
kyleobrien/Cubert
Cubert/primeSieves.swift
1
3134
// // primeSieves.swift // ProjectEuler // // Created by Kyle O'Brien on 2015.7.16. // Copyright (c) 2015 Kyle O'Brien. All rights reserved. // import Foundation enum SieveType { case Eratosthenes case Sundaram } func primesUpTo(limit: Int, withSieveType: SieveType) -> [Int] { var primeNumbers: [Int] switch withSieveType { case .Eratosthenes: primeNumbers = sieveWithEratosthenesUpTo(limit) case .Sundaram: primeNumbers = sieveWithSundaramUpTo(limit) } return primeNumbers } /** Simple implementation of the Sieve of Eratosthenes. - Parameter limit: The upper bound (inclusive) when searching for primes. - Returns An array of prime numbers. */ func sieveWithEratosthenesUpTo(limit: Int) -> [Int] { var primeNumbers = [Int]() if limit >= 2 { var isCompositeNumber = [Int: Bool]() var candidate = 3 primeNumbers.append(2) while candidate <= limit { let isCandidateComposite = isCompositeNumber[candidate] ?? false if !isCandidateComposite { primeNumbers.append(candidate) // Optimization 1: Start marking composites at candidate squared. var compositeNumber = candidate * candidate repeat { isCompositeNumber[compositeNumber] = true compositeNumber += candidate } while compositeNumber < limit } // Optimization 2: Only iterate over odd numbers, since even numbers after 2 aren't prime. candidate += 2 } } return primeNumbers } /** Simple implementation of the Sieve of Sundaram. - Parameter limit: The upper bound (inclusive) when searching for primes. - Returns An array of prime numbers. */ func sieveWithSundaramUpTo(limit: Int) -> [Int] { var primeNumbers = [Int]() if limit >= 2 { var i = 1, j = 1 var isNumberExcluded = [Int: Bool]() primeNumbers.append(2) // Generate a list of numbers that will not have the prime generating // formula applied, with the following two conditions: // 1.) i, j ∈ ℕ, 1 ≤ i ≤ j // 2.) i + j + 2ij ≤ n while (i + j + (2 * i * j)) <= limit { while (i + j + (2 * i * j)) <= limit { isNumberExcluded[i + j + (2 * i * j)] = true j += 1 } i += 1 j = i } // Apply the formula p = 2k + 1 to all the numbers not excluded above. for k in 1...limit { let isCandidateCrossedOut = isNumberExcluded[k] ?? false if !isCandidateCrossedOut { let primeNumber = (2 * k) + 1 if primeNumber > limit { break } else { primeNumbers.append(primeNumber) } } } } return primeNumbers }
mit
8f41ed0c3cd2e10ed516d1ae131742d0
26.892857
102
0.529449
4.469242
false
false
false
false
fireflyexperience/emitter-kit
tests/PerformanceTests.swift
2
617
import XCTest import EmitterKit class PerformanceTests : XCTestCase { var listeners = [Listener]() override func setUp() { super.setUp() listeners = [] } func testNotificationPerformance () { let n = Notification("test1") for _ in 0...99 { self.listeners += n.on { _ in } } measureBlock { for _ in 0...99 { n.emit([:]) } } } func testEmitterPerformance () { let e = Event<NSDictionary>() for _ in 0...99 { self.listeners += e.on { _ in } } measureBlock { for _ in 0...99 { e.emit([:]) } } } }
mit
1745733757e4762d527b51550890d7a5
14.04878
39
0.512156
3.85625
false
true
false
false
honghaoz/FidoUsage
FidoUsage/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Burn.swift
1
7155
// // LTMorphingLabel+Burn.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2015 Lex Tang, http://lexrus.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the “Software”), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit extension LTMorphingLabel { private func burningImageForCharLimbo(charLimbo: LTCharacterLimbo, withProgress progress: CGFloat) -> (UIImage, CGRect) { let maskedHeight = charLimbo.rect.size.height * max(0.01, progress) let maskedSize = CGSizeMake( charLimbo.rect.size.width, maskedHeight) UIGraphicsBeginImageContextWithOptions(maskedSize, false, UIScreen.mainScreen().scale) let rect = CGRectMake(0, 0, charLimbo.rect.size.width, maskedHeight) String(charLimbo.char).drawInRect(rect, withAttributes: [ NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.textColor ]) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let newRect = CGRectMake( charLimbo.rect.origin.x, charLimbo.rect.origin.y, charLimbo.rect.size.width, maskedHeight) return (newImage, newRect) } func BurnLoad() { startClosures["Burn\(LTMorphingPhaseStart)"] = { self.emitterView.removeAllEmitters() } progressClosures["Burn\(LTMorphingPhaseManipulateProgress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if !isNewChar { return min(1.0, max(0.0, progress)) } let j = Float(sin(Float(index))) * 1.5 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } effectClosures["Burn\(LTMorphingPhaseDisappear)"] = { (char:Character, index: Int, progress: Float) in return LTCharacterLimbo( char: char, rect: self.previousRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0 ) } effectClosures["Burn\(LTMorphingPhaseAppear)"] = { (char:Character, index: Int, progress: Float) in if char != " " { let rect = self.newRects[index] let emitterPosition = CGPointMake( rect.origin.x + rect.size.width / 2.0, CGFloat(progress) * rect.size.height / 1.2 + rect.origin.y) self.emitterView.createEmitter("c\(index)", particleName: "Fire", duration: self.morphingDuration) { (layer, cell) in layer.emitterSize = CGSizeMake(rect.size.width , 1) layer.renderMode = kCAEmitterLayerAdditive layer.emitterMode = kCAEmitterLayerOutline cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 160.0 cell.scaleSpeed = self.font.pointSize / 100.0 cell.birthRate = Float(self.font.pointSize) cell.emissionLongitude = CGFloat(arc4random_uniform(30)) cell.emissionRange = CGFloat(M_PI_4) cell.alphaSpeed = self.morphingDuration * -3.0 cell.yAcceleration = 10 cell.velocity = CGFloat(10 + Int(arc4random_uniform(3))) cell.velocityRange = 10 cell.spin = 0 cell.spinRange = 0 cell.lifetime = self.morphingDuration / 3.0 }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() self.emitterView.createEmitter("s\(index)", particleName: "Smoke", duration: self.morphingDuration) { (layer, cell) in layer.emitterSize = CGSizeMake(rect.size.width , 10) layer.renderMode = kCAEmitterLayerAdditive layer.emitterMode = kCAEmitterLayerVolume cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 40.0 cell.scaleSpeed = self.font.pointSize / 100.0 cell.birthRate = Float(self.font.pointSize) / Float(arc4random_uniform(10) + 10) cell.emissionLongitude = 0 cell.emissionRange = CGFloat(M_PI_4) cell.alphaSpeed = self.morphingDuration * -3 cell.yAcceleration = -5 cell.velocity = CGFloat(20 + Int(arc4random_uniform(15))) cell.velocityRange = 20 cell.spin = CGFloat(Float(arc4random_uniform(30)) / 10.0) cell.spinRange = 3 cell.lifetime = self.morphingDuration }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() } return LTCharacterLimbo( char: char, rect: self.newRects[index], alpha: 1.0, size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } drawingClosures["Burn\(LTMorphingPhaseDraw)"] = { (charLimbo: LTCharacterLimbo) in if charLimbo.drawingProgress > 0.0 { let (charImage, rect) = self.burningImageForCharLimbo(charLimbo, withProgress: charLimbo.drawingProgress) charImage.drawInRect(rect) return true } return false } skipFramesClosures["Burn\(LTMorphingPhaseSkipFrames)"] = { return 1 } } }
mit
a0bed7c49e576f2bca29365c61abfca5
42.315152
125
0.559675
5.134339
false
false
false
false
silkyprogrammer/iOS-Lessons
Dictionaries.playground/Contents.swift
1
6269
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print("Hello Hari") print(str) var myVariable = 50 let newVariable = 42 //newVariable = 50 - constant by "let" let implicitInteger = 10 let implicitDouble = 20 let explicitDouble:Double = 40 let explicitFloat:Float = 4 let label = "The width is " let width = 98 let widthLabel = label + String(width) //let widthLabel = label + width - binary operator cannot be applied to operands of type string and int. let apples = 8 let oranges = 10 let appleSummary = "I have \(apples) apples!" let fruitSummary = "I have \(apples) apples and \(oranges) oranges, in total \(apples+oranges) fruits!" //let quotes = """ // Where there is a will there // is a // way // """ var shoppingList = ["catfish","water","tulips","blue paint"] shoppingList[1] var occupations = [ "malcolm" : "Captain", "kaylee" : "Mechanic" ] occupations["jane"] = "Flowerist" //occupations let emptyArray = [String]() let emptyDict = [String:Float]() shoppingList = [] occupations = [:] let individualScores = [10,20,30,40,50] var teamScore = 0 for score in individualScores{ if score > 30{ teamScore += 3 }else{ teamScore += 1 } } print(teamScore) var optionalString:String? = "Hello" print(optionalString == nil) var optionalName:String? = "Homely Lyric!" //var optionalName:String? = nil var greeting = "" if let name = optionalName{ greeting = "Hello\(name)" print(greeting) } //else{ // print(greeting) //} let vegetable = "red" switch vegetable { case "celery": print("Add some raisins and make ants on a log.") case "cucumber", "watercress": print("That would make a good tea sandwich.") case let x where x.hasSuffix("pepper"): print("Is it a spicy \(x)?") default: print("Everything tastes good in soup") } let interestingNumbers = [ "Prime" : [2,3,5,7,11,13], "Fibonacci": [1,1,2,3,5,8], "Square": [1,4,9,16,25] ] var largest = 0 for (kind, numbers) in interestingNumbers{ for number in numbers{ if number > largest{ largest = number } } } print(largest) var n = 2 while n < 100 { n *= 2 } print(n) var m = 2 repeat{ m *= 2 }while m < 100 print(m) var total = 0 for i in 0..<4{ total += i } print(total) func greet(person:String, day:String) -> String{ return "Hello \(person), today is \(day)" } print(greet(person: "Hari", day: "Monday")) func greeting(_ person:String, on day:String) -> String{ return "Hello \(person), today is \(day)." } greeting("Hari", on:"Wednesday") func calculateStatistics(scores: [Int]) -> (min:Int, max:Int, sum:Int) { var min = scores[0] var max = scores[0] var sum = 0 for score in scores{ if score > max{ max = score }else if score < min{ min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [5,3,100,3,9]) print(statistics.sum) print(statistics.2) func returnFifteen() -> Int{ var y = 10 func add(){ y += 5 } add() return y } returnFifteen() func makeIncrementer() -> ((Int)-> Int){ func addOne(number: Int) -> Int{ return 1 + number } return addOne } var increment = makeIncrementer() increment(1) func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool{ for item in list{ if condition(item){ return true } } return false } func lessThanTen(number: Int) -> Bool{ return number < 10 } var numbers = [20,19,7, 12] hasAnyMatches(list: numbers, condition: lessThanTen) numbers.map({(number:Int) -> Int in let result = 3 * number return result }) class Shape{ var numberOfSides = 0 func simpleDescription() -> String { return "A Shape with \(numberOfSides) sides." } } class NamedShape{ var numberOfSides: Int = 0 var name:String init(name:String){ self.name = name } func SimpleDescription() -> String { return "A Shape with \(numberOfSides) sides." } } class Square: NamedShape{ var sideLength:Double init(sideLength: Double, name:String){ self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func Area() -> Double { return sideLength * sideLength } override func SimpleDescription() -> String { return "A square with sides of length \(sideLength)." } } let test = Square(sideLength: 5.2, name: "my Test Square") test.Area() test.SimpleDescription() class EquilateralTriangle: NamedShape{ var sideLength: Double = 0.0 init(sideLength:Double, name:String){ self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } var perimeter:Double{ get{ return 3.0 * sideLength } set{ sideLength = newValue / 3.0 } } override func SimpleDescription() -> String { return "An equilateral triangle with sides of Length \(sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "A Triangle") print(triangle.perimeter) triangle.perimeter = 9.9 print(triangle.sideLength) class TriangleAndSquare{ var triangle: EquilateralTriangle{ willSet{ square.sideLength = newValue.sideLength } } var square: Square{ willSet{ triangle.sideLength = newValue.sideLength } } init(size:Double, name:String){ square = Square(sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) } } var trianglAndSquare = TriangleAndSquare(size: 10, name: "Another Test Shape") print(trianglAndSquare.square.sideLength) print(trianglAndSquare.triangle.sideLength) trianglAndSquare.square = Square(sideLength: 50, name: "Large square") print(trianglAndSquare.triangle.sideLength) let optionalSquare:Square? = Square(sideLength: 2.5, name: "Optional Square") let sideLength = optionalSquare?.sideLength
mit
6474f4640132dd85a46db7b16e5ad4bf
15.454068
104
0.616685
3.657526
false
false
false
false
aclissold/the-oakland-post
The Oakland Post/PostTableViewController.swift
2
4626
// // PostTableViewController.swift // The Oakland Post // // The main feature of the app: a table view of posts. // // Created by Andrew Clissold on 6/13/14. // Copyright (c) 2014 Andrew Clissold. All rights reserved. // import UIKit class PostTableViewController: BugFixTableViewController, MWFeedParserDelegate, StarButtonDelegate { var baseURL: String! var feedParser: FeedParser! var parsedItems = [MWFeedItem]() var finishedParsing = false override func viewDidLoad() { super.viewDidLoad() // Pull to refresh. let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) self.refreshControl = refreshControl feedParser = FeedParser(baseURL: baseURL, length: 15, delegate: self) feedParser.parseInitial() tableView.addInfiniteScrollingWithActionHandler(loadMorePosts) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if !finishedParsing { UIApplication.sharedApplication().networkActivityIndicatorVisible = true SVProgressHUD.show() } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) UIApplication.sharedApplication().networkActivityIndicatorVisible = false SVProgressHUD.dismiss() } func refresh() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true tableView.userInteractionEnabled = false parsedItems.removeAll() feedParser.parseInitial() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } func loadMorePosts() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true tableView.userInteractionEnabled = false feedParser.parseMore() } // MARK: StarButtonDelegate func didSelectStarButton(starButton: UIButton, forItem item: MWFeedItem) { starButton.selected = !starButton.selected if starButton.selected { // Persist the new favorite. let object = PFObject(item: item) object.saveEventually() BugFixWrapper.starredPosts.append(object) } else { deleteStarredPostWithIdentifier(item.identifier) } } // MARK: MWFeedParserDelegate func feedParser(parser: MWFeedParser!, didParseFeedItem item: MWFeedItem!) { parsedItems.append(item) } func feedParserDidFinish(parser: MWFeedParser!) { finishedParsing = true reloadData() } func feedParser(parser: MWFeedParser!, didFailWithError error: NSError!) { showAlertForErrorCode(feedParserDidFailErrorCode) finishedParsing = true reloadData() } func reloadData() { tableView.reloadData() UIApplication.sharedApplication().networkActivityIndicatorVisible = false SVProgressHUD.dismiss() refreshControl!.endRefreshing() tableView.infiniteScrollingView.stopAnimating() tableView.userInteractionEnabled = true } // MARK: Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == readPostID { let indexPath = self.tableView.indexPathForSelectedRow! let item = parsedItems[indexPath.row] as MWFeedItem (segue.destinationViewController as! PostViewController).URL = item.link } } // MARK: Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return parsedItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! PostCell cell.delegate = self if indexPath.row <= parsedItems.count { cell.item = parsedItems[indexPath.row] as MWFeedItem cell.starButton.hidden = PFUser.currentUser() == nil if !cell.starButton.hidden { cell.starButton.selected = starredPostIdentifiers.contains(cell.item.identifier) } } return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return tableViewRowHeight } }
bsd-3-clause
2a25c743f7b8e943dddb84e7a2489f37
30.903448
118
0.680285
5.634592
false
false
false
false
Sourcegasm/Math-Parser-Swift
Math Parser/main.swift
1
1007
// // main.swift // Math Parser // // Created by Vid Drobnic on 8/4/15. // Copyright (c) 2015 Vid Drobnic. All rights reserved. // import Foundation let expression = "cos(-0)"//"3123234×91243+7^3+32!÷16-asinh(cos(√(2,π+e)))" let start = NSDate.timeIntervalSinceReferenceDate() let result = evaluateExpression(expression, MathParserAngleUnit.Degrees) let end = NSDate.timeIntervalSinceReferenceDate() let difference = Double(end) - Double(start) var resultString: String if let unwrapedResult = result { if unwrapedResult == Double.infinity { resultString = "Math error" } else if unwrapedResult == -0.0 { resultString = "\(-unwrapedResult)" resultString = mathParserFormatNumber(resultString) } else { resultString = "\(unwrapedResult)" resultString = mathParserFormatNumber(resultString) } } else { resultString = "Syntax error" } println("\(mathParserFormatExpression(expression)) = \(resultString)\nTime: \(difference * 1000)ms")
mit
5994edb3314f037b0beb9445d7b1a3c2
28.5
100
0.697605
3.83908
false
false
false
false
Arty-Maly/Volna
Volna/Colors.swift
1
1425
// // colors.swift // Volna // // Created by Artem Malyshev on 2/17/17. // Copyright © 2017 Artem Malyshev. All rights reserved. // import UIKit struct Colors { static let borderColor = UIColor(red:0.31, green:0.52, blue:0.61, alpha:1.0) static let darkerBlue = UIColor(red:0.27, green:0.45, blue:0.53, alpha:1.0) static let lighterBlue = UIColor(red:0.38, green:0.65, blue:0.76, alpha:1.0) static let highlightColor = UIColor(red:0.84, green:0.86, blue:0.88, alpha:0.85) static let darkerBlueBorderColor = UIColor(red:0.24, green:0.40, blue:0.47, alpha:1.0) static func bottomGradient() -> CAGradientLayer { return gradient(lighterBlue, darkerBlue) } static func topGradient() -> CAGradientLayer { return gradient(darkerBlue, lighterBlue) } private static func gradient(_ top_color: UIColor, _ bottom_color: UIColor) -> CAGradientLayer { let gl = CAGradientLayer() gl.colors = [top_color.cgColor, bottom_color.cgColor] gl.locations = [0.0, 1.0] return gl } static func getUIntColor() -> UInt { var colorAsUInt : UInt32 = 0 var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 if Colors.darkerBlue.getRed(&red, green: &green, blue: &blue, alpha: &alpha) { colorAsUInt += UInt32(red * 255.0) << 16 + UInt32(green * 255.0) << 8 + UInt32(blue * 255.0) } return UInt(colorAsUInt) } }
gpl-3.0
b0a97678a7ad9934ac5e3e28ed659ad5
31.363636
98
0.654494
3.2
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/ViewControllerProgressProcess.swift
1
3366
// // ViewControllerProgressProcess.swift // RsyncOSXver30 // // Created by Thomas Evensen on 24/08/2016. // Copyright © 2016 Thomas Evensen. All rights reserved. // import Cocoa // Protocol for progress indicator protocol Count: AnyObject { func maxCount() -> Int func inprogressCount() -> Int } class ViewControllerProgressProcess: NSViewController, SetConfigurations, SetDismisser, Abort { var count: Double = 0 var maxcount: Double = 0 weak var countDelegate: Count? @IBOutlet var abort: NSButton! @IBOutlet var progress: NSProgressIndicator! @IBAction func abort(_: NSButton) { switch countDelegate { case is ViewControllerSnapshots: dismissview(viewcontroller: self, vcontroller: .vcsnapshot) case is ViewControllerRestore: dismissview(viewcontroller: self, vcontroller: .vcrestore) default: dismissview(viewcontroller: self, vcontroller: .vctabmain) } abort() } override func viewDidAppear() { super.viewDidAppear() SharedReference.shared.setvcref(viewcontroller: .vcprogressview, nsviewcontroller: self) if (presentingViewController as? ViewControllerMain) != nil { if let pvc = (presentingViewController as? ViewControllerMain)?.singletask { countDelegate = pvc } } else if (presentingViewController as? ViewControllerRestore) != nil { countDelegate = SharedReference.shared.getvcref(viewcontroller: .vcrestore) as? ViewControllerRestore } else if (presentingViewController as? ViewControllerSnapshots) != nil { countDelegate = SharedReference.shared.getvcref(viewcontroller: .vcsnapshot) as? ViewControllerSnapshots } initiateProgressbar() abort.isEnabled = true } override func viewWillDisappear() { super.viewWillDisappear() stopProgressbar() SharedReference.shared.setvcref(viewcontroller: .vcprogressview, nsviewcontroller: nil) } private func stopProgressbar() { progress.stopAnimation(self) } // Progress bars private func initiateProgressbar() { if (presentingViewController as? ViewControllerSnapshots) != nil { progress.maxValue = Double(countDelegate?.maxCount() ?? 0) } else { progress.maxValue = Double((countDelegate?.maxCount() ?? 0) + SharedReference.shared.extralines) } progress.minValue = 0 progress.doubleValue = 0 progress.startAnimation(self) } private func updateProgressbar(_ value: Double) { progress.doubleValue = value } } extension ViewControllerProgressProcess: UpdateProgress { func processTermination() { stopProgressbar() switch countDelegate { case is ViewControllerMain: dismissview(viewcontroller: self, vcontroller: .vctabmain) case is ViewControllerSnapshots: dismissview(viewcontroller: self, vcontroller: .vcsnapshot) case is ViewControllerRestore: dismissview(viewcontroller: self, vcontroller: .vcrestore) default: dismissview(viewcontroller: self, vcontroller: .vctabmain) } } func fileHandler() { updateProgressbar(Double(countDelegate?.inprogressCount() ?? 0)) } }
mit
17d2f3a77dbf998c06a01f020f273994
33.690722
116
0.671025
4.941263
false
false
false
false
powerytg/Accented
Accented/UI/Home/Menu/Sections/MainMenuAuthenticatedUserSectionView.swift
1
7578
// // MainMenuAuthenticatedUserSectionView.swift // Accented // // Main menu section for authenticated user // // Created by Tiangong You on 8/27/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class MainMenuAuthenticatedUserSectionView: MainMenuSectionBase { private let rowHeight : CGFloat = 32 private let paddingTop : CGFloat = 32 private let separatorHeight : CGFloat = 16 let signedInOptions = [MenuItem(action : .Search, text: "Search", image : UIImage(named: "SearchButtonMainMenu")), MenuSeparator(), MenuItem(action:.MyPhotos, text: "My Photos"), MenuItem(action:.MyGalleries, text: "My Galleries"), MenuItem(action:.MyProfile, text: "My Profile"), MenuSeparator(), MenuItem(action:.MyFriends, text: "My Friends"), MenuItem(action:.FriendsPhotos, text: "Recent Activities"), MenuSeparator(), MenuItem(action:.PearlCam, text: "Pearl Cam"), MenuSeparator(), MenuItem(action:.About, text: "Feedback And About"), MenuItem(action:.SignOut, text: "Sign Out")] let signedOutOptions = [MenuItem(action : .Search, text: "Search", image : UIImage(named: "SearchButtonMainMenu")), MenuSeparator(), MenuItem(action:.PopularPhotos, text: "Popular Photos"), MenuItem(action:.FreshPhotos, text: "Fresh"), MenuItem(action:.UpcomingPhotos, text: "Upcoming"), MenuItem(action:.EditorsChoice, text: "Editors' Choice"), MenuSeparator(), MenuItem(action:.PearlCam, text: "Pearl Cam"), MenuSeparator(), MenuItem(action:.About, text: "Feedback And About"), MenuItem(action:.SignIn, text: "Sign In")] private var renderers = [MainMenuItemRenderer]() private var currentMenu : [MenuItem]! override func initialize() { super.initialize() if StorageService.sharedInstance.currentUser != nil { currentMenu = signedInOptions } else { currentMenu = signedOutOptions } for item in currentMenu { let renderer = MainMenuItemRenderer(item) contentView.addSubview(renderer) renderers.append(renderer) let tap = UITapGestureRecognizer(target: self, action: #selector(menuItemDidReceiveTap(_:))) renderer.addGestureRecognizer(tap) } } override func calculateContentHeight(maxWidth: CGFloat) -> CGFloat { var totalHeight : CGFloat = 0 for item in currentMenu { if item is MenuSeparator { totalHeight += separatorHeight } else { totalHeight += rowHeight } } return totalHeight + paddingTop } override func layoutSubviews() { super.layoutSubviews() var nextY : CGFloat = paddingTop for renderer in renderers { var f = renderer.frame f.origin.x = contentLeftPadding f.origin.y = nextY f.size.width = contentView.bounds.width - contentLeftPadding - contentRightPadding if renderer.menuItem is MenuSeparator { f.size.height = separatorHeight } else { f.size.height = rowHeight } renderer.frame = f if renderer.menuItem is MenuSeparator { nextY += separatorHeight } else { nextY += rowHeight } } } @objc private func menuItemDidReceiveTap(_ tap : UITapGestureRecognizer) { guard tap.view != nil else { return } guard tap.view! is MainMenuItemRenderer else { return } let renderer = tap.view! as! MainMenuItemRenderer didSelectMenuItem(renderer.menuItem) } private func didSelectMenuItem(_ item : MenuItem) { switch item.action { case .SignIn: drawer?.dismiss(animated: false, completion: nil) NavigationService.sharedInstance.signout() case .SignOut: drawer?.dismiss(animated: false, completion: nil) NavigationService.sharedInstance.signout() case .PopularPhotos: switchStream(.Popular) drawer?.dismiss(animated: true, completion: nil) case .FreshPhotos: switchStream(.FreshToday) drawer?.dismiss(animated: true, completion: nil) case .UpcomingPhotos: switchStream(.Upcoming) drawer?.dismiss(animated: true, completion: nil) case .EditorsChoice: switchStream(.Editors) drawer?.dismiss(animated: true, completion: nil) case .PearlCam: drawer?.dismiss(animated: true, completion: { NavigationService.sharedInstance.navigateToCamera() }) case .Search: drawer?.dismiss(animated: true, completion: { if let topVC = NavigationService.sharedInstance.topViewController() { NavigationService.sharedInstance.navigateToSearch(from: topVC) } }) case .MyProfile: drawer?.dismiss(animated: true, completion: { if let currentUser = StorageService.sharedInstance.currentUser { NavigationService.sharedInstance.navigateToUserProfilePage(user: currentUser) } }) case .MyGalleries: drawer?.dismiss(animated: true, completion: { if let currentUser = StorageService.sharedInstance.currentUser { NavigationService.sharedInstance.navigateToUserGalleryListPage(user: currentUser) } }) case .MyPhotos: drawer?.dismiss(animated: true, completion: { if let currentUser = StorageService.sharedInstance.currentUser { NavigationService.sharedInstance.navigateToUserStreamPage(user: currentUser) } }) case .MyFriends: drawer?.dismiss(animated: true, completion: { if let currentUser = StorageService.sharedInstance.currentUser { NavigationService.sharedInstance.navigateToUserFriendsPage(user: currentUser) } }) case .FriendsPhotos: drawer?.dismiss(animated: true, completion: { if let currentUser = StorageService.sharedInstance.currentUser { NavigationService.sharedInstance.navigateToUserFriendsPhotosPage(user: currentUser) } }) case .About: drawer?.dismiss(animated: true, completion: { NavigationService.sharedInstance.navigateToAboutPage() }) default: break } } private func switchStream(_ streamType: StreamType) { let userInfo = [StreamEvents.selectedStreamType : streamType.rawValue] NotificationCenter.default.post(name: StreamEvents.streamSelectionWillChange, object: nil, userInfo: userInfo) } }
mit
f3d6245df72e53cf685086257e723f54
39.518717
119
0.568827
5.579529
false
false
false
false
wisonlin/AppBook
AppBook/TMUIKit/LabelRender.swift
1
2099
// // LabelRender.swift // AppBook // // Created by wison on 14-6-20. // Copyright (c) 2014年 Time Studio. All rights reserved. // import Foundation import UIKit class LabelRender { var renderQueue: NSOperationQueue! var renderOperationPool: Dictionary<Int, NSBlockOperation> var renderCache: Dictionary<String, UIImage> class func sharedLabelRender() -> LabelRender! { struct Static { static var instance: LabelRender? } if !Static.instance { Static.instance = LabelRender() } return Static.instance! } init() { self.renderQueue = NSOperationQueue() self.renderQueue.maxConcurrentOperationCount = 1 self.renderOperationPool = [:] self.renderCache = [:] } func renderImageFromText(text: String, commandId: Int, finishedBlock: (image: UIImage, commandId: Int) -> ()) -> Int { var cacheImage = self.renderCache[text] if cacheImage { finishedBlock(image:cacheImage!, commandId:commandId) return commandId } var blockOperation: NSBlockOperation blockOperation = NSBlockOperation(block:{ //if blockOperation.cancelled { // return //} UIGraphicsBeginImageContext(CGSizeMake(320, 52)) (text as NSString).drawInRect(CGRectMake(0, 0, 320, 52), withFont:UIFont.systemFontOfSize(26)) var image = UIGraphicsGetImageFromCurrentImageContext() self.renderCache[text] = image dispatch_async(dispatch_get_main_queue(), { finishedBlock(image: image, commandId: commandId) self.renderOperationPool.removeValueForKey(commandId) }) }); self.renderOperationPool[commandId] = blockOperation self.renderQueue.addOperation(blockOperation) return commandId } func cancelRender(commandId: Int) -> () { var operation = self.renderOperationPool[commandId] operation?.cancel() } }
mit
d70f8ef50ba6414014c2d56b32aaf593
30.772727
122
0.615165
4.854167
false
false
false
false
boycechang/BCColor
BCColor/HexColorViewController.swift
1
1541
// // HexColorViewController.swift // BCColorDemo // // Created by Boyce on 4/12/16. // Copyright © 2016 Boyce. All rights reserved. // import UIKit class HexColorViewController: UIViewController { @IBOutlet fileprivate weak var label_1: UILabel! @IBOutlet fileprivate weak var view_1: UIView! @IBOutlet fileprivate weak var label_2: UILabel! @IBOutlet fileprivate weak var view_2: UIView! @IBOutlet fileprivate weak var label_3: UILabel! @IBOutlet fileprivate weak var view_3: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. label_1.text = "123456" view_1.backgroundColor = UIColor.colorWithHex("123456") label_2.text = "#5d13e2" view_2.backgroundColor = UIColor.colorWithHex("#5d13e2", alpha: 1) label_3.text = "#931" view_3.backgroundColor = UIColor.colorWithHex("#931", alpha: 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
1dbef7e053fc86cecec88e35625aac63
28.056604
106
0.653896
4.556213
false
false
false
false
zapdroid/RXWeather
Pods/Nimble/Sources/Nimble/Matchers/AllPass.swift
1
3841
import Foundation public func allPass<T, U> (_ passFunc: @escaping (T?) -> Bool) -> NonNilMatcherFunc<U> where U: Sequence, U.Iterator.Element == T { return allPass("pass a condition", passFunc) } public func allPass<T, U> (_ passName: String, _ passFunc: @escaping (T?) -> Bool) -> NonNilMatcherFunc<U> where U: Sequence, U.Iterator.Element == T { return createAllPassMatcher { expression, failureMessage in failureMessage.postfixMessage = passName return passFunc(try expression.evaluate()) } } public func allPass<U, V> (_ matcher: V) -> NonNilMatcherFunc<U> where U: Sequence, V: Matcher, U.Iterator.Element == V.ValueType { return createAllPassMatcher { try matcher.matches($0, failureMessage: $1) } } private func createAllPassMatcher<T, U> (_ elementEvaluator: @escaping (Expression<T>, FailureMessage) throws -> Bool) -> NonNilMatcherFunc<U> where U: Sequence, U.Iterator.Element == T { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.actualValue = nil if let actualValue = try actualExpression.evaluate() { for currentElement in actualValue { let exp = Expression( expression: { currentElement }, location: actualExpression.location) if try !elementEvaluator(exp, failureMessage) { failureMessage.postfixMessage = "all \(failureMessage.postfixMessage)," + " but failed first at element <\(stringify(currentElement))>" + " in <\(stringify(actualValue))>" return false } } failureMessage.postfixMessage = "all \(failureMessage.postfixMessage)" } else { failureMessage.postfixMessage = "all pass (use beNil() to match nils)" return false } return true } } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func allPassMatcher(_ matcher: NMBObjCMatcher) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() var nsObjects = [NSObject]() var collectionIsUsable = true if let value = actualValue as? NSFastEnumeration { let generator = NSFastEnumerationIterator(value) while let obj = generator.next() { if let nsObject = obj as? NSObject { nsObjects.append(nsObject) } else { collectionIsUsable = false break } } } else { collectionIsUsable = false } if !collectionIsUsable { failureMessage.postfixMessage = "allPass only works with NSFastEnumeration (NSArray, NSSet, ...) of NSObjects" failureMessage.expected = "" failureMessage.to = "" return false } let expr = Expression(expression: ({ nsObjects }), location: location) let elementEvaluator: (Expression<NSObject>, FailureMessage) -> Bool = { expression, failureMessage in matcher.matches({ try! expression.evaluate() }, failureMessage: failureMessage, location: expr.location) } return try! createAllPassMatcher(elementEvaluator).matches( expr, failureMessage: failureMessage) } } } #endif
mit
893539d8b3a040da439bb44b4562dc72
39.861702
124
0.563916
5.623719
false
false
false
false
jdkelley/Udacity-OnTheMap-ExampleApps
MyFavoriteMovies/MyFavoriteMovies/Movie.swift
1
1071
// // Movie.swift // MyFavoriteMovies // // Created by Jarrod Parkes on 1/23/15. // Copyright (c) 2015 Udacity. All rights reserved. // import UIKit // MARK: - Movie struct Movie { // MARK: Properties let title: String let id: Int let posterPath: String? // MARK: Initializers init(dictionary: [String:AnyObject]) { title = dictionary[Constants.TMDBResponseKeys.Title] as! String id = dictionary[Constants.TMDBResponseKeys.ID] as! Int posterPath = dictionary[Constants.TMDBResponseKeys.PosterPath] as? String } static func moviesFromResults(results: [[String:AnyObject]]) -> [Movie] { var movies = [Movie]() // iterate through array of dictionaries, each Movie is a dictionary for result in results { movies.append(Movie(dictionary: result)) } return movies } } // MARK: - Movie: Equatable extension Movie: Equatable {} func ==(lhs: Movie, rhs: Movie) -> Bool { return lhs.id == rhs.id }
mit
2764eb79edbcadfe8e3441480ac06828
20.857143
81
0.606909
4.167315
false
false
false
false