repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
noxytrux/RescueKopter
refs/heads/master
RescueKopter/Utilities.swift
mit
1
// // Utilities.swift // RescueKopter // // Created by Marcin Pędzimąż on 15.11.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit import QuartzCore let kKPTDomain:String! = "KPTDomain" struct imageStruct { var width : Int = 0 var height : Int = 0 var bitsPerPixel : Int = 0 var hasAlpha : Bool = false var bitmapData : UnsafeMutablePointer<Void>? = nil } func createImageData(name: String!,inout texInfo: imageStruct) { let baseImage = UIImage(named: name) let image: CGImageRef? = baseImage?.CGImage if let image = image { texInfo.width = CGImageGetWidth(image) texInfo.height = CGImageGetHeight(image) texInfo.bitsPerPixel = CGImageGetBitsPerPixel(image) texInfo.hasAlpha = CGImageGetAlphaInfo(image) != .None let sizeInBytes = texInfo.width * texInfo.height * texInfo.bitsPerPixel / 8 let bytesPerRow = texInfo.width * texInfo.bitsPerPixel / 8 texInfo.bitmapData = malloc(Int(sizeInBytes)) let context: CGContextRef? = CGBitmapContextCreate( texInfo.bitmapData!, texInfo.width, texInfo.height, 8, bytesPerRow, CGImageGetColorSpace(image), CGImageGetBitmapInfo(image).rawValue) if let context = context { CGContextDrawImage( context, CGRectMake(0, 0, CGFloat(texInfo.width), CGFloat(texInfo.height)), image) } } } func convertToRGBA(inout texInfo: imageStruct) { assert(texInfo.bitsPerPixel == 24, "Wrong image format") let stride = texInfo.width * 4 let newPixels = malloc(stride * texInfo.height) var dstPixels = UnsafeMutablePointer<UInt32>(newPixels) var r: UInt8, g: UInt8, b: UInt8, a: UInt8 a = 255 let sourceStride = texInfo.width * texInfo.bitsPerPixel / 8 let pointer = texInfo.bitmapData! for var j : Int = 0; j < texInfo.height; j++ { for var i : Int = 0; i < sourceStride; i+=3 { let position : Int = Int(i + (sourceStride * j)) var srcPixel = UnsafeMutablePointer<UInt8>(pointer + position) r = srcPixel.memory srcPixel++ g = srcPixel.memory srcPixel++ b = srcPixel.memory srcPixel++ dstPixels.memory = (UInt32(a) << 24 | UInt32(b) << 16 | UInt32(g) << 8 | UInt32(r) ) dstPixels++ } } if let _ = texInfo.bitmapData { free(texInfo.bitmapData!) } texInfo.bitmapData = newPixels texInfo.bitsPerPixel = 32 texInfo.hasAlpha = true } struct mapDataStruct { var object: UInt32 //BGRA! var playerSpawn: UInt8 { return UInt8(object & 0x000000FF) } var ground: UInt8 { return UInt8((object & 0x0000FF00) >> 8) } var grass: UInt8 { return UInt8((object & 0x00FF0000) >> 16) } var wall: UInt8 { return UInt8((object & 0xFF000000) >> 24) } var desc : String { return "(\(self.ground),\(self.grass),\(self.wall),\(self.playerSpawn))" } } func makeNormal(x1:Float32, y1:Float32, z1:Float32, x2:Float32, y2:Float32, z2:Float32, x3:Float32, y3:Float32, z3:Float32, inout rx:Float32, inout ry:Float32, inout rz:Float32 ) { let ax:Float32 = x3-x1, ay:Float32 = y3-y1, az:Float32 = z3-z1, bx:Float32 = x2-x1, by:Float32 = y2-y1, bz:Float32 = z2-z1 rx = ay*bz - by*az ry = bx*az - ax*bz rz = ax*by - bx*ay } func createARGBBitmapContext(inImage: CGImage) -> CGContext! { var bitmapByteCount = 0 var bitmapBytesPerRow = 0 let pixelsWide = CGImageGetWidth(inImage) let pixelsHigh = CGImageGetHeight(inImage) bitmapBytesPerRow = Int(pixelsWide) * 4 bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapData = malloc(Int(bitmapByteCount)) let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue) let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, Int(8), Int(bitmapBytesPerRow), colorSpace, bitmapInfo.rawValue) return context } func loadMapData(mapName: String) -> (data: UnsafeMutablePointer<Void>, width: Int, height: Int) { let image = UIImage(named: mapName) let inImage = image?.CGImage let cgContext = createARGBBitmapContext(inImage!) let imageWidth = CGImageGetWidth(inImage) let imageHeight = CGImageGetHeight(inImage) var rect = CGRectZero rect.size.width = CGFloat(imageWidth) rect.size.height = CGFloat(imageHeight) CGContextDrawImage(cgContext, rect, inImage) let dataPointer = CGBitmapContextGetData(cgContext) return (dataPointer, imageWidth, imageHeight) }
566a6a76967c723c543c13fabc3a258d
24.726368
98
0.598143
false
false
false
false
honghaoz/CrackingTheCodingInterview
refs/heads/master
Swift/LeetCode/Binary Search/69_Sqrt(x).swift
mit
1
// 69_Sqrt(x) // https://leetcode.com/problems/sqrtx/submissions/ // // Created by Honghao Zhang on 9/15/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Implement int sqrt(int x). // //Compute and return the square root of x, where x is guaranteed to be a non-negative integer. // //Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. // //Example 1: // //Input: 4 //Output: 2 //Example 2: // //Input: 8 //Output: 2 //Explanation: The square root of 8 is 2.82842..., and since // the decimal part is truncated, 2 is returned. // // Tag: Binary search // 求sqrt(x) import Foundation class Num69 { // Use binary search to find the result in the range 1...x - 1 func mySqrt(_ x: Int) -> Int { guard x > 1 else { return x } var start = 1 var end = x - 1 while start + 1 < end { let mid = start + (end - start) / 2 if mid * mid < x { start = mid } else if mid * mid > x { end = mid } else { return mid } } return start } }
3a0a45d8b6225134821b99c976cdfc8f
20.471698
124
0.591388
false
false
false
false
blomma/gameoflife
refs/heads/master
gameoflife/Cell.swift
mit
1
enum CellState { case alive, dead } class Cell { let x: Int let y: Int var state: CellState var neighbours: [Cell] = [Cell]() init(state: CellState, x: Int, y: Int) { self.state = state self.x = x self.y = y } } extension Cell: Hashable { var hashValue: Int { return x.hashValue ^ y.hashValue } static func ==(lhs: Cell, rhs: Cell) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } }
2ba5ccfa4a95b287711b092a615598f9
14.5
50
0.578341
false
false
false
false
Yurssoft/QuickFile
refs/heads/master
QuickFile/Additional_Classes/Extensions/YSTabBarControllerExtension.swift
mit
1
// // YSTabBarController.swift // YSGGP // // Created by Yurii Boiko on 9/28/16. // Copyright © 2016 Yurii Boiko. All rights reserved. // import UIKit extension UITabBarController { func setTabBarVisible(isVisible: Bool, animated: Bool, completion: (() -> Swift.Void)? = nil) { let tabBarFrame = tabBar.frame let tabBarHeight = tabBarFrame.size.height let offsetY = (isVisible ? -tabBarHeight : tabBarHeight) let duration: TimeInterval = (animated ? 0.3 : 0.0) UIView.animate(withDuration: duration, animations: { [weak self] in self?.tabBar.frame = tabBarFrame.offsetBy(dx: 0, dy: offsetY) }, completion: { (isFinished) in if isFinished && completion != nil { completion!() } }) } func tabBarIsVisible() -> Bool { return tabBar.frame.origin.y < UIScreen.main.bounds.height } open override func viewDidLayoutSubviews() { print("")//seems to have fixed bug with resetting frame of UITabBarController's tabBar } }
44484cf6a86d9763b8ad883ddbcf2805
32.314286
100
0.575472
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Controllers/Settings/Passphrase/Views/PassphraseView.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // 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 UIKit import SweetUIKit struct Word { let index: Int let text: String init(_ index: Int, _ text: String) { self.index = index self.text = text } } typealias Phrase = [Word] typealias Layout = [NSLayoutConstraint] protocol AddDelegate: class { func add(_ wordView: PassphraseWordView) } protocol RemoveDelegate: class { func remove(_ wordView: PassphraseWordView) } protocol VerificationDelegate: class { func verify(_ phrase: Phrase) -> VerificationStatus } enum PassphraseType { case original case shuffled case verification } enum VerificationStatus { case unverified case tooShort case correct case incorrect } class PassphraseView: UIView { private var type: PassphraseType = .original var verificationStatus: VerificationStatus = .unverified { didSet { if self.verificationStatus == .incorrect { DispatchQueue.main.asyncAfter(seconds: 0.5) { self.shake() } } else { Profile.current?.updateVerificationState(self.verificationStatus == .correct) } } } private var originalPhrase: Phrase = [] private var currentPhrase: Phrase = [] private var layout: Layout = [] let margin: CGFloat = 10 let maxWidth = UIScreen.main.bounds.width - 30 weak var addDelegate: AddDelegate? weak var removeDelegate: RemoveDelegate? weak var verificationDelegate: VerificationDelegate? var wordViews: [PassphraseWordView] = [] var containers: [UILayoutGuide] = [] convenience init(with originalPhrase: [String], for type: PassphraseType) { self.init(withAutoLayout: true) self.type = type assert(originalPhrase.count <= 12, "Too large") self.originalPhrase = originalPhrase.enumerated().map { index, text in Word(index, text) } wordViews = wordViews(for: self.originalPhrase) for wordView in wordViews { addSubview(wordView) } switch self.type { case .original: isUserInteractionEnabled = false currentPhrase.append(contentsOf: self.originalPhrase) activateNewLayout() case .shuffled: self.originalPhrase.shuffle() currentPhrase.append(contentsOf: self.originalPhrase) activateNewLayout() case .verification: backgroundColor = Theme.lightGrayBackgroundColor layer.cornerRadius = 4 clipsToBounds = true activateNewLayout() } } func add(_ word: Word) { currentPhrase.append(word) deactivateLayout() activateNewLayout() animateLayout() wordViews.filter { wordView in if let index = wordView.word?.index { return self.currentPhrase.map { word in word.index }.contains(index) } else { return false } }.forEach { wordView in if word.index == wordView.word?.index { self.sendSubview(toBack: wordView) wordView.alpha = 0 } UIView.animate(withDuration: 0.4, delay: 0.1, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .easeOutFromCurrentStateWithUserInteraction, animations: { wordView.alpha = 1 }, completion: nil) } verificationStatus = verificationDelegate?.verify(currentPhrase) ?? .unverified } func remove(_ word: Word) { currentPhrase = currentPhrase.filter { currentWord in currentWord.index != word.index } deactivateLayout() activateNewLayout() animateLayout() wordViews.filter { wordView in if let index = wordView.word?.index { return !self.currentPhrase.map { word in word.index }.contains(index) } else { return false } }.forEach { wordView in wordView.alpha = 0 } } func reset(_ word: Word) { wordViews.filter { wordView in wordView.word?.index == word.index }.forEach { wordView in wordView.isAddedForVerification = false wordView.isEnabled = true wordView.bounce() } } func animateLayout(completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .easeOutFromCurrentStateWithUserInteraction, animations: { self.superview?.layoutIfNeeded() }, completion: completion) } func deactivateLayout() { NSLayoutConstraint.deactivate(layout) for container in containers { removeLayoutGuide(container) } layout.removeAll() } func wordViews(for phrase: Phrase) -> [PassphraseWordView] { return phrase.map { word -> PassphraseWordView in let wordView = PassphraseWordView(with: word) wordView.isAddedForVerification = false wordView.addTarget(self, action: #selector(toggleAddedState(for:)), for: .touchUpInside) return wordView } } func newContainer(withOffset offset: CGFloat) -> UILayoutGuide { let container = UILayoutGuide() containers.append(container) addLayoutGuide(container) layout.append(container.centerXAnchor.constraint(equalTo: centerXAnchor)) layout.append(container.topAnchor.constraint(equalTo: topAnchor, constant: offset)) return container } func currentWordViews() -> [PassphraseWordView] { var views: [PassphraseWordView] = [] for currentWord in currentPhrase { for wordView in wordViews { if let word = wordView.word, word.index == currentWord.index { views.append(wordView) if case .verification = type { wordView.isAddedForVerification = false } } } } return views } private func activateNewLayout() { var origin = CGPoint(x: 0, y: margin) var container = newContainer(withOffset: origin.y) let currentWordViews = self.currentWordViews() var previousWordView: UIView? for wordView in currentWordViews { let size = wordView.getSize() let newWidth = origin.x + size.width + margin if newWidth > maxWidth { origin.y += PassphraseWordView.height + margin origin.x = 0 if let previousWordView = previousWordView { layout.append(previousWordView.rightAnchor.constraint(equalTo: container.rightAnchor, constant: -margin)) } container = newContainer(withOffset: origin.y) previousWordView = nil } layout.append(wordView.topAnchor.constraint(equalTo: container.topAnchor)) layout.append(wordView.leftAnchor.constraint(equalTo: previousWordView?.rightAnchor ?? container.leftAnchor, constant: margin)) layout.append(wordView.bottomAnchor.constraint(equalTo: container.bottomAnchor)) if let lastWordView = currentWordViews.last, lastWordView == wordView { layout.append(wordView.rightAnchor.constraint(equalTo: container.rightAnchor, constant: -margin)) } previousWordView = wordView origin.x += size.width + margin } prepareHiddenViews(for: origin) layout.append(container.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -margin)) NSLayoutConstraint.activate(layout) } func prepareHiddenViews(for origin: CGPoint) { guard let lastContainer = containers.last else { return } wordViews.filter { wordView in if let index = wordView.word?.index { return !self.currentPhrase.map { word in word.index }.contains(index) } else { return false } }.forEach { wordView in wordView.alpha = 0 let size = wordView.getSize() let newWidth = origin.x + size.width + self.margin self.layout.append(wordView.topAnchor.constraint(equalTo: lastContainer.topAnchor, constant: newWidth > self.maxWidth ? PassphraseWordView.height + self.margin : 0)) self.layout.append(wordView.centerXAnchor.constraint(equalTo: lastContainer.centerXAnchor)) } } @objc func toggleAddedState(for wordView: PassphraseWordView) { wordView.isAddedForVerification = !wordView.isAddedForVerification if wordView.isAddedForVerification { addDelegate?.add(wordView) removeDelegate?.remove(wordView) } } }
41941fd4b1cc8e509dcc0b99f70b2b1d
30.555556
178
0.622618
false
false
false
false
duongsonthong/waveFormLibrary
refs/heads/master
waveFormLibrary-Example/Example/Pods/waveFormLibrary/waveFormLibrary/ControllerWaveForm.swift
mit
2
// // ControllerWaveForm.swift // // Created by SSd on 10/30/16. // import UIKit import AVFoundation import MediaPlayer @IBDesignable public class ControllerWaveForm: UIView{ var urlLocal = URL(fileURLWithPath: "") var mWaveformView : WaveFormView? var mTouchDragging : Bool = false var mTouchStart : Int = 0 var mTouchInitialOffset : Int = 0 var mOffset : Int = 0 var mMaxPos : Int = 0 var mStartPos : Int = 0 var mEndPos : Int = 0 let buttonWidth : Int = 100 var mTouchInitialStartPos : Int = 0 var mTouchInitialEndPos : Int = 0 var mWidth : Int = 0 var mOffsetGoal : Int = 0 var mFlingVelocity : Int = 0 var playButton : PlayButtonView? var zoomInButton : UIButton? var zoomOutButton : UIButton? var audioPlayer : AVAudioPlayer! var mPlayStartOffset : Int = 0 var mPlayStartMsec : Int = 0 var mPlayEndMsec : Int = 0 var mTimer : Timer? var mButtonStart : CustomButtom? var mButtonEnd : CustomButtom? var waveFormBackgroundColorPrivate : UIColor = UIColor.white var currentPlayColorPrivate : UIColor = UIColor.blue var mediaPlayer:MPMusicPlayerController = MPMusicPlayerController.applicationMusicPlayer() override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func setMp3Url(mp3Url : URL){ urlLocal = mp3Url let rectFrame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height*6/10) mWidth = Int(frame.size.width) mWaveformView = WaveFormView(frame: rectFrame,deletgate: self,waveFormBackgroundColor: waveFormBackground,currentPlayLineColor: currentPlayColor) do { try mWaveformView?.setFileUrl(url: urlLocal) } catch let error as NSError{ print(error) } //controll player let controllerViewWidth = frame.width*2/10 let controllerViewFrame = CGRect(x: 0, y: (mWaveformView?.frame.height)!+8, width: frame.width, height: controllerViewWidth) let controllerView = UIView(frame: controllerViewFrame) controllerView.backgroundColor = UIColor.clear let playButtonWidth = controllerView.frame.height let playButtonRect = CGRect(x: controllerView.frame.width/2-playButtonWidth/2, y: 0, width: playButtonWidth, height: playButtonWidth) playButton = PlayButtonView(frame: playButtonRect) playButton?.backgroundColor = UIColor.clear let zoomInRect = CGRect(x: 0, y: 0, width: controllerView.frame.height, height: controllerView.frame.height) let zoomOutRect = CGRect(x: controllerView.frame.width-controllerView.frame.height, y: 0, width: controllerView.frame.height, height: controllerView.frame.height) zoomInButton = UIButton(frame: zoomInRect) zoomInButton?.backgroundColor = UIColor.clear zoomInButton?.setTitle("+", for: .normal) zoomOutButton = UIButton(frame: zoomOutRect) zoomOutButton?.backgroundColor = UIColor.clear zoomOutButton?.setTitle("-", for: .normal) playButton?.addTarget(self, action: #selector(self.clickPlay), for: .touchUpInside) zoomOutButton?.addTarget(self, action: #selector(self.waveformZoomOut), for: .touchUpInside) zoomInButton?.addTarget(self, action: #selector(self.waveformZoomIn), for: .touchUpInside) //add subview controllerView.addSubview(playButton!) controllerView.addSubview(zoomInButton!) controllerView.addSubview(zoomOutButton!) let buttonWidth = CGFloat(100) let buttonHeigh = CGFloat(50) mButtonStart = CustomButtom(frame: CGRect(x: 0, y: 0, width: buttonWidth, height: buttonHeigh),parentViewParam : self,isLeft : true,delegate: self) mButtonStart?.setBackgroundImage(UIImage(named : "HandleLeftBig"), for: .normal) mButtonEnd = CustomButtom(frame: CGRect(x: frame.size.width-buttonWidth, y: mWaveformView!.frame.height-buttonHeigh, width: buttonWidth, height: buttonHeigh),parentViewParam : self,isLeft : false,delegate: self) mButtonEnd?.setBackgroundImage(UIImage(named: "buttonHandle"), for: .normal) finishOpeningSoundFile() addSubview(mWaveformView!) mWaveformView!.addSubview(mButtonEnd!) mWaveformView!.addSubview(mButtonStart!) addSubview(controllerView) } func finishOpeningSoundFile() { if let waveFormUnWrap = mWaveformView { mMaxPos = waveFormUnWrap.maxPos() mTouchDragging = false; mOffset = 0; mOffsetGoal = 0; mFlingVelocity = 0; resetPositions(); updateDisplay(); } do { audioPlayer = try AVAudioPlayer(contentsOf: urlLocal) audioPlayer.delegate = self } catch let error as NSError { print(error) } } func waveformZoomIn(){ mWaveformView?.zoomIn(); mStartPos = (mWaveformView?.getStart())!; mEndPos = (mWaveformView?.getEnd())!; mMaxPos = (mWaveformView?.maxPos())!; mOffset = (mWaveformView?.getOffset())!; mOffsetGoal = mOffset; updateDisplay(); } func waveformZoomOut() { mWaveformView?.zoomOut(); mStartPos = (mWaveformView?.getStart())!; mEndPos = (mWaveformView?.getEnd())!; mMaxPos = (mWaveformView?.maxPos())!; mOffset = (mWaveformView?.getOffset())!; mOffsetGoal = mOffset; updateDisplay(); } func clickPlay(){ onPlay(startPosition: mStartPos) } func trap(pos : Int) -> Int { if (pos < 0){ return 0 } if (pos > mMaxPos ){ return mMaxPos } return pos; } func onPlay(startPosition : Int){ if isPlaying() { if let audioPlayerUW = audioPlayer { audioPlayerUW.pause() mTimer?.invalidate() mTimer = nil updateButton() } return } mPlayStartMsec = mWaveformView!.pixelsToMillisecs(pixels: startPosition) mPlayEndMsec = mWaveformView!.pixelsToMillisecs(pixels: mEndPos) if let audioPlayerUW = audioPlayer { audioPlayerUW.currentTime = TimeInterval(exactly: Float(mPlayStartMsec)/1000)! audioPlayerUW.play() } updateButton() mTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.updateDisplay), userInfo: nil, repeats: true) mTimer?.fire() } func updateButton(){ if isPlaying() { playButton?.setPlayStatus(isPlay: true) }else { playButton?.setPlayStatus(isPlay: false) } } func updateDisplay() { if isPlaying() { let now : Int = Int(round(Double(audioPlayer.currentTime)*1000) + Double(mPlayStartOffset)) let frames : Int = mWaveformView!.millisecsToPixels(msecs: now) mWaveformView?.setPlayback(pos: frames) setOffsetGoalNoUpdate(offset: frames - mWidth / 2) if now > mPlayEndMsec { if let audioPlayerUW = audioPlayer { audioPlayerUW.currentTime = TimeInterval(exactly: Float(mPlayStartMsec)/1000)! audioPlayerUW.play() } } } var offsetDelta : Int = 0 if (!mTouchDragging) { if (mFlingVelocity != 0) { offsetDelta = mFlingVelocity / 30 if (mFlingVelocity > 80) { mFlingVelocity -= 80 } else if (mFlingVelocity < -80) { mFlingVelocity += 80 } else { mFlingVelocity = 0 } mOffset += offsetDelta; if (mOffset + mWidth / 2 > mMaxPos) { mOffset = mMaxPos - mWidth / 2 mFlingVelocity = 0 } if (mOffset < 0) { mOffset = 0; mFlingVelocity = 0 } mOffsetGoal = mOffset } else { offsetDelta = mOffsetGoal - mOffset if (offsetDelta > 10){ offsetDelta = offsetDelta / 10 } else if (offsetDelta > 0){ offsetDelta = 1 } else if (offsetDelta < -10){ offsetDelta = offsetDelta / 10 } else if (offsetDelta < 0){ offsetDelta = -1 } else{ offsetDelta = 0 } mOffset += offsetDelta } } if let waveFormUW = mWaveformView { waveFormUW.setParameters(start: mStartPos, end: mEndPos, offset: mOffset) waveFormUW.setNeedsDisplay() } if let buttonEndUW = mButtonEnd { let endX : Int = mEndPos - mOffset - Int(buttonEndUW.getWidth()-buttonEndUW.getWidth()/2) buttonEndUW.updateFramePostion(position: endX) } if let buttonStartUW = mButtonStart { let startX : Int = mStartPos - mOffset - Int (buttonStartUW.getWidth()/2) buttonStartUW.updateFramePostion(position: startX) } } func setOffsetGoalStart() { setOffsetGoal(offset: mStartPos - mWidth / 2) } func setOffsetGoalEnd() { setOffsetGoal(offset: mEndPos - mWidth / 2) } func setOffsetGoal(offset : Int) { setOffsetGoalNoUpdate(offset: offset); updateDisplay() } func setOffsetGoalNoUpdate(offset : Int) { if (mTouchDragging) { return; } mOffsetGoal = offset; if (mOffsetGoal + mWidth / 2 > mMaxPos){ mOffsetGoal = mMaxPos - mWidth / 2 } if (mOffsetGoal < 0){ mOffsetGoal = 0 } } func resetPositions() { mStartPos = 0; mEndPos = mMaxPos; } // Play state func pause(){ if let audioPlayerUW = audioPlayer { audioPlayerUW.pause() } } func isPlaying() -> Bool { if let audioPlayerUW = audioPlayer { if audioPlayerUW.isPlaying { return true } return false } return false } } extension ControllerWaveForm : AVAudioPlayerDelegate { } extension ControllerWaveForm : WaveFormMoveProtocol { // waveForm touch func touchesBegan(position : Int){ mTouchDragging = true mTouchStart = position mTouchInitialOffset = mOffset } func touchesMoved(position : Int){ mOffset = trap(pos: Int(mTouchInitialOffset + (mTouchStart - position))); updateDisplay() } func touchesEnded(position : Int){ mTouchDragging = false; mOffsetGoal = mOffset; } } extension ControllerWaveForm : ButtonMoveProtocol{ // Button touch func buttonTouchesBegan(position : Int,isLeft : Bool){ mTouchDragging = true; mTouchStart = position; mTouchInitialStartPos = mStartPos; mTouchInitialEndPos = mEndPos; } func buttonTouchesMoved(position : Int,isLeft : Bool){ let delta = position - mTouchStart; if isLeft { mStartPos = trap(pos: Int (mTouchInitialStartPos + delta)); if mStartPos > mEndPos { mStartPos = mEndPos } }else { mEndPos = trap(pos: Int(mTouchInitialEndPos + delta)); if mEndPos < mStartPos { mEndPos = mStartPos } //waveFormView.updateEnd(x: Float(position)) } mPlayStartMsec = mWaveformView!.pixelsToMillisecs(pixels: mStartPos) mPlayEndMsec = mWaveformView!.pixelsToMillisecs(pixels: mEndPos) updateDisplay() } func buttonTouchesEnded(position : Int,isLeft : Bool){ //print("buttonTouchesEnded") mTouchDragging = false if isLeft { setOffsetGoalStart() }else { setOffsetGoalEnd() } } } extension ControllerWaveForm{ @IBInspectable public var waveFormBackground : UIColor{ get { return waveFormBackgroundColorPrivate } set(newValue){ waveFormBackgroundColorPrivate = newValue } } @IBInspectable public var currentPlayColor : UIColor { get{ return currentPlayColorPrivate } set(newValue){ currentPlayColorPrivate = newValue } } }
af9d44214715ca1e3ce172c1d077d52c
32.40665
219
0.577859
false
false
false
false
EasySwift/EasySwift
refs/heads/master
Carthage/Checkouts/Bond/Carthage/Checkouts/ReactiveKit/Sources/Observer.swift
apache-2.0
7
// // The MIT License (MIT) // // Copyright (c) 2016 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. // /// Represents a type that receives events. public protocol ObserverProtocol { /// Type of elements being received. associatedtype Element /// Type of error that can be received. associatedtype Error: Swift.Error /// Send the event to the observer. func on(_ event: Event<Element, Error>) } /// Represents a type that receives events. Observer is just a convenience /// wrapper around a closure that accepts an event. public struct Observer<Element, Error: Swift.Error>: ObserverProtocol { private let observer: (Event<Element, Error>) -> Void /// Creates an observer that wraps given closure. public init(observer: @escaping (Event<Element, Error>) -> Void) { self.observer = observer } /// Calles wrapped closure with the given element. public func on(_ event: Event<Element, Error>) { observer(event) } } /// Observer that ensures events are sent atomically. public class AtomicObserver<Element, Error: Swift.Error>: ObserverProtocol { private let observer: (Event<Element, Error>) -> Void private let disposable: Disposable private let lock = NSRecursiveLock(name: "com.reactivekit.signal.atomicobserver") private var terminated = false /// Creates an observer that wraps given closure. public init(disposable: Disposable, observer: @escaping (Event<Element, Error>) -> Void) { self.disposable = disposable self.observer = observer } /// Calles wrapped closure with the given element. public func on(_ event: Event<Element, Error>) { lock.lock(); defer { lock.unlock() } guard !disposable.isDisposed && !terminated else { return } if event.isTerminal { terminated = true observer(event) disposable.dispose() } else { observer(event) } } } // MARK: - Extensions public extension ObserverProtocol { /// Convenience method to send `.next` event. public func next(_ element: Element) { on(.next(element)) } /// Convenience method to send `.failed` event. public func failed(_ error: Error) { on(.failed(error)) } /// Convenience method to send `.completed` event. public func completed() { on(.completed) } /// Convenience method to send `.next` event followed by a `.completed` event. public func completed(with element: Element) { next(element) completed() } }
9d95cee656e02e6b75aa9caf1c158cca
31.757009
92
0.710128
false
false
false
false
CrazyZhangSanFeng/BanTang
refs/heads/master
BanTang/BanTang/Classes/Home/View/BTCoverView.swift
apache-2.0
1
// // BTCoverView.swift // BanTang // // Created by 张灿 on 16/6/13. // Copyright © 2016年 张灿. All rights reserved. // 遮盖 import UIKit class BTCoverView: UIView { //闭包作为属性 var click: () -> Void = { } class func show() -> BTCoverView { let cover = BTCoverView() cover.frame = UIScreen.mainScreen().bounds cover.backgroundColor = UIColor.blackColor() cover.alpha = 0.4 UIApplication.sharedApplication().keyWindow?.addSubview(cover) return cover } /** popShow, */ class func popShow() -> BTCoverView { let cover = BTCoverView() cover.frame = CGRect(x: 0, y: 64, width: BTscreenW, height: BTscreenH - 64 - 49) cover.backgroundColor = UIColor.blackColor() cover.alpha = 0.4 UIApplication.sharedApplication().keyWindow?.addSubview(cover) return cover } //点击屏幕调用闭包,类似代理 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.click() } }
eb2a47c394ec8e6f19b1860d7b93c858
23.666667
88
0.600386
false
false
false
false
shirai/SwiftLearning
refs/heads/master
playground/オプショナル型.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit /*オプショナル型とは、変数の型がもつ通常の値に加えて、空の(値が無い)状態を保持できる変数です。空の状態はnilで表現します。*/ /* * *宣言 変数の宣言時に、型の後ろに「?」をつけて宣言 * */ var name: String? //name = nil //nilを入れなくても最初に入っている name = "Saki" print(name) //"?"のオプショナル型の変数は出力したときにOptionalという記述が含まれる name = "Saki" print(name!) // 変数名の後ろに!をつけてアンラップ // オプショナル型でない変数にはnilを代入できない。 //var name1: String //name1 = nil // エラーになる。 /* * *オプショナルバインディング 値が空(nil)の場合はfalse、それ以外はtrue アンラップをする場合には、必ずラッピングの中身が存在する(=nilではない)ことが保証されていなければいけません。 nilかどうかわからない場合は後述するオプショナルチェイニングかオプショナルバインディングを使いましょう。 * */ var price: Int? = 100 if let p = price { print("価格:\(p)円") }else{ print("価格:未定") } price = nil if let p = price { print("価格:\(p)円") }else{ print("価格:未定") } /* * *アンラップ オプショナル型を計算で使用したり、通常の型を受け取る関数の引数に渡したりする場合は、値が空でないことを明示するために、アンラップする必要があります。アンラップはラップ(包装)の反対で、オプションという包装紙に包まれた変数の包装を解くイメージです。 *アンラップするには、オプショナル型の変数名の後ろに「!」をつけます。 * */ var diameter: Double? diameter = 4 print("円の周りの長さは\(Double(Double(diameter!) * 3.14))センチです。")// 変数名の後ろに!をつけてアンラップ var diameter2: Int? diameter2 = 4 print("円の周りの長さは\(Int(Double(diameter2!) * 3.14))センチです。")// 変数名の後ろに!をつけてアンラップ /*3.14はDouble型。自動変換されないので、Double型*Double型しかできない。(Int*Double->エラー)一番外側で計算結果の型を指定する。*/ //中身が空(nil)のオプショナル型の変数をアンラップすると実行時エラーが発生 //diameter = nil //print("円の直径は\(Double(Double(diameter!)*3.14))㎠です。") //非オプショナル型を受けとるには関数の呼び出し側でアンラップが必要 func calculateTax(p: Int) -> Int { //func <関数>(<引数名>:<型>){<処理>} return Int(Double(p) * 1.08) } var price2: Int? price2 = 300 let priceWithTax = calculateTax(p:price2!)//変数名の後ろに!をつけてアンラップ print(priceWithTax) //if文を使うと、値が空かどうかの判定とアンラップされた別変数への代入を同時に行うことができる。 diameter = 4 if let unwrappedDiameter = diameter{ // unwrappedPriceはアンラップされているので後ろに!は不要 print("円の周りの長さは \(unwrappedDiameter*3.14) センチです。") } diameter = nil if let unwrappedDiameter = diameter{ // unwrappedPriceはアンラップされているので後ろに!は不要 print("円の周りの長さは \(unwrappedDiameter*3.14) センチです。") }else{ print("円の直径がわかりません。") } //定数でも変数でも同様に書ける //配列やディクショナリも同様にオプショナル型として宣言できる var party: Array<String>? party = ["戦士", "魔法使い"] party!.append("nil") // 変数名の後ろに!をつけてアンラップ party!.append("僧侶") // 変数名の後ろに!をつけてアンラップ print(party) /* * *暗黙的なオプショナル型 宣言時に?ではなく!をつけて宣言 暗黙的なオプショナル型は、空値(nil)をとり得るという意味では、上で説明したオプショナル型と同じですが、使用時にアンラップする必要がありません。 アンラップの必要がないので、初期値がnilでも使用時までには必ず値が入っていると想定されるケースでは、暗黙的なオプショナル型の方が便利です。 但し、アンラップが必要な状況で、暗黙的なオプショナル型を空のまま使用すると実行時エラーが発生します。 * */ var うまい棒: Double! うまい棒 = 10 print("税込み価格は\(Int(うまい棒 * 1.08))円") // 変数名の後ろに!をつける必要がない //うまい棒 = nil //print("税込み価格は\(Int(うまい棒 * 1.08))円") // エラー /*暗黙的なオプショナル型の宣言に使用する!と、アンラップに使用する!を混同しないようにしてください。同じ記号が使われていますが意味は異なります。*/ //暗黙的なオプショナル型をif文の中で条件として使用 var ガリガリ君: Double! ガリガリ君 = 60 if let unwrappedPrice = ガリガリ君 { print("税込み価格は\(Int(unwrappedPrice * 1.08))円") } else { print("価格は未定") } /* * *nil結合演算子 ??という演算子を使うと、オプショナル型がnilでなければその値を、nilの場合は指定した値を与えることができる。 * */ var a: Int? let b = a ?? 10 //aはnilなので、10が代入される let c = b ?? 20 //bはnilではないので、20が代入される
bbbf61e02398cd1ebbfdcf54ea3806a9
21.058394
124
0.724686
false
false
false
false
AbidHussainCom/HackingWithSwift
refs/heads/master
project21/Project21/AppDelegate.swift
unlicense
20
// // AppDelegate.swift // Project21 // // Created by Hudzilla on 24/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if let options = launchOptions { if let notification = options[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification { if let userInfo = notification.userInfo { let customField1 = userInfo["CustomField1"] as! String // do something neat here } } } return true } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { if let userInfo = notification.userInfo { let customField1 = userInfo["CustomField1"] as! String println("didReceiveLocalNotification: \(customField1)") } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
4feec48d2eca64642343f6c248bb4d69
40.967213
279
0.778906
false
false
false
false
isohrab/gpkey
refs/heads/master
GPKeyboard/KeyboardViewController.swift
mit
1
// // KeyboardViewController.swift // Gachpazh Keyboard // // Created by sohrab on 09/09/16. // Copyright © 2016 ark.sohrab. All rights reserved. // import UIKit import AudioToolbox class KeyboardViewController: UIInputViewController, GPButtonEventsDelegate { // 1396 - 1397 - 1306:char - 1155:delete - 1156:space+number+shift+return let delSound: SystemSoundID = 1155 let charSound: SystemSoundID = 1104 let utilSound: SystemSoundID = 1156 let vibSound: SystemSoundID = 1520 var soundState: Int = 0 /**************************** * define alphabet value * ****************************/ // [layer][row][column] let characters :[[[Harf]]]=[[ // first layer: first row: [Harf.init(name: "zad", face: "ض", output: "ض", returnable: false, spaceReturnable: false), Harf.init(name: "sad", face: "ص", output: "ص", returnable: false, spaceReturnable: false), Harf.init(name: "ghaf", face: "ق", output: "ق", returnable: false, spaceReturnable: false), Harf.init(name: "fe", face: "ف", output: "ف", returnable: false, spaceReturnable: false), Harf.init(name: "ghein",face: "غ", output: "غ", returnable: false, spaceReturnable: false), Harf.init(name: "ein", face: "ع", output: "ع", returnable: false, spaceReturnable: false), Harf.init(name: "ha", face: "ه", output: "ه", returnable: false, spaceReturnable: false), Harf.init(name: "khe", face: "خ", output: "خ", returnable: false, spaceReturnable: false), Harf.init(name: "he", face: "ح", output: "ح", returnable: false, spaceReturnable: false), Harf.init(name: "je", face: "ج", output: "ج", returnable: false, spaceReturnable: false), Harf.init(name: "che", face: "چ", output: "چ", returnable: false, spaceReturnable: false)], //first Layer, Second Row: [Harf.init(name: "she", face: "ش", output: "ش", returnable: false, spaceReturnable: false), Harf.init(name: "se", face: "س", output: "س", returnable: false, spaceReturnable: false), Harf.init(name: "ye", face: "ی", output: "ی", returnable: false, spaceReturnable: false), Harf.init(name: "be", face: "ب", output: "ب", returnable: false, spaceReturnable: false), Harf.init(name: "lam", face: "ل", output: "ل", returnable: false, spaceReturnable: false), Harf.init(name: "alef",face: "ا", output: "ا", returnable: false, spaceReturnable: false), Harf.init(name: "te", face: "ت", output: "ت", returnable: false, spaceReturnable: false), Harf.init(name: "non", face: "ن", output: "ن", returnable: false, spaceReturnable: false), Harf.init(name: "mim", face: "م", output: "م", returnable: false, spaceReturnable: false), Harf.init(name: "ke", face: "ک", output: "ک", returnable: false, spaceReturnable: false), Harf.init(name: "ge", face: "گ", output: "گ", returnable: false, spaceReturnable: false)], //first Layer, Third Row: [Harf.init(name: "za", face: "ظ", output: "ظ", returnable: false, spaceReturnable: false), Harf.init(name: "ta", face: "ط", output: "ط", returnable: false, spaceReturnable: false), Harf.init(name: "ze", face: "ز", output: "ز", returnable: false, spaceReturnable: false), Harf.init(name: "re", face: "ر", output: "ر", returnable: false, spaceReturnable: false), Harf.init(name: "zal", face: "ذ", output: "ذ", returnable: false, spaceReturnable: false), Harf.init(name: "dal", face: "د", output: "د", returnable: false, spaceReturnable: false), Harf.init(name: "pe", face: "پ", output: "پ", returnable: false, spaceReturnable: false), Harf.init(name: "ve", face: "و", output: "و", returnable: false, spaceReturnable: false)], // first Layer, Fourth Row: [Harf.init(name: "se3noghte",face: "ث", output: "ث", returnable: false, spaceReturnable: false), Harf.init(name: "zhe", face: "ژ", output: "ژ", returnable: false, spaceReturnable: false)]], // Shift LAYER // Second Layer: first Row: [[Harf.init(name: "saken", face: "ْ", output: "ْ", returnable: true, spaceReturnable: false), Harf.init(name: "o", face: "ُ", output: "ُ", returnable: true, spaceReturnable: false), Harf.init(name: "e", face: "ِ", output: "ِ", returnable: true, spaceReturnable: false), Harf.init(name: "a", face: "َ", output: "َ", returnable: true, spaceReturnable: false), Harf.init(name: "an", face: "ً", output: "ً", returnable: true, spaceReturnable: false), Harf.init(name: "parantezL", face: "\u{0028}", output: "\u{0029}", returnable: false, spaceReturnable: true), Harf.init(name: "parantezR", face: "\u{0029}", output: "\u{0028}", returnable: false, spaceReturnable: true), Harf.init(name: "akoladL", face: "\u{007B}", output: "\u{007D}", returnable: false, spaceReturnable: true), Harf.init(name: "akoladR", face: "\u{007D}", output: "\u{007B}", returnable: false, spaceReturnable: true), Harf.init(name: "beraketL", face: "\u{005b}", output: "\u{005d}", returnable: false, spaceReturnable: true), Harf.init(name: "beraketR", face: "\u{005d}", output: "\u{005b}", returnable: false, spaceReturnable: true)], // second Layer, Second Row: [Harf.init(name: "bullet", face: "•", output: "•", returnable: false, spaceReturnable: true), Harf.init(name: "underline",face: "_", output: "_", returnable: false, spaceReturnable: true), Harf.init(name: "yeHamze", face: "ئ", output: "ئ", returnable: true, spaceReturnable: false), Harf.init(name: "tashdid", face: "\u{0651}", output: "\u{0651}", returnable: true, spaceReturnable: false), Harf.init(name: "hamze", face: "ء", output: "ء", returnable: true, spaceReturnable: false), Harf.init(name: "abakola", face: "آ", output: "آ", returnable: true, spaceReturnable: false), Harf.init(name: "keshidan",face: "ـ", output: "ـ", returnable: false, spaceReturnable: true), Harf.init(name: "2fleshL", face: "\u{00ab}", output: "\u{00bb}", returnable: false, spaceReturnable: true), Harf.init(name: "2fleshR", face: "\u{00bb}", output: "\u{00ab}", returnable: false, spaceReturnable: true), Harf.init(name: "apostroph",face: "'", output: "'", returnable: true, spaceReturnable: false), Harf.init(name: "quotation",face: "\"", output: "\"", returnable: false, spaceReturnable: true)], //second layer, third Row: [Harf.init(name: "noghte", face: ".", output: ".", returnable: false, spaceReturnable: true), Harf.init(name: "virgol", face: "،", output: "،", returnable: false, spaceReturnable: true), Harf.init(name: "3noghte", face: "\u{2026}", output: "\u{2026}", returnable: false, spaceReturnable: true), Harf.init(name: "donoghte", face: ":", output: ":", returnable: false, spaceReturnable: true), Harf.init(name: "semicolon", face: "؛", output: "؛", returnable: false, spaceReturnable: true), Harf.init(name: "centigrad", face: "°", output: "°", returnable: false, spaceReturnable: true), Harf.init(name: "soal", face: "؟", output: "؟", returnable: false, spaceReturnable: true), Harf.init(name: "tajob", face: "!", output: "!", returnable: false, spaceReturnable: true)], // second layer, fourth Row: [Harf.init(name: "atsign", face: "@", output: "@", returnable: false, spaceReturnable: true), Harf.init(name: "sharp", face: "#", output: "#", returnable: false, spaceReturnable: true)]], //Number layer // first Row: [[Harf.init(name: "yek",face: "۱", output: "۱", returnable: false, spaceReturnable: false), Harf.init(name: "do",face: "۲", output: "۲", returnable: false, spaceReturnable: false), Harf.init(name: "se",face: "۳", output: "۳", returnable: false, spaceReturnable: false), Harf.init(name: "char",face: "۴", output: "۴", returnable: false, spaceReturnable: false), Harf.init(name: "panj",face: "۵", output: "۵", returnable: false, spaceReturnable: false), Harf.init(name: "shesh",face: "۶", output: "۶", returnable: false, spaceReturnable: false), Harf.init(name: "haft",face: "۷", output: "۷", returnable: false, spaceReturnable: false), Harf.init(name: "hasht",face: "۸", output: "۸", returnable: false, spaceReturnable: false), Harf.init(name: "noh",face: "۹", output: "۹", returnable: false, spaceReturnable: false), Harf.init(name: "sefr",face: "۰", output: "۰", returnable: false, spaceReturnable: false), Harf.init(name: "mosbat",face: "=", output: "=", returnable: false, spaceReturnable: false)], //second Row: [Harf.init(name: "prime",face: "`", output: "`", returnable: false, spaceReturnable: false), Harf.init(name: "mad",face: "~", output: "~", returnable: false, spaceReturnable: false), Harf.init(name: "bala",face: "^", output: "^", returnable: false, spaceReturnable: false), Harf.init(name: "dollar",face: "$", output: "$", returnable: false, spaceReturnable: false), Harf.init(name: "euro",face: "€", output: "€", returnable: false, spaceReturnable: false), Harf.init(name: "star",face: "*", output: "*", returnable: false, spaceReturnable: false), Harf.init(name: "darsad",face: "٪", output: "٪", returnable: false, spaceReturnable: false), Harf.init(name: "mosbat",face: "+", output: "+", returnable: false, spaceReturnable: false), Harf.init(name: "menha", face: "-",output: "-", returnable: false, spaceReturnable: false), Harf.init(name: "zarb",face: "×", output: "×", returnable: false, spaceReturnable: false), Harf.init(name: "taghsim",face: "÷", output: "÷", returnable: false, spaceReturnable: false)], //third Row: [Harf.init(name: "number-seperator",face: ",", output: ",", returnable: false, spaceReturnable: false), Harf.init(name: "register",face: ".", output: ".", returnable: false, spaceReturnable: false), Harf.init(name: "Copyright",face: ":", output: ":", returnable: false, spaceReturnable: false), Harf.init(name: "kama",face: "،", output: "،", returnable: false, spaceReturnable: false), Harf.init(name: "small",face: "<", output: ">", returnable: false, spaceReturnable: false), Harf.init(name: "great",face: ">", output: "<", returnable: false, spaceReturnable: false), Harf.init(name: "pipe",face: "|", output: "|", returnable: false, spaceReturnable: false), Harf.init(name: "parantezL", face: "\u{0028}", output: "\u{0028}", returnable: false, spaceReturnable: false), Harf.init(name: "parantezR", face: "\u{0029}", output: "\u{0029}", returnable: false, spaceReturnable: false),], // fourht row: [Harf.init(name: "back-slash",face: "\\", output: "\\", returnable: false, spaceReturnable: false), Harf.init(name: "slash",face: "/", output: "/", returnable: false, spaceReturnable: false),]]] // the smiles are changable in main App var smile:[String] = ["\u{1F600}", // 😀 "\u{1F601}", // 😁 "\u{1F602}", // 😂 "\u{1F60F}", // 😏 "\u{0263A}", // 😘☺ "\u{1F917}", // 🤗 "\u{1F60D}", // 😍 "\u{1F618}", // 😘 "\u{1F61C}", // 😜 "\u{1F339}", // 🌹 "\u{02764}", // 🌹❤ "\u{1f614}", // 😔 "\u{1F622}", // 😢 "\u{1F62D}", // 😭 "\u{1F612}", // 😒 "\u{1F620}", // 😠 "\u{1F624}", // 😤 "\u{1F633}", // 😳 "\u{1F631}", // 😱 "\u{1F60B}", // 😋 "\u{1F38A}", // 🎊 "\u{1F494}", // 💔 "\u{1F610}", // 😐 "\u{1F62C}", // 😬 "\u{1F644}", // 🙄 "\u{1F60E}", // 😎 "\u{1F615}", // 😕 "\u{1F925}", // 🤥 "\u{1F914}", // 🤔 "\u{1F922}", // 🤢 "\u{1F44C}", // 👌 "\u{1F44D}", // 👍 "\u{1F64F}"] // 🙏 /************************************* * * * Define Global Value * * - keyboards layers * * - keyboard dimension and points * * * *************************************/ var gapHorizontal: CGFloat = 6 // in iPad screens should be multiply by 2 var gapVertical: CGFloat = 10 // in iPad Screen should be multiply by 2 var buttonHeight: CGFloat = 52 var dmpPatriot: CGFloat = 1 var shift: Bool = false // show state of shift button { didSet { doShift(shifting: shift) } } var returnAfterSpace = false { didSet { if returnAfterSpace == true { alefbaButtons[4][3].label?.text = "فاصله" alefbaButtons[4][3].type = .SPACE } } } var deleting: Bool = false // when it is true, continuing deleting characters var deleteTimer: TimeInterval = 0.3 // it will accelerate deleting upto 500 milisecond var timer:Timer! // colors var buttonBackground = UIColor.white // color of button in noraml state var viewBackground = UIColor(red:0.82, green:0.84, blue:0.86, alpha:1.0) // main background color var utilBackgroundColor = UIColor(red:0.67, green:0.70, blue:0.73, alpha:1.0) // color of util button in normal state var textColorNormal = UIColor.black var textColorHighlighted = UIColor.black var makeButtonBiggerTextColor = UIColor.black var buttonShadowColor = UIColor.gray.cgColor var utilButtonTouchDownColor = UIColor.white var buttonBorderColor = UIColor.gray.cgColor var makeButtonBiggerBackground = UIColor(red:0.90, green:0.89, blue:0.89, alpha:1.0) /******* Layout variabels *********/ var alefbaLayout: UIView! var numberLayout: UIView! var alefbaButtons: [[GPButton]]! var numberButtons: [[GPButton]]! var portraitConstraints:[NSLayoutConstraint]! var landscapeConstraints:[NSLayoutConstraint]! /****************************************** * * * initial Alefba Layout * * * *****************************************/ func initAlefbaLayout(){ alefbaButtons = [[GPButton]]() // Add emojies var rowButtons = [GPButton]() for i in 0...10 { let btn = GPButton(with: .EMOJI) btn.label?.text = smile[i] rowButtons.append(btn) btn.backLayerInsetX = 0 btn.backLayerInsetY = 0 btn.addTarget(self, action: #selector(self.emojiTouched(_:)), for: .touchUpInside) alefbaLayout.addSubview(btn) } alefbaButtons.append(rowButtons) // Add character buttons for i in 0..<characters[0].count { var rowButtons = [GPButton]() for j in 0..<characters[0][i].count { let btn = GPButton(with: .CHAR) btn.harf = characters[0][i][j] rowButtons.append(btn) btn.backLayerInsetX = gapHorizontal / 2 btn.backLayerInsetY = gapVertical / 2 // btn.isExclusiveTouch = true btn.addTarget(self, action: #selector(self.charTouched(_:)), for: .touchUpInside) alefbaLayout.addSubview(btn) } alefbaButtons.append(rowButtons) } // add all util function let shiftButton = GPButton(with: .SHIFT) shiftButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside) shiftButton.label?.text = ".؟!" shiftButton.backLayerInsetX = gapHorizontal / 2 shiftButton.backLayerInsetY = gapVertical / 2 alefbaButtons[3].insert(shiftButton, at: 0) alefbaLayout.addSubview(shiftButton) let deleteButton = GPButton(with: .DELETE) deleteButton.addTarget(self, action: #selector(self.deleteTouchDown(sender:)), for: .touchDown) deleteButton.addTarget(self, action: #selector(self.deleteTouchUp(_:)), for: .touchUpInside) deleteButton.addTarget(self, action: #selector(self.deleteTouchUp(_:)), for: .touchUpOutside) deleteButton.label?.text = "" deleteButton.backLayerInsetX = gapHorizontal / 2 deleteButton.backLayerInsetY = gapVertical / 2 alefbaButtons[3].insert(deleteButton, at: alefbaButtons[3].count) alefbaLayout.addSubview(deleteButton) let numberButton = GPButton(with: .NUMBER) numberButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside) numberButton.label?.text = "۱۲۳" numberButton.backLayerInsetX = gapHorizontal / 2 numberButton.backLayerInsetY = gapVertical / 2 alefbaButtons[4].insert(numberButton, at: 0) alefbaLayout.addSubview(numberButton) let globeButton = GPButton(with: .GLOBE) globeButton.backLayerInsetX = gapHorizontal / 2 globeButton.backLayerInsetY = gapVertical / 2 globeButton.label?.text = "" alefbaButtons[4].insert(globeButton, at: 1) alefbaLayout.addSubview(globeButton) globeButton.addTarget(self, action: #selector(advanceToNextInputMode), for: .touchUpInside) let spaceButton = GPButton(with: .SPACE) spaceButton.label?.text = "فاصله" spaceButton.backLayerInsetX = gapHorizontal / 2 spaceButton.backLayerInsetY = gapVertical / 2 spaceButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside) alefbaButtons[4].insert(spaceButton, at: 3) alefbaLayout.addSubview(spaceButton) let enterButton = GPButton(with: .ENTER) enterButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside) enterButton.label?.text = "" enterButton.backLayerInsetX = gapHorizontal / 2 enterButton.backLayerInsetY = gapVertical / 2 alefbaButtons[4].insert(enterButton, at: 5) alefbaLayout.addSubview(enterButton) // calculate constraints sizeConstraints(buttons: alefbaButtons, kbLayout: alefbaLayout) positionConstraints(buttons: alefbaButtons, kbLayout: alefbaLayout) } /****************************************** * * * initial Number Layout * * * *****************************************/ func initNumberLayout(){ // TODO: background should be checked here numberLayout.backgroundColor = viewBackground numberButtons = [[GPButton]]() // Add emojies var rowButtons = [GPButton]() for i in 0...10 { let btn = GPButton(with: .EMOJI) btn.label?.text = smile[i+22] rowButtons.append(btn) btn.backLayerInsetX = 0 btn.backLayerInsetY = 0 btn.addTarget(self, action: #selector(self.emojiTouched(_:)), for: .touchUpInside) numberLayout.addSubview(btn) } numberButtons.append(rowButtons) for i in 0..<characters[2].count { var rowButtons = [GPButton]() for j in 0..<characters[2][i].count { let btn = GPButton(with: .CHAR) btn.harf = characters[2][i][j] rowButtons.append(btn) btn.backLayerInsetX = gapHorizontal / 2 btn.backLayerInsetY = gapVertical / 2 btn.isExclusiveTouch = true btn.addTarget(self, action: #selector(self.charTouched(_:)), for: .touchUpInside) numberLayout.addSubview(btn) } numberButtons.append(rowButtons) } // add all util function let deleteButton = GPButton(with: .DELETE) deleteButton.addTarget(self, action: #selector(self.deleteTouchDown(sender:)), for: .touchDown) deleteButton.addTarget(self, action: #selector(self.deleteTouchUp(_:)), for: .touchUpInside) deleteButton.addTarget(self, action: #selector(self.deleteTouchUp(_:)), for: .touchUpOutside) deleteButton.label?.text = "" deleteButton.backLayerInsetX = gapHorizontal / 2 deleteButton.backLayerInsetY = gapVertical / 2 numberButtons[3].insert(deleteButton, at: numberButtons[3].count) numberLayout.addSubview(deleteButton) let numberButton = GPButton(with: .NUMBER) numberButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside) numberButton.label?.text = "الفبا" numberButton.backLayerInsetX = gapHorizontal / 2 numberButton.backLayerInsetY = gapVertical / 2 numberButtons[4].insert(numberButton, at: 0) numberLayout.addSubview(numberButton) let globeButton = GPButton(with: .GLOBE) globeButton.backLayerInsetX = gapHorizontal / 2 globeButton.backLayerInsetY = gapVertical / 2 globeButton.label?.text = "" numberButtons[4].insert(globeButton, at: 1) numberLayout.addSubview(globeButton) globeButton.addTarget(self, action: #selector(advanceToNextInputMode), for: .touchUpInside) let spaceButton = GPButton(with: .SPACE) spaceButton.label?.text = "فاصله" spaceButton.backLayerInsetX = gapHorizontal / 2 spaceButton.backLayerInsetY = gapVertical / 2 spaceButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside) numberButtons[4].insert(spaceButton, at: 3) numberLayout.addSubview(spaceButton) let enterButton = GPButton(with: .ENTER) enterButton.addTarget(self, action: #selector(self.utilTouched(sender:)), for: .touchUpInside) enterButton.label?.text = "" enterButton.backLayerInsetX = gapHorizontal / 2 enterButton.backLayerInsetY = gapVertical / 2 numberButtons[4].insert(enterButton, at: 5) numberLayout.addSubview(enterButton) // Calculate constraint sizeConstraints(buttons: numberButtons, kbLayout: numberLayout) positionConstraints(buttons: numberButtons, kbLayout: numberLayout) } /************************************ * DELETE FUNCTION * ************************************/ // delete touching func deleteTouchDown(sender: GPButton) { playSound(for: delSound) let proxy = textDocumentProxy as UITextDocumentProxy proxy.deleteBackward() deleting = true timer = Timer.scheduledTimer(timeInterval: deleteTimer, target: self, selector: #selector(doDeleting), userInfo: nil, repeats: false) } func doDeleting() { if deleting { let proxy = textDocumentProxy as UITextDocumentProxy proxy.deleteBackward() if deleteTimer > 0.1 { deleteTimer -= 0.08 } if proxy.documentContextBeforeInput != nil { timer = Timer.scheduledTimer(timeInterval: deleteTimer, target: self, selector: #selector(doDeleting), userInfo: nil, repeats: false) playSound(for: delSound) } else { proxy.deleteBackward() timer = Timer.scheduledTimer(timeInterval: deleteTimer, target: self, selector: #selector(doDeleting), userInfo: nil, repeats: false) } } } // set deleting boolean value to false with this event func deleteTouchUp(_ sender: GPButton) { deleting = false deleteTimer = 0.3 timer.invalidate() } /************************************ * UTIL FUNCTION * ************************************/ func utilTouched(sender: GPButton) { let proxy = textDocumentProxy as UITextDocumentProxy let type = sender.type! switch type { case .SPACE: playSound(for: utilSound) proxy.insertText(" ") if shift == true { if returnAfterSpace == true { shift = false returnAfterSpace = false } } break case .GLOBE: self.advanceToNextInputMode() break case .SHIFT: playSound(for: utilSound) shift = !shift break case .NUMBER: playSound(for: utilSound) if alefbaLayout.layer.opacity == 0 { numberLayout.layer.opacity = 0 alefbaLayout.layer.opacity = 1 } else { alefbaLayout.layer.opacity = 0 numberLayout.layer.opacity = 1 } if shift == true { shift = false } break case .ENTER: playSound(for: utilSound) proxy.insertText("\n") break case .HALBSPACE: playSound(for: utilSound) proxy.insertText("\u{200C}") shift = false break default: break } } /************************************ * SHIFT FUNCTION * ************************************/ func doShift(shifting:Bool) { if shifting { for i in 0...10 { alefbaButtons[0][i].label?.text = smile[i+11] } // first two row in characters array for i in 0...1 { for j in 0...10 { // i+1 because buttons have one more row for emojies alefbaButtons[i+1][j].harf = characters[1][i][j] } } // row 3 is include shift and delete button for j in 1...8 { alefbaButtons[3][j].harf = characters[1][2][j-1] } // 4th row, the buttons beside the space alefbaButtons[4][2].harf = characters[1][3][0] alefbaButtons[4][4].harf = characters[1][3][1] // half space alefbaButtons[4][3].label?.text = "نیم‌فاصله" alefbaButtons[4][3].type = .HALBSPACE } else { for i in 0...10 { alefbaButtons[0][i].label?.text = smile[i] } // row 1 and 2 for i in 0...1 { for j in 0...10 { alefbaButtons[i+1][j].harf = characters[0][i][j] } } // row 3 is include shift and delete button for j in 1...8 { alefbaButtons[3][j].harf = characters[0][2][j-1] } // 4th row, the buttons beside the space alefbaButtons[4][2].harf = characters[0][3][0] alefbaButtons[4][4].harf = characters[0][3][1] // half space alefbaButtons[4][3].label?.text = "فاصله" alefbaButtons[4][3].type = .SPACE } } func shiftManager(sender: GPButton) { if shift == true { let type = sender.type! if type == .CHAR { if let h = sender.harf { if h.returnable == true { sender.Highlighting(state: false) shift = false return } if h.spaceReturnable == true { returnAfterSpace = true } } } } } /************************************ * OTHER FUNCTION * ************************************/ // add character into textfield func charTouched(_ sender: GPButton) { playSound(for: charSound) let proxy = textDocumentProxy as UITextDocumentProxy guard let char = sender.harf?.output else {return} proxy.insertText(char) shiftManager(sender: sender) } func emojiTouched(_ sender: GPButton) { playSound(for: charSound) let proxy = textDocumentProxy as UITextDocumentProxy guard let char = sender.label?.text else {return} proxy.insertText(char) if shift == true { returnAfterSpace = true } } func playSound(for type:UInt32) { // mute mode if soundState == 1 { return // hisssss! >:/ } // vibrate mode if soundState == 2 { AudioServicesPlaySystemSound(vibSound) return } AudioServicesPlaySystemSound(type) } //////////// constraints functions: /////////// func positionConstraints(buttons: [[GPButton]], kbLayout: UIView) { // chaining all first column to top and botton of each other vertically. for row in 0..<buttons.count-1 { NSLayoutConstraint(item: buttons[row][0], attribute: .bottom, relatedBy: .equal, toItem: buttons[row+1][0], attribute: .top, multiplier: 1, constant: 0).isActive = true } // chain first button to top of the keyboard layer NSLayoutConstraint(item: buttons[0][0], attribute: .top, relatedBy: .equal, toItem: kbLayout, attribute: .top, multiplier: 1, constant: 0).isActive = true // chain the last button to top of the keyboard layer NSLayoutConstraint(item: buttons[buttons.count-1][0], attribute: .bottom, relatedBy: .equal, toItem: kbLayout, attribute: .bottom, multiplier: 1, constant: 0).isActive = true // chaining all buttons in a row from left to right of each other horizontally. for row in 0..<buttons.count { for col in 1..<buttons[row].count { NSLayoutConstraint(item: buttons[row][col-1], attribute: .right, relatedBy: .equal, toItem: buttons[row][col], attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: buttons[row][col-1], attribute: .centerY, relatedBy: .equal, toItem: buttons[row][col], attribute: .centerY, multiplier: 1, constant: 0).isActive = true } } for row in 0..<buttons.count { NSLayoutConstraint(item: buttons[row][0], attribute: .left, relatedBy: .equal, toItem: kbLayout, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: buttons[row][buttons[row].count-1], attribute: .right, relatedBy: .equal, toItem: kbLayout, attribute: .right, multiplier: 1, constant: 0).isActive = true } } func sizeConstraints(buttons: [[GPButton]], kbLayout: UIView) { let muster = buttons[1][1] let np = NSLayoutConstraint(item: muster, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: buttonHeight) np.priority = 999 portraitConstraints.append(np) let nl = NSLayoutConstraint(item: muster, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: buttonHeight * 0.8) nl.priority = 999 landscapeConstraints.append(nl) for row in 0..<buttons.count { for col in 0..<buttons[row].count { let type = buttons[row][col].type! // all buttons should have same height (except emoji buttons) if type != .EMOJI { NSLayoutConstraint(item: buttons[row][col], attribute: .height, relatedBy: .equal, toItem: muster, attribute: .height, multiplier: 1, constant: 0).isActive = true } // assign width constraint to buttons according to its characteristic switch type { case .CHAR: NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1, constant: 0).isActive = true break case .EMOJI: // the width is always equal to muster // Portrait portraitConstraints.append(NSLayoutConstraint(item: buttons[row][col], attribute: .height, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1.3, constant: 0)) // Landscape landscapeConstraints.append(NSLayoutConstraint(item: buttons[row][col], attribute: .height, relatedBy: .equal, toItem: muster, attribute: .height, multiplier: 0.8, constant: 0)) NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1, constant: 0).isActive = true break case .SHIFT, .DELETE: NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .greaterThanOrEqual, toItem: muster, attribute: .width, multiplier: 1.5, constant: 0).isActive = true break case .ENTER: NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1.75, constant: 0).isActive = true break case .SPACE, .HALBSPACE: NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .greaterThanOrEqual, toItem: muster, attribute: .width, multiplier: 3.5, constant: 0).isActive = true break case .GLOBE, .NUMBER: NSLayoutConstraint(item: buttons[row][col], attribute: .width, relatedBy: .equal, toItem: muster, attribute: .width, multiplier: 1.25, constant: 0).isActive = true break } } } } /**************************************** * * * System default function * * * ****************************************/ override func updateViewConstraints() { super.updateViewConstraints() // Activate constraints according device orientation if UIScreen.main.bounds.size.height > UIScreen.main.bounds.size.width { NSLayoutConstraint.deactivate(landscapeConstraints) NSLayoutConstraint.activate(portraitConstraints) } else { NSLayoutConstraint.deactivate(portraitConstraints) NSLayoutConstraint.activate(landscapeConstraints) } self.view.layoutSubviews() } override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { updateViewConstraints() } override func viewDidLoad() { super.viewDidLoad() let prefs = UserDefaults(suiteName: "group.me.alirezak.gachpazh") // retreive user Sound settings if let s = prefs?.integer(forKey: "sound") { if s != 0 { soundState = s } else { soundState = 3 // default sound is On } } for i in 0..<33 { if let emojiInt = prefs?.integer(forKey: String(i)){ if emojiInt != 0 { smile [i] = String(Character(UnicodeScalar(emojiInt)!)) } } } // get all variable according current device state calculateVariables() } override func viewWillAppear(_ animated: Bool) { print("viewWillAppear") super.viewWillAppear(animated) setTheme() // initial landscape and portrait constraints landscapeConstraints = [NSLayoutConstraint]() portraitConstraints = [NSLayoutConstraint]() /**** initial Alefba layer ****/ alefbaLayout = UIView() alefbaLayout.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(alefbaLayout) alefbaLayout.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true alefbaLayout.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true alefbaLayout.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true alefbaLayout.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true initAlefbaLayout() alefbaLayout.layer.opacity = 0 /*** Initial Number Layer ***/ numberLayout = UIView() numberLayout.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(numberLayout) numberLayout.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true numberLayout.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true numberLayout.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true numberLayout.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true initNumberLayout() numberLayout.layer.opacity = 0 } override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 0.4) { self.alefbaLayout.layer.opacity = 1 } } func calculateVariables() { // define a default multiplier based iphone 6/6s/7 (width = 375) screen size. if UIScreen.main.bounds.size.height > UIScreen.main.bounds.size.width { dmpPatriot = UIScreen.main.bounds.size.width / 375 } else { dmpPatriot = UIScreen.main.bounds.size.width / 667 } gapHorizontal = gapHorizontal * dmpPatriot if dmpPatriot < 1 { gapVertical = gapVertical / dmpPatriot } else { gapVertical = gapVertical * dmpPatriot buttonHeight = buttonHeight * dmpPatriot } } override func textDidChange(_ textInput: UITextInput?) { //The app has just changed the document's contents, the document context has been updated. setTheme() // check if user "SEND" the message! let proxy = self.textDocumentProxy if proxy.documentContextAfterInput == nil && proxy.documentContextBeforeInput == nil { guard (alefbaLayout != nil) else { return } shift = false } } // GPButtonEventsDelegate func moveCursor(numberOfMovement: Int) { let proxy = textDocumentProxy as UITextDocumentProxy proxy.adjustTextPosition(byCharacterOffset: numberOfMovement) } func setTheme() { let proxy = self.textDocumentProxy if proxy.keyboardAppearance == UIKeyboardAppearance.dark { viewBackground = UIColor(red:0.08, green:0.08, blue:0.08, alpha:1.0) GPButton.buttonColor = UIColor(red:0.35, green:0.35, blue:0.35, alpha:1.0) GPButton.buttonHighlighted = UIColor(red:0.35, green:0.35, blue:0.35, alpha:1.0) GPButton.utilBackgroundColor = UIColor(red:0.22, green:0.22, blue:0.22, alpha:1.0) GPButton.charColor = UIColor.white GPButton.shadowColor = UIColor(red:0.08, green:0.08, blue:0.08, alpha:1.0) GPButton.layoutColor = UIColor(red:0.08, green:0.08, blue:0.08, alpha:1.0) } else { viewBackground = UIColor(red:0.84, green:0.84, blue:0.84, alpha:1.0) GPButton.buttonColor = UIColor.white GPButton.buttonHighlighted = UIColor.white GPButton.utilBackgroundColor = UIColor(red:0.67, green:0.70, blue:0.73, alpha:1.0) GPButton.charColor = UIColor.black GPButton.shadowColor = UIColor(red:0.54, green:0.55, blue:0.56, alpha:1.0) GPButton.layoutColor = UIColor(red:0.84, green:0.84, blue:0.84, alpha:1.0) } } }
8fe7225f68f027925b54e73ff737a2a8
43.39135
197
0.546705
false
false
false
false
ChenJian345/realm-cocoa
refs/heads/master
RealmSwift-swift1.2/Tests/SwiftTestObjects.swift
apache-2.0
15
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import RealmSwift class SwiftStringObject: Object { dynamic var stringCol = "" } class SwiftBoolObject: Object { dynamic var boolCol = false } class SwiftIntObject: Object { dynamic var intCol = 0 } class SwiftLongObject: Object { dynamic var longCol: Int64 = 0 } class SwiftObject: Object { dynamic var boolCol = false dynamic var intCol = 123 dynamic var floatCol = 1.23 as Float dynamic var doubleCol = 12.3 dynamic var stringCol = "a" dynamic var binaryCol = "a".dataUsingEncoding(NSUTF8StringEncoding)! dynamic var dateCol = NSDate(timeIntervalSince1970: 1) dynamic var objectCol = SwiftBoolObject() let arrayCol = List<SwiftBoolObject>() class func defaultValues() -> [String: AnyObject] { return ["boolCol": false as AnyObject, "intCol": 123 as AnyObject, "floatCol": 1.23 as AnyObject, "doubleCol": 12.3 as AnyObject, "stringCol": "a" as AnyObject, "binaryCol": "a".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, "dateCol": NSDate(timeIntervalSince1970: 1) as NSDate, "objectCol": [false], "arrayCol": [] as NSArray] } } class SwiftOptionalObject: Object { // FIXME: Support all optional property types // dynamic var optBoolCol: Bool? // dynamic var optIntCol: Int? // dynamic var optFloatCol: Float? // dynamic var optDoubleCol: Double? #if REALM_ENABLE_NULL dynamic var optStringCol: NSString? dynamic var optBinaryCol: NSData? #endif // dynamic var optDateCol: NSDate? dynamic var optObjectCol: SwiftBoolObject? // let arrayCol = List<SwiftBoolObject>() } class SwiftDogObject: Object { dynamic var dogName = "" } class SwiftOwnerObject: Object { dynamic var name = "" dynamic var dog = SwiftDogObject() } class SwiftAggregateObject: Object { dynamic var intCol = 0 dynamic var floatCol = 0 as Float dynamic var doubleCol = 0.0 dynamic var boolCol = false dynamic var dateCol = NSDate() dynamic var trueCol = true dynamic var stringListCol = List<SwiftStringObject>() } class SwiftAllIntSizesObject: Object { dynamic var int8 : Int8 = 0 dynamic var int16 : Int16 = 0 dynamic var int32 : Int32 = 0 dynamic var int64 : Int64 = 0 } class SwiftEmployeeObject: Object { dynamic var name = "" dynamic var age = 0 dynamic var hired = false } class SwiftCompanyObject: Object { dynamic var employees = List<SwiftEmployeeObject>() } class SwiftArrayPropertyObject: Object { dynamic var name = "" let array = List<SwiftStringObject>() let intArray = List<SwiftIntObject>() } class SwiftDoubleListOfSwiftObject: Object { let array = List<SwiftListOfSwiftObject>() } class SwiftListOfSwiftObject: Object { let array = List<SwiftObject>() } class SwiftArrayPropertySubclassObject: SwiftArrayPropertyObject { let boolArray = List<SwiftBoolObject>() } class SwiftUTF8Object: Object { dynamic var 柱колоéнǢкƱаم👍 = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا" } class SwiftIgnoredPropertiesObject: Object { dynamic var name = "" dynamic var age = 0 dynamic var runtimeProperty: AnyObject? dynamic var runtimeDefaultProperty = "property" dynamic var readOnlyProperty: Int { return 0 } override class func ignoredProperties() -> [String] { return ["runtimeProperty", "runtimeDefaultProperty"] } } class SwiftLinkToPrimaryStringObject: Object { dynamic var pk = "" dynamic var object: SwiftPrimaryStringObject? let objects = List<SwiftPrimaryStringObject>() override class func primaryKey() -> String? { return "pk" } } class SwiftRecursiveObject: Object { let objects = List<SwiftRecursiveObject>() } class SwiftPrimaryStringObject: Object { dynamic var stringCol = "" dynamic var intCol = 0 override class func primaryKey() -> String? { return "stringCol" } } class SwiftIndexedPropertiesObject: Object { dynamic var stringCol = "" dynamic var intCol = 0 override class func indexedProperties() -> [String] { return ["stringCol"] // Add "intCol" when integer indexing is supported } }
8adc8af1249d03b96e22eec9972e018b
27.112994
81
0.66881
false
false
false
false
filograno/Moya
refs/heads/master
Demo/Tests/SignalProducer+MoyaSpec.swift
mit
1
import Quick import Moya import ReactiveSwift import Nimble #if os(iOS) || os(watchOS) || os(tvOS) private func ImageJPEGRepresentation(_ image: Image, _ compression: CGFloat) -> Data? { return UIImageJPEGRepresentation(image, compression) as Data? } #elseif os(OSX) private func ImageJPEGRepresentation(_ image: Image, _ compression: CGFloat) -> Data? { var imageRect: CGRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) let imageRep = NSBitmapImageRep(cgImage: image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)!) return imageRep.representation(using: .JPEG, properties: [:]) } #endif // Necessary since Image(named:) doesn't work correctly in the test bundle private extension ImageType { class func testPNGImage(named name: String) -> ImageType { class TestClass { } let bundle = Bundle(for: type(of: TestClass())) let path = bundle.path(forResource: name, ofType: "png") return Image(contentsOfFile: path!)! } } private func signalSendingData(_ data: Data, statusCode: Int = 200) -> SignalProducer<Response, Moya.Error> { return SignalProducer(value: Response(statusCode: statusCode, data: data as Data, response: nil)) } class SignalProducerMoyaSpec: QuickSpec { override func spec() { describe("status codes filtering") { it("filters out unrequested status codes") { let data = Data() let signal = signalSendingData(data, statusCode: 10) var errored = false signal.filterStatusCodes(range: 0...9).startWithResult { event -> Void in switch event { case .success(let object): fail("called on non-correct status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("filters out non-successful status codes") { let data = Data() let signal = signalSendingData(data, statusCode: 404) var errored = false signal.filterSuccessfulStatusCodes().startWithResult { result -> Void in switch result { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = Data() let signal = signalSendingData(data) var called = false signal.filterSuccessfulStatusCodes().startWithResult({ _ in called = true }) expect(called).to(beTruthy()) } it("filters out non-successful status and redirect codes") { let data = Data() let signal = signalSendingData(data, statusCode: 404) var errored = false signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { result -> Void in switch result { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = Data() let signal = signalSendingData(data) var called = false signal.filterSuccessfulStatusAndRedirectCodes().startWithResult({ _ in called = true }) expect(called).to(beTruthy()) } it("passes through correct redirect codes") { let data = Data() let signal = signalSendingData(data, statusCode: 304) var called = false signal.filterSuccessfulStatusAndRedirectCodes().startWithResult({ _ in called = true }) expect(called).to(beTruthy()) } it("knows how to filter individual status codes") { let data = Data() let signal = signalSendingData(data, statusCode: 42) var called = false signal.filterStatusCode(code: 42).startWithResult({ _ in called = true }) expect(called).to(beTruthy()) } it("filters out different individual status code") { let data = Data() let signal = signalSendingData(data, statusCode: 43) var errored = false signal.filterStatusCode(code: 42).startWithResult { result -> Void in switch result { case .success(let object): fail("called on non-success status code: \(object)") case .failure: errored = true } } expect(errored).to(beTruthy()) } } describe("image maping") { it("maps data representing an image to an image") { let image = Image.testPNGImage(named: "testImage") let data = ImageJPEGRepresentation(image, 0.75) let signal = signalSendingData(data!) var size: CGSize? signal.mapImage().startWithResult({ _ in size = image.size }) expect(size).to(equal(image.size)) } it("ignores invalid data") { let data = Data() let signal = signalSendingData(data) var receivedError: Moya.Error? signal.mapImage().startWithResult { result -> Void in switch result { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error } } expect(receivedError).toNot(beNil()) let expectedError = Moya.Error.imageMapping(Response(statusCode: 200, data: Data(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } describe("JSON mapping") { it("maps data representing some JSON to that JSON") { let json = ["name": "John Crighton", "occupation": "Astronaut"] let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) let signal = signalSendingData(data) var receivedJSON: [String: String]? signal.mapJSON().startWithResult { result -> Void in if case .success(let _json) = result, let json = _json as? [String: String] { receivedJSON = json } } expect(receivedJSON?["name"]).to(equal(json["name"])) expect(receivedJSON?["occupation"]).to(equal(json["occupation"])) } it("returns a Cocoa error domain for invalid JSON") { let json = "{ \"name\": \"john }" let data = json.data(using: String.Encoding.utf8) let signal = signalSendingData(data!) var receivedError: Moya.Error? signal.mapJSON().startWithResult { result -> Void in switch result { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error } } expect(receivedError).toNot(beNil()) switch receivedError { case .some(.jsonMapping): break default: fail("expected NSError with \(NSCocoaErrorDomain) domain") } } } describe("string mapping") { it("maps data representing a string to a string") { let string = "You have the rights to the remains of a silent attorney." let data = string.data(using: String.Encoding.utf8) let signal = signalSendingData(data!) var receivedString: String? signal.mapString().startWithResult({ _ in receivedString = string }) expect(receivedString).to(equal(string)) } it("ignores invalid data") { let data = NSData(bytes: [0x11FFFF] as [UInt32], length: 1) //Byte exceeding UTF8 let signal = signalSendingData(data as Data) var receivedError: Moya.Error? signal.mapString().startWithResult { result -> Void in switch result { case .success: fail("next called for invalid data") case .failure(let error): receivedError = error } } expect(receivedError).toNot(beNil()) let expectedError = Moya.Error.stringMapping(Response(statusCode: 200, data: Data(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } } }
ad89aa43ac5da5bfe2e9e2c46b0061a8
38.791667
119
0.474631
false
false
false
false
SwiftORM/StORM
refs/heads/master
Sources/StORM/StORMtResultSet.swift
apache-2.0
2
// // StORMResultSet.swift // StORM // // Created by Jonathan Guthrie on 2016-09-23. // // /// Result Set container class. /// Collects the Restltset, and the cursor data. /// Datasurce specific properties can also be set, such as those required for MySQL ResultSet parsing. open class StORMResultSet { /// A container for the ResultSet Rows. public var rows: [StORMRow] = [StORMRow]() /// The ResultSet's cursor. public var cursorData: StORMCursor = StORMCursor() /// An array of strings which are the field/column names. /// Used exclusively for MySQL datasources at this time. public var fieldNames = [String]() // explicitly for MySQL, but should be adopted globally /// A [String:String] which are is the field property information. /// Used exclusively for MySQL datasources at this time. open var fieldInfo = [String:String]() // explicitly for MySQL, but should be adopted globally /// The foundSetCount property. /// Used exclusively for MySQL datasources at this time. public var foundSetCount = 0 // explicityly for MySQL, but should be adopted globally /// The inserted ID value. /// Used exclusively for MySQL datasources at this time. public var insertedID = 0 // explicityly for MySQL, but should be adopted globally /// Public initializer. public init() {} }
ea76a94ab441f6b9ddbcb6dcf827a73c
33.421053
102
0.727829
false
false
false
false
Inquisitor0/LSB2
refs/heads/master
Carthage/Checkouts/PKHUD/PKHUD/PKHUDAnimation.swift
apache-2.0
9
// // PKHUDAnimation.swift // PKHUD // // Created by Piergiuseppe Longo on 06/01/16. // Copyright © 2016 Piergiuseppe Longo, NSExceptional. All rights reserved. // Licensed under the MIT license. // import Foundation import QuartzCore public final class PKHUDAnimation { public static let discreteRotation: CAAnimation = { let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z") animation.values = [ NSNumber(value: 0.0), NSNumber(value: 1.0 * .pi / 6.0), NSNumber(value: 2.0 * .pi / 6.0), NSNumber(value: 3.0 * .pi / 6.0), NSNumber(value: 4.0 * .pi / 6.0), NSNumber(value: 5.0 * .pi / 6.0), NSNumber(value: 6.0 * .pi / 6.0), NSNumber(value: 7.0 * .pi / 6.0), NSNumber(value: 8.0 * .pi / 6.0), NSNumber(value: 9.0 * .pi / 6.0), NSNumber(value: 10.0 * .pi / 6.0), NSNumber(value: 11.0 * .pi / 6.0), NSNumber(value: 2.0 * .pi) ] animation.keyTimes = [ NSNumber(value: 0.0), NSNumber(value: 1.0 / 12.0), NSNumber(value: 2.0 / 12.0), NSNumber(value: 3.0 / 12.0), NSNumber(value: 4.0 / 12.0), NSNumber(value: 5.0 / 12.0), NSNumber(value: 0.5), NSNumber(value: 7.0 / 12.0), NSNumber(value: 8.0 / 12.0), NSNumber(value: 9.0 / 12.0), NSNumber(value: 10.0 / 12.0), NSNumber(value: 11.0 / 12.0), NSNumber(value: 1.0) ] animation.duration = 1.2 animation.calculationMode = "discrete" animation.repeatCount = Float(INT_MAX) return animation }() static let continuousRotation: CAAnimation = { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = 2.0 * .pi animation.duration = 1.2 animation.repeatCount = Float(INT_MAX) return animation }() }
1503030e86773ab9c5b09cb32397f2b6
32.721311
76
0.533787
false
false
false
false
byu-oit-appdev/ios-byuSuite
refs/heads/dev
byuSuite/Apps/UniversityClassSchedule/controller/UniversityClassScheduleSectionViewController.swift
apache-2.0
1
// // UniversityClassScheduleSectionViewController.swift // byuSuite // // Created by Erik Brady on 5/8/18. // Copyright © 2018 Brigham Young University. All rights reserved. // private let SHOW_MAP_SEGUE_ID = "showBuildingMap" class UniversityClassScheduleSectionViewController: ByuTableDataViewController { //MARK: Outlets @IBOutlet private weak var spinner: UIActivityIndicatorView! //MARK: Public Properties var section: RegCourseSection! //MARK: Private Properties private var buildings = [CampusBuilding2]() override func viewDidLoad() { super.viewDidLoad() title = "Section \(section.section)" loadTableData() loadBuildings() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == SHOW_MAP_SEGUE_ID, let vc = segue.destination as? CampusBuildingsMapViewController2, let building = sender as? CampusBuilding2 { vc.building = building } } //MARK: Private Methods private func loadBuildings() { CampusLocationsClient2.getCampusBuildings { (campusBuildings, error) in self.spinner.stopAnimating() self.tableView.isHidden = false if let campusBuildings = campusBuildings { self.buildings = campusBuildings } else { super.displayAlert(error: error, alertHandler: nil) } } } private func loadTableData() { let sectionSegueAction: (RegCourseSection) -> Void = { (sect) in let acronym = sect.building ?? "" if let building = self.buildings.findBuilding(with: acronym) { //Pass the building object as the argument for sender (even though it's not what is initiating the segue, which is traditionally what sender is used for) to avoid having to create a peroperty to store the building temporarily self.performSegue(withIdentifier: SHOW_MAP_SEGUE_ID, sender: building) } else { super.displayAlert(message: "The building \(acronym) is not currently in our system.") { (_) in self.tableView.deselectSelectedRow() } } } //Set up section rows with Row for section var sectionRows = [Row(text: section.sectionDateTimeDetailText(), detailText: section.sectionPlaceDetailText(), action: { sectionSegueAction(self.section) }, object: section)] //Append Rows for all child sections sectionRows.append(contentsOf: section.childSections.map { (sect) -> Row in return Row(text: section.sectionDateTimeDetailText(), detailText: section.sectionPlaceDetailText(), action: { sectionSegueAction(sect) }, object: sect) }) let rowData: [(String, String?)] = [ ("Permission Code Required", section.permissionCodeRequired ? "Yes" : "No"), ("Add Action", section.addAction), ("Limitations", section.limitations), ("Section Type", section.sectionType), ("Available Seats", section.availableSeats), ("Section Size", section.sectionSize), ("Lab/Quiz Section", section.labQuizSection), ("Credit Hours", section.creditHours), ("Honors", section.honors ? "Yes" : "No"), ("Instructor", section.instructor), ("Section Begin Date", section.sectionBeginDate), ("Section End Date", section.sectionEndDate), ("Course Fee", section.courseFee) ].filter { $0.1 != nil } tableData = TableData(sections: [ Section(height: 30, cellId: "dateTimePlaceCell", rows: sectionRows), Section(height: 15, cellId: "detailCell", rows: rowData.map({ (rowInfo) -> Row in return Row(text: rowInfo.0, detailText: rowInfo.1, action: { super.displayAlert(title: rowInfo.0, message: rowInfo.1, alertHandler: { (_) in self.tableView.deselectSelectedRow() }) }, enabled: !(rowInfo.1?.isEmpty ?? true)) })) ]) } }
4f65b24a0b124c3b31ae6cc8a156d8ee
33.330189
229
0.707612
false
false
false
false
zcrome/taxi-app-client-end-point
refs/heads/master
taxi-app-client-end-point/taxi-app-client-end-point/Model/Client.swift
mit
1
// // Client.swift // taxi-app-client-end-point // // Created by zcrome on 10/16/17. // Copyright © 2017 zcrome. All rights reserved. // import Foundation import SwiftyJSON class Client: TypeOfUserProtocol{ var id: String var name: String var lastName: String var phone: String var email: String let typeUseIs: TypeOfUser = .client var isValid: Bool{ if id.isEmpty{ return false } return true } init(name: String, lastName: String, phone: String, email: String) { self.name = name self.lastName = lastName self.phone = phone self.email = email self.id = "" } init(TaxiJSON json: JSON) { if let id = json["userId"].string{ self.id = id }else{ self.id = "" } if let name = json["name"].string{ self.name = name }else{ self.name = "" } if let lastName = json["lastName"].string{ self.lastName = lastName }else{ self.lastName = "" } if let phone = json["phone"].string{ self.phone = phone }else{ self.phone = "" } if let email = json["email"].string{ self.email = email }else{ self.email = "" } } }
3f5f468a6393b684b17042a4a90db998
16.054795
49
0.554217
false
false
false
false
toggl/superday
refs/heads/develop
teferi/Interactors/GetActivitiesGroupedByDaysInRange.swift
bsd-3-clause
1
import Foundation import RxSwift class GetActivitiesGroupedByDaysInRange: Interactor { private let repositoryService: RepositoryService private let timeService: TimeService private let startDay: Date private let endDay: Date init(repositoryService: RepositoryService, timeService: TimeService, startDay: Date, endDay: Date) { self.repositoryService = repositoryService self.timeService = timeService self.startDay = startDay self.endDay = endDay } func execute() -> Observable<[Date: [Activity]]> { return repositoryService.getTimeSlots(fromDate: startDay.ignoreTimeComponents(), toDate: endDay.tomorrow.ignoreTimeComponents()) .map(toDictionary) } func toDictionary(timeSlots: [TimeSlotEntity]) -> [Date: [Activity]] { return timeSlots .groupBy({ $0.startTime.ignoreTimeComponents() }) .reduce([Date:[Activity]]()) { dict, timeSlotsForDay in guard let date = timeSlotsForDay.first?.startTime else { return dict } var dictCopy = dict dictCopy[date] = timeSlotsForDay .groupBy({ $0.category }) .map { timeSlotsGroup in let totalDuration = timeSlotsGroup.map { [unowned self] timeSlot in timeSlot.duration ?? self.timeService.now.timeIntervalSince(timeSlot.startTime) } .reduce(0, +) return Activity(category: timeSlotsGroup.first!.category, duration: totalDuration) } return dictCopy } } }
b74d114409d7eb8f7351adbb6c6709c6
32.698113
136
0.572788
false
false
false
false
PezHead/tiny-tennis-scoreboard
refs/heads/master
Tiny Tennis/ChampionStore.swift
mit
1
// // ChampionStore.swift // Tiny Tennis // // Created by David Bireta on 10/20/16. // Copyright © 2016 David Bireta. All rights reserved. // import TableTennisAPI /// Provides access to available `Champion`s. class ChampionStore { /// Returns all of the `Champion`s. /// This will make a API call to fetch champion data. Results will be cached for offline usage. /// /// - parameter completion: Closure to be called when the final list of champions is compiled. static func all(_ completion: @escaping ([Champion]) -> Void) { var championList = [Champion]() if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let path = dir.appendingPathComponent("combinedPlayers.json") if let jsonData = try? Data(contentsOf: path) { let json = try? JSONSerialization.jsonObject(with: jsonData, options: []) if let peeps = json as? [Any] { for case let playerObj as [String: Any] in peeps { if let champ = Champion(jsonData: playerObj) { championList.append(champ) } } // FIXME: Not a huge fan of calling the completion twice (once for cache, once for network). completion(championList) } } } // Request players from API API.shared.getPlayers { champions in champions.forEach { champ in // Merge updated players with exisitng players // Simple approach: Just add players that don't already exist if championList.contains(champ) { let index = championList.index(of: champ)! championList.remove(at: index) } championList.append(champ) } // Send completion result completion(championList) // Write updated player list to disk do { let jsonFriendlyChamps = championList.map({ (champion) -> [String: Any] in return champion.dictionaryRep() }) if JSONSerialization.isValidJSONObject(jsonFriendlyChamps) { let jsonified = try JSONSerialization.data(withJSONObject: jsonFriendlyChamps, options: .prettyPrinted) if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let path = dir.appendingPathComponent("combinedPlayers.json") do { try jsonified.write(to: path, options: .atomic) } catch let error { print("Error writing player file: \(error)") } } } } catch let error { print("Error serializing to json: \(error)") } } } }
c379226392cfb7928a290e872d7836ae
39.139241
123
0.51561
false
false
false
false
adolfrank/Swift_practise
refs/heads/master
08-day/08-day/HomeViewController.swift
mit
1
// // HomeViewController.swift // 08-day // // Created by Adolfrank on 3/21/16. // Copyright © 2016 FrankAdol. All rights reserved. // import UIKit class HomeViewController: UITableViewController { let cellIdentifer = "NewCellIdentifier" let favoriteEmoji = ["🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆"] let newFavoriteEmoji = ["🏃🏃🏃🏃🏃", "💩💩💩💩💩", "👸👸👸👸👸", "🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆" ] var emojiData = [String]() // var tableViewController = UITableViewController(style: .Plain) // var refreshControl = UIRefreshControl() @IBAction func showNav(sender: AnyObject) { print("yyy") } override func viewDidLoad() { super.viewDidLoad() emojiData = favoriteEmoji let emojiTableView = self.tableView emojiTableView.backgroundColor = UIColor(red:0.092, green:0.096, blue:0.116, alpha:1) emojiTableView.dataSource = self emojiTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifer) emojiTableView.tableFooterView = UIView(frame: CGRectZero) emojiTableView.separatorStyle = UITableViewCellSeparatorStyle.None self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: "didRoadEmoji", forControlEvents: UIControlEvents.ValueChanged) self.refreshControl!.backgroundColor = UIColor(red:100/255/0 , green:0.113, blue:0.145, alpha:1) let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.refreshControl!.attributedTitle = NSAttributedString(string: "Last updated on \(NSDate())", attributes: attributes) self.refreshControl!.tintColor = UIColor.whiteColor() // self.title = "emoji" let titleLabel = UILabel(frame: CGRectMake(0, 0, 0 , 44)) titleLabel.textAlignment = NSTextAlignment.Center titleLabel.text = "下拉刷新" titleLabel.textColor = UIColor.whiteColor() self.navigationItem.titleView = titleLabel self.navigationController?.hidesBarsOnSwipe self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "bg"), forBarMetrics: UIBarMetrics.Default) self.navigationController?.navigationBar.shadowImage = UIImage(named: "bg") emojiTableView.rowHeight = UITableViewAutomaticDimension emojiTableView.estimatedRowHeight = 60.0 } func didRoadEmoji() { print("ttt") self.emojiData = newFavoriteEmoji self.tableView.reloadData() self.refreshControl!.endRefreshing() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return emojiData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer, forIndexPath: indexPath) // let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer)! as UITableViewCell // Configure the cell... cell.textLabel!.text = self.emojiData[indexPath.row] cell.textLabel!.textAlignment = NSTextAlignment.Center cell.textLabel!.font = UIFont.systemFontOfSize(50) cell.backgroundColor = UIColor.clearColor() cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } }
fe7359a0051f867b4380e4d9ff0c13b5
37.8125
128
0.676329
false
false
false
false
jhaigler94/cs4720-iOS
refs/heads/master
Pensieve/Pensieve/MemoryViewController.swift
apache-2.0
1
// // MemoryViewController.swift // Pensieve // // Created by Jennifer Ruth Haigler on 10/26/15. // Copyright © 2015 University of Virginia. All rights reserved. // import UIKit import CoreData class MemoryViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var passedMemName: UILabel! @IBOutlet weak var passedMemDate: UILabel! @IBOutlet weak var passedMemTime: UILabel! @IBOutlet weak var MemPointTable: UITableView! var memName = String() var memDate = String() var memTime = String() var memLoc = String() var memId = String() var note = String() //var picFileLoc = String() var passName:String! var passDate:String! var passTime:String! var names = [String]() // MARK: Properties let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() passedMemName.text = passName; passedMemDate.text = passDate; passedMemTime.text = passTime; title = "Pensieve" /*populateNames() MemPointTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") */ // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { print("VIEWDIDAPPEAR: MEMORYVIEW") names = [] populateNames() MemPointTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") //MemPointTable.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { NSLog("You selected cell number: \(indexPath.row)!") let fetchRequest = NSFetchRequest(entityName: "Memory") /* And execute the fetch request on the context */ do { let mems = try managedObjectContext.executeFetchRequest(fetchRequest) for memory in mems{ if((memory.valueForKey("memname")as? String!)==((passedMemName.text)as?String!)){ if((memory.valueForKey("pointid")as? String!)==(names[indexPath.row])){ memName = ((memory.valueForKey("memname")as? String)!) memDate = ((memory.valueForKey("memdate")as? String)!) memTime = ((memory.valueForKey("memtime")as? String)!) memLoc = ((memory.valueForKey("memloc")as? String)!) memId = ((memory.valueForKey("pointid")as? String)!) //picFileLoc = ((memory.valueForKey("picfileloc")as? String)!) note = ((memory.valueForKey("note")as? String)!) } } } }catch let error as NSError{ print(error) } NSLog(memName) NSLog(memDate) NSLog(memTime) self.performSegueWithIdentifier("ToViewMemPt", sender: self) } // MARK: Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "ToCreateMemPtSeg") { var cMemVC = segue.destinationViewController as! CreateMemPtViewController; cMemVC.passFromMemName = passedMemName.text } else if (segue.identifier == "ToViewMemPt") { var memVC = segue.destinationViewController as! ViewMemPt; memVC.passedName = memName memVC.passedDate = memDate memVC.passedTime = memTime memVC.passedLoc = memLoc memVC.passedId = memId memVC.passedNote = note //memVC.passedFileLoc = picFileLoc } } @IBAction func unwindToMemView(unwindSegue: UIStoryboardSegue) { if let memViewController = unwindSegue.sourceViewController as? CreateMemPtViewController { print("Coming from CreateMemPtViewController") } } func populateNames(){ /* Create the fetch request first */ let fetchRequest = NSFetchRequest(entityName: "Memory") /* And execute the fetch request on the context */ do { let mems = try managedObjectContext.executeFetchRequest(fetchRequest) for memory in mems{ if(!((memory.valueForKey("memloc")as? String!)==("MainNotPoint"))){ if((memory.valueForKey("memname")as? String!)==(passName)){ names.append(((memory.valueForKey("pointid")as? String)!)) } } } }catch let error as NSError{ print(error) } } func tableView(MemPointTable: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } func tableView(MemPointTable: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = MemPointTable.dequeueReusableCellWithIdentifier("Cell") cell!.textLabel!.text = names[indexPath.row] return cell! } /* // 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. } */ }
b54fae6aa9381c2665e2c602d20819b8
31.747253
112
0.580034
false
false
false
false
caamorales/JTSplashView
refs/heads/master
JTSplashView/JTSplashView.swift
mit
3
// // JTSplashView.swift // JTSplashView Example // // Created by Jakub Truhlar on 25.07.15. // Copyright (c) 2015 Jakub Truhlar. All rights reserved. // import UIKit class JTSplashView: UIView { // MARK: Properties static let sharedInstance = JTSplashView() static let screenSize = UIScreen.mainScreen().bounds.size let duration = 0.3 let borderWidth : CGFloat = 10.0 var bgColor = UIColor(red: 45.0 / 255.0, green: 61.0 / 255.0, blue: 81.0 / 255.0, alpha: 1.0) var circleColor = UIColor(red: 110.0 / 255.0, green: 180.0 / 255.0, blue: 240.0 / 255.0, alpha: 1.0) var vibrateAgain = true var completionBlock:(() -> Void)? var circlePathInitial = UIBezierPath(ovalInRect: CGRect(x: screenSize.width / 2, y: screenSize.height / 2, width: 0.0, height: 0.0)) var circlePathFinal = UIBezierPath(ovalInRect: CGRect(x: (screenSize.width / 2) - 35.0, y: (screenSize.height / 2) - 35.0, width: 70.0, height: 70.0)) var circlePathShrinked = UIBezierPath(ovalInRect: CGRect(x: screenSize.width / 2 - 5.0, y: screenSize.height / 2 - 5.0, width: 10.0, height: 10.0)) var circlePathSqueezeVertical = UIBezierPath(ovalInRect: CGRect(x: (screenSize.width / 2) - 34.0, y: (screenSize.height / 2) - 36.0, width: 68.0, height: 72.0)) var circlePathSqueezeHorizontal = UIBezierPath(ovalInRect: CGRect(x: (screenSize.width / 2) - 36.0, y: (screenSize.height / 2) - 34.0, width: 72.0, height: 68.0)) var baseCircleLayer = CAShapeLayer() var bgWithMask = UIView() var bgWithoutMask = UIView() // MARK: Initializers init() { super.init(frame:CGRectZero) self.alpha = 0.0 UIApplication.sharedApplication().delegate?.window??.makeKeyAndVisible() } override init(frame: CGRect) { super.init(frame: frame) doInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) doInit() } func doInit() { // 1x with mask and above 1x without mask BG bgWithMask = createBackgroundWithMask(createMaskCircleLayer()) bgWithoutMask = createBackgroundWithMask(nil) addSubview(bgWithMask) addSubview(bgWithoutMask) createBaseCircle() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("addToWindow"), name: UIWindowDidBecomeVisibleNotification, object: nil) } /** Class function to create the splash view. This function takes three optional arguments and generate splash view above everything in keyWindow. StatusBar is hidden during the process, so you should make it visible in finish function block. :param: backgroundColor Background color of the splash view. Default is asphalt color. :param: circleColor Color of the animated circle. Default is blue color. :param: circleSize Size of the animated circle. 10pt border will be added, but the size remains the same. Width should be same as height. Default is CGSize(70, 70). */ class func splashViewWithBackgroundColor(backgroundColor: UIColor?, circleColor: UIColor?, circleSize: CGSize?) { if isVisible() { return } UIApplication.sharedApplication().statusBarHidden = true sharedInstance.alpha = 1.0 // Redefine properties if (backgroundColor != nil) { sharedInstance.bgColor = backgroundColor! } if (circleColor != nil) { sharedInstance.circleColor = circleColor! } if (circleSize != nil) { var sizeWithoutBorder = CGSizeMake(circleSize!.width - sharedInstance.borderWidth, circleSize!.height - sharedInstance.borderWidth) sharedInstance.circlePathFinal = UIBezierPath(ovalInRect: CGRect(x: (JTSplashView.screenSize.width / 2) - (sizeWithoutBorder.width / 2), y: (JTSplashView.screenSize.height / 2) - (sizeWithoutBorder.height / 2), width: sizeWithoutBorder.width, height: sizeWithoutBorder.height)) sharedInstance.circlePathSqueezeVertical = UIBezierPath(ovalInRect: CGRect(x: (JTSplashView.screenSize.width / 2) - ((sizeWithoutBorder.width / 2) * 0.96), y: (JTSplashView.screenSize.height / 2) - ((sizeWithoutBorder.height / 2) * 1.04), width: sizeWithoutBorder.width * 0.96, height: sizeWithoutBorder.height * 1.04)) sharedInstance.circlePathSqueezeHorizontal = UIBezierPath(ovalInRect: CGRect(x: (JTSplashView.screenSize.width / 2) - ((sizeWithoutBorder.width / 2) * 1.04), y: (JTSplashView.screenSize.height / 2) - ((sizeWithoutBorder.height / 2) * 0.96), width: sizeWithoutBorder.width * 1.04, height: sizeWithoutBorder.height * 0.96)) } sharedInstance.doInit() } // MARK: Public functions /** Class function to hide the splash view. This function hide the splash view. Should be called in the right time after the app is ready. */ class func finish() { finishWithCompletion(nil) } /** Class function to hide the splash view with completion handler. This function hide the splash view and call the completion block afterward. Should be called in the right time after the app is ready. :param: completion The completion block */ class func finishWithCompletion(completion: (() -> Void)?) { if !isVisible() { return } if (completion != nil) { sharedInstance.completionBlock = completion } sharedInstance.vibrateAgain = false; } /** Class function obtains the splashView visibility state. This function will tell you if the splashView is visible or not. :returns: Bool Tells us if is the splashView visible. */ class func isVisible() -> Bool { return (sharedInstance.alpha != 0.0) } // MARK: Private functions @objc private func addToWindow() { UIApplication.sharedApplication().keyWindow?.addSubview(JTSplashView.sharedInstance) } private func finalAnimation() { zoomOut() } private func createMaskCircleLayer() -> CAShapeLayer { var circleLayer = CAShapeLayer() var maskPath = CGPathCreateMutable() CGPathAddPath(maskPath, nil, circlePathShrinked.CGPath) CGPathAddRect(maskPath, nil, CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) circleLayer.path = maskPath circleLayer.fillRule = kCAFillRuleEvenOdd circleLayer.fillColor = circleColor.CGColor return circleLayer } private func createBaseCircle() { baseCircleLayer.path = circlePathInitial.CGPath baseCircleLayer.fillRule = kCAFillRuleEvenOdd baseCircleLayer.fillColor = UIColor.clearColor().CGColor baseCircleLayer.strokeColor = circleColor.CGColor baseCircleLayer.lineWidth = borderWidth enlarge() NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: Selector("vibration"), userInfo: nil, repeats: false) layer.addSublayer(baseCircleLayer) } private func createBackgroundWithMask(mask: CAShapeLayer?) -> UIView { var backgroundView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) backgroundView.backgroundColor = bgColor backgroundView.userInteractionEnabled = false if (mask != nil) { backgroundView.layer.mask = createMaskCircleLayer() } return backgroundView } // Animations @objc private func zoomIn() { UIView.animateWithDuration(NSTimeInterval(self.duration * 0.5), delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in // The rest of the transformation will not be visible due completion block alpha = 0 part. But it will look like it just continued faster var cornerCorrection : CGFloat = 1.25 var multiplier = (JTSplashView.screenSize.height / self.borderWidth) * cornerCorrection self.bgWithMask.transform = CGAffineTransformMakeScale(multiplier, multiplier) self.bgWithMask.center = CGPointMake(JTSplashView.screenSize.width / 2, JTSplashView.screenSize.height / 2) }) { (Bool) -> Void in // Run optional block if exists if (self.completionBlock != nil) { self.completionBlock!() } self.alpha = 0.0 self.bgWithMask.transform = CGAffineTransformMakeScale(1.0, 1.0) self.bgWithMask.center = CGPointMake(JTSplashView.screenSize.width / 2, JTSplashView.screenSize.height / 2) } } private func zoomOut() { // Shrink var shrinkAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path") shrinkAnimation.fromValue = circlePathFinal.CGPath shrinkAnimation.toValue = circlePathShrinked.CGPath shrinkAnimation.duration = duration; shrinkAnimation.fillMode = kCAFillModeForwards shrinkAnimation.removedOnCompletion = false shrinkAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) baseCircleLayer.addAnimation(shrinkAnimation, forKey: nil) NSTimer.scheduledTimerWithTimeInterval(shrinkAnimation.duration, target: self, selector: Selector("fadeOut"), userInfo: nil, repeats: false) NSTimer.scheduledTimerWithTimeInterval(shrinkAnimation.duration, target: self, selector: Selector("zoomIn"), userInfo: nil, repeats: false) } private func enlarge() { var enlargeAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path") enlargeAnimation.fromValue = circlePathInitial.CGPath enlargeAnimation.toValue = circlePathFinal.CGPath enlargeAnimation.duration = duration; enlargeAnimation.fillMode = kCAFillModeForwards enlargeAnimation.removedOnCompletion = false baseCircleLayer.addAnimation(enlargeAnimation, forKey: nil) } @objc private func vibration() { var vibration1: CABasicAnimation = CABasicAnimation(keyPath: "path") vibration1.fromValue = circlePathFinal.CGPath vibration1.toValue = circlePathSqueezeVertical.CGPath vibration1.beginTime = 0.0 vibration1.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) vibration1.duration = duration var vibration2: CABasicAnimation = CABasicAnimation(keyPath: "path") vibration2.fromValue = circlePathSqueezeVertical.CGPath vibration2.toValue = circlePathSqueezeHorizontal.CGPath vibration2.beginTime = duration vibration2.duration = duration vibration2.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) var vibration3: CABasicAnimation = CABasicAnimation(keyPath: "path") vibration3.fromValue = circlePathSqueezeHorizontal.CGPath vibration3.toValue = circlePathSqueezeVertical.CGPath vibration3.beginTime = duration * 2 vibration3.duration = duration vibration3.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) var vibration4: CABasicAnimation = CABasicAnimation(keyPath: "path") vibration4.fromValue = circlePathSqueezeVertical.CGPath vibration4.toValue = circlePathFinal.CGPath vibration4.beginTime = duration * 3 vibration4.duration = duration vibration4.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) var vibrations: CAAnimationGroup = CAAnimationGroup() vibrations.animations = [vibration1, vibration2, vibration3, vibration4] vibrations.duration = duration * 4 vibrations.repeatCount = 1 baseCircleLayer.addAnimation(vibrations, forKey: nil) // Vibrate one more time or trigger final animation if vibrateAgain { NSTimer.scheduledTimerWithTimeInterval(duration * 4, target: self, selector: Selector("vibration"), userInfo: nil, repeats: false) } else { finalAnimation() } } @objc private func fadeOut() { self.bgWithoutMask.alpha = 0.0 self.baseCircleLayer.opacity = 0.0 } }
4b089cb4c284a284eb7799b8ce361b5b
43.307692
333
0.668061
false
false
false
false
apple/swift-tools-support-core
refs/heads/main
Sources/TSCUtility/Platform.swift
apache-2.0
1
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import TSCBasic import Foundation /// Recognized Platform types. public enum Platform: Equatable { case android case darwin case linux(LinuxFlavor) case windows /// Recognized flavors of linux. public enum LinuxFlavor: Equatable { case debian case fedora } /// Lazily checked current platform. public static var currentPlatform = Platform.findCurrentPlatform(localFileSystem) /// Returns the cache directories used in Darwin. private static var darwinCacheDirectoriesLock = NSLock() private static var _darwinCacheDirectories: [AbsolutePath]? = .none /// Attempt to match `uname` with recognized platforms. internal static func findCurrentPlatform(_ fileSystem: FileSystem) -> Platform? { #if os(Windows) return .windows #else guard let uname = try? Process.checkNonZeroExit(args: "uname").spm_chomp().lowercased() else { return nil } switch uname { case "darwin": return .darwin case "linux": return Platform.findCurrentPlatformLinux(fileSystem) default: return nil } #endif } internal static func findCurrentPlatformLinux(_ fileSystem: FileSystem) -> Platform? { do { if try fileSystem.isFile(AbsolutePath(validating: "/etc/debian_version")) { return .linux(.debian) } if try fileSystem.isFile(AbsolutePath(validating: "/system/bin/toolbox")) || fileSystem.isFile(AbsolutePath(validating: "/system/bin/toybox")) { return .android } if try fileSystem.isFile(AbsolutePath(validating: "/etc/redhat-release")) || fileSystem.isFile(AbsolutePath(validating: "/etc/centos-release")) || fileSystem.isFile(AbsolutePath(validating: "/etc/fedora-release")) || Platform.isAmazonLinux2(fileSystem) { return .linux(.fedora) } } catch {} return nil } private static func isAmazonLinux2(_ fileSystem: FileSystem) -> Bool { do { let release = try fileSystem.readFileContents(AbsolutePath(validating: "/etc/system-release")).cString return release.hasPrefix("Amazon Linux release 2") } catch { return false } } /// Returns the cache directories used in Darwin. public static func darwinCacheDirectories() throws -> [AbsolutePath] { try Self.darwinCacheDirectoriesLock.withLock { if let darwinCacheDirectories = Self._darwinCacheDirectories { return darwinCacheDirectories } var directories = [AbsolutePath]() // Compute the directories. try directories.append(AbsolutePath(validating: "/private/var/tmp")) (try? TSCBasic.determineTempDirectory()).map{ directories.append($0) } #if canImport(Darwin) getConfstr(_CS_DARWIN_USER_TEMP_DIR).map({ directories.append($0) }) getConfstr(_CS_DARWIN_USER_CACHE_DIR).map({ directories.append($0) }) #endif Self._darwinCacheDirectories = directories return directories } } #if canImport(Darwin) /// Returns the value of given path variable using `getconf` utility. /// /// - Note: This method returns `nil` if the value is an invalid path. private static func getConfstr(_ name: Int32) -> AbsolutePath? { let len = confstr(name, nil, 0) let tmp = UnsafeMutableBufferPointer(start: UnsafeMutablePointer<Int8>.allocate(capacity: len), count:len) defer { tmp.deallocate() } guard confstr(name, tmp.baseAddress, len) == len else { return nil } let value = String(cString: tmp.baseAddress!) guard value.hasSuffix(AbsolutePath.root.pathString) else { return nil } return try? resolveSymlinks(AbsolutePath(validating: value)) } #endif }
5699103acc8aa2aa137e0f29c38d212b
37.087719
115
0.637494
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/WordPressTest/BlogTests.swift
gpl-2.0
1
import CoreData import XCTest @testable import WordPress final class BlogTests: XCTestCase { private var context: NSManagedObjectContext! override func setUp() { super.setUp() context = TestContextManager().mainContext } override func tearDown() { super.tearDown() } // MARK: - Atomic Tests func testIsAtomic() { let blog = BlogBuilder(context) .with(atomic: true) .build() XCTAssertTrue(blog.isAtomic()) } func testIsNotAtomic() { let blog = BlogBuilder(context) .with(atomic: false) .build() XCTAssertFalse(blog.isAtomic()) } // MARK: - Blog Lookup func testThatLookupByBlogIDWorks() throws { let blog = BlogBuilder(context).build() XCTAssertNotNil(blog.dotComID) XCTAssertNotNil(Blog.lookup(withID: blog.dotComID!, in: context)) } func testThatLookupByBlogIDFailsForInvalidBlogID() throws { XCTAssertNil(Blog.lookup(withID: NSNumber(integerLiteral: 1), in: context)) } func testThatLookupByBlogIDWorksForIntegerBlogID() throws { let blog = BlogBuilder(context).build() XCTAssertNotNil(blog.dotComID) XCTAssertNotNil(try Blog.lookup(withID: blog.dotComID!.intValue, in: context)) } func testThatLookupByBlogIDFailsForInvalidIntegerBlogID() throws { XCTAssertNil(try Blog.lookup(withID: 1, in: context)) } func testThatLookupBlogIDWorksForInt64BlogID() throws { let blog = BlogBuilder(context).build() XCTAssertNotNil(blog.dotComID) XCTAssertNotNil(try Blog.lookup(withID: blog.dotComID!.int64Value, in: context)) } func testThatLookupByBlogIDFailsForInvalidInt64BlogID() throws { XCTAssertNil(try Blog.lookup(withID: Int64(1), in: context)) } // MARK: - Plugin Management func testThatPluginManagementIsDisabledForSimpleSites() { let blog = BlogBuilder(context) .with(atomic: true) .build() XCTAssertFalse(blog.supports(.pluginManagement)) } func testThatPluginManagementIsEnabledForBusinessPlans() { let blog = BlogBuilder(context) .with(isHostedAtWPCom: true) .with(planID: 1008) // Business plan .with(isAdmin: true) .build() XCTAssertTrue(blog.supports(.pluginManagement)) } func testThatPluginManagementIsDisabledForPrivateSites() { let blog = BlogBuilder(context) .with(isHostedAtWPCom: true) .with(planID: 1008) // Business plan .with(isAdmin: true) .with(siteVisibility: .private) .build() XCTAssertTrue(blog.supports(.pluginManagement)) } func testThatPluginManagementIsEnabledForJetpack() { let blog = BlogBuilder(context) .withAnAccount() .withJetpack(version: "5.6", username: "test_user", email: "[email protected]") .with(isHostedAtWPCom: false) .with(isAdmin: true) .build() XCTAssertTrue(blog.supports(.pluginManagement)) } func testThatPluginManagementIsDisabledForWordPress54AndBelow() { let blog = BlogBuilder(context) .with(wordPressVersion: "5.4") .with(username: "test_username") .with(password: "test_password") .with(isAdmin: true) .build() XCTAssertFalse(blog.supports(.pluginManagement)) } func testThatPluginManagementIsEnabledForWordPress55AndAbove() { let blog = BlogBuilder(context) .with(wordPressVersion: "5.5") .with(username: "test_username") .with(password: "test_password") .with(isAdmin: true) .build() XCTAssertTrue(blog.supports(.pluginManagement)) } func testThatPluginManagementIsDisabledForNonAdmins() { let blog = BlogBuilder(context) .with(wordPressVersion: "5.5") .with(username: "test_username") .with(password: "test_password") .with(isAdmin: false) .build() XCTAssertFalse(blog.supports(.pluginManagement)) } func testStatsActiveForSitesHostedAtWPCom() { let blog = BlogBuilder(context) .isHostedAtWPcom() .with(modules: [""]) .build() XCTAssertTrue(blog.isStatsActive()) } func testStatsActiveForSitesNotHotedAtWPCom() { let blog = BlogBuilder(context) .isNotHostedAtWPcom() .with(modules: ["stats"]) .build() XCTAssertTrue(blog.isStatsActive()) } func testStatsNotActiveForSitesNotHotedAtWPCom() { let blog = BlogBuilder(context) .isNotHostedAtWPcom() .with(modules: [""]) .build() XCTAssertFalse(blog.isStatsActive()) } // MARK: - Blog.version string conversion testing func testTheVersionIsAStringWhenGivenANumber() { let blog = BlogBuilder(context) .set(blogOption: "software_version", value: 13.37) .build() XCTAssertTrue((blog.version as Any) is String) XCTAssertEqual(blog.version, "13.37") } func testTheVersionIsAStringWhenGivenAString() { let blog = BlogBuilder(context) .set(blogOption: "software_version", value: "5.5") .build() XCTAssertTrue((blog.version as Any) is String) XCTAssertEqual(blog.version, "5.5") } func testTheVersionDefaultsToAnEmptyStringWhenTheValueIsNotConvertible() { let blog = BlogBuilder(context) .set(blogOption: "software_version", value: NSObject()) .build() XCTAssertTrue((blog.version as Any) is String) XCTAssertEqual(blog.version, "") } }
36b914203789c07ebbf8b5b16348aef3
29.05641
90
0.620031
false
true
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Delay/Simple Delay/AKDelayPresets.swift
mit
2
// // AKDelayPresets.swift // AudioKit // // Created by Nicholas Arner, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation /// Preset for the AKDelay public extension AKDelay { /// Short Delay public func presetShortDelay() { time = 0.125 feedback = 0.204 lowPassCutoff = 5077.644 dryWetMix = 0.100 } /// Long, dense delay public func presetDenseLongDelay() { time = 0.795 feedback = 0.900 lowPassCutoff = 5453.823 dryWetMix = 0.924 } /// Electrical Circuits, Robotic Delay Effect public func presetElectricCircuitsDelay() { time = 0.025 feedback = 0.797 lowPassCutoff = 13960.832 dryWetMix = 0.747 } /// Print out current values in case you want to save it as a preset public func printCurrentValuesAsPreset() { print("public func presetSomeNewDelay() {") print(" time = \(String(format: "%0.3f", time))") print(" feedback = \(String(format: "%0.3f", feedback))") print(" lowPassCutoff = \(String(format: "%0.3f", lowPassCutoff))") print(" dryWetMix = \(String(format: "%0.3f", dryWetMix))") print("}\n") } }
912431999375c3307e81a7b892065683
25.895833
78
0.584496
false
false
false
false
USAssignmentWarehouse/EnglishNow
refs/heads/master
EnglishNow/Controller/Auth/SignUpVC.swift
apache-2.0
1
// // SignUpVC.swift // EnglishNow // // Created by Nha T.Tran on 5/20/17. // Copyright © 2017 IceTeaViet. All rights reserved. // import UIKit import Firebase import FirebaseDatabase class SignUpVC: UIViewController { // MARK: -declare @IBAction func btnDismiss(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBOutlet weak var registerView: UIView! @IBOutlet weak var txtEmail: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var txtConfirmPassword: UITextField! @IBOutlet var txtUsername: UITextField! @IBOutlet var txtError: UILabel! @IBOutlet var btnSignUp: UIButton! @IBAction func btnSignUp(_ sender: Any) { ProgressHUD.show(view: view) if txtPassword.text != txtConfirmPassword.text{ txtError.text = WSString.passwordNotMatch ProgressHUD.hide(view: self.view) } else{ if let email = txtEmail.text, let password = txtPassword.text { FirebaseClient.shared.signUp(email: email, password: password, userName: txtUsername.text!, skills: skills, completion: {(user, error) in if let firebaseError = error{ MessageBox.warning(body: firebaseError.localizedDescription) ProgressHUD.hide(view: self.view) return } if let user = user { ProgressHUD.hide(view: self.view) MessageBox.show(body: "Sign Up successfully!") self.dismiss(animated: true, completion: nil) } }) } else { self.txtError.text = WSString.invalidEmailPassword ProgressHUD.hide(view: self.view) } } } var skills: [Skill] = [Skill]() override func viewDidLoad() { super.viewDidLoad() skills.append(Listening()) skills.append(Speaking()) skills.append(Pronunciation()) initShow() // Do any additional setup after loading the view. } // MARK: -init to show func initShow(){ registerView.layer.cornerRadius = 5 txtEmail.layer.cornerRadius = 5 txtEmail.layer.borderWidth = 1 txtEmail.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor txtPassword.layer.cornerRadius = 5 txtPassword.layer.borderWidth = 1 txtPassword.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor txtPassword.isSecureTextEntry = true txtUsername.layer.cornerRadius = 5 txtUsername.layer.borderWidth = 1 txtUsername.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor txtConfirmPassword.layer.cornerRadius = 5 txtConfirmPassword.layer.borderWidth = 1 txtConfirmPassword.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor txtConfirmPassword.isSecureTextEntry = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //disappear keyboard when click on anywhere in screen override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } }
b2680cdae7f83b524a526c4434a9234c
30.535088
153
0.600556
false
false
false
false
xmartlabs/XLMediaZoom
refs/heads/master
Sources/MediaZoom.swift
mit
1
// // MediaZoom.swift // MediaZoom (https://github.com/xmartlabs/XLMediaZoom) // // Copyright (c) 2017 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 public class MediaZoom: UIView, UIScrollViewDelegate { public lazy var imageView: UIImageView = { let image = UIImageView(frame: self.mediaFrame()) image.clipsToBounds = true image.autoresizingMask = [.flexibleWidth, .flexibleHeight] image.contentMode = .scaleAspectFill return image }() public var maxAlpha: CGFloat = 1 public var hideHandler: (() -> ())? public var useBlurEffect = false public var animationTime: Double public var originalImageView: UIImageView public var backgroundView: UIView public lazy var contentView: UIScrollView = { let contentView = UIScrollView(frame: MediaZoom.currentFrame()) contentView.contentSize = self.mediaFrame().size contentView.backgroundColor = .clear contentView.maximumZoomScale = 1.5 return contentView }() public init(with image: UIImageView, animationTime: Double, useBlur: Bool = false) { let frame = MediaZoom.currentFrame() self.animationTime = animationTime useBlurEffect = useBlur originalImageView = image backgroundView = MediaZoom.backgroundView(with: frame, useBlur: useBlur) super.init(frame: frame) NotificationCenter.default.addObserver( self, selector: #selector(deviceOrientationDidChange(notification:)), name: .UIDeviceOrientationDidChange, object: nil ) imageView.image = image.image addGestureRecognizer( UITapGestureRecognizer( target: self, action: #selector(handleSingleTap(sender:)) ) ) contentView.addSubview(imageView) contentView.delegate = self addSubview(backgroundView) addSubview(contentView) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func show(onHide callback: (() -> ())? = nil) { let frame = MediaZoom.currentFrame() self.frame = frame backgroundView.frame = frame imageView.frame = mediaFrame() hideHandler = callback UIView.animate( withDuration: animationTime, animations: { [weak self] in guard let `self` = self else { return } self.imageView.frame = self.imageFrame() self.backgroundView.alpha = self.maxAlpha }, completion: { [weak self] finished in if finished { self?.showAnimationDidFinish() } } ) } private static func backgroundView(with frame: CGRect, useBlur: Bool) -> UIView { if useBlur { let blurView = UIVisualEffectView(frame: frame) blurView.effect = UIBlurEffect(style: .dark) blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] blurView.alpha = 0 return blurView } else { let bgView = UIView(frame: frame) bgView.backgroundColor = .black bgView.alpha = 0 return bgView } } private static func currentFrame() -> CGRect { let screenSize = UIScreen.main.bounds return CGRect( x: CGFloat(0), y: CGFloat(0), width: screenSize.width, height: screenSize.height ) } private func imageFrame() -> CGRect { let size = bounds guard let imageSize = imageView.image?.size else { return CGRect.zero } let ratio = min(size.height / imageSize.height, size.width / imageSize.width) let imageWidth = imageSize.width * ratio let imageHeight = imageSize.height * ratio let imageX = (frame.size.width - imageWidth) * 0.5 let imageY = (frame.size.height - imageHeight) * 0.5 return CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight) } private func mediaFrame() -> CGRect { return originalImageView.frame } func deviceOrientationDidChange(notification: NSNotification) { let orientation = UIDevice.current.orientation switch orientation { case .landscapeLeft, .landscapeRight, .portrait: let newFrame = MediaZoom.currentFrame() frame = newFrame backgroundView.frame = newFrame imageView.frame = imageFrame() default: break } } public func handleSingleTap(sender: UITapGestureRecognizer) { willHandleSingleTap() UIView.animate( withDuration: animationTime, animations: { [weak self] in guard let `self` = self else { return } self.contentView.zoomScale = 1 self.imageView.frame = self.mediaFrame() self.backgroundView.alpha = 0 }, completion: { [weak self] finished in if finished { self?.removeFromSuperview() self?.contentView.zoomScale = 1 self?.hideHandler?() } } ) } public func viewForZooming(in scrollView: UIScrollView) -> UIView? { let yOffset = (scrollView.frame.height - imageView.frame.height) / 2.0 let xOffset = (scrollView.frame.width - imageView.frame.width) / 2.0 let x = xOffset > 0 ? xOffset : scrollView.frame.origin.x let y = yOffset > 0 ? yOffset : scrollView.frame.origin.y UIView.animate(withDuration: 0.3) { [weak self] in self?.imageView.frame.origin = CGPoint(x: x, y: y) } return imageView } open func willHandleSingleTap() { } open func showAnimationDidFinish() { } deinit { NotificationCenter.default.removeObserver(self) } }
caf18462c42b7896622a7a425c43d1a3
34.77
88
0.619793
false
false
false
false
VoIPGRID/VialerSIPLib
refs/heads/develop
Example/VialerSIPLib/VSLMainViewController.swift
gpl-3.0
1
// // VSLMainViewController.swift // Copyright © 2016 Devhouse Spindle. All rights reserved. // import UIKit private var myContext = 0 class VSLMainViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { // MARK: - Configuration fileprivate struct Configuration { struct Segues { static let ShowIncomingCall = "ShowIncomingCallSegue" static let DirectlyShowActiveCallControllerSegue = "DirectlyShowActiveCallControllerSegue" } } // MARK: - Properties fileprivate var account: VSLAccount { get { return AppDelegate.shared.getAccount() } } fileprivate var activeCall: VSLCall? fileprivate var transportPickerData: [String] = [String]() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() transportPickerData = ["UDP", "TCP", "TLS"] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(incomingCallNotification(_:)), name: AppDelegate.Configuration.Notifications.incomingCall, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(directlyShowActiveCallController(_:)), name: Notification.Name.CallKitProviderDelegateOutboundCallStarted, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(directlyShowActiveCallController(_:)), name: Notification.Name.CallKitProviderDelegateInboundCallAccepted, object: nil) account.addObserver(self, forKeyPath: #keyPath(VSLAccount.accountState), options: .new, context: &myContext) updateUI() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) account.removeObserver(self, forKeyPath: #keyPath(VSLAccount.accountState)) NotificationCenter.default.removeObserver(self, name:AppDelegate.Configuration.Notifications.incomingCall, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.CallKitProviderDelegateOutboundCallStarted, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.CallKitProviderDelegateInboundCallAccepted, object: nil) } // MARK: - Outlets @IBOutlet weak var registerAccountButton: UIButton! @IBOutlet weak var transportPicker: UIPickerView! @IBOutlet weak var useVideoSwitch: UISwitch! @IBOutlet weak var unregisterAfterCallSwitch: UISwitch! // MARK: - Actions @IBAction func useVideoSwichPressed(_ sender: UISwitch) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let prefs = UserDefaults.standard prefs.set(sender.isOn, forKey: "useVideo") account.removeObserver(self, forKeyPath: #keyPath(VSLAccount.accountState)) appDelegate.stopVoIPEndPoint(); appDelegate.setupVoIPEndpoint() appDelegate.setupAccount() account.addObserver(self, forKeyPath: #keyPath(VSLAccount.accountState), options: .new, context: &myContext) } @IBAction func unregisterAfterCallPressed(_ sender: UISwitch) { DispatchQueue.main.async { [weak self] in guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let prefs = UserDefaults.standard prefs.set(sender.isOn, forKey: "unregisterAfterCall") self!.account.removeObserver(self!, forKeyPath: #keyPath(VSLAccount.accountState)) appDelegate.stopVoIPEndPoint(); appDelegate.setupVoIPEndpoint() appDelegate.setupAccount() self!.account.addObserver(self!, forKeyPath: #keyPath(VSLAccount.accountState), options: .new, context: &myContext) } } @IBAction func registerAccountButtonPressed(_ sender: UIButton) { if account.isRegistered { try! account.unregisterAccount() } else { registerAccount() } } // MARK: - TransportType Picker func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return transportPickerData.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return transportPickerData[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let prefs = UserDefaults.standard prefs.set(transportPickerData[row], forKey: "transportType") account.removeObserver(self, forKeyPath: #keyPath(VSLAccount.accountState)) VialerSIPLib.sharedInstance().removeEndpoint() guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } appDelegate.stopVoIPEndPoint(); appDelegate.setupVoIPEndpoint() appDelegate.setupAccount() account.addObserver(self, forKeyPath: #keyPath(VSLAccount.accountState), options: .new, context: &myContext) } // MARK: - Helper functions fileprivate func updateUI() { DispatchQueue.main.async { self.registerAccountButton.setTitle(self.account.isRegistered ? "Unregister" : "Register", for: UIControlState()) } let prefs = UserDefaults.standard let useVideo = prefs.bool(forKey: "useVideo") DispatchQueue.main.async { self.useVideoSwitch.setOn(useVideo, animated: true) } let unregisterAfterCall = prefs.bool(forKey: "unregisterAfterCall") DispatchQueue.main.async { self.unregisterAfterCallSwitch.setOn(unregisterAfterCall, animated: true) } let transportType = prefs.string(forKey: "transportType") if transportType != nil, let defaultRowIndex = transportPickerData.index(of: transportType!) { DispatchQueue.main.async { [weak self] in self?.transportPicker.selectRow(defaultRowIndex, inComponent: 0, animated: true) } } } fileprivate func registerAccount() { registerAccountButton.isEnabled = false account.register{ (success, error) in DispatchQueue.main.async { self.registerAccountButton.isEnabled = true if (error != nil) { let alert = UIAlertController(title: NSLocalizedString("Account registration failed", comment: ""), message: error?.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil)) self.present(alert, animated: true) } } } } // MARK: - Segues @IBAction func unwindToMainViewController(_ segue: UIStoryboardSegue) {} override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let callViewController = segue.destination as? VSLCallViewController { callViewController.activeCall = activeCall } else if let makeCallVC = segue.destination as? VSLMakeCallViewController { makeCallVC.account = account } else if let call = activeCall, let incomingCallVC = segue.destination as? VSLIncomingCallViewController { incomingCallVC.call = call } } // MARK: - KVO override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let account = object as? VSLAccount, account == self.account { updateUI() } } // MARK: - NSNotificationCenter @objc func incomingCallNotification(_ notification: Notification) { guard let call = notification.userInfo?[VSLNotificationUserInfoCallKey] as? VSLCall else { return } // When there is another call active, decline incoming call. if call != account.firstActiveCall() { try! call.hangup() return } // Show incoming call view. activeCall = call DispatchQueue.main.async { self.performSegue(withIdentifier: Configuration.Segues.ShowIncomingCall, sender: nil) } } // When an outbound call is requested trough CallKit, show the VSLCallViewController directly. @objc func directlyShowActiveCallController(_ notification: Notification) { guard let call = notification.userInfo?[VSLNotificationUserInfoCallKey] as? VSLCall else { return } activeCall = call DispatchQueue.main.async { self.performSegue(withIdentifier: Configuration.Segues.DirectlyShowActiveCallControllerSegue, sender: nil) } } }
283a9a143ae03fe3b7fd034ea11ddbd9
39.59322
181
0.631211
false
false
false
false
renzifeng/ZFZhiHuDaily
refs/heads/master
ZFZhiHuDaily/NewsComments/Model/ZFComments.swift
apache-2.0
1
// // ZFComments.swift // // Created by 任子丰 on 16/1/30 // Copyright (c) 任子丰. All rights reserved. // import Foundation import SwiftyJSON public class ZFComments: NSObject { // MARK: Declaration for string constants to be used to decode and also serialize. internal let kZFCommentsAuthorKey: String = "author" internal let kZFCommentsContentKey: String = "content" internal let kZFCommentsInternalIdentifierKey: String = "id" internal let kZFCommentsAvatarKey: String = "avatar" internal let kZFCommentsLikesKey: String = "likes" internal let kZFCommentsTimeKey: String = "time" // MARK: Properties public var author: String? public var content: String? public var internalIdentifier: Int? public var avatar: String? public var likes: Int? public var time: Int? // MARK: SwiftyJSON Initalizers /** Initates the class based on the object - parameter object: The object of either Dictionary or Array kind that was passed. - returns: An initalized instance of the class. */ convenience public init(object: AnyObject) { self.init(json: JSON(object)) } /** Initates the class based on the JSON that was passed. - parameter json: JSON object from SwiftyJSON. - returns: An initalized instance of the class. */ public init(json: JSON) { author = json[kZFCommentsAuthorKey].string content = json[kZFCommentsContentKey].string internalIdentifier = json[kZFCommentsInternalIdentifierKey].int avatar = json[kZFCommentsAvatarKey].string likes = json[kZFCommentsLikesKey].int time = json[kZFCommentsTimeKey].int } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ public func dictionaryRepresentation() -> [String : AnyObject ] { var dictionary: [String : AnyObject ] = [ : ] if author != nil { dictionary.updateValue(author!, forKey: kZFCommentsAuthorKey) } if content != nil { dictionary.updateValue(content!, forKey: kZFCommentsContentKey) } if internalIdentifier != nil { dictionary.updateValue(internalIdentifier!, forKey: kZFCommentsInternalIdentifierKey) } if avatar != nil { dictionary.updateValue(avatar!, forKey: kZFCommentsAvatarKey) } if likes != nil { dictionary.updateValue(likes!, forKey: kZFCommentsLikesKey) } if time != nil { dictionary.updateValue(time!, forKey: kZFCommentsTimeKey) } return dictionary } }
7135497116a160925ca7c1d19e815fee
28.139535
88
0.714286
false
false
false
false
Frainbow/ShaRead.frb-swift
refs/heads/master
ShaRead/ShaRead/AppDelegate.swift
mit
1
// // AppDelegate.swift // ShaRead // // Created by martin on 2016/4/13. // Copyright © 2016年 Frainbow. All rights reserved. // import UIKit import CoreData import Firebase import FBSDKCoreKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.fbTokenChangeNoti(_:)), name: FBSDKAccessTokenDidChangeNotification, object: nil) FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) FIRApp.configure() return true } func fbTokenChangeNoti(noti: NSNotification) { } func toggleUserMode() { toggleRootView("Main", controllerIdentifier: "MainController") } func toggleAdminMode() { toggleRootView("StoreAdmin", controllerIdentifier: "StoreAdminMainController") } func toggleRootView(storyboardName: String, controllerIdentifier: String) { let storyboard = UIStoryboard(name: storyboardName, bundle: nil) let rootController = storyboard.instantiateViewControllerWithIdentifier(controllerIdentifier) self.window!.rootViewController = rootController } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. FBSDKAppEvents.activateApp() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "tw.frb.ShaRead" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("ShaRead", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
f391fa58a8c6e379852a914205c02188
50.811189
291
0.722905
false
false
false
false
FredericJacobs/AsyncMessagesViewController
refs/heads/master
Source/Views/MessageCellNode.swift
mit
1
// // MessageCellNode.swift // AsyncMessagesViewController // // Created by Huy Nguyen on 12/02/15. // Copyright (c) 2015 Huy Nguyen. All rights reserved. // import Foundation let kAMMessageCellNodeTopTextAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.boldSystemFontOfSize(12)] let kAMMessageCellNodeContentTopTextAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)] let kAMMessageCellNodeBottomTextAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(11)] private let kContentHorizontalInset: CGFloat = 4 private let kContentVerticalInset: CGFloat = 1 class MessageCellNode: ASCellNode { private let isOutgoing: Bool private let topTextNode: ASTextNode? private let contentTopTextNode: ASTextNode? private let bottomTextNode: ASTextNode? private let contentNode: MessageContentNode private var contentTopTextNodeXOffset: CGFloat { return contentNode.avatarImageSize > 0 ? 56 : 11 } init(isOutgoing: Bool, topText: NSAttributedString?, contentTopText: NSAttributedString?, bottomText: NSAttributedString?, senderAvatarURL: NSURL?, senderAvatarImageSize: CGFloat, bubbleNode: ASDisplayNode) { self.isOutgoing = isOutgoing topTextNode = topText != nil ? ASTextNode() : nil topTextNode?.layerBacked = true topTextNode?.attributedString = topText contentTopTextNode = contentTopText != nil ? ASTextNode() : nil contentTopTextNode?.layerBacked = true contentTopTextNode?.attributedString = contentTopText contentNode = MessageContentNode(isOutgoing: isOutgoing, avatarURL: senderAvatarURL, avatarImageSize: senderAvatarImageSize, bubbleNode: bubbleNode) bottomTextNode = bottomText != nil ? ASTextNode() : nil bottomTextNode?.layerBacked = true bottomTextNode?.attributedString = bottomText super.init() if let node = topTextNode { addSubnode(node) } if let node = contentTopTextNode { addSubnode(node) } addSubnode(contentNode) if let node = bottomTextNode { addSubnode(node) } selectionStyle = .None } override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize { let pairs: [(ASDisplayNode?, CGFloat)] = [(topTextNode, 0), (contentTopTextNode, contentTopTextNodeXOffset), (contentNode, 0), (bottomTextNode, 0)] var requiredHeight: CGFloat = 0 for (optionalNode, xOffset) in pairs { if let node = optionalNode { let measuredSize = node.measure(CGSizeMake(constrainedSize.width - xOffset - 2 * kContentHorizontalInset, constrainedSize.height)) requiredHeight += measuredSize.height } } return CGSizeMake(constrainedSize.width, requiredHeight + 2 * kContentVerticalInset) } override func layout() { let topTextNodeXOffset = (self.calculatedSize.width - (topTextNode?.calculatedSize.width ?? 0)) / 2 - kContentHorizontalInset // topTextNode is center-aligned let pairs: [(ASDisplayNode?, CGFloat)] = [(topTextNode, topTextNodeXOffset), (contentTopTextNode, contentTopTextNodeXOffset), (contentNode, 0), (bottomTextNode, 0)] var y: CGFloat = kContentVerticalInset for (optionalNode, xOffset) in pairs { if let node = optionalNode { var x = kContentHorizontalInset + xOffset if isOutgoing { x = self.calculatedSize.width - node.calculatedSize.width - x // Right-aligned } node.frame = CGRectMake(x, y, node.calculatedSize.width, node.calculatedSize.height) y = node.frame.maxY } } } }
4d3cdef00f3c69513549b58d828f5d90
42.94382
212
0.693095
false
false
false
false
csound/csound
refs/heads/develop
iOS/Csound iOS Swift Examples/Csound iOS SwiftExamples/HarmonizerTestViewController.swift
lgpl-2.1
3
/* HarmonizerTestViewController.swift Nikhil Singh, Dr. Richard Boulanger Adapted from the Csound iOS Examples by Steven Yi and Victor Lazzarini This file is part of Csound iOS SwiftExamples. The Csound for iOS Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import UIKit class HarmonizerTestViewController: BaseCsoundViewController { @IBOutlet var mHarmPitchSlider: UISlider! @IBOutlet var mGainSlider: UISlider! @IBOutlet var mSwitch: UISwitch! override func viewDidLoad() { title = "12. Mic: Harmonizer" super.viewDidLoad() } @IBAction func toggleOnOff(_ sender: UISwitch) { if sender.isOn { let tempFile = Bundle.main.path(forResource: "harmonizer", ofType: "csd") csound.stop() csound = CsoundObj() csound.useAudioInput = true csound.add(self) let csoundUI = CsoundUI(csoundObj: csound) csoundUI?.add(mHarmPitchSlider, forChannelName: "slider") csoundUI?.add(mGainSlider, forChannelName: "gain") csound.play(tempFile) } else { csound.stop() } } @IBAction func showInfo(_ sender: UIButton) { infoVC.preferredContentSize = CGSize(width: 300, height: 120) infoText = "This examples uses Csound's streaming phase vocoder to create a harmonizer effect. A dry/wet balance control is provided." displayInfo(sender) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension HarmonizerTestViewController: CsoundObjListener { func csoundObjCompleted(_ csoundObj: CsoundObj!) { DispatchQueue.main.async { [unowned self] in self.mSwitch.isOn = false } } }
f8d740f1716ec7a9ce259e1dfd9d2572
31.922078
142
0.675345
false
false
false
false
alobanov/Dribbble
refs/heads/master
Dribbble/services/NetworkService.swift
mit
1
// // BaseNetworkService.swift // Dribbble // // Created by Lobanov Aleksey on 17.02.17. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import Foundation import RxSwift struct NetworkError { let type: NetworkReqestType let error: NSError static func unknown() -> NetworkError { return NetworkError(type: .unknown, error: AppError.dummyError.error) } } struct NetworkState { let type: NetworkReqestType let state: LoadingState static func unknown() -> NetworkState { return NetworkState(type: .unknown, state: .unknown) } } protocol NetworkServiceStateble { var networkError: Observable<NetworkError> {get} var commonNetworkState: Observable<NetworkState> {get} } class NetworkService { let bag = DisposeBag() var networkError: Observable<NetworkError> { return _networkError.asObservable().skip(1) } var commonNetworkState: Observable<NetworkState> { return _commonNetworkState.asObservable() } // Dependencies var api: Networking! private var requestInProcess = false internal var _networkError = Variable<NetworkError>(NetworkError.unknown()) internal var _commonNetworkState = Variable<NetworkState>(NetworkState.unknown()) init(api: Networking) { self.api = api } func isRequestInProcess(networkReqestType: NetworkReqestType = .unknown) -> Bool { guard _commonNetworkState.value.state != .loading else { return true } _commonNetworkState.value = NetworkState(type: networkReqestType, state: .loading) return false } func handleResponse<E>(_ response: Observable<E>, networkReqestType: NetworkReqestType) -> Observable<E> { return response.map {[weak self] event -> E in self?._commonNetworkState.value = NetworkState(type: networkReqestType, state: .normal) return event }.do(onError: {[weak self] err in self?.throwError(type: networkReqestType, error: err as NSError) }) } func throwError(type: NetworkReqestType, error: NSError) { self._networkError.value = NetworkError(type: type, error: error) self._commonNetworkState.value = NetworkState(type: type, state: .error) } }
a435b9f6db0ac6967b31fdd025bdb05e
27.526316
108
0.717251
false
false
false
false
Eric217/-OnSale
refs/heads/master
打折啦/打折啦/ESTabBarItem.swift
apache-2.0
1
// // ESTabBarController.swift // // Created by Vincent Li on 2017/2/8. // Copyright (c) 2013-2017 ESTabBarController (https://github.com/eggswift/ESTabBarController) // // 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 /* * ESTabBarItem继承自UITabBarItem,目的是为ESTabBarItemContentView提供UITabBarItem属性的设置。 * 目前支持大多常用的属性,例如image, selectedImage, title, tag 等。 * * Unsupport properties: * MARK: UIBarItem properties * 1. var isEnabled: Bool * 2. var landscapeImagePhone: UIImage? * 3. var imageInsets: UIEdgeInsets * 4. var landscapeImagePhoneInsets: UIEdgeInsets * 5. func setTitleTextAttributes(_ attributes: [String : Any]?, for state: UIControlState) * 6. func titleTextAttributes(for state: UIControlState) -> [String : Any]? * MARK: UITabBarItem properties * 7. var titlePositionAdjustment: UIOffset * 8. func setBadgeTextAttributes(_ textAttributes: [String : Any]?, for state: UIControlState) * 9. func badgeTextAttributes(for state: UIControlState) -> [String : Any]? */ @available(iOS 8.0, *) open class ESTabBarItem: UITabBarItem { /// Customize content view open var contentView: ESTabBarItemContentView? // MARK: UIBarItem properties open override var title: String? // default is nil { didSet { self.contentView?.title = title } } open override var image: UIImage? // default is nil { didSet { self.contentView?.image = image } } // MARK: UITabBarItem properties open override var selectedImage: UIImage? // default is nil { didSet { self.contentView?.selectedImage = selectedImage } } open override var badgeValue: String? // default is nil { get { return contentView?.badgeValue } set(newValue) { contentView?.badgeValue = newValue } } /// Override UITabBarItem.badgeColor, make it available for iOS8.0 and later. /// If this item displays a badge, this color will be used for the badge's background. If set to nil, the default background color will be used instead. @available(iOS 8.0, *) open override var badgeColor: UIColor? { get { return contentView?.badgeColor } set(newValue) { contentView?.badgeColor = newValue } } open override var tag: Int // default is 0 { didSet { self.contentView?.tag = tag } } /* The unselected image is autogenerated from the image argument. The selected image is autogenerated from the selectedImage if provided and the image argument otherwise. To prevent system coloring, provide images with UIImageRenderingModeAlwaysOriginal (see UIImage.h) */ public init(_ contentView: ESTabBarItemContentView = ESTabBarItemContentView(), title: String? = nil, image: UIImage? = nil, selectedImage: UIImage? = nil, tag: Int = 0) { super.init() self.contentView = contentView self.setTitle(title, image: image, selectedImage: selectedImage, tag: tag) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func setTitle(_ title: String? = nil, image: UIImage? = nil, selectedImage: UIImage? = nil, tag: Int = 0) { self.title = title self.image = image self.selectedImage = selectedImage self.tag = tag } }
290cdd403195ae53b21fed843d5ffc2e
40.607477
175
0.688679
false
false
false
false
SimpleApp/evc-swift
refs/heads/master
EVC/EVC/Engine/core/EVCEngine.swift
mit
1
// // EVCEngine.swift // EVC // // Created by Benjamin Garrigues on 04/09/2017. import Foundation class EVCEngine { //MARK: - Context fileprivate (set) var context: EVCEngineContext //MARK: - Capabilities //Replace and add your own capabilities fileprivate let dataStore : FileDataStore fileprivate let restAPI : SampleJSONRestAPI //MARK: - Middlewares //Add your own middleware here //MARK: - Services //Service are the only properties visible from the GUI Layer. //Replace and add your own services let sampleService: SampleService //type of allComponents is array of nullable because a common scenario //is to disable components when using the engine in an extension. fileprivate var allComponents : [EVCEngineComponent?] { return [ //Capabilities dataStore, restAPI, //Middleware //Service sampleService] } //MARK: - Initialization //init may become a big function if your engine has a lot of components. //This function however should have very little logic beyond creating and injecting components init(initialContext : EVCEngineContext, //Mock injection for unit-testing purpose mockedDatastore: FileDataStore? = nil, mockedRestAPI : SampleJSONRestAPI? = nil, mockedService : SampleService? = nil ) { //Capabilities dataStore = try! mockedDatastore ?? FileDataStore() restAPI = try! mockedRestAPI ?? SampleJSONRestAPI(environment: initialContext.environment) //Middlewares //Services if let mockedService = mockedService { sampleService = mockedService } else { sampleService = SampleService(dataStore: dataStore, restAPI: restAPI) } //Context context = initialContext propagateContext() } //MARK: - Internal flow fileprivate func propagateContext() { for o in allComponents { o?.onEngineContextUpdate(context: context) } } //MARK: - Public interface //MARK: Application State //Note : application state may not be available on all platforms (such as extensions) //so we don't directly use UIApplication inside the engine, but let the outside provide us with the information public func onApplicationDidEnterBackground() { context.applicationForeground = false propagateContext() } public func onApplicationDidBecomeActive() { context.applicationForeground = true propagateContext() } }
48e66eacad7c04e614a4528ddb94d5d2
29.079545
115
0.653948
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/Serialization/class.swift
apache-2.0
12
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-object -emit-module -o %t %S/Inputs/def_class.swift -disable-objc-attr-requires-foundation-module // RUN: llvm-bcanalyzer %t/def_class.swiftmodule | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -Xllvm -sil-disable-pass="External Definition To Declaration" -sil-debug-serialization -I %t %s | %FileCheck %s -check-prefix=SIL // RUN: echo "import def_class; struct A : ClassProto {}" | not %target-swift-frontend -typecheck -I %t - 2>&1 | %FileCheck %s -check-prefix=CHECK-STRUCT // CHECK-NOT: UnknownCode // CHECK-STRUCT: non-class type 'A' cannot conform to class protocol 'ClassProto' // Make sure we can "merge" def_class. // RUN: %target-swift-frontend -emit-module -o %t-merged.swiftmodule %t/def_class.swiftmodule -module-name def_class import def_class var a : Empty var b = TwoInts(a: 1, b: 2) var computedProperty : ComputedProperty var sum = b.x + b.y + computedProperty.value var intWrapper = ResettableIntWrapper() var r : Resettable = intWrapper r.reset() r.doReset() class AnotherIntWrapper : SpecialResettable, ClassProto { init() { value = 0 } var value : Int func reset() { value = 0 } func compute() { value = 42 } } var intWrapper2 = AnotherIntWrapper() r = intWrapper2 r.reset() var c : Cacheable = intWrapper2 c.compute() c.reset() var p = Pair(a: 1, b: 2.5) p.first = 2 p.second = 5.0 struct Int {} var gc = GenericCtor<Int>() gc.doSomething() a = StillEmpty() r = StillEmpty() var bp = BoolPair<Bool>() bp.bothTrue() var rawBP : Pair<Bool, Bool> rawBP = bp var rev : SpecialPair<Double> rev.first = 42 var comp : Computable = rev var simpleSub = ReadonlySimpleSubscript() var subVal = simpleSub[4] var complexSub = ComplexSubscript() complexSub[4, false] = complexSub[3, true] var rsrc = Resource() getReqPairLike() // SIL-LABEL: sil public_external [transparent] [serialized] @_T0Si1poiS2i_SitFZ : $@convention(method) (Int, Int, @thin Int.Type) -> Int func test(_ sharer: ResourceSharer) {} class HasNoOptionalReqs : ObjCProtoWithOptional { } HasNoOptionalReqs() OptionalImplementer().unrelated() extension def_class.ComputedProperty { }
e0c9d65383e4ed531d8a9059e593d88b
23.829545
170
0.709382
false
false
false
false
nubbel/Cococapods-Xcode7GenericArchive
refs/heads/master
FluxKit/Dispatcher.swift
mit
2
// // Dispatcher.swift // FluxKit // // Created by Dominique d'Argent on 16/05/15. // Copyright (c) 2015 Dominique d'Argent. All rights reserved. // import Foundation public class Dispatcher<Action : ActionType> { public typealias Token = String public typealias Callback = Action -> Void private var tokenGenerator : TokenStream.Generator private var isDispatching : Bool = false private var pendingAction : Action? private var callbacks : [Token: Callback] = [:] private var dispatchTokens : Set<Token> { return Set(callbacks.keys) } private var pendingDispatchTokens : Set<Token> = [] private var handledDispatchTokens : Set<Token> = [] public init() { tokenGenerator = TokenStream(prefix: "ID_").generate() } public func register(callback: Callback) -> Token { if let token = tokenGenerator.next() { callbacks[token] = callback return token } preconditionFailure("FluxKit.Dispatcher: Failed to generate new dispatch token.") } public func unregister(dispatchToken: Token) { precondition(isRegistered(dispatchToken), "FluxKit.Dispatcher: Unknown dispatch token \(dispatchToken).") callbacks.removeValueForKey(dispatchToken) } public func dispatch(action: Action) { precondition(!isDispatching, "FluxKit.Dispatcher: Cannot dispatch while dispatching.") beginDispatching(action) for dispatchToken in dispatchTokens { if isPending(dispatchToken) { continue } invokeCallback(dispatchToken) } endDispatching() } public func waitFor(dispatchTokens: Token...) { waitFor(dispatchTokens) } public func waitFor(dispatchTokens: [Token]) { for dispatchToken in dispatchTokens { if isPending(dispatchToken) { precondition(isHandled(dispatchToken), "FluxKit.Dispatcher: Circular dependency detected while waiting for \(dispatchToken).") continue } invokeCallback(dispatchToken) } } } private extension Dispatcher { func beginDispatching(action: Action) { isDispatching = true pendingAction = action pendingDispatchTokens = [] handledDispatchTokens = [] } func endDispatching() { isDispatching = false pendingAction = nil } func invokeCallback(dispatchToken: Token) { precondition(isDispatching, "FluxKit.Dispatcher: Not dispatching.") precondition(pendingAction != nil, "FluxKit.Dispatcher: Action missing.") precondition(isRegistered(dispatchToken), "FluxKit.Dispatcher: Unknown dispatch token \(dispatchToken).") if let action = pendingAction, callback = callbacks[dispatchToken] { pendingDispatchTokens.insert(dispatchToken) callback(action) handledDispatchTokens.insert(dispatchToken) } } func isRegistered(dispatchToken: Token) -> Bool { return callbacks[dispatchToken] != nil } func isPending(dispatchToken: Token) -> Bool { return pendingDispatchTokens.contains(dispatchToken) } func isHandled(dispatchToken: Token) -> Bool { return handledDispatchTokens.contains(dispatchToken) } }
c864e70e1c7f275cc0963bebce27d0a4
28.779661
142
0.623791
false
false
false
false
nyalix/shiro-obi-app
refs/heads/master
Todoapp3/EditViewController.swift
mit
1
// // TodoItemViewController.swift // Todoapp // // Created by Katsuya yamamoto on 2015/12/13. // Copyright (c) 2015年 nyalix. All rights reserved. // import UIKit class EditViewController: UIViewController { var task: Todo? = nil @IBOutlet weak var todoField: UITextView! @IBAction func cancel(sender: UIBarButtonItem) { navigationController!.popViewControllerAnimated(true) } @IBAction func save(sender: UIBarButtonItem) { // // let newTask: Todo = Todo.MR_createEntity() as Todo // newTask.item = makeTodo.text // newTask.managedObjectContext!.MR_saveToPersistentStoreAndWait() // //self.dismissViewControllerAnimated(true, completion: nil) // navigationController!.popViewControllerAnimated(true) // } // @IBAction func clickSave(sender: UIBarButtonItem) { if task != nil { editTask() } else { createTask() } navigationController!.popViewControllerAnimated(true) } func createTask() { let newTask: Todo = Todo.MR_createEntity() as Todo newTask.item = todoField.text _ = NSDate() let dateFormatter = NSDateFormatter() // フォーマットの取得 dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") // JPロケール dateFormatter.dateFormat = "yyyy/MM/dd HH:mm" // フォーマットの指定 newTask.date = dateFormatter.stringFromDate(NSDate()) // 現在日時 newTask.managedObjectContext!.MR_saveToPersistentStoreAndWait() } func editTask() { task?.item = todoField.text task?.managedObjectContext!.MR_saveToPersistentStoreAndWait() } override func viewDidLoad() { super.viewDidLoad() if let taskTodo = task { todoField.text = taskTodo.item } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
5c6b217cbe69a135e395e2c1e6b28e4e
30.487805
106
0.605345
false
false
false
false
adauguet/ClusterMapView
refs/heads/master
Example/Example/ViewController.swift
mit
1
// // ViewController.swift // ClusterMapViewDemo // // Created by Antoine DAUGUET on 02/05/2017. // // import UIKit import MapKit import ClusterMapView class ViewController: UIViewController { @IBOutlet weak var mapView: ClusterMapView! override func viewDidLoad() { super.viewDidLoad() // let path = Bundle.main.path(forResource: "Toilets", ofType: "json")! // let url = URL(fileURLWithPath: path) // let data = try! Data(contentsOf: url) // let json = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String : Any]] // let toilets = Toilet.foo(json: json) // mapView.delegate = mapView // mapView.setAnnotations(toilets) let path = Bundle.main.path(forResource: "Streetlights", ofType: "json")! let url = URL(fileURLWithPath: path) let data = try! Data(contentsOf: url) let json = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [[String : Any]] let streetlights = Streetlight.foo(json: json) mapView.delegate = self mapView.setAnnotations(streetlights) } } extension ViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { if let mapView = mapView as? ClusterMapView { mapView.updateNodes(animated: animated) } } func mapViewDidFinishClustering(_ mapView: ClusterMapView) { print(#function) } func mapViewDidFinishAnimating(_ mapView: ClusterMapView) { print(#function) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if let node = annotation as? Node { var pin: MKPinAnnotationView! if let dequeued = mapView.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKPinAnnotationView { pin = dequeued pin.annotation = node } else { pin = MKPinAnnotationView(annotation: node, reuseIdentifier: "pin") } switch node.type { case .leaf: pin.pinTintColor = .green case .node: pin.pinTintColor = .blue case .root: pin.pinTintColor = .red } return pin } return nil } }
b3cdf113889df439d8d0f31a6c7b8d3b
32.459459
124
0.592892
false
false
false
false
ahoppen/swift
refs/heads/main
test/Sanitizers/tsan/actor_counters.swift
apache-2.0
2
// RUN: %target-run-simple-swift(-Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library -sanitize=thread) // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // REQUIRES: tsan_runtime // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: linux // UNSUPPORTED: windows // REQUIRES: rdar83246843 @available(SwiftStdlib 5.1, *) actor Counter { private var value = 0 private let scratchBuffer: UnsafeMutableBufferPointer<Int> init(maxCount: Int) { scratchBuffer = .allocate(capacity: maxCount) scratchBuffer.initialize(repeating: 0) } func next() -> Int { let current = value // Make sure we haven't produced this value before assert(scratchBuffer[current] == 0) scratchBuffer[current] = 1 value = value + 1 return current } deinit { for i in 0..<value { assert(scratchBuffer[i] == 1) } } } @available(SwiftStdlib 5.1, *) func worker(identity: Int, counters: [Counter], numIterations: Int) async { for i in 0..<numIterations { let counterIndex = Int.random(in: 0 ..< counters.count) let counter = counters[counterIndex] let nextValue = await counter.next() print("Worker \(identity) calling counter \(counterIndex) produced \(nextValue)") } } @available(SwiftStdlib 5.1, *) func runTest(numCounters: Int, numWorkers: Int, numIterations: Int) async { // Create counter actors. var counters: [Counter] = [] for i in 0..<numCounters { counters.append(Counter(maxCount: numWorkers * numIterations)) } // Create a bunch of worker threads. var workers: [Task.Handle<Void, Error>] = [] for i in 0..<numWorkers { workers.append( detach { [counters] in await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000) await worker(identity: i, counters: counters, numIterations: numIterations) } ) } // Wait until all of the workers have finished. for worker in workers { try! await worker.get() } print("DONE!") } @available(SwiftStdlib 5.1, *) @main struct Main { static func main() async { // Useful for debugging: specify counter/worker/iteration counts let args = CommandLine.arguments let counters = args.count >= 2 ? Int(args[1])! : 10 let workers = args.count >= 3 ? Int(args[2])! : 100 let iterations = args.count >= 4 ? Int(args[3])! : 1000 print("counters: \(counters), workers: \(workers), iterations: \(iterations)") await runTest(numCounters: counters, numWorkers: workers, numIterations: iterations) } }
b4895b7e7e3e92189fb669accd61c2f5
27.3
130
0.671378
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/Views/TransactionCells/TxAmountCell.swift
mit
1
// // TxAmountCell.swift // breadwallet // // Created by Ehsan Rezaie on 2017-12-21. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit class TxAmountCell: UITableViewCell, Subscriber { // MARK: - Vars private let container = UIView() private lazy var tokenAmountLabel: UILabel = { let label = UILabel(font: UIFont.customBody(size: 26.0)) label.textAlignment = .center label.adjustsFontSizeToFitWidth = true return label }() private lazy var fiatAmountLabel: UILabel = { let label = UILabel(font: UIFont.customBody(size: 14.0)) label.textAlignment = .center return label }() private let separator = UIView(color: .clear) // MARK: - Init override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } private func setupViews() { addSubviews() addConstraints() } private func addSubviews() { contentView.addSubview(container) contentView.addSubview(separator) container.addSubview(fiatAmountLabel) container.addSubview(tokenAmountLabel) } private func addConstraints() { container.constrain(toSuperviewEdges: UIEdgeInsets(top: C.padding[1], left: C.padding[2], bottom: -C.padding[2], right: -C.padding[2])) tokenAmountLabel.constrain([ tokenAmountLabel.constraint(.top, toView: container), tokenAmountLabel.constraint(.leading, toView: container), tokenAmountLabel.constraint(.trailing, toView: container) ]) fiatAmountLabel.constrain([ fiatAmountLabel.constraint(toBottom: tokenAmountLabel, constant: 0), fiatAmountLabel.constraint(.leading, toView: container), fiatAmountLabel.constraint(.trailing, toView: container), fiatAmountLabel.constraint(.bottom, toView: container) ]) separator.constrainBottomCorners(height: 0.5) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func set(viewModel: TxDetailViewModel) { let largeFont = UIFont.customBody(size: 26.0) let smallFont = UIFont.customBody(size: 14.0) let fiatColor = UIColor.mediumGray let textColor = UIColor.lightGray let tokenColor: UIColor = (viewModel.direction == .received) ? .receivedGreen : .darkGray let amountText = NSMutableAttributedString(string: viewModel.amount, attributes: [.font: largeFont, .foregroundColor: tokenColor]) tokenAmountLabel.attributedText = amountText // fiat amount label let currentAmount = viewModel.fiatAmount let originalAmount = viewModel.originalFiatAmount if viewModel.status != .complete || originalAmount == nil { fiatAmountLabel.attributedText = NSAttributedString(string: currentAmount, attributes: [.font: smallFont, .foregroundColor: fiatColor]) } else { let format = (viewModel.direction == .sent) ? S.TransactionDetails.amountWhenSent : S.TransactionDetails.amountWhenReceived let attributedText = NSMutableAttributedString(string: String(format: format, originalAmount!, currentAmount), attributes: [.font: smallFont, .foregroundColor: textColor]) attributedText.set(attributes: [.foregroundColor: fiatColor], forText: currentAmount) attributedText.set(attributes: [.foregroundColor: fiatColor], forText: originalAmount!) fiatAmountLabel.attributedText = attributedText } } }
7a359e5be58bf2d9e57e32ecc0693b00
39.305556
135
0.572479
false
false
false
false
mleiv/IBStyler
refs/heads/master
IBStylerDemo/IBStylerDemo/IBStyles/IBGradient.swift
mit
2
// // IBGradient.swift // // Created by Emily Ivie on 9/17/16. // // Licensed under The MIT License // For full copyright and license information, please see http://opensource.org/licenses/MIT // Redistributions of files must retain the above copyright notice. import UIKit /// Just a helpful way to define background gradients. /// See CAGradientLayer for more information on the properties used here. /// /// - direction: .Vertical or .Horizontal /// - colors /// - locations /// - createGradientView() public struct IBGradient { /// Quick enum to more clearly define IBGradient direction (Vertical or Horizontal). public enum Direction { case vertical, horizontal } public var direction: Direction = .vertical public var colors: [UIColor] = [] public var locations: [Double] = [] init(direction: Direction, colors: [UIColor]) { self.direction = direction self.colors = colors } /// Generates a IBGradientView from the gradient values provided. /// /// - parameter bounds: The size to use in creating the gradient view. /// - returns: a UIView with a gradient background layer public func createGradientView(_ bounds: CGRect) -> (IBGradientView) { let gradientView = IBGradientView(frame: bounds) gradientView.setLayerColors(colors) if !locations.isEmpty { gradientView.setLayerLocations(locations) } else { gradientView.setLayerEndPoint(direction == .vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)) } return gradientView } } //MARK: IBGradientView /// Allows for an auto-resizable CAGradientLayer (like, say, during device orientation changes). /// /// IBStyles IBStylePropertyName.BackgroundGradient uses this. final public class IBGradientView: UIView { /// Built-in UIView function that responds to .layer requests. /// Changes the .layer property of the view to be CAGradientLayer. But we still have to change all interactions with .layer to recognize this new type, hence the other functions. /// /// returns: CAGradientLayer .layer reference override public class var layerClass : (AnyClass) { return CAGradientLayer.self } /// Sets the colors of the gradient. Can be more than two. /// /// parameter colors: a list of UIColor elements. public func setLayerColors(_ colors: [UIColor]) { let layer = self.layer as? CAGradientLayer layer?.colors = colors.map({ $0.cgColor }) } /// Sets the locations of the gradient. See CAGradientLayer documentation for how this work, because I only used endPoint myself. /// parameter locations: a list of Double location positions. public func setLayerLocations(_ locations: [Double]) { let layer = self.layer as? CAGradientLayer layer?.locations = locations.map({ NSNumber(value: $0 as Double) }) } /// Sets the start point of the gradient (this is the simplest way to define a gradient: setting the start or end point) /// /// parameter startPoint: a CGPoint using 0.0 - 1.0 values public func setLayerStartPoint(_ startPoint: CGPoint) { let layer = self.layer as? CAGradientLayer layer?.startPoint = startPoint } /// Sets the end point of the gradient (this is the simplest way to define a gradient: setting the start or end point) /// /// parameter endPoint: a CGPoint using 0.0 - 1.0 values public func setLayerEndPoint(_ endPoint: CGPoint) { let layer = self.layer as? CAGradientLayer layer?.endPoint = endPoint } }
1ab812e7dd821d8f3398c5ccc5ca8d09
39.808989
182
0.677863
false
false
false
false
CodaFi/swift
refs/heads/main
benchmark/single-source/ObserverClosure.swift
apache-2.0
22
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import TestsUtils public let ObserverClosure = BenchmarkInfo( name: "ObserverClosure", runFunction: run_ObserverClosure, tags: [.validation], legacyFactor: 10) class Observer { @inline(never) func receive(_ value: Int) { } } class Signal { var observers: [(Int) -> ()] = [] func subscribe(_ observer: @escaping (Int) -> ()) { observers.append(observer) } func send(_ value: Int) { for observer in observers { observer(value) } } } public func run_ObserverClosure(_ iterations: Int) { let signal = Signal() let observer = Observer() for _ in 0 ..< 1_000 * iterations { signal.subscribe { i in observer.receive(i) } } signal.send(1) }
32f01be3a868fee53422aa7585cfb087
23.816327
80
0.583882
false
false
false
false
jopamer/swift
refs/heads/master
stdlib/public/SDK/SpriteKit/SpriteKit.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import SpriteKit import simd // SpriteKit defines SKColor using a macro. #if os(macOS) public typealias SKColor = NSColor #elseif os(iOS) || os(tvOS) || os(watchOS) public typealias SKColor = UIColor #endif // this class only exists to allow AnyObject lookup of _copyImageData // since that method only exists in a private header in SpriteKit, the lookup // mechanism by default fails to accept it as a valid AnyObject call @objc class _SpriteKitMethodProvider : NSObject { override init() { preconditionFailure("don't touch me") } @objc func _copyImageData() -> NSData! { return nil } } @available(iOS, introduced: 10.0) @available(macOS, introduced: 10.12) @available(tvOS, introduced: 10.0) @available(watchOS, introduced: 3.0) extension SKWarpGeometryGrid { /// Create a grid of the specified dimensions, source and destination positions. /// /// Grid dimensions (columns and rows) refer to the number of faces in each dimension. The /// number of vertices required for a given dimension is equal to (cols + 1) * (rows + 1). /// /// SourcePositions are normalized (0.0 - 1.0) coordinates to determine the source content. /// /// DestinationPositions are normalized (0.0 - 1.0) positional coordinates with respect to /// the node's native size. Values outside the (0.0-1.0) range are perfectly valid and /// correspond to positions outside of the native undistorted bounds. /// /// Source and destination positions are provided in row-major order starting from the top-left. /// For example the indices for a 2x2 grid would be as follows: /// /// [0]---[1]---[2] /// | | | /// [3]---[4]---[5] /// | | | /// [6]---[7]---[8] /// /// - Parameter columns: the number of columns to initialize the SKWarpGeometryGrid with /// - Parameter rows: the number of rows to initialize the SKWarpGeometryGrid with /// - Parameter sourcePositions: the source positions for the SKWarpGeometryGrid to warp from /// - Parameter destinationPositions: the destination positions for SKWarpGeometryGrid to warp to public convenience init(columns: Int, rows: Int, sourcePositions: [simd.float2] = [float2](), destinationPositions: [simd.float2] = [float2]()) { let requiredElementsCount = (columns + 1) * (rows + 1) switch (destinationPositions.count, sourcePositions.count) { case (0, 0): self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: nil) case (let dests, 0): precondition(dests == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: nil, destPositions: destinationPositions) case (0, let sources): precondition(sources == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: nil) case (let dests, let sources): precondition(dests == requiredElementsCount && sources == requiredElementsCount, "Mismatch found between rows/columns and positions.") self.init(__columns: columns, rows: rows, sourcePositions: sourcePositions, destPositions: destinationPositions) } } public func replacingBySourcePositions(positions source: [simd.float2]) -> SKWarpGeometryGrid { return self.__replacingSourcePositions(source) } public func replacingByDestinationPositions(positions destination: [simd.float2]) -> SKWarpGeometryGrid { return self.__replacingDestPositions(destination) } }
3986ff32300d1e0d4f6fbc48ae3dc6c5
47.388235
147
0.685874
false
false
false
false
ColorPenBoy/ios-charts
refs/heads/master
Charts/Classes/Data/BubbleChartDataSet.swift
apache-2.0
5
// // BubbleChartDataSet.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class BubbleChartDataSet: BarLineScatterCandleChartDataSet { internal var _xMax = Double(0.0) internal var _xMin = Double(0.0) internal var _maxSize = CGFloat(0.0) public var xMin: Double { return _xMin } public var xMax: Double { return _xMax } public var maxSize: CGFloat { return _maxSize } public func setColor(color: UIColor, alpha: CGFloat) { super.setColor(color.colorWithAlphaComponent(alpha)) } internal override func calcMinMax(start start: Int, end: Int) { if (yVals.count == 0) { return } let entries = yVals as! [BubbleChartDataEntry] // need chart width to guess this properly var endValue : Int if end == 0 { endValue = entries.count - 1 } else { endValue = end } _lastStart = start _lastEnd = end _yMin = yMin(entries[start]) _yMax = yMax(entries[start]) for (var i = start; i <= endValue; i++) { let entry = entries[i] let ymin = yMin(entry) let ymax = yMax(entry) if (ymin < _yMin) { _yMin = ymin } if (ymax > _yMax) { _yMax = ymax } let xmin = xMin(entry) let xmax = xMax(entry) if (xmin < _xMin) { _xMin = xmin } if (xmax > _xMax) { _xMax = xmax } let size = largestSize(entry) if (size > _maxSize) { _maxSize = size } } } /// Sets/gets the width of the circle that surrounds the bubble when highlighted public var highlightCircleWidth: CGFloat = 2.5 private func yMin(entry: BubbleChartDataEntry) -> Double { return entry.value } private func yMax(entry: BubbleChartDataEntry) -> Double { return entry.value } private func xMin(entry: BubbleChartDataEntry) -> Double { return Double(entry.xIndex) } private func xMax(entry: BubbleChartDataEntry) -> Double { return Double(entry.xIndex) } private func largestSize(entry: BubbleChartDataEntry) -> CGFloat { return entry.size } }
1834eb3db4a72123af5b459a58871797
21.672
84
0.500706
false
false
false
false
SSU-CS-Department/ssumobile-ios
refs/heads/master
SSUMobile/Modules/Email/Views/SSUEmailPickerViewController.swift
apache-2.0
1
// // SSUEmailPickerViewController.swift // SSUMobile // // Created by Eric Amorde on 7/26/15. // Copyright (c) 2015 Sonoma State University Department of Computer Science. All rights reserved. // import UIKit class SSUEmailPickerViewController: UITableViewController { struct Segue { static let google = "gdocs" static let exchange = "exchange" } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? SSUEmailViewController { if segue.identifier == Segue.exchange { destination.mode = .email } else if segue.identifier == Segue.google { destination.mode = .googleDocs } } } }
ae2ced8f62c5590c32866d879fc9d04a
26.068966
99
0.634395
false
false
false
false
mcjcloud/Show-And-Sell
refs/heads/master
Show And Sell/LoginViewController.swift
apache-2.0
1
// // ViewController.swift // Show And Sell // // Created by Brayden Cloud on 9/5/16. // Copyright © 2016 Brayden Cloud. All rights reserved. // // UIViewController implementation to show a Login screen for accessing the server // import UIKit import Google import GoogleSignIn protocol LoginViewControllerDelegate { func login(didPressCreateButton createButton: UIButton) } class LoginViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate, UIGestureRecognizerDelegate { // GUI properties @IBOutlet var emailField: UITextField! @IBOutlet var passwordField: UITextField! @IBOutlet var messageLabel: UILabel! @IBOutlet var loginButton: UIButton! @IBOutlet var googleButton: GIDSignInButton! @IBOutlet var createAccountButton: UIButton! // delegate for switching between login and create var delegate: LoginViewControllerDelegate? var user: User! var autoLogin: Bool = true var loggingIn: Bool = false var loadOverlay = OverlayView(type: .loading, text: nil) override func viewDidLoad() { super.viewDidLoad() print("Login view did load") // setup text fields setupTextField(emailField, placeholder: "Email") setupTextField(passwordField, placeholder: "Password") // make textfields dismiss when uiview tapped let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) self.view.addGestureRecognizer(gestureRecognizer) gestureRecognizer.cancelsTouchesInView = false // allow subviews to receive clicks. // assign textField methods emailField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged) passwordField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged) // configure google delegate var configureError: NSError? GGLContext.sharedInstance().configureWithError(&configureError) //assert(configureError == nil, "Error configuring Google services: \(configureError)") GIDSignIn.sharedInstance().delegate = self GIDSignIn.sharedInstance().uiDelegate = self // set gray color for disabled button loginButton.setTitleColor(UIColor.gray, for: .disabled) createAccountButton.setTitleColor(UIColor.gray, for: .disabled) // adjust google button googleButton.colorScheme = .dark googleButton.addTarget(self, action: #selector(googleSignIn), for: .touchUpInside) // Do any additional setup after loading the view, typically from a nib. AppDelegate.loginVC = self // pass a reference to the AppDelegate messageLabel.text = "" // enable/disable login button loginButton.isEnabled = shouldEnableLogin() // auto login if let email = AppData.save.email, let pword = AppData.save.password { emailField.text = email passwordField.text = HttpRequestManager.decrypt(pword) if autoLogin { logIn(loginButton) } } } override func viewWillAppear(_ animated: Bool) { // enable/disable login button loginButton.isEnabled = shouldEnableLogin() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Transition @IBAction func unwindToLogin(segue: UIStoryboardSegue) { print("unwind to login") // save data from session AppData.saveData() // clear tab bar data AppDelegate.tabVC?.clearTabData() // clear fields emailField.text = "" passwordField.text = "" messageLabel.text = "" logout() loginButton.isEnabled = true createAccountButton.isEnabled = true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // do nothing } // IBOutlet functions @IBAction func logIn(_ sender: UIButton) { // clear error message messageLabel.text = "" loggingIn = true loadOverlay.showOverlay(view: self.view, position: .center) // GET user data. if let email = emailField.text, let password = passwordField.text { let securePassword = HttpRequestManager.encrypt(password) // disable login button and create account button (until login attempt is complete) loginButton.isEnabled = false createAccountButton.isEnabled = false HttpRequestManager.user(withEmail: email, andPassword: securePassword) { user, response, error in self.postLogin(user: user, response: response, error: error) } } else { messageLabel.text = "Please make sure all fields are filled." } } @IBAction func createAccount(_ sender: UIButton) { delegate?.login(didPressCreateButton: sender) } // MARK: Google Auth func application(application: UIApplication, openURL url: URL, options: [String: Any]) -> Bool { return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication.rawValue] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation.rawValue]) } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if (error == nil) { // Perform any operations on signed in user here. let userId = user.userID // For client-side use only! let email = user.profile.email let name = user.profile.name?.components(separatedBy: " ") let firstName = name?[0] let lastName = name?[1] // do sign in for google account print("userId: \(userId)") print("\(email) signed in") print("name: \(name)") if let email = email, let userId = userId, let firstName = firstName, let lastName = lastName { loadOverlay.showOverlay(view: UIApplication.shared.keyWindow!, position: .center) HttpRequestManager.googleUser(email: email, userId: HttpRequestManager.encrypt(userId), firstName: firstName, lastName: lastName) { user, response, error in print("calling postlogin from google sign in") // finish login AppData.save.isGoogleSigned = true AppData.saveData() self.postLogin(user: user, response: response, error: error) } } } else { print("signin error: \(error.localizedDescription)") } } func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) { // disconnect print("google disconnect") } func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) { // stop loading icon print("stop loading") loadOverlay.hideOverlayView() } func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) { // present a sign in vc print("should present VC") self.present(viewController, animated: true, completion: nil) } func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) { // dismiss the sign in vc print("should dismissVC") self.dismiss(animated: true, completion: nil) } // MARK: Helper func textChanged(_ textField: UITextField) { loginButton.isEnabled = shouldEnableLogin() } // dismiss a keyboard func dismissKeyboard() { emailField.resignFirstResponder() passwordField.resignFirstResponder() self.view.endEditing(true) } // MARK: Gesture Recognizer // fix for google button not working - google button wouldn't get tap because the GestureRecognizer added to its superview got it. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if touch.view is GIDSignInButton { return false } else { return true } } // setup the custom TextField func setupTextField(_ textfield: UITextField, placeholder: String) { // edit password field let width = CGFloat(1.5) let border = CALayer() border.borderColor = UIColor(colorLiteralRed: 0.298, green: 0.686, blue: 0.322, alpha: 1.0).cgColor // Green border.frame = CGRect(x: 0, y: textfield.frame.size.height - width, width: textfield.frame.size.width, height: textfield.frame.size.height) border.borderWidth = width textfield.layer.addSublayer(border) textfield.layer.masksToBounds = true textfield.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged) textfield.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: UIColor.white]) } // check if the login button should be enabled. func shouldEnableLogin() -> Bool { return (emailField.text?.characters.count ?? 0) > 0 && (passwordField.text?.characters.count ?? 0) > 0 && !loggingIn } func postLogin(user: User?, response: URLResponse?, error: Error?) { print("postlogin response: \((response as? HTTPURLResponse)?.statusCode)") // stop any loading DispatchQueue.main.async { self.loadOverlay.hideOverlayView() self.loggingIn = false } // check error if let e = error { print("error logging in: \(e)") // switch buttons and change message label in main thread DispatchQueue.main.async { self.messageLabel.text = "Error logging in." self.loginButton.isEnabled = true self.createAccountButton.isEnabled = true } } else if let u = user { print("user recieved: \(u.email)") self.user = u self.autoLogin = true // if the signed in user is not the same as the saved user, reasign the "save user" AppData.user = u AppData.save.email = u.email AppData.save.password = u.password AppData.saveData() // go to tabs segue from main thread DispatchQueue.main.async(execute: { print("Logging in, groupId: \(u.groupId)") print("segue to tabs") self.performSegue(withIdentifier: "loginToTabs", sender: self) }) // save data AppData.saveData() } else { DispatchQueue.main.async { if let status = (response as? HTTPURLResponse)?.statusCode { // check error switch(status) { case 409: self.messageLabel.text = "Account with gmail address already exists." GIDSignIn.sharedInstance().signOut() case 401: self.messageLabel.text = "Incorrect username or password." default: self.messageLabel.text = "Error getting user." } } else { // generic error message self.messageLabel.text = "Error getting user." } // re-enable buttons self.loginButton.isEnabled = true self.createAccountButton.isEnabled = true } } } // when the google button is clicked func googleSignIn() { // clear message label messageLabel.text = "" print("google button clicked") loadOverlay.showOverlay(view: UIApplication.shared.keyWindow!, position: .center) } // log the user out func logout() { // clear non-persistant data. AppData.myGroup = nil AppData.user = nil AppData.group = nil AppData.bookmarks = nil AppData.save.isGoogleSigned = false AppData.saveData() // logout google user GIDSignIn.sharedInstance().signOut() } }
2350be98536b7d0abf2a336c31fa2b20
37.050595
224
0.597028
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/URLSession/http/HTTPURLProtocol.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation import Dispatch internal class _HTTPURLProtocol: _NativeProtocol { public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { super.init(task: task, cachedResponse: cachedResponse, client: client) } public required init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { super.init(request: request, cachedResponse: cachedResponse, client: client) } override class func canInit(with request: URLRequest) -> Bool { guard request.url?.scheme == "http" || request.url?.scheme == "https" else { return false } return true } override func didReceive(headerData data: Data, contentLength: Int64) -> _EasyHandle._Action { guard case .transferInProgress(let ts) = internalState else { fatalError("Received header data, but no transfer in progress.") } guard let task = task else { fatalError("Received header data but no task available.") } task.countOfBytesExpectedToReceive = contentLength > 0 ? contentLength : NSURLSessionTransferSizeUnknown do { let newTS = try ts.byAppending(headerLine: data) internalState = .transferInProgress(newTS) let didCompleteHeader = !ts.isHeaderComplete && newTS.isHeaderComplete if didCompleteHeader { // The header is now complete, but wasn't before. didReceiveResponse() } return .proceed } catch { return .abort } } /// Set options on the easy handle to match the given request. /// /// This performs a series of `curl_easy_setopt()` calls. override func configureEasyHandle(for request: URLRequest) { // At this point we will call the equivalent of curl_easy_setopt() // to configure everything on the handle. Since we might be re-using // a handle, we must be sure to set everything and not rely on default // values. //TODO: We could add a strong reference from the easy handle back to // its URLSessionTask by means of CURLOPT_PRIVATE -- that would ensure // that the task is always around while the handle is running. // We would have to break that retain cycle once the handle completes // its transfer. // Behavior Options easyHandle.set(verboseModeOn: enableLibcurlDebugOutput) easyHandle.set(debugOutputOn: enableLibcurlDebugOutput, task: task!) easyHandle.set(passHeadersToDataStream: false) easyHandle.set(progressMeterOff: true) easyHandle.set(skipAllSignalHandling: true) // Error Options: easyHandle.set(errorBuffer: nil) easyHandle.set(failOnHTTPErrorCode: false) // Network Options: guard let url = request.url else { fatalError("No URL in request.") } easyHandle.set(url: url) let session = task?.session as! URLSession let _config = session._configuration easyHandle.set(sessionConfig: _config) easyHandle.setAllowedProtocolsToHTTPAndHTTPS() easyHandle.set(preferredReceiveBufferSize: Int.max) do { switch (task?.body, try task?.body.getBodyLength()) { case (nil, _): set(requestBodyLength: .noBody) case (_, let length?): set(requestBodyLength: .length(length)) task!.countOfBytesExpectedToSend = Int64(length) case (_, nil): set(requestBodyLength: .unknown) } } catch let e { // Fail the request here. // TODO: We have multiple options: // NSURLErrorNoPermissionsToReadFile // NSURLErrorFileDoesNotExist self.internalState = .transferFailed let error = NSError(domain: NSURLErrorDomain, code: errorCode(fileSystemError: e), userInfo: [NSLocalizedDescriptionKey: "File system error"]) failWith(error: error, request: request) return } // HTTP Options: easyHandle.set(followLocation: false) // The httpAdditionalHeaders from session configuration has to be added to the request. // The request.allHTTPHeaders can override the httpAdditionalHeaders elements. Add the // httpAdditionalHeaders from session configuration first and then append/update the // request.allHTTPHeaders so that request.allHTTPHeaders can override httpAdditionalHeaders. let httpSession = self.task?.session as! URLSession var httpHeaders: [AnyHashable : Any]? if let hh = httpSession.configuration.httpAdditionalHeaders { httpHeaders = hh } if let hh = request.allHTTPHeaderFields { if httpHeaders == nil { httpHeaders = hh } else { hh.forEach { // When adding a header, remove any current entry with the same header name regardless of case let newKey = $0.lowercased() for key in httpHeaders!.keys { if newKey == (key as! String).lowercased() { httpHeaders?.removeValue(forKey: key) break } } httpHeaders![$0] = $1 } } } let customHeaders: [String] let headersForRequest = curlHeaders(for: httpHeaders) if ((request.httpMethod == "POST") && (request.httpBody?.count ?? 0 > 0) && (request.value(forHTTPHeaderField: "Content-Type") == nil)) { customHeaders = headersForRequest + ["Content-Type:application/x-www-form-urlencoded"] } else { customHeaders = headersForRequest } easyHandle.set(customHeaders: customHeaders) //TODO: The CURLOPT_PIPEDWAIT option is unavailable on Ubuntu 14.04 (libcurl 7.36) //TODO: Introduce something like an #if, if we want to set them here //set the request timeout //TODO: the timeout value needs to be reset on every data transfer var timeoutInterval = Int(httpSession.configuration.timeoutIntervalForRequest) * 1000 if request.isTimeoutIntervalSet { timeoutInterval = Int(request.timeoutInterval) * 1000 } let timeoutHandler = DispatchWorkItem { [weak self] in guard let _ = self?.task else { fatalError("Timeout on a task that doesn't exist") } //this guard must always pass self?.internalState = .transferFailed let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: nil)) self?.completeTask(withError: urlError) self?.client?.urlProtocol(self!, didFailWithError: urlError) } guard let task = self.task else { fatalError() } easyHandle.timeoutTimer = _TimeoutSource(queue: task.workQueue, milliseconds: timeoutInterval, handler: timeoutHandler) easyHandle.set(automaticBodyDecompression: true) easyHandle.set(requestMethod: request.httpMethod ?? "GET") if request.httpMethod == "HEAD" { easyHandle.set(noBody: true) } } /// What action to take override func completionAction(forCompletedRequest request: URLRequest, response: URLResponse) -> _CompletionAction { // Redirect: guard let httpURLResponse = response as? HTTPURLResponse else { fatalError("Reponse was not HTTPURLResponse") } if let request = redirectRequest(for: httpURLResponse, fromRequest: request) { return .redirectWithRequest(request) } return .completeTask } override func redirectFor(request: URLRequest) { //TODO: Should keep track of the number of redirects that this // request has gone through and err out once it's too large, i.e. // call into `failWith(errorCode: )` with NSURLErrorHTTPTooManyRedirects guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = self.internalState else { fatalError("Trying to redirect, but the transfer is not complete.") } guard let session = task?.session as? URLSession else { fatalError() } switch session.behaviour(for: task!) { case .taskDelegate(let delegate): // At this point we need to change the internal state to note // that we're waiting for the delegate to call the completion // handler. Then we'll call the delegate callback // (willPerformHTTPRedirection). The task will then switch out of // its internal state once the delegate calls the completion // handler. //TODO: Should the `public response: URLResponse` property be updated // before we call delegate API self.internalState = .waitingForRedirectCompletionHandler(response: response, bodyDataDrain: bodyDataDrain) // We need this ugly cast in order to be able to support `URLSessionTask.init()` session.delegateQueue.addOperation { delegate.urlSession(session, task: self.task!, willPerformHTTPRedirection: response as! HTTPURLResponse, newRequest: request) { [weak self] (request: URLRequest?) in guard let task = self else { return } self?.task?.workQueue.async { task.didCompleteRedirectCallback(request) } } } case .noDelegate, .dataCompletionHandler, .downloadCompletionHandler: // Follow the redirect. Need to configure new request with cookies, etc. let configuredRequest = session._configuration.configure(request: request) startNewTransfer(with: configuredRequest) } } override func validateHeaderComplete(transferState: _NativeProtocol._TransferState) -> URLResponse? { if !transferState.isHeaderComplete { return HTTPURLResponse(url: transferState.url, statusCode: 200, httpVersion: "HTTP/0.9", headerFields: [:]) /* we received body data before CURL tells us that the headers are complete, that happens for HTTP/0.9 simple responses, see - https://www.w3.org/Protocols/HTTP/1.0/spec.html#Message-Types - https://github.com/curl/curl/issues/467 */ } return nil } } fileprivate extension _HTTPURLProtocol { /// These are a list of headers that should be passed to libcurl. /// /// Headers will be returned as `Accept: text/html` strings for /// setting fields, `Accept:` for disabling the libcurl default header, or /// `Accept;` for a header with no content. This is the format that libcurl /// expects. /// /// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html func curlHeaders(for httpHeaders: [AnyHashable : Any]?) -> [String] { var result: [String] = [] var names = Set<String>() if let hh = httpHeaders as? [String : String] { hh.forEach { let name = $0.0.lowercased() guard !names.contains(name) else { return } names.insert(name) if $0.1.isEmpty { result.append($0.0 + ";") } else { result.append($0.0 + ": " + $0.1) } } } curlHeadersToSet.forEach { let name = $0.0.lowercased() guard !names.contains(name) else { return } names.insert(name) if $0.1.isEmpty { result.append($0.0 + ";") } else { result.append($0.0 + ": " + $0.1) } } curlHeadersToRemove.forEach { let name = $0.lowercased() guard !names.contains(name) else { return } names.insert(name) result.append($0 + ":") } return result } /// Any header values that should be passed to libcurl /// /// These will only be set if not already part of the request. /// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html var curlHeadersToSet: [(String,String)] { var result = [("Connection", "keep-alive"), ("User-Agent", userAgentString), ] if let language = NSLocale.current.languageCode { result.append(("Accept-Language", language)) } return result } /// Any header values that should be removed from the ones set by libcurl /// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html var curlHeadersToRemove: [String] { if task?.body == nil { return [] } else { return ["Expect"] } } } fileprivate var userAgentString: String = { // Darwin uses something like this: "xctest (unknown version) CFNetwork/760.4.2 Darwin/15.4.0 (x86_64)" let info = ProcessInfo.processInfo let name = info.processName let curlVersion = CFURLSessionCurlVersionInfo() //TODO: Should probably use sysctl(3) to get these: // kern.ostype: Darwin // kern.osrelease: 15.4.0 //TODO: Use Bundle to get the version number? return "\(name) (unknown version) curl/\(curlVersion.major).\(curlVersion.minor).\(curlVersion.patch)" }() /// State Transfers extension _HTTPURLProtocol { fileprivate func didCompleteRedirectCallback(_ request: URLRequest?) { guard case .waitingForRedirectCompletionHandler(response: let response, bodyDataDrain: let bodyDataDrain) = self.internalState else { fatalError("Received callback for HTTP redirection, but we're not waiting for it. Was it called multiple times?") } // If the request is `nil`, we're supposed to treat the current response // as the final response, i.e. not do any redirection. // Otherwise, we'll start a new transfer with the passed in request. if let r = request { startNewTransfer(with: r) } else { self.internalState = .transferCompleted(response: response, bodyDataDrain: bodyDataDrain) completeTask() } } } /// Response processing internal extension _HTTPURLProtocol { /// Whenever we receive a response (i.e. a complete header) from libcurl, /// this method gets called. func didReceiveResponse() { guard let _ = task as? URLSessionDataTask else { return } guard case .transferInProgress(let ts) = self.internalState else { fatalError("Transfer not in progress.") } guard let response = ts.response as? HTTPURLResponse else { fatalError("Header complete, but not URL response.") } guard let session = task?.session as? URLSession else { fatalError() } switch session.behaviour(for: self.task!) { case .noDelegate: break case .taskDelegate: //TODO: There's a problem with libcurl / with how we're using it. // We're currently unable to pause the transfer / the easy handle: // https://curl.haxx.se/mail/lib-2016-03/0222.html // // For now, we'll notify the delegate, but won't pause the transfer, // and we'll disregard the completion handler: switch response.statusCode { case 301, 302, 303, 307: break default: self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } case .dataCompletionHandler: break case .downloadCompletionHandler: break } } /// If the response is a redirect, return the new request /// /// RFC 7231 section 6.4 defines redirection behavior for HTTP/1.1 /// /// - SeeAlso: <https://tools.ietf.org/html/rfc7231#section-6.4> func redirectRequest(for response: HTTPURLResponse, fromRequest: URLRequest) -> URLRequest? { //TODO: Do we ever want to redirect for HEAD requests? func methodAndURL() -> (String, URL)? { guard let location = response.value(forHeaderField: .location, response: response), let targetURL = URL(string: location) else { // Can't redirect when there's no location to redirect to. return nil } // Check for a redirect: switch response.statusCode { //TODO: Should we do this for 300 "Multiple Choices", too? case 301, 302, 303: // Change into "GET": return ("GET", targetURL) case 307: // Re-use existing method: return (fromRequest.httpMethod ?? "GET", targetURL) default: return nil } } guard let (method, targetURL) = methodAndURL() else { return nil } var request = fromRequest request.httpMethod = method // If targetURL has only relative path of url, create a new valid url with relative path // Otherwise, return request with targetURL ie.url from location field guard targetURL.scheme == nil || targetURL.host == nil else { request.url = targetURL return request } let scheme = request.url?.scheme let host = request.url?.host let port = request.url?.port var components = URLComponents() components.scheme = scheme components.host = host // Use the original port if the new URL does not contain a host // ie Location: /foo => <original host>:<original port>/Foo // but Location: newhost/foo will ignore the original port if targetURL.host == nil { components.port = port } //The path must either begin with "/" or be an empty string. if targetURL.relativeString.first != "/" { components.path = "/" + targetURL.relativeString } else { components.path = targetURL.relativeString } guard let urlString = components.string else { fatalError("Invalid URL") } request.url = URL(string: urlString) let timeSpent = easyHandle.getTimeoutIntervalSpent() request.timeoutInterval = fromRequest.timeoutInterval - timeSpent return request } } fileprivate extension HTTPURLResponse { /// Type safe HTTP header field name(s) enum _Field: String { /// `Location` /// - SeeAlso: RFC 2616 section 14.30 <https://tools.ietf.org/html/rfc2616#section-14.30> case location = "Location" } func value(forHeaderField field: _Field, response: HTTPURLResponse?) -> String? { let value = field.rawValue guard let response = response else { fatalError("Response is nil") } if let location = response.allHeaderFields[value] as? String { return location } return nil } }
4c88da5e40f548daee85b89087cf34a7
42.245614
181
0.611156
false
false
false
false
josve05a/wikipedia-ios
refs/heads/develop
Wikipedia/Code/DescriptionWelcomeImageViewController.swift
mit
4
class DescriptionWelcomeImageViewController: UIViewController { var pageType:DescriptionWelcomePageType = .intro private lazy var imageForWelcomePageType: UIImage? = { switch pageType { case .intro: return UIImage(named: "description-cat") case .exploration: return UIImage(named: "description-planet") } }() private var image: UIImage? { return imageForWelcomePageType } override func viewDidLoad() { super.viewDidLoad() guard let image = image else { return } let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFit view.wmf_addSubviewWithConstraintsToEdges(imageView) } }
4c32a7fb19b6f77ae1dd788f125135c4
28.230769
63
0.634211
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/CryptoAssets/Sources/StellarKit/Foundation/AccountResponse+Convenience.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import PlatformKit import stellarsdk // MARK: StellarSDK Convenience extension AccountResponse { var totalBalance: CryptoValue { let value = balances .lazy .filter { $0.whichAssetType == .native } .map(\.balance) .compactMap { Decimal(string: $0) } .reduce(0, +) return CryptoValue.create(major: value, currency: .stellar) } func toAssetAccountDetails(minimumBalance: CryptoValue) -> StellarAccountDetails { let account = StellarAssetAccount( accountAddress: accountId, name: CryptoCurrency.stellar.defaultWalletName, description: CryptoCurrency.stellar.defaultWalletName, sequence: Int(sequenceNumber), subentryCount: subentryCount ) var actionableBalance: CryptoValue = .zero(currency: .stellar) if let balanceMinusReserve = try? totalBalance - minimumBalance, balanceMinusReserve.isPositive { actionableBalance = balanceMinusReserve } return StellarAccountDetails( account: account, balance: totalBalance, actionableBalance: actionableBalance ) } } extension AccountBalanceResponse { fileprivate enum WhichAssetType: String, Codable { case native case credit_alphanum4 case credit_alphanum12 } fileprivate var whichAssetType: WhichAssetType? { WhichAssetType(rawValue: assetType) } }
9d7f93aca3cddb592c2a84865618daf1
29.346154
105
0.651458
false
false
false
false
jngd/advanced-ios10-training
refs/heads/master
T2E02/T2E02/CustomSegue.swift
apache-2.0
1
// // CustomSegue.swift // T2E02 // // Created by jngd on 23/01/2017. // Copyright © 2017 jngd. All rights reserved. // import UIKit class CustomSegue: UIStoryboardSegue { override func perform() { let source : UIViewController = self.source as UIViewController let destination : UIViewController = self.destination as UIViewController UIGraphicsBeginImageContext(source.view.bounds.size) source.view.layer.render(in: UIGraphicsGetCurrentContext()!) let sourceImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()! destination.view.layer.render(in: UIGraphicsGetCurrentContext()!) let destinationImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() let sourceImageView : UIImageView = UIImageView (image: sourceImage) let destinationImageView : UIImageView = UIImageView (image: destinationImage) source.view.addSubview(sourceImageView) source.view.addSubview(destinationImageView) destinationImageView.transform = CGAffineTransform(translationX: destinationImageView.frame.size.width, y: 0) UIView.animate(withDuration: 1.0, animations: { () in sourceImageView.transform = CGAffineTransform(translationX: -sourceImageView.frame.size.width, y: 0) destinationImageView.transform = CGAffineTransform(translationX: 0, y: 0) }, completion: { (finished) in source.present(destination, animated: false, completion: {() -> Void in sourceImageView.removeFromSuperview() destinationImageView.removeFromSuperview() }) }) } }
7f767f2ad4121ff68ddb5e5748254f72
35.47619
111
0.772846
false
false
false
false
Moonsownner/DearFace
refs/heads/master
DearFace/Pods/SwiftIconFont/SwiftIconFont/Classes/FontLoader.swift
mit
2
// // FontLoader.swift // SwiftIconFont // // Created by Sedat Ciftci on 18/03/16. // Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved. // import UIKit import CoreText class FontLoader: NSObject { class func loadFont(_ fontName: String) { let bundle = Bundle(for: FontLoader.self) var fontURL = URL(string: "") for filePath : String in bundle.paths(forResourcesOfType: "ttf", inDirectory: nil) { let filename = NSURL(fileURLWithPath: filePath).lastPathComponent! if filename.lowercased().range(of: fontName.lowercased()) != nil { fontURL = NSURL(fileURLWithPath: filePath) as URL } } do { let data = try Data(contentsOf: fontURL!) let provider = CGDataProvider(data: data as CFData) let font = CGFont.init(provider!) var error: Unmanaged<CFError>? if !CTFontManagerRegisterGraphicsFont(font, &error) { let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue()) let nsError = error!.takeUnretainedValue() as AnyObject as! NSError NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } } catch { } } }
c98f071739200d7690e30781d1aafc25
32.790698
168
0.599449
false
false
false
false
superpeteblaze/BikeyProvider
refs/heads/master
Code/Location/LocationProvider.swift
mit
1
// // Created by Pete Smith // http://www.petethedeveloper.com // // // License // Copyright © 2016-present Pete Smith // Released under an MIT license: http://opensource.org/licenses/MIT // import CoreLocation /** ### LocationProviderDelegate Location Provider delegate protocol */ public protocol LocationProviderDelegate { func retrieved(_ location: CLLocation) func accessDenied() #if os(iOS) @available(iOS 9, *) func retrieved(_ heading: CLHeading) #endif func locationAccess(_ isGranted: Bool) } /** Empty extension to make some delegate methods optional */ public extension LocationProviderDelegate { #if os(iOS) func retrieved(_ heading: CLHeading) {} #endif func locationAccess(_ isGranted: Bool){} } /** ### LocationProvider Provides location services such as current location, currect heading Messages are sent to the specified delegate */ final public class LocationProvider: NSObject, CLLocationManagerDelegate { // Singleton public static let sharedInstance = LocationProvider() // MARK: - Public properties public var delegate: LocationProviderDelegate? var requiredAccuracy: CLLocationAccuracy = 70 public var needsToRequestAccess: Bool { return CLLocationManager.authorizationStatus() == .notDetermined } // MARK: - Private properties fileprivate var locman = CLLocationManager() fileprivate var startTime: Date! fileprivate var trying = false fileprivate var updatingHeading = false // MARK: - Initialization fileprivate override init() { super.init() locman.delegate = self locman.desiredAccuracy = kCLLocationAccuracyBest #if os(iOS) locman.activityType = .fitness locman.pausesLocationUpdatesAutomatically = true #endif } // MARK: - Public Methods /** Request location access authorization */ public func requestAlwaysAuthorization() { #if os(iOS) locman.requestAlwaysAuthorization() #endif } /** Request location access authorization */ public func requestWhenInUseAuthorization() { #if os(iOS) locman.requestWhenInUseAuthorization() #endif } /** Get the current location Location is passed back to caller using the delegate */ public func getLocation(withAuthScope authScope: CLAuthorizationStatus) { if !determineStatus(withAuthScope: authScope) { delegate?.accessDenied() return } if trying { return } trying = true startTime = nil locman.startUpdatingLocation() } /** Stop all location based updates (location, heading) */ public func stopUpdates () { locman.stopUpdatingLocation() #if os(iOS) locman.stopUpdatingHeading() #endif updatingHeading = false trying = false startTime = nil } /** Get the current heading */ @available(iOS 9, *) public func getHeading() { #if os(iOS) if !CLLocationManager.headingAvailable() { return } if updatingHeading { return } self.locman.headingFilter = 5 self.locman.headingOrientation = .portrait self.locman.startUpdatingHeading() #endif updatingHeading = true } // MARK: - CLLocationManager Delegate public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { stopUpdates() delegate?.accessDenied() } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last, location.horizontalAccuracy > 0 && location.horizontalAccuracy < requiredAccuracy else { return } delegate?.retrieved(location) } #if os(iOS) @available(iOS 9, *) public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { self.delegate?.retrieved(newHeading) } #endif public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .authorizedAlways, .authorizedWhenInUse: delegate?.locationAccess(true) default: delegate?.locationAccess(false) } } // MARK: - Location helper methods fileprivate func determineStatus(withAuthScope authScope: CLAuthorizationStatus) -> Bool { let ok = CLLocationManager.locationServicesEnabled() if !ok { // System will display dialog prompting for location access return true } let status = CLLocationManager.authorizationStatus() switch status { case .authorizedAlways, .authorizedWhenInUse: return true case .notDetermined: #if os(iOS) if authScope == .authorizedWhenInUse { requestWhenInUseAuthorization() } else { requestAlwaysAuthorization() } #endif requestAlwaysAuthorization() return true case .restricted: delegate?.accessDenied() return false case .denied: delegate?.accessDenied() return false } } }
a07835e8be0f58ad1d6d26be5f94c0e7
25.313636
142
0.598549
false
false
false
false
alickbass/SweetRouter
refs/heads/master
SweetRouter/Router.swift
mit
1
// // Router.swift // SweetRouter // // Created by Oleksii on 17/03/2017. // Copyright © 2017 ViolentOctopus. All rights reserved. // import Foundation public struct Router<T: EndpointType>: URLRepresentable { public let environment: T.Environment public let route: T.Route public init(_ environment: T.Environment = T.current, at route: T.Route) { self.environment = environment self.route = route } public var components: URLComponents { var components = environment.components let route = self.route.route components.path = environment.value.defaultPath.with(route.path).pathValue components.queryItems = route.query?.queryItems components.fragment = route.fragment return components } } public protocol URLRepresentable { var components: URLComponents { get } var url: URL { get } } public extension URLRepresentable { public var url: URL { guard let url = components.url else { fatalError("URL components are not valid") } return url } } public protocol EndpointType { associatedtype Environment: EnvironmentType associatedtype Route: RouteType static var current: Environment { get } } public protocol RouteType { var route: URL.Route { get } } public protocol EnvironmentType: URLRepresentable { var value: URL.Env { get } } public extension EnvironmentType { public var components: URLComponents { var components = URLComponents() let environment = value components.scheme = environment.scheme.rawValue components.host = environment.host.hostString components.port = environment.port components.path = environment.defaultPath.pathValue return components } }
d5fa92121980aa235309be20fcd3cf53
24.816901
90
0.672122
false
false
false
false
tungvoduc/DTButtonMenuController
refs/heads/master
DTButtonMenuController/Classes/ButtonPositioningDriver.swift
mit
1
// // ButtonPositioningDriver.swift // Pods // // Created by Admin on 17/03/2017. // // import UIKit enum ButtonPositionDriverType { case Satellite case Arc } enum Position { case left case right case top case bottom } enum TouchPointPosition { case topLeft case topRight case bottomLeft case bottomRight case center } class ButtonPositioningDriver: NSObject { /// Automatically shrink the arc of buttons var shouldShrinkArc = true /// Number of buttons that will be displayed. var numberOfItems: Int var buttonAngle: Double /// Radius of button. var buttonRadius: CGFloat /// Positioning type var positioningType: ButtonPositionDriverType /// Arc var buttonsArc: Double = Double.pi / 2 + Double.pi / 6 /// Distance from touchPoint to a button var distance: CGFloat = 80.0 /// Allow the buttons and the distance from touchPoint to the button center to be scaled var scaleable: Bool = false /// Margin to the edge to the screen or the defined view var margin: CGFloat = 8.0 /// If not provide maxButtonsAngle, maxButtonsAngle will be automatically calculated by numberOfButtons, maxButtonsAngle = Pi/(numberOfButtons * 2) init(numberOfButtons: Int = 1, buttonRadius radius: CGFloat, buttonsAngle angle: Double = Double.pi/6, positioningType type: ButtonPositionDriverType = .Arc) { numberOfItems = numberOfButtons buttonRadius = radius buttonAngle = angle positioningType = type; super.init() } func positionsOfItemsInView(with size: CGSize, at touchPoint: CGPoint) -> [CGPoint] { var points = [CGPoint]() let fromAndToAngles = self.fromAngleAndToAngleInView(withSize: size, atPoint: touchPoint) let fromAngle = fromAndToAngles[0] let toAngle = fromAndToAngles[1] var startingAngle = 0.0 let difference = toAngle - fromAngle let sign = toAngle - fromAngle > 0 ? 1.0 : -1.0 var step = (buttonsArc * sign) / Double(numberOfItems - 1) if fabs(difference) > buttonsArc { startingAngle = difference > 0 ? (difference - buttonsArc) / 2 : (difference + buttonsArc) / 2 } if fabs(difference) < buttonsArc { if (shouldShrinkArc) { step = fabs(difference) * sign / Double(numberOfItems - 1) } } for i in 0 ..< numberOfItems { let angle = step * Double(i) + fromAngle + startingAngle; let x = touchPoint.x + (distance + buttonRadius) * CGFloat(cos(angle)) let y = touchPoint.y + (distance + buttonRadius) * CGFloat(sin(angle)) let point = CGPoint(x: x, y: y) points.append(point) } return points } private func fromAngleAndToAngleInView(withSize size: CGSize, atPoint point: CGPoint) -> [Double] { var fromAngle = 0.0; var toAngle = 0.0; if (positioningType == .Satellite) { fromAngle = 0.0; toAngle = Double.pi * 2; } else { if (buttonsArc > Double.pi * 2) { fromAngle = (buttonsArc - Double.pi) / 2 toAngle = fromAngle - buttonsArc } else { fromAngle = -(Double.pi - buttonsArc) / 2 toAngle = -(Double.pi - abs(fromAngle)) } } let outerRadius: CGFloat = distance + buttonRadius * 2 + margin; let touchPointInset = self.distanceOfTouchPointToEdges(touchPoint: point, inViewWithSize: size) let touchPointPosition = self.touchPointPositionInView(withSize: size, touchPoint: point) // This version prioritises to display the buttons to the TOP therefore it does not check touchPointInset.bottom > outerRadius if (touchPointInset.top > outerRadius && touchPointInset.left > outerRadius && touchPointInset.right > outerRadius) { return [fromAngle, toAngle] } if (touchPointInset.top < outerRadius && touchPointInset.left > outerRadius && touchPointInset.right > outerRadius) { return [-fromAngle, -toAngle] } if (touchPointInset.top > outerRadius && touchPointInset.bottom > outerRadius && touchPointInset.left < touchPointInset.right) { return [-(Double.pi / 2 + fromAngle), (Double.pi / 2 + fromAngle)] } if (touchPointInset.top > outerRadius && touchPointInset.bottom > outerRadius && touchPointInset.left > touchPointInset.right) { return [(Double.pi / 2 + fromAngle) - Double.pi, (Double.pi / 2 + fromAngle) - Double.pi - buttonsArc] } let thresholdPoints = self.thresholdPointsOfButtonsArcInView(withSize: size, atTouchPoint: point); let firstPoint = thresholdPoints[0]; let secondPoint = thresholdPoints[1]; var firstAngle: Double = (Double)(self.angleBetweenHorizontalLineAndLineHasCenterPointAndAnotherPoint(centerPoint: point, anotherPoint: firstPoint)) var secondAngle: Double = (Double)(self.angleBetweenHorizontalLineAndLineHasCenterPointAndAnotherPoint(centerPoint: point, anotherPoint: secondPoint)) if (firstAngle > secondAngle) { let temp = secondAngle secondAngle = firstAngle firstAngle = temp } if touchPointPosition == .topLeft || touchPointPosition == .bottomLeft { //secondAngle = secondAngle < 0 ? Double.pi + fabs(Double.pi - fabs(secondAngle)) : secondAngle } else if touchPointPosition == .topRight || touchPointPosition == .bottomRight { secondAngle = secondAngle > 0 ? -(Double.pi * 2 - secondAngle) : secondAngle; } return [firstAngle, secondAngle]; } private func touchPointPositionInView(withSize size: CGSize, touchPoint:CGPoint) -> TouchPointPosition { let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) let centerPoint = CGPoint(x: size.width/2 + rect.origin.x, y: size.height/2 + rect.origin.y) var touchPosition: TouchPointPosition = .center if touchPoint.x <= centerPoint.x && touchPoint.y <= centerPoint.y { touchPosition = .topLeft } if touchPoint.x >= centerPoint.x && touchPoint.y <= centerPoint.y { touchPosition = .topRight } if touchPoint.x <= centerPoint.x && touchPoint.y >= centerPoint.y { touchPosition = .bottomLeft } if touchPoint.x >= centerPoint.x && touchPoint.y >= centerPoint.y { touchPosition = .bottomRight } return touchPosition } private func thresholdPointsOfButtonsArcInView(withSize size: CGSize, atTouchPoint point: CGPoint) -> [CGPoint] { let marginX: CGFloat = margin; let marginY: CGFloat = margin; let arcRadius: CGFloat = distance + buttonRadius * 2 + margin; let touchPointInset = self.distanceOfTouchPointToEdges(touchPoint: point, inViewWithSize: size) let touchPointPosition = self.touchPointPositionInView(withSize: size, touchPoint: point) var fromPointOffsetXSign: CGFloat = 1 var fromPointOffsetYSign: CGFloat = 1 var toPointOffsetXSign: CGFloat = 1 var toPointOffsetYSign: CGFloat = 1 switch touchPointPosition { case .topLeft: fromPointOffsetXSign = touchPointInset.top >= arcRadius ? -1 : 1 fromPointOffsetYSign = marginY + buttonRadius >= touchPointInset.top ? -1 : 1 toPointOffsetXSign = 1 toPointOffsetYSign = 1 case .topRight: fromPointOffsetXSign = touchPointInset.top >= arcRadius ? 1 : -1 fromPointOffsetYSign = marginY + buttonRadius >= touchPointInset.top ? -1 : 1 toPointOffsetXSign = -1 toPointOffsetYSign = 1 case .bottomLeft: fromPointOffsetXSign = touchPointInset.bottom >= arcRadius ? -1 : 1 fromPointOffsetYSign = marginY + buttonRadius >= touchPointInset.bottom ? 1 : -1 toPointOffsetXSign = 1 toPointOffsetYSign = -1 case .bottomRight: fromPointOffsetXSign = touchPointInset.bottom >= arcRadius ? 1 : -1 fromPointOffsetYSign = marginY + buttonRadius >= touchPointInset.bottom ? 1 : -1 toPointOffsetXSign = -1 toPointOffsetYSign = -1 default: fromPointOffsetXSign = -1 fromPointOffsetYSign = -1 toPointOffsetXSign = 1 toPointOffsetYSign = -1 } let closestHorizontalDistanceToEdge = touchPointInset.left > touchPointInset.right ? touchPointInset.right : touchPointInset.left let closestVerticalDistanceToEdge = touchPointInset.top > touchPointInset.bottom ? touchPointInset.bottom : touchPointInset.top let offsetX: CGFloat = sqrt(pow(arcRadius, 2) - pow(max(abs((closestHorizontalDistanceToEdge - (marginX + buttonRadius))), (marginX + buttonRadius)), 2)) let offsetY: CGFloat = sqrt(pow(arcRadius, 2) - pow(max(abs((closestVerticalDistanceToEdge - (marginY + buttonRadius))), (marginY + buttonRadius)), 2)) let baseFromPointX = point.x; let baseFromPointY = touchPointPosition == .topLeft || touchPointPosition == .topRight ? 0.0 : size.height; let baseToPointX = touchPointPosition == .topLeft || touchPointPosition == .bottomLeft ? 0.0 : size.width; let baseToPointY = point.y; let fromPoint: CGPoint = CGPoint(x: baseFromPointX + fromPointOffsetXSign * offsetX, y: baseFromPointY + (marginY + buttonRadius) * fromPointOffsetYSign) let toPoint: CGPoint = CGPoint(x:baseToPointX + (marginX + buttonRadius) * toPointOffsetXSign, y: baseToPointY + toPointOffsetYSign * offsetY) return [fromPoint, toPoint] } private func distanceOfTouchPointToEdges(touchPoint point: CGPoint, inViewWithSize size: CGSize) -> UIEdgeInsets { var edgeInsets : UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) edgeInsets.top = point.y edgeInsets.bottom = size.height - edgeInsets.top edgeInsets.left = point.x edgeInsets.right = size.width - point.x return edgeInsets } private func angleBetweenHorizontalLineAndLineHasCenterPointAndAnotherPoint(centerPoint: CGPoint, anotherPoint: CGPoint) -> CGFloat { let sign: CGFloat = anotherPoint.y < centerPoint.y ? -1 : 1 let isObstubeAngle: Bool = anotherPoint.x < centerPoint.x ? true : false let horizontalLength = fabs(centerPoint.x - anotherPoint.x) let verticalLength = fabs(centerPoint.y - anotherPoint.y) var angle = atan(verticalLength/horizontalLength) if isObstubeAngle { angle = ((CGFloat)(Double.pi) - angle) * sign } else { angle = angle * sign } return angle } }
b7492071626659f3cfd0dcc56990c60f
39.621429
163
0.620802
false
false
false
false
Ivacker/swift
refs/heads/master
test/Parse/errors.swift
apache-2.0
10
// RUN: %target-parse-verify-swift enum MSV : ErrorType { case Foo, Bar, Baz case CarriesInt(Int) var domain: String { return "" } var code: Int { return 0 } } func opaque_error() -> ErrorType { return MSV.Foo } func one() { do { true ? () : throw opaque_error() // expected-error {{expected expression after '? ... :' in ternary expression}} } catch _ { } do { } catch { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} let error2 = error } do { } catch where true { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} let error2 = error } catch { } // <rdar://problem/20985280> QoI: improve diagnostic on improper pattern match on type do { throw opaque_error() } catch MSV { // expected-error {{'is' keyword required to pattern match against type name}} {{11-11=is }} } catch { } do { throw opaque_error() } catch is ErrorType { // expected-warning {{'is' test is always true}} } } func takesAutoclosure(@autoclosure fn : () -> Int) {} func takesThrowingAutoclosure(@autoclosure fn : () throws -> Int) {} func genError() throws -> Int { throw MSV.Foo } func genNoError() -> Int { return 0 } func testAutoclosures() throws { takesAutoclosure(genError()) // expected-error {{call can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}} takesAutoclosure(genNoError()) try takesAutoclosure(genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}} try takesAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesAutoclosure(try genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}} takesAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesThrowingAutoclosure(try genError()) takesThrowingAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} try takesThrowingAutoclosure(genError()) try takesThrowingAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesThrowingAutoclosure(genError()) // expected-error {{call can throw but is not marked with 'try'}} takesThrowingAutoclosure(genNoError()) } struct IllegalContext { var x: Int = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} func foo(x: Int = genError()) {} // expected-error {{call can throw, but errors cannot be thrown out of a default argument}} func catcher() throws { do { try genError() } catch MSV.CarriesInt(genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch pattern}} } catch MSV.CarriesInt(let i) where i == genError() { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} } } } func illformed() throws { do { try genError() // TODO: this recovery is terrible } catch MSV.CarriesInt(let i) where i == genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} expected-error {{expected '{'}} expected-error {{braced block of statements is an unused closure}} expected-error {{expression resolves to an unused function}} } } func postThrows() -> Int throws { // expected-error{{'throws' may only occur before '->'}}{{19-19=throws }}{{25-32=}} return 5 } func postRethrows(f: () throws -> Int) -> Int rethrows { // expected-error{{'rethrows' may only occur before '->'}}{{40-40=rethrows }}{{46-55=}} return try f() } // rdar://21328447 func fixitThrow0() throw {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}} func fixitThrow1() throw -> Int {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}} func fixitThrow2() throws { var _: (Int) throw MSV.Foo var _: Int throw -> Int // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{14-19=throws}} }
f49f8e16529bc63b545771a52b27146a
38.444444
316
0.687089
false
false
false
false
adamnemecek/AudioKit
refs/heads/main
Sources/AudioKit/MIDI/Listeners/MIDIOmniListener.swift
mit
1
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ #if !os(tvOS) import Foundation import CoreMIDI /// This class probably needs to support observers as well /// so that a client may be able to be notified of state changes public class MIDIOMNIListener: NSObject { var omniMode: Bool /// Initialize with omni mode /// - Parameter omni: Omni mode activate public init(omni: Bool = true) { omniMode = omni } } // MARK: - MIDIOMNIListener should be used as an MIDIListener extension MIDIOMNIListener: MIDIListener { /// Receive the MIDI note on event /// /// - Parameters: /// - noteNumber: MIDI Note number of activated note /// - velocity: MIDI Velocity (0-127) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive the MIDI note off event /// /// - Parameters: /// - noteNumber: MIDI Note number of released note /// - velocity: MIDI Velocity (0-127) usually speed of release, often 0. /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDINoteOff(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive a generic controller value /// /// - Parameters: /// - controller: MIDI Controller Number /// - value: Value of this controller /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDIController(_ controller: MIDIByte, value: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { if controller == MIDIControl.omniModeOff.rawValue { guard omniMode == true else { return } omniMode = false omniStateChange() } if controller == MIDIControl.omniModeOn.rawValue { guard omniMode == false else { return } omniMode = true omniStateChange() } } /// Receive single note based aftertouch event /// /// - Parameters: /// - noteNumber: Note number of touched note /// - pressure: Pressure applied to the note (0-127) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDIAftertouch(noteNumber: MIDINoteNumber, pressure: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive global aftertouch /// /// - Parameters: /// - pressure: Pressure applied (0-127) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp:MIDI Event TimeStamp /// public func receivedMIDIAftertouch(_ pressure: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive pitch wheel value /// /// - Parameters: /// - pitchWheelValue: MIDI Pitch Wheel Value (0-16383) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp: MIDI Event TimeStamp /// public func receivedMIDIPitchWheel(_ pitchWheelValue: MIDIWord, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive program change /// /// - Parameters: /// - program: MIDI Program Value (0-127) /// - channel: MIDI Channel (1-16) /// - portID: MIDI Unique Port ID /// - timeStamp:MIDI Event TimeStamp /// public func receivedMIDIProgramChange(_ program: MIDIByte, channel: MIDIChannel, portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// Receive a MIDI system command (such as clock, SysEx, etc) /// /// - data: Array of integers /// - portID: MIDI Unique Port ID /// - offset: MIDI Event TimeStamp /// public func receivedMIDISystemCommand(_ data: [MIDIByte], portID: MIDIUniqueID? = nil, timeStamp: MIDITimeStamp? = nil) { // Do nothing } /// MIDI Setup has changed public func receivedMIDISetupChange() { // Do nothing } /// MIDI Object Property has changed public func receivedMIDIPropertyChange(propertyChangeInfo: MIDIObjectPropertyChangeNotification) { // Do nothing } /// Generic MIDI Notification public func receivedMIDINotification(notification: MIDINotification) { // Do nothing } /// OMNI State Change - override in subclass public func omniStateChange() { // override in subclass? } } #endif
39676ead41ba2e4b1a977dd6e9f3242a
34.423729
102
0.518022
false
false
false
false
debugsquad/Hyperborea
refs/heads/master
Hyperborea/Model/Search/MSearchEntryNumber.swift
mit
1
import UIKit class MSearchEntryNumber { private static let kBreak:String = "\n" private static let kSeparator:String = ", " private static let kKeyEntries:String = "entries" private static let kKeyGrammaticalFeatures:String = "grammaticalFeatures" private static let kKeyType:String = "type" private static let kKeyText:String = "text" private static let kTypeNumber:String = "Number" private static let kNumberFontSize:CGFloat = 14 class func parse(json:Any) -> NSAttributedString? { guard let jsonMap:[String:Any] = json as? [String:Any], let jsonEntries:[Any] = jsonMap[kKeyEntries] as? [Any] else { return nil } var numbers:[String] = [] let mutableString:NSMutableAttributedString = NSMutableAttributedString() let attributes:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:kNumberFontSize), NSForegroundColorAttributeName:UIColor.black] let stringBreak:NSAttributedString = NSAttributedString( string:kBreak, attributes:attributes) let stringSeparator:NSAttributedString = NSAttributedString( string:kSeparator, attributes:attributes) for jsonEntry:Any in jsonEntries { guard let jsonEntryMap:[String:Any] = jsonEntry as? [String:Any], let jsonFeatures:[Any] = jsonEntryMap[ kKeyGrammaticalFeatures] as? [Any] else { continue } for jsonFeature:Any in jsonFeatures { guard let featureMap:[String:Any] = jsonFeature as? [String:Any], let featureMapType:String = featureMap[kKeyType] as? String, let featureMapText:String = featureMap[kKeyText] as? String else { continue } if featureMapType == kTypeNumber { let numberLowerCase:String = featureMapText.lowercased() var append:Bool = true for number:String in numbers { if number == numberLowerCase { append = false break } } if append { numbers.append(numberLowerCase) if mutableString.string.isEmpty { mutableString.append(stringBreak) } else { mutableString.append(stringSeparator) } let numberString:NSAttributedString = NSAttributedString( string:numberLowerCase, attributes:attributes) mutableString.append(numberString) } } } } return mutableString } }
c8eb79c17117887594330e12a90d5b8e
32.952381
81
0.453857
false
false
false
false
IngmarStein/swift
refs/heads/master
test/SILGen/objc_extensions.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_extensions_helper class Sub : Base {} extension Sub { override var prop: String! { didSet { // Ignore it. } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC15objc_extensions3Subg4propGSQSS_ // CHECK: = super_method [volatile] %1 : $Sub, #Base.prop!setter.1.foreign // CHECK: = function_ref @_TFC15objc_extensions3SubW4propGSQSS_ // CHECK: } } func foo() { } override func objCBaseMethod() {} } // CHECK-LABEL: sil hidden @_TF15objc_extensions20testOverridePropertyFCS_3SubT_ func testOverrideProperty(_ obj: Sub) { // CHECK: = class_method [volatile] %0 : $Sub, #Sub.prop!setter.1.foreign : (Sub) -> (String!) -> () obj.prop = "abc" } // CHECK: } testOverrideProperty(Sub()) // CHECK-LABEL: sil shared [thunk] @_TFC15objc_extensions3Sub3fooFT_T_ // CHECK: function_ref @_TTDFC15objc_extensions3Sub3foofT_T_ // CHECK: sil shared [transparent] [thunk] @_TTDFC15objc_extensions3Sub3foofT_T_ // CHECK: class_method [volatile] %0 : $Sub, #Sub.foo!1.foreign func testCurry(_ x: Sub) { _ = x.foo } extension Sub { var otherProp: String { get { return "hello" } set { } } } class SubSub : Sub { // CHECK-LABEL: sil hidden @_TFC15objc_extensions6SubSub14objCBaseMethodfT_T_ // CHECK: super_method [volatile] %0 : $SubSub, #Sub.objCBaseMethod!1.foreign : (Sub) -> () -> () , $@convention(objc_method) (Sub) -> () override func objCBaseMethod() { super.objCBaseMethod() } } extension SubSub { // CHECK-LABEL: sil hidden @_TFC15objc_extensions6SubSubs9otherPropSS // CHECK: = super_method [volatile] %1 : $SubSub, #Sub.otherProp!getter.1.foreign // CHECK: = super_method [volatile] %1 : $SubSub, #Sub.otherProp!setter.1.foreign override var otherProp: String { didSet { // Ignore it. } } } // SR-1025 extension Base { fileprivate static var x = 1 } // CHECK-LABEL: sil hidden @_TF15objc_extensions19testStaticVarAccessFT_T_ func testStaticVarAccess() { // CHECK: [[F:%.*]] = function_ref @_TFE15objc_extensionsCSo4BaseauP33_1F05E59585E0BB585FCA206FBFF1A92D1xSi // CHECK: [[PTR:%.*]] = apply [[F]]() // CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]] _ = Base.x }
78393b4a552c9d38ece3cf68b91fdacd
28.5875
138
0.660752
false
true
false
false
louisdh/microcontroller-kit
refs/heads/master
Sources/MicrocontrollerKit/Nibble.swift
mit
1
// // Nibble.swift // MicrocontrollerKit // // Created by Louis D'hauwe on 14/08/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import Foundation /// 4 bits public struct Nibble: Hashable { public let b0: Bit public let b1: Bit public let b2: Bit public let b3: Bit public init(b0: Bit, b1: Bit, b2: Bit, b3: Bit) { self.b0 = b0 self.b1 = b1 self.b2 = b2 self.b3 = b3 } } extension Nibble: CustomStringConvertible { public var description: String { return "\(b3)\(b2)\(b1)\(b0)" } } extension Nibble: Comparable { public static func <(lhs: Nibble, rhs: Nibble) -> Bool { return lhs.decimalValue < rhs.decimalValue } } public extension Nibble { var decimalValue: Int { return 1 * b0.rawValue + 2 * b1.rawValue + 4 * b2.rawValue + 8 * b3.rawValue } } public extension Nibble { static func + (lhs: Nibble, rhs: Nibble) -> (out: Nibble, c: Bit) { let (s0, c0) = halfAdder(a: lhs.b0, b: rhs.b0) let (s1, c1) = fullAdder(a: lhs.b1, b: rhs.b1, cIn: c0) let (s2, c2) = fullAdder(a: lhs.b2, b: rhs.b2, cIn: c1) let (s3, c3) = fullAdder(a: lhs.b3, b: rhs.b3, cIn: c2) let s = Nibble(b0: s0, b1: s1, b2: s2, b3: s3) return (s, c3) } }
06cb7ed573de8d500d8907d3e537a7a3
17.257576
78
0.624896
false
false
false
false
crash-wu/CSRefresher
refs/heads/master
MyViewController.swift
mit
1
// // MyViewController.swift // CSRefresh // // Created by 吴小星 on 16/6/5. // Copyright © 2016年 crash. All rights reserved. // import UIKit class MyViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var tableView : UITableView? var count : Int = 10 override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height), style: .Plain) tableView?.dataSource = self tableView?.delegate = self self.view.addSubview(tableView!) tableView?.autoresizingMask = [.FlexibleHeight,.FlexibleWidth] tableView?.separatorStyle = .None tableView?.dropDownToRefresh({ (_) in dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { [weak self] in self?.tableView?.header?.endRefreshing() } }) tableView?.headerPullToRefreshText = "下拉刷新" tableView?.headerReleaseToRefreshText = "松开马上刷新" tableView?.headerRefreshingText = "正在加载..." tableView?.pullUpToRefresh ({ (_) in dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { [weak self] in self?.count = (self?.count)! + 10 self?.tableView?.reloadData() self?.tableView?.footer?.endRefreshing() } }) tableView?.footerPullToRefreshText = "上拉加载更多" tableView?.footerReleaseToRefreshText = "重开马上加载" tableView?.footerRefreshingText = "正在加载..." } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellID = "cellID" var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? Cell if cell == nil{ cell = Cell(style: .Default, reuseIdentifier: cellID) } cell?.label.text = "测试单元格:\(indexPath.row)" return cell! } }
f234497f119933ea2f9e16558bc6c807
28.409091
137
0.576121
false
false
false
false
devios1/Gravity
refs/heads/master
Plugins/Default.swift
mit
1
// // Default.swift // Gravity // // Created by Logan Murray on 2016-02-15. // Copyright © 2016 Logan Murray. All rights reserved. // import Foundation // do we really need/want this class? maybe rename? @available(iOS 9.0, *) extension Gravity { @objc public class Default: GravityPlugin { // private static let keywords = ["id", "zIndex", "gravity"] // add more? move? // TODO: these should ideally be blocked at the same location they are used (e.g. zIndex and gravity in Layout, id should be blocked in the kernel. var defaultValues = [GravityNode: [String: AnyObject?]]() // when should we purge this? // deprecated // public override var recognizedAttributes: [String]? { // get { // return nil // all attributes // } // } static var swizzleToken: dispatch_once_t = 0 // we should abstract this to a function in core that just swaps two selectors on a class like swizzle(UIView.self, selector1, selector2) public override class func initialize() { dispatch_once(&swizzleToken) { // method swizzling: let loadView_orig = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.loadView)) let loadView_swiz = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.grav_loadView)) if class_addMethod(UIViewController.self, #selector(UIViewController.loadView), method_getImplementation(loadView_swiz), method_getTypeEncoding(loadView_swiz)) { class_replaceMethod(UIViewController.self, #selector(UIViewController.grav_loadView), method_getImplementation(loadView_orig), method_getTypeEncoding(loadView_orig)); } else { method_exchangeImplementations(loadView_orig, loadView_swiz); } } } public override func instantiateView(node: GravityNode) -> UIView? { var type: AnyClass? = NSClassFromString(node.nodeName) if type == nil { // couldn't find type; try Swift style naming if let appName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String { type = NSClassFromString("\(appName).\(node.nodeName)") } } if let type = type as? GravityElement.Type where type.instantiateView != nil { return type.instantiateView!(node) } else if let type = type as? UIView.Type { // var view: UIView // tryBlock { let view = type.init() view.translatesAutoresizingMaskIntoConstraints = false // do we need this? i think so // TODO: should we set clipsToBounds for views by default? // } return view // TODO: determine if the instance is an instance of UIView or UIViewController and handle the latter by embedding a view controller } else if let type = type as? UIViewController.Type { let vc = type.init() vc.gravityNode = node node.controller = vc // this might be a problem since node.view is not set at this point (dispatch_async?) // FIXME: there is a design issue here: accessing vc.view calls viewDidLoad on the vc; we should think of a way to avoid doing this until the very end, which may involve wrapping it in an extra view, or swizzling viewDidLoad return UIView() // this will be bound to the node; is a plain UIView enough? //node._view = vc.view // let container = UIView() // container.addSu } return nil } public override func selectAttribute(node: GravityNode, attribute: String, inout value: GravityNode?) -> GravityResult { value = node.attributes[attribute] // good? return .Handled } // this is really a singleton; should we provide a better way for this to be overridden? // we should turn this into processValue() public override func handleAttribute(node: GravityNode, attribute: String?, value: GravityNode?) -> GravityResult { // guard let node = value.parentNode else { // return .NotHandled // } guard let attribute = attribute else { return .NotHandled } // NSLog("KeyPath \(attribute) converted var objectValue: AnyObject? if value != nil { objectValue = value!.objectValue tryBlock { if self.defaultValues[node] == nil { self.defaultValues[node] = [String: AnyObject?]() } if self.defaultValues[node]![attribute] == nil { // only store the default value the first time (so it is deterministic) let defaultValue = node.view.valueForKeyPath(attribute) self.defaultValues[node]![attribute] = defaultValue } } } else { if let nodeIndex = defaultValues[node] { if let defaultValue = nodeIndex[attribute] { NSLog("Default value found for attribute \(attribute): \(defaultValue)") objectValue = defaultValue } } } if let objectValue = objectValue { if tryBlock({ NSLog("Setting property \(attribute) to value: \(objectValue)") node.view.setValue(objectValue, forKeyPath: attribute) }) != nil { NSLog("Warning: Key path '\(attribute)' not found on object \(node.view).") return .NotHandled } } else { return .NotHandled } return .Handled } // public override func postprocessValue(node: GravityNode, attribute: String, value: GravityNode) -> GravityResult { // // TODO: if value is a node, check property type on target and potentially convert into a view (view controller?) // // var propertyType: String? = nil // // // this is string.endsWith in swift. :| lovely. // if attribute.lowercaseString.rangeOfString("color", options:NSStringCompareOptions.BackwardsSearch)?.endIndex == attribute.endIndex { // propertyType = "UIColor" // bit of a hack because UIView.backgroundColor doesn't seem to know its property class via inspection :/ // } // // if propertyType == nil { //// NSLog("Looking up property for \(node.view.dynamicType) . \(attribute)") // // is there a better/safer way to do this reliably? // let property = class_getProperty(NSClassFromString("\(node.view.dynamicType)"), attribute) // if property != nil { // if let components = String.fromCString(property_getAttributes(property))?.componentsSeparatedByString("\"") { // if components.count >= 2 { // propertyType = components[1] //// NSLog("propertyType: \(propertyType!)") // } // } // } // } // // var convertedValue: AnyObject? = value.stringValue // // if let propertyType = propertyType { // convertedValue = value.convert(propertyType) //// if let converter = Conversion.converters[propertyType!] { //// var newOutput: AnyObject? = output //// if converter(input: input, output: &newOutput) == .Handled { //// output = newOutput! // this feels ugly //// return .Handled //// } //// } // } // //// NSLog("KeyPath \(attribute) converted // // if tryBlock({ // node.view.setValue(convertedValue, forKeyPath: attribute) // }) != nil { // NSLog("Warning: Key path '\(attribute)' not found on object \(node.view).") // } // } // public override func postprocessElement(node: GravityNode) -> GravityResult { // } } } @available(iOS 9.0, *) extension UIViewController { public func grav_loadView() { if self.gravityNode != nil { self.view = self.gravityNode?.view // TODO: make sure this works for all levels of embedded VCs } if !self.isViewLoaded() { grav_loadView() } } }
1c2dfd216697c731ab99d86b8aee0bae
36.19898
228
0.676955
false
false
false
false
nab0y4enko/PrettyFloatingMenuView
refs/heads/master
Example/ViewController.swift
mit
1
// // ViewController.swift // Example // // Created by Oleksii Naboichenko on 5/11/17. // Copyright © 2017 Oleksii Naboichenko. All rights reserved. // import UIKit import PrettyFloatingMenuView class ViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var menuView: PrettyFloatingMenuView! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() prepareMenuView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // toggle test menuView.toggle() DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in guard let strongSelf = self else { return } strongSelf.menuView.toggle() } } // MARK: - Private Instance Methods private func prepareMenuView() { let firstItemView = PrettyFloatingMenuItemView() firstItemView.title = NSAttributedString(string: "Test Item 1") firstItemView.iconImage = UIImage(named: "community-icon") firstItemView.action = { (item) in print(item.title!.string) } let secondItemView = PrettyFloatingMenuItemView() secondItemView.title = NSAttributedString(string: "Test Item 2") secondItemView.iconImage = UIImage(named: "trophy-icon") secondItemView.action = { (item) in print(item.title!.string) } let thirdItemView = PrettyFloatingMenuItemView() thirdItemView.title = NSAttributedString(string: "Test Item 3") thirdItemView.iconImage = UIImage(named: "alert-icon") thirdItemView.action = { (item) in print(item.title!.string) } let fourthItemView = PrettyFloatingMenuItemView() fourthItemView.title = NSAttributedString(string: "Test Item 4") fourthItemView.iconImage = UIImage(named: "community-icon") fourthItemView.action = { (item) in print(item.title!.string) } fourthItemView.titleVerticalPosition = .top let fifthItemView = PrettyFloatingMenuItemView() fifthItemView.title = NSAttributedString(string: "Test Item 5") fifthItemView.iconImage = UIImage(named: "trophy-icon") fifthItemView.action = { (item) in print(item.title!.string) } fifthItemView.titleVerticalPosition = .top menuView.itemViews = [firstItemView, secondItemView, thirdItemView, fourthItemView, fifthItemView] // menuView.itemViews = [firstItemView] menuView.setImage(UIImage(named: "menu-icon"), forState: .closed) menuView.setImage(UIImage(named: "close-icon"), forState: .opened) menuView.setImageTintColor(UIColor.red, forState: .opened) menuView.setBackgroundColor(UIColor.yellow, forState: .closed) menuView.setBackgroundColor(UIColor.blue, forState: .opened) menuView.setOverlayColor(UIColor.green.withAlphaComponent(0.5), forState: .opened) menuView.animator = PrettyFloatingMenuRoundSlideAnimator() } }
b075615cc89d1f61513a5dbb583dfc93
34.897727
106
0.646724
false
true
false
false
juangrt/SwiftImageUploader
refs/heads/master
SwiftImageUploader/PhotoShareService.swift
gpl-3.0
1
// // Uploader.swift // SwiftImageUploader // // Created by Juan Carlos Garzon on 6/22/16. // Copyright © 2016 ZongWare. All rights reserved. // import Foundation import UIKit import Alamofire //Make this a singleton class class PhotoShareService { static let sharedInstance = PhotoShareService() enum SegmentType { case PARTY ,MEDIA , USER } func segment(type:SegmentType) -> String { switch type { case SegmentType.PARTY: return "party" case SegmentType.MEDIA: return "media" case SegmentType.USER: return "user" } } func segmentUpload(type:SegmentType) -> String { switch type { case SegmentType.PARTY: return "headerImage" case SegmentType.MEDIA: return "mediaImage" case SegmentType.USER: return "profileImage" } } private func segmentCreate(type:SegmentType) -> [String] { var createParams = [String]() switch type { case SegmentType.PARTY: createParams.append("title") createParams.append("slug") break case SegmentType.MEDIA: break case SegmentType.USER: break } createParams.append("meta") return createParams } func new(seg:SegmentType, image: UIImage, params:[String:String], completion: (result: AnyObject) -> Void) { let apiUrl:String = Config.sharedInstance.host + self.segment(seg) + "/new" let imageData:NSData! = UIImageJPEGRepresentation(image, 1.0) Alamofire.upload(.POST, apiUrl, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: imageData!, name: self.segmentUpload(seg), fileName: "upload.jpg" , mimeType: "image/jpg") for param in params { multipartFormData.appendBodyPart(data: param.1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name : param.0) } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .Failure(let encodingError): print(encodingError) } completion(result: "") }) } func get(seg:SegmentType, page:NSNumber , completion: (result: AnyObject) -> Void) { Alamofire.request(.GET , Config.sharedInstance.host + segment(seg)).responseJSON{ response in switch response.result { case .Success(let JSON): let partiesRaw = JSON completion(result: partiesRaw) case .Failure(let error): print("Request failed with error: \(error)") } } } func uploadFile(seg:SegmentType, image: UIImage) { let apiUrl:String = Config.sharedInstance.host + self.segment(seg) + "/new" //Add logic to upload right image representation let imageData:NSData! = UIImageJPEGRepresentation(image, 1.0) Alamofire.upload(.POST, apiUrl, multipartFormData: { multipartFormData in //Appends the image //To Do: Ensure proper mimeType multipartFormData.appendBodyPart(data: imageData!, name: self.segmentUpload(seg), fileName: "upload.jpg" , mimeType: "image/jpg") //To Do: Dynamic keys? multipartFormData.appendBodyPart(data:"India".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"name") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .Failure(let encodingError): print(encodingError) } }) } }
a90eb2edb91bf15a0730de46885d7025
32.503497
158
0.499165
false
false
false
false
programmerC/JNews
refs/heads/master
JNews/UILabel+Helpers.swift
gpl-3.0
1
// // UILabel+Helpers.swift // JNews // // Created by ChenKaijie on 16/7/23. // Copyright © 2016年 com.ckj. All rights reserved. // import UIKit import Foundation private var labelNumberKey : Void? private var labelTimerKey : Void? extension UILabel { public var labelNumber: NSNumber? { get { return objc_getAssociatedObject(self, &labelNumberKey) as? NSNumber } } private func setLabelNumber(number: NSNumber) { objc_setAssociatedObject(self, &labelNumberKey, number, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } public var labelTimer: NSTimer? { get { return objc_getAssociatedObject(self, &labelTimerKey) as? NSTimer } } private func setLabelTimer(timer: NSTimer) { objc_setAssociatedObject(self, &labelTimerKey, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private let BeginNumber = "BeginNumber" private let EndNumber = "EndNumber" private let RangeNumber = "RangeNumber" private let Attributes = "Attributes" private let frequency = 1.0/30.0 extension UILabel { public func setLabelText(text: String, duration: NSTimeInterval, delay: NSTimeInterval, attributed: AnyObject?) { // 使之前的Timer失效 self.labelTimer?.invalidate() // Duration 执行时间 var durationTime: NSTimeInterval = duration < 0.8 ? 0.8 : duration // 初始化 labelNumber self.setLabelNumber(NSNumber.init(int: 0)) let userDict: NSMutableDictionary = NSMutableDictionary() let beginNumber: NSNumber = 0 userDict.setValue(beginNumber, forKey: BeginNumber) let tempNumber = NSInteger(text) guard (tempNumber != nil) else { return } let endNumber = Int64(tempNumber!) guard endNumber < INT64_MAX else { return } userDict.setValue(NSNumber.init(longLong: endNumber), forKey: EndNumber) // 如果每次增长少于数字少于1,减少执行时间 if Double(endNumber)*frequency/durationTime < 1.0 { durationTime = durationTime*0.3 } // 数字滚动每次增长的数目 let rangeNumber = (Double(endNumber)*frequency)/durationTime userDict.setValue(NSNumber(double: rangeNumber), forKey: RangeNumber) if attributed != nil { userDict.setValue(attributed, forKey: Attributes) } // Delay 延时 Delay(delay) { self.setLabelTimer(NSTimer.scheduledTimerWithTimeInterval(frequency, target: self, selector: #selector(UILabel.labelAnimation(_:)), userInfo: userDict, repeats: true)) // 滑动状态和普通状态都执行timer NSRunLoop.currentRunLoop().addTimer(self.labelTimer!, forMode: NSRunLoopCommonModes) } } public func labelAnimation(timer: NSTimer) { if timer.userInfo?.valueForKey(RangeNumber)?.floatValue >= 1.0 { let rangeInteger = timer.userInfo?.valueForKey(RangeNumber)?.longLongValue; let resultInteger = (self.labelNumber?.longLongValue)! + rangeInteger!; self.setLabelNumber(NSNumber(longLong: resultInteger)) } else { let rangeInteger = timer.userInfo?.valueForKey(RangeNumber)?.floatValue; let resultInteger = (self.labelNumber?.floatValue)! + rangeInteger!; self.setLabelNumber(NSNumber(float: resultInteger)) } // 设置 Text let numberText = String.init(format: "%.6d", self.labelNumber!.integerValue) assert(numberText.characters.count == 6, "LabelNumber转换位数出错:\(numberText)") let numberTextString = NSMutableString.init(string: numberText) numberTextString.insertString("h ", atIndex: 2) numberTextString.insertString("m ", atIndex: 6) numberTextString.insertString("s ", atIndex: 10) self.text = numberTextString as String // 设置 Attributes let attributes = timer.userInfo?.valueForKey(Attributes) if attributes != nil { self.drawAttributes(attributes!) } let endNumber : NSNumber = timer.userInfo?.valueForKey(EndNumber) as! NSNumber if self.labelNumber?.longLongValue >= endNumber.longLongValue { // 大于当前时间 let resultNumber: NSNumber = timer.userInfo?.valueForKey(EndNumber) as! NSNumber let resultText = String.init(format: "%.6d", resultNumber.longLongValue) assert(resultText.characters.count == 6, "LabelNumber转换位数出错:\(numberText)") let resultTextString = NSMutableString.init(string: resultText) resultTextString.insertString("h ", atIndex: 2) resultTextString.insertString("m ", atIndex: 6) resultTextString.insertString("s ", atIndex: 10) self.text = resultTextString as String let attributes = timer.userInfo?.valueForKey(Attributes) if attributes != nil { self.drawAttributes(attributes!) } // 停止计时器 self.labelTimer?.invalidate() } } public func drawAttributes(attributes: AnyObject) -> Void { if attributes.isKindOfClass(NSDictionary) { let range = attributes.valueForKey("rangeValue")?.rangeValue let attribute = attributes.valueForKey("attributeValue") self.addAttributes(attribute!, range : range!) } else if attributes.isKindOfClass(NSArray) { for attribute in attributes as! NSArray { let range = attribute.valueForKey("rangeValue")?.rangeValue let attri = attribute.valueForKey("attributeValue") self.addAttributes(attri!, range : range!) } } } private func addAttributes(attributes: AnyObject, range: NSRange) -> Void { let attributedStr = NSMutableAttributedString(attributedString : self.attributedText!) if range.location + range.length < attributedStr.length { attributedStr.addAttributes(attributes as! [String : AnyObject], range: range) } self.attributedText = attributedStr; } }
6dee2e57e485c71960b1fd0c6bcfd9cf
38.012658
179
0.634269
false
false
false
false
vector-im/riot-ios
refs/heads/develop
Riot/Modules/Settings/IdentityServer/SettingsIdentityServerViewController.swift
apache-2.0
1
// File created from ScreenTemplate // $ createScreen.sh Test SettingsIdentityServer /* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class SettingsIdentityServerViewController: UIViewController { // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet weak var identityServerContainer: UIView! @IBOutlet weak var identityServerLabel: UILabel! @IBOutlet weak var identityServerTextField: UITextField! @IBOutlet private weak var messageLabel: UILabel! @IBOutlet weak var addOrChangeButtonContainer: UIView! @IBOutlet private weak var addOrChangeButton: UIButton! @IBOutlet weak var disconnectMessageLabel: UILabel! @IBOutlet weak var disconnectButtonContainer: UIView! @IBOutlet weak var disconnectButton: UIButton! // MARK: Private private var viewModel: SettingsIdentityServerViewModelType! private var theme: Theme! private var keyboardAvoider: KeyboardAvoider? private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var viewState: SettingsIdentityServerViewState? private var displayMode: SettingsIdentityServerDisplayMode? private weak var alertController: UIAlertController? private var serviceTermsModalCoordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter? private var serviceTermsModalCoordinatorBridgePresenterOnComplete: ((Bool) -> Void)? // MARK: - Setup class func instantiate(with viewModel: SettingsIdentityServerViewModelType) -> SettingsIdentityServerViewController { let viewController = StoryboardScene.SettingsIdentityServerViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = VectorL10n.identityServerSettingsTitle self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .load) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.keyboardAvoider?.startAvoiding() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.keyboardAvoider?.stopAvoiding() } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.identityServerContainer.backgroundColor = theme.backgroundColor self.identityServerLabel.textColor = theme.textPrimaryColor theme.applyStyle(onTextField: self.identityServerTextField) self.identityServerTextField.textColor = theme.textSecondaryColor self.messageLabel.textColor = theme.textPrimaryColor self.addOrChangeButtonContainer.backgroundColor = theme.backgroundColor theme.applyStyle(onButton: self.addOrChangeButton) self.disconnectMessageLabel.textColor = theme.textPrimaryColor self.disconnectButtonContainer.backgroundColor = theme.backgroundColor theme.applyStyle(onButton: self.disconnectButton) self.disconnectButton.setTitleColor(self.theme.warningColor, for: .normal) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { self.scrollView.keyboardDismissMode = .interactive self.identityServerLabel.text = VectorL10n.identityServerSettingsTitle self.identityServerTextField.placeholder = VectorL10n.identityServerSettingsPlaceHolder self.identityServerTextField.keyboardType = .URL self.identityServerTextField.addTarget(self, action: #selector(identityServerTextFieldDidChange(_:)), for: .editingChanged) self.identityServerTextField.addTarget(self, action: #selector(identityServerTextFieldDidEndOnExit(_:)), for: .editingDidEndOnExit) self.disconnectMessageLabel.text = VectorL10n.identityServerSettingsDisconnectInfo self.disconnectButton.setTitle(VectorL10n.identityServerSettingsDisconnect, for: .normal) self.disconnectButton.setTitle(VectorL10n.identityServerSettingsDisconnect, for: .highlighted) } private func render(viewState: SettingsIdentityServerViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(let displayMode): self.renderLoaded(displayMode: displayMode) case .presentTerms(let session, let accessToken, let baseUrl, let onComplete): self.presentTerms(session: session, accessToken: accessToken, baseUrl: baseUrl, onComplete: onComplete) case .alert(let alert, let onContinue): self.renderAlert(alert: alert, onContinue: onContinue) case .error(let error): self.render(error: error) } } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded(displayMode: SettingsIdentityServerDisplayMode) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.displayMode = displayMode switch displayMode { case .noIdentityServer: self.renderNoIdentityServer() case .identityServer(let host): self.renderIdentityServer(host: host) } } private func renderNoIdentityServer() { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.identityServerTextField.text = nil self.messageLabel.text = VectorL10n.identityServerSettingsNoIsDescription self.addOrChangeButton.setTitle(VectorL10n.identityServerSettingsAdd, for: .normal) self.addOrChangeButton.setTitle(VectorL10n.identityServerSettingsAdd, for: .highlighted) self.addOrChangeButton.isEnabled = false self.disconnectMessageLabel.isHidden = true self.disconnectButtonContainer.isHidden = true } private func renderIdentityServer(host: String) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.identityServerTextField.text = host self.messageLabel.text = VectorL10n.identityServerSettingsDescription(host.hostname()) self.addOrChangeButton.setTitle(VectorL10n.identityServerSettingsChange, for: .normal) self.addOrChangeButton.setTitle(VectorL10n.identityServerSettingsChange, for: .highlighted) self.addOrChangeButton.isEnabled = false self.disconnectMessageLabel.isHidden = false self.disconnectButtonContainer.isHidden = false } private func presentTerms(session: MXSession, accessToken: String, baseUrl: String, onComplete: @escaping (Bool) -> Void) { let serviceTermsModalCoordinatorBridgePresenter = ServiceTermsModalCoordinatorBridgePresenter(session: session, baseUrl: baseUrl, serviceType: MXServiceTypeIdentityService, accessToken: accessToken) serviceTermsModalCoordinatorBridgePresenter.present(from: self, animated: true) serviceTermsModalCoordinatorBridgePresenter.delegate = self self.serviceTermsModalCoordinatorBridgePresenter = serviceTermsModalCoordinatorBridgePresenter self.serviceTermsModalCoordinatorBridgePresenterOnComplete = onComplete } private func hideTerms(accepted: Bool) { guard let serviceTermsModalCoordinatorBridgePresenterOnComplete = self.serviceTermsModalCoordinatorBridgePresenterOnComplete else { return } self.serviceTermsModalCoordinatorBridgePresenter?.dismiss(animated: true, completion: nil) self.serviceTermsModalCoordinatorBridgePresenter = nil serviceTermsModalCoordinatorBridgePresenterOnComplete(accepted) self.serviceTermsModalCoordinatorBridgePresenterOnComplete = nil } private func renderAlert(alert: SettingsIdentityServerAlert, onContinue: @escaping () -> Void) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) switch alert { case .addActionAlert(.invalidIdentityServer(let newHost)), .changeActionAlert(.invalidIdentityServer(let newHost)): self.showAlert(title: nil, message: VectorL10n.identityServerSettingsAlertErrorInvalidIdentityServer(newHost), continueButtonTitle: nil, cancelButtonTitle: VectorL10n.cancel, onContinue: onContinue) case .addActionAlert(.noTerms), .changeActionAlert(.noTerms): self.showAlert(title: VectorL10n.identityServerSettingsAlertNoTermsTitle, message: VectorL10n.identityServerSettingsAlertNoTerms, continueButtonTitle: VectorL10n.continue, cancelButtonTitle: VectorL10n.cancel, onContinue: onContinue) case .addActionAlert(.termsNotAccepted(let newHost)), .changeActionAlert(.termsNotAccepted(let newHost)): self.showAlert(title: nil, message: VectorL10n.identityServerSettingsAlertErrorTermsNotAccepted(newHost.hostname()), continueButtonTitle: nil, cancelButtonTitle: VectorL10n.cancel, onContinue: onContinue) case .changeActionAlert(.stillSharing3Pids(let oldHost, _)): self.showAlert(title: VectorL10n.identityServerSettingsAlertChangeTitle, message: VectorL10n.identityServerSettingsAlertDisconnectStillSharing3pid(oldHost.hostname()), continueButtonTitle: VectorL10n.identityServerSettingsAlertDisconnectStillSharing3pidButton, cancelButtonTitle: VectorL10n.cancel, onContinue: onContinue) case .changeActionAlert(.doubleConfirmation(let oldHost, let newHost)): self.showAlert(title: VectorL10n.identityServerSettingsAlertChangeTitle, message: VectorL10n.identityServerSettingsAlertChange(oldHost.hostname(), newHost.hostname()), continueButtonTitle: VectorL10n.continue, cancelButtonTitle: VectorL10n.cancel, onContinue: onContinue) case .disconnectActionAlert(.stillSharing3Pids(let oldHost)): self.showAlert(title: VectorL10n.identityServerSettingsAlertDisconnectTitle, message: VectorL10n.identityServerSettingsAlertDisconnectStillSharing3pid(oldHost.hostname()), continueButtonTitle: VectorL10n.identityServerSettingsAlertDisconnectStillSharing3pidButton, cancelButtonTitle: VectorL10n.cancel, onContinue: onContinue) case .disconnectActionAlert(.doubleConfirmation(let oldHost)): self.showAlert(title: VectorL10n.identityServerSettingsAlertDisconnectTitle, message: VectorL10n.identityServerSettingsAlertDisconnect(oldHost.hostname()), continueButtonTitle: VectorL10n.identityServerSettingsAlertDisconnectButton, cancelButtonTitle: VectorL10n.cancel, onContinue: onContinue) } } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } // MARK: - Alert private func showAlert(title: String?, message: String, continueButtonTitle: String?, cancelButtonTitle: String, onContinue: @escaping () -> Void) { guard self.alertController == nil else { return } let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: cancelButtonTitle, style: .cancel, handler: { action in })) if let continueButtonTitle = continueButtonTitle { alertController.addAction(UIAlertAction(title: continueButtonTitle, style: .default, handler: { action in onContinue() })) } self.present(alertController, animated: true, completion: nil) self.alertController = alertController } private func hideAlert(animated: Bool) { self.alertController?.dismiss(animated: true, completion: nil) } // MARK: - Actions @objc private func identityServerTextFieldDidChange(_ textField: UITextField) { self.addOrChangeButton.isEnabled = textField.text?.count ?? 0 > 0 && (textField.text?.hostname() != self.viewModel.identityServer?.hostname()) } @objc private func identityServerTextFieldDidEndOnExit(_ textField: UITextField) { self.addOrChangeAction() } @IBAction private func addOrChangeButtonAction(_ sender: Any) { self.addOrChangeAction() } private func addOrChangeAction() { self.identityServerTextField.resignFirstResponder() guard let displayMode = self.displayMode, let identityServer = self.identityServerTextField.text else { return } let viewAction: SettingsIdentityServerViewAction? switch displayMode { case .noIdentityServer: viewAction = .add(identityServer: identityServer.makeURLValid()) case .identityServer: viewAction = .change(identityServer: identityServer.makeURLValid()) } if let viewAction = viewAction { self.viewModel.process(viewAction: viewAction) } } @IBAction private func disconnectButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .disconnect) } } // MARK: - SettingsIdentityServerViewModelViewDelegate extension SettingsIdentityServerViewController: SettingsIdentityServerViewModelViewDelegate { func settingsIdentityServerViewModel(_ viewModel: SettingsIdentityServerViewModelType, didUpdateViewState viewState: SettingsIdentityServerViewState) { self.viewState = viewState self.render(viewState: viewState) } } // MARK: - ServiceTermsModalCoordinatorBridgePresenterDelegate extension SettingsIdentityServerViewController: ServiceTermsModalCoordinatorBridgePresenterDelegate { func serviceTermsModalCoordinatorBridgePresenterDelegateDidAccept(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter) { self.hideTerms(accepted: true) } func serviceTermsModalCoordinatorBridgePresenterDelegateDidDecline(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter, session: MXSession) { self.hideTerms(accepted: false) } func serviceTermsModalCoordinatorBridgePresenterDelegateDidCancel(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter) { self.hideTerms(accepted: false) } } // MARK: - Private extension fileprivate extension String { func hostname() -> String { return URL(string: self)?.host ?? self } func makeURLValid() -> String { if self.hasPrefix("http://") || self.hasPrefix("https://") { return self } else { return "https://" + self } } }
5eaa82cef042d6d24cf924f24be3d383
40.915254
206
0.701115
false
false
false
false
EasySwift/EasySwift
refs/heads/master
BondTests/UIKitTests.swift
apache-2.0
3
// // BondTests.swift // BondTests // // Created by Srdan Rasic on 19/07/16. // Copyright © 2016 Swift Bond. All rights reserved. // import XCTest import ReactiveKit @testable import Bond class BondTests: XCTestCase { func testUIView() { let view = UIView() Signal1.just(UIColor.red).bind(to: view.bnd_backgroundColor) XCTAssertEqual(view.backgroundColor!, UIColor.red) Signal1.just(0.3).bind(to: view.bnd_alpha) XCTAssertEqual(view.alpha, 0.3) Signal1.just(true).bind(to: view.bnd_isHidden) XCTAssertEqual(view.isHidden, true) Signal1.just(true).bind(to: view.bnd_isUserInteractionEnabled) XCTAssertEqual(view.isUserInteractionEnabled, true) Signal1.just(UIColor.red).bind(to: view.bnd_tintColor) XCTAssertEqual(view.tintColor, UIColor.red) } func testUIActivityIndicatorView() { let subject = PublishSubject1<Bool>() let view = UIActivityIndicatorView() subject.bind(to: view.bnd_animating) XCTAssertEqual(view.isAnimating, false) subject.next(true) XCTAssertEqual(view.isAnimating, true) subject.next(false) XCTAssertEqual(view.isAnimating, false) } func testUIBarItem() { let view = UIBarButtonItem() Signal1.just("test").bind(to: view.bnd_title) XCTAssertEqual(view.title!, "test") let image = UIImage() Signal1.just(image).bind(to: view.bnd_image) XCTAssertEqual(view.image!, image) Signal1.just(true).bind(to: view.bnd_isEnabled) XCTAssertEqual(view.isEnabled, true) Signal1.just(false).bind(to: view.bnd_isEnabled) XCTAssertEqual(view.isEnabled, false) view.bnd_tap.expectNext([(), ()]) view.bnd_tap.expectNext([(), ()]) // second observer _ = view.target!.perform(view.action!) _ = view.target!.perform(view.action!) } func testUIButton() { let view = UIButton() Signal1.just("test").bind(to: view.bnd_title) XCTAssertEqual(view.titleLabel?.text, "test") Signal1.just(true).bind(to: view.bnd_isSelected) XCTAssertEqual(view.isSelected, true) Signal1.just(false).bind(to: view.bnd_isSelected) XCTAssertEqual(view.isSelected, false) Signal1.just(true).bind(to: view.bnd_isHighlighted) XCTAssertEqual(view.isHighlighted, true) Signal1.just(false).bind(to: view.bnd_isHighlighted) XCTAssertEqual(view.isHighlighted, false) view.bnd_tap.expectNext([(), ()]) view.sendActions(for: .touchUpInside) view.sendActions(for: .touchUpInside) view.sendActions(for: .touchUpOutside) } func testUIControl() { let view = UIControl() Signal1.just(true).bind(to: view.bnd_isEnabled) XCTAssertEqual(view.isEnabled, true) Signal1.just(false).bind(to: view.bnd_isEnabled) XCTAssertEqual(view.isEnabled, false) view.bnd_controlEvents(UIControlEvents.touchUpInside).expectNext([(), ()]) view.sendActions(for: .touchUpInside) view.sendActions(for: .touchUpOutside) view.sendActions(for: .touchUpInside) } func testUIDatePicker() { let date1 = Date(timeIntervalSince1970: 10) let date2 = Date(timeIntervalSince1970: 1000) let subject = PublishSubject1<Date>() let view = UIDatePicker() subject.bind(to: view) subject.next(date1) XCTAssertEqual(view.date, date1) subject.next(date2) XCTAssertEqual(view.date, date2) view.bnd_date.expectNext([date2, date1]) view.date = date1 view.sendActions(for: .valueChanged) } func testUIImageView() { let image1 = UIImage() let image2 = UIImage() let subject = PublishSubject1<UIImage?>() let view = UIImageView() subject.bind(to: view) subject.next(image1) XCTAssertEqual(view.image!, image1) subject.next(image2) XCTAssertEqual(view.image!, image2) subject.next(nil) XCTAssertEqual(view.image, nil) } func testUILabel() { let subject = PublishSubject1<String?>() let view = UILabel() subject.bind(to: view) subject.next("a") XCTAssertEqual(view.text!, "a") subject.next("b") XCTAssertEqual(view.text!, "b") subject.next(nil) XCTAssertEqual(view.text, nil) } func testUINavigationBar() { let subject = PublishSubject1<UIColor?>() let view = UINavigationBar() subject.bind(to: view.bnd_barTintColor) subject.next(.red) XCTAssertEqual(view.barTintColor!, .red) subject.next(.blue) XCTAssertEqual(view.barTintColor!, .blue) subject.next(nil) XCTAssertEqual(view.barTintColor, nil) } func testUINavigationItem() { let subject = PublishSubject1<String?>() let view = UINavigationItem() subject.bind(to: view.bnd_title) subject.next("a") XCTAssertEqual(view.title!, "a") subject.next("b") XCTAssertEqual(view.title!, "b") subject.next(nil) XCTAssertEqual(view.title, nil) } func testUIProgressView() { let subject = PublishSubject1<Float>() let view = UIProgressView() subject.bind(to: view) subject.next(0.2) XCTAssertEqual(view.progress, 0.2) subject.next(0.4) XCTAssertEqual(view.progress, 0.4) } func testUIRefreshControl() { let subject = PublishSubject1<Bool>() let view = UIRefreshControl() subject.bind(to: view) subject.next(true) XCTAssertEqual(view.isRefreshing, true) subject.next(false) XCTAssertEqual(view.isRefreshing, false) view.bnd_refreshing.expectNext([false, true]) view.beginRefreshing() view.sendActions(for: .valueChanged) } func testUISegmentedControl() { let subject = PublishSubject1<Int>() let view = UISegmentedControl(items: ["a", "b"]) subject.bind(to: view) subject.next(1) XCTAssertEqual(view.selectedSegmentIndex, 1) subject.next(0) XCTAssertEqual(view.selectedSegmentIndex, 0) view.bnd_selectedSegmentIndex.expectNext([0, 1]) view.selectedSegmentIndex = 1 view.sendActions(for: .valueChanged) } func testUISlider() { let subject = PublishSubject1<Float>() let view = UISlider() subject.bind(to: view) subject.next(0.2) XCTAssertEqual(view.value, 0.2) subject.next(0.4) XCTAssertEqual(view.value, 0.4) view.bnd_value.expectNext([0.4, 0.6]) view.value = 0.6 view.sendActions(for: .valueChanged) } func testUISwitch() { let subject = PublishSubject1<Bool>() let view = UISwitch() subject.bind(to: view) subject.next(false) XCTAssertEqual(view.isOn, false) subject.next(true) XCTAssertEqual(view.isOn, true) view.bnd_isOn.expectNext([true, false]) view.isOn = false view.sendActions(for: .valueChanged) } func testUITextField() { let subject = PublishSubject1<String?>() let view = UITextField() subject.bind(to: view) subject.next("a") XCTAssertEqual(view.text!, "a") subject.next("b") XCTAssertEqual(view.text!, "b") view.bnd_text.expectNext(["b", "c"]) view.text = "c" view.sendActions(for: .allEditingEvents) } func testUITextView() { let subject = PublishSubject1<String?>() let view = UITextView() subject.bind(to: view) subject.next("a") XCTAssertEqual(view.text!, "a") subject.next("b") XCTAssertEqual(view.text!, "b") view.bnd_text.expectNext(["b", "c"]) view.text = "c" NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: view) } }
b639fc6b3e6b36f6fcf195a0a561aab9
23.355987
100
0.664231
false
true
false
false
scinfu/SwiftSoup
refs/heads/master
Sources/Tag.swift
mit
1
// // Tag.swift // SwiftSoup // // Created by Nabil Chatbi on 15/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation open class Tag: Hashable { // map of known tags static var tags: Dictionary<String, Tag> = { do { return try Tag.initializeMaps() } catch { preconditionFailure("This method must be overridden") } return Dictionary<String, Tag>() }() fileprivate var _tagName: String fileprivate var _tagNameNormal: String fileprivate var _isBlock: Bool = true // block or inline fileprivate var _formatAsBlock: Bool = true // should be formatted as a block fileprivate var _canContainBlock: Bool = true // Can this tag hold block level tags? fileprivate var _canContainInline: Bool = true // only pcdata if not fileprivate var _empty: Bool = false // can hold nothing e.g. img fileprivate var _selfClosing: Bool = false // can self close (<foo />). used for unknown tags that self close, without forcing them as empty. fileprivate var _preserveWhitespace: Bool = false // for pre, textarea, script etc fileprivate var _formList: Bool = false // a control that appears in forms: input, textarea, output etc fileprivate var _formSubmit: Bool = false // a control that can be submitted in a form: input etc public init(_ tagName: String) { self._tagName = tagName self._tagNameNormal = tagName.lowercased() } /** * Get this tag's name. * * @return the tag's name */ open func getName() -> String { return self._tagName } open func getNameNormal() -> String { return self._tagNameNormal } /** * Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything. * <p> * Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals(). * </p> * * @param tagName Name of tag, e.g. "p". Case insensitive. * @param settings used to control tag name sensitivity * @return The tag, either defined or new generic. */ public static func valueOf(_ tagName: String, _ settings: ParseSettings)throws->Tag { var tagName = tagName var tag: Tag? = Tag.tags[tagName] if (tag == nil) { tagName = settings.normalizeTag(tagName) try Validate.notEmpty(string: tagName) tag = Tag.tags[tagName] if (tag == nil) { // not defined: create default; go anywhere, do anything! (incl be inside a <p>) tag = Tag(tagName) tag!._isBlock = false tag!._canContainBlock = true } } return tag! } /** * Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything. * <p> * Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals(). * </p> * * @param tagName Name of tag, e.g. "p". <b>Case sensitive</b>. * @return The tag, either defined or new generic. */ public static func valueOf(_ tagName: String)throws->Tag { return try valueOf(tagName, ParseSettings.preserveCase) } /** * Gets if this is a block tag. * * @return if block tag */ open func isBlock() -> Bool { return _isBlock } /** * Gets if this tag should be formatted as a block (or as inline) * * @return if should be formatted as block or inline */ open func formatAsBlock() -> Bool { return _formatAsBlock } /** * Gets if this tag can contain block tags. * * @return if tag can contain block tags */ open func canContainBlock() -> Bool { return _canContainBlock } /** * Gets if this tag is an inline tag. * * @return if this tag is an inline tag. */ open func isInline() -> Bool { return !_isBlock } /** * Gets if this tag is a data only tag. * * @return if this tag is a data only tag */ open func isData() -> Bool { return !_canContainInline && !isEmpty() } /** * Get if this is an empty tag * * @return if this is an empty tag */ open func isEmpty() -> Bool { return _empty } /** * Get if this tag is self closing. * * @return if this tag should be output as self closing. */ open func isSelfClosing() -> Bool { return _empty || _selfClosing } /** * Get if this is a pre-defined tag, or was auto created on parsing. * * @return if a known tag */ open func isKnownTag() -> Bool { return Tag.tags[_tagName] != nil } /** * Check if this tagname is a known tag. * * @param tagName name of tag * @return if known HTML tag */ public static func isKnownTag(_ tagName: String) -> Bool { return Tag.tags[tagName] != nil } /** * Get if this tag should preserve whitespace within child text nodes. * * @return if preserve whitepace */ public func preserveWhitespace() -> Bool { return _preserveWhitespace } /** * Get if this tag represents a control associated with a form. E.g. input, textarea, output * @return if associated with a form */ public func isFormListed() -> Bool { return _formList } /** * Get if this tag represents an element that should be submitted with a form. E.g. input, option * @return if submittable with a form */ public func isFormSubmittable() -> Bool { return _formSubmit } @discardableResult func setSelfClosing() -> Tag { _selfClosing = true return self } /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static public func ==(lhs: Tag, rhs: Tag) -> Bool { let this = lhs let o = rhs if (this === o) {return true} if (type(of: this) != type(of: o)) {return false} let tag: Tag = o if (lhs._tagName != tag._tagName) {return false} if (lhs._canContainBlock != tag._canContainBlock) {return false} if (lhs._canContainInline != tag._canContainInline) {return false} if (lhs._empty != tag._empty) {return false} if (lhs._formatAsBlock != tag._formatAsBlock) {return false} if (lhs._isBlock != tag._isBlock) {return false} if (lhs._preserveWhitespace != tag._preserveWhitespace) {return false} if (lhs._selfClosing != tag._selfClosing) {return false} if (lhs._formList != tag._formList) {return false} return lhs._formSubmit == tag._formSubmit } public func equals(_ tag: Tag) -> Bool { return self == tag } /// The hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. public func hash(into hasher: inout Hasher) { hasher.combine(_tagName) hasher.combine(_isBlock) hasher.combine(_formatAsBlock) hasher.combine(_canContainBlock) hasher.combine(_canContainInline) hasher.combine(_empty) hasher.combine(_selfClosing) hasher.combine(_preserveWhitespace) hasher.combine(_formList) hasher.combine(_formSubmit) } open func toString() -> String { return _tagName } // internal static initialisers: // prepped from http://www.w3.org/TR/REC-html40/sgml/dtd.html and other sources private static let blockTags: [String] = [ "html", "head", "body", "frameset", "script", "noscript", "style", "meta", "link", "title", "frame", "noframes", "section", "nav", "aside", "hgroup", "header", "footer", "p", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "pre", "div", "blockquote", "hr", "address", "figure", "figcaption", "form", "fieldset", "ins", "del", "s", "dl", "dt", "dd", "li", "table", "caption", "thead", "tfoot", "tbody", "colgroup", "col", "tr", "th", "td", "video", "audio", "canvas", "details", "menu", "plaintext", "template", "article", "main", "svg", "math" ] private static let inlineTags: [String] = [ "object", "base", "font", "tt", "i", "b", "u", "big", "small", "em", "strong", "dfn", "code", "samp", "kbd", "var", "cite", "abbr", "time", "acronym", "mark", "ruby", "rt", "rp", "a", "img", "br", "wbr", "map", "q", "sub", "sup", "bdo", "iframe", "embed", "span", "input", "select", "textarea", "label", "button", "optgroup", "option", "legend", "datalist", "keygen", "output", "progress", "meter", "area", "param", "source", "track", "summary", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track", "data", "bdi" ] private static let emptyTags: [String] = [ "meta", "link", "base", "frame", "img", "br", "wbr", "embed", "hr", "input", "keygen", "col", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track" ] private static let formatAsInlineTags: [String] = [ "title", "a", "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "address", "li", "th", "td", "script", "style", "ins", "del", "s" ] private static let preserveWhitespaceTags: [String] = [ "pre", "plaintext", "title", "textarea" // script is not here as it is a data node, which always preserve whitespace ] // todo: I think we just need submit tags, and can scrub listed private static let formListedTags: [String] = [ "button", "fieldset", "input", "keygen", "object", "output", "select", "textarea" ] private static let formSubmitTags: [String] = [ "input", "keygen", "object", "select", "textarea" ] static private func initializeMaps()throws->Dictionary<String, Tag> { var dict = Dictionary<String, Tag>() // creates for tagName in blockTags { let tag = Tag(tagName) dict[tag._tagName] = tag } for tagName in inlineTags { let tag = Tag(tagName) tag._isBlock = false tag._canContainBlock = false tag._formatAsBlock = false dict[tag._tagName] = tag } // mods: for tagName in emptyTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._canContainBlock = false tag?._canContainInline = false tag?._empty = true } for tagName in formatAsInlineTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._formatAsBlock = false } for tagName in preserveWhitespaceTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._preserveWhitespace = true } for tagName in formListedTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._formList = true } for tagName in formSubmitTags { let tag = dict[tagName] try Validate.notNull(obj: tag) tag?._formSubmit = true } return dict } }
78f3f85e08e6c51ebe03ad7a08c7aa34
32.778098
145
0.568467
false
false
false
false
ABTSoftware/SciChartiOSTutorial
refs/heads/master
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ModifyAxisBehaviour/SecondaryYAxesChartView.swift
mit
1
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // SecondaryYAxesChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class SecondaryYAxesChartView: SingleChartLayout { override func initExample() { let xAxis = SCINumericAxis() xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) xAxis.axisTitle = "Bottom Axis" let rightYAxis = SCINumericAxis() rightYAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) rightYAxis.axisId = "rightAxisId" rightYAxis.axisTitle = "Right Axis" rightYAxis.axisAlignment = .right rightYAxis.style.labelStyle.colorCode = 0xFF279B27 let leftYAxis = SCINumericAxis() leftYAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) leftYAxis.axisId = "leftAxisId" leftYAxis.axisTitle = "Left Axis" leftYAxis.axisAlignment = .left leftYAxis.style.labelStyle.colorCode = 0xFF4083B7 let ds1 = SCIXyDataSeries(xType: .double, yType: .double) let ds2 = SCIXyDataSeries(xType: .double, yType: .double) let ds1Points = DataManager.getFourierSeries(withAmplitude: 1.0, phaseShift: 0.1, count: 5000) let ds2Points = DataManager.getDampedSinewave(withAmplitude: 3.0, dampingFactor: 0.005, pointCount: 5000, freq: 10) ds1.appendRangeX(ds1Points!.xValues, y: ds1Points!.yValues, count: ds1Points!.size) ds2.appendRangeX(ds2Points!.xValues, y: ds2Points!.yValues, count: ds2Points!.size) let rs1 = SCIFastLineRenderableSeries() rs1.dataSeries = ds1 rs1.strokeStyle = SCISolidPenStyle(colorCode: 0xFF4083B7, withThickness: 2.0) rs1.yAxisId = "leftAxisId" let rs2 = SCIFastLineRenderableSeries() rs2.dataSeries = ds2 rs2.strokeStyle = SCISolidPenStyle(colorCode: 0xFF279B27, withThickness: 2.0) rs2.yAxisId = "rightAxisId" SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(leftYAxis) self.surface.yAxes.add(rightYAxis) self.surface.renderableSeries.add(rs1) self.surface.renderableSeries.add(rs2) rs1.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) rs2.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) } } }
4d12867493f061c741e8810145732f3f
45.882353
123
0.642095
false
false
false
false
codeliling/HXDYWH
refs/heads/master
dywh/dywh/controllers/ArticleMapViewController.swift
apache-2.0
1
// // MapViewController.swift // dywh // // Created by lotusprize on 15/5/22. // Copyright (c) 2015年 geekTeam. All rights reserved. // import UIKit import Haneke class ArticleMapViewController: UIViewController,BMKMapViewDelegate { let cache = Shared.imageCache var mapView:BMKMapView! var articleList:[ArticleModel] = [] var mAPView:MapArticlePanelView! var articleModel:ArticleModel? override func viewDidLoad() { super.viewDidLoad() mapView = BMKMapView() mapView.frame = self.view.frame mapView.mapType = UInt(BMKMapTypeStandard) mapView.zoomLevel = 5 mapView.showMapScaleBar = true mapView.mapScaleBarPosition = CGPointMake(10, 10) mapView.showsUserLocation = true mapView.compassPosition = CGPointMake(self.view.frame.width - 50, 10) mapView.setCenterCoordinate(CLLocationCoordinate2DMake(26.2038,109.8151), animated: true) mapView.delegate = self self.view.addSubview(mapView) mAPView = MapArticlePanelView(frame: CGRectMake(10, UIScreen.mainScreen().bounds.size.height - 300, UIScreen.mainScreen().bounds.size.width - 20, 130), title: "", articleDescription: "") mAPView.backgroundColor = UIColor.whiteColor() mAPView.alpha = 0.8 mAPView.hidden = true mAPView.userInteractionEnabled = true var tapView:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "panelClick:") self.mAPView.addGestureRecognizer(tapView) self.view.addSubview(mAPView) } func mapView(mapView: BMKMapView!, didSelectAnnotationView view: BMKAnnotationView!) { var title:String = view.annotation.title!() for aModle in articleList{ if title == aModle.articleName{ articleModel = aModle } } if (articleModel != nil){ mAPView.hidden = false self.loadImageByUrl(mAPView, url: articleModel!.articleImageUrl!) mAPView.title = articleModel!.articleName mAPView.articleDescription = articleModel!.articleDescription mAPView.setNeedsDisplay() } } func addMapPoint(articleModel:ArticleModel){ var annotation:BMKPointAnnotation = BMKPointAnnotation() annotation.coordinate = CLLocationCoordinate2DMake(Double(articleModel.latitude), Double(articleModel.longitude)); annotation.title = articleModel.articleName mapView.addAnnotation(annotation) articleList.append(articleModel) } func mapView(mapView: BMKMapView!, viewForAnnotation annotation: BMKAnnotation!) -> BMKAnnotationView! { if annotation.isKindOfClass(BMKPointAnnotation.classForCoder()) { var newAnnotationView:BMKPinAnnotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: "articleAnnotation"); newAnnotationView.pinColor = UInt(BMKPinAnnotationColorPurple) newAnnotationView.animatesDrop = true;// 设置该标注点动画显示 newAnnotationView.annotation = annotation; newAnnotationView.image = UIImage(named: "locationIcon") newAnnotationView.frame = CGRectMake(newAnnotationView.frame.origin.x, newAnnotationView.frame.origin.y, 30, 30) newAnnotationView.paopaoView = nil return newAnnotationView } return nil } func mapView(mapView: BMKMapView!, annotationViewForBubble view: BMKAnnotationView!) { } func panelClick(gesture:UIGestureRecognizer){ if articleModel != nil{ var detailViewController:ArticleDetailViewController? = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ArticleDetail") as? ArticleDetailViewController detailViewController?.articleModel = articleModel self.navigationController?.pushViewController(detailViewController!, animated: true) } } func loadImageByUrl(view:MapArticlePanelView, url:String){ let URL = NSURL(string: url)! let fetcher = NetworkFetcher<UIImage>(URL: URL) cache.fetch(fetcher: fetcher).onSuccess { image in // Do something with image view.imageLayer.contents = image.CGImage } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) mapView.delegate = self } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) mapView.delegate = nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
9345a107cdf2a38db0ef5e1716cfaacd
37.795082
196
0.672723
false
false
false
false
adrfer/swift
refs/heads/master
stdlib/public/core/Print.swift
apache-2.0
1
//===--- Print.swift ------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// Writes the textual representations of `items`, separated by /// `separator` and terminated by `terminator`, into the standard /// output. /// /// The textual representations are obtained for each `item` via /// the expression `String(item)`. /// /// - Note: To print without a trailing newline, pass `terminator: ""` /// /// - SeeAlso: `debugPrint`, `Streamable`, `CustomStringConvertible`, /// `CustomDebugStringConvertible` @inline(never) @_semantics("stdlib_binary_only") public func print( items: Any..., separator: String = " ", terminator: String = "\n" ) { if let hook = _playgroundPrintHook { var output = _TeeStream(left: "", right: _Stdout()) _print( items, separator: separator, terminator: terminator, toStream: &output) hook(output.left) } else { var output = _Stdout() _print( items, separator: separator, terminator: terminator, toStream: &output) } } /// Writes the textual representations of `items` most suitable for /// debugging, separated by `separator` and terminated by /// `terminator`, into the standard output. /// /// The textual representations are obtained for each `item` via /// the expression `String(reflecting: item)`. /// /// - Note: To print without a trailing newline, pass `terminator: ""` /// /// - SeeAlso: `print`, `Streamable`, `CustomStringConvertible`, /// `CustomDebugStringConvertible` @inline(never) @_semantics("stdlib_binary_only") public func debugPrint( items: Any..., separator: String = " ", terminator: String = "\n") { if let hook = _playgroundPrintHook { var output = _TeeStream(left: "", right: _Stdout()) _debugPrint( items, separator: separator, terminator: terminator, toStream: &output) hook(output.left) } else { var output = _Stdout() _debugPrint( items, separator: separator, terminator: terminator, toStream: &output) } } /// Writes the textual representations of `items`, separated by /// `separator` and terminated by `terminator`, into `output`. /// /// The textual representations are obtained for each `item` via /// the expression `String(item)`. /// /// - Note: To print without a trailing newline, pass `terminator: ""` /// /// - SeeAlso: `debugPrint`, `Streamable`, `CustomStringConvertible`, /// `CustomDebugStringConvertible` @inline(__always) public func print<Target: OutputStreamType>( items: Any..., separator: String = " ", terminator: String = "\n", inout toStream output: Target ) { _print(items, separator: separator, terminator: terminator, toStream: &output) } /// Writes the textual representations of `items` most suitable for /// debugging, separated by `separator` and terminated by /// `terminator`, into `output`. /// /// The textual representations are obtained for each `item` via /// the expression `String(reflecting: item)`. /// /// - Note: To print without a trailing newline, pass `terminator: ""` /// /// - SeeAlso: `print`, `Streamable`, `CustomStringConvertible`, /// `CustomDebugStringConvertible` @inline(__always) public func debugPrint<Target: OutputStreamType>( items: Any..., separator: String = " ", terminator: String = "\n", inout toStream output: Target ) { _debugPrint( items, separator: separator, terminator: terminator, toStream: &output) } @inline(never) @_semantics("stdlib_binary_only") internal func _print<Target: OutputStreamType>( items: [Any], separator: String = " ", terminator: String = "\n", inout toStream output: Target ) { var prefix = "" output._lock() for item in items { output.write(prefix) _print_unlocked(item, &output) prefix = separator } output.write(terminator) output._unlock() } @inline(never) @_semantics("stdlib_binary_only") internal func _debugPrint<Target: OutputStreamType>( items: [Any], separator: String = " ", terminator: String = "\n", inout toStream output: Target ) { var prefix = "" output._lock() for item in items { output.write(prefix) _debugPrint_unlocked(item, &output) prefix = separator } output.write(terminator) output._unlock() } //===----------------------------------------------------------------------===// //===--- Migration Aids ---------------------------------------------------===// @available(*, unavailable, message="Please wrap your tuple argument in parentheses: 'print((...))'") public func print<T>(_: T) {} @available(*, unavailable, message="Please wrap your tuple argument in parentheses: 'debugPrint((...))'") public func debugPrint<T>(_: T) {} @available(*, unavailable, message="Please use 'terminator: \"\"' instead of 'appendNewline: false': 'print((...), terminator: \"\")'") public func print<T>(_: T, appendNewline: Bool) {} @available(*, unavailable, message="Please use 'terminator: \"\"' instead of 'appendNewline: false': 'debugPrint((...), terminator: \"\")'") public func debugPrint<T>(_: T, appendNewline: Bool) {} //===--- FIXME: Not working due to <rdar://22101775> ----------------------===// @available(*, unavailable, message="Please use the 'toStream' label for the target stream: 'print((...), toStream: &...)'") public func print<T>(_: T, inout _: OutputStreamType) {} @available(*, unavailable, message="Please use the 'toStream' label for the target stream: 'debugPrint((...), toStream: &...))'") public func debugPrint<T>(_: T, inout _: OutputStreamType) {} @available(*, unavailable, message="Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'toStream' label for the target stream: 'print((...), terminator: \"\", toStream: &...)'") public func print<T>(_: T, inout _: OutputStreamType, appendNewline: Bool) {} @available(*, unavailable, message="Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'toStream' label for the target stream: 'debugPrint((...), terminator: \"\", toStream: &...)'") public func debugPrint<T>( _: T, inout _: OutputStreamType, appendNewline: Bool ) {} //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
9f787b09f4b5ed76d9fdbbd4be353280
35.618785
207
0.630658
false
false
false
false
Wolox/wolmo-core-ios
refs/heads/master
WolmoCore/Extensions/UIKit/UIViewController.swift
mit
1
// // UIViewController.swift // WolmoCore // // Created by Guido Marucci Blas on 5/7/16. // Copyright © 2016 Wolox. All rights reserved. // import UIKit public extension UIViewController { /** Loads the childViewController into the specified containerView. It can be done after self's view is initialized, as it uses constraints to determine the childViewController size. Take into account that self will retain the childViewController, so if for any other reason the childViewController is retained in another place, this would lead to a memory leak. In that case, one should call unloadViewController(). - parameter childViewController: The controller to load. - parameter into: The containerView into which the controller will be loaded. - parameter viewPositioning: Back or Front. Default: Front */ func load(childViewController: UIViewController, into containerView: UIView, with insets: UIEdgeInsets = .zero, in viewPositioning: ViewPositioning = .front, layout: LayoutMode = .constraints, respectSafeArea: Bool = false) { childViewController.willMove(toParent: self) addChild(childViewController) childViewController.didMove(toParent: self) childViewController.view.add(into: containerView, with: insets, in: viewPositioning, layout: layout, respectSafeArea: respectSafeArea) } /** Unloads a childViewController and its view from its parentViewController. */ func unloadFromParentViewController() { view.removeFromSuperview() removeFromParent() } /** Unloads all childViewController and their view from self. */ func unloadChildViewControllers() { for childController in self.children { childController.unloadFromParentViewController() } } } // MARK: - Navigation Bar public extension UIViewController { /** Configures the navigation bar to have a particular image as back button. - parameter image: The image of the back button. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ func setNavigationBarBackButton(_ image: UIImage) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.topItem?.title = "" navigationController.navigationBar.backIndicatorImage = image navigationController.navigationBar.backIndicatorTransitionMaskImage = image } /** Configures the navigation bar color. - parameter color: The new color of the navigation bar. This represents the navigation bar background color. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ func setNavigationBarColor(_ color: UIColor) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.barTintColor = color } /** Configures the navigation bar tint color. - parameter color: The new tint color of the navigation bar. This represents the color of the left and right button items. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ func setNavigationBarTintColor(_ color: UIColor) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.tintColor = color } /** Configures the navigation bar style. - parameter style: The new style of the navigation bar. - warning: This function must be called when self is inside a navigation controller. If not it will arise a runtime fatal error. */ func setNavigationBarStyle(_ style: UIBarStyle) { guard let navigationController = navigationController else { fatalError("There is no navigation controller.") } navigationController.navigationBar.barStyle = style } /** Sets a collection of buttons as the navigation bar left buttons. - parameter buttons: the Array of buttons to use. */ func setNavigationLeftButtons(_ buttons: [UIBarButtonItem]) { navigationItem.leftBarButtonItems = buttons } /** Sets a collection of buttons as the navigation bar right buttons. - parameter buttons: the Array of buttons to use. */ func setNavigationRightButtons(_ buttons: [UIBarButtonItem]) { navigationItem.rightBarButtonItems = buttons } /** Adds and configures a label to use as title of the navigation bar. - parameter title: the string of the label. - parameter font: the font to use for the label. - parameter color: the color of the text. */ func setNavigationBarTitle(_ title: String, font: UIFont, color: UIColor) { let label = UILabel(frame: .zero) label.backgroundColor = .clear label.font = font label.textColor = color label.adjustsFontSizeToFitWidth = true label.text = title label.sizeToFit() navigationItem.titleView = label } /** Adds an ImageView with the image passed as the titleView of the navigation bar. - parameter image: The image to set as title. */ func setNavigationBarTitleImage(_ image: UIImage) { navigationItem.titleView = UIImageView(image: image) } }
6f80f8dee8526c7d1cb39e89309d64f0
38.342105
161
0.664047
false
false
false
false
halo/LinkLiar
refs/heads/master
LinkHelper/Classes/BootDaemon.swift
mit
1
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 struct BootDaemon { enum SubCommand: String { case bootstrap = "bootstrap" case bootout = "bootout" } static func bootstrap() -> Bool { if bootout() { Log.debug("Deactivated daemon so I can now go ahead and safely (re-)activate it...") } else { Log.debug("Just-In-Case-Deactivation failed, but that's fine, let me activate it") } return launchctl(.bootstrap) } static func bootout() -> Bool { return launchctl(.bootout) } // MARK Private Instance Methods private static func launchctl(_ subcommand: SubCommand) -> Bool { Log.debug("Preparing \(subcommand.rawValue) of daemon...") let task = Process() // Set the task parameters task.launchPath = "/usr/bin/sudo" task.arguments = ["/bin/launchctl", subcommand.rawValue, "system", Paths.daemonPlistFile] let outputPipe = Pipe() let errorPipe = Pipe() task.standardOutput = outputPipe task.standardError = errorPipe // Launch the task task.launch() task.waitUntilExit() let status = task.terminationStatus if status == 0 { Log.debug("Task succeeded.") return(true) } else { Log.debug("Task failed \(task.terminationStatus)") let outdata = outputPipe.fileHandleForReading.availableData guard let stdout = String(data: outdata, encoding: .utf8) else { Log.debug("Could not read stdout") return false } let errdata = errorPipe.fileHandleForReading.availableData guard let stderr = String(data: errdata, encoding: .utf8) else { Log.debug("Could not read stderr") return false } Log.debug("Reason: \(stdout) \(stderr)") return(false) } } }
040f660e0cd995fcef2a15242877106b
32.835294
133
0.692629
false
false
false
false
mateuszstompor/MSEngine
refs/heads/master
ExampleProject/MSEngineTestApp/Controllers/ModelsTableViewController.swift
mit
1
// // MenuViewController.swift // MSEngineTestApp // // Created by Mateusz Stompór on 14/10/2017. // Copyright © 2017 Mateusz Stompór. All rights reserved. // import UIKit class ModelsTableViewController: UITableViewController { var lightSources: [MSPositionedLight?]? = MSEngine.getInstance()?.getPointLights() override func viewDidLoad() { super.viewDidLoad() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "PointLightTableViewCell") as? PointLightTableViewCell { if let positionedLight = lightSources?[indexPath.row] { let light = positionedLight.getLight()! let modelPosition = positionedLight.getTransformation() cell.isOn = light.isOn() cell.position = CIVector(x: CGFloat(modelPosition?.position().value(at: 0) ?? 0.0), y: CGFloat(modelPosition?.position().value(at: 1) ?? 0.0), z: CGFloat(modelPosition?.position().value(at: 1) ?? 0.0)) cell.lightPower = light.getPower() cell.lightWasSwitchedBlock = { [weak self] (cell: PointLightTableViewCell, isOn: Bool) in if let indexPath = self?.tableView.indexPath(for: cell) { self?.lightSources?[indexPath.row]?.getLight()?.lights(isOn) } } } return cell } else { return UITableViewCell() } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let pointLightsArray = self.lightSources { return pointLightsArray.count } else { return 0 } } }
f33ba4a3ddc5109bd7092fb94b3c45a0
36.633333
217
0.611603
false
false
false
false
nicksweet/Clink
refs/heads/master
Clink/Classes/Peer.swift
mit
1
// // ClinkPeer.swift // clink // // Created by Nick Sweet on 6/16/17. // import Foundation import CoreBluetooth public protocol ClinkPeerManager { func createPeer(withId peerId: String) func update(value: Any, forKey key: String, ofPeerWithId peerId: String) func getPeer<T: ClinkPeer>(withId peerId: String) -> T? func getKnownPeerIds() -> [Clink.PeerId] func delete(peerWithId peerId: String) } public protocol ClinkPeer { var id: String { get set } init(id: String) subscript(propertyName: Clink.PeerPropertyKey) -> Any? { get set } } extension Clink { public class DefaultPeer: ClinkPeer { public var id: String private var dict = [String: Any]() required public init(id: String) { self.id = id } public init?(dict: [String: Any]) { guard let id = dict["id"] as? String, let dict = dict["dict"] as? [String: Any] else { return nil } self.id = id self.dict = dict } public subscript(propertyName: Clink.PeerPropertyKey) -> Any? { get { return dict[propertyName] } set { dict[propertyName] = newValue } } public func toDict() -> [String: Any] { return [ "id": self.id, "dict": self.dict ] } } }
5fd535d70e248c092e00e5df0e194b41
22.375
76
0.52139
false
false
false
false
pristap/SwiftRSS
refs/heads/master
SwiftRSS/RSSParser.swift
mit
1
// // RSSParser.swift // SwiftRSS_Example // // Created by Thibaut LE LEVIER on 05/09/2014. // Copyright (c) 2014 Thibaut LE LEVIER. All rights reserved. // import UIKit class RSSParser: NSObject, NSXMLParserDelegate { class func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void) { let rssParser: RSSParser = RSSParser() rssParser.parseFeedForRequest(request, callback: callback) } var callbackClosure: ((feed: RSSFeed?, error: NSError?) -> Void)? var currentElement: String = "" var currentItem: RSSItem? var feed: RSSFeed = RSSFeed() // node names let node_item: String = "item" let node_title: String = "title" let node_link: String = "link" let node_guid: String = "guid" let node_publicationDate: String = "pubDate" let node_description: String = "description" let node_content: String = "content:encoded" let node_language: String = "language" let node_lastBuildDate = "lastBuildDate" let node_generator = "generator" let node_copyright = "copyright" // wordpress specifics let node_commentsLink = "comments" let node_commentsCount = "slash:comments" let node_commentRSSLink = "wfw:commentRss" let node_author = "dc:creator" let node_category = "category" func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void) { NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in if ((error) != nil) { callback(feed: nil, error: error) } else { self.callbackClosure = callback let parser : NSXMLParser = NSXMLParser(data: data!) parser.delegate = self parser.shouldResolveExternalEntities = false parser.parse() } } } // MARK: NSXMLParserDelegate func parserDidStartDocument(parser: NSXMLParser) { } func parserDidEndDocument(parser: NSXMLParser) { if let closure = self.callbackClosure { closure(feed: self.feed, error: nil) } } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { if elementName == node_item { self.currentItem = RSSItem() } self.currentElement = "" } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == node_item { if let item = self.currentItem { self.feed.items.append(item) } self.currentItem = nil return } if let item = self.currentItem { if elementName == node_title { item.title = self.currentElement } if elementName == node_link { item.setLink1(self.currentElement) } if elementName == node_guid { item.guid = self.currentElement } if elementName == node_publicationDate { item.setPubDate1(self.currentElement) } if elementName == node_description { item.itemDescription = self.currentElement } if elementName == node_content { item.content = self.currentElement } if elementName == node_commentsLink { item.setCommentsLink1(self.currentElement) } if elementName == node_commentsCount { item.commentsCount = Int(self.currentElement) } if elementName == node_commentRSSLink { item.setCommentRSSLink1(self.currentElement) } if elementName == node_author { item.author = self.currentElement } if elementName == node_category { item.categories.append(self.currentElement) } } else { if elementName == node_title { feed.title = self.currentElement } if elementName == node_link { feed.setLink1(self.currentElement) } if elementName == node_description { feed.feedDescription = self.currentElement } if elementName == node_language { feed.language = self.currentElement } if elementName == node_lastBuildDate { feed.setlastBuildDate(self.currentElement) } if elementName == node_generator { feed.generator = self.currentElement } if elementName == node_copyright { feed.copyright = self.currentElement } } } func parser(parser: NSXMLParser, foundCharacters string: String) { self.currentElement += string } func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { if let closure = self.callbackClosure { closure(feed: nil, error: parseError) } } }
9b66466e6c6836742a350890103d7dda
27.440758
173
0.514
false
false
false
false
ali-zahedi/AZViewer
refs/heads/master
AZViewer/AZConstraint.swift
apache-2.0
1
// // AZConstraint.swift // AZViewer // // Created by Ali Zahedi on 1/14/1396 AP. // Copyright © 1396 AP Ali Zahedi. All rights reserved. // import Foundation public class AZConstraint: NSObject { // MARK: Public public var parent: Any? public var top: NSLayoutConstraint? public var bottom: NSLayoutConstraint? public var left: NSLayoutConstraint? public var right: NSLayoutConstraint? public var centerX: NSLayoutConstraint? public var centerY: NSLayoutConstraint? public var width: NSLayoutConstraint? public var height: NSLayoutConstraint? // MARK: Internal // MARK: Private fileprivate var view: Any! // MARK: Override public init(view: Any) { super.init() self.view = view self.defaultInit() } // MARK: Function fileprivate func defaultInit(){ } } extension AZConstraint{ public func parent(parent: UIView) -> AZConstraint{ self.parent = parent return self } } // constraint extension AZConstraint{ // top public func top(to: Any? = nil, toAttribute: NSLayoutAttribute = .top, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .top, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.top = constraint self.top?.isActive = active return self } // bottom public func bottom(to: Any? = nil, toAttribute: NSLayoutAttribute = .bottom, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .bottom, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.bottom = constraint self.bottom?.isActive = active return self } // right public func right(to: Any? = nil, toAttribute: NSLayoutAttribute = .right, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .right, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.right = constraint self.right?.isActive = active return self } // left public func left(to: Any? = nil, toAttribute: NSLayoutAttribute = .left, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .left, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.left = constraint self.left?.isActive = active return self } // centerY public func centerY(to: Any? = nil, toAttribute: NSLayoutAttribute = .centerY, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.centerY = constraint self.centerY?.isActive = active return self } // centerX public func centerX(to: Any? = nil, toAttribute: NSLayoutAttribute = .centerX, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to ?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .centerX, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.centerX = constraint self.centerX?.isActive = active return self } // width public func width(to: Any? = nil, toAttribute: NSLayoutAttribute = .width, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to //?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .width, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.width = constraint self.width?.isActive = active return self } // height public func height(to: Any? = nil, toAttribute: NSLayoutAttribute = .height, multiplier: CGFloat = 1, constant: CGFloat = 0, active: Bool = true) -> AZConstraint{ let toItem = to //?? self.parent let constraint = NSLayoutConstraint(item: self.view, attribute: .height, relatedBy: .equal, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant) self.height = constraint self.height?.isActive = active return self } }
14bed54b14e02b5766b7b88c55fd31ce
31.856287
184
0.615272
false
false
false
false
piemapping/pie-overlay-menu-ios
refs/heads/master
Source/PieOverlayMenu.swift
mit
1
// // PieOverlayMenu2.swift // PieOverlayMenu // // Created by Anas Ait Ali on 28/12/2016. // Copyright © 2016 Pie mapping. All rights reserved. // import UIKit public protocol PieOverlayMenuProtocol { func setContentViewController(_ viewController: UIViewController, animated: Bool) func showMenu(_ animated: Bool) func closeMenu(_ animated: Bool, _ completion: ((Bool) -> ())?) func getMenuViewController() -> PieOverlayMenuContentViewController? func getContentViewController() -> UIViewController? } open class PieOverlayMenu: UIViewController, PieOverlayMenuProtocol { open fileprivate(set) var contentViewController: UIViewController? open fileprivate(set) var menuViewController: PieOverlayMenuContentViewController? fileprivate var visibleViewController: UIViewController? // MARK: - Init methods - public init() { super.init(nibName: nil, bundle: nil) print("this is not handled yet") } public init(contentViewController: UIViewController, menuViewController: UIViewController) { super.init(nibName: nil, bundle: nil) self.contentViewController = contentViewController self.menuViewController = PieOverlayMenuContentViewController(rootViewController: menuViewController) self.changeVisibleViewController(contentViewController) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func changeVisibleViewController(_ viewController: UIViewController) { visibleViewController?.willMove(toParentViewController: nil) self.addChildViewController(viewController) viewController.view.frame = self.view.bounds self.view.addSubview(viewController.view) visibleViewController?.view.removeFromSuperview() visibleViewController?.removeFromParentViewController() viewController.didMove(toParentViewController: self) visibleViewController = viewController setNeedsStatusBarAppearanceUpdate() } open func setContentViewController(_ viewController: UIViewController, animated: Bool) { //TODO: Implement animated self.contentViewController?.viewWillDisappear(animated) viewController.viewWillAppear(animated) self.changeVisibleViewController(viewController) self.contentViewController?.viewDidDisappear(animated) viewController.viewDidAppear(animated) self.contentViewController = viewController } open func showMenu(_ animated: Bool) { //TODO: Implement animated self.menuViewController?.viewWillAppear(animated) self.changeVisibleViewController(self.menuViewController!) self.menuViewController?.viewDidAppear(animated) } open func closeMenu(_ animated: Bool, _ completion: ((Bool) -> ())? = nil) { //TODO: Implement animated self.menuViewController?.viewWillDisappear(animated) self.changeVisibleViewController(self.contentViewController!) self.menuViewController?.viewDidDisappear(animated) self.menuViewController?.popToRootViewControllerAnimated(true, completion) } open func getMenuViewController() -> PieOverlayMenuContentViewController? { return self.menuViewController } open func getContentViewController() -> UIViewController? { return self.contentViewController } open override var preferredStatusBarStyle: UIStatusBarStyle { return self.visibleViewController?.preferredStatusBarStyle ?? .default } } extension UIViewController { public func pieOverlayMenuContent() -> PieOverlayMenuContentViewController? { return self.pieOverlayMenu()?.getMenuViewController() } public func pieOverlayContentViewController() -> UIViewController? { return self.pieOverlayMenu()?.getContentViewController() } public func pieOverlayMenu() -> PieOverlayMenuProtocol? { var iteration : UIViewController? = self.parent if (iteration == nil) { return topMostController() } repeat { if (iteration is PieOverlayMenuProtocol) { return iteration as? PieOverlayMenuProtocol } else if (iteration?.parent != nil && iteration?.parent != iteration) { iteration = iteration!.parent } else { iteration = nil } } while (iteration != nil) return iteration as? PieOverlayMenuProtocol } internal func topMostController () -> PieOverlayMenuProtocol? { var topController : UIViewController? = UIApplication.shared.keyWindow?.rootViewController if (topController is UITabBarController) { topController = (topController as! UITabBarController).selectedViewController } var lastMenuProtocol : PieOverlayMenuProtocol? while (topController?.presentedViewController != nil) { if(topController?.presentedViewController is PieOverlayMenuProtocol) { lastMenuProtocol = topController?.presentedViewController as? PieOverlayMenuProtocol } topController = topController?.presentedViewController } if (lastMenuProtocol != nil) { return lastMenuProtocol } else { return topController as? PieOverlayMenuProtocol } } }
65407815400e6909be90c2ccbee0acee
38.078014
109
0.693648
false
false
false
false
TZLike/GiftShow
refs/heads/master
GiftShow/GiftShow/Classes/ProductDetail/Model/LeeListDetailModel.swift
apache-2.0
1
// // LeeListDetailModel.swift // GiftShow // // Created by admin on 16/11/3. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit class LeeListDetailModel:LeeBaseModel { //描述 var des:String? //网页地址 var detail_html:String? var favorites_count:NSNumber = 0 var image_urls:[String]? var likes_count:NSNumber = 0 var name:String? var price:CGFloat = 0 var purchase_url:String? var short_description:String? init(dict:[String:NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if "description" == key { self.des = value as! String? } super.setValue(value, forKey: key) } }
acf2b05282692574b81244d9f755bbd2
19.6
63
0.570388
false
false
false
false
hooman/swift
refs/heads/main
test/Sema/placeholder_type.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift let x: _ = 0 // expected-error {{placeholders are not allowed as top-level types}} let x2 = x let dict1: [_: Int] = ["hi": 0] let dict2: [Character: _] = ["h": 0] let arr = [_](repeating: "hi", count: 3) func foo(_ arr: [_] = [0]) {} // expected-error {{type placeholder not allowed here}} let foo = _.foo // expected-error {{placeholders are not allowed as top-level types}} let zero: _ = .zero // expected-error {{placeholders are not allowed as top-level types}} struct S<T> { var x: T } var s1: S<_> = .init(x: 0) var s2 = S<_>(x: 0) let losslessStringConverter = Double.init as (String) -> _? let optInt: _? = 0 let implicitOptInt: _! = 0 let func1: (_) -> Double = { (x: Int) in 0.0 } let func2: (Int) -> _ = { x in 0.0 } let func3: (_) -> _ = { (x: Int) in 0.0 } let func4: (_, String) -> _ = { (x: Int, y: String) in 0.0 } let func5: (_, String) -> _ = { (x: Int, y: Double) in 0.0 } // expected-error {{cannot convert value of type '(Int, Double) -> Double' to specified type '(_, String) -> _'}} let type: _.Type = Int.self let type2: Int.Type.Type = _.Type.self struct MyType1<T, U> { init(t: T, mt2: MyType2<T>) where U == MyType2<T> {} } struct MyType2<T> { init(t: T) {} } let _: MyType2<_> = .init(t: "c" as Character) let _: MyType1<_, MyType2<_>> = .init(t: "s" as Character, mt2: .init(t: "c" as Character)) func dictionary<K, V>(ofType: [K: V].Type) -> [K: V] { [:] } let _: [String: _] = dictionary(ofType: [_: Int].self) let _: [_: _] = dictionary(ofType: [String: Int].self) let _: [String: Int] = dictionary(ofType: _.self) // expected-error {{placeholders are not allowed as top-level types}} let _: @convention(c) _ = { 0 } // expected-error {{@convention attribute only applies to function types}} // expected-error@-1 {{placeholders are not allowed as top-level types}} let _: @convention(c) (_) -> _ = { (x: Double) in 0 } let _: @convention(c) (_) -> Int = { (x: Double) in 0 } struct NonObjc {} let _: @convention(c) (_) -> Int = { (x: NonObjc) in 0 } // expected-error {{'(NonObjc) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}} func overload() -> Int? { 0 } func overload() -> String { "" } let _: _? = overload() let _ = overload() as _? struct Bar<T, U> where T: ExpressibleByIntegerLiteral, U: ExpressibleByIntegerLiteral { var t: T var u: U func frobnicate() -> Bar { return Bar(t: 42, u: 42) } } extension Bar { func frobnicate2() -> Bar<_, _> { // expected-error {{type placeholder not allowed here}} return Bar(t: 42, u: 42) } func frobnicate3() -> Bar { return Bar<_, _>(t: 42, u: 42) } func frobnicate4() -> Bar<_, _> { // expected-error {{type placeholder not allowed here}} return Bar<_, _>(t: 42, u: 42) } func frobnicate5() -> Bar<_, U> { // expected-error {{type placeholder not allowed here}} return Bar(t: 42, u: 42) } func frobnicate6() -> Bar { return Bar<_, U>(t: 42, u: 42) } func frobnicate7() -> Bar<_, _> { // expected-error {{type placeholder not allowed here}} return Bar<_, U>(t: 42, u: 42) } func frobnicate8() -> Bar<_, U> { // expected-error {{type placeholder not allowed here}} return Bar<_, _>(t: 42, u: 42) } } // FIXME: We should probably have better diagnostics for these situations--the user probably meant to use implicit member syntax let _: Int = _() // expected-error {{placeholders are not allowed as top-level types}} let _: () -> Int = { _() } // expected-error {{unable to infer closure type in the current context}} expected-error {{placeholders are not allowed as top-level types}} let _: Int = _.init() // expected-error {{placeholders are not allowed as top-level types}} let _: () -> Int = { _.init() } // expected-error {{unable to infer closure type in the current context}} expected-error {{placeholders are not allowed as top-level types}} func returnsInt() -> Int { _() } // expected-error {{placeholders are not allowed as top-level types}} func returnsIntClosure() -> () -> Int { { _() } } // expected-error {{unable to infer closure type in the current context}} expected-error {{placeholders are not allowed as top-level types}} func returnsInt2() -> Int { _.init() } // expected-error {{placeholders are not allowed as top-level types}} func returnsIntClosure2() -> () -> Int { { _.init() } } // expected-error {{unable to infer closure type in the current context}} expected-error {{placeholders are not allowed as top-level types}} let _: Int.Type = _ // expected-error {{'_' can only appear in a pattern or on the left side of an assignment}} let _: Int.Type = _.self // expected-error {{placeholders are not allowed as top-level types}} struct SomeSuperLongAndComplexType {} func getSomething() -> SomeSuperLongAndComplexType? { .init() } let something: _! = getSomething() extension Array where Element == Int { static var staticMember: Self { [] } static func staticFunc() -> Self { [] } var member: Self { [] } func method() -> Self { [] } } extension Array { static var otherStaticMember: Self { [] } } let _ = [_].staticMember let _ = [_].staticFunc() let _ = [_].otherStaticMember.member let _ = [_].otherStaticMember.method() func f(x: Any, arr: [Int]) { // FIXME: Better diagnostics here. Maybe we should suggest replacing placeholders with 'Any'? if x is _ {} // expected-error {{placeholders are not allowed as top-level types}} if x is [_] {} // expected-error {{type of expression is ambiguous without more context}} if x is () -> _ {} // expected-error {{type of expression is ambiguous without more context}} if let y = x as? _ {} // expected-error {{placeholders are not allowed as top-level types}} if let y = x as? [_] {} // expected-error {{type of expression is ambiguous without more context}} if let y = x as? () -> _ {} // expected-error {{type of expression is ambiguous without more context}} let y1 = x as! _ // expected-error {{placeholders are not allowed as top-level types}} let y2 = x as! [_] // expected-error {{type of expression is ambiguous without more context}} let y3 = x as! () -> _ // expected-error {{type of expression is ambiguous without more context}} switch x { case is _: break // expected-error {{type placeholder not allowed here}} case is [_]: break // expected-error {{type placeholder not allowed here}} case is () -> _: break // expected-error {{type placeholder not allowed here}} case let y as _: break // expected-error {{type placeholder not allowed here}} case let y as [_]: break // expected-error {{type placeholder not allowed here}} case let y as () -> _: break // expected-error {{type placeholder not allowed here}} } if arr is _ {} // expected-error {{placeholders are not allowed as top-level types}} if arr is [_] {} // expected-error {{type of expression is ambiguous without more context}} if arr is () -> _ {} // expected-error {{type of expression is ambiguous without more context}} if let y = arr as? _ {} // expected-error {{placeholders are not allowed as top-level types}} if let y = arr as? [_] {} // expected-error {{type of expression is ambiguous without more context}} if let y = arr as? () -> _ {} // expected-error {{type of expression is ambiguous without more context}} let y1 = arr as! _ // expected-error {{placeholders are not allowed as top-level types}} let y2 = arr as! [_] // expected-error {{type of expression is ambiguous without more context}} let y3 = arr as! () -> _ // expected-error {{type of expression is ambiguous without more context}} switch arr { case is _: break // expected-error {{type placeholder not allowed here}} case is [_]: break // expected-error {{type placeholder not allowed here}} case is () -> _: break // expected-error {{type placeholder not allowed here}} case let y as _: break // expected-error {{type placeholder not allowed here}} case let y as [_]: break // expected-error {{type placeholder not allowed here}} case let y as () -> _: break // expected-error {{type placeholder not allowed here}} } } protocol Publisher { associatedtype Output associatedtype Failure } struct Just<Output>: Publisher { typealias Failure = Never } struct SetFailureType<Output, Failure>: Publisher {} extension Publisher { func setFailureType<T>(to: T.Type) -> SetFailureType<Output, T> { return .init() } } let _: SetFailureType<Int, String> = Just<Int>().setFailureType(to: _.self) // expected-error {{placeholders are not allowed as top-level types}} let _: SetFailureType<Int, [String]> = Just<Int>().setFailureType(to: [_].self) let _: SetFailureType<Int, (String) -> Double> = Just<Int>().setFailureType(to: ((_) -> _).self) let _: SetFailureType<Int, (String, Double)> = Just<Int>().setFailureType(to: (_, _).self) // TODO: Better error message here? Would be nice if we could point to the placeholder... let _: SetFailureType<Int, String> = Just<Int>().setFailureType(to: _.self).setFailureType(to: String.self) // expected-error {{placeholders are not allowed as top-level types}} let _: (_) = 0 as Int // expected-error {{placeholders are not allowed as top-level types}} let _: Int = 0 as (_) // expected-error {{placeholders are not allowed as top-level types}} _ = (1...10) .map { ( $0, ( "\($0)", $0 > 5 ) ) } .map { (intValue, x: (_, boolValue: _)) in x.boolValue ? intValue : 0 }
f733a8d164dc0109d0bf891faca7c0e5
43.357798
196
0.628232
false
false
false
false
alitan2014/swift
refs/heads/master
Heath/Heath/AppDelegate.swift
gpl-2.0
1
// // AppDelegate.swift // Heath // // Created by Mac on 15/7/13. // Copyright (c) 2015年 Mac. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. var navigationBarappearace = UINavigationBar.appearance() navigationBarappearace.translucent = false navigationBarappearace.barTintColor = UIColor.grayColor() //navigation Bar title 字体为白色 UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "Heiti SC", size: 17)!] let tabBarController = HeathTabBarcontroller() tabBarController.tabBar.translucent = false tabBarController.tabBar.tintColor=UIColor(red: 251/25.0, green: 78/255.0, blue: 10/255.0, alpha: 1) self.window?.rootViewController=tabBarController return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
ac9e8b0d16675cf493fc02abfb8d3b6a
49.035714
285
0.745539
false
false
false
false
lrtitze/Swift-VectorBoolean
refs/heads/master
Swift VectorBoolean/VectorBoolean/FBBezierIntersectRange.swift
mit
1
// // FBBezierIntersectRange.swift // Swift VectorBoolean for iOS // // Based on FBBezierIntersectRange - Created by Andrew Finnell on 11/16/12. // Copyright (c) 2012 Fortunate Bear, LLC. All rights reserved. // // Created by Leslie Titze on 2015-06-29. // Copyright (c) 2015 Leslie Titze. All rights reserved. // import UIKit public class FBBezierIntersectRange { var _curve1: FBBezierCurve var _parameterRange1: FBRange var _curve1LeftBezier: FBBezierCurve? var _curve1MiddleBezier: FBBezierCurve? var _curve1RightBezier: FBBezierCurve? var _curve2: FBBezierCurve var _parameterRange2: FBRange var _curve2LeftBezier: FBBezierCurve? var _curve2MiddleBezier: FBBezierCurve? var _curve2RightBezier: FBBezierCurve? // TODO: perhaps this should be replaced by use of the optionals var needToComputeCurve1 = true var needToComputeCurve2 = true var _reversed: Bool var curve1 : FBBezierCurve { return _curve1 } var parameterRange1: FBRange { return _parameterRange1 } var curve2 : FBBezierCurve { return _curve2 } var parameterRange2: FBRange { return _parameterRange2 } var reversed : Bool { return _reversed } //+ (id) intersectRangeWithCurve1:(FBBezierCurve *)curve1 parameterRange1:(FBRange)parameterRange1 curve2:(FBBezierCurve *)curve2 parameterRange2:(FBRange)parameterRange2 reversed:(BOOL)reversed; // let i = FBBezierIntersectRange(curve1: dvbc1, parameterRange1: pr1, curve2: dvbc2, parameterRange2: pr2, reversed: rvsd) init(curve1: FBBezierCurve, parameterRange1: FBRange, curve2: FBBezierCurve, parameterRange2: FBRange, reversed: Bool) { _curve1 = curve1 _parameterRange1 = parameterRange1 _curve2 = curve2 _parameterRange2 = parameterRange2 _reversed = reversed } //- (FBBezierCurve *) curve1LeftBezier var curve1LeftBezier : FBBezierCurve { computeCurve1() return _curve1LeftBezier! } //- (FBBezierCurve *) curve1OverlappingBezier var curve1OverlappingBezier : FBBezierCurve { computeCurve1() return _curve1MiddleBezier! } //- (FBBezierCurve *) curve1RightBezier var curve1RightBezier : FBBezierCurve { computeCurve1() return _curve1RightBezier! } //- (FBBezierCurve *) curve2LeftBezier var curve2LeftBezier : FBBezierCurve { computeCurve2() return _curve2LeftBezier! } //- (FBBezierCurve *) curve2OverlappingBezier var curve2OverlappingBezier : FBBezierCurve { computeCurve2() return _curve2MiddleBezier! } //- (FBBezierCurve *) curve2RightBezier var curve2RightBezier : FBBezierCurve { computeCurve2() return _curve2RightBezier! } //- (BOOL) isAtStartOfCurve1 var isAtStartOfCurve1 : Bool { return FBAreValuesCloseWithOptions(_parameterRange1.minimum, value2: 0.0, threshold: FBParameterCloseThreshold) } //- (BOOL) isAtStopOfCurve1 var isAtStopOfCurve1 : Bool { return FBAreValuesCloseWithOptions(_parameterRange1.maximum, value2: 1.0, threshold: FBParameterCloseThreshold) } //- (BOOL) isAtStartOfCurve2 var isAtStartOfCurve2 : Bool { return FBAreValuesCloseWithOptions(_parameterRange2.minimum, value2: 0.0, threshold: FBParameterCloseThreshold) } //- (BOOL) isAtStopOfCurve2 var isAtStopOfCurve2 : Bool { return FBAreValuesCloseWithOptions(_parameterRange2.maximum, value2: 1.0, threshold: FBParameterCloseThreshold) } //- (FBBezierIntersection *) middleIntersection var middleIntersection : FBBezierIntersection { return FBBezierIntersection ( curve1: _curve1, param1: (_parameterRange1.minimum + _parameterRange1.maximum) / 2.0, curve2: _curve2, param2: (_parameterRange2.minimum + _parameterRange2.maximum) / 2.0 ) } func merge(_ other: FBBezierIntersectRange) { // We assume the caller already knows we're talking about the same curves _parameterRange1 = FBRangeUnion(_parameterRange1, range2: other._parameterRange1); _parameterRange2 = FBRangeUnion(_parameterRange2, range2: other._parameterRange2); clearCache() } fileprivate func clearCache() { needToComputeCurve1 = true needToComputeCurve2 = true _curve1LeftBezier = nil _curve1MiddleBezier = nil _curve1RightBezier = nil _curve2LeftBezier = nil _curve2MiddleBezier = nil _curve2RightBezier = nil } //- (void) computeCurve1 fileprivate func computeCurve1() { if needToComputeCurve1 { let swr = _curve1.splitSubcurvesWithRange(_parameterRange1, left: true, middle: true, right: true) _curve1LeftBezier = swr.left _curve1MiddleBezier = swr.mid _curve1RightBezier = swr.right needToComputeCurve1 = false } } // 114 //- (void) computeCurve2 fileprivate func computeCurve2() { if needToComputeCurve2 { let swr = _curve2.splitSubcurvesWithRange(_parameterRange2, left: true, middle: true, right: true) _curve2LeftBezier = swr.left _curve2MiddleBezier = swr.mid _curve2RightBezier = swr.right needToComputeCurve2 = false } } }
f5c92048d4fb8f31d452198743b75aac
26.741758
197
0.723312
false
false
false
false
K-cat/CatMediaPickerController
refs/heads/master
Sources/Controllers/CatPhotosPickerController.swift
mit
1
// // CatImagePickerController.swift // CatMediaPicker // // Created by Kcat on 2018/3/10. // Copyright © 2018年 ImKcat. All rights reserved. // // https://github.com/ImKcat/CatMediaPicker // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import Photos // MARK: - CatPhotosPickerController Requirements public class CatPhotosPickerControllerConfigure { public var mediaType: PHAssetMediaType = .image { didSet { switch mediaType { case .unknown: mediaType = .image default: break } } } public var maximumSelectCount: Int = 1 { didSet { if maximumSelectCount < 1 { maximumSelectCount = 1 } } } public init() {} } public protocol CatPhotosPickerControllerDelegate: NSObjectProtocol { func didFinishPicking(pickerController: CatPhotosPickerController, media: [CatMedia]) func didCancelPicking(pickerController: CatPhotosPickerController) } // MARK: - CatPhotosPickerController public class CatPhotosPickerController: UINavigationController, UINavigationControllerDelegate, CatPhotosListControllerDelegate { public weak var pickerControllerDelegate: CatPhotosPickerControllerDelegate? // MARK: - Initialize public init(configure: CatPhotosPickerControllerConfigure? = CatPhotosPickerControllerConfigure()) { let listController = CatPhotosListController() listController.pickerControllerConfigure = configure! super.init(rootViewController: listController) listController.listControllerDelegate = self self.delegate = self } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - CatPhotosListControllerDelegate func didTapDoneBarButtonItem(photosListController: CatPhotosListController, pickedAssets: [PHAsset]) { if self.pickerControllerDelegate != nil { guard pickedAssets.count != 0 else { self.pickerControllerDelegate?.didFinishPicking(pickerController: self, media: []) return } let media = pickedAssets.map{ return CatMedia(type: $0.mediaType, source: $0) } self.pickerControllerDelegate?.didFinishPicking(pickerController: self, media: media) } } func didTapCancelBarButtonItem(photosListController: CatPhotosListController) { if self.pickerControllerDelegate != nil { self.pickerControllerDelegate?.didCancelPicking(pickerController: self) } } } // MARK: - CatPhotosListController Requirements protocol CatPhotosListControllerDelegate: NSObjectProtocol { func didTapCancelBarButtonItem(photosListController: CatPhotosListController) func didTapDoneBarButtonItem(photosListController: CatPhotosListController, pickedAssets: [PHAsset]) } // MARK: - CatPhotosListController class CatPhotosListController: UICollectionViewController, UICollectionViewDelegateFlowLayout { weak var listControllerDelegate: CatPhotosListControllerDelegate? var pickerControllerConfigure: CatPhotosPickerControllerConfigure = CatPhotosPickerControllerConfigure() var doneBarButtonItem: UIBarButtonItem? var cancelBarButtonItem: UIBarButtonItem? var photosAssets: [PHAsset] = [] var selectedAssetIndexPaths: [IndexPath] = [] // MARK: - Initialize init() { let photosListCollectionViewLayout = UICollectionViewFlowLayout() photosListCollectionViewLayout.minimumInteritemSpacing = 0 photosListCollectionViewLayout.minimumLineSpacing = 0 photosListCollectionViewLayout.itemSize = CGSize(width: UIScreen.main.bounds.width / 4, height: UIScreen.main.bounds.width / 4) super.init(collectionViewLayout: photosListCollectionViewLayout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Stack override func viewDidLoad() { super.viewDidLoad() self.layoutInit() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.refreshData() } func layoutInit() { self.title = String.localizedString(defaultString: "Photos", key: "CatMediaPicker.PhotosPickerControllerTitle", comment: "") self.view.backgroundColor = UIColor.white self.collectionView?.allowsMultipleSelection = true self.collectionView?.backgroundColor = UIColor.clear self.collectionView?.alwaysBounceVertical = true self.cancelBarButtonItem = UIBarButtonItem(title: String.localizedString(defaultString: "Cancel", key: "CatMediaPicker.Cancel", comment: ""), style: .plain, target: self, action: #selector(cancelAction)) self.navigationItem.leftBarButtonItem = self.cancelBarButtonItem self.doneBarButtonItem = UIBarButtonItem(title: String.localizedString(defaultString: "Done", key: "CatMediaPicker.Done", comment: ""), style: .done, target: self, action: #selector(doneAction)) self.navigationItem.rightBarButtonItem = self.doneBarButtonItem self.collectionView?.register(CatPhotosListCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: CatPhotosListCollectionViewCell.self)) } func refreshData() { self.photosAssets.removeAll() let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let fetchResult = PHAsset.fetchAssets(with: self.pickerControllerConfigure.mediaType, options: fetchOptions) fetchResult.enumerateObjects { (asset, _, _) in self.photosAssets.append(asset) } self.collectionView?.reloadData() } // MARK: - Action @objc func cancelAction() { if self.listControllerDelegate != nil { self.listControllerDelegate?.didTapCancelBarButtonItem(photosListController: self) } } @objc func doneAction() { if self.listControllerDelegate != nil { let selectedIndexPaths = selectedAssetIndexPaths let selectedRows = selectedIndexPaths.map{ return $0.row } let selectedAssets = selectedRows.map{ return self.photosAssets[$0] } self.listControllerDelegate?.didTapDoneBarButtonItem(photosListController: self, pickedAssets: selectedAssets) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { let flowLayout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.itemSize = CGSize(width: size.width / 4, height: size.width / 4) self.collectionView?.collectionViewLayout = flowLayout } // MARK: - UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CatPhotosListCollectionViewCell.self), for: indexPath) as! CatPhotosListCollectionViewCell let photoAsset = photosAssets[indexPath.row] let imageRequestOptions = PHImageRequestOptions() imageRequestOptions.resizeMode = .exact imageRequestOptions.normalizedCropRect = CGRect(x: 0, y: 0, width: 200, height: 200) PHImageManager.default().requestImage(for: photoAsset, targetSize: CGSize(width: 200, height: 200), contentMode: PHImageContentMode.aspectFill, options: imageRequestOptions) { (photoImage, photoImageInfo) in guard photoImage != nil else { return } cell.photoImageView.image = photoImage } cell.isSelected = selectedAssetIndexPaths.contains(indexPath) ? true : false return cell } override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { guard selectedAssetIndexPaths.count < pickerControllerConfigure.maximumSelectCount else { return false } return true } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedAssetIndexPaths.append(indexPath) } override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { for i in 0...(selectedAssetIndexPaths.count - 1) { if selectedAssetIndexPaths[i] == indexPath { selectedAssetIndexPaths.remove(at: i) return } } } // MARK: - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photosAssets.count } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } } class CatPhotosListCollectionViewCell: UICollectionViewCell { var photoImageView: UIImageView var highlightView: UIView var checkmarkView: UIView = { let checkmarkView = UIView() let circleLayer = CAShapeLayer() let circlePath = UIBezierPath() circlePath.move(to: CGPoint(x: 10, y: 0)) circlePath.addCurve(to: CGPoint(x: 0, y: 10), controlPoint1: CGPoint(x: 4.48, y: 0), controlPoint2: CGPoint(x: 0, y: 4.48)) circlePath.addCurve(to: CGPoint(x: 10, y: 20), controlPoint1: CGPoint(x: 0, y: 15.52), controlPoint2: CGPoint(x: 4.48, y: 20)) circlePath.addCurve(to: CGPoint(x: 20, y: 10), controlPoint1: CGPoint(x: 15.52, y: 20), controlPoint2: CGPoint(x: 20, y: 15.52)) circlePath.addCurve(to: CGPoint(x: 10, y: 0), controlPoint1: CGPoint(x: 20, y: 4.48), controlPoint2: CGPoint(x: 15.52, y: 0)) circlePath.close() circlePath.fill() circleLayer.path = circlePath.cgPath circleLayer.fillColor = UIColor(red: 0.0000000000, green: 0.4784313738, blue: 1.0000000000, alpha: 1.0000000000).cgColor let checkmarkLayer = CAShapeLayer() let checkmarkPath = UIBezierPath() checkmarkPath.move(to: CGPoint(x: 8.46, y: 13.54)) checkmarkPath.addCurve(to: CGPoint(x: 8.03, y: 13.75), controlPoint1: CGPoint(x: 8.34, y: 13.66), controlPoint2: CGPoint(x: 8.18, y: 13.75)) checkmarkPath.addCurve(to: CGPoint(x: 7.61, y: 13.54), controlPoint1: CGPoint(x: 7.89, y: 13.75), controlPoint2: CGPoint(x: 7.73, y: 13.65)) checkmarkPath.addLine(to: CGPoint(x: 4.91, y: 10.85)) checkmarkPath.addLine(to: CGPoint(x: 5.77, y: 9.99)) checkmarkPath.addLine(to: CGPoint(x: 8.04, y: 12.26)) checkmarkPath.addLine(to: CGPoint(x: 14.04, y: 6.22)) checkmarkPath.addLine(to: CGPoint(x: 14.88, y: 7.09)) checkmarkPath.addLine(to: CGPoint(x: 8.46, y: 13.54)) checkmarkPath.close() checkmarkPath.usesEvenOddFillRule = true checkmarkPath.fill() checkmarkLayer.path = checkmarkPath.cgPath checkmarkLayer.fillColor = UIColor.white.cgColor checkmarkView.layer.addSublayer(circleLayer) checkmarkView.layer.addSublayer(checkmarkLayer) return checkmarkView }() override var isSelected: Bool { didSet { UIView.animate(withDuration: 0.2, animations: { self.checkmarkView.alpha = self.isSelected ? 1 : 0 self.highlightView.alpha = self.isSelected ? 0.3 : 0 }) } } override init(frame: CGRect) { self.photoImageView = UIImageView() self.highlightView = UIView() super.init(frame: frame) self.layoutInit() } func layoutInit() { self.photoImageView.contentMode = .scaleAspectFill self.photoImageView.translatesAutoresizingMaskIntoConstraints = false self.highlightView.backgroundColor = UIColor.white self.highlightView.alpha = 0 self.highlightView.translatesAutoresizingMaskIntoConstraints = false self.checkmarkView.alpha = 0 self.checkmarkView.contentMode = .scaleAspectFit self.checkmarkView.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(self.photoImageView) self.contentView.addSubview(self.highlightView) self.contentView.addSubview(self.checkmarkView) var constraintArray: [NSLayoutConstraint] = [] constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[photoImageView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["photoImageView": self.photoImageView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[photoImageView]|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["photoImageView": self.photoImageView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[highlightView]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["highlightView": self.highlightView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[highlightView]|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["highlightView": self.highlightView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[checkmarkView(20)]-|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["checkmarkView": self.checkmarkView])) constraintArray.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[checkmarkView(20)]-|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["checkmarkView": self.checkmarkView])) self.addConstraints(constraintArray) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
3d889071ff9f2c5c6e9ddd405fc01974
46.997297
184
0.606791
false
false
false
false
Palleas/Batman
refs/heads/master
Batman/Domain/Builder.swift
mit
1
import Foundation import Result struct Builder { enum BuilderError: Error, AutoEquatable { case missingContent case somethingElse } typealias TitleAndNotes = (title: String, notes: String?) static func task(from content: String) -> Result<TitleAndNotes, BuilderError> { let scanner = Scanner(string: content) var extractedTitle: NSString? scanner.scanUpToCharacters(from: .newlines, into: &extractedTitle) guard let title = extractedTitle else { return .failure(.missingContent) } guard !scanner.isAtEnd else { return .success((title: title as String, notes: nil) as TitleAndNotes) } let index = content.index(content.startIndex, offsetBy: scanner.scanLocation) let notes = content[index...].trimmingCharacters(in: .whitespacesAndNewlines) return .success((title: title as String, notes: notes) as TitleAndNotes) } }
5888c8054e3335f149649095d04b70d5
34.538462
110
0.695887
false
false
false
false
blkbrds/intern09_final_project_tung_bien
refs/heads/master
MyApp/Model/Schema/NotificationContent.swift
mit
1
// // NotificationContent.swift // MyApp // // Created by AST on 9/1/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import ObjectMapper final class NotificationContent: Mappable { var id = 0 var name = "" var content = "" var time = "" var idOrder = 0 init() { } init?(map: Map) { } func mapping(map: Map) { id <- map["id"] idOrder <- map["typeId"] name <- map["title"] content <- map["description"] time <- map["updatedAt"] } }
04695a83e690ddf32c3533185a26859b
16.060606
62
0.543517
false
false
false
false
BridgeNetworking/Bridge
refs/heads/dev
Bridge/Encoding.swift
mit
2
// // Encoding.swift // Rentals // // Created by Justin Huang on 7/28/15. // Copyright (c) 2015 Zumper. All rights reserved. // import Foundation public enum Encoding { case json public func encode(_ mutableRequest: NSMutableURLRequest, parameters: Dict?) throws -> NSMutableURLRequest { guard let parameters = parameters else { return mutableRequest } switch self { case .json: switch HTTPMethod(rawValue: mutableRequest.httpMethod)! { case .GET, .DELETE: // Encode params in the URL of the request let mappedParameters: Array<(key: String, value: String)> = (parameters).map({ (key, value) in if let collection = value as? [Any] { return (key, self.escapeString("\(key)") + "=" + (collection.reduce("", { $0 + ($0.isEmpty ? "" : ",") + self.escapeString("\($1)")}))) } else { return (key, self.escapeString("\(key)") + "=" + self.escapeString("\(value)") ) } }) let flattenedString = mappedParameters.reduce("", { $0 + $1.1 + "&" } ) // Append the leading `?` character for url encoded requests // and drop the trailing `&` from the reduce let queryString = "?" + String(flattenedString.dropLast()) let baseURL = mutableRequest.url mutableRequest.url = URL(string: queryString, relativeTo: baseURL!) case .POST, .PUT: // Encode params in the HTTP body of the request if JSONSerialization.isValidJSONObject(parameters) { do { let data = try JSONSerialization.data(withJSONObject: parameters, options: []) mutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableRequest.httpBody = data } catch let error { throw error } } else { // `parameters` is not a valid JSON object throw BridgeErrorType.encoding } } } return mutableRequest } public func serialize(_ data: Data) throws -> ResponseObject { switch self { case .json: let serializedObject: Any? do { serializedObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) } catch { throw BridgeErrorType.serializing } if let object = serializedObject as? Array<Any> { return ResponseObject.jsonArray(object) } else if let object = serializedObject as? Dict { return ResponseObject.jsonDict(object) } } throw BridgeErrorType.serializing } func escapeString(_ string: String) -> String { let allowedDelimiters: String = ":#[]@!$&'()*+,;=" var customAllowedSet = CharacterSet.urlQueryAllowed customAllowedSet.remove(charactersIn: allowedDelimiters) let escapedString = string.addingPercentEncoding(withAllowedCharacters: customAllowedSet) return escapedString! } public func serializeToString(_ data: Data) -> String? { switch self { case .json: return String(data: data, encoding: String.Encoding.utf8) } } } public enum ResponseObject { case jsonArray(Array<Any>) case jsonDict(Dict) public func rawValue() -> Any { switch self { case .jsonArray(let arrayValue): return arrayValue as Any case .jsonDict(let dictionaryValue): return dictionaryValue as Any } } public subscript(key: String) -> Any? { switch self { case .jsonDict(let dictionaryValue): return dictionaryValue[key] default: return nil } } }
e9b69421d64963bc79a810a0cf4e8113
33.892562
159
0.527949
false
false
false
false
ColinConduff/BlocFit
refs/heads/master
BlocFit/Supporting Files/Supporting Models/BFUserDefaults.swift
mit
1
// // BFUserDefaults.swift // BlocFit // // Created by Colin Conduff on 11/8/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import Foundation struct BFUserDefaults { static let unitSetting = "unitsSetting" static let friendsDefaultTrusted = "friendsDefaultTrusted" static let shareFirstNameWithTrusted = "shareFirstNameWithTrusted" static func stringFor(unitsSetting isImperialUnits: Bool) -> String { if isImperialUnits { return "Imperial (mi)" } else { return "Metric (km)" } } static func getUnitsSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.unitSetting) } static func set(isImperial: Bool) { let defaults = UserDefaults.standard defaults.set(isImperial, forKey: BFUserDefaults.unitSetting) } static func stringFor(friendsWillDefaultToTrusted defaultTrusted: Bool) -> String { if defaultTrusted { return "New friends are trusted by default" } else { return "New friends are untrusted by default" } } static func getNewFriendDefaultTrustedSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.friendsDefaultTrusted) } static func set(friendsWillDefaultToTrusted defaultTrusted: Bool) { let defaults = UserDefaults.standard defaults.set(defaultTrusted, forKey: BFUserDefaults.friendsDefaultTrusted) } static func stringFor(willShareFirstNameWithTrustedFriends willShareName: Bool) -> String { if willShareName { return "Share first name with trusted friends" } else { return "Do not share first name with trusted friends" } } static func getShareFirstNameWithTrustedSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.shareFirstNameWithTrusted) } static func set(willShareFirstNameWithTrustedFriends willShareName: Bool) { let defaults = UserDefaults.standard defaults.set(willShareName, forKey: BFUserDefaults.shareFirstNameWithTrusted) } }
b2c9b38a3fff8941017b8f24c51978c0
31.728571
95
0.672632
false
false
false
false
zhangao0086/DKImageBrowserVC
refs/heads/develop
DKPhotoGallery/Preview/ImagePreview/DKPhotoImageDownloader.swift
mit
2
// // DKPhotoImageDownloader.swift // DKPhotoGallery // // Created by ZhangAo on 2018/6/6. // Copyright © 2018 ZhangAo. All rights reserved. // import Foundation import Photos import MobileCoreServices #if canImport(SDWebImage) import SDWebImage #endif protocol DKPhotoImageDownloader { static func downloader() -> DKPhotoImageDownloader func downloadImage(with identifier: Any, progressBlock: ((_ progress: Float) -> Void)?, completeBlock: @escaping ((_ image: UIImage?, _ data: Data?, _ error: Error?) -> Void)) } class DKPhotoImageWebDownloader: DKPhotoImageDownloader { private static let shared = DKPhotoImageWebDownloader() static func downloader() -> DKPhotoImageDownloader { return shared } var _downloader: SDWebImageDownloader = { let config = SDWebImageDownloaderConfig() config.executionOrder = .lifoExecutionOrder let downloader = SDWebImageDownloader.init(config: config) return downloader }() func downloadImage(with identifier: Any, progressBlock: ((Float) -> Void)?, completeBlock: @escaping ((UIImage?, Data?, Error?) -> Void)) { if let URL = identifier as? URL { self._downloader.downloadImage(with: URL, options: .highPriority, progress: { (receivedSize, expectedSize, targetURL) in if let progressBlock = progressBlock { progressBlock(Float(receivedSize) / Float(expectedSize)) } }, completed: { (image, data, error, finished) in if (image != nil || data != nil) && finished { completeBlock(image, data, error) } else { let error = NSError(domain: Bundle.main.bundleIdentifier!, code: -1, userInfo: [ NSLocalizedDescriptionKey : DKPhotoGalleryResource.localizedStringWithKey("preview.image.fetch.error") ]) completeBlock(nil, nil, error) } }) } else { assertionFailure() } } } class DKPhotoImageAssetDownloader: DKPhotoImageDownloader { private static let shared = DKPhotoImageAssetDownloader() static func downloader() -> DKPhotoImageDownloader { return shared } func downloadImage(with identifier: Any, progressBlock: ((Float) -> Void)?, completeBlock: @escaping ((UIImage?, Data?, Error?) -> Void)) { if let asset = identifier as? PHAsset { let options = PHImageRequestOptions() options.resizeMode = .exact options.deliveryMode = .highQualityFormat options.isNetworkAccessAllowed = true if let progressBlock = progressBlock { options.progressHandler = { (progress, error, stop, info) in if progress > 0 { progressBlock(Float(progress)) } } } let isGif = (asset.value(forKey: "uniformTypeIdentifier") as? String) == (kUTTypeGIF as String) if isGif { PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (data, _, _, info) in if let data = data { completeBlock(nil, data, nil) } else { let error = NSError(domain: Bundle.main.bundleIdentifier!, code: -1, userInfo: [ NSLocalizedDescriptionKey : DKPhotoGalleryResource.localizedStringWithKey("preview.image.fetch.error") ]) completeBlock(nil, nil, error) } }) } else { PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: UIScreen.main.bounds.width * UIScreen.main.scale, height:UIScreen.main.bounds.height * UIScreen.main.scale), contentMode: .default, options: options, resultHandler: { (image, info) in if let image = image { completeBlock(image, nil, nil) } else { let error = NSError(domain: Bundle.main.bundleIdentifier!, code: -1, userInfo: [ NSLocalizedDescriptionKey : DKPhotoGalleryResource.localizedStringWithKey("preview.image.fetch.error") ]) completeBlock(nil, nil, error) } }) } } else { assertionFailure() } } }
95df9feb48155a360a76491b95c19915
45.071429
188
0.452885
false
false
false
false
HolidayAdvisorIOS/HolidayAdvisor
refs/heads/master
HolidayAdvisor/HolidayAdvisor/PlaceDetailsViewController.swift
mit
1
// // PlaceDetailsViewController.swift // HolidayAdvisor // // Created by Iliyan Gogov on 4/3/17. // Copyright © 2017 Iliyan Gogov. All rights reserved. // import UIKit class PlaceDetailsViewController: UIViewController { @IBOutlet weak var placeImage: UIImageView! @IBOutlet weak var placeNameLabel: UILabel! @IBOutlet weak var placeInfoLabel: UILabel! @IBOutlet weak var placeOwnerLabel: UILabel! var name : String? = "" var imageUrl: String? = "" var info: String? = "" var owner: String? = "" var rating: Int? = 0 override func viewDidLoad() { super.viewDidLoad() self.placeNameLabel.text = self.name self.placeOwnerLabel.text = self.owner self.placeInfoLabel.text = self.info if let url = NSURL(string: self.imageUrl!) { if let data = NSData(contentsOf: url as URL) { self.placeImage?.image = UIImage(data: data as Data) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
b2a03c11efd6406a069dd261207308f7
27.296296
106
0.63678
false
false
false
false
JGiola/swift-package-manager
refs/heads/master
Sources/Utility/StringExtensions.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ extension String { /** Remove trailing newline characters. By default chomp removes all trailing \n (UNIX) or all trailing \r\n (Windows) (it will not remove mixed occurrences of both separators. */ public func spm_chomp(separator: String? = nil) -> String { func scrub(_ separator: String) -> String { var E = endIndex while String(self[startIndex..<E]).hasSuffix(separator) && E > startIndex { E = index(before: E) } return String(self[startIndex..<E]) } if let separator = separator { return scrub(separator) } else if hasSuffix("\r\n") { return scrub("\r\n") } else if hasSuffix("\n") { return scrub("\n") } else { return self } } /** Trims whitespace from both ends of a string, if the resulting string is empty, returns `nil`.String Useful because you can short-circuit off the result and thus handle “falsy” strings in an elegant way: return userInput.chuzzle() ?? "default value" */ public func spm_chuzzle() -> String? { var cc = self loop: while true { switch cc.first { case nil: return nil case "\n"?, "\r"?, " "?, "\t"?, "\r\n"?: cc = String(cc.dropFirst()) default: break loop } } loop: while true { switch cc.last { case nil: return nil case "\n"?, "\r"?, " "?, "\t"?, "\r\n"?: cc = String(cc.dropLast()) default: break loop } } return String(cc) } /// Splits string around a delimiter string into up to two substrings /// If delimiter is not found, the second returned substring is nil public func spm_split(around delimiter: String) -> (String, String?) { let comps = self.spm_split(around: Array(delimiter)) let head = String(comps.0) if let tail = comps.1 { return (head, String(tail)) } else { return (head, nil) } } }
0cb89b2a32fb5a06dbeb9d245b55a56c
29.294118
87
0.537476
false
false
false
false
Longhanks/gtk-test
refs/heads/master
Sources/gtk-test/SWGtkOrientation.swift
mit
1
// // Created by Andreas Schulz on 05.06.16. // import Foundation import Gtk struct SWGtkOrientation : OptionSet { let rawValue : GtkOrientation init(rawValue: GtkOrientation) { self.rawValue = rawValue } init() { rawValue = GTK_ORIENTATION_HORIZONTAL } mutating func formUnion(_ other: SWGtkOrientation) {} mutating func formIntersection(_ other: SWGtkOrientation) {} mutating func formSymmetricDifference(_ other: SWGtkOrientation) {} static let Horizontal = SWGtkOrientation(rawValue: GTK_ORIENTATION_HORIZONTAL) static let Vertical = SWGtkOrientation(rawValue: GTK_ORIENTATION_VERTICAL) } extension GtkOrientation: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = Int public init(integerLiteral: IntegerLiteralType) { self.init(UInt32(integerLiteral)) } }
4155c7cc12ea86fc62406d7c8010ab59
25.151515
82
0.726218
false
false
false
false
eppeo/FYSliderView
refs/heads/master
FYBannerView/Classes/View/BannerPageControl.swift
mit
2
// // TimerDelegate.swift // FYBannerView // // Created by 武飞跃 on 2017/4/10. // import Foundation public class BannerPageControl: UIView { public var borderColor: UIColor = UIColor.white.withAlphaComponent(0.6) public var normalColor: UIColor = UIColor.white.withAlphaComponent(0.6) public var selectorColor: UIColor = UIColor.white public var isHidesForSinglePage: Bool = true /** pageControl的样式*/ internal var style: BannerPageControlStyle! internal var numberOfPages: Int = 0 { didSet { updateLayer() invalidateIntrinsicContentSize() if defaultActiveStatus { defaultActiveStatus = false //默认第一个显示 changeActivity(index: 0, isActive: true) } } } internal var currentPage:Int = 0 { willSet{ if newValue == currentPage { return } changeActivity(index: newValue, isActive: true) } didSet{ if currentPage == oldValue { return } changeActivity(index: oldValue, isActive: false) } } private var defaultActiveStatus: Bool = true private var dots:[DotLayer] = [] { didSet{ if dots.count == 1 { if isHidesForSinglePage { dots.first?.isHidden = true } else{ changeActivity(index: 0, isActive: true) } } else{ dots.first?.isHidden = false } } } private func changeActivity(index: Int, isActive: Bool){ guard index >= 0 && index < dots.count else { return } if isActive == true { dots[index].startAnimation() } else{ dots[index].stopAnimation() } } private func createLayer() -> DotLayer { var dot: DotLayer! switch style.type { case .ring: let ringDot = RingDotLayer(size: CGSize(width: style.width, height: style.height), borderWidth: style.borderWidth) ringDot.normalColor = normalColor.cgColor ringDot.selectedColor = selectorColor.cgColor dot = ringDot } defer { dots.append(dot) } dot.anchorPoint = CGPoint.zero dot.stopAnimation() return dot } public override var intrinsicContentSize: CGSize { return style.calcDotSize(num: numberOfPages) } /// 移除多余layer /// /// - Parameter num: 需要移除的layer个数 private func removeLayer(num:Int){ if let unwrapped = layer.sublayers, unwrapped.count >= num { for _ in 0 ..< num { layer.sublayers?.last?.removeFromSuperlayer() } } let range:Range<Int> = numberOfPages ..< dots.count dots.removeSubrange(range) } private func updateLayer(){ let sub = dots.count - numberOfPages if sub > 0 { removeLayer(num: sub) } else if sub < 0 { addLayer() } } private func addLayer(){ for i in 0 ..< numberOfPages { var dot: CALayer! if dots.count > i { dot = dots[i] } else{ dot = createLayer() } let point = style.calcDotPosition(index: i) dot.position = point layer.addSublayer(dot) } } }
888792a31e280499a45e1a182d39f664
23.993333
126
0.496666
false
false
false
false
digitwolf/SwiftFerrySkill
refs/heads/master
Sources/Ferry/Models/SpaceForArrivalTerminals.swift
apache-2.0
1
// // SpaceForArrivalTerminals.swift // FerrySkill // // Created by Shakenova, Galiya on 3/3/17. // // import Foundation import SwiftyJSON public class SpaceForArrivalTerminals { public var terminalID : Int? = 0 public var terminalName : String? = "" public var vesselID : Int? = 0 public var vesselName : String? = "" public var displayReservableSpace : Bool? = false public var reservableSpaceCount : Int? = 0 public var reservableSpaceHexColor : String? = "" public var displayDriveUpSpace : Bool? = false public var driveUpSpaceCount : Int? = 0 public var driveUpSpaceHexColor : String? = "" public var maxSpaceCount : Int? = 0 public var arrivalTerminalIDs: [Int] = [] init() { } public init(_ json: JSON) { terminalID = json["TerminalID"].intValue terminalName = json["TerminalName"].stringValue vesselName = json["VesselName"].stringValue vesselID = json["VesselID"].intValue displayReservableSpace = json["DisplayReservableSpace"].boolValue reservableSpaceCount = json["ReservableSpaceCount"].intValue reservableSpaceHexColor = json["ReservableSpaceHexColor"].stringValue displayDriveUpSpace = json["DisplayDriveUpSpace"].boolValue driveUpSpaceCount = json["DriveUpSpaceCount"].intValue driveUpSpaceHexColor = json["DriveUpSpaceHexColor"].stringValue maxSpaceCount = json["MaxSpaceCount"].intValue for terminal in json["ArrivalTerminalIDs"].arrayValue { arrivalTerminalIDs.append(terminal.intValue) } } public func toJson() -> JSON { var json = JSON([]) json["TerminalID"].intValue = terminalID! json["TerminalName"].stringValue = terminalName! json["VesselName"].stringValue = vesselName! json["VesselID"].intValue = vesselID! json["DisplayReservableSpace"].boolValue = displayReservableSpace! json["ReservableSpaceCount"].intValue = reservableSpaceCount! json["ReservableSpaceHexColor"].stringValue = reservableSpaceHexColor! json["DisplayDriveUpSpace"].boolValue = displayDriveUpSpace! json["DriveUpSpaceCount"].intValue = driveUpSpaceCount! json["DriveUpSpaceHexColor"].stringValue = driveUpSpaceHexColor! json["MaxSpaceCount"].intValue = maxSpaceCount! var terminals: [Int] = [] for terminal in arrivalTerminalIDs { terminals.append(terminal) } json["ArrivalTerminalIDs"] = JSON(terminals) return json } }
5b296b64fa7cb8f0aca585abe295bad7
36.710145
78
0.669101
false
false
false
false
Vostro162/VaporTelegram
refs/heads/master
Sources/App/Document+Extensions.swift
mit
1
// // Document+Extensions.swift // VaporTelegram // // Created by Marius Hartig on 11.05.17. // // import Foundation import Vapor // MARK: - JSON extension Document: JSONInitializable { public init(json: JSON) throws { guard let fileId = json["file_id"]?.string else { throw VaporTelegramError.parsing } self.fileId = fileId /* * * Optionals * */ if let fileName = json["file_name"]?.string { self.fileName = fileName } else { self.fileName = nil } if let mimeType = json["mime_type"]?.string { self.mimeType = mimeType } else { self.mimeType = nil } if let fileSize = json["file_size"]?.int { self.fileSize = fileSize } else { self.fileSize = nil } if let json = json["thumb"], let thumb = try? PhotoSize(json: json) { self.thumb = thumb } else { self.thumb = nil } } }
5aff76ade8113bc7cc6c1e43e252182b
19.690909
77
0.465729
false
false
false
false
crspybits/SyncServerII
refs/heads/dev
Tests/ServerTests/SpecificDatabaseTests_SharingGroups.swift
mit
1
// // SpecificDatabaseTests_SharingGroups.swift // ServerTests // // Created by Christopher G Prince on 7/4/18. // import XCTest @testable import Server import LoggerAPI import HeliumLogger import Foundation import SyncServerShared class SpecificDatabaseTests_SharingGroups: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAddSharingGroupWithoutName() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } } func testAddSharingGroupWithName() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID, sharingGroupName: "Foobar") else { XCTFail() return } } func testLookupFromSharingGroupExisting() { let sharingGroupUUID = UUID().uuidString guard addSharingGroup(sharingGroupUUID: sharingGroupUUID) else { XCTFail() return } let key = SharingGroupRepository.LookupKey.sharingGroupUUID(sharingGroupUUID) let result = SharingGroupRepository(db).lookup(key: key, modelInit: SharingGroup.init) switch result { case .found(let model): guard let obj = model as? Server.SharingGroup else { XCTFail() return } XCTAssert(obj.sharingGroupUUID != nil) case .noObjectFound: XCTFail("No object found") case .error(let error): XCTFail("Error: \(error)") } } func testLookupFromSharingGroupNonExisting() { let key = SharingGroupRepository.LookupKey.sharingGroupUUID(UUID().uuidString) let result = SharingGroupRepository(db).lookup(key: key, modelInit: SharingGroup.init) switch result { case .found: XCTFail() case .noObjectFound: break case .error(let error): XCTFail("Error: \(error)") } } } extension SpecificDatabaseTests_SharingGroups { static var allTests : [(String, (SpecificDatabaseTests_SharingGroups) -> () throws -> Void)] { return [ ("testAddSharingGroupWithoutName", testAddSharingGroupWithoutName), ("testAddSharingGroupWithName", testAddSharingGroupWithName), ("testLookupFromSharingGroupExisting", testLookupFromSharingGroupExisting), ("testLookupFromSharingGroupNonExisting", testLookupFromSharingGroupNonExisting) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SpecificDatabaseTests_SharingGroups.self) } }
89b702212b3477756d6b306adbe85cd1
31.752688
111
0.648063
false
true
false
false
crashlytics/cannonball-ios
refs/heads/master
Cannonball/ThemeChooserViewController.swift
apache-2.0
2
// // Copyright (C) 2017 Google, Inc. and other contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import QuartzCore import Crashlytics class ThemeChooserViewController: UITableViewController { // MARK: Properties @IBOutlet weak var historyButton: UIBarButtonItem! @IBOutlet weak var tweetsButton: UIBarButtonItem! var logoView: UIImageView! var themes: [Theme] = [] let themeTableCellReuseIdentifier = "ThemeCell" // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Retrieve the themes. themes = Theme.getThemes() // Add the logo view to the top (not in the navigation bar title in order to position it better). logoView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) logoView.image = UIImage(named: "Logo")?.withRenderingMode(.alwaysTemplate) logoView.tintColor = UIColor.cannonballGreenColor() logoView.frame.origin.x = (view.frame.size.width - logoView.frame.size.width) / 2 logoView.frame.origin.y = -logoView.frame.size.height - 10 navigationController?.view.addSubview(logoView) navigationController?.view.bringSubview(toFront: logoView) let logoTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ThemeChooserViewController.logoTapped)) logoView.isUserInteractionEnabled = true logoView.addGestureRecognizer(logoTapRecognizer) // Prevent vertical bouncing. tableView.alwaysBounceVertical = false // Add a table header and computer the cell height so they perfectly fit the screen. let headerHeight: CGFloat = 15 let contentHeight = view.frame.size.height - headerHeight let navHeight = navigationController?.navigationBar.frame.height let navYOrigin = navigationController?.navigationBar.frame.origin.y tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: headerHeight)) // Compute the perfect table cell height to fit the content. let themeTableCellHeight = (contentHeight - navHeight! - navYOrigin!) / CGFloat(themes.count) tableView.rowHeight = themeTableCellHeight // Customize the navigation bar. let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.cannonballGreenColor()] navigationController?.navigationBar.titleTextAttributes = titleDict as? [String : AnyObject] navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.topItem?.title = "" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Animate the logo when the view appears. UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: UIViewAnimationOptions(), animations: { // Place the frame at the correct origin position. self.logoView.frame.origin.y = 8 }, completion: nil ) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Make sure the navigation bar is translucent. navigationController?.navigationBar.isTranslucent = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Move the logo view off screen if a new controller was pushed. if let vcCount = navigationController?.viewControllers.count, vcCount > 1 { UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: UIViewAnimationOptions(), animations: { // Place the frame at the correct origin position. self.logoView.frame.origin.y = -self.logoView.frame.size.height - 10 }, completion: nil ) } } // MARK: UIStoryboardSegue Handling // Pass the selected theme to the poem composer. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (sender! as AnyObject).isKind(of: ThemeCell.self) { let indexPath = tableView.indexPathForSelectedRow if let row = indexPath?.row { // Pass the selected theme to the poem composer. let poemComposerViewController = segue.destination as! PoemComposerViewController poemComposerViewController.theme = themes[row] // Tie this selected theme to any crashes in Crashlytics. Crashlytics.sharedInstance().setObjectValue(themes[row].name, forKey: "Theme") // Log Answers Custom Event. Answers.logCustomEvent(withName: "Selected Theme", customAttributes: ["Theme": themes[row].name]) } } } // Bring the about view when tapping the logo. func logoTapped() { performSegue(withIdentifier: "ShowAbout", sender: self) } // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return themes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: themeTableCellReuseIdentifier, for: indexPath) as! ThemeCell // Find the corresponding theme. let theme = themes[indexPath.row] // Configure the cell with the theme. cell.configureWithTheme(theme) // Return the theme cell. return cell } }
2603e4af09f2b0d186eb372027e61694
39.821656
147
0.677173
false
false
false
false
hollance/swift-algorithm-club
refs/heads/master
Graph/Graph/AdjacencyMatrixGraph.swift
mit
4
// // AdjacencyMatrixGraph.swift // Graph // // Created by Andrew McKnight on 5/13/16. // import Foundation open class AdjacencyMatrixGraph<T>: AbstractGraph<T> where T: Hashable { // If adjacencyMatrix[i][j] is not nil, then there is an edge from // vertex i to vertex j. fileprivate var adjacencyMatrix: [[Double?]] = [] fileprivate var _vertices: [Vertex<T>] = [] public required init() { super.init() } public required init(fromGraph graph: AbstractGraph<T>) { super.init(fromGraph: graph) } open override var vertices: [Vertex<T>] { return _vertices } open override var edges: [Edge<T>] { var edges = [Edge<T>]() for row in 0 ..< adjacencyMatrix.count { for column in 0 ..< adjacencyMatrix.count { if let weight = adjacencyMatrix[row][column] { edges.append(Edge(from: vertices[row], to: vertices[column], weight: weight)) } } } return edges } // Adds a new vertex to the matrix. // Performance: possibly O(n^2) because of the resizing of the matrix. open override func createVertex(_ data: T) -> Vertex<T> { // check if the vertex already exists let matchingVertices = vertices.filter { vertex in return vertex.data == data } if matchingVertices.count > 0 { return matchingVertices.last! } // if the vertex doesn't exist, create a new one let vertex = Vertex(data: data, index: adjacencyMatrix.count) // Expand each existing row to the right one column. for i in 0 ..< adjacencyMatrix.count { adjacencyMatrix[i].append(nil) } // Add one new row at the bottom. let newRow = [Double?](repeating: nil, count: adjacencyMatrix.count + 1) adjacencyMatrix.append(newRow) _vertices.append(vertex) return vertex } open override func addDirectedEdge(_ from: Vertex<T>, to: Vertex<T>, withWeight weight: Double?) { adjacencyMatrix[from.index][to.index] = weight } open override func addUndirectedEdge(_ vertices: (Vertex<T>, Vertex<T>), withWeight weight: Double?) { addDirectedEdge(vertices.0, to: vertices.1, withWeight: weight) addDirectedEdge(vertices.1, to: vertices.0, withWeight: weight) } open override func weightFrom(_ sourceVertex: Vertex<T>, to destinationVertex: Vertex<T>) -> Double? { return adjacencyMatrix[sourceVertex.index][destinationVertex.index] } open override func edgesFrom(_ sourceVertex: Vertex<T>) -> [Edge<T>] { var outEdges = [Edge<T>]() let fromIndex = sourceVertex.index for column in 0..<adjacencyMatrix.count { if let weight = adjacencyMatrix[fromIndex][column] { outEdges.append(Edge(from: sourceVertex, to: vertices[column], weight: weight)) } } return outEdges } open override var description: String { var grid = [String]() let n = self.adjacencyMatrix.count for i in 0..<n { var row = "" for j in 0..<n { if let value = self.adjacencyMatrix[i][j] { let number = NSString(format: "%.1f", value) row += "\(value >= 0 ? " " : "")\(number) " } else { row += " ø " } } grid.append(row) } return (grid as NSArray).componentsJoined(by: "\n") } }
8e7743c33db541df2203b5cc7dc9f762
28
104
0.637931
false
false
false
false
J-Mendes/Weather
refs/heads/master
Weather/Weather/Core Layer/Data Model/Astronomy.swift
gpl-3.0
1
// // Astronomy.swift // Weather // // Created by Jorge Mendes on 05/07/17. // Copyright © 2017 Jorge Mendes. All rights reserved. // import Foundation struct Astronomy { internal var sunrise: Date! internal var sunset: Date! init() { self.sunrise = Date() self.sunset = Date() } init(dictionary: [String: Any]) { self.init() if let sunriseString: String = dictionary["sunrise"] as? String, let sunrise: Date = sunriseString.dateValueFromHour() { self.sunrise = sunrise } if let sunsetString: String = dictionary["sunset"] as? String, let sunset: Date = sunsetString.dateValueFromHour() { self.sunset = sunset } } }
87f7fa5fbc82b243225da71fdb65ca3e
21.4
72
0.566327
false
false
false
false
ColinConduff/BlocFit
refs/heads/master
BlocFit/CoreData/ManagedObjects/RunPoint+CoreDataClass.swift
mit
1
// // RunPoint+CoreDataClass.swift // BlocFit // // Created by Colin Conduff on 10/1/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import CoreLocation import CoreData public class RunPoint: NSManagedObject { static let entityName = "RunPoint" /* longitude: Double latitude: Double timestamp: NSDate? metersFromLastPoint: Double run: Run? */ class func create( latitude: Double, longitude: Double, run: Run, lastRunPoint: RunPoint?, // must pass in nil if first run point context: NSManagedObjectContext) throws -> RunPoint? { var runPoint: RunPoint? context.performAndWait { runPoint = NSEntityDescription.insertNewObject( forEntityName: RunPoint.entityName, into: context) as? RunPoint runPoint?.run = run runPoint?.timestamp = NSDate() runPoint?.latitude = latitude runPoint?.longitude = longitude if let lastLatitude = lastRunPoint?.latitude, let lastLongitude = lastRunPoint?.longitude { let current2DCoordinates = CLLocationCoordinate2D( latitude: latitude, longitude: longitude) let last2DCoordinates = CLLocationCoordinate2D( latitude: lastLatitude, longitude: lastLongitude) let currentLocation = CLLocation( latitude: current2DCoordinates.latitude, longitude: current2DCoordinates.longitude) let lastLocation = CLLocation( latitude: last2DCoordinates.latitude, longitude: last2DCoordinates.longitude) let distance = currentLocation.distance(from: lastLocation) runPoint?.metersFromLastPoint = distance } else { runPoint?.metersFromLastPoint = 0 } } try context.save() return runPoint } func delete() throws { self.managedObjectContext?.delete(self) try self.managedObjectContext?.save() } }
e6858c669cf78af5097d827bfee0a3dd
29.61039
75
0.54773
false
false
false
false
josipbernat/Hasher
refs/heads/master
Carthage/Checkouts/CryptoSwift/Sources/CryptoSwift/Updatable.swift
mit
4
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /// A type that supports incremental updates. For example Digest or Cipher may be updatable /// and calculate result incerementally. public protocol Updatable { /// Update given bytes in chunks. /// /// - parameter bytes: Bytes to process. /// - parameter isLast: Indicate if given chunk is the last one. No more updates after this call. /// - returns: Processed partial result data or empty array. mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> /// Update given bytes in chunks. /// /// - Parameters: /// - bytes: Bytes to process. /// - isLast: Indicate if given chunk is the last one. No more updates after this call. /// - output: Resulting bytes callback. /// - Returns: Processed partial result data or empty array. mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool, output: (_ bytes: Array<UInt8>) -> Void) throws } extension Updatable { public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws { let processed = try update(withBytes: bytes, isLast: isLast) if !processed.isEmpty { output(processed) } } public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { return try update(withBytes: bytes, isLast: isLast) } public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { return try update(withBytes: bytes.slice, isLast: isLast) } public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws { return try update(withBytes: bytes.slice, isLast: isLast, output: output) } /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - returns: Processed data. public mutating func finish(withBytes bytes: ArraySlice<UInt8>) throws -> Array<UInt8> { return try update(withBytes: bytes, isLast: true) } public mutating func finish(withBytes bytes: Array<UInt8>) throws -> Array<UInt8> { return try finish(withBytes: bytes.slice) } /// Finish updates. May add padding. /// /// - Returns: Processed data /// - Throws: Error public mutating func finish() throws -> Array<UInt8> { return try update(withBytes: [], isLast: true) } /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - parameter output: Resulting data /// - returns: Processed data. public mutating func finish(withBytes bytes: ArraySlice<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws { let processed = try update(withBytes: bytes, isLast: true) if !processed.isEmpty { output(processed) } } public mutating func finish(withBytes bytes: Array<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws { return try finish(withBytes: bytes.slice, output: output) } /// Finish updates. May add padding. /// /// - Parameter output: Processed data /// - Throws: Error public mutating func finish(output: (Array<UInt8>) -> Void) throws { try finish(withBytes: [], output: output) } }
5f3bd80aa5c63c6f6078e0eecac5e786
42.816327
217
0.676991
false
false
false
false