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
crspybits/SyncServerII
refs/heads/dev
Sources/Server/Account Specifics/Microsoft/MicrosoftCreds.swift
mit
1
// // MicrosoftCreds.swift // Server // // Created by Christopher G Prince on 9/1/19. // import Foundation import Kitura import SyncServerShared import LoggerAPI import HeliumLogger import KituraNet // Assumes that the microsft app has been registered as multi-tenant. E.g., see https://docs.microsoft.com/en-us/graph/auth-register-app-v2?context=graph%2Fapi%2F1.0&view=graph-rest-1.0 // Originally, I thought I had to register two apps (a server and a client)-- E.g., https://paulryan.com.au/2017/oauth-on-behalf-of-flow-adal/ HOWEVER, I have only a client iOS app registered (and using that client id and secret) and thats working. class MicrosoftCreds : AccountAPICall, Account { static var accountScheme: AccountScheme = .microsoft var accountScheme: AccountScheme { return MicrosoftCreds.accountScheme } var owningAccountsNeedCloudFolderName: Bool = false var delegate: AccountDelegate? var accountCreationUser: AccountCreationUser? // Don't use the "accessToken" from the iOS MSAL for this; use the iOS MSAL idToken. var accessToken: String! var refreshToken: String? private var alreadyRefreshed = false private let scopes = "https://graph.microsoft.com/user.read+offline_access" override init?() { super.init() baseURL = "login.microsoftonline.com/common" } func needToGenerateTokens(dbCreds: Account?) -> Bool { // If we get fancy, eventually we could look at the expiry date/time in the JWT access token and estimate if we need to generate tokens. return true } enum MicrosoftError: Swift.Error { case noAccessToken case failedGettingClientIdOrSecret case badStatusCode(HTTPStatusCode?) case nilAPIResult case noDataInResult case couldNotDecodeTokens case errorSavingCredsToDatabase case noRefreshToken } struct MicrosoftTokens: Decodable { let token_type: String let scope: String let expires_in: Int let ext_expires_in: Int let access_token: String let refresh_token: String } private struct ClientInfo { let id: String let secret: String } func encoded(string: String, baseCharSet: CharacterSet = .urlQueryAllowed, additionalExcludedCharacters: String? = nil) -> String? { var charSet: CharacterSet = baseCharSet if let additionalExcludedCharacters = additionalExcludedCharacters { for char in additionalExcludedCharacters { if let scalar = char.unicodeScalars.first { charSet.remove(scalar) } } } return string.addingPercentEncoding(withAllowedCharacters: charSet) } private func getClientInfo() -> ClientInfo? { guard let clientId = Configuration.server.MicrosoftClientId, let clientSecret = Configuration.server.MicrosoftClientSecret else { Log.error("No client id or secret.") return nil } // Encode the secret-- without this, my call fails with: // AADSTS7000215: Invalid client secret is provided. // See https://stackoverflow.com/questions/41133573/microsoft-graph-rest-api-invalid-client-secret guard let clientSecretEncoded = encoded(string: clientSecret, additionalExcludedCharacters: ",/?:@&=+$#") else { Log.error("Failed encoding client secret.") return nil } return ClientInfo(id: clientId, secret: clientSecretEncoded) } /// If successful, sets the `refreshToken`. The `accessToken` must be set prior to this call. The access token, when used from the iOS MSAL library, must be the "idToken" and not the iOS MSAL "accessToken". The accessToken from the iOS MSAL library is not a JWT -- when I use it I get: "AADSTS50027: JWT token is invalid or malformed". func generateTokens(response: RouterResponse?, completion:@escaping (Swift.Error?)->()) { guard let accessToken = accessToken else{ Log.info("No accessToken from client.") completion(MicrosoftError.noAccessToken) return } guard let clientInfo = getClientInfo() else { completion(MicrosoftError.failedGettingClientIdOrSecret) return } // https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow let grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer" let scopes = "https://graph.microsoft.com/user.read+offline_access" let bodyParameters = "grant_type=\(grantType)" + "&" + "client_id=\(clientInfo.id)" + "&" + "client_secret=\(clientInfo.secret)" + "&" + "assertion=\(accessToken)" + "&" + "scope=\(scopes)" + "&" + "requested_token_use=on_behalf_of" // Log.debug("bodyParameters: \(bodyParameters)") let additionalHeaders = ["Content-Type": "application/x-www-form-urlencoded"] self.apiCall(method: "POST", path: "/oauth2/v2.0/token", additionalHeaders:additionalHeaders, body: .string(bodyParameters), expectedSuccessBody: .data) { apiResult, statusCode, responseHeaders in guard statusCode == HTTPStatusCode.OK else { completion(MicrosoftError.badStatusCode(statusCode)) return } guard let apiResult = apiResult else { completion(MicrosoftError.nilAPIResult) return } guard case .data(let data) = apiResult else { completion(MicrosoftError.noDataInResult) return } let tokens: MicrosoftTokens let decoder = JSONDecoder() do { tokens = try decoder.decode(MicrosoftTokens.self, from: data) } catch let error { Log.error("Error decoding token result: \(error)") completion(MicrosoftError.couldNotDecodeTokens) return } self.accessToken = tokens.access_token self.refreshToken = tokens.refresh_token guard let delegate = self.delegate else { Log.warning("No Microsoft Creds delegate!") completion(nil) return } if delegate.saveToDatabase(account: self) { completion(nil) } else { completion(MicrosoftError.errorSavingCredsToDatabase) } } } // Use the refresh token to generate a new access token. // If error is nil when the completion handler is called, then the accessToken of this object has been refreshed. Uses delegate, if one is defined, to save refreshed creds to database. func refresh(completion:@escaping (Swift.Error?)->()) { // https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow guard let refreshToken = refreshToken else { completion(MicrosoftError.noRefreshToken) return } guard let clientInfo = getClientInfo() else { completion(MicrosoftError.failedGettingClientIdOrSecret) return } let grantType = "refresh_token" let bodyParameters = "grant_type=\(grantType)" + "&" + "client_id=\(clientInfo.id)" + "&" + "client_secret=\(clientInfo.secret)" + "&" + "scope=\(scopes)" + "&" + "refresh_token=\(refreshToken)" // Log.debug("bodyParameters: \(bodyParameters)") let additionalHeaders = ["Content-Type": "application/x-www-form-urlencoded"] self.apiCall(method: "POST", path: "/oauth2/v2.0/token", additionalHeaders:additionalHeaders, body: .string(bodyParameters), expectedSuccessBody: .data, expectedFailureBody: .json) { apiResult, statusCode, responseHeaders in guard statusCode == HTTPStatusCode.OK else { Log.error("Bad status code: \(String(describing: statusCode))") completion(MicrosoftError.badStatusCode(statusCode)) return } guard let apiResult = apiResult else { Log.error("API result was nil!") completion(MicrosoftError.nilAPIResult) return } guard case .data(let data) = apiResult else { completion(MicrosoftError.noDataInResult) return } let tokens: MicrosoftTokens let decoder = JSONDecoder() do { tokens = try decoder.decode(MicrosoftTokens.self, from: data) } catch let error { Log.error("Error decoding token result: \(error)") completion(MicrosoftError.couldNotDecodeTokens) return } // Log.debug("tokens.access_token: \(tokens.access_token)") self.accessToken = tokens.access_token self.refreshToken = tokens.refresh_token guard let delegate = self.delegate else { Log.warning("No Microsoft Creds delegate!") completion(nil) return } if delegate.saveToDatabase(account: self) { completion(nil) } else { completion(MicrosoftError.errorSavingCredsToDatabase) } } } func merge(withNewer account: Account) { guard let newerCreds = account as? MicrosoftCreds else { assertionFailure("Wrong other type of creds!") return } if let refreshToken = newerCreds.refreshToken { self.refreshToken = refreshToken } if let accessToken = newerCreds.accessToken { self.accessToken = accessToken } } static func getProperties(fromRequest request:RouterRequest) -> [String: Any] { var result = [String: Any]() if let accessToken = request.headers[ServerConstants.HTTPOAuth2AccessTokenKey] { result[ServerConstants.HTTPOAuth2AccessTokenKey] = accessToken } return result } static func fromProperties(_ properties: AccountManager.AccountProperties, user:AccountCreationUser?, delegate:AccountDelegate?) -> Account? { guard let creds = MicrosoftCreds() else { return nil } creds.accountCreationUser = user creds.delegate = delegate creds.accessToken = properties.properties[ServerConstants.HTTPOAuth2AccessTokenKey] as? String return creds } func toJSON() -> String? { var jsonDict = [String:String]() jsonDict[MicrosoftCreds.accessTokenKey] = self.accessToken jsonDict[MicrosoftCreds.refreshTokenKey] = self.refreshToken return JSONExtras.toJSONString(dict: jsonDict) } static func fromJSON(_ json: String, user: AccountCreationUser, delegate: AccountDelegate?) throws -> Account? { guard let jsonDict = json.toJSONDictionary() as? [String:String] else { Log.error("Could not convert string to JSON [String:String]: \(json)") return nil } guard let result = MicrosoftCreds() else { return nil } result.delegate = delegate result.accountCreationUser = user switch user { case .user(let user) where AccountScheme(.accountName(user.accountType))?.userType == .owning: fallthrough case .userId: try setProperty(jsonDict:jsonDict, key: accessTokenKey) { value in result.accessToken = value } default: // Sharing users not allowed. assert(false) } try setProperty(jsonDict:jsonDict, key: refreshTokenKey, required:false) { value in result.refreshToken = value } return result } override func apiCall(method:String, baseURL:String? = nil, path:String, additionalHeaders: [String:String]? = nil, additionalOptions: [ClientRequest.Options] = [], urlParameters:String? = nil, body:APICallBody? = nil, returnResultWhenNon200Code:Bool = true, expectedSuccessBody:ExpectedResponse? = nil, expectedFailureBody:ExpectedResponse? = nil, completion:@escaping (_ result: APICallResult?, HTTPStatusCode?, _ responseHeaders: HeadersContainer?)->()) { super.apiCall(method: method, baseURL: baseURL, path: path, additionalHeaders: additionalHeaders, additionalOptions: additionalOptions, urlParameters: urlParameters, body: body, returnResultWhenNon200Code: returnResultWhenNon200Code, expectedSuccessBody: expectedSuccessBody, expectedFailureBody: expectedFailureBody) { (apiCallResult, statusCode, responseHeaders) in var headers:[String:String] = additionalHeaders ?? [:] if self.expiredAccessToken(apiResult: apiCallResult, statusCode: statusCode) && !self.alreadyRefreshed { self.alreadyRefreshed = true Log.info("Attempting to refresh Microsoft access token...") self.refresh() { error in if let error = error { let message = "Failed refreshing access token: \(error)" let errorResult = ErrorResult(error: MicrosoftCreds.ErrorResult.TheError(code: MicrosoftCreds.ErrorResult.invalidAuthToken, message: message)) let encoder = JSONEncoder() guard let response = try? encoder.encode(errorResult) else { completion( APICallResult.dictionary(["error": message]), .unauthorized, nil) return } Log.error("\(message)") completion(APICallResult.data(response), .unauthorized, nil) } else { Log.info("Successfully refreshed access token!") // Refresh was successful, update the authorization header and try the operation again. headers["Authorization"] = "Bearer \(self.accessToken!)" super.apiCall(method: method, baseURL: baseURL, path: path, additionalHeaders: headers, additionalOptions: additionalOptions, urlParameters: urlParameters, body: body, returnResultWhenNon200Code: returnResultWhenNon200Code, expectedSuccessBody: expectedSuccessBody, expectedFailureBody: expectedFailureBody, completion: completion) } } } else { completion(apiCallResult, statusCode, responseHeaders) } } } private func expiredAccessToken(apiResult: APICallResult?, statusCode: HTTPStatusCode?) -> Bool { guard let apiResult = apiResult else { return false } guard case .data(let data) = apiResult else { return false } let decoder = JSONDecoder() guard let errorResult = try? decoder.decode(ErrorResult.self, from: data) else { return false } return self.accessTokenIsRevokedOrExpired(errorResult: errorResult, statusCode: statusCode) } }
d927c0394ebc55f95998afc76ab1ae46
38.748148
355
0.593241
false
false
false
false
vysotsky/WhatsTheWeatherIn
refs/heads/master
WhatsTheWeatherIn/BaseViewController.swift
mit
1
// // BaseViewController.swift // WhatsTheWeatherIn // // Created by Vlad on 4/15/16. // Copyright © 2016 marinbenc. All rights reserved. // import UIKit import RxSwift class BaseTableViewController: UITableViewController { var disposeBag = DisposeBag() internal func bindSourceToLabel(_ source: PublishSubject<String?>, label: UILabel) { source .subscribe(onNext: { text in self.dispatchInMainQueue { label.text = text } }) .addDisposableTo(disposeBag) } internal func bindSourceToImageView(_ source: PublishSubject<UIImage?>, imageView: UIImageView) { source .subscribe(onNext: { image in self.dispatchInMainQueue { imageView.image = image } }) .addDisposableTo(disposeBag) } internal func bindSourceToImageView(_ source: PublishSubject<URL?>, imageView: UIImageView) { source .subscribe(onNext: { url in self.dispatchInMainQueue { if let url = url { let imageLoader = AppDelegate.resolve(ImageLoaderType.self) imageLoader.loadImageTo(imageView, url: url) } else { imageView.image = nil } } }) .addDisposableTo(disposeBag) } internal func bindSourceToHandler<U>(_ source: PublishSubject<U?>, handler: @escaping (U?) -> Void) { source .subscribe(onNext: { data in self.dispatchInMainQueue { handler(data) } }) .addDisposableTo(disposeBag) } }
89b57bc65589912fdca334d6b63ccecb
29.981481
105
0.570233
false
false
false
false
danielrhodes/ActiveLabel.swift
refs/heads/master
ActiveLabel/RegexParser.swift
mit
1
// // RegexParser.swift // ActiveLabel // // Created by Pol Quintana on 06/01/16. // Copyright © 2016 Optonaut. All rights reserved. // import Foundation struct RegexParser { static let urlPattern = "(?:[^|[\\s.:;?\\-\\]<\\(]])?" + "((https?://|www\\.|pic\\.)[-\\w;/?:@&=+$\\|\\_.!~*\\|'()\\[\\]%#,☺]+[\\w/#](\\(\\))?)" static let hashtagRegex = try? NSRegularExpression(pattern: "(?:[^|\\s|$|[^.]])?(#[\\p{L}0-9_]*)", options: [.CaseInsensitive]) static let mentionRegex = try? NSRegularExpression(pattern: "(?:[^|\\s|$|.])?(@[\\p{L}0-9_]*)", options: [.CaseInsensitive]); static let urlDetector = try? NSRegularExpression(pattern: urlPattern, options: [.CaseInsensitive]) static func getMentions(fromText text: String, range: NSRange) -> [NSTextCheckingResult] { guard let mentionRegex = mentionRegex else { return [] } return mentionRegex.matchesInString(text, options: [], range: range) } static func getHashtags(fromText text: String, range: NSRange) -> [NSTextCheckingResult] { guard let hashtagRegex = hashtagRegex else { return [] } return hashtagRegex.matchesInString(text, options: [], range: range) } static func getURLs(fromText text: String, range: NSRange) -> [NSTextCheckingResult] { guard let urlDetector = urlDetector else { return [] } return urlDetector.matchesInString(text, options: [], range: range) } }
ec29f8f0fed0948f1e3591a68b6ca57d
40.542857
131
0.611149
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/EmailLogin/Credentials/TwoFAReducer.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import ComposableArchitecture import FeatureAuthenticationDomain import WalletPayloadKit // MARK: - Type public enum TwoFAAction: Equatable { public enum IncorrectTwoFAContext: Equatable { case incorrect case missingCode case none var hasError: Bool { self != .none } } case didChangeTwoFACode(String) case didChangeTwoFACodeAttemptsLeft(Int) case showIncorrectTwoFACodeError(IncorrectTwoFAContext) case showResendSMSButton(Bool) case showTwoFACodeField(Bool) } private enum Constants { static let twoFACodeMaxAttemptsLeft = 5 } // MARK: - Properties struct TwoFAState: Equatable { var twoFACode: String var twoFAType: WalletAuthenticatorType var isTwoFACodeFieldVisible: Bool var isResendSMSButtonVisible: Bool var isTwoFACodeIncorrect: Bool var twoFACodeIncorrectContext: TwoFAAction.IncorrectTwoFAContext var twoFACodeAttemptsLeft: Int init( twoFACode: String = "", twoFAType: WalletAuthenticatorType = .standard, isTwoFACodeFieldVisible: Bool = false, isResendSMSButtonVisible: Bool = false, isTwoFACodeIncorrect: Bool = false, twoFACodeIncorrectContext: TwoFAAction.IncorrectTwoFAContext = .none, twoFACodeAttemptsLeft: Int = Constants.twoFACodeMaxAttemptsLeft ) { self.twoFACode = twoFACode self.twoFAType = twoFAType self.isTwoFACodeFieldVisible = isTwoFACodeFieldVisible self.isResendSMSButtonVisible = isResendSMSButtonVisible self.isTwoFACodeIncorrect = isTwoFACodeIncorrect self.twoFACodeIncorrectContext = twoFACodeIncorrectContext self.twoFACodeAttemptsLeft = twoFACodeAttemptsLeft } } let twoFAReducer = Reducer< TwoFAState, TwoFAAction, CredentialsEnvironment > { state, action, _ in switch action { case .didChangeTwoFACode(let code): state.twoFACode = code return .none case .didChangeTwoFACodeAttemptsLeft(let attemptsLeft): state.twoFACodeAttemptsLeft = attemptsLeft return Effect(value: .showIncorrectTwoFACodeError(.incorrect)) case .showIncorrectTwoFACodeError(let context): state.twoFACodeIncorrectContext = context state.isTwoFACodeIncorrect = context.hasError return .none case .showResendSMSButton(let shouldShow): state.isResendSMSButtonVisible = shouldShow return .none case .showTwoFACodeField(let isVisible): state.twoFACode = "" state.isTwoFACodeFieldVisible = isVisible return .none } }
95befe94c96bd66ee358627d31de60e4
30.341176
77
0.718844
false
false
false
false
Awalz/ark-ios-monitor
refs/heads/master
ArkMonitor/Explorer/Tableview Cells/ExplorerTransactionTableViewCell.swift
mit
1
// Copyright (c) 2016 Ark // // 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 SwiftyArk class ExplorerTransactionTableViewCell: UITableViewCell { public let transaction: Transaction init(_ transaction: Transaction) { self.transaction = transaction super.init(style: .default, reuseIdentifier: "transaction") backgroundColor = ArkPalette.secondaryBackgroundColor selectionStyle = .none let nameLabel = UILabel() nameLabel.textColor = ArkPalette.highlightedTextColor nameLabel.text = transaction.id nameLabel.adjustsFontSizeToFitWidth = true nameLabel.textAlignment = .left nameLabel.numberOfLines = 2 nameLabel.font = UIFont.systemFont(ofSize: 16.0, weight: .semibold) addSubview(nameLabel) nameLabel.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(12.5) make.right.equalToSuperview().offset(-12.5) } let seperator = UIView() seperator.backgroundColor = ArkPalette.backgroundColor addSubview(seperator) seperator.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(0.5) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
02dedcfe87a60fef270a4f37cd085ded
41.775862
137
0.696493
false
false
false
false
AlvinL33/TownHunt
refs/heads/master
TownHunt/TownHunt/AddNewMapPacksViewController.swift
apache-2.0
1
// // AddNewMapPacksViewController.swift // TownHunt // // Copyright © 2016 LeeTech. All rights reserved. // import UIKit import MapKit import Foundation class AddNewMapPacksViewController: UIViewController { @IBOutlet weak var viewBelowNav: UIView! @IBOutlet weak var addPinDetailView: UIView! @IBOutlet weak var pinPointValTextField: UITextField! @IBOutlet weak var pinCodewordTextField: UITextField! @IBOutlet weak var pinHintTextField: UITextField! @IBOutlet weak var pinTitleTextField: UITextField! @IBOutlet weak var totalPinsButtonLabel: BorderedButton! @IBOutlet weak var maxPointsButtonLabel: BorderedButton! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var menuOpenNavBarButton: UIBarButtonItem! var gamePins: [PinLocation] = [] var newPLat = 0.0 var newPLong = 0.0 var isNewPinOnMap = false var newPinCoords = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0) let newPin = MKPointAnnotation() let filePath = NSHomeDirectory() + "/Documents/" + "MITPack.txt" override func viewDidLoad() { loadPackFromFile() NotificationCenter.default.addObserver(self, selector: #selector(AddNewMapPacksViewController.refreshAnnotations(_:)),name:NSNotification.Name(rawValue: "load"), object: nil) let longPressRecog = UILongPressGestureRecognizer(target: self, action: #selector(MKMapView.addAnnotation(_:))) longPressRecog.minimumPressDuration = 1.0 mapView.addGestureRecognizer(longPressRecog) menuOpenNavBarButton.target = self.revealViewController() menuOpenNavBarButton.action = #selector(SWRevealViewController.revealToggle(_:)) updatePackLabels() // Setting up the map view mapView.showsUserLocation = true mapView.mapType = MKMapType.hybrid mapView.addAnnotations(gamePins) print("This view has loaded") super.viewDidLoad() // Do any additional setup after loading the view. } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { } @IBAction func zoomButton(_ sender: AnyObject) { let userLocation = mapView.userLocation let region = MKCoordinateRegionMakeWithDistance(userLocation.location!.coordinate, 200, 200) mapView.setRegion(region, animated: true) } @IBAction func totalPinsButton(_ sender: AnyObject) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updatePackLabels(){ totalPinsButtonLabel.setTitle("Total Pins: \(gamePins.count)", for: UIControlState()) var maxPoints = 0 for pin in gamePins{ maxPoints += pin.pointVal } maxPointsButtonLabel.setTitle("Max Points: \(maxPoints)", for: UIControlState()) } func addAnnotation(_ gestureRecognizer:UIGestureRecognizer){ if isNewPinOnMap == false{ let touchLocation = gestureRecognizer.location(in: mapView) newPinCoords = mapView.convert(touchLocation, toCoordinateFrom: mapView) newPin.coordinate = newPinCoords mapView.addAnnotation(newPin) isNewPinOnMap = true } } func refreshAnnotations(_ notification: Notification){ loadPackFromFile() mapView.addAnnotations(gamePins) updatePackLabels() } @IBAction func addPinDetailsButton(_ sender: AnyObject) { if isNewPinOnMap == true{ let region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: newPinCoords.latitude + 0.0003, longitude: newPinCoords.longitude), 100, 100) mapView.setRegion(region, animated: true) addPinDetailView.isHidden = false } else{ let alert = UIAlertController(title: "No New Pin On The Map", message: "A new pin hasn't been added to the map yet. Long hold on the location you want to place the pin", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } } @IBAction func cancelAddPinDetButton(_ sender: AnyObject) { addPinDetailView.isHidden = true mapView.removeAnnotation(newPin) resetTextFieldLabels() view.endEditing(true) resetTextFieldLabels() } @IBAction func saveAddPinDetButton(_ sender: AnyObject) { //let newPinDetails = PinLocation(title: pinTitleTextField.text!, hint: pinHintTextField.text!, codeword: pinCodewordTextField.text!, coordinate: newPinCoords, pointVal: Int(pinPointValTextField.text!)!) let writeLine = "\(pinTitleTextField.text!),\(pinHintTextField.text!),\(pinCodewordTextField.text!),\(newPinCoords.latitude),\(newPinCoords.longitude),\(pinPointValTextField.text!)" let pin = PinLocation(title: pinTitleTextField.text!, hint: pinHintTextField.text!, codeword: pinCodewordTextField.text!, coordinate: newPinCoords, pointVal: Int(pinPointValTextField.text!)!) mapView.addAnnotation(pin) mapView.removeAnnotation(newPin) writeToFile(writeLine) addPinDetailView.isHidden = true resetTextFieldLabels() gamePins.append(pin) updatePackLabels() view.endEditing(true) } func resetTextFieldLabels(){ isNewPinOnMap = false pinTitleTextField.text = "Title" pinHintTextField.text = "Hint" pinCodewordTextField.text = "Codeword" pinPointValTextField.text = "Point Value" } func writeToFile(_ content: String) { let contentToAppend = content+"\n" //Check if file exists if let fileHandle = FileHandle(forWritingAtPath: filePath) { //Append to file fileHandle.seekToEndOfFile() fileHandle.write(contentToAppend.data(using: String.Encoding.utf8)!) } else { //Create new file do { try contentToAppend.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8) } catch { print("Error creating \(filePath)") } } } //Loads all of the pins from a pack into the map func loadPackFromFile(){ var stringFromFile: String do{ stringFromFile = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue) as String let packPinLocArrays = stringFromFile.characters.split(separator: "\n").map(String.init) if packPinLocArrays.isEmpty == false{ for pinArray in packPinLocArrays{ let pinDetails = pinArray.characters.split(separator: ",").map(String.init) let pin = PinLocation(title: pinDetails[0], hint: pinDetails[1], codeword: pinDetails[2], coordinate: CLLocationCoordinate2D(latitude: Double(pinDetails[3])!, longitude: Double(pinDetails[4])!),pointVal: Int(pinDetails[5])!) gamePins.append(pin) } } } catch let error as NSError{ print(error.description) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "PinInPackListSegue" { let destNavCon = segue.destination as! UINavigationController if let targetController = destNavCon.topViewController as? PinListInPackTableViewController{ targetController.listOfPins = gamePins targetController.filePath = filePath mapView.removeAnnotations(gamePins) gamePins = [] } else { print("Data NOT Passed! destination vc is not set to correct view") } } else { print("Id doesnt match with Storyboard segue Id") } } @IBAction func changeMapButton(_ sender: AnyObject) { if mapView.mapType == MKMapType.hybrid{ mapView.mapType = MKMapType.standard viewBelowNav.backgroundColor = UIColor.brown.withAlphaComponent(0.8) } else{ mapView.mapType = MKMapType.hybrid viewBelowNav.backgroundColor = UIColor.white.withAlphaComponent(0.8) } } } /* @IBAction func write(sender: AnyObject) { let writeString = "Hello, world!" let filePath = NSHomeDirectory() + "/Documents/test.txt" do { _ = try writeString.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding) } catch let error as NSError { print(error.description) } } @IBAction func read(sender: AnyObject) { var readString: String let filePath = NSHomeDirectory() + "/Documents/test.txt" do { readString = try NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding) as String print(readString) } catch let error as NSError { print(error.description) } } */
bb95ebb3a893b74fa9a1bac835cc4a22
39.668161
244
0.66402
false
false
false
false
Zewo/Mustache
refs/heads/master
Sources/Mustache/Rendering/MustacheBox.swift
mit
1
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /** Mustache templates don't eat raw values: they eat values boxed in `MustacheBox`. To box something in a `MustacheBox`, you use one variant of the `Box()` function. It comes in several variants so that nearly anything can be boxed and feed templates: - Basic Swift values: template.render(Box("foo")) - Dictionaries & collections: template.render(Box(["numbers": [1,2,3]])) - Custom types via the `MustacheBoxable` protocol: extension User: MustacheBoxable { ... } template.render(Box(user)) - Functions such as `FilterFunction`, `RenderFunction`, `WillRenderFunction` and `DidRenderFunction`: let square = Filter { (x: Int?) in Box(x! * x!) } template.registerInBaseContext("square", Box(square)) **Warning**: the fact that `MustacheBox` is a subclass of NSObject is an implementation detail that is enforced by the Swift 2 language itself. This may change in the future: do not rely on it. */ final public class MustacheBox { // IMPLEMENTATION NOTE // // Why is MustacheBox a subclass of NSObject, and not, say, a Swift struct? // // Swift does not allow a class extension to override a method that is // inherited from an extension to its superclass and incompatible with // Objective-C. // // If MustacheBox were a pure Swift type, this Swift limit would prevent // NSObject subclasses such as NSNull, NSNumber, etc. to override // MustacheBoxable.mustacheBox, and provide custom rendering behavior. // // For an example of this limitation, see example below: // // import Foundation // // // A type that is not compatible with Objective-C // struct MustacheBox { } // // // So far so good // extension NSObject { // var mustacheBox: MustacheBox { return MustacheBox() } // } // // // Error: declarations in extensions cannot override yet // extension NSNull { // override var mustacheBox: MustacheBox { return MustacheBox() } // } // // This problem does not apply to Objc-C compatible protocols: // // import Foundation // // // So far so good // extension NSObject { // var prop: String { return "NSObject" } // } // // // No error // extension NSNull { // override var prop: String { return "NSNull" } // } // // NSObject().prop // "NSObject" // NSNull().prop // "NSNull" // // In order to let the user easily override NSObject.mustacheBox, we had to // keep its return type compatible with Objective-C, that is to say make // MustacheBox a subclass of NSObject. // ------------------------------------------------------------------------- // MARK: - The boxed value /// The boxed value. public let value: Any? /// The only empty box is `Box()`. public let isEmpty: Bool /** The boolean value of the box. It tells whether the Box should trigger or prevent the rendering of regular `{{#section}}...{{/}}` and inverted `{{^section}}...{{/}}`. */ public let boolValue: Bool /** If the boxed value can be iterated (Swift collection, NSArray, NSSet, etc.), returns an array of `MustacheBox`. */ public var arrayValue: [MustacheBox]? { return converter?.arrayValue() } /** If the boxed value is a dictionary (Swift dictionary, NSDictionary, etc.), returns a dictionary `[String: MustacheBox]`. */ public var dictionaryValue: [String: MustacheBox]? { return converter?.dictionaryValue() } /** Extracts a key out of a box. let box = Box(["firstName": "Arthur"]) box.mustacheBoxForKey("firstName").value // "Arthur" - parameter key: A key. - returns: The MustacheBox for *key*. */ public func mustacheBox(forKey key: String) -> MustacheBox { return keyedSubscript?(key: key) ?? Box() } // ------------------------------------------------------------------------- // MARK: - Other facets /// See the documentation of `RenderFunction`. public private(set) var render: RenderFunction /// See the documentation of `FilterFunction`. public let filter: FilterFunction? /// See the documentation of `WillRenderFunction`. public let willRender: WillRenderFunction? /// See the documentation of `DidRenderFunction`. public let didRender: DidRenderFunction? // ------------------------------------------------------------------------- // MARK: - Multi-facetted Box Initialization /** This is the most low-level initializer of MustacheBox. It is suited for building "advanced" boxes. There are simpler versions of the `Box` function that may well better suit your need: you should check them. This initializer can take up to seven parameters, all optional, that define how the box interacts with the Mustache engine: - `value`: an optional boxed value - `boolValue`: an optional boolean value for the Box. - `keyedSubscript`: an optional KeyedSubscriptFunction - `filter`: an optional FilterFunction - `render`: an optional RenderFunction - `willRender`: an optional WillRenderFunction - `didRender`: an optional DidRenderFunction To illustrate the usage of all those parameters, let's look at how the `{{f(a)}}` tag is rendered. First the `a` and `f` expressions are evaluated. The Mustache engine looks in the context stack for boxes whose *keyedSubscript* return non-empty boxes for the keys "a" and "f". Let's call them aBox and fBox. Then the *filter* of the fBox is evaluated with aBox as an argument. It is likely that the result depends on the *value* of the aBox: it is the resultBox. Then the Mustache engine is ready to render resultBox. It looks in the context stack for boxes whose *willRender* function is defined. Those willRender functions have the opportunity to process the resultBox, and eventually provide the box that will be actually rendered: the renderedBox. The renderedBox has a *render* function: it is evaluated by the Mustache engine which appends its result to the final rendering. Finally the Mustache engine looks in the context stack for boxes whose *didRender* function is defined, and call them. ### value The optional `value` parameter gives the boxed value. The value is used when the box is rendered (unless you provide a custom RenderFunction). It is also returned by the `value` property of MustacheBox. let aBox = MustacheBox(value: 1) // Renders "1" let template = try! Template(string: "{{a}}") try! template.render(Box(["a": aBox])) ### boolValue The optional `boolValue` parameter tells whether the Box should trigger or prevent the rendering of regular `{{#section}}...{{/}}` and inverted `{{^section}}...{{/}}` tags. The default boolValue is true, unless the Box is initialized without argument to build the empty box. // Render "true", "false" let template = try! Template(string:"{{#.}}true{{/.}}{{^.}}false{{/.}}") try! template.render(MustacheBox(boolValue: true)) try! template.render(MustacheBox(boolValue: false)) ### keyedSubscript The optional `keyedSubscript` parameter is a `KeyedSubscriptFunction` that lets the Mustache engine extract keys out of the box. For example, the `{{a}}` tag would call the subscript function with `"a"` as an argument, and render the returned box. The default value is nil, which means that no key can be extracted. See `KeyedSubscriptFunction` for a full discussion of this type. let box = MustacheBox(keyedSubscript: { (key: String) in return Box("key:\(key)") }) // Renders "key:a" let template = try! Template(string:"{{a}}") try! template.render(box) ### filter The optional `filter` parameter is a `FilterFunction` that lets the Mustache engine evaluate filtered expression that involve the box. The default value is nil, which means that the box can not be used as a filter. See `FilterFunction` for a full discussion of this type. let box = MustacheBox(filter: Filter { (x: Int?) in return Box(x! * x!) }) // Renders "100" let template = try! Template(string:"{{square(x)}}") try! template.render(Box(["square": box, "x": Box(10)])) ### render The optional `render` parameter is a `RenderFunction` that is evaluated when the Box is rendered. The default value is nil, which makes the box perform default Mustache rendering: - `{{box}}` renders the built-in Swift String Interpolation of the value, HTML-escaped. - `{{{box}}}` renders the built-in Swift String Interpolation of the value, not HTML-escaped. - `{{#box}}...{{/box}}` does not render if `boolValue` is false. Otherwise, it pushes the box on the top of the context stack, and renders the section once. - `{{^box}}...{{/box}}` renders once if `boolValue` is false. Otherwise, it does not render. See `RenderFunction` for a full discussion of this type. let box = MustacheBox(render: { (info: RenderingInfo) in return Rendering("foo") }) // Renders "foo" let template = try! Template(string:"{{.}}") try! template.render(box) ### willRender, didRender The optional `willRender` and `didRender` parameters are a `WillRenderFunction` and `DidRenderFunction` that are evaluated for all tags as long as the box is in the context stack. See `WillRenderFunction` and `DidRenderFunction` for a full discussion of those types. let box = MustacheBox(willRender: { (tag: Tag, box: MustacheBox) in return Box("baz") }) // Renders "baz baz" let template = try! Template(string:"{{#.}}{{foo}} {{bar}}{{/.}}") try! template.render(box) ### Multi-facetted boxes By mixing all those parameters, you can finely tune the behavior of a box. GRMustache source code ships a few multi-facetted boxes, which may inspire you. See for example: - NSFormatter.mustacheBox - HTMLEscape.mustacheBox - StandardLibrary.Localizer.mustacheBox Let's give an example: // A regular type: struct Person { let firstName: String let lastName: String } We want: 1. `{{person.firstName}}` and `{{person.lastName}}` should render the matching properties. 2. `{{person}}` should render the concatenation of the first and last names. We'll provide a `KeyedSubscriptFunction` to implement 1, and a `RenderFunction` to implement 2: // Have Person conform to MustacheBoxable so that we can box people, and // render them: extension Person : MustacheBoxable { // MustacheBoxable protocol requires objects to implement this property // and return a MustacheBox: var mustacheBox: MustacheBox { // A person is a multi-facetted object: return MustacheBox( // It has a value: value: self, // It lets Mustache extracts properties by name: keyedSubscript: { (key: String) -> MustacheBox in switch key { case "firstName": return Box(self.firstName) case "lastName": return Box(self.lastName) default: return Box() } }, // It performs custom rendering: render: { (info: RenderingInfo) -> Rendering in switch info.tag.type { case .Variable: // {{ person }} return Rendering("\(self.firstName) \(self.lastName)") case .Section: // {{# person }}...{{/}} // // Perform the default rendering: push self on the top // of the context stack, and render the section: let context = info.context.extendedContext(Box(self)) return try info.tag.render(context) } } ) } } // Renders "The person is Errol Flynn" let person = Person(firstName: "Errol", lastName: "Flynn") let template = try! Template(string: "{{# person }}The person is {{.}}{{/ person }}") try! template.render(Box(["person": person])) - parameter value: An optional boxed value. - parameter boolValue: An optional boolean value for the Box. - parameter keyedSubscript: An optional `KeyedSubscriptFunction`. - parameter filter: An optional `FilterFunction`. - parameter render: An optional `RenderFunction`. - parameter willRender: An optional `WillRenderFunction`. - parameter didRender: An optional `DidRenderFunction`. - returns: A MustacheBox. */ public convenience init( value: Any? = nil, boolValue: Bool? = nil, keyedSubscript: KeyedSubscriptFunction? = nil, filter: FilterFunction? = nil, render: RenderFunction? = nil, willRender: WillRenderFunction? = nil, didRender: DidRenderFunction? = nil) { self.init( converter: nil, value: value, boolValue: boolValue, keyedSubscript: keyedSubscript, filter: filter, render: render, willRender: willRender, didRender: didRender) } // ------------------------------------------------------------------------- // MARK: - Internal let keyedSubscript: KeyedSubscriptFunction? let converter: Converter? init( converter: Converter?, value: Any? = nil, boolValue: Bool? = nil, keyedSubscript: KeyedSubscriptFunction? = nil, filter: FilterFunction? = nil, render: RenderFunction? = nil, willRender: WillRenderFunction? = nil, didRender: DidRenderFunction? = nil) { let empty = (value == nil) && (keyedSubscript == nil) && (render == nil) && (filter == nil) && (willRender == nil) && (didRender == nil) self.isEmpty = empty self.value = value self.converter = converter self.boolValue = boolValue ?? !empty self.keyedSubscript = keyedSubscript self.filter = filter self.willRender = willRender self.didRender = didRender if let render = render { self.hasCustomRenderFunction = true self.render = render } else { // The default render function: it renders {{variable}} tags as the // boxed value, and {{#section}}...{{/}} tags by adding the box to // the context stack. // // IMPLEMENTATIN NOTE // // We have to set self.render twice in order to avoid the compiler // error: "variable 'self.render' captured by a closure before being // initialized" self.render = { (_) in return Rendering("") } self.hasCustomRenderFunction = false self.render = { [unowned self] (info: RenderingInfo) in // Default rendering depends on the tag type: switch info.tag.type { case .Variable: // {{ box }} and {{{ box }}} if let value = self.value { // Use the built-in Swift String Interpolation: return Rendering("\(value)", .Text) } else { return Rendering("", .Text) } case .Section: // {{# box }}...{{/ box }} // Push the value on the top of the context stack: let context = info.context.extendedContext(self) // Renders the inner content of the section tag: return try info.tag.render(context: context) } } } } private let hasCustomRenderFunction: Bool // Converter wraps all the conversion closures that help MustacheBox expose // its raw value (typed Any) as useful types. struct Converter { let arrayValue: (() -> [MustacheBox]?) let dictionaryValue: (() -> [String: MustacheBox]?) init( arrayValue: @autoclosure(escaping)() -> [MustacheBox]? = nil, dictionaryValue: @autoclosure(escaping)() -> [String: MustacheBox]? = nil) { self.arrayValue = arrayValue self.dictionaryValue = dictionaryValue } } } extension MustacheBox { /// A textual representation of `self`. public var description: String { let facets = self.facetsDescriptions switch facets.count { case 0: return "MustacheBox(Empty)" default: let content = facets.joined(separator: ",") return "MustacheBox(\(content))" } } } extension MustacheBox { /// A textual representation of the boxed value. Useful for debugging. public var valueDescription: String { let facets = self.facetsDescriptions switch facets.count { case 0: return "Empty" case 1: return facets.first! default: return "(" + facets.joined(separator: ",") + ")" } } var facetsDescriptions: [String] { var facets = [String]() if let array = arrayValue { let items = array.map { $0.valueDescription }.joined(separator: ",") facets.append("[\(items)]") } else if let dictionary = dictionaryValue { if dictionary.isEmpty { facets.append("[:]") } else { let items = dictionary.map { (key, box) in return "\(key.debugDescription):\(box.valueDescription)" }.joined(separator: ",") facets.append("[\(items)]") } } else if let value = value { facets.append(String(reflecting: value)) } if let _ = filter { facets.append("FilterFunction") } if let _ = willRender { facets.append("WillRenderFunction") } if let _ = didRender { facets.append("DidRenderFunction") } if value == nil && hasCustomRenderFunction { facets.append("RenderFunction") } return facets } }
cbee75e9076d8750e5e482859281e873
34.621762
144
0.580121
false
false
false
false
w91379137/PFFGCDProgramming
refs/heads/master
GCDProgramming30/GCDProgramming30/HTTPBinManagerOperation.swift
mit
1
// // HTTPBinManagerOperation.swift // GCDProgramming23 // // Created by w91379137 on 2016/6/28. // Copyright © 2016年 w91379137. All rights reserved. // import UIKit protocol HTTPBinManagerOperationDelegate { func operationNotice<T : HTTPBinManagerOperationType>(operation: T!) } protocol HTTPBinManagerOperationType { var isCancelled: Bool { get } func progress() -> Float var error : NSError? { get } } class HTTPBinManagerOperation: Operation,HTTPBinManagerOperationType { //MARK: - Property var delegate : HTTPBinManagerOperationDelegate? var error : NSError? var image : UIImage? var getDict : NSDictionary? var postDict : NSDictionary? //MARK: override func main() { self.loopAllTask() } func loopAllTask() { if self.isCancelled || (self.error != nil) { return } DispatchQueue.main.async() { self.delegate?.operationNotice(operation: self); } if self.getDict == nil { fetchGetResponseWithCallback { (dict, error) in if error != nil { self.error = error self.cancel() } else { self.getDict = dict } self.loopAllTask() } } else if self.postDict == nil { postCustomerName(name: "test") { (dict, error) in if error != nil { self.error = error self.cancel() } else { self.postDict = dict } self.loopAllTask() } } else if self.image == nil { fetchImageWithCallback { (image, error) in if error != nil { self.error = error self.cancel() } else { self.image = image } self.loopAllTask() } } else { //Finish } } //MARK: override func cancel() { super.cancel() self.delegate?.operationNotice(operation: self) } func progress() -> Float { var progress = Float(0) if self.getDict != nil {progress += 0.33} if self.postDict != nil {progress += 0.33} if self.image != nil {progress += 0.34} return progress } }
21fdb66c9f3aaca1891c734209073d32
23.980198
72
0.486326
false
false
false
false
zshannon/ZCSSlideToAction
refs/heads/master
Classes/ZCSSlideToActionView.swift
mit
1
// // ZCSSlideToActionView.swift // ZCSSlideToAction // // Created by Zane Shannon on 10/10/14. // Copyright (c) 2014 Zane Shannon. All rights reserved. // import Foundation @objc protocol ZCSSlideToActionViewDelegate { func slideToActionActivated(sender:ZCSSlideToActionView) optional func slideToActionStarted(sender:ZCSSlideToActionView) optional func slideToActionCancelled(sender:ZCSSlideToActionView) optional func slideToActionReset(sender:ZCSSlideToActionView) } @objc protocol SliderProtocol { func renderPosition(percentagePosition:Double, animated:Bool) } class ZCSSlideToActionView: UIView, SliderProtocol { @IBOutlet weak var delegate:ZCSSlideToActionViewDelegate? = nil var activationPoint:Double = 0.66 var preventSlideBack:Bool = true override func awakeFromNib() { self.clipsToBounds = true let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:") self.addGestureRecognizer(panGestureRecognizer) } override func layoutSubviews() { super.layoutSubviews() // self.bounds = self.superview!.bounds } func reset() { self.willActivate = false self.renderPosition(0.0, animated: true) if let d = self.delegate { if let f = d.slideToActionReset { f(self) } } } func renderPosition(percentagePosition:Double, animated:Bool) { println("Subclass must override renderPosition!") abort() } internal var willActivate:Bool = false func handlePanGesture(recognizer: UIGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { let percentagePosition = Double((recognizer as! UIPanGestureRecognizer).translationInView(self).x) / Double(self.frame.width) self.willActivate = percentagePosition >= self.activationPoint self.renderPosition(percentagePosition, animated: false) if let d = self.delegate { if let f = d.slideToActionStarted { f(self) } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled || recognizer.state == UIGestureRecognizerState.Failed) { let percentagePosition = Double((recognizer as! UIPanGestureRecognizer).translationInView(self).x) / Double(self.frame.width) self.willActivate = percentagePosition >= self.activationPoint if self.willActivate { self.renderPosition(1.0, animated: true) } else { self.renderPosition(0.0, animated: true) } if let d = self.delegate { if self.willActivate { d.slideToActionActivated(self) } else { if let f = d.slideToActionCancelled { f(self) } } } } else if (recognizer.state == UIGestureRecognizerState.Changed) { let percentagePosition = Double((recognizer as! UIPanGestureRecognizer).translationInView(self).x) / Double(self.frame.width) self.willActivate = percentagePosition >= self.activationPoint self.renderPosition(percentagePosition, animated: false) } } }
503b54291146020770a0916304dd09a7
29.402062
128
0.746608
false
false
false
false
jshultz/ios9-swift2-multiplication-table
refs/heads/master
times table app/ViewController.swift
mit
1
// // ViewController.swift // times table app // // Created by Jason Shultz on 9/24/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBOutlet weak var table: UITableView! var cellContent = [0] @IBOutlet weak var sliderValue: UISlider! @IBOutlet weak var multiplyLabel: UILabel! @IBAction func sliderMoved(sender: AnyObject) { print(sliderValue) cellContent = [0] let factor = Int(sliderValue.value) // convert Float to Int to shave off decimal multiplyLabel.text = "Multiplying by \(factor)" var x = 1 while (x <= 20) { cellContent.append(factor * x) x++ } table.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellContent.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let factor = Int(sliderValue.value) // convert Float to Int to shave off decimal let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") let rowText = "\(indexPath.row) times \(factor) equals \(String(cellContent[indexPath.row]))" cell.textLabel?.text = rowText return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
faa87a2c2647aa5426b36e7b0fe8045a
25.686567
109
0.619687
false
false
false
false
mansoor92/MaksabComponents
refs/heads/master
Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Loading View/LoadingView.swift
mit
1
// // LoadingBackgroundView.swift // Pods // // Created by Incubasys on 26/07/2017. // // import UIKit //import MRProgress import SVProgressHUD public protocol RefreshControlDelegate{ func refreshData() } public class LoadingView: UIView { private var serviceResponseView : ServiceResponseView? public var loadingMessage:String = "Loading..." private var loadingIsVisible = false private var refreshControl : UIRefreshControl? private var pageLoadingView : PageLoadingView! private var refreshDelegate: RefreshControlDelegate? override public func awakeFromNib() {} public static func show(msg: String = "Loading...",window: UIWindow? = nil){ if window != nil{ SVProgressHUD.setContainerView(window!) } SVProgressHUD.show(withStatus: msg) } public static func hide(){ SVProgressHUD.dismiss() } //Service Response View public func addServiceReponseView(delegate:ServiceResponseViewDelegate,top:CGFloat=0,bottom:CGFloat=0, isLight: Bool = true) { createServiceResponseView(delegate:delegate,top:top,bottom:bottom, isLight: isLight) } func createServiceResponseView(delegate:ServiceResponseViewDelegate,top:CGFloat=0,bottom:CGFloat=0, isLight: Bool) { let w = UIScreen.main.bounds.width let h = UIScreen.main.bounds.height - top - bottom serviceResponseView = ServiceResponseView(frame: CGRect(x: 0, y: top, width: w, height: h)) serviceResponseView?.delegate = delegate serviceResponseView?.isLight = isLight self.addSubview(serviceResponseView!) self.bringSubview(toFront: serviceResponseView!) serviceResponseView?.isHidden = true } //Refresh control func createRefreshControl(controller: UIViewController, title: String) -> UIRefreshControl { let rControl = UIRefreshControl() rControl.attributedTitle = NSAttributedString(string: title) rControl.addTarget(controller, action: Selector(("refreshData")), for: .valueChanged) return rControl } public func addRefreshControl(tableView:UITableView,refreshTitle:String,controller: UIViewController, delegate: RefreshControlDelegate) { self.refreshDelegate = delegate refreshControl = createRefreshControl(controller: controller, title: refreshTitle) tableView.addSubview(refreshControl!) } public func addRefreshControl(collectionView:UICollectionView,refreshTitle:String,controller: UIViewController, delegate: RefreshControlDelegate) { self.refreshDelegate = delegate refreshControl = createRefreshControl(controller: controller, title: refreshTitle) collectionView.addSubview(refreshControl!) } //Page Loading view for pagination public func addPageLoadingView(bottom:CGFloat = 0) { let w = UIScreen.main.bounds.width let y = UIScreen.main.bounds.height - 44 - bottom pageLoadingView = PageLoadingView(frame:CGRect(x: 0, y: y, width: w, height: 44)) pageLoadingView.backgroundColor = UIColor.yellow self.addSubview(pageLoadingView) pageLoadingView.isHidden = true } public func showPageLoading(msg:String = "Loading more...") { pageLoadingView.labelMsg.text = msg pageLoadingView.isHidden = false loadingIsVisible = true } func hidePageLoading() { pageLoadingView.isHidden = true } public func isLoadingVisible() -> Bool { return loadingIsVisible } public func hideLoadingOrMessageView() { // if mrProgressOverlay != nil{ // mrProgressOverlay.hide(true) // mrProgressOverlay = nil // self.loadingIsVisible = false // }else { // serviceResponseView?.isHidden = true // } if loadingIsVisible{ LoadingView.hide() if pageLoadingView != nil{ hidePageLoading() } refreshControl?.endRefreshing() loadingIsVisible = false }else{ serviceResponseView?.isHidden = true } } //Show Loading View // , mode:MRProgressOverlayViewMode = MRProgressOverlayViewMode.indeterminate public func showLoadingView(msg: String = "Loading...", window: UIWindow? = nil) { var title = "" if msg.isEmpty{ title = loadingMessage }else{ title = msg } self.loadingIsVisible = true LoadingView.show(msg: title, window: window) } public func showReponseView(title: String?, msg: String?, img: UIImage?, hideRetryBtn: Bool, retryBtnTitle:String = "Try Again") { if serviceResponseView != nil{ serviceResponseView?.showMessage(title: title, msg: msg, image: img, hideRetryButton: hideRetryBtn, btnTitle: retryBtnTitle) serviceResponseView?.btnRetry.setTitle(retryBtnTitle, for: .normal) serviceResponseView?.isHidden = false } } }
72d3636bdb6148febc6ec7e374aa9804
34.423611
152
0.663595
false
false
false
false
harlanhaskins/swift
refs/heads/master
test/Sema/enum_conformance_synthesis.swift
apache-2.0
2
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/enum_conformance_synthesis_other.swift -verify-ignore-unknown -swift-version 4 var hasher = Hasher() enum Foo: CaseIterable { case A, B } func foo() { if Foo.A == .B { } var _: Int = Foo.A.hashValue Foo.A.hash(into: &hasher) _ = Foo.allCases Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}} } enum Generic<T>: CaseIterable { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } func generic() { if Generic<Foo>.A == .B { } var _: Int = Generic<Foo>.A.hashValue Generic<Foo>.A.hash(into: &hasher) _ = Generic<Foo>.allCases } func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B func hash(into hasher: inout Hasher) {} } func ==(x: CustomHashable, y: CustomHashable) -> Bool { return true } func customHashable() { if CustomHashable.A == .B { } var _: Int = CustomHashable.A.hashValue CustomHashable.A.hash(into: &hasher) } // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } // expected-error {{invalid redeclaration of synthesized implementation for protocol requirement 'hashValue'}} } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { return "" } func invalidCustomHashable() { if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue _ = s var _: Int = InvalidCustomHashable.A.hashValue InvalidCustomHashable.A.hash(into: &hasher) } // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } func getFromOtherFile() -> AlsoFromOtherFile { return .A } func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } func useEnumBeforeDeclaration() { // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue if .A == getFromOtherFile() {} if .A == overloadFromOtherFile() {} } // Complex enums are not automatically Equatable, Hashable, or CaseIterable. enum Complex { case A(Int) case B } func complex() { if Complex.A(1) == .B { } // expected-error{{cannot convert value of type 'Complex' to expected argument type 'CustomHashable'}} } // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } func enumWithEquatablePayload() { if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } func enumWithHashablePayload() { _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue EnumWithHashablePayload.A(1).hash(into: &hasher) EnumWithHashablePayload.B("x", 1).hash(into: &hasher) EnumWithHashablePayload.C.hash(into: &hasher) // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Equatable'}} } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } func genericHashable() { if GenericHashable<String>.A("a") == .B { } var _: Int = GenericHashable<String>.A("a").hashValue } // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}} case A(T) //expected-note 2 {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}} case B } func genericNotHashable() { if GenericNotHashable<String>.A("a") == .B { } let _: Int = GenericNotHashable<String>.A("a").hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails GenericNotHashable<String>.A("a").hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}} } // An enum with no cases should also derive conformance. enum NoCases: Hashable, Comparable {} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{cannot find type 'Unknown' in scope}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} extension Instrument : CaseIterable {} enum UnusedGeneric<T> { case a, b, c } extension UnusedGeneric : CaseIterable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { return true } // No explicit conformance; but it can be derived, for the same-file cases. enum Complex2 { case A(Int) case B } extension Complex2 : Hashable {} extension Complex2 : CaseIterable {} // expected-error {{type 'Complex2' does not conform to protocol 'CaseIterable'}} extension FromOtherFile: CaseIterable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}} expected-error {{does not conform to protocol 'CaseIterable'}} // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}} } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} extension NotExplicitlyHashableAndCannotDerive : CaseIterable {} // expected-error {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { return true } func hash(into hasher: inout Hasher) {} } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}} extension YetOtherFileNonconforming: CaseIterable {} // expected-error {{does not conform}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // Check the use of conditional conformances. enum ArrayOfEquatables : Equatable { case only([Int]) } struct NotEquatable { } enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}} case only([NotEquatable]) //expected-note {{associated value type '[NotEquatable]' does not conform to protocol 'Equatable', preventing synthesized conformance of 'ArrayOfNotEquatables' to 'Equatable'}} } // Conditional conformances should be able to be synthesized enum GenericDeriveExtension<T> { case A(T) } extension GenericDeriveExtension: Equatable where T: Equatable {} extension GenericDeriveExtension: Hashable where T: Hashable {} // Incorrectly/insufficiently conditional shouldn't work enum BadGenericDeriveExtension<T> { case A(T) //expected-note {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}} //expected-note@-1 {{associated value type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}} } extension BadGenericDeriveExtension: Equatable {} // // expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}} extension BadGenericDeriveExtension: Hashable where T: Equatable {} // expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}} // But some cases don't need to be conditional, even if they look similar to the // above struct AlwaysHashable<T>: Hashable {} enum UnusedGenericDeriveExtension<T> { case A(AlwaysHashable<T>) } extension UnusedGenericDeriveExtension: Hashable {} // Cross-file synthesis is disallowed for conditional cases just as it is for // non-conditional ones. extension GenericOtherFileNonconforming: Equatable where T: Equatable {} // expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in a different file to the type}} // rdar://problem/41852654 // There is a conformance to Equatable (or at least, one that implies Equatable) // in the same file as the type, so the synthesis is okay. Both orderings are // tested, to catch choosing extensions based on the order of the files, etc. protocol ImplierMain: Equatable {} enum ImpliedMain: ImplierMain { case a(Int) } extension ImpliedOther: ImplierMain {} // Comparable enum synthesis enum Angel: Comparable { case lily, elsa, karlie } func pit(_ a: Angel, against b: Angel) -> Bool { return a < b } // enums with non-conforming payloads don’t get synthesized Comparable enum Notice: Comparable { // expected-error{{type 'Notice' does not conform to protocol 'Comparable'}} expected-error{{type 'Notice' does not conform to protocol 'Equatable'}} case taylor((Int, Int)), taylornation(Int) // expected-note{{associated value type '(Int, Int)' does not conform to protocol 'Equatable', preventing synthesized conformance of 'Notice' to 'Equatable'}} } // neither do enums with raw values enum Track: Int, Comparable { // expected-error{{type 'Track' does not conform to protocol 'Comparable'}} case four = 4 case five = 5 case six = 6 } // synthesized Comparable must be explicit enum Publicist { case thow, paine } func miss(_ a: Publicist, outsold b: Publicist) -> Bool { return b < a // expected-error{{binary operator '<' cannot be applied to two 'Publicist' operands}} } // can synthesize Comparable conformance through extension enum Birthyear { case eighties(Int) case nineties(Int) case twothousands(Int) } extension Birthyear: Comparable { } func canEatHotChip(_ birthyear:Birthyear) -> Bool { return birthyear > .nineties(3) } // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
8acc8abfaf86c621d3ff8be5c46405ed
34.538667
209
0.7364
false
false
false
false
moltin/ios-sdk
refs/heads/master
Tests/moltin iOS Tests/CartTests.swift
mit
1
// // CartTests.swift // moltin iOS // // Created by Craig Tweedy on 26/02/2018. // import XCTest @testable import moltin class CartTests: XCTestCase { func testGettingANewCart() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") _ = request.get(forID: "3333") { (result) in switch result { case .success(let cart): XCTAssert(cart.id == "3333") XCTAssert(type(of: cart) == moltin.Cart.self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testGettingCartItems() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") _ = request.items(forCartID: "3333") { (result) in switch result { case .success(let cartItems): XCTAssert(cartItems.data?[0].id == "abc123") XCTAssert(type(of: cartItems.data) == Optional<[moltin.CartItem]>.self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testGettingCartItemsWithTaxes() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsWithTaxesData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") _ = request.items(forCartID: "3333") { (result) in switch result { case .success(let cartItems): XCTAssert(cartItems.data?[0].id == "abc123") XCTAssert(type(of: cartItems.data) == Optional<[moltin.CartItem]>.self) XCTAssert(cartItems.data?[0].relationships != nil) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testAddingAProductToCart() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") let cartID = "3333" let productID = "12345" _ = request.addProduct(withID: productID, ofQuantity: 5, toCart: cartID) { (result) in switch result { case .success(let cartItems): XCTAssert(cartItems[0].id == "abc123") XCTAssert(type(of: cartItems) == [moltin.CartItem].self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testBuildingACartItem() { let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345")) let item = request.buildCartItem(withID: "12345", ofQuantity: 5) XCTAssert(item["type"] as? String == "cart_item") XCTAssert(item["id"] as? String == "12345") XCTAssert(item["quantity"] as? Int == 5) } func testAddingACustomItem() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") let cartID: String = "3333" let customCartPrice = CartItemPrice(amount: 111, includes_tax: false) let customItem = CustomCartItem(withName: "testItem", sku: "1231", quantity: 1, description: "test desc", price: customCartPrice) _ = request.addCustomItem(customItem, toCart: cartID) { (result) in switch result { case .success(let cart): XCTAssert(type(of: cart) == [moltin.CartItem].self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testAddingAPromotion() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.cartItemsData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") let cartID: String = "3333" _ = request.addPromotion("12345", toCart: cartID) { (result) in switch result { case .success(let cart): XCTAssert(type(of: cart) == [moltin.CartItem].self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testBuildingAPromotionItem() { let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345")) let item = request.buildCartItem(withID: "12345", ofType: .promotionItem) XCTAssert(item["type"] as? String == "promotion_item") XCTAssert(item["code"] as? String == "12345") } func testRemovingAnItemFromCart() { } func testUpdatingAnItemInCart() { } func testCheckingOutCart() { } func testBuildingCheckoutCartDataWithoutShippingAddressWorks() { let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345")) let customer = Customer(withID: "12345") let billingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy") billingAddress.line1 = "7 Patterdale Terrace" let item = request.buildCartCheckoutData(withCustomer: customer, withBillingAddress: billingAddress, withShippingAddress: nil) let customerDetails = item["customer"] as? [String: Any] ?? [:] let shippingDetails = item["shipping_address"] as? [String: Any] ?? [:] let billingDetails = item["billing_address"] as? [String: Any] ?? [:] XCTAssert(customerDetails["id"] as? String == "12345") XCTAssert(shippingDetails["line_1"] as? String == "7 Patterdale Terrace") XCTAssert(billingDetails["line_1"] as? String == "7 Patterdale Terrace") } func testBuildingCheckoutCartDataWithShippingAddressWorks() { let request = CartRequest(withConfiguration: MoltinConfig.default(withClientID: "12345")) let customer = Customer(withID: "12345") let billingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy") billingAddress.line1 = "7 Patterdale Terrace" let shippingAddress = Address(withFirstName: "Craig", withLastName: "Tweedy") shippingAddress.line1 = "8 Patterdale Terrace" let item = request.buildCartCheckoutData(withCustomer: customer, withBillingAddress: billingAddress, withShippingAddress: shippingAddress) let customerDetails = item["customer"] as? [String: Any] ?? [:] let shippingDetails = item["shipping_address"] as? [String: Any] ?? [:] let billingDetails = item["billing_address"] as? [String: Any] ?? [:] XCTAssert(customerDetails["id"] as? String == "12345") XCTAssert(shippingDetails["line_1"] as? String == "8 Patterdale Terrace") XCTAssert(billingDetails["line_1"] as? String == "7 Patterdale Terrace") } func testDeletingCart() { let (_, request) = MockFactory.mockedCartRequest(withJSON: MockCartDataFactory.deletedCartData) let expectationToFulfill = expectation(description: "CartRequest calls the method and runs the callback closure") let cartID: String = "3333" _ = request.deleteCart(cartID) { (result) in switch result { case .success(let cart): XCTAssert(type(of: cart) == [moltin.Cart].self) case .failure(let error): XCTFail(error.localizedDescription) } expectationToFulfill.fulfill() } waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } }
0be08954bcb8393b055a70143fb350db
37.425703
146
0.614235
false
true
false
false
kstaring/swift
refs/heads/upstream-master
test/SILGen/init_ref_delegation.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s struct X { } // Initializer delegation within a struct. struct S { // CHECK-LABEL: sil hidden @_TFV19init_ref_delegation1SC{{.*}} : $@convention(method) (@thin S.Type) -> S { init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin S.Type): // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box $@box S // CHECK-NEXT: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S // CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1SC{{.*}} : $@convention(method) (X, @thin S.Type) -> S // CHECK: [[X_CTOR:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X // CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(method) (X, @thin S.Type) -> S self.init(x: X()) // CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[SELF]] : $*S // CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [trivial] [[SELF]] : $*S // CHECK-NEXT: destroy_value [[SELF_BOX]] : $@box S // CHECK-NEXT: return [[SELF_BOX1]] : $S } init(x: X) { } } // Initializer delegation within an enum enum E { // We don't want the enum to be uninhabited case Foo // CHECK-LABEL: sil hidden @_TFO19init_ref_delegation1EC{{.*}} : $@convention(method) (@thin E.Type) -> E init() { // CHECK: bb0([[E_META:%[0-9]+]] : $@thin E.Type): // CHECK: [[E_BOX:%[0-9]+]] = alloc_box $@box E // CHECK: [[PB:%.*]] = project_box [[E_BOX]] // CHECK: [[E_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*E // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFO19init_ref_delegation1EC{{.*}} : $@convention(method) (X, @thin E.Type) -> E // CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(method) (X, @thin E.Type) -> E // CHECK: assign [[S:%[0-9]+]] to [[E_SELF]] : $*E // CHECK: [[E_BOX1:%[0-9]+]] = load [trivial] [[E_SELF]] : $*E self.init(x: X()) // CHECK: destroy_value [[E_BOX]] : $@box E // CHECK: return [[E_BOX1:%[0-9]+]] : $E } init(x: X) { } } // Initializer delegation to a generic initializer struct S2 { // CHECK-LABEL: sil hidden @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(method) (@thin S2.Type) -> S2 init() { // CHECK: bb0([[S2_META:%[0-9]+]] : $@thin S2.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $@box S2 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S2 // CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X // CHECK: store [[X]] to [trivial] [[X_BOX]] : $*X // CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: assign [[SELF_BOX1]] to [[SELF]] : $*S2 // CHECK: dealloc_stack [[X_BOX]] : $*X // CHECK: [[SELF_BOX4:%[0-9]+]] = load [trivial] [[SELF]] : $*S2 self.init(t: X()) // CHECK: destroy_value [[SELF_BOX]] : $@box S2 // CHECK: return [[SELF_BOX4]] : $S2 } init<T>(t: T) { } } class C1 { var ivar: X // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C1c{{.*}} : $@convention(method) (X, @owned C1) -> @owned C1 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C1): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $@box C1 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C1 // CHECK: store [[ORIG_SELF]] to [init] [[SELF]] : $*C1 // CHECK: [[SELF_FROM_BOX:%[0-9]+]] = load_borrow [[SELF]] : $*C1 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_FROM_BOX]] : $C1, #C1.init!initializer.1 : (C1.Type) -> (X, X) -> C1 , $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_FROM_BOX]]) : $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: store [[SELFP]] to [init] [[SELF]] : $*C1 // CHECK: [[SELFP:%[0-9]+]] = load [copy] [[SELF]] : $*C1 // CHECK: destroy_value [[SELF_BOX]] : $@box C1 // CHECK: return [[SELFP]] : $C1 self.init(x1: x, x2: x) } init(x1: X, x2: X) { ivar = x1 } } @objc class C2 { var ivar: X // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2c{{.*}} : $@convention(method) (X, @owned C2) -> @owned C2 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C2): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $@box C2 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C2 // CHECK: store [[ORIG_SELF]] to [init] [[UNINIT_SELF]] : $*C2 // SEMANTIC ARC TODO: Another case of us doing a borrow and passing // something in @owned. I think we will need some special help for // definite-initialization. // CHECK: [[SELF:%[0-9]+]] = load_borrow [[UNINIT_SELF]] : $*C2 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF]] : $C2, #C2.init!initializer.1 : (C2.Type) -> (X, X) -> C2 , $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF]]) : $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: store [[REPLACE_SELF]] to [init] [[UNINIT_SELF]] : $*C2 // CHECK: [[VAR_15:%[0-9]+]] = load [copy] [[UNINIT_SELF]] : $*C2 // CHECK: destroy_value [[SELF_BOX]] : $@box C2 // CHECK: return [[VAR_15]] : $C2 self.init(x1: x, x2: x) // CHECK-NOT: sil hidden @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, @owned C2) -> @owned C2 { } // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2C{{.*}} : $@convention(method) (X, X, @thick C2.Type) -> @owned C2 { // CHECK-NOT: sil @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 { init(x1: X, x2: X) { ivar = x1 } } var x: X = X() class C3 { var i: Int = 5 // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C3c{{.*}} : $@convention(method) (@owned C3) -> @owned C3 convenience init() { // CHECK: mark_uninitialized [delegatingself] // CHECK-NOT: integer_literal // CHECK: class_method [[SELF:%[0-9]+]] : $C3, #C3.init!initializer.1 : (C3.Type) -> (X) -> C3 , $@convention(method) (X, @owned C3) -> @owned C3 // CHECK-NOT: integer_literal // CHECK: return self.init(x: x) } init(x: X) { } } // Initializer delegation from a constructor defined in an extension. class C4 { } extension C4 { convenience init(x1: X) { self.init() } // CHECK: sil hidden @_TFC19init_ref_delegation2C4c{{.*}} // CHECK: [[PEER:%[0-9]+]] = function_ref @_TFC19init_ref_delegation2C4c{{.*}} // CHECK: apply [[PEER]]([[X:%[0-9]+]], [[OBJ:%[0-9]+]]) convenience init(x2: X) { self.init(x1: x2) } } // Initializer delegation to a constructor defined in a protocol extension. protocol Pb { init() } extension Pb { init(d: Int) { } } class Sn : Pb { required init() { } convenience init(d3: Int) { self.init(d: d3) } } // Same as above but for a value type. struct Cs : Pb { init() { } init(d3: Int) { self.init(d: d3) } }
4e8ddae647bc57f7502af14d9db5ae73
40.826733
183
0.538644
false
false
false
false
Blackjacx/StickyHeaderFlowLayout
refs/heads/master
Demo/Demo/CollectionViewController.swift
mit
1
// // InvoicesViewController.swift // Kundencenter // // Created by Stefan Herold on 19.11.14. // Copyright (c) 2014 Deutsche Telekom AG. All rights reserved. // import UIKit class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { private let reuseIDTitleCell = "TitleCell" private let reuseIDHeaderView = "HeaderView" override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition({ (ctx) -> Void in self.collectionViewLayout.invalidateLayout() }, completion: nil) } // TODO: Deprecated - It is safe to delete this in iOS8++ apps. The above viewWillTransitionToSize will replace it. override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { self.collectionViewLayout.invalidateLayout() } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 5 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIDTitleCell, forIndexPath: indexPath) as! TitleCell cell.titleLabel.text = "(\(indexPath.section), \(indexPath.item))" return cell } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { var header: HeaderView? if kind == UICollectionElementKindSectionHeader { header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: reuseIDHeaderView, forIndexPath: indexPath) as? HeaderView header?.backgroundColor = UIColor.lightGrayColor() } header?.titleLabel.text = NSLocalizedString("This is the Funny Header 🎉", comment:"") return header! } // MARK: UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if UIDevice.currentDevice().userInterfaceIdiom == .Pad { return CGSizeMake(8*12, 8*12) } else { return CGSizeMake(self.view.frame.size.width, 4*12) } } }
3483e3e9367c7c785c7acef966003875
38.46875
177
0.794141
false
false
false
false
Ajunboys/actor-platform
refs/heads/master
actor-apps/app-ios/Actor/Utils/MeasureUtils.swift
mit
40
// // MeasureUtils.swift // ActorApp // // Created by Stepan Korshakov on 27.07.15. // Copyright (c) 2015 Actor LLC. All rights reserved. // import Foundation private var startTime: NSDate! func startMeasure() { startTime = NSDate() } func trackMeasure(name: String) { if startTime == nil { return } let timeInterval = Int(NSDate().timeIntervalSinceDate(startTime) * 1000) startTime = NSDate() log("Measured \(name) in \(timeInterval) ms") } func stopMeasure() { startTime = nil }
fa69ac7da58ee66af5ec8de56402c184
17.785714
76
0.657143
false
false
false
false
kuler90/OrangeFramework
refs/heads/master
Source/Extensions/Core/Log/Log+OFExtensions.swift
mit
1
import Foundation /// setup which message should print, by default print all in DEBUG and nothing otherwise public func of_printSetup(handler: OFLogHandler) { OFLogSetup(handler) } public func of_print(value: Any?, level: OFLogLevel = .Default, _ function: String = #function, _ file: String = #file, _ line: UInt32 = #line) { __OFLog(value != nil ? String(value!) : nil, level, function, file, line) } extension OFLogLevel: Comparable {} public func ==(lhs: OFLogLevel, rhs: OFLogLevel) -> Bool { return lhs.rawValue == rhs.rawValue } public func <(lhs: OFLogLevel, rhs: OFLogLevel) -> Bool { return lhs.rawValue < rhs.rawValue }
05a617df461c1eef4cb41f340131e82b
29.714286
145
0.706522
false
false
false
false
quran/quran-ios
refs/heads/main
Sources/TranslationService/TranslationsVersionUpdater.swift
apache-2.0
1
// // TranslationsVersionUpdater.swift // Quran // // Created by Mohamed Afifi on 3/12/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import BatchDownloader import PromiseKit protocol TranslationsVersionUpdater { func updateInstalledVersion(for translation: Translation) throws -> Translation } struct VersionPersistenceFactory { let create: (String) -> DatabaseVersionPersistence } struct DefaultTranslationsVersionUpdater: TranslationsVersionUpdater { let selectedTranslationsPreferences = SelectedTranslationsPreferences.shared let persistence: ActiveTranslationsPersistence let versionPersistenceCreator: VersionPersistenceFactory let unzipper: TranslationUnzipper func updateInstalledVersion(for translation: Translation) throws -> Translation { try unzipper.unzipIfNeeded(translation) // unzip if needed return try updateInstalledVersion(translation) // update versions } private func updateInstalledVersion(_ translation: Translation) throws -> Translation { var translation = translation let fileURL = translation.localURL let isReachable = fileURL.isReachable let previousInstalledVersion = translation.installedVersion // installed on the latest version & the db file exists if translation.version != translation.installedVersion, isReachable { let versionPersistence = versionPersistenceCreator.create(fileURL.absoluteString) do { let version = try versionPersistence.getTextVersion() translation.installedVersion = version } catch { // if an error occurred while getting the version // that means the db file is corrupted. translation.installedVersion = nil } } else if translation.installedVersion != nil, !isReachable { translation.installedVersion = nil } if previousInstalledVersion != translation.installedVersion { try persistence.update(translation) // remove the translation from selected translations if translation.installedVersion == nil { var selectedTranslations = selectedTranslationsPreferences.selectedTranslations if let index = selectedTranslations.firstIndex(of: translation.id) { selectedTranslations.remove(at: index) selectedTranslationsPreferences.selectedTranslations = selectedTranslations } } } return translation } } private extension DownloadRequest { var isTranslation: Bool { destinationPath.hasPrefix(Translation.translationsPathComponent) } } private extension DownloadBatchResponse { var isTranslation: Bool { requests.count == 1 && requests.contains(where: \.isTranslation) } }
ed4678300de4d28b388fb226cc56e0c7
37.411111
95
0.702632
false
false
false
false
tjw/swift
refs/heads/master
test/NameBinding/scope_map_lookup.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift %s -enable-astscope-lookup // Name binding in default arguments // FIXME: Semantic analysis should produce an error here, because 'x' // is not actually available. func functionParamScopes(x: Int, y: Int = x) -> Int { return x + y } // Name binding in instance methods. class C1 { var x = 0 var hashValue: Int { return x } } // Protocols involving 'Self'. protocol P1 { associatedtype A = Self } // Protocols involving associated types. protocol AProtocol { associatedtype e : e // expected-error@-1 {{use of undeclared type 'e'}} } // Extensions. protocol P2 { } extension P2 { func getSelf() -> Self { return self } } #if false // Lazy properties class LazyProperties { init() { lazy var localvar = 42 // FIXME: should error {{lazy is only valid for members of a struct or class}} {{5-10=}} localvar += 1 _ = localvar } var value: Int = 17 lazy var prop1: Int = value lazy var prop2: Int = { value + 1 }() lazy var prop3: Int = { [weak self] in self.value + 1 }() lazy var prop4: Int = self.value lazy var prop5: Int = { self.value + 1 }() } #endif // Protocol extensions. // Extending via a superclass constraint. class Superclass { func foo() { } static func bar() { } typealias Foo = Int } protocol PConstrained4 { } extension PConstrained4 where Self : Superclass { func testFoo() -> Foo { foo() self.foo() return Foo(5) } static func testBar() { bar() self.bar() } } // Local computed properties. func localComputedProperties() { var localProperty: Int { get { return localProperty // expected-warning{{attempting to access 'localProperty' within its own getter}} } set { _ = newValue print(localProperty) } } { print(localProperty) }() } // Top-level code. func topLevel() { } topLevel() let c1opt: C1? = C1() guard let c1 = c1opt else { } protocol Fooable { associatedtype Foo var foo: Foo { get } } // The extension below once caused infinite recursion. struct S<T> // expected-error{{expected '{' in struct}} extension S // expected-error{{expected '{' in extension}} let a = b ; let b = a // expected-note@-1 {{'a' declared here}} // expected-error@-2 {{ambiguous use of 'a'}}
e64064428c8de3d1e1f24312a299c8e3
17.609756
116
0.641328
false
false
false
false
mrahmiao/Velociraptor
refs/heads/master
VelociraptorTests/VLRHeaderFieldMatchingOptionsSpec.swift
mit
1
// // VLRHeaderFieldMatchingOptionsSpec.swift // Velociraptor // // Created by mrahmiao on 4/28/15. // Copyright (c) 2015 Code4Blues. All rights reserved. // import Quick import Nimble class VLRHeaderFieldMatchingOptionsSpec: QuickSpec { typealias Matcher = [NSObject: AnyObject] -> Bool func matchingOption(option: VLRHeaderFieldMatchingOptions, withStubbedHeaderFields stubbedFields: [String: String]) -> Matcher { return { (fields) -> Bool in return option.incomingHeaderFields(fields, matchesStubbedHeaderFields: stubbedFields) } } override func spec() { let minimumNumberOfMatchedHeaders = 3 let stubbedHeaders = [ "Authroization": "13145253", "Accept": "text/plain", "Cookie": "hello=world", "Custom": "customHeader" ] let sameHeaders = [ "Authroization": "13145253", "Accept": "text/plain", "Cookie": "hello=world", "Custom": "customHeader" ] let lowercaseSameHeaders = [ "Authroization": "13145253", "accept": "text/plain", "cookie": "hello=world", "Custom": "customHeader" ] let sameNameDifferentValueHeaders = [ "Authroization": "DifferentHeader", "Accept": "text/plain", "Cookie": "hello=world", "Custom": "customHeader" ] let supersetHeaders = [ "Authroization": "13145253", "accept": "text/plain", "cookie": "hello=world", "Custom": "customHeader", "Super": "Man", "Icon": "Man" ] let subsetHeaders = [ "Authroization": "13145253", "Accept": "text/plain" ] let lowercaseSubsetHeaders = [ "Authroization": "13145253", "accept": "text/plain" ] let differentSubsetHeaders = [ "Authroization": "13145253", "accept": "application/json" ] let emptySetHeaders = [String: String]() let matchedIntersectHeaders = [ "Authroization": "13145253", "Accept": "text/plain", "Cookie": "hello=world", "Different": "DifferentHeaderField" ] let lowercaseMatchedIntersectHeaders = [ "Authroization": "13145253", "accept": "text/plain", "cookie": "hello=world", "Different": "DifferentHeaderField" ] /// With 2 common header fields, which is less than the minimum: 3. let dismatchedIntersectHeaders = [ "Authroization": "13145253", "Accept": "text/plain", "Different": "DifferentHeaderField" ] let disjointHeaders = [ "Totally": "Different", "Completely": "Also Different", "Disjoint": "With out any identical" ] let anotherDisjointHeaders = [ "Totally": "Different", "Completely": "Also Different", "Disjoint": "With out any identical", "Different": "Different" ] var matchingResult: Bool! var matches: Matcher! afterEach { matchingResult = nil matches = nil } describe("When matching requests with exactly the same header fields") { beforeEach { matches = self.matchingOption(.Exactly, withStubbedHeaderFields: stubbedHeaders) } it("matches when the both header fields are exactly the same") { matchingResult = matches(sameHeaders) expect(matchingResult).to(beTrue()) } it("matches when incoming requests have lowecase haeder field names but with same values") { matchingResult = matches(lowercaseSameHeaders) expect(matchingResult).to(beTrue()) } it("does not any other header fields") { let dismatchedHeaders = [ sameNameDifferentValueHeaders, supersetHeaders, subsetHeaders, lowercaseSubsetHeaders, differentSubsetHeaders, matchedIntersectHeaders, lowercaseMatchedIntersectHeaders, dismatchedIntersectHeaders, emptySetHeaders, disjointHeaders, anotherDisjointHeaders ] for dismathed in dismatchedHeaders { matchingResult = matches(dismathed) expect(matchingResult).to(beFalse()) } } } describe("When matching requests with partially common header fields") { context("With minimum number set to 3") { beforeEach { matches = self.matchingOption(.Partially(3), withStubbedHeaderFields: stubbedHeaders) } it("matches the identical header fields") { matchingResult = matches(sameHeaders) expect(matchingResult).to(beTrue()) } it("matches the identical header fields with lowercase names") { matchingResult = matches(lowercaseSameHeaders) expect(matchingResult).to(beTrue()) } it("matches the super set header fields") { matchingResult = matches(supersetHeaders) expect(matchingResult).to(beTrue()) } it("matches the header fields with satisfied number of common elements") { matchingResult = matches(matchedIntersectHeaders) expect(matchingResult).to(beTrue()) matchingResult = nil matchingResult = matches(sameNameDifferentValueHeaders) expect(matchingResult).to(beTrue()) } it("matches the header fields with satisfied number of common elements and lowercase names") { matchingResult = matches(lowercaseMatchedIntersectHeaders) expect(matchingResult).to(beTrue()) } it("does not match any other header fields") { let headers = [ subsetHeaders, lowercaseSubsetHeaders, differentSubsetHeaders, dismatchedIntersectHeaders, emptySetHeaders, disjointHeaders, anotherDisjointHeaders ] for header in headers { matchingResult = matches(header) expect(matchingResult).to(beFalse()) } } } context("With minimum number set to 10") { beforeEach { matches = self.matchingOption(.Partially(10), withStubbedHeaderFields: stubbedHeaders) } it("mathes the identical header fields") { matchingResult = matches(sameHeaders) expect(matchingResult).to(beTrue()) } it("mathes the identical header fields with lowercase names") { matchingResult = matches(lowercaseSameHeaders) expect(matchingResult).to(beTrue()) } it("matches the super set header fields") { matchingResult = matches(supersetHeaders) expect(matchingResult).to(beTrue()) } it("does not match any other header fields") { let headers = [ sameNameDifferentValueHeaders, subsetHeaders, lowercaseSubsetHeaders, differentSubsetHeaders, matchedIntersectHeaders, lowercaseMatchedIntersectHeaders, dismatchedIntersectHeaders, emptySetHeaders, disjointHeaders, anotherDisjointHeaders ] for header in headers { matchingResult = matches(header) expect(matchingResult).to(beFalse()) } } } context("With minimum number set to 0") { it("matches arbitrary header fields") { matches = self.matchingOption(.Partially(0), withStubbedHeaderFields: stubbedHeaders) let headers = [ sameHeaders, lowercaseSameHeaders, sameNameDifferentValueHeaders, supersetHeaders, subsetHeaders, lowercaseSubsetHeaders, differentSubsetHeaders, matchedIntersectHeaders, lowercaseMatchedIntersectHeaders, dismatchedIntersectHeaders, emptySetHeaders, disjointHeaders, anotherDisjointHeaders ] for header in headers { matchingResult = matches(header) expect(matchingResult).to(beTrue()) } } } } describe("When matching requests with strict subset header fields") { beforeEach { matches = self.matchingOption(.StrictSubset, withStubbedHeaderFields: stubbedHeaders) } it("matches subset of stubbed header fields") { matchingResult = matches(subsetHeaders) expect(matchingResult).to(beTrue()) } it("matches subset of stubbed header fields with lowercase names") { matchingResult = matches(lowercaseSubsetHeaders) expect(matchingResult).to(beTrue()) } it("matches empty header fields") { matchingResult = matches(emptySetHeaders) expect(matchingResult).to(beTrue()) } it("does not match any other header fields") { let headers = [ sameHeaders, lowercaseSameHeaders, sameNameDifferentValueHeaders, supersetHeaders, differentSubsetHeaders, matchedIntersectHeaders, lowercaseMatchedIntersectHeaders, dismatchedIntersectHeaders, disjointHeaders, anotherDisjointHeaders ] for header in headers { matchingResult = matches(header) expect(matchingResult).to(beFalse()) } } } describe("When matching request with arbitrary header fields") { beforeEach { matches = self.matchingOption(.Arbitrarily, withStubbedHeaderFields: stubbedHeaders) } it("matches arbitrary header fields") { let headers = [ sameHeaders, lowercaseSameHeaders, sameNameDifferentValueHeaders, supersetHeaders, subsetHeaders, lowercaseSubsetHeaders, differentSubsetHeaders, matchedIntersectHeaders, lowercaseMatchedIntersectHeaders, dismatchedIntersectHeaders, emptySetHeaders, disjointHeaders, anotherDisjointHeaders ] for header in headers { matchingResult = matches(header) expect(matchingResult).to(beTrue()) } } } } }
f9820494b2a216d4b8f343937c304896
31.202572
130
0.619932
false
false
false
false
Softwave/Radix
refs/heads/master
Radix/ViewController.swift
mit
1
// // ViewController.swift // Radix // // Created by J Leyba on 8/20/15. // Copyright (c) 2015 Softwave. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet var mainView: NSView! @IBOutlet var baseSelect: NSPopUpButton! @IBOutlet var inputField: NSTextField! @IBOutlet var lblDecimal: NSTextField! @IBOutlet var lblBinary: NSTextField! @IBOutlet var lblOctal: NSTextField! @IBOutlet var lblHex: NSTextField! var inVal:String = "" var outVal:Float = 4 var outDec:NSString = "0" var outBin:NSString = "0" var outOct:NSString = "0" var outHex:NSString = "0" var pasteBoard = NSPasteboard.generalPasteboard() override func viewDidLoad() { super.viewDidLoad() //mainView.backgroundColor = NSColor(hexString: "#404e95") mainView.backgroundColor = NSColor(hexString: "#fbebe0") setInitVal() // Do any additional setup after loading the view. pasteBoard.clearContents() } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } func setInitVal() { lblDecimal.stringValue = "Decimal: " + String(outDec) lblBinary.stringValue = "Binary: " + String(outBin) lblOctal.stringValue = "Octal: " + String(outOct) lblHex.stringValue = "Hex: " + String(outHex) } func convAction() { outVal = (inputField.stringValue as NSString).floatValue if baseSelect.indexOfSelectedItem == 0 { outVal = (inputField.stringValue as NSString).floatValue } if baseSelect.indexOfSelectedItem == 1 { outVal = Float(strtoul(inputField.stringValue, nil, 2)) } if baseSelect.indexOfSelectedItem == 2 { outVal = Float(strtoul(inputField.stringValue, nil, 8)) } if baseSelect.indexOfSelectedItem == 3 { outVal = Float(strtoul(inputField.stringValue, nil, 16)) } outDec = String(Int(outVal), radix: 10) outBin = String(Int(outVal), radix: 2) outOct = String(Int(outVal), radix: 8) outHex = String(Int(outVal), radix: 16) //pasteBoard.writeObjects([outHex]) } @IBAction func btnConvert(sender: NSButton) { let tempString:NSString = inputField.stringValue as NSString let stringLength = (tempString as String).characters.count if stringLength > 10 { //print("too big") let thingy = stringLength - 10 let substringIndex = stringLength - thingy inputField.stringValue = inputField.stringValue.substringToIndex(inputField.stringValue.startIndex.advancedBy(substringIndex)) } else { convAction() } setInitVal() } @IBAction func btnCopyDecimal(sender: NSButton) { pasteBoard.clearContents() pasteBoard.writeObjects([outDec]) } @IBAction func btnCopyBinary(sender: NSButton) { pasteBoard.clearContents() pasteBoard.writeObjects([outBin]) } @IBAction func btnCopyOctal(sender: NSButton) { pasteBoard.clearContents() pasteBoard.writeObjects([outOct]) } @IBAction func btnCopyHex(sender: NSButton) { pasteBoard.clearContents() pasteBoard.writeObjects([outHex]) } }
44f4c2c2134a741896f2e76619ff2756
26.174242
138
0.595762
false
false
false
false
CodaFi/swift
refs/heads/main
test/Serialization/Recovery/type-removal-objc.swift
apache-2.0
30
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t -module-name Lib -I %S/Inputs/custom-modules %s // RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules | %FileCheck %s // RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules -Xcc -DBAD > %t.txt // RUN: %FileCheck -check-prefix CHECK-RECOVERY %s < %t.txt // RUN: %FileCheck -check-prefix CHECK-RECOVERY-NEGATIVE %s < %t.txt // REQUIRES: objc_interop import TypeRemovalObjC // CHECK-DAG: let simple: AnyObject? // CHECK-RECOVERY-DAG: let simple: AnyObject? public let simple: AnyObject? = nil // CHECK-DAG: let someObject: Base? // CHECK-RECOVERY-NEGATIVE-NOT: let someObject: public let someObject: Base? = nil // CHECK-DAG: let someGenericObject: Generic<AnyObject>? // CHECK-RECOVERY-NEGATIVE-NOT: let someGenericObject: public let someGenericObject: Generic<AnyObject>? = nil // CHECK-DAG: let someProtoValue: SomeProto? // CHECK-RECOVERY-NEGATIVE-NOT: let someProtoValue: public let someProtoValue: SomeProto? = nil // CHECK-DAG: let someProtoType: SomeProto.Type? // CHECK-RECOVERY-NEGATIVE-NOT: let someProtoType: public let someProtoType: SomeProto.Type? = nil // CHECK-DAG: let someProtoCompositionValue: (AProto & SomeProto)? // CHECK-RECOVERY-NEGATIVE-NOT: let someProtoCompositionValue: public let someProtoCompositionValue: (AProto & SomeProto)? = nil // CHECK-DAG: let someProtoCompositionValue2: (SomeProto & ZProto)? // CHECK-RECOVERY-NEGATIVE-NOT: let someProtoCompositionValue2: public let someProtoCompositionValue2: (SomeProto & ZProto)? = nil // CHECK-DAG: let someTypedefValue: SomeTypedef // CHECK-RECOVERY-DAG: let someTypedefValue: Int64 public let someTypedefValue: SomeTypedef = 0 // CHECK-DAG: let someTypedefOptValue: SomeTypedef? // CHECK-RECOVERY-DAG: let someTypedefOptValue: Int64? public let someTypedefOptValue: SomeTypedef? = nil // CHECK-DAG: unowned var someUnownedObject: @sil_unowned Base // CHECK-RECOVERY-NEGATIVE-NOT: var someUnownedObject: public unowned var someUnownedObject: Base = Base() // CHECK-DAG: unowned(unsafe) var someUnownedUnsafeObject: @sil_unmanaged Base // CHECK-RECOVERY-NEGATIVE-NOT: var someUnownedUnsafeObject: public unowned(unsafe) var someUnownedUnsafeObject: Base = Base() // CHECK-DAG: weak var someWeakObject: @sil_weak Base // CHECK-RECOVERY-NEGATIVE-NOT: var someWeakObject: public weak var someWeakObject: Base? = nil // CHECK-DAG: struct GenericStruct<T> // CHECK-RECOVERY-DAG: struct GenericStruct<T> struct GenericStruct<T> {} // CHECK-DAG: extension GenericStruct where T : SomeProto // CHECK-RECOVERY-NEGATIVE-NOT: extension GenericStruct{{.*}}SomeProto extension GenericStruct where T: SomeProto { // CHECK-DAG: func someOperation // CHECK-RECOVERY-NEGATIVE-NOT: someOperation func someOperation() {} }
294f44885b4af33bf447539d64ef3b0c
44.375
138
0.761708
false
false
false
false
brentdax/Upconvert
refs/heads/master
UpconvertTests/KeyPathTests.swift
mit
1
// // KeyPathTests.swift // UpconvertTests // // Created by Brent Royal-Gordon on 7/8/17. // Copyright © 2017 Architechies. Distributed under the MIT License. // import XCTest import Upconvert class Person: Equatable { init(name: String) { self.name = name } var name: String var friends: [Person] = [] var isFriendless: Bool { return friends.isEmpty } static func == (lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.friends == rhs.friends } } class KeyPathTests: XCTestCase { let people: [Person] = { let p = [ Person(name: "Alice"), Person(name: "Bob"), Person(name: "Eve") ] p[0].friends = [p[1]] p[1].friends = [p[0]] return p }() func testSpecific() { let fn = ^\Person.name XCTAssertEqual(fn(people[0]), "Alice", "Key path converted to function looks up the key path") } func testInferred() { // This test passes merely by compiling. let _: (Person) -> String = ^\.name let _: (Person) -> [Person] = ^\.friends let _: (Person) -> Bool = (^\.isFriendless) } func testUsage() { let names = people.map(^\.name) XCTAssertEqual(names, ["Alice", "Bob", "Eve"], "Key path conversion works in map") let bestFriends = people.flatMap(^\.friends.first) XCTAssertEqual(bestFriends, [people[1], people[0]], "Key path conversion works in flatMap") let friendless = people.filter(^\.isFriendless) XCTAssertEqual(friendless, [people[2]], "Key path conversion works in filter") } }
756876b9cc1d3cbdbe3a4ad4dbde9633
26.483871
102
0.562207
false
true
false
false
austinzmchen/guildOfWarWorldBosses
refs/heads/master
GoWWorldBosses/Models/APIs/Remote/WBRemote.swift
mit
1
// // WBRemote.swift // GoWWorldBosses // // Created by Austin Chen on 2016-11-23. // import Foundation import RealmSwift protocol WBRemoteRecordSyncableType { var id: String { get } } enum WBRemoteRecordChange<T: WBRemoteRecordSyncableType, S: WBObject> { case found(T, S) case inserted(T, S) case removed var isInserted: Bool { switch self { case .inserted: return true default: return false } } var isFound: Bool { switch self { case .found: return true default: return false } } var isRemoved: Bool { switch self { case .removed: return true default: return false } } } import Alamofire /* remote settings */ struct WBRemoteSettings { static let serialQueue: DispatchQueue = DispatchQueue(label: "com.ac.GoWWorldBosses.remote-serial-queue", attributes: []) static let concurrentQueue: DispatchQueue = DispatchQueue(label: "com.ac.GoWWorldBosses.remote-concurrent-queue", attributes: DispatchQueue.Attributes.concurrent) } /// All Remote subclasses fetch remote data ASYNCHRONOUSLY, so be aware the completion block is NOT executed on main thread class WBSimpleRemote: NSObject { // domains static let domain = "https://api.guildwars2.com/v2" var alamoFireManager: SessionManager override init() { let serverTrustPolicies: [String: ServerTrustPolicy] = [ type(of: self).domain: .disableEvaluation ] alamoFireManager = SessionManager(configuration: URLSessionConfiguration.default, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)) } } class WBRemote: WBSimpleRemote { let remoteSession: WBRemoteSessionType? init(remoteSession: WBRemoteSession?) { self.remoteSession = remoteSession super.init() } } // for AlamoFire 4.0 + extension String: ParameterEncoding { public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var request = try urlRequest.asURLRequest() request.httpBody = data(using: .utf8, allowLossyConversion: false) return request } }
941896911152af3565628e4063cef805
25.303371
166
0.649722
false
false
false
false
ArbiterLib/Arbiter
refs/heads/master
bindings/swift/Arbiter/Types.swift
mit
2
/** * Base class for any Arbiter Swift object which is backed by a corresponding * C object. */ public class CObject : Equatable { /** * Initializes an object of this type from a C pointer, optionally copying its * contents. * * This initializer cannot perform any typechecking, so the pointer must * correspond to an object of this class. * * If `shouldCopy` is false, the CObject is assumed to retain ownership over * the given pointer, and will free it when the CObject is deinitialized by * ARC. */ public init (_ pointer: COpaquePointer, shouldCopy: Bool = true) { if (shouldCopy) { self._pointer = COpaquePointer(ArbiterCreateCopy(UnsafePointer(pointer))); } else { self._pointer = pointer } } /** * Steals ownership of the `pointer` from this object, returning it. * * After invoking this method, `pointer` will be nil. The caller is * responsible for eventually freeing the stolen pointer. */ public func takeOwnership () -> COpaquePointer { precondition(_pointer != nil) let result = _pointer _pointer = nil return result } deinit { if (_pointer != nil) { ArbiterFree(UnsafeMutablePointer(_pointer)) } } /** * The backing C pointer for this object, or nil. */ public var pointer: COpaquePointer { return _pointer } /** * An internally-visible mutable reference to this object's backing pointer. * * This can be used for two-step initialization (where the CObject needs to * complete initializing before the C pointer is known). It is also used in * the implementation of takeOwnership(). */ var _pointer: COpaquePointer } public func == (lhs: CObject, rhs: CObject) -> Bool { return ArbiterEqual(UnsafePointer(lhs.pointer), UnsafePointer(rhs.pointer)) }
3df665a1ef5ae5da06320a695cc55538
25.2
80
0.673937
false
false
false
false
yankodimitrov/SignalKit
refs/heads/master
SignalKitTests/Extensions/UIKit/UISliderExtensionsTests.swift
mit
1
// // UISliderExtensionsTests.swift // SignalKit // // Created by Yanko Dimitrov on 3/6/16. // Copyright © 2016 Yanko Dimitrov. All rights reserved. // import XCTest @testable import SignalKit class UISliderExtensionsTests: XCTestCase { var bag: DisposableBag! override func setUp() { super.setUp() bag = DisposableBag() } func testObserveValueChanges() { var result: Float = 0 let slider = MockSlider() slider.maximumValue = 20 slider.observe().valueChanges .next { result = $0 } .disposeWith(bag) slider.value = 10 slider.sendActionsForControlEvents(.ValueChanged) XCTAssertEqual(result, 10, "Should observe the UISlider for value changes") } }
1d9feab40157a0e5e18ea923b91eee90
21.405405
83
0.594692
false
true
false
false
kazuhiro4949/PagingKit
refs/heads/master
iOS Sample/iOS Sample/ContentTableViewController.swift
mit
1
// // ContentTableViewController.swift // iOS Sample // // Copyright (c) 2017 Kazuhiro Hayashi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class ContentTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var data: [(emoji: String, name: String)] = [ (emoji: "🐶", name: "Dog"), (emoji: "🐱", name: "Cat"), (emoji: "🦁", name: "Lion"), (emoji: "🐴", name: "Horse"), (emoji: "🐮", name: "Cow"), (emoji: "🐷", name: "Pig"), (emoji: "🐭", name: "Mouse"), (emoji: "🐹", name: "Hamster"), (emoji: "🐰", name: "Rabbit"), (emoji: "🐻", name: "Bear"), (emoji: "🐨", name: "Koala"), (emoji: "🐼", name: "Panda"), (emoji: "🐔", name: "Chicken"), (emoji: "🐤", name: "Baby"), (emoji: "🐵", name: "Monkey"), (emoji: "🦊", name: "Fox"), (emoji: "🐸", name: "Frog"), (emoji: "🦀", name: "Crab"), (emoji: "🦑", name: "Squid"), (emoji: "🐙", name: "Octopus"), (emoji: "🐬", name: "Dolphin"), ] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! ContentTableViewCell cell.configure(data: data[indexPath.row]) return cell } @available(iOS 11.0, *) override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() guard let tableViewLayoutMargin = tableViewLayoutMargin else { return } tableView.layoutMargins = tableViewLayoutMargin } /// To support safe area, all tableViews aligned on scrollView needs to be set margin for the cell's contentView and separator. @available(iOS 11.0, *) private var tableViewLayoutMargin: UIEdgeInsets? { guard let superview = parent?.view else { return nil } let defaultTableContentInsetLeft: CGFloat = 16 return UIEdgeInsets( top: 0, left: superview.safeAreaInsets.left + defaultTableContentInsetLeft, bottom: 0, right: 0 ) } }
9087ea83280061c99a58593717fd4d0c
35.365385
131
0.630354
false
false
false
false
alloyapple/GooseGtk
refs/heads/master
Sources/uGet/MainViewController.swift
apache-2.0
1
// // Created by color on 4/6/18. // import Foundation import GooseGtk import Goose import Dispatch import CGTK let appDir = "uget" let dataDir = "/usr/share" let localDir = "/locale" var configDir = "" let APP_ACCEL_PATH_NEW = "<uGet>/File/New" let APP_ACCEL_PATH_LOAD = "<uGet>/File/Load" let APP_ACCEL_PATH_SAVE = "<uGet>/File/Save" let APP_ACCEL_PATH_SAVE_ALL = "<uGet>/File/SaveAll" let APP_ACCEL_PATH_DELETE = "<uGet>/Download/Delete" let APP_ACCEL_PATH_DELETE_F = "<uGet>/Download/DeleteFile" let APP_ACCEL_PATH_OPEN = "<uGet>/Download/Open" let APP_ACCEL_PATH_OPEN_F = "<uGet>/Download/OpenFolder" let APP_ACCEL_PATH_SWITCH = "<uGet>/Download/SwitchState" class MainViewController: GTKViewController { lazy var pannedView: GTKBox = GTKBox(orientation: .VERTICAL, spacing: 0) var appSetting = AppSetting.load(path: "") func viewDidLoad() { configDir = "\(userConfigDir())\\appDir" registerAccelMap() } func registerAccelMap() { gtk_accel_map_add_entry(APP_ACCEL_PATH_NEW, UInt32(GDK_KEY_n), GDK_CONTROL_MASK); gtk_accel_map_add_entry(APP_ACCEL_PATH_LOAD, UInt32(GDK_KEY_o), GDK_CONTROL_MASK); gtk_accel_map_add_entry(APP_ACCEL_PATH_SAVE, UInt32(GDK_KEY_s), GDK_CONTROL_MASK); gtk_accel_map_add_entry(APP_ACCEL_PATH_SAVE_ALL, UInt32(GDK_KEY_s), GdkModifierType(GDK_CONTROL_MASK.rawValue | GDK_SHIFT_MASK.rawValue)); gtk_accel_map_add_entry(APP_ACCEL_PATH_DELETE, UInt32(GDK_KEY_Delete), GdkModifierType(0)); gtk_accel_map_add_entry(APP_ACCEL_PATH_DELETE_F, UInt32(GDK_KEY_Delete), GDK_CONTROL_MASK); gtk_accel_map_add_entry(APP_ACCEL_PATH_OPEN, UInt32(GDK_KEY_Return), GdkModifierType(0)); gtk_accel_map_add_entry(APP_ACCEL_PATH_OPEN_F, UInt32(GDK_KEY_Return), GDK_SHIFT_MASK); } }
2f2a7363aa09291c86587c21eeef55a0
35.755102
146
0.695556
false
true
false
false
JJCoderiOS/DDMusic
refs/heads/master
DDMusic/View/MusicListCell.swift
apache-2.0
1
import UIKit class MusicListCell: UITableViewCell { var musicM : MusicModel? { didSet { singerIconImageView.image = UIImage(named: (musicM?.singerIcon)!) songNameLabel.text = musicM?.name singerNameLabel.text = musicM?.singer } } @IBOutlet weak var singerIconImageView: UIImageView! @IBOutlet weak var songNameLabel: UILabel! @IBOutlet weak var singerNameLabel: UILabel! class func cellWithTableView(tableView : UITableView) ->MusicListCell { let cellID = "MusicListCell" var cell = tableView.dequeueReusableCell(withIdentifier: cellID) as? MusicListCell if cell == nil { //print("貌似有问题") cell = Bundle.main.loadNibNamed("MusicListCell", owner: nil, options: nil)?.first as?MusicListCell } return cell! } override func awakeFromNib() { super.awakeFromNib( ) //layout不能获取真正的控价大小 所以需要调用此方法进行绘制 self.layoutIfNeeded() singerIconImageView.layer.cornerRadius = singerIconImageView.width * 0.5 singerIconImageView.layer.masksToBounds = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
cb2fb2e7b670bb4980cb11001ae10d4a
26.265306
110
0.622754
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Lumia/Lumia/Component/QuartzDemo/Views/QuartzBezierView.swift
mit
2
// // QuartzBezierView.swift // QuartzDemo // // Created by 伯驹 黄 on 2017/4/7. // Copyright © 2017年 伯驹 黄. All rights reserved. // class QuartzBezierView: QuartzView { override func draw(in context: CGContext) { // Drawing with a white stroke color context.setStrokeColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) // Draw them with a 2.0 stroke width so they are a bit more visible. context.setLineWidth(2.0) // Draw a bezier curve with end points s,e and control points cp1,cp2 var s = CGPoint(x: 30.0, y: 120.0) var e = CGPoint(x: 300.0, y: 120.0) var cp1 = CGPoint(x: 120.0, y: 30.0) let cp2 = CGPoint(x: 210.0, y: 210.0) context.move(to: s) context.addCurve(to: e, control1: cp1, control2: cp2) context.strokePath() // Show the control points. context.setStrokeColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) context.move(to: s) context.addLine(to: cp1) context.move(to: e) context.addLine(to: cp2) context.strokePath() // Draw a quad curve with end points s,e and control point cp1 context.setStrokeColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) s = CGPoint(x: 30.0, y: 300.0) e = CGPoint(x: 270.0, y: 300.0) cp1 = CGPoint(x: 150.0, y: 180.0) context.move(to: s) context.addQuadCurve(to: e, control: cp1) context.strokePath() // Show the control point. context.setStrokeColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) context.move(to: s) context.addLine(to: cp1) context.strokePath() } }
2354987d4c6eaae580fcb96fdc9aecb8
34.104167
77
0.581602
false
false
false
false
Acidburn0zzz/firefox-ios
refs/heads/main
Client/Frontend/Browser/BrowserViewController/BrowserViewController+FindInPage.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared extension BrowserViewController { func updateFindInPageVisibility(visible: Bool, tab: Tab? = nil) { if visible { if findInPageBar == nil { let findInPageBar = FindInPageBar() self.findInPageBar = findInPageBar findInPageBar.delegate = self alertStackView.addArrangedSubview(findInPageBar) findInPageBar.snp.makeConstraints { make in make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(alertStackView) } updateViewConstraints() // We make the find-in-page bar the first responder below, causing the keyboard delegates // to fire. This, in turn, will animate the Find in Page container since we use the same // delegate to slide the bar up and down with the keyboard. We don't want to animate the // constraints added above, however, so force a layout now to prevent these constraints // from being lumped in with the keyboard animation. findInPageBar.layoutIfNeeded() } self.findInPageBar?.becomeFirstResponder() } else if let findInPageBar = self.findInPageBar { findInPageBar.endEditing(true) let tab = tab ?? tabManager.selectedTab guard let webView = tab?.webView else { return } webView.evaluateJavascriptInDefaultContentWorld("__firefox__.findDone()") findInPageBar.removeFromSuperview() self.findInPageBar = nil updateViewConstraints() } } } extension BrowserViewController: FindInPageBarDelegate, FindInPageHelperDelegate { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) { find(text, function: "find") } func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) { findInPageBar?.endEditing(true) find(text, function: "findNext") } func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) { findInPageBar?.endEditing(true) find(text, function: "findPrevious") } func findInPageDidPressClose(_ findInPage: FindInPageBar) { updateFindInPageVisibility(visible: false) } fileprivate func find(_ text: String, function: String) { guard let webView = tabManager.selectedTab?.webView else { return } let escaped = text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") webView.evaluateJavascriptInDefaultContentWorld("__firefox__.\(function)(\"\(escaped)\")") } func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int) { findInPageBar?.currentResult = currentResult } func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int) { findInPageBar?.totalResults = totalResults } }
20c114bdf602f30bc4c1d5f2733949b0
42.118421
116
0.654562
false
false
false
false
festrs/ListIO
refs/heads/master
ListioTests/APICommunicatorTest.swift
mit
1
// // APICommunicatorTest.swift // Listio // // Created by Felipe Dias Pereira on 2017-04-17. // Copyright © 2017 Felipe Dias Pereira. All rights reserved. // import XCTest @testable import Prod class APICommunicatorTest: XCTestCase { var apiCommunicator:APICommunicator! override func setUp() { super.setUp() apiCommunicator = APICommunicator() } override func tearDown() { super.tearDown() } func testApiCommunicatorGetReceipt() { let linkUrl = "https://www.sefaz.rs.gov.br/NFCE/NFCE-COM.aspx?chNFe=43160593015006003210651190000448421163150095&nVersao=100&tpAmb=1&dhEmi=323031362d30352d32395432303a35353a30392d30333a3030&vNF=59.22&vICMS=0.00&digVal=7973536f417074336a3054747135614a46593548304b6b5a6535413d&cIdToken=000001&cHashQRCode=F975680E1E08C7A23C78B8FE0A68CFAD6F4C3852" let asyncExpectation = expectation(description: "getReceipt") var result:[String: AnyObject]? = nil apiCommunicator.getReceipt(linkUrl: linkUrl) { (error, resultJSON) in guard error == nil else { XCTAssertTrue(false) return } result = resultJSON asyncExpectation.fulfill() } self.waitForExpectations(timeout: 60) { (error) in XCTAssertNil(error) XCTAssertNotNil(result) } } }
f94b18e2cf41b85e8b831454b58e319a
30.533333
352
0.656096
false
true
false
false
CodeEagle/SSPhotoKit
refs/heads/master
Clubber/ImagePickerSheetController/Sheet/Preview/PreviewSupplementaryView.swift
apache-2.0
6
// // PreviewSupplementaryView.swift // ImagePickerSheet // // Created by Laurin Brandner on 06/09/14. // Copyright (c) 2014 Laurin Brandner. All rights reserved. // import UIKit class PreviewSupplementaryView: UICollectionReusableView { private let button: UIButton = { let button = UIButton() button.tintColor = .whiteColor() button.userInteractionEnabled = false button.setImage(PreviewSupplementaryView.checkmarkImage, forState: .Normal) button.setImage(PreviewSupplementaryView.selectedCheckmarkImage, forState: .Selected) return button }() var buttonInset = UIEdgeInsetsZero var selected: Bool = false { didSet { button.selected = selected reloadButtonBackgroundColor() } } class var checkmarkImage: UIImage? { let bundle = NSBundle(forClass: ImagePickerSheetController.self) let image = UIImage(named: "PreviewSupplementaryView-Checkmark", inBundle: bundle, compatibleWithTraitCollection: nil) return image?.imageWithRenderingMode(.AlwaysTemplate) } class var selectedCheckmarkImage: UIImage? { let bundle = NSBundle(forClass: ImagePickerSheetController.self) let image = UIImage(named: "PreviewSupplementaryView-Checkmark-Selected", inBundle: bundle, compatibleWithTraitCollection: nil) return image?.imageWithRenderingMode(.AlwaysTemplate) } // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { addSubview(button) } // MARK: - Other Methods override func prepareForReuse() { super.prepareForReuse() selected = false } override func tintColorDidChange() { super.tintColorDidChange() reloadButtonBackgroundColor() } private func reloadButtonBackgroundColor() { button.backgroundColor = (selected) ? tintColor : nil } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() button.sizeToFit() button.frame.origin = CGPointMake(buttonInset.left, CGRectGetHeight(bounds)-CGRectGetHeight(button.frame)-buttonInset.bottom) button.layer.cornerRadius = CGRectGetHeight(button.frame) / 2.0 } }
04665c5a187c9a723db7a637811eaacd
27.021739
135
0.641195
false
false
false
false
PerrchicK/swift-app
refs/heads/master
SomeApp/SomeApp/Logic/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // SomeApp // // Created by Perry on 1/19/16. // Copyright © 2016 PerrchicK. All rights reserved. // import UIKit import CoreData import FirebaseAuth import FirebaseMessaging import UserNotifications enum ShortcutItemType: String { case OpenImageExamples case OpenMultiTaskingExamples case OpenMapExamples } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate { var signInHolder: Synchronizer.Holder? var tokenHolder: Synchronizer.Holder? var loggedInUser: User? private(set) var fcmToken: String? { didSet { self.tokenHolder?.release() } } var window: UIWindow? static var shared: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let loggedInTokenSynchronizer: Synchronizer = Synchronizer(finalOperationClosure: { [weak self] in guard let user = self?.loggedInUser else { return } FirebaseHelper.createUserNode(user: user) }) tokenHolder = loggedInTokenSynchronizer.createHolder() signInHolder = loggedInTokenSynchronizer.createHolder() // FirebaseHelper.loggedInUser { [weak self] (user) in // self?.loggedInUser = user // self?.signInHolder?.release() // } if let deepLinkDictionary = launchOptions { 📘("launch options dictionary: \(deepLinkDictionary)") if let deepLinkDictionaryFromUrl = deepLinkDictionary[UIApplicationLaunchOptionsKey.url] as? URL { handleDeepLink(deeplinkUrl: deepLinkDictionaryFromUrl) } if let deepLinkDictionaryFromLocalNotification = deepLinkDictionary[UIApplicationLaunchOptionsKey.localNotification] { 📘("Local notification params: \(deepLinkDictionaryFromLocalNotification)") } if let deepLinkDictionaryFromRemoteNotification = deepLinkDictionary[UIApplicationLaunchOptionsKey.remoteNotification] { 📘("Remote notification params: \(deepLinkDictionaryFromRemoteNotification)") } } let rootViewController = SplashScreenViewController.instantiate() self.window?.rootViewController = rootViewController CrashOps.shared().previousCrashReports = { reports in 📘(reports) } // NSSetUncaughtExceptionHandler { (exception) in // UserDefaults.save(value: exception.callStackSymbols, forKey: "last crash").synchronize() // } CrashOps.shared().appExceptionHandler = { exception in UserDefaults.save(value: exception.callStackSymbols, forKey: "last crash").synchronize() } // Another (programmatic) way to determine the window // window = UIWindow(frame: UIScreen.main.bounds) // window?.rootViewController = UINavigationController(rootViewController: _) // window?.makeKeyAndVisible() return true } @discardableResult func handleDeepLink(deeplinkUrl: URL) -> Bool { 📘("Deep Link URL: \(deeplinkUrl)") return true } func setupNotifications() { setupNotifications(application: UIApplication.shared) } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { 📘(shortcutItem.type) ToastMessage.show(messageText: "3D Touched! User chose quick action: \(shortcutItem.localizedTitle)") guard let shortcutItemType = ShortcutItemType.init(rawValue: shortcutItem.type) else { 📘("Error: Failed to instatiate ShortcutItemType enum from: '\(shortcutItem.type)'"); return } switch shortcutItemType { case .OpenImageExamples: MainViewController.shared?.onSelected(menuOption: LeftMenuOptions.iOS.ImagesCoreMotion) case .OpenMultiTaskingExamples: MainViewController.shared?.onSelected(menuOption: LeftMenuOptions.Concurrency.GCD) case .OpenMapExamples: MainViewController.shared?.onSelected(menuOption: LeftMenuOptions.iOS.CommunicationLocation) default: 📘("Error: Unhandled shortcut item type: \(shortcutItemType.rawValue)") } completionHandler(true) } private func setupNotifications(application: UIApplication) { if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } Messaging.messaging().delegate = self application.registerForRemoteNotifications() } 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 application(_ application: UIApplication, didReceive notification: UILocalNotification) { if let title = notification.alertTitle, let message = notification.alertBody, application.applicationState == .active { UIAlertController.makeAlert(title: title, message: message).withAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)).show() } 📘("Received a local notification: \(notification)") } func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { 📘("Registered: \(notificationSettings)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { 📘("Received a remote notification: \(userInfo)") completionHandler(.noData) } func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) { 📘("FCM (refreshed) token string: \(fcmToken)") self.fcmToken = fcmToken } func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { // Sets the notification as "acknowledged" Messaging.messaging().appDidReceiveMessage(remoteMessage.appData) 📘("Received a FCM notification: \(remoteMessage.appData)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { 📘("Received a remote notification: \(userInfo)") } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let apnsTokenString = deviceToken.reduce("", { $0 + String(format: "%02X", $1) }) 📘("APNs token string: \(apnsTokenString.uppercased())") //InstanceID.instanceID().setAPNSToken(deviceToken, type: InstanceIDAPNSTokenType.prod) Messaging.messaging().apnsToken = deviceToken if let fcmToken = Messaging.messaging().fcmToken { 📘("FCM token string: \(fcmToken)") self.fcmToken = fcmToken } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { 📘(error) } 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return handleDeepLink(deeplinkUrl: url) } // MARK: - Core Data stack // Lazy instantiation variable - will be allocated (and initialized) only once lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.perrchick.SomeApp" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .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 = Bundle.main.url(forResource: "SomeApp", withExtension: "momd")! return NSManagedObjectModel(contentsOf: 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.appendingPathComponent("SingleViewCoreData.sqlite") do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch let error { // Report any error we got. let wrappedError = NSError.create(errorDomain: "YOUR_ERROR_DOMAIN", errorCode: 9999, description: "Failed to initialize the application's saved data", failureReason: "There was an error creating or loading the application's saved data.", underlyingError: error) // 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: NSPersistentStoreCoordinator = 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() } } } } @available(iOS 10.0, *) extension AppDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) } // User did tap on notification... hallelujah, thank you iOS10! func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo if let notificationAddress = userInfo["address"] as? String, notificationAddress == "/main/notifications" { //MainViewController?.shared?.navigateToNotifications() } completionHandler() } } extension UIWindow { // Solution from: https://stackoverflow.com/questions/39518529/motionbeganwithevent-not-called-in-appdelegate-in-ios-10 override open var canBecomeFirstResponder: Bool { return true } open override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if motion == .motionShake { // Show local UI live debugging tool FLEXManager.shared().showExplorer() // Delete if it doesn't exist } } }
3bff0d575aa597dbb96e87a0d6cca53d
47.837209
291
0.69898
false
false
false
false
wookay/Look
refs/heads/master
Look/Pods/C4/C4/UI/C4Ellipse.swift
mit
3
// Copyright © 2014 C4 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: The above copyright // notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import Foundation import CoreGraphics /// C4Ellipse is a concrete subclass of C4Shape that has a special initialzer that creates an ellipse whose shape is defined by the object's frame. public class C4Ellipse: C4Shape { /// Creates an ellipse. /// /// ```` /// let r = C4Rect(0,0,100,200) /// let e = C4Ellipse(frame: r) /// ```` /// /// - parameter frame: The frame within which to draw an ellipse that touches each of the four sides of the frame. convenience public init(frame: C4Rect) { self.init() view.frame = CGRect(frame) updatePath() } override func updatePath() { let newPath = C4Path() newPath.addEllipse(bounds) path = newPath } }
12d862519fac1d4b29ef4f047d35792f
40.022222
148
0.705691
false
false
false
false
jquave/Swift-Tutorial-2
refs/heads/master
SwiftData/RootViewController.swift
mit
1
// // RootViewController.swift // SwiftData // // Created by Jameson Quave on 6/13/14. // Copyright (c) 2014 JQ Software LLC. All rights reserved. // import UIKit class RootViewController: UIViewController, UITextFieldDelegate { var textField = UITextField() var textLabel = UILabel() var button = UIButton() var userName = "" var buttonFinalFrame: CGRect? var buttonHiddenFrame: CGRect? init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } override func viewDidLoad() { super.viewDidLoad() createViews() } func createViews() { var margin = CGPointMake(15, 5) var frame = CGRectMake(margin.x, 0, 320-margin.x*2, 44) textLabel.frame = frame textLabel.text = "Hello World!" textLabel.textAlignment = NSTextAlignment.Center textLabel.center = view.center textLabel.alpha = 0 frame = textLabel.frame // Previously we centered the frame // We're going to add 3 44-point height fields, so move it up by that much // This leaves the controls on the top half of the screen frame.origin.y -= (44+margin.y)*3 textLabel.frame = frame view.addSubview(textLabel) frame = textLabel.frame frame.origin.y += 44 + margin.y textField.frame = frame textField.placeholder = "Name" textField.borderStyle = UITextBorderStyle.Line textField.backgroundColor = UIColor(red: 1.0, green: 0.9, blue: 0.8, alpha: 1) view.addSubview(textField) textField.delegate = self frame.origin.y += 44 + margin.y button = UIButton(frame: frame) button.setTitle("Okay", forState: UIControlState.Normal) buttonFinalFrame = frame frame.origin.y += UIScreen.mainScreen().bounds.height button.frame = frame buttonHiddenFrame = button.frame button.addTarget(self, action: "OkayPressed:", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(button) } func OkayPressed(sender: UIButton!) { hideResult() } func hideResult() { UIView.animateWithDuration(0.5, animations: { self.button.frame = self.buttonHiddenFrame! self.textLabel.alpha = 0 }) self.textField.enabled = true self.title = "" self.textField.text = "" navigationController.navigationBarHidden = true } func showResult() { UIView.animateWithDuration(0.5, animations: { self.button.frame = self.buttonFinalFrame! self.textLabel.alpha = 1 }) self.textField.enabled = false self.title = userName navigationController.navigationBarHidden = false } func textFieldShouldReturn(textField: UITextField!) -> Bool { textField.resignFirstResponder() userName = textField.text textLabel.text = "Hello \(userName)!" showResult() return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
62bbeb51739400311102e65ede4007e7
28.293103
103
0.611242
false
false
false
false
chipxsd/stream-based-sync
refs/heads/master
example-01-light-switch/example-01-light-switch/ViewController.swift
cc0-1.0
1
// // ViewController.swift // example-01-light-switch // // Created by Klemen Verdnik on 12/10/15. // Copyright © 2015 Klemen Verdnik. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, LightSwitchClientDelegate { /// Reference to the `backgroundImage` instantiated in the storyboard. @IBOutlet weak var backgroundImage: UIImageView! /// The local Light Switch state. private var _lightSwitchState = false /// Light Switch Client using the web socket. private var lightSwitchClient: LightSwitchClient? /// The `AVAudioPlayer` instance that gets instantated in /// `func playSound(...)` we keep as a local instance. private var audioPlayer: AVAudioPlayer? override func viewDidLoad() { self.lightSwitchClient = LightSwitchClient(hostURL: NSURL(string: "ws://10.0.17.1:8080/")!) self.lightSwitchClient?.delegate = self super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } /** Full screen button didTouchUpInside event handling. - Parameter sender: The sender invoking the function. */ @IBAction func onButtonDidTouchUpInside(sender: AnyObject) { self.toggleAndSendLightSwitchState() } /** Sets the new value for the private ivar `_lightSwitchState` and updates the background image and plays a corresponding sound. */ private var lightSwitchState: Bool { get { return self._lightSwitchState } set { if newValue == self._lightSwitchState { return } self._lightSwitchState = newValue backgroundImage.highlighted = newValue self.playSound(newValue == true ? "lightsOn" : "lightsOff") } } /** Plays a sound from the resources bundle with a given file name. - Parameter soundName: The filename of the sound. */ func playSound(soundName: String) { let soundFileURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!) do { self.audioPlayer = try AVAudioPlayer(contentsOfURL:soundFileURL) self.audioPlayer!.prepareToPlay() self.audioPlayer!.play() } catch let error { print("Failed to play sound named '\(soundName)' with \(error)") } } /** Toggles the private ivar `_lightSwitchState` boolean, updates the backgrund image, plays a sound and transmits the change over network. */ func toggleAndSendLightSwitchState() { self.lightSwitchState = !self.lightSwitchState self.lightSwitchClient?.sendLightSwitchState(self.lightSwitchState) } /** LightSwitchClientDelegate function implementation, which gets executed whenever a new light switch state comes in from the network. The new state gets stored in a local variable `self.lightSwitchState`. - Parameter client: The `LightSwitchClient` executing the function. - Parameter lightsOn: The new Light Switch state coming from network. */ func lightSwitchClientDidReceiveChange(client: LightSwitchClient, lightsOn: Bool) { self.lightSwitchState = lightsOn } }
48e5435cec8553dbf20f8c9a595cd836
31.885714
115
0.662323
false
false
false
false
ArtSabintsev/Siren
refs/heads/master
Sources/Models/Localization.swift
mit
1
// // Localization.swift // Siren // // Created by Arthur Sabintsev on 9/25/18. // Copyright © 2018 Sabintsev iOS Projects. All rights reserved. // import Foundation /// Localization information and strings for Siren. public struct Localization { /// Determines the available languages in which the update message and alert button titles should appear. /// /// By default, the operating system's default lanuage setting is used. However, you can force a specific language /// by setting the forceLanguageLocalization property before calling checkVersion() public enum Language: String { /// Arabic Language Localization case arabic = "ar" /// Armenian Language Localization case armenian = "hy" /// Basque Language Localization case basque = "eu" /// Simplified Chinese Language Localization case chineseSimplified = "zh-Hans" /// Traditional Chinese Localization Localization case chineseTraditional = "zh-Hant" /// Croatian Language Localization case croatian = "hr" /// Czech Language Localization case czech = "cs" /// Danish Language Localization case danish = "da" /// Dutch Language Localization case dutch = "nl" /// English Language Localization case english = "en" /// Estonian Language Localization case estonian = "et" /// Finnish Language Localization case finnish = "fi" /// French Language Localization case french = "fr" /// German Language Localization case german = "de" /// Greek Language Localization case greek = "el" /// Hebrew Language Localization case hebrew = "he" /// Hungarian Language Localization case hungarian = "hu" /// Indonesian Language Localization case indonesian = "id" /// Italian Language Localization case italian = "it" /// Japanese Language Localization case japanese = "ja" /// Korean Language Localization case korean = "ko" /// Latvian Language Localization case latvian = "lv" /// Lithuanian Language Localization case lithuanian = "lt" /// Malay Language Localization case malay = "ms" /// Norwegian Language Localization case norwegian = "nb-NO" /// Persian Language Localization case persian = "fa" /// Persian (Afghanistan) Language Localization case persianAfghanistan = "fa-AF" /// Persian (Iran) Language Localization case persianIran = "fa-IR" /// Polish Language Localization case polish = "pl" /// Brazilian Portuguese Language Localization case portugueseBrazil = "pt" /// Portugal's Portuguese Language Localization case portuguesePortugal = "pt-PT" /// Romanian Language Localization case romanian = "ro" /// Russian Language Localization case russian = "ru" /// Serbian (Cyrillic) Language Localization case serbianCyrillic = "sr-Cyrl" /// Serbian (Latin) Language Localization case serbianLatin = "sr-Latn" /// Slovenian Language Localization case slovenian = "sl" /// Spanish Language Localization case spanish = "es" /// Swedish Language Localization case swedish = "sv" /// Thai Language Localization case thai = "th" /// Turkish Language Localization case turkish = "tr" /// Urdu Language Localization case urdu = "ur" /// Ukranian Language Localization case ukrainian = "uk" /// Vietnamese Language Localization case vietnamese = "vi" } /// The name of the app as defined by the `Info.plist`. private var appName: String = Bundle.bestMatchingAppName() /// Overrides the default localization of a user's device when presenting the update message and button titles in the alert. /// /// See the Siren.Localization.Language enum for more details. private let forceLanguage: Language? /// Initializes /// /// - Parameters: /// - appName: Overrides the default name of the app. This is optional and defaults to the app that is defined in the `Info.plist`. /// - forceLanguage: The language the alert to which the alert should be set. If `nil`, it falls back to the device's preferred locale. init(appName: String?, andForceLanguageLocalization forceLanguage: Language?) { if let appName = appName { self.appName = appName } self.forceLanguage = forceLanguage } /// The localized string for the `UIAlertController`'s message field. . /// /// - Returns: A localized string for the update message. public func alertMessage(forCurrentAppStoreVersion currentAppStoreVersion: String) -> String { let message = Bundle.localizedString(forKey: AlertConstants.alertMessage, andForceLocalization: forceLanguage) return String(format: message, appName, currentAppStoreVersion) } /// The localized string for the `UIAlertController`'s title field. . /// /// - Returns: A localized string for the phrase "Update Available". public func alertTitle() -> String { return Bundle.localizedString(forKey: AlertConstants.alertTitle, andForceLocalization: forceLanguage) } /// The localized string for the "Next time" `UIAlertAction`. /// /// - Returns: A localized string for the phrase "Next time". public func nextTimeButtonTitle() -> String { return Bundle.localizedString(forKey: AlertConstants.nextTimeButtonTitle, andForceLocalization: forceLanguage) } /// The localized string for the "Skip this version" `UIAlertAction`. /// /// - Returns: A localized string for the phrase "Skip this version". public func skipButtonTitle() -> String { return Bundle.localizedString(forKey: AlertConstants.skipButtonTitle, andForceLocalization: forceLanguage) } /// The localized string for the "Update" `UIAlertAction`. /// /// - Returns: A localized string for the phrase "Update". public func updateButtonTitle() -> String { return Bundle.localizedString(forKey: AlertConstants.updateButtonTitle, andForceLocalization: forceLanguage) } }
4a029a13e351f5744495766b60474e29
38.535714
141
0.627974
false
false
false
false
k06a/Linqwift
refs/heads/master
Example/Tests/Tests.swift
mit
1
import UIKit import XCTest import Linqwift class Tests: XCTestCase { func testWhere() { let seq = AnySequence([1,2,3,4,5,6,7,8]) XCTAssertEqual([1,3,5,7], Array<Int>(seq.Where { a,i in i%2==0 })) XCTAssertEqual([2,4,6,8], Array<Int>(seq.Where { a,i in i%2==1 })) XCTAssertEqual([2,4,6,8], Array<Int>(seq.Where { a,i in a%2==0 })) XCTAssertEqual([1,3,5,7], Array<Int>(seq.Where { a,i in a%2==1 })) XCTAssertEqual([3,4,5,6], Array<Int>(seq.Where { a,i in a>2&&a<7 })) } func testSelect() { let seq = AnySequence([1,2,3,4]) XCTAssertEqual([2,4,6,8], Array<Int>(seq.Select { a,i in a*2 })) XCTAssertEqual([6,7,8,9], Array<Int>(seq.Select { a,i in a+5 })) XCTAssertEqual([1,3,5,7], Array<Int>(seq.Select { a,i in a+i })) let dict: [Int:String] = [ 1:"One", 2:"Two", 3:"Three", 4:"Four" ] let ans = ["One","Two","Three","Four"] XCTAssertEqual(ans, Array<String>(seq.Select { a,i in dict[a]! })) } }
b1387903dbc8085db916568a14c1ddc6
32.090909
76
0.513736
false
true
false
false
3DprintFIT/octoprint-ios-client
refs/heads/dev
OctoPhone/Model/Printer.swift
mit
1
// // Printer.swift // OctoPhone // // Created by Josef Dolezal on 29/11/2016. // Copyright © 2016 Josef Dolezal. All rights reserved. // import Foundation import RealmSwift /// Real printer device final class Printer: Object { // MARK: - Stored properties /// Stored representation of printer URL private dynamic var _url = "" /// Stored representation of stream URL private dynamic var _streamUrl: String? /// User's access token for authorization to printer dynamic var accessToken = "" /// User-frindly printer name dynamic var name = "" // MARK: - Computed properties /// Getter for printer ID backed by it's URL // swiftlint:disable identifier_name var ID: String { return _url } // swiftlint:enable identifier_name /// Printer URL based on stored property var url: URL { get { return URL(string: _url)! } set { _url = newValue.absoluteString } } /// Print stream URL var streamUrl: URL? { get { guard let url = _streamUrl else { return nil } return URL(string: url) } set { _streamUrl = newValue?.absoluteString } } // MARK: - Public API /// Creates new Printer instance /// /// - Parameters: /// - url: String representation of printer URL /// - accessToken: User's access token convenience init(url: URL, accessToken: String, name: String, streamUrl: URL?) { self.init() self.url = url self.accessToken = accessToken self.name = name self.streamUrl = streamUrl } // MARK: - Realm API override static func primaryKey() -> String? { return "_url" } override static func ignoredProperties() -> [String] { return ["url", "streamUrl"] } }
a17bd1171cb5f8cb8f0fce4a9c8c10a6
21.662651
84
0.584795
false
false
false
false
victorlin/ReactiveCocoa
refs/heads/master
ReactiveCocoa/Swift/Observer.swift
mit
1
// // Observer.swift // ReactiveCocoa // // Created by Andy Matuschak on 10/2/15. // Copyright © 2015 GitHub. All rights reserved. // /// A protocol for type-constrained extensions of `Observer`. public protocol ObserverProtocol { associatedtype Value associatedtype Error: Swift.Error /// Puts a `next` event into `self`. func sendNext(_ value: Value) /// Puts a failed event into `self`. func sendFailed(_ error: Error) /// Puts a `completed` event into `self`. func sendCompleted() /// Puts an `interrupted` event into `self`. func sendInterrupted() } /// An Observer is a simple wrapper around a function which can receive Events /// (typically from a Signal). public final class Observer<Value, Error: Swift.Error> { public typealias Action = @escaping (Event<Value, Error>) -> Void /// An action that will be performed upon arrival of the event. public let action: Action /// An initializer that accepts a closure accepting an event for the /// observer. /// /// - parameters: /// - action: A closure to lift over received event. public init(_ action: Action) { self.action = action } /// An initializer that accepts closures for different event types. /// /// - parameters: /// - next: Optional closure executed when a `next` event is observed. /// - failed: Optional closure that accepts an `Error` parameter when a /// failed event is observed. /// - completed: Optional closure executed when a `completed` event is /// observed. /// - interruped: Optional closure executed when an `interrupted` event is /// observed. public convenience init( next: ((Value) -> Void)? = nil, failed: ((Error) -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil ) { self.init { event in switch event { case let .next(value): next?(value) case let .failed(error): failed?(error) case .completed: completed?() case .interrupted: interrupted?() } } } } extension Observer: ObserverProtocol { /// Puts a `next` event into `self`. /// /// - parameters: /// - value: A value sent with the `next` event. public func sendNext(_ value: Value) { action(.next(value)) } /// Puts a failed event into `self`. /// /// - parameters: /// - error: An error object sent with failed event. public func sendFailed(_ error: Error) { action(.failed(error)) } /// Puts a `completed` event into `self`. public func sendCompleted() { action(.completed) } /// Puts an `interrupted` event into `self`. public func sendInterrupted() { action(.interrupted) } }
1040afb7e4ba31fd5f45ae80f01d510e
24.375
78
0.650625
false
false
false
false
Rapid-SDK/ios
refs/heads/master
Source/RapidQuery.swift
mit
1
// // RapidQuery.swift // Rapid // // Created by Jan Schwarz on 17/03/2017. // Copyright © 2017 Rapid. All rights reserved. // import Foundation import CoreGraphics public protocol RapidQuery {} extension RapidQuery { /// Special key which stands for a document ID property public static var docIdKey: String { return "$id" } /// Special key which stands for a document creation timestamp property public static var docCreatedAtKey: String { return "$created" } /// Special key which stands for a document modification timestamp property public static var docModifiedAtKey: String { return "$modified" } } /// Protocol describing data types that can be used in filter for comparison purposes /// /// Data types that conform to `RapidComparable` defaultly are guaranteed to be /// compatible with Rapid database /// /// When developer explicitly adds a conformance of another data type to `RapidComparable` /// we cannot guarantee any behavior public protocol RapidComparable {} extension String: RapidComparable {} extension Int: RapidComparable {} extension Double: RapidComparable {} extension Float: RapidComparable {} extension CGFloat: RapidComparable {} extension Bool: RapidComparable {} /// Structure that describes subscription filter public struct RapidFilter: RapidQuery { /// Type of filter /// /// - compound: Filter that combines one or more `Expression`s with a logical operator /// - simple: Filter that describes simple relation between an attribute and a specified value public indirect enum Expression { case compound(operator: Operator, operands: [Expression]) case simple(keyPath: String, relation: Relation, value: Any?) } /// Type of logical operator /// /// - and: Logical AND /// - or: Logical OR /// - not: Logical NOT public enum Operator { case and case or case not var hash: String { switch self { case .and: return "and" case .or: return "or" case .not: return "not" } } } /// Type of relation to a specified value /// /// - equal: Property value is equal to a reference value /// - greaterThanOrEqual: Property value is greater than or equal to a reference value /// - lessThanOrEqual: Property value is less than or equal to a reference value /// - greaterThan: Parameter value is greater than a reference value /// - lessThan: Property value is less than a reference value /// - contains: Property value contains a reference value as a substring /// - startsWith: Property value starts with a reference value /// - endsWith: Property value ends with a reference value /// - arrayContains: Property array contains a reference value public enum Relation { case equal case greaterThanOrEqual case lessThanOrEqual case greaterThan case lessThan case contains case startsWith case endsWith case arrayContains var hash: String { switch self { case .equal: return "e" case .greaterThanOrEqual: return "gte" case .lessThanOrEqual: return "lte" case .greaterThan: return "gt" case .lessThan: return "lt" case .contains: return "cnt" case .startsWith: return "pref" case .endsWith: return "suf" case .arrayContains: return "arr-cnt" } } } /// Array of filters public let expression: Expression /// Filter hash public let filterHash: String /// Compound filter initializer /// /// - Parameters: /// - compoundOperator: Logical operator /// - operands: Array of filters that are combined together with the `compoundOperator` init(compoundOperator: Operator, operands: [RapidFilter]) { self.expression = Expression.compound(operator: compoundOperator, operands: operands.map({ $0.expression })) let hash = operands.sorted(by: { $0.filterHash > $1.filterHash }).flatMap({ $0.filterHash }).joined(separator: "|") self.filterHash = "\(compoundOperator.hash)(\(hash))" } /// Simple filter initializer /// /// - Parameters: /// - keyPath: Name of a document parameter /// - relation: Ralation to the `value` /// - value: Reference value init(keyPath: String, relation: Relation, value: RapidComparable) { self.expression = Expression.simple(keyPath: keyPath, relation: relation, value: value) self.filterHash = "\(keyPath)-\(relation.hash)-\(value)" } /// Simple filter initializer /// /// - Parameters: /// - keyPath: Name of a document parameter /// - relation: Ralation to the `value` init(keyPath: String, relation: Relation) { self.expression = Expression.simple(keyPath: keyPath, relation: relation, value: nil) self.filterHash = "\(keyPath)-\(relation.hash)-null" } // MARK: Compound filters /// Negate filter /// /// - Parameter filter: Filter to be negated /// - Returns: Negated filter public static func not(_ filter: RapidFilter) -> RapidFilter { return RapidFilter(compoundOperator: .not, operands: [filter]) } /// Combine filters with logical AND /// /// - Parameter operands: Filters to be combined /// - Returns: Compound filter public static func and(_ operands: [RapidFilter]) -> RapidFilter { return RapidFilter(compoundOperator: .and, operands: operands) } /// Combine filters with logical OR /// /// - Parameter operands: Filters to be combined /// - Returns: Compound filter public static func or(_ operands: [RapidFilter]) -> RapidFilter { return RapidFilter(compoundOperator: .or, operands: operands) } // MARK: Simple filters /// Create equality filter /// /// - Parameters: /// - keyPath: Document property key path /// - value: Property value /// - Returns: Filter for key path equal to value public static func equal(keyPath: String, value: RapidComparable) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .equal, value: value) } /// Create equal to null filter /// /// - Parameter keyPath: Document property key path /// - Returns: Filter for key path equal to null public static func isNull(keyPath: String) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .equal) } /// Create greater than filter /// /// - Parameters: /// - keyPath: Document property key path /// - value: Property value /// - Returns: Filter for key path greater than value public static func greaterThan(keyPath: String, value: RapidComparable) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .greaterThan, value: value) } /// Create greater than or equal filter /// /// - Parameters: /// - keyPath: Document property key path /// - value: Property value /// - Returns: Filter for key path greater than or equal to value public static func greaterThanOrEqual(keyPath: String, value: RapidComparable) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .greaterThanOrEqual, value: value) } /// Create less than filter /// /// - Parameters: /// - keyPath: Document property key path /// - value: Property value /// - Returns: Filter for key path less than value public static func lessThan(keyPath: String, value: RapidComparable) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .lessThan, value: value) } /// Create less than or equal filter /// /// - Parameters: /// - keyPath: Document property key path /// - value: Property value /// - Returns: Filter for key path less than or equal to value public static func lessThanOrEqual(keyPath: String, value: RapidComparable) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .lessThanOrEqual, value: value) } /// Create string contains filter /// /// - Parameters: /// - keyPath: Document property key path /// - subString: Property value substring /// - Returns: Filter for string at key path contains a substring public static func contains(keyPath: String, subString: String) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .contains, value: subString) } /// Create string starts with filter /// /// - Parameters: /// - keyPath: Document property key path /// - prefix: Property value prefix /// - Returns: Filter for string at key path starts with a prefix public static func startsWith(keyPath: String, prefix: String) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .startsWith, value: prefix) } /// Create string ends with filter /// /// - Parameters: /// - keyPath: Document property key path /// - suffix: Property value suffix /// - Returns: Filter for string at key path ends with a suffix public static func endsWith(keyPath: String, suffix: String) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .endsWith, value: suffix) } /// Create array contains filter /// /// - Parameters: /// - keyPath: Document property key path /// - value: Value that should be present in a property array /// - Returns: Filter for array at key path that contains a value public static func arrayContains(keyPath: String, value: RapidComparable) -> RapidFilter { return RapidFilter(keyPath: keyPath, relation: .arrayContains, value: value) } } /// Structure that describes subscription ordering public struct RapidOrdering: RapidQuery { /// Type of ordering /// /// - ascending: Ascending ordering /// - descending: Descending ordering public enum Ordering { case ascending case descending var hash: String { switch self { case .ascending: return "a" case .descending: return "d" } } } /// Name of a document property public let keyPath: String /// Ordering type public let ordering: Ordering /// Initialize an ordering /// /// - Parameters: /// - keyPath: Name of a document property /// - ordering: Ordering type public init(keyPath: String, ordering: Ordering) { self.keyPath = keyPath self.ordering = ordering } var orderingHash: String { return "o-\(keyPath)-\(ordering.hash)" } } /// Structure that describes subscription paging values public struct RapidPaging { /// Maximum value of `take` public static let takeLimit = 500 // Number of documents to be skipped //public let skip: Int? /// Maximum number of documents to be returned /// /// Max. value is 500 public let take: Int var pagingHash: String { let hash = "t\(take)" //TODO: Implement skip /*if let skip = skip { hash += "s\(skip)" }*/ return hash } }
d380439bdbf506b317cded336bba1d27
31.183288
123
0.605444
false
false
false
false
ifeherva/HSTracker
refs/heads/master
HSTracker/Logging/LogLineNamespace.swift
mit
2
// // LogLineNamespace.swift // HSTracker // // Created by Benjamin Michotte on 11/08/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation enum LogLineNamespace: String { case achievements = "Achievements", adTracking = "AdTracking", all = "All", arena = "Arena", asset = "Asset", biReport = "BIReport", battleNet = "BattleNet", becca = "Becca", ben = "Ben", bob = "Bob", brian = "Brian", bugReporter = "BugReporter", cameron = "Cameron", cardbackMgr = "CardbackMgr", changedCards = "ChangedCards", clientRequestManager = "ClientRequestManager", configFile = "ConfigFile", crafting = "Crafting", dbfXml = "DbfXml", deckHelper = "DeckHelper", deckRuleset = "DeckRuleset", deckTray = "DeckTray", derek = "Derek", deviceEmulation = "DeviceEmulation", downloader = "Downloader", endOfGame = "EndOfGame", eventTiming = "EventTiming", faceDownCard = "FaceDownCard", fullScreenFX = "FullScreenFX", gameMgr = "GameMgr", graphics = "Graphics", hand = "Hand", healthyGaming = "HealthyGaming", henry = "Henry", innKeepersSpecial = "InnKeepersSpecial", jMac = "JMac", jay = "Jay", josh = "Josh", kyle = "Kyle", loadingScreen = "LoadingScreen", mike = "Mike", mikeH = "MikeH", missingAssets = "MissingAssets", net = "Net", packet = "Packet", party = "Party", playErrors = "PlayErrors", power = "Power", raf = "RAF", rachelle = "Rachelle", reset = "Reset", robin = "Robin", ryan = "Ryan", sound = "Sound", spectator = "Spectator", store = "Store", updateManager = "UpdateManager", userAttention = "UserAttention", yim = "Yim", zone = "Zone" static func usedValues() -> [LogLineNamespace] { return [.power, .rachelle, .arena, .loadingScreen] } static func allValues() -> [LogLineNamespace] { return [.achievements, .adTracking, .all, .arena, .asset, .biReport, .battleNet, .becca, .ben, .bob, .brian, .bugReporter, .cameron, .cardbackMgr, .changedCards, .clientRequestManager, .configFile, .crafting, .dbfXml, .deckHelper, .deckRuleset, .deckTray, .derek, .deviceEmulation, .downloader, .endOfGame, .eventTiming, .faceDownCard, .fullScreenFX, .gameMgr, .graphics, .hand, .healthyGaming, .henry, .innKeepersSpecial, .jMac, .jay, .josh, .kyle, .loadingScreen, .mike, .mikeH, .missingAssets, .net, .packet, .party, .playErrors, .power, .raf, .rachelle, .reset, .robin, .ryan, .sound, .spectator, .store, .updateManager, .userAttention, .yim, .zone] } }
6efadac423df40f49fbc975003042523
30.625
100
0.598994
false
false
false
false
hucool/XMImagePicker
refs/heads/master
Pod/Classes/Album.swift
mit
1
// // AlbumInfo.swift // XMImagePicker // // Created by tiger on 2017/2/8. // Copyright © 2017年 xinma. All rights reserved. // import UIKit import Photos import Foundation class Album { var count: Int var title: String var thumb: UIImage? var collection: PHAssetCollection init(collection: PHAssetCollection) { func transformAblumTitle(_ title: String) -> String { switch title { case "Slo-mo": return "慢动作" case "Recently Added": return "最近添加" case "Favorites": return "最爱" case "Recently Deleted": return "最近删除" case "Videos": return "视频" case "All Photos": return "所有照片" case "Selfies": return "自拍" case "Screenshots": return "屏幕快照" case "Camera Roll": return "相机胶卷" case "Time-lapse": return "延时摄影" case "Panoramas": return "全景照片" case "Bursts": return "连拍" case "Hidden": return "隐藏照片" default: return title } } let assets = PHAsset.fetchAssets(in: collection, options: nil) count = assets.count self.collection = collection title = transformAblumTitle(collection.localizedTitle!) guard count > 0 else { return } let screenScale: CGFloat = UIScreen.main.scale let imageSize = CGSize(width: 100 * screenScale, height: 100 * screenScale) let options = PHImageRequestOptions() options.resizeMode = .fast options.isSynchronous = true PHCachingImageManager.default().requestImage(for: assets.lastObject!, targetSize: imageSize, contentMode: .aspectFill, options: options) { (image, info) in // 处理获得的图片 self.thumb = image } } }
c9e2243f1ea598803c75b4a929c195e0
25.858974
163
0.508831
false
false
false
false
Estimote/iOS-SDK
refs/heads/master
Examples/swift/Configuration/Configuration/TagsViewController.swift
mit
1
// // Please report any problems with this app template to [email protected] // import UIKit /** Utility view controller to allow the user to pick tags to associate with the beacon currently being configured. **WHAT TO CUSTOMIZE HERE?** The tags are taken from the `tagsAndMajorsMapping` constant defined in "BeaconConfig.swift". You will likely want to adjust them, or maybe populate the list dynamically from your own backend. You might also want to add custom logic to allow more than one tag picked for a beacon. */ class TagsViewController: UITableViewController { @objc var selectedTag: String? @objc let sortedTags = Array(tagsAndMajorsMapping.keys).sorted() override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sortedTags.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Tag", for: indexPath) let tag = sortedTags[indexPath.row] cell.textLabel!.text = tag if tag == selectedTag { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let tag = sortedTags[indexPath.row] selectedTag = tag tableView.reloadData() } }
e8dac78645082b8e545b7a9a8b8851a1
35.85
308
0.702171
false
false
false
false
Jranco/SwiftyGraph
refs/heads/master
SwiftyGraph/SwiftyGraph/Graph/Protocol/GraphProtocol.swift
mit
1
// // Graph.swift // Pods // // Created by Thomas Segkoulis on 18/12/16. // // import Foundation protocol GraphProtocol: class { associatedtype VerticeType: Hashable, Comparable // MARK: - Properties - var adjacency: [VerticeType: [VerticeType:EdgeProtocol]] {set get} var verticeDictionary: [VerticeType: VerticeType] {set get} var verticeArray: [VerticeType] {get} var direction: DirectionType {set get} // MARK: - Init method - init(direction: DirectionType) // MARK: - Functions with default implementation - func addEdge(verticeA: VerticeType, verticeB: VerticeType, direction: DirectionType, weight: Weight<Any>) func addEdge(verticeA: VerticeType, verticeB: VerticeType, direction: DirectionType) func addEdge(verticeA: VerticeType, verticeB: VerticeType, edge: Edge) func addVertice(vertice: VerticeType) func addVertices(vertices: [VerticeType]) // MARK: - Functions to be implemented by class conforming to this protocol - func existsEdge(from verticeA: VerticeType,to verticeB: VerticeType) -> Bool func existsVertice(vertice: VerticeType) -> Bool // MARK: - Adjacency - // MARK: - Path - } // MARK: - GraphProtocol Extension - extension GraphProtocol { // MARK: - Add Edges & Vertices - func addEdge(verticeA: VerticeType, verticeB: VerticeType, direction: DirectionType, weight: Weight<Any>) { let edge = Edge.weighted(direction, weight) addEdge(verticeA: verticeA, verticeB: verticeB, edge: edge) if(direction == .undirected && adjacency[verticeB]?[verticeA] == nil) { addEdge(verticeA: verticeB, verticeB: verticeA, direction: direction, weight: weight) } } func addEdge(verticeA: VerticeType, verticeB: VerticeType, direction: DirectionType) { let edge = Edge.unweighted(direction) addEdge(verticeA: verticeA, verticeB: verticeB, edge: edge) if(direction == .undirected && adjacency[verticeB]?[verticeA] == nil) { addEdge(verticeA: verticeB, verticeB: verticeA, direction: direction) } } func addEdge(verticeA: VerticeType, verticeB: VerticeType, edge: Edge) { // Add edge var nearbyDictionary: [VerticeType: EdgeProtocol] = [:] if(adjacency[verticeA] != nil) { nearbyDictionary = adjacency[verticeA]! } nearbyDictionary[verticeB] = edge adjacency[verticeA] = nearbyDictionary } }
c2a61f95c82984c666928c57feb58fd4
28.438202
109
0.63855
false
false
false
false
gb-6k-house/YsSwift
refs/heads/master
Sources/Peacock/Extenstion/NSAttributedString+Extension.swift
mit
1
/****************************************************************************** ** auth: liukai ** date: 2017/7 ** ver : 1.0 ** desc: 说明 ** Copyright © 2017年 尧尚信息科技(wwww.yourshares.cn). All rights reserved ******************************************************************************/ import Foundation import UIKit import YsSwift extension YSSwift where Base: NSMutableAttributedString { func colorOfString(_ string: String, color: UIColor) { if let range = self.base.string.range(of: string) { let start = self.base.string.characters.distance(from: self.base.string.startIndex, to: range.lowerBound) // let length = range.upperBound - range.lowerBound // string.characters.startIndex.distanceTo(from: range.lowerBound, to: range.upperBound) let end = self.base.string.characters.distance(from: self.base.string.startIndex, to: range.upperBound) let length = end - start // let length = <#T##String.CharacterView corresponding to your index##String.CharacterView#>.distance(from: range.lowerBound, to: range.upperBound) let attrs = [NSAttributedStringKey.foregroundColor: color] self.base.setAttributes(attrs, range: NSRange(location: start, length: length)) } } }
fa1e5de5c2dadc3acd50405d2399d332
44.964286
160
0.602176
false
false
false
false
15221758864/TestKitchen_1606
refs/heads/master
GiftSay/Pods/XWSwiftRefresh/XWSwiftRefresh/Header/XWRefreshHeader.swift
gpl-3.0
7
// // XWRefreshHeader.swift // XWRefresh // // Created by Xiong Wei on 15/9/8. // Copyright © 2015年 Xiong Wei. All rights reserved. // 简书:猫爪 import UIKit /** 抽象类不直接使用 用于重写*/ public class XWRefreshHeader: XWRefreshComponent { //MARK: 公开的 /** 利用这个key来保存上次的刷新时间(不同界面的刷新控件应该用不同的dateKey,以区分不同界面的刷新时间) */ var lastUpdatedateKey:String = "" /** 忽略多少scrollView的contentInset的top */ public var ignoredScrollViewContentInsetTop:CGFloat = 0.0 /** 上一次下拉刷新成功的时间 */ public var lastUpdatedTime:NSDate{ get{ if let realTmp = NSUserDefaults.standardUserDefaults().objectForKey(self.lastUpdatedateKey){ return realTmp as! NSDate }else{ return NSDate() } } } //MARK: 覆盖父类方法 override func prepare() { super.prepare() // 设置key self.lastUpdatedateKey = XWRefreshHeaderLastUpdatedTimeKey // 设置高度 self.xw_height = XWRefreshHeaderHeight } override func placeSubvies() { super.placeSubvies() // 设置y值(当自己的高度发生改变了,肯定要重新调整Y值,所以放到placeSubviews方法中设置y值) self.xw_y = -self.xw_height - self.ignoredScrollViewContentInsetTop } override func scrollViewContentOffsetDidChange(change: Dictionary<String,AnyObject>?) { super.scrollViewContentOffsetDidChange(change) // 在刷新的refreshing状态 if self.state == XWRefreshState.Refreshing { return } // 跳转到下一个控制器时,contentInset可能会变 self.scrollViewOriginalInset = self.scrollView.contentInset // 当前的contentOffset let offsetY = self.scrollView.xw_offSetY // 头部控件刚好出现的offsetY let happenOffsetY = -self.scrollViewOriginalInset.top // 如果是向上滚动到看不见头部控件,直接返回 if offsetY > happenOffsetY { return } // 普通 和 即将刷新 的临界点 let normal2pullingOffsetY = happenOffsetY - self.xw_height let pullingPercent = (happenOffsetY - offsetY) / self.xw_height // 如果正在 拖拽 if self.scrollView.dragging { self.pullingPercent = pullingPercent if self.state == XWRefreshState.Idle && offsetY < normal2pullingOffsetY { // 转为即将刷新状态 self.state = XWRefreshState.Pulling } else if self.state == XWRefreshState.Pulling && offsetY >= normal2pullingOffsetY { // 转为普通状态 self.state = XWRefreshState.Idle } } else if self.state == XWRefreshState.Pulling { //开始刷新 self.beginRefreshing() } else if self.pullingPercent < 1 { self.pullingPercent = pullingPercent } } //MARK: 改变状态后 /** 刷新控件的状态 */ override var state:XWRefreshState{ didSet{ //状态和以前的一样就不用改变 if oldValue == state { return } //根据状态来做一些事情 if state == XWRefreshState.Idle { if oldValue != XWRefreshState.Refreshing { return } //保存刷新的时间 NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: self.lastUpdatedateKey as String) NSUserDefaults.standardUserDefaults().synchronize() // 恢复inset和offset UIView.animateWithDuration(XWRefreshSlowAnimationDuration, animations: { [unowned self] () -> Void in self.scrollView.xw_insertTop -= self.xw_height // 自动调整透明度 if self.automaticallyChangeAlpha {self.alpha = 0.0} }, completion: { [unowned self] (flag) -> Void in self.pullingPercent = 0.0 }) }else if state == XWRefreshState.Refreshing { UIView.animateWithDuration(XWRefreshSlowAnimationDuration, animations: {[unowned self] () -> Void in let top = self.scrollViewOriginalInset.top + self.xw_height // 增加滚动区域 self.scrollView.xw_insertTop = top // 设置滚动位置 self.scrollView.xw_offSetY = -top }, completion: { (flag) -> Void in self.executeRefreshingCallback() }) } } } /** 结束刷新 */ override public func endRefreshing() { if self.scrollView.isKindOfClass(UICollectionView){ xwDelay(0.1){ super.endRefreshing() } }else{ super.endRefreshing() } } override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bb3caa12fc83ce8988cdec4cff876c7b
27.260638
117
0.511575
false
false
false
false
JohnCoates/Aerial
refs/heads/master
Aerial/Source/Models/PlaybackSpeed.swift
mit
1
// // PlaybackSpeed.swift // Aerial // // Created by Guillaume Louel on 08/07/2021. // Copyright © 2021 Guillaume Louel. All rights reserved. // import Foundation struct PlaybackSpeed { static func forVideo(_ id: String) -> Float { if let value = PrefsVideos.playbackSpeed[id] { return value } else { return 1 } } static func update(video: String, value: Float) { // Just in case... if value == 0 { PrefsVideos.playbackSpeed[video] = 0.01 } else { PrefsVideos.playbackSpeed[video] = value } } static func reset(video: String) { PrefsVideos.playbackSpeed[video] = 1 } }
fb7daab601a22b2a118ad4a8d38246c7
21.28125
58
0.569425
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Reverb/Flat Frequency Response Reverb/AKFlatFrequencyResponseReverb.swift
mit
1
// // AKFlatFrequencyResponseReverb.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This filter reiterates the input with an echo density determined by loop /// time. The attenuation rate is independent and is determined by the /// reverberation time (defined as the time in seconds for a signal to decay to /// 1/1000, or 60dB down from its original amplitude). Output will begin to /// appear immediately. /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The duration in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude. /// - loopDuration: The loop duration of the filter, in seconds. This can also be thought of as the delay time or “echo density” of the reverberation. /// public class AKFlatFrequencyResponseReverb: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKFlatFrequencyResponseReverbAudioUnit? internal var token: AUParameterObserverToken? private var reverbDurationParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// The duration in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude. public var reverbDuration: Double = 0.5 { willSet { if reverbDuration != newValue { if internalAU!.isSetUp() { reverbDurationParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.reverbDuration = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this reverb node /// /// - Parameters: /// - input: Input node to process /// - reverbDuration: The duration in seconds for a signal to decay to 1/1000, or 60dB down from its original amplitude. /// - loopDuration: The loop duration of the filter, in seconds. This can also be thought of as the delay time or “echo density” of the reverberation. /// public init( _ input: AKNode, reverbDuration: Double = 0.5, loopDuration: Double = 0.1) { self.reverbDuration = reverbDuration var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x616c7073 /*'alps'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKFlatFrequencyResponseReverbAudioUnit.self, asComponentDescription: description, name: "Local AKFlatFrequencyResponseReverb", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKFlatFrequencyResponseReverbAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) self.internalAU!.setLoopDuration(Float(loopDuration)) } guard let tree = internalAU?.parameterTree else { return } reverbDurationParameter = tree.valueForKey("reverbDuration") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.reverbDurationParameter!.address { self.reverbDuration = Double(value) } } } internalAU?.reverbDuration = Float(reverbDuration) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
5760e67032bf8a33c4b0b7e690a5b980
34.838462
156
0.646276
false
false
false
false
calkinssean/TIY-Assignments
refs/heads/master
Day 19/WeatherOrNot/WeatherOrNot/City.swift
cc0-1.0
1
// // City.swift // WeatherOrNot // // Created by Sean Calkins on 2/25/16. // Copyright © 2016 Dape App Productions LLC. All rights reserved. // import UIKit class City { var formatted_address: String = "" var longitude: Double = 0.0 var latitude: Double = 0.0 var weatherArray = [Weather]() var temperature: Double = 0.0 var summary: String = "" var icon: String = "" init() { } init(dict: JSONDictionary) { if let temperature = dict["temperature"] as? Double { self.temperature = temperature } else { print("couldn't parse temperature") } if let summary = dict["summary"] as? String { self.summary = summary } else { print("couldn't parse summary") } if let icon = dict["icon"] as? String { self.icon = icon } else { print("couldn't parse icon") } } }
a72a0a5a5435a0e2296e12e1fc3f0750
22.585366
67
0.536232
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGraphics/Font/Decoder/SFNTFontFace/SFNTPOST.swift
mit
1
// // SFNTPOST.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // struct SFNTPOST: ByteDecodable { var format: Fixed16Number<BEInt32> var italicAngle: Fixed16Number<BEInt32> var underlinePosition: BEInt16 var underlineThickness: BEInt16 var isFixedPitch: BEUInt32 var minMemType42: BEUInt32 var maxMemType42: BEUInt32 var minMemType1: BEUInt32 var maxMemType1: BEUInt32 init(from data: inout Data) throws { self.format = try data.decode(Fixed16Number<BEInt32>.self) self.italicAngle = try data.decode(Fixed16Number<BEInt32>.self) self.underlinePosition = try data.decode(BEInt16.self) self.underlineThickness = try data.decode(BEInt16.self) self.isFixedPitch = try data.decode(BEUInt32.self) self.minMemType42 = try data.decode(BEUInt32.self) self.maxMemType42 = try data.decode(BEUInt32.self) self.minMemType1 = try data.decode(BEUInt32.self) self.maxMemType1 = try data.decode(BEUInt32.self) } }
bcade4d853ec2b1a139f2739795d0fac
43.102041
81
0.728829
false
false
false
false
marinehero/LeetCode-Solutions-in-Swift
refs/heads/master
Solutions/Solutions/Hard/Hard_010_Regular_Expression_Matching.swift
mit
3
/* https://oj.leetcode.com/problems/regular-expression-matching/ #10 Regular Expression Matching Level: hard Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true Inspired by @xiaohui7 at https://leetcode.com/discuss/18970/concise-recursive-and-dp-solutions-with-full-explanation-in */ // Helper private extension String { subscript (index: Int) -> Character { return self[self.startIndex.advancedBy(index)] } subscript (range: Range<Int>) -> String { return self[self.startIndex.advancedBy(range.startIndex)..<self.startIndex.advancedBy(range.endIndex)] } } class Hard_010_Regular_Expression_Matching { // recursion class func isMatch_recursion(s s: String, p: String) -> Bool { if p.characters.count == 0 { return s.characters.count == 0 } if p.characters.count > 1 && p[1] == "*" { return isMatch_recursion(s: s, p: p[2..<p.characters.count]) || s.characters.count != 0 && (s[0] == p[0] || p[0] == ".") && isMatch_recursion(s: s[1..<s.characters.count], p: p) } else { return s.characters.count != 0 && (s[0] == p[0] || p[0] == ".") && isMatch_recursion(s: s[1..<s.characters.count], p: p[1..<p.characters.count]) } } // dp class func isMatch(s s: String, p: String) -> Bool { let m: Int = s.characters.count let n: Int = p.characters.count var f: [[Bool]] = Array<Array<Bool>>(count: m + 1, repeatedValue: Array<Bool>(count: n + 1, repeatedValue: false)) f[0][0] = true for var i = 1; i <= m; i++ { f[i][0] = false } for var i = 1; i <= n; i++ { f[0][i] = i > 1 && "*" == p[i-1] && f[0][i-2] } for var i = 1; i <= m; i++ { for var j = 1; j <= n; j++ { if p[j-1] != "*" { f[i][j] = f[i - 1][j - 1] && (s[i - 1] == p[j - 1] || "." == p[j - 1]) } else { f[i][j] = f[i][j - 2] || (s[i - 1] == p[j - 2] || "." == p[j - 2]) && f[i - 1][j] } } } return f[m][n] } }
cc6fcf5f9607d1b069fbfa1511721a67
32.519481
189
0.527907
false
false
false
false
bgould/thrift
refs/heads/master
lib/swift/Sources/TSocketTransport.swift
apache-2.0
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc import Dispatch #endif import Foundation import CoreFoundation #if !swift(>=4.2) // Swift 3/4 compatibility fileprivate extension RunLoopMode { static let `default` = defaultRunLoopMode } #endif private struct Sys { #if os(Linux) static let read = Glibc.read static let write = Glibc.write static let close = Glibc.close #else static let read = Darwin.read static let write = Darwin.write static let close = Darwin.close #endif } extension in_addr { public init?(hostent: hostent?) { guard let host = hostent, host.h_addr_list != nil, host.h_addr_list.pointee != nil else { return nil } self.init() memcpy(&self, host.h_addr_list.pointee!, Int(host.h_length)) } } #if os(Linux) /// TCFSocketTransport currently unavailable /// remove comments and build to see why/fix /// currently CF[Read|Write]Stream's can't cast to [Input|Output]Streams which breaks thigns #else extension Stream.PropertyKey { static let SSLPeerTrust = Stream.PropertyKey(kCFStreamPropertySSLPeerTrust as String) } /// TCFSocketTransport, uses CFSockets and (NS)Stream's public class TCFSocketTransport: TStreamTransport { public init?(hostname: String, port: Int, secure: Bool = false) { var inputStream: InputStream var outputStream: OutputStream var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, hostname as CFString, UInt32(port), &readStream, &writeStream) if let readStream = readStream?.takeRetainedValue(), let writeStream = writeStream?.takeRetainedValue() { CFReadStreamSetProperty(readStream, .shouldCloseNativeSocket, kCFBooleanTrue) CFWriteStreamSetProperty(writeStream, .shouldCloseNativeSocket, kCFBooleanTrue) if secure { CFReadStreamSetProperty(readStream, .socketSecurityLevel, StreamSocketSecurityLevel.negotiatedSSL.rawValue as CFString) CFWriteStreamSetProperty(writeStream, .socketSecurityLevel, StreamSocketSecurityLevel.negotiatedSSL.rawValue as CFString) } inputStream = readStream as InputStream inputStream.schedule(in: .current, forMode: .default) inputStream.open() outputStream = writeStream as OutputStream outputStream.schedule(in: .current, forMode: .default) outputStream.open() } else { if readStream != nil { readStream?.release() } if writeStream != nil { writeStream?.release() } super.init(inputStream: nil, outputStream: nil) return nil } super.init(inputStream: inputStream, outputStream: outputStream) self.input?.delegate = self self.output?.delegate = self } } extension TCFSocketTransport: StreamDelegate { } #endif /// TSocketTransport, posix sockets. Supports IPv4 only for now public class TSocketTransport : TTransport { public var socketDescriptor: Int32 /// Initialize from an already set up socketDescriptor. /// Expects socket thats already bound/connected (i.e. from listening) /// /// - parameter socketDescriptor: posix socket descriptor (Int32) public init(socketDescriptor: Int32) { self.socketDescriptor = socketDescriptor } public convenience init(hostname: String, port: Int) throws { guard let hp = gethostbyname(hostname.cString(using: .utf8)!)?.pointee, let hostAddr = in_addr(hostent: hp) else { throw TTransportError(error: .unknown, message: "Invalid address: \(hostname)") } #if os(Linux) let sock = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0) var addr = sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: in_port_t(htons(UInt16(port))), sin_addr: hostAddr, sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) #else let sock = socket(AF_INET, SOCK_STREAM, 0) var addr = sockaddr_in(sin_len: UInt8(MemoryLayout<sockaddr_in>.size), sin_family: sa_family_t(AF_INET), sin_port: in_port_t(htons(UInt16(port))), sin_addr: in_addr(s_addr: in_addr_t(0)), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) #endif let addrPtr = withUnsafePointer(to: &addr){ UnsafePointer<sockaddr>(OpaquePointer($0)) } let connected = connect(sock, addrPtr, UInt32(MemoryLayout<sockaddr_in>.size)) if connected != 0 { throw TTransportError(error: .notOpen, message: "Error binding to host: \(hostname) \(port)") } self.init(socketDescriptor: sock) } deinit { close() } public func readAll(size: Int) throws -> Data { var out = Data() while out.count < size { out.append(try self.read(size: size)) } return out } public func read(size: Int) throws -> Data { var buff = Array<UInt8>.init(repeating: 0, count: size) let readBytes = Sys.read(socketDescriptor, &buff, size) return Data(buff[0..<readBytes]) } public func write(data: Data) { var bytesToWrite = data.count var writeBuffer = data while bytesToWrite > 0 { let written = writeBuffer.withUnsafeBytes { Sys.write(socketDescriptor, $0.baseAddress!, writeBuffer.count) } writeBuffer = writeBuffer.subdata(in: written ..< writeBuffer.count) bytesToWrite -= written } } public func flush() throws { // nothing to do } public func close() { shutdown(socketDescriptor, Int32(SHUT_RDWR)) _ = Sys.close(socketDescriptor) } }
1594117f94e020fb9ac8edcf0d6fae9e
30.449074
133
0.648314
false
true
false
false
julienbodet/wikipedia-ios
refs/heads/develop
Wikipedia/Code/SessionsFunnel.swift
mit
1
// https://meta.wikimedia.org/wiki/Schema:MobileWikiAppiOSSessions @objc final class SessionsFunnel: EventLoggingFunnel, EventLoggingStandardEventProviding { @objc public static let shared = SessionsFunnel() private override init() { super.init(schema: "MobileWikiAppiOSSessions", version: 18121261) } private enum Action: String { case sessionStart = "session_start" case sessionEnd = "session_end" } private func event(category: EventLoggingCategory, label: EventLoggingLabel?, action: Action, measure: Double? = nil) -> Dictionary<String, Any> { let category = category.rawValue let action = action.rawValue var event: [String: Any] = ["category": category, "action": action, "primary_language": primaryLanguage(), "is_anon": isAnon] if let label = label?.rawValue { event["label"] = label } if let measure = measure { event["measure_time"] = Int(round(measure)) } return event } override func preprocessData(_ eventData: [AnyHashable: Any]) -> [AnyHashable: Any] { return wholeEvent(with: eventData) } @objc public func logSessionStart() { resetSession() log(event(category: .unknown, label: nil, action: .sessionStart)) } private func resetSession() { EventLoggingService.shared.resetSession() } @objc public func logSessionEnd() { guard let sessionStartDate = EventLoggingService.shared.sessionStartDate else { assertionFailure("Session start date cannot be nil") return } log(event(category: .unknown, label: nil, action: .sessionEnd, measure: fabs(sessionStartDate.timeIntervalSinceNow))) } }
652b91bfb655f1c2d3d2ca3e4b25f91c
34.019231
150
0.632619
false
false
false
false
con-beo-vang/Spendy
refs/heads/master
Spendy/View Controllers/SelectReminderCategoryViewController.swift
mit
1
// // SelectReminderCategoryViewController.swift // Spendy // // Created by Dave Vo on 9/30/15. // Copyright © 2015 Cheetah. All rights reserved. // import UIKit class SelectReminderCategoryViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var items: [Category]? var backButton: UIButton? // MARK: - Main functions override func viewDidLoad() { super.viewDidLoad() addBarButton() items = Category.allExpenseType() tableView.tableFooterView = UIView() tableView.reloadData() } // MARK: Button func addBarButton() { backButton = UIButton() Helper.sharedInstance.customizeBarButton(self, button: backButton!, imageName: "Bar-Back", isLeft: true) backButton!.addTarget(self, action: "onBackButton:", forControlEvents: UIControlEvents.TouchUpInside) } func onBackButton(sender: UIButton!) { navigationController?.popViewControllerAnimated(true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let cell = sender as! CategoryCell let indexPath = tableView.indexPathForCell(cell) let toController = segue.destinationViewController if toController is AddReminderViewController { let vc = toController as! AddReminderViewController let category:Category = items![indexPath!.row] vc.selectedUserCategory = UserCategory.findByCategoryId(category.id) vc.isNewReminder = true } } } // MARK: - Table view extension SelectReminderCategoryViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 56 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath) as! CategoryCell if let item = items?[indexPath.row] { cell.nameLabel.text = item["name"] as! String? if let icon = item["icon"] as? String { cell.iconImageView.image = Helper.sharedInstance.createIcon(icon) cell.iconImageView.setNewTintColor(UIColor.whiteColor()) cell.iconImageView.layer.backgroundColor = Color.expenseColor.CGColor } } cell.setSeparatorFullWidth() return cell } }
0358260f29ca9fc6930ec67a02963136
27.277778
116
0.708055
false
false
false
false
alexburtnik/ABSwiftExtensions
refs/heads/master
ABSwiftExtensions/Classes/Geometry/CGPoint+Geometry.swift
mit
1
// // CGPoint+Geometry.swift // Pods // // Created by Alex Burtnik on 8/31/17. // // import Foundation public extension CGPoint { public func rounded() -> CGPoint { return CGPoint(x: round(x), y: round(y)) } public func distanceSquared(toPoint point: CGPoint) -> CGFloat { return pow(x - point.x, 2) + pow(y - point.y, 2) } public func distance(toPoint point: CGPoint) -> CGFloat { return sqrt(distanceSquared(toPoint: point)) } public func vectorToPoint(_ point: CGPoint) -> CGVector { return CGVector(dx: point.x - x, dy: point.y - y) } public func vectorToSegment(_ segment: Segment) -> CGVector { let a = vectorToPoint(segment.start) let b = vectorToPoint(segment.end) let c = segment.vector if a.lengthSquared >= b.lengthSquared + segment.lengthSquared { return b } if b.lengthSquared >= a.lengthSquared + segment.lengthSquared { return a } return a - c * (a.dotProduct(c) / c.lengthSquared) } public func vectorToRect(_ rect: CGRect) -> CGVector { if rect.contains(self) { return .zero } var vector = CGVector.zero if x > rect.maxX { vector.dx = rect.maxX - x } if x < rect.minX { vector.dx = rect.minX - x } if y > rect.maxY { vector.dy = rect.maxY - y } if y < rect.minY { vector.dy = rect.minY - y } return vector } }
69620d78c0d5a2478e34592e8e5e64b7
28.816327
82
0.5859
false
false
false
false
PhillipEnglish/TIY-Assignments
refs/heads/master
VenueMenu/VenueMenu/VenuesTableViewController.swift
cc0-1.0
1
// // VenuesTableViewController.swift // VenueMenu // // Created by Phillip English on 11/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreData protocol VenueSearchDelegate { func venueWasselected(venue: NSManagedObject) } class VenuesTableViewController: UITableViewController, VenueSearchDelegate { var venues = Array<NSManagedObject>() let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() let fetchRequest = NSFetchRequest(entityName: "Venue") do { let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [Venue] venues = fetchResults! } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } self.navigationItem.leftBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return venues.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("VenueCell", forIndexPath: indexPath) let aVenue = venues[indexPath.row] cell.textLabel?.text = aVenue.valueForKey("name") as? String return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let aVenue = venues[indexPath.row] venues.removeAtIndex(indexPath.row) managedObjectContext.deleteObject(aVenue) saveContext() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } // MARK: - Search Delegate func venueWasselected(venue: NSManagedObject) { } // MARK: - Private functions private func saveContext() { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } // 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?) { } }
c67ac44d95daab4bb65033794a604b54
25.53719
155
0.634693
false
false
false
false
peaks-cc/iOS11_samplecode
refs/heads/master
chapter_02/07_ARMeasure/ARMeasure/ViewController.swift
mit
1
// // ViewController.swift // ARTapeMeasure // // Created by Shuichi Tsutsumi on 2017/07/17. // Copyright © 2017 Shuichi Tsutsumi. All rights reserved. // import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { private var startNode: SCNNode? private var endNode: SCNNode? private var lineNode: SCNNode? @IBOutlet var sceneView: ARSCNView! @IBOutlet var trackingStateLabel: UILabel! @IBOutlet var statusLabel: UILabel! @IBOutlet var resetBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // デバッグオプションをセット sceneView.debugOptions = [ARSCNDebugOptions.showFeaturePoints] // シーンを生成してARSCNViewにセット sceneView.scene = SCNScene() reset() // セッション開始 let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal configuration.isLightEstimationEnabled = true sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors]) } // MARK: - Private private func reset() { startNode?.removeFromParentNode() startNode = nil endNode?.removeFromParentNode() endNode = nil statusLabel.isHidden = true } private func putSphere(at pos: SCNVector3, color: UIColor) -> SCNNode { let node = SCNNode.sphereNode(color: color) sceneView.scene.rootNode.addChildNode(node) node.position = pos return node } private func drawLine(from: SCNNode, to: SCNNode, length: Float) -> SCNNode { let lineNode = SCNNode.lineNode(length: CGFloat(length), color: UIColor.red) from.addChildNode(lineNode) lineNode.position = SCNVector3Make(0, 0, -length / 2) from.look(at: to.position) return lineNode } private func hitTest(_ pos: CGPoint) { // 平面を対象にヒットテストを実行 let results = sceneView.hitTest(pos, types: [.existingPlane]) // 平面もしくは特徴点を対象にヒットテストを実行 // let results = sceneView.hitTest(pos, types: [.existingPlane, .featurePoint]) // 最も近い(手前にある)結果を取得 guard let result = results.first else {return} // ヒットした位置を計算する let hitPos = result.worldTransform.position() // 始点はもう決まっているか? if let startNode = startNode { // 終点を決定する(終点ノードを追加) endNode = putSphere(at: hitPos, color: UIColor.green) guard let endNode = endNode else {fatalError()} // 始点と終点の距離を計算する let distance = (endNode.position - startNode.position).length() print("distance: \(distance) [m]") // 始点と終点を結ぶ線を描画する lineNode = drawLine(from: startNode, to: endNode, length: distance) // ラベルに表示 statusLabel.text = String(format: "Distance: %.2f [m]", distance) } else { // 始点を決定する(始点ノードを追加) startNode = putSphere(at: hitPos, color: UIColor.blue) statusLabel.text = "終点をタップしてください" } } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { guard let frame = sceneView.session.currentFrame else {return} DispatchQueue.main.async(execute: { self.statusLabel.isHidden = !(frame.anchors.count > 0) if self.startNode == nil { self.statusLabel.text = "始点をタップしてください" } }) } func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()} print("anchor:\(anchor), node: \(node), node geometry: \(String(describing: node.geometry))") planeAnchor.addPlaneNode(on: node, color: UIColor.bookYellow.withAlphaComponent(0.1)) } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()} planeAnchor.updatePlaneNode(on: node) } func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { print("\(self.classForCoder)/" + #function) } // MARK: - ARSessionObserver func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) { print("trackingState: \(camera.trackingState)") trackingStateLabel.text = camera.trackingState.description } // MARK: - Touch Handlers override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // タップ位置のスクリーン座標を取得 guard let touch = touches.first else {return} let pos = touch.location(in: sceneView) // 終点が既に決まっている場合は終点を置き換える処理とする if let endNode = endNode { endNode.removeFromParentNode() lineNode?.removeFromParentNode() } hitTest(pos) } // MARK: - Actions @IBAction func resetBtnTapped(_ sender: UIButton) { reset() } }
4ae311773591d46a39a6ac21903a2e23
31.695652
101
0.617401
false
false
false
false
ehtd/HackerNews
refs/heads/master
Hackyto/Hackyto/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // Hackyto // // Created by Ernesto Torres on 10/22/14. // Copyright (c) 2014 ehtd. All rights reserved. // import UIKit import MessageUI @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let tabbarControllerDelegate = TabbarControllerDelegate() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = ColorFactory.darkGrayColor() let tabBarController: UITabBarController = UITabBarController() tabBarController.delegate = tabbarControllerDelegate var viewControllers: [UIViewController] = [] for i in 0..<ContentType.count { let type: ContentType = ContentType(rawValue: i)! let navigationController = UINavigationController(rootViewController: TableController(type: type)) let textAttributes = [NSForegroundColorAttributeName: ColorFactory.lightColor()] navigationController.navigationBar.titleTextAttributes = textAttributes viewControllers.append(navigationController) } tabBarController.viewControllers = viewControllers if let startingController = viewControllers[0] as? UINavigationController { tabbarControllerDelegate.setStartingController(startingController) } let tabBarImageNames = ["top", "new", "ask", "show", "jobs"] let tabBarTitles = tabBarImageNames.map { $0.capitalized } for i in 0..<viewControllers.count { if let tab = tabBarController.tabBar.items?[i] { tab.image = UIImage(named: tabBarImageNames[i]) tab.title = tabBarTitles[i] } } configureAppearance() window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } // MARK: Apperance configuration func configureAppearance() { UINavigationBar.appearance().barTintColor = ColorFactory.lightColor() UINavigationBar.appearance().tintColor = ColorFactory.darkGrayColor() UINavigationBar.appearance().isTranslucent = false UITabBar.appearance().tintColor = ColorFactory.darkGrayColor() UITabBar.appearance().barTintColor = ColorFactory.lightColor() UITabBar.appearance().isTranslucent = false UIToolbar.appearance().barTintColor = ColorFactory.lightColor() UIToolbar.appearance().tintColor = ColorFactory.darkGrayColor() } }
4a199904dd404fc0a8d1162848a758c0
35.302632
144
0.685393
false
false
false
false
amdaza/Scoop-iOS-Client
refs/heads/master
ScoopClient/ScoopClient/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // ScoopClient // // Created by Home on 30/10/16. // Copyright © 2016 Alicia. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /* // Create rootVC let mVC = MainViewController(nibName: nil, bundle: nil) let navVC = UINavigationController(rootViewController: mVC) // Create window window = UIWindow(frame: UIScreen.main.bounds) // Put rootVC into window and show it window?.rootViewController = navVC window?.makeKeyAndVisible() */ return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "ScoopClient") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
21f06a88cf3223229060c0a813ea9816
46.355769
285
0.675736
false
false
false
false
arslanbilal/cryptology-project
refs/heads/master
Cryptology Project/Cryptology Project/Classes/Controllers/User/PasswordEditController/PasswordEditViewController.swift
mit
1
// // PasswordEditViewController.swift // Cryptology Project // // Created by Bilal Arslan on 08/04/16. // Copyright © 2016 Bilal Arslan. All rights reserved. // import UIKit class PasswordEditViewController: UIViewController, UITextFieldDelegate { let passwordTextField = UITextField.newAutoLayoutView() let password2TextField = UITextField.newAutoLayoutView() let submitButton = UIButton.newAutoLayoutView() // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.navigationItem.title = "Change Password" self.loadViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Load Views func loadViews() { let loginElementsView = UIView.newAutoLayoutView() loginElementsView.backgroundColor = UIColor.loginViewBackgroundColor() loginElementsView.layer.cornerRadius = 10.0 self.view.addSubview(loginElementsView) loginElementsView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(30.0, 15.5, 0, 15.5), excludingEdge: .Bottom) loginElementsView.autoSetDimension(.Height, toSize: 190) let passwordView = UIView.newAutoLayoutView() passwordView.backgroundColor = UIColor.whiteColor() passwordView.layer.cornerRadius = 5.0 loginElementsView.addSubview(passwordView) passwordView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(10.0, 10.0, 0, 10.0), excludingEdge: .Bottom) passwordView.autoSetDimension(.Height, toSize: 50) passwordTextField.delegate = self passwordTextField.textAlignment = .Center passwordTextField.secureTextEntry = true passwordTextField.placeholder = "password" passwordView.addSubview(passwordTextField) passwordTextField.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(2.0, 5.0, 2.0, 5.0)) let password2View = UIView.newAutoLayoutView() password2View.backgroundColor = UIColor.whiteColor() password2View.layer.cornerRadius = 5.0 loginElementsView.addSubview(password2View) password2View.autoPinEdgeToSuperviewEdge(.Left, withInset: 10.0) password2View.autoPinEdgeToSuperviewEdge(.Right, withInset: 10.0) password2View.autoPinEdge(.Top, toEdge: .Bottom, ofView: passwordView, withOffset: 10.0) password2View.autoSetDimension(.Height, toSize: 50) password2TextField.delegate = self password2TextField.textAlignment = .Center password2TextField.secureTextEntry = true password2TextField.placeholder = "retype password" password2View.addSubview(password2TextField) password2TextField.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(2.0, 5.0, 2.0, 5.0)) submitButton.backgroundColor = UIColor.incomingMessageColor() submitButton.titleLabel?.textColor = UIColor.whiteColor() submitButton.setTitle("Change Password", forState: .Normal) submitButton.addTarget(self, action: #selector(PasswordEditViewController.didTapSubmitButton(_:)), forControlEvents: .TouchUpInside) submitButton.layer.cornerRadius = 5.0 loginElementsView.addSubview(submitButton) submitButton.autoPinEdge(.Top, toEdge: .Bottom, ofView: password2View, withOffset: 10.0) submitButton.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0.0, 10.0, 10.0, 10.0), excludingEdge: .Top) //submitButton.autoSetDimension(.Height, toSize: 50) } // MARK: - Button Action func didTapSubmitButton(sender: UIButton) { let password1 = passwordTextField.text! let password2 = password2TextField.text! if password1 != "" && password2 != "" { if password1 == password2 { if password1.length > 7 { ActiveUser.sharedInstance.user.changePassword(password1) passwordTextField.text = "" passwordTextField.resignFirstResponder() password2TextField.text = "" password2TextField.resignFirstResponder() showAlertView("Password Changed!", message: "", style: .Alert) } else { showAlertView("Cannot Change", message: "Enter more than 8 chracter.", style: .Alert) } } else { showAlertView("Match Error", message: "Passwords you enter does not match.", style: .Alert) } } else { showAlertView("Error!", message: "Fill the password fields.", style: .Alert) } } // MARK: - UITextField Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return false } // MARK: - AlertViewInitialise func showAlertView(title: String, message: String, style: UIAlertControllerStyle) { let alertController = UIAlertController.init(title: title, message: message, preferredStyle: style) alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } }
bf8fd251eb96d23e9f37c6011a89c5a8
40.716418
140
0.656708
false
false
false
false
igormatyushkin014/Sensitive
refs/heads/master
Sensitive/SensitiveDemo/ViewControllers/Main/MainViewController.swift
mit
1
// // MainViewController.swift // SensitiveDemo // // Created by Igor Matyushkin on 09.11.15. // Copyright © 2015 Igor Matyushkin. All rights reserved. // import UIKit import Sensitive class MainViewController: UIViewController { // MARK: Class variables & properties // MARK: Class methods // MARK: Initializers // MARK: Deinitializer deinit { } // MARK: Outlets @IBOutlet fileprivate weak var circleView: CircleView! // MARK: Variables & properties fileprivate let colors: [UIColor] = [ .green, .yellow, .orange, .white ] fileprivate var indexOfCurrentColor: Int? // MARK: Public methods override func viewDidLoad() { super.viewDidLoad() // Initialize circle view self.circleView.onTap .handle { (tapGestureRecognizer) in if (self.indexOfCurrentColor == nil) || (self.indexOfCurrentColor! >= self.colors.count - 1) { self.indexOfCurrentColor = 0 } else { self.indexOfCurrentColor = self.indexOfCurrentColor! + 1 } let colorForCircleView = self.colors[self.indexOfCurrentColor!] self.circleView.backgroundColor = colorForCircleView } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var prefersStatusBarHidden : Bool { return true } // MARK: Private methods // MARK: Actions // MARK: Protocol methods }
e1b05273fd6637c2157c534b963dfba5
22.093333
110
0.569861
false
false
false
false
Ashok28/Kingfisher
refs/heads/acceptance
DYLive/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift
lgpl-3.0
7
// // ImagePrefetcher.swift // Kingfisher // // Created by Claire Knight <[email protected]> on 24/02/2016 // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Progress update block of prefetcher when initialized with a list of resources. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while /// downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void) /// Progress update block of prefetcher when initialized with a list of resources. /// /// - `skippedSources`: An array of sources that are already cached before the prefetching starting. /// - `failedSources`: An array of sources that fail to be fetched. /// - `completedResources`: An array of sources that are fetched and cached successfully. public typealias PrefetcherSourceProgressBlock = ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void) /// Completion block of prefetcher when initialized with a list of sources. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while /// downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void) /// Completion block of prefetcher when initialized with a list of sources. /// /// - `skippedSources`: An array of sources that are already cached before the prefetching starting. /// - `failedSources`: An array of sources that fail to be fetched. /// - `completedSources`: An array of sources that are fetched and cached successfully. public typealias PrefetcherSourceCompletionHandler = ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void) /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them. /// This is useful when you know a list of image resources and want to download them before showing. It also works with /// some Cocoa prefetching mechanism like table view or collection view `prefetchDataSource`, to start image downloading /// and caching before they display on screen. public class ImagePrefetcher: CustomStringConvertible { public var description: String { return "\(Unmanaged.passUnretained(self).toOpaque())" } /// The maximum concurrent downloads to use when prefetching images. Default is 5. public var maxConcurrentDownloads = 5 private let prefetchSources: [Source] private let optionsInfo: KingfisherParsedOptionsInfo private var progressBlock: PrefetcherProgressBlock? private var completionHandler: PrefetcherCompletionHandler? private var progressSourceBlock: PrefetcherSourceProgressBlock? private var completionSourceHandler: PrefetcherSourceCompletionHandler? private var tasks = [String: DownloadTask.WrappedTask]() private var pendingSources: ArraySlice<Source> private var skippedSources = [Source]() private var completedSources = [Source]() private var failedSources = [Source]() private var stopped = false // A manager used for prefetching. We will use the helper methods in manager. private let manager: KingfisherManager private let pretchQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.pretchQueue") private static let requestingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.requestingQueue") private var finished: Bool { let totalFinished: Int = failedSources.count + skippedSources.count + completedSources.count return totalFinished == prefetchSources.count && tasks.isEmpty } /// Creates an image prefetcher with an array of URLs. /// /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process. /// The images which are already cached will be skipped without downloading again. /// /// - Parameters: /// - urls: The URLs which should be prefetched. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init( urls: [URL], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { let resources: [Resource] = urls.map { $0 } self.init( resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /// Creates an image prefetcher with an array of URLs. /// /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process. /// The images which are already cached will be skipped without downloading again. /// /// - Parameters: /// - urls: The URLs which should be prefetched. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init( urls: [URL], options: KingfisherOptionsInfo? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { let resources: [Resource] = urls.map { $0 } self.init( resources: resources, options: options, progressBlock: nil, completionHandler: completionHandler) } /// Creates an image prefetcher with an array of resources. /// /// - Parameters: /// - resources: The resources which should be prefetched. See `Resource` type for more. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init( resources: [Resource], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { self.init(sources: resources.map { $0.convertToSource() }, options: options) self.progressBlock = progressBlock self.completionHandler = completionHandler } /// Creates an image prefetcher with an array of resources. /// /// - Parameters: /// - resources: The resources which should be prefetched. See `Resource` type for more. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init( resources: [Resource], options: KingfisherOptionsInfo? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { self.init(sources: resources.map { $0.convertToSource() }, options: options) self.completionHandler = completionHandler } /// Creates an image prefetcher with an array of sources. /// /// - Parameters: /// - sources: The sources which should be prefetched. See `Source` type for more. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called every time an source fetching successes, fails, is skipped. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init(sources: [Source], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherSourceProgressBlock? = nil, completionHandler: PrefetcherSourceCompletionHandler? = nil) { self.init(sources: sources, options: options) self.progressSourceBlock = progressBlock self.completionSourceHandler = completionHandler } /// Creates an image prefetcher with an array of sources. /// /// - Parameters: /// - sources: The sources which should be prefetched. See `Source` type for more. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. /// - completionHandler: Called when the whole prefetching process finished. /// /// - Note: /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as /// the downloader and cache target respectively. You can specify another downloader or cache by using /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. public convenience init(sources: [Source], options: KingfisherOptionsInfo? = nil, completionHandler: PrefetcherSourceCompletionHandler? = nil) { self.init(sources: sources, options: options) self.completionSourceHandler = completionHandler } init(sources: [Source], options: KingfisherOptionsInfo?) { var options = KingfisherParsedOptionsInfo(options) prefetchSources = sources pendingSources = ArraySlice(sources) // We want all callbacks from our prefetch queue, so we should ignore the callback queue in options. // Add our own callback dispatch queue to make sure all internal callbacks are // coming back in our expected queue. options.callbackQueue = .dispatch(pretchQueue) optionsInfo = options let cache = optionsInfo.targetCache ?? .default let downloader = optionsInfo.downloader ?? .default manager = KingfisherManager(downloader: downloader, cache: cache) } /// Starts to download the resources and cache them. This can be useful for background downloading /// of assets that are required for later use in an app. This code will not try and update any UI /// with the results of the process. public func start() { pretchQueue.async { guard !self.stopped else { assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.") self.handleComplete() return } guard self.maxConcurrentDownloads > 0 else { assertionFailure("There should be concurrent downloads value should be at least 1.") self.handleComplete() return } // Empty case. guard self.prefetchSources.count > 0 else { self.handleComplete() return } let initialConcurrentDownloads = min(self.prefetchSources.count, self.maxConcurrentDownloads) for _ in 0 ..< initialConcurrentDownloads { if let resource = self.pendingSources.popFirst() { self.startPrefetching(resource) } } } } /// Stops current downloading progress, and cancel any future prefetching activity that might be occuring. public func stop() { pretchQueue.async { if self.finished { return } self.stopped = true self.tasks.values.forEach { $0.cancel() } } } private func downloadAndCache(_ source: Source) { let downloadTaskCompletionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void) = { result in self.tasks.removeValue(forKey: source.cacheKey) do { let _ = try result.get() self.completedSources.append(source) } catch { self.failedSources.append(source) } self.reportProgress() if self.stopped { if self.tasks.isEmpty { self.failedSources.append(contentsOf: self.pendingSources) self.handleComplete() } } else { self.reportCompletionOrStartNext() } } var downloadTask: DownloadTask.WrappedTask? ImagePrefetcher.requestingQueue.sync { let context = RetrievingContext( options: optionsInfo, originalSource: source ) downloadTask = manager.loadAndCacheImage( source: source, context: context, completionHandler: downloadTaskCompletionHandler) } if let downloadTask = downloadTask { tasks[source.cacheKey] = downloadTask } } private func append(cached source: Source) { skippedSources.append(source) reportProgress() reportCompletionOrStartNext() } private func startPrefetching(_ source: Source) { if optionsInfo.forceRefresh { downloadAndCache(source) return } let cacheType = manager.cache.imageCachedType( forKey: source.cacheKey, processorIdentifier: optionsInfo.processor.identifier) switch cacheType { case .memory: append(cached: source) case .disk: if optionsInfo.alsoPrefetchToMemory { let context = RetrievingContext(options: optionsInfo, originalSource: source) _ = manager.retrieveImageFromCache( source: source, context: context) { _ in self.append(cached: source) } } else { append(cached: source) } case .none: downloadAndCache(source) } } private func reportProgress() { if progressBlock == nil && progressSourceBlock == nil { return } let skipped = self.skippedSources let failed = self.failedSources let completed = self.completedSources CallbackQueue.mainCurrentOrAsync.execute { self.progressSourceBlock?(skipped, failed, completed) self.progressBlock?( skipped.compactMap { $0.asResource }, failed.compactMap { $0.asResource }, completed.compactMap { $0.asResource } ) } } private func reportCompletionOrStartNext() { if let resource = self.pendingSources.popFirst() { // Loose call stack for huge ammount of sources. pretchQueue.async { self.startPrefetching(resource) } } else { guard allFinished else { return } self.handleComplete() } } var allFinished: Bool { return skippedSources.count + failedSources.count + completedSources.count == prefetchSources.count } private func handleComplete() { if completionHandler == nil && completionSourceHandler == nil { return } // The completion handler should be called on the main thread CallbackQueue.mainCurrentOrAsync.execute { self.completionSourceHandler?(self.skippedSources, self.failedSources, self.completedSources) self.completionHandler?( self.skippedSources.compactMap { $0.asResource }, self.failedSources.compactMap { $0.asResource }, self.completedSources.compactMap { $0.asResource } ) self.completionHandler = nil self.progressBlock = nil } } }
598f94945d4237768175fc54432d4d31
44.357466
120
0.668246
false
false
false
false
qingcai518/MyFacePlus
refs/heads/develop
MyFacePlus/BarcaView.swift
apache-2.0
1
// // BarcaView.swift // MyFacePlus // // Created by liqc on 2017/07/11. // Copyright © 2017年 RN-079. All rights reserved. // import UIKit import RxSwift class BarcaView: UIView { @IBOutlet weak var iconView : UIImageView! let disposeBag = DisposeBag() lazy var rx_timer = Observable<Int>.interval(0.5, scheduler: MainScheduler.instance).shareReplay(1) var currentImage = UIImage(named: "icon_face2")! var nextImage = UIImage(named: "icon_face2_big")! override func awakeFromNib() { super.awakeFromNib() frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight) backgroundColor = UIColor.init(white: 0, alpha: 0) let defaultSize = CGFloat(44) setIconPosition((screenWidth - defaultSize) / 2, (screenHeight - defaultSize) / 2, defaultSize, defaultSize) iconView.image = currentImage // iconView.image = UIImage.animatedImage(with: [UIImage(named: "icon_face2")!, UIImage(named: "icon_face2_big")!], duration: 1) startAnimation() } } extension BarcaView { func setIconPosition(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) { iconView.frame = CGRect(x: x, y: y, width: w, height: h) } fileprivate func startAnimation() { rx_timer.bind { [weak self] count in guard let `self` = self else {return} self.iconView.image = self.nextImage self.nextImage = self.currentImage self.currentImage = self.iconView.image! }.addDisposableTo(disposeBag) } }
e040bdee8a91437bb333ef46a8ee9366
32.617021
135
0.63481
false
false
false
false
xedin/swift
refs/heads/master
test/IRGen/class_resilience.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: %{python} %utils/chex.py < %s > %t/class_resilience.swift // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution %t/class_resilience.swift | %FileCheck %t/class_resilience.swift --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-runtime -DINT=i%target-ptrsize // RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution -O %t/class_resilience.swift // CHECK: @"$s16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd" = hidden global [[INT]] 0 // CHECK: @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0 // CHECK: @"$s16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd" = hidden global [[INT]] 0 // CHECK: @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0 // CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvpWvd" = hidden global [[INT]] {{8|16}} // CHECK: @"$s16class_resilience21ResilientGenericChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS:{ (i32|i64), i32, i32 }]] zeroinitializer // CHECK: @"$s16class_resilience27ClassWithEmptyThenResilientC9resilient0H7_struct0G3IntVvpWvd" = hidden global [[INT]] 0, // CHECK: @"$s16class_resilience27ClassWithResilientThenEmptyC9resilient0H7_struct0E3IntVvpWvd" = hidden global [[INT]] 0, // CHECK: @"$s16class_resilience26ClassWithResilientPropertyCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 } // CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 } // CHECK: @"$s16class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvpWvd" = hidden constant [[INT]] {{8|16}} // CHECK: @"$s16class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|20}} // CHECK: @"$s16class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvpWvd" = hidden constant [[INT]] {{8|16}} // CHECK: @"$s16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|24}} // CHECK: [[RESILIENTCHILD_NAME:@.*]] = private constant [15 x i8] c"ResilientChild\00" // CHECK: @"$s16class_resilience14ResilientChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS]] zeroinitializer // CHECK: @"$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq" = external{{( dllimport)?}} global %swift.method_descriptor // CHECK: @"$s16class_resilience14ResilientChildCMn" = {{(protected )?}}{{(dllexport )?}}constant <{{.*}}> <{ // -- flags: class, unique, has vtable, has override table, in-place initialization, has resilient superclass // CHECK-SAME: <i32 0xE201_0050> // -- parent: // CHECK-SAME: @"$s16class_resilienceMXM" // -- name: // CHECK-SAME: [15 x i8]* [[RESILIENTCHILD_NAME]] // -- metadata accessor function: // CHECK-SAME: @"$s16class_resilience14ResilientChildCMa" // -- field descriptor: // CHECK-SAME: @"$s16class_resilience14ResilientChildCMF" // -- metadata bounds: // CHECK-SAME: @"$s16class_resilience14ResilientChildCMo" // -- metadata positive size in words (not used): // CHECK-SAME: i32 0, // -- num immediate members: // CHECK-SAME: i32 4, // -- num fields: // CHECK-SAME: i32 1, // -- field offset vector offset: // CHECK-SAME: i32 0, // -- superclass: // CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentCMn" // -- singleton metadata initialization cache: // CHECK-SAME: @"$s16class_resilience14ResilientChildCMl" // -- resilient pattern: // CHECK-SAME: @"$s16class_resilience14ResilientChildCMP" // -- completion function: // CHECK-SAME: @"$s16class_resilience14ResilientChildCMr" // -- number of method overrides: // CHECK-SAME: i32 2, // CHECK-SAME: %swift.method_override_descriptor { // -- base class: // CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentCMn" // -- base method: // CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq" // -- implementation: // CHECK-SAME: @"$s16class_resilience14ResilientChildC8getValueSiyF" // CHECK-SAME: } // CHECK-SAME: %swift.method_override_descriptor { // -- base class: // CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentCMn" // -- base method: // CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentCACycfCTq" // -- implementation: // CHECK-SAME: @"$s16class_resilience14ResilientChildCACycfC" // CHECK-SAME: } // CHECK-SAME: }> // CHECK: @"$s16class_resilience14ResilientChildCMP" = internal constant <{{.*}}> <{ // -- instantiation function: // CHECK-SAME: i32 0, // -- destructor: // CHECK-SAME: @"$s16class_resilience14ResilientChildCfD" // -- ivar destroyer: // CHECK-SAME: i32 0, // -- flags: // CHECK-SAME: i32 2, // -- RO data: // CHECK-objc-SAME: @_DATA__TtC16class_resilience14ResilientChild // CHECK-native-SAME: i32 0, // -- metaclass: // CHECK-objc-SAME: @"$s16class_resilience14ResilientChildCMm" // CHECK-native-SAME: i32 0 // CHECK: @"$s16class_resilience17MyResilientParentCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 } // CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 } // CHECK: @"$s16class_resilience16MyResilientChildCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 60, i32 2, i32 15 } // CHECK-SAME-64: { [[INT]] 96, i32 2, i32 12 } // CHECK: @"$s16class_resilience24MyResilientGenericParentCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 } // CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 } // CHECK: @"$s16class_resilience24MyResilientConcreteChildCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 64, i32 2, i32 16 } // CHECK-SAME-64: { [[INT]] 104, i32 2, i32 13 } // CHECK: @"$s16class_resilience27ClassWithEmptyThenResilientC5emptyAA0E0VvpWvd" = hidden constant [[INT]] 0, // CHECK: @"$s16class_resilience27ClassWithResilientThenEmptyC5emptyAA0G0VvpWvd" = hidden constant [[INT]] 0, // CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvgTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds // CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvsTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds // CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvMTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds // CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvgTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds // CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvsTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds // CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvMTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds // CHECK: @"$s16class_resilience17MyResilientParentCACycfCTq" = hidden alias %swift.method_descriptor, getelementptr inbounds // CHECK: @"$s16class_resilience24MyResilientGenericParentC1tACyxGx_tcfCTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds // CHECK: @"$s16class_resilience24MyResilientConcreteChildC1xACSi_tcfCTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds import resilient_class import resilient_struct import resilient_enum // Concrete class with resilient stored property public class ClassWithResilientProperty { public let p: Point public let s: Size public let color: Int32 public init(p: Point, s: Size, color: Int32) { self.p = p self.s = s self.color = color } } // Concrete class with non-fixed size stored property public class ClassWithResilientlySizedProperty { public let r: Rectangle public let color: Int32 public init(r: Rectangle, color: Int32) { self.r = r self.color = color } } // Concrete class with resilient stored property that // is fixed-layout inside this resilience domain public struct MyResilientStruct { public let x: Int32 } public class ClassWithMyResilientProperty { public let r: MyResilientStruct public let color: Int32 public init(r: MyResilientStruct, color: Int32) { self.r = r self.color = color } } // Enums with indirect payloads are fixed-size public class ClassWithIndirectResilientEnum { public let s: FunnyShape public let color: Int32 public init(s: FunnyShape, color: Int32) { self.s = s self.color = color } } // Superclass is resilient, so the number of fields and their // offsets is not known at compile time public class ResilientChild : ResilientOutsideParent { public var field: Int32 = 0 public override func getValue() -> Int { return 1 } } // Superclass is resilient, so the number of fields and their // offsets is not known at compile time public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> { public var field: Int32 = 0 } // Superclass is resilient and has a resilient value type payload, // but everything is in one module public class MyResilientParent { public let s: MyResilientStruct = MyResilientStruct(x: 0) } public class MyResilientChild : MyResilientParent { public let field: Int32 = 0 } public class MyResilientGenericParent<T> { public let t: T public init(t: T) { self.t = t } } public class MyResilientConcreteChild : MyResilientGenericParent<Int> { public let x: Int public init(x: Int) { self.x = x super.init(t: x) } } extension ResilientGenericOutsideParent { public func genericExtensionMethod() -> A.Type { return A.self } } // rdar://48031465 // Field offsets for empty fields in resilient classes should be initialized // to their best-known value and made non-constant if that value might // disagree with the dynamic value. @frozen public struct Empty {} public class ClassWithEmptyThenResilient { public let empty: Empty public let resilient: ResilientInt public init(empty: Empty, resilient: ResilientInt) { self.empty = empty self.resilient = resilient } } public class ClassWithResilientThenEmpty { public let resilient: ResilientInt public let empty: Empty public init(empty: Empty, resilient: ResilientInt) { self.empty = empty self.resilient = resilient } } // ClassWithResilientProperty.color getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32Vvg"(%T16class_resilience26ClassWithResilientPropertyC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd" // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience26ClassWithResilientPropertyC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK: ret i32 [[FIELD_VALUE]] // ClassWithResilientProperty metadata accessor // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s16class_resilience26ClassWithResilientPropertyCMa"( // CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s16class_resilience26ClassWithResilientPropertyCMl", i32 0, i32 0) // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s16class_resilience26ClassWithResilientPropertyCMn" to %swift.type_descriptor*)) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0 // CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ] // CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ] // CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0 // CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1 // CHECK-NEXT: ret %swift.metadata_response [[T1]] // ClassWithResilientlySizedProperty.color getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32Vvg"(%T16class_resilience33ClassWithResilientlySizedPropertyC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd" // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience33ClassWithResilientlySizedPropertyC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK: ret i32 [[FIELD_VALUE]] // ClassWithResilientlySizedProperty metadata accessor // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s16class_resilience33ClassWithResilientlySizedPropertyCMa"( // CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMl", i32 0, i32 0) // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s16class_resilience33ClassWithResilientlySizedPropertyCMn" to %swift.type_descriptor*)) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0 // CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ] // CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ] // CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0 // CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1 // CHECK-NEXT: ret %swift.metadata_response [[T1]] // ClassWithIndirectResilientEnum.color getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32Vvg"(%T16class_resilience30ClassWithIndirectResilientEnumC* swiftself) // CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T16class_resilience30ClassWithIndirectResilientEnumC, %T16class_resilience30ClassWithIndirectResilientEnumC* %0, i32 0, i32 2 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK: ret i32 [[FIELD_VALUE]] // ResilientChild.field getter // CHECK-LABEL: define hidden swiftcc i32 @"$s16class_resilience14ResilientChildC5fields5Int32Vvg"(%T16class_resilience14ResilientChildC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience14ResilientChildC5fields5Int32VvpWvd" // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience14ResilientChildC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[FIELD_VALUE]] // ResilientGenericChild.field getter // CHECK-LABEL: define hidden swiftcc i32 @"$s16class_resilience21ResilientGenericChildC5fields5Int32Vvg"(%T16class_resilience21ResilientGenericChildC* swiftself) // FIXME: we could eliminate the unnecessary isa load by lazily emitting // metadata sources in EmitPolymorphicParameters // CHECK: load %swift.type* // CHECK: [[ADDR:%.*]] = getelementptr inbounds %T16class_resilience21ResilientGenericChildC, %T16class_resilience21ResilientGenericChildC* %0, i32 0, i32 0, i32 0 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]] // CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s16class_resilience21ResilientGenericChildCMo", i32 0, i32 0) // CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{4|8}} // CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8* // CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[METADATA_OFFSET]] // CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]* // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]] // CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T16class_resilience21ResilientGenericChildC* %0 to i8* // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[RESULT]] // MyResilientChild.field getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience16MyResilientChildC5fields5Int32Vvg"(%T16class_resilience16MyResilientChildC* swiftself) // CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %T16class_resilience16MyResilientChildC, %T16class_resilience16MyResilientChildC* %0, i32 0, i32 2 // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]] // CHECK: ret i32 [[RESULT]] // ResilientGenericOutsideParent.genericExtensionMethod() // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s15resilient_class29ResilientGenericOutsideParentC0B11_resilienceE22genericExtensionMethodxmyF"(%T15resilient_class29ResilientGenericOutsideParentC* swiftself) #0 { // CHECK: [[ISA_ADDR:%.*]] = bitcast %T15resilient_class29ResilientGenericOutsideParentC* %0 to %swift.type** // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s15resilient_class29ResilientGenericOutsideParentCMo", i32 0, i32 0) // CHECK-NEXT: [[GENERIC_PARAM_OFFSET:%.*]] = add [[INT]] [[BASE]], 0 // CHECK-NEXT: [[ISA_TMP:%.*]] = bitcast %swift.type* [[ISA]] to i8* // CHECK-NEXT: [[GENERIC_PARAM_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_TMP]], [[INT]] [[GENERIC_PARAM_OFFSET]] // CHECK-NEXT: [[GENERIC_PARAM_ADDR:%.*]] = bitcast i8* [[GENERIC_PARAM_TMP]] to %swift.type** // CHECK-NEXT: [[GENERIC_PARAM:%.*]] = load %swift.type*, %swift.type** [[GENERIC_PARAM_ADDR]] // CHECK: ret %swift.type* [[GENERIC_PARAM]] // ClassWithResilientProperty metadata initialization function // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience26ClassWithResilientPropertyCMr"(%swift.type*, i8*, i8**) // CHECK: entry: // CHECK-NEXT: [[FIELDS:%.*]] = alloca [3 x i8**] // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* %0 to [[INT]]* // CHECK-NEXT: [[FIELDS_DEST:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] {{10|13}} // CHECK-NEXT: [[FIELDS_ADDR:%.*]] = bitcast [3 x i8**]* [[FIELDS]] to i8* // CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 {{12|24}}, i8* [[FIELDS_ADDR]]) // CHECK-NEXT: [[FIELDS_PTR:%.*]] = getelementptr inbounds [3 x i8**], [3 x i8**]* [[FIELDS]], i32 0, i32 0 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319) // CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1 // CHECK-NEXT: [[RESULT:%.*]] = icmp ule [[INT]] [[STATUS]], 63 // CHECK-NEXT: br i1 [[RESULT]], label %dependency-satisfied, label %metadata-dependencies.cont // CHECK: dependency-satisfied: // -- ClassLayoutFlags = 0x100 (HasStaticVTable) // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 3, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]]) // CHECK-NEXT: [[INITDEP_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[INITDEP_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1 // CHECK-NEXT: [[INITDEP_PRESENT:%.*]] = icmp eq %swift.type* [[INITDEP_METADATA]], null // CHECK-NEXT: br i1 [[INITDEP_PRESENT]], label %dependency-satisfied1, label %metadata-dependencies.cont // CHECK: dependency-satisfied1: // CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}} // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd" // CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}} // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd" // CHECK: br label %metadata-dependencies.cont // CHECK: metadata-dependencies.cont: // CHECK-NEXT: [[PENDING_METADATA:%.*]] = phi %swift.type* [ [[SIZE_METADATA]], %entry ], [ [[INITDEP_METADATA]], %dependency-satisfied ], [ null, %dependency-satisfied1 ] // CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 63, %entry ], [ [[INITDEP_STATUS]], %dependency-satisfied ], [ 0, %dependency-satisfied1 ] // CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[PENDING_METADATA]], 0 // CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1 // CHECK-NEXT: ret %swift.metadata_response [[T1]] // ClassWithResilientProperty method lookup function // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience26ClassWithResilientPropertyCMu"(%swift.type*, %swift.method_descriptor*) // CHECK-NEXT: entry: // CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast (<{{.*}}>* @"$s16class_resilience26ClassWithResilientPropertyCMn" to %swift.type_descriptor*)) // CHECK-NEXT: ret i8* [[RESULT]] // CHECK-NEXT: } // ClassWithResilientlySizedProperty metadata initialization function // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience33ClassWithResilientlySizedPropertyCMr"(%swift.type*, i8*, i8**) // CHECK: entry: // CHECK-NEXT: [[FIELDS:%.*]] = alloca [2 x i8**] // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* %0 to [[INT]]* // CHECK-NEXT: [[FIELDS_DEST:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] {{10|13}} // CHECK-NEXT: [[FIELDS_ADDR:%.*]] = bitcast [2 x i8**]* [[FIELDS]] to i8* // CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 {{8|16}}, i8* [[FIELDS_ADDR]]) // CHECK-NEXT: [[FIELDS_PTR:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* [[FIELDS]], i32 0, i32 0 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct9RectangleVMa"([[INT]] 319) // CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1 // CHECK-NEXT: [[RESULT:%.*]] = icmp ule [[INT]] [[STATUS]], 63 // CHECK-NEXT: br i1 [[RESULT]], label %dependency-satisfied, label %metadata-dependencies.cont // CHECK: dependency-satisfied: // -- ClassLayoutFlags = 0x100 (HasStaticVTable) // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 2, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]]) // CHECK-NEXT: [[INITDEP_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[INITDEP_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1 // CHECK-NEXT: [[INITDEP_PRESENT:%.*]] = icmp eq %swift.type* [[INITDEP_METADATA]], null // CHECK-NEXT: br i1 [[INITDEP_PRESENT]], label %dependency-satisfied1, label %metadata-dependencies.cont // CHECK: dependency-satisfied1: // CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}} // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd" // CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}} // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd" // CHECK: br label %metadata-dependencies.cont // CHECK: metadata-dependencies.cont: // CHECK-NEXT: [[PENDING_METADATA:%.*]] = phi %swift.type* [ [[SIZE_METADATA]], %entry ], [ [[INITDEP_METADATA]], %dependency-satisfied ], [ null, %dependency-satisfied1 ] // CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 63, %entry ], [ [[INITDEP_STATUS]], %dependency-satisfied ], [ 0, %dependency-satisfied1 ] // CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[PENDING_METADATA]], 0 // CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1 // CHECK-NEXT: ret %swift.metadata_response [[T1]] // ClassWithResilientlySizedProperty method lookup function // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMu"(%swift.type*, %swift.method_descriptor*) // CHECK-NEXT: entry: // CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast (<{{.*}}>* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMn" to %swift.type_descriptor*)) // CHECK-NEXT: ret i8* [[RESULT]] // CHECK-NEXT: } // ResilientChild metadata initialization function // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience14ResilientChildCMr"(%swift.type*, i8*, i8**) // Initialize field offset vector... // CHECK: call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 0, [[INT]] 1, i8*** {{.*}}, [[INT]]* {{.*}}) // CHECK: ret %swift.metadata_response // ResilientChild method lookup function // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience14ResilientChildCMu"(%swift.type*, %swift.method_descriptor*) // CHECK-NEXT: entry: // CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast (<{{.*}}>* @"$s16class_resilience14ResilientChildCMn" to %swift.type_descriptor*)) // CHECK-NEXT: ret i8* [[RESULT]] // CHECK-NEXT: } // ResilientChild.field setter dispatch thunk // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience14ResilientChildC5fields5Int32VvsTj"(i32, %T16class_resilience14ResilientChildC* swiftself) // CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T16class_resilience14ResilientChildC, %T16class_resilience14ResilientChildC* %1, i32 0, i32 0, i32 0 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s16class_resilience14ResilientChildCMo", i32 0, i32 0) // CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{8|16}} // CHECK-NEXT: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[ISA]] to i8* // CHECK-NEXT: [[VTABLE_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[METADATA_OFFSET]] // CHECK-NEXT: [[VTABLE_OFFSET_ADDR:%.*]] = bitcast i8* [[VTABLE_OFFSET_TMP]] to void (i32, %T16class_resilience14ResilientChildC*)** // CHECK-NEXT: [[METHOD:%.*]] = load void (i32, %T16class_resilience14ResilientChildC*)*, void (i32, %T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]] // CHECK-NEXT: call swiftcc void [[METHOD]](i32 %0, %T16class_resilience14ResilientChildC* swiftself %1) // CHECK-NEXT: ret void // ResilientGenericChild metadata initialization function // CHECK-LABEL: define internal %swift.type* @"$s16class_resilience21ResilientGenericChildCMi"(%swift.type_descriptor*, i8**, i8*) // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8* %2) // CHECK: ret %swift.type* [[METADATA]] // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience21ResilientGenericChildCMr" // CHECK-SAME: (%swift.type* [[METADATA:%.*]], i8*, i8**) // CHECK: call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* [[METADATA]], [[INT]] 0, // CHECK: ret %swift.metadata_response // ResilientGenericChild method lookup function // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience21ResilientGenericChildCMu"(%swift.type*, %swift.method_descriptor*) // CHECK-NEXT: entry: // CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast (<{{.*}}>* @"$s16class_resilience21ResilientGenericChildCMn" to %swift.type_descriptor*)) // CHECK-NEXT: ret i8* [[RESULT]] // CHECK-NEXT: }
f1496fb7255ceff8e8285f65622b1d3d
53.679931
254
0.68872
false
false
false
false
visenze/visearch-sdk-swift
refs/heads/master
ViSearchSDK/ViSearchSDKTests/ViGroupResultTest.swift
mit
1
// // ViGroupResultTest.swift // ViSearchSDKTests // // Created by visenze on 19/3/21. // import XCTest @testable import ViSearchSDK class ViGroupResultTest: XCTestCase { private let RESPONSE: String = """ [{ "group_by_value": "Pomelo", "result": [ { "product_id": "POMELO2-AF-SG_b28d580ccf5dfd999d1006f15f773bb371542559", "main_image_url": "http://d3vhkxmeglg6u9.cloudfront.net/img/p/2/2/1/8/0/6/221806.jpg", "data": { "link": "https://iprice.sg/r/p/?_id=b28d580ccf5dfd999d1006f15f773bb371542559", "product_name": "Skrrrrt Cropped Graphic Hoodie Light Grey", "sale_price": { "currency": "SGD", "value": "44.0" } } }, { "product_id": "POMELO2-AF-SG_43d7a0fb6e12d1f1079e6efb38b9d392fa135cdd", "main_image_url": "http://d3vhkxmeglg6u9.cloudfront.net/img/p/1/6/2/3/2/1/162321.jpg", "data": { "link": "https://iprice.sg/r/p/?_id=43d7a0fb6e12d1f1079e6efb38b9d392fa135cdd", "product_name": "Premium Twisted Cold Shoulder Top Pink", "sale_price": { "currency": "SGD", "value": "54.0" } } } ] }] """; override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testParse() { let groupObjects = ViProductSearchResponse.parseGroupResults(RESPONSE) XCTAssertEqual(groupObjects.isEmpty, false) XCTAssertNotNil(groupObjects[0]) XCTAssertEqual(groupObjects[0].groupByValue, "Pomelo") XCTAssertEqual(groupObjects[0].results.count, 2) let result = groupObjects[0].results[1] XCTAssertEqual(result.productId, "POMELO2-AF-SG_43d7a0fb6e12d1f1079e6efb38b9d392fa135cdd") XCTAssertEqual(result.mainImageUrl, "http://d3vhkxmeglg6u9.cloudfront.net/img/p/1/6/2/3/2/1/162321.jpg") let data = result.data let link = data["link"] as! String XCTAssertEqual(link, "https://iprice.sg/r/p/?_id=43d7a0fb6e12d1f1079e6efb38b9d392fa135cdd") let productName = data["product_name"] as! String XCTAssertEqual(productName, "Premium Twisted Cold Shoulder Top Pink") let price = data["sale_price"] as! Dictionary<String,String> let currency = price["currency"] XCTAssertEqual(currency, "SGD") let value = price["value"] XCTAssertEqual(value, "54.0") } }
3702883df7cccfbb45da42c3293dc937
31.650602
112
0.561624
false
true
false
false
timestocome/swiftFFT
refs/heads/master
SwiftFFT/BarGraphView.swift
mit
1
// // BarGraphView.swift // Sounds // // Created by Linda Cobb on 10/10/14. // Copyright (c) 2014 TimesToCome Mobile. All rights reserved. // import Foundation import UIKit class BarGraphView : UIView { // graph dimensions var area: CGRect! var maxPoints = 128 var height: CGFloat! let barWidth = 2.0 as CGFloat var bar:CGRect! // incoming data to graph var dataArrayX:[Float]! // graph data points var x: CGFloat = 0.0 var previousX:CGFloat = 0.0 var mark:CGFloat = 0.0 required init( coder aDecoder: NSCoder ){ super.init(coder: aDecoder) } override init(frame:CGRect){ super.init(frame:frame) } // get graph size and set up data array func setupGraphView() { area = frame height = CGFloat(area.size.height) dataArrayX = [Float](count:maxPoints, repeatedValue: 0.0) } func addX(x: [Float]){ // scale incoming data // stuff the scaled data in the array dataArrayX = x // update graph setNeedsDisplay() } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSetFillColor(context, [1.0, 0.0, 0.0, 1.0]) for i in 1..<maxPoints { mark = CGFloat(i) * 10.0 // plot x bar = CGRectMake(mark, height, 8.0, CGFloat(-dataArrayX[i])) UIRectFill(bar) } } }
7ea63addc21935713bd301544af511d1
16.157895
75
0.525153
false
false
false
false
LipliStyle/Liplis-iOS
refs/heads/master
Liplis/ObjLiplisTouch.swift
mit
1
// // ObjLiplisTouch.swift // Liplis // // タッチ設定管理クラス // touch.xmlのインスタンス // //アップデート履歴 // 2015/04/16 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // 2015/05/16 ver1.4.0 リファクタリング // // Created by sachin on 2015/04/16. // Copyright (c) 2015年 sachin. All rights reserved. // import Foundation class ObjLiplisTouch : NSObject, NSXMLParserDelegate { ///========================== /// 内容 internal var touchDefList : Array<ObjTouch>! ///========================== /// タッチおしゃべり中 internal var touchChatting : Bool! = false; ///========================== /// フラグ internal var checkFlg : Bool! = false; ///=========================================== /// スキンファイル読み込み完了フラグ internal var loadDefault : Bool! = false //================================= //XML操作一時変数 internal var _ParseKey: String! = "" internal var _touch : ObjTouch! //============================================================ // //初期化処理 // //============================================================ /** デフォルトイニシャライザ */ internal init(url : NSURL) { super.init() self.initList() //ロードXML self.loadXml(url) } /** リストの初期化 */ internal func initList() { self.touchDefList = Array<ObjTouch>() } //============================================================ // //XMLロード // //============================================================ /** XMLのロード */ internal func loadXml(url : NSURL) { let parser : NSXMLParser? = NSXMLParser(contentsOfURL: url) if parser != nil { parser!.delegate = self parser!.parse() } else { } } /** 読み込み開始処理完了時処理 */ internal func parserDidStartDocument(parser: NSXMLParser) { //結果格納リストの初期化(イニシャラいざで初期化しているので省略) } /** 更新処理 */ internal func parserDidEndDocument(parser: NSXMLParser) { // 画面など、他オブジェクトを更新する必要がある場合はここに記述する(必要ないので省略) } /** タグの読み始めに呼ばれる */ internal func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI : String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { _ParseKey = elementName if elementName == "touchDiscription" {_touch = ObjTouch()} } /** タグの最後で呼ばれる */ internal func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "touchDiscription" {touchDefList.append(_touch)} self._ParseKey = "" } /** パースする。 */ internal func parser(parser: NSXMLParser, foundCharacters value: String) { if (self._ParseKey == "name") { self._touch!.name = value } else if (self._ParseKey == "type") { self._touch!.type = Int(value) } else if (self._ParseKey == "sens") { self._touch!.sens = Int(value) } else if (self._ParseKey == "top") { self._touch!.top = Int(value) } else if (self._ParseKey == "left") { self._touch!.left = Int(value) } else if (self._ParseKey == "bottom") { self._touch!.bottom = Int(value) } else if (self._ParseKey == "right") { self._touch!.right = Int(value) } else if (self._ParseKey == "chat") { self._touch!.setChat(value) } else { // nop } } /// <summary> /// タッチチェック /// </summary> /// <returns></returns> internal func checkTouch(x : Int, y : Int, checkList : Array<String> )->ObjTouchResult { let result : ObjTouchResult = ObjTouchResult(obj: nil) for msg in self.touchDefList { if !checkListContains(msg.name,checkList: checkList) { continue } if msg.sens == 0 { continue } let res : Int = msg.checkTouch(x, y: y) if (res == 2) { result.result = 2 result.obj = msg return result } else if (res == 1) { result.result = 1 } } return result; } /// <summary> /// クリックチェック /// </summary> /// <returns></returns> internal func checkClick(x : Int, y : Int, checkList : Array<String>, mode : Int)->ObjTouchResult { let result : ObjTouchResult = ObjTouchResult(obj: nil) for msg in self.touchDefList { if !checkListContains(msg.name,checkList: checkList) { continue } if mode == msg.type { result.result = mode if (msg.checkClick(x, y: y)) { result.obj = msg return result } } } return result } internal func checkListContains(target : String, checkList : Array<String>) -> Bool { for item : String in checkList { if String(item) == String(target) { return true } } return false } }
9d226bb92319b388c3fc9c542ee8f14a
22.940171
133
0.446349
false
false
false
false
annatovstyga/REA-Schedule
refs/heads/master
Raspisaniye/MenuViewController.swift
mit
1
// // MenuViewController.swift // Raspisaniye // // Created by _ on 9/7/16. // Copyright © 2016 rGradeStd. All rights reserved. // import UIKit import CCAutocomplete import RealmSwift class MenuViewController: UIViewController ,UITextFieldDelegate { var searchArray = [String]() @IBOutlet var menuItems:MenuItems? var isFirstLoad = true override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if self.isFirstLoad { self.isFirstLoad = false Autocomplete.setupAutocompleteForViewcontroller(self) } } @IBAction func change_group(_ sender: AnyObject) { defaults.set(false, forKey: "isLogined") if let vc = storyboard?.instantiateViewController(withIdentifier: "LoginViewOneControllerID") as? LoginViewOneController { self.view.window?.rootViewController = vc;//making a view to root view self.view.window?.makeKeyAndVisible() } } @IBOutlet weak var textField: UITextField! @IBOutlet weak var group_name: UILabel! override func viewDidLoad() { super.viewDidLoad() textField.delegate = self textField.autocorrectionType = .no menuItems?.addLabel() group_name.text = defaults.value(forKey: "subjectName") as? String } override func viewWillAppear(_ animated: Bool) { let realm = try! Realm() let results = realm.objects(Unit.self) for item in results{ self.searchArray.append(item.name) } } @IBAction func searchClick(_ sender: Any) { view.endEditing(true) let realm = try! Realm() let predicate = NSPredicate(format: "name = %@",self.textField.text!) let lectorIDObject = realm.objects(Unit.self).filter(predicate) let lectorID = lectorIDObject.first //получем расписание по поиску и парсим его в реалм search if(lectorID != nil){ DispatchQueue.main.async(execute: { updateSchedule(itemID: (lectorID?.ID)!,type:(lectorID?.type)!, successBlock: { successBlock in DispatchQueue.main.async(execute: { parse(jsonDataList!,realmName:"search", successBlock: { (parsed) in self.performSegue(withIdentifier: "searchSegue", sender: lectorID) }) }) }) }) }else{ showWarning() } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func showWarning() { let alertController = UIAlertController(title: "Не найдено ничего по запросу!", message: "Попробуйте проверить имя/название", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: nil)) self.present(alertController, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if(segue.identifier == "searchSegue"){ let unit:Unit = sender as! Unit let dsVC = segue.destination as! MMSwiftTabBarController dsVC.realmName = "search" dsVC.searchName = unit.name if (unit.type) == 1 { dsVC.type = unit.type }else { dsVC.type = 0 } } } } extension MenuViewController: AutocompleteDelegate { func autoCompleteTextField() -> UITextField { return self.textField } func autoCompleteThreshold(_ textField: UITextField) -> Int { self.textField.adjustsFontSizeToFitWidth = true return 2 } func autoCompleteItemsForSearchTerm(_ term: String) -> [AutocompletableOption] { var filteredCountries = [String]() //FIXIT переименовать переменные filteredCountries = self.searchArray.filter { (country) -> Bool in return country.lowercased().contains(term.lowercased()) } let countriesAndFlags: [AutocompletableOption] = filteredCountries.map { ( country) -> AutocompleteCellData in var country = country country.replaceSubrange(country.startIndex...country.startIndex, with: String(country.characters[country.startIndex]).capitalized) return AutocompleteCellData(text: country, image: UIImage(named: country)) }.map( { $0 as AutocompletableOption }) return countriesAndFlags } func autoCompleteHeight() -> CGFloat { return self.view.frame.height / 3.0 } func didSelectItem(_ item: AutocompletableOption) { self.textField.text = item.text view.endEditing(true) let realm = try! Realm() let predicate = NSPredicate(format: "name = %@",self.textField.text!) let lectorIDObject = realm.objects(Unit.self).filter(predicate) let lectorID = lectorIDObject.first //получем расписание по поиску и парсим его в реалм search if(lectorID != nil){ DispatchQueue.main.async(execute: { updateSchedule(itemID: (lectorID?.ID)!,type:(lectorID?.type)!, successBlock: { successBlock in DispatchQueue.main.async(execute: { parse(jsonDataList!,realmName:"search", successBlock: { (parsed) in self.performSegue(withIdentifier: "searchSegue", sender: lectorID) }) }) }) }) self.textField.text = "" }else{ showWarning() } } }
5cf79a2a4e89eb1d125d8ceb0cfe8f16
32.491525
142
0.603914
false
false
false
false
jboullianne/EndlessTunes
refs/heads/master
EndlessSoundFeed/LoginViewController.swift
gpl-3.0
1
// // LoginViewController.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 5/1/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import UIKit import FirebaseAuth import SkyFloatingLabelTextField import SwiftOverlays class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet var usernameField: SkyFloatingLabelTextField! @IBOutlet var passwordField: SkyFloatingLabelTextField! @IBOutlet var errorLabel:UILabel! @IBOutlet var newAccountButton: UIButton! @IBOutlet var loginButton: UIButton! @IBOutlet var backgroundImage: UIImageView! @IBOutlet var signupStackView: UIStackView! @IBOutlet var loginStackView: UIStackView! @IBOutlet var newEmailField: SkyFloatingLabelTextField! @IBOutlet var newDisplayNameField: SkyFloatingLabelTextField! @IBOutlet var newPasswordField: SkyFloatingLabelTextField! @IBOutlet var cancelSignupButton: UIButton! @IBOutlet var signupButton: UIButton! var gradientLayer:CAGradientLayer! override func viewDidLoad() { super.viewDidLoad() usernameField.delegate = self passwordField.delegate = self newEmailField.delegate = self newDisplayNameField.delegate = self newPasswordField.delegate = self passwordField.returnKeyType = .done newPasswordField.returnKeyType = .done passwordField.isSecureTextEntry = true newPasswordField.isSecureTextEntry = true /* if (FIRAuth.auth()?.currentUser) != nil { let manager = AccountManager.sharedInstance manager.loginUser(user: FIRAuth.auth()!.currentUser!) self.performSegue(withIdentifier: "LoginUser", sender: self) } */ newAccountButton.layer.cornerRadius = 3.0 loginButton.layer.cornerRadius = 3.0 cancelSignupButton.layer.cornerRadius = 3.0 signupButton.layer.cornerRadius = 3.0 cancelSignupButton.backgroundColor = UIColor.clear cancelSignupButton.layer.borderWidth = 2.0 cancelSignupButton.layer.borderColor = UIColor.white.cgColor let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = backgroundImage.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundImage.addSubview(blurEffectView) prepViews() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //createGradientLayer() usernameField.text = "" passwordField.text = "" newEmailField.text = "" newDisplayNameField.text = "" newPasswordField.text = "" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func prepViews() { backgroundImage.alpha = 0 loginStackView.alpha = 0 signupStackView.alpha = 0 } func showViews() { UIView.animate(withDuration: 0.5) { self.backgroundImage.alpha = 1.0 self.loginStackView.alpha = 1.0 } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func createGradientLayer(){ gradientLayer = CAGradientLayer() gradientLayer.frame = self.view.bounds let startColor = UIColor(red: 30/255, green: 60/255, blue: 109/255, alpha: 1.0).cgColor let endColor = UIColor(red: 11/255, green: 24/255, blue: 45/255, alpha: 1.0).cgColor gradientLayer.colors = [startColor, endColor] self.view.layer.insertSublayer(gradientLayer, at: 0) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == passwordField { textField.resignFirstResponder() return true } if textField == usernameField { let _ = passwordField.becomeFirstResponder() return true } if textField == newEmailField { newDisplayNameField.becomeFirstResponder() return true } if textField == newDisplayNameField { newPasswordField.becomeFirstResponder() return true } if textField == newPasswordField { newPasswordField.resignFirstResponder() return true } return true } @IBAction func createAccountPressed(_ sender: Any) { print("CREATE NEW ACCOUNT PRESSED") errorLabel.isHidden = true UIView.animate(withDuration: 0.3, animations: { self.loginStackView.alpha = 0.0 }) { (success) in if success { UIView.animate(withDuration: 0.3, animations: { self.signupStackView.alpha = 1.0 }) } } } @IBAction func loginPressed(_ sender: Any) { let email = usernameField.text let pass = passwordField.text self.showWaitOverlay() let manager = AccountManager.sharedInstance manager.loginUser(email: email, pass: pass) { (success, errorString) in if(success){ print("Successful Login: After Login Pressed") self.removeAllOverlays() self.performSegue(withIdentifier: "LoginUser", sender: self) } else { self.removeAllOverlays() self.errorLabel.isHidden = false self.errorLabel.text = errorString } } print("LOGIN PRESSED") } @IBAction func cancelPressed(_ sender: Any) { self.errorLabel.isHidden = true UIView.animate(withDuration: 0.3, animations: { self.signupStackView.alpha = 0.0 }) { (success) in if success { UIView.animate(withDuration: 0.3, animations: { self.loginStackView.alpha = 1.0 }) } } } @IBAction func signupPressed(_ sender: Any) { print("SIGNUP BUTTON PRESSED") self.showWaitOverlay() let email = newEmailField.text let pass = newPasswordField.text let displayName = newDisplayNameField.text if let count = displayName?.characters.count { if count <= 5 { self.errorLabel.isHidden = false self.errorLabel.text = "Display Name Too Short" self.removeAllOverlays() return } } if (email != nil) && (pass != nil) { FIRAuth.auth()?.createUser(withEmail: email!, password: pass!, completion: { (user, error) in if let err = error as NSError? { if let code = FIRAuthErrorCode(rawValue: err.code) { switch code { case .errorCodeInvalidEmail: //Invalid Email print("Invalid Email") self.errorLabel.isHidden = false self.errorLabel.text = "Invalid Email" case .errorCodeEmailAlreadyInUse: self.errorLabel.isHidden = false self.errorLabel.text = "Email Already In Use" case .errorCodeWeakPassword: self.errorLabel.isHidden = false self.errorLabel.text = "Too Weak of Password" default: print("Error Code Not Recognized") self.errorLabel.isHidden = false self.errorLabel.text = "Error Creating Account" } self.removeAllOverlays() } }else{ print("Firebase Signup Success") let changeRequest = FIRAuth.auth()?.currentUser?.profileChangeRequest() changeRequest?.displayName = displayName changeRequest?.commitChanges { (error) in if(error != nil){ print("Error Updating Display Name") self.removeAllOverlays() } else{ let manager = AccountManager.sharedInstance manager.setupNewUser(user: user!) self.removeAllOverlays() self.performSegue(withIdentifier: "SignupUser", sender: self) } } } }) } } @IBAction func backgroundTapped(_ sender: Any) { endUserInput() } @IBAction func logoTapped(_ sender: Any) { endUserInput() } func endUserInput() { if usernameField.isFirstResponder { usernameField.resignFirstResponder() }else if passwordField.isFirstResponder { passwordField.resignFirstResponder() }else{ } } // 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. print(segue.identifier!) } }
13b83a44ec8edb8c631c7af8c1723d3b
31.964052
106
0.561019
false
false
false
false
Mobilette/MobiletteFoundation
refs/heads/master
Source/MBOAuthCredential.swift
mit
1
// // MBOAuthCredential.swift // MBOAuthCredential // // Created by Romain ASNAR on 19/11/15. // Copyright © 2015 Romain ASNAR. All rights reserved. // import Foundation import Security open class MBOAuthCredential: NSObject, NSCoding { // MARK: - Type fileprivate struct CodingKeys { static let base = Bundle.main.bundleIdentifier! + "." static let userIdentifier = base + "user_identifier" static let accessToken = base + "access_token" static let expirationDate = base + "expiration_date" static let refreshToken = base + "refresh_token" } // MARK: - Property open var userIdentifier: String? = nil open var token: String? { if self.isExpired() { return nil } return self.accessToken } open var refreshToken: String? = nil open var expirationDate: Date? = nil open var archivedOAuthCredential: Data { return NSKeyedArchiver.archivedData(withRootObject: self) } fileprivate var accessToken: String? = nil // MARK: - Life cycle public init(userIdentifier: String, accessToken: String, refreshToken: String, expirationDate: Date? = nil ) { self.userIdentifier = userIdentifier self.accessToken = accessToken self.refreshToken = refreshToken self.expirationDate = expirationDate } // MARK: - NSCoding protocol @objc required public init?(coder decoder: NSCoder) { self.userIdentifier = decoder.decodeObject(forKey: CodingKeys.userIdentifier) as? String self.accessToken = decoder.decodeObject(forKey: CodingKeys.accessToken) as? String self.expirationDate = decoder.decodeObject(forKey: CodingKeys.expirationDate) as? Date self.refreshToken = decoder.decodeObject(forKey: CodingKeys.refreshToken) as? String } @objc open func encode(with coder: NSCoder) { coder.encode(self.userIdentifier, forKey: CodingKeys.userIdentifier) coder.encode(self.accessToken, forKey: CodingKeys.accessToken) coder.encode(self.expirationDate, forKey: CodingKeys.expirationDate) coder.encode(self.refreshToken, forKey: CodingKeys.refreshToken) } // MARK: - Archiving open func storeToKeychain() throws { guard let userIdentifier = self.userIdentifier, let _ = self.accessToken, let _ = self.refreshToken else { throw MBOAuthCredentialError.badCredentials } let query = [ "\(kSecClass)" : "\(kSecClassGenericPassword)", "\(kSecAttrAccount)" : userIdentifier, "\(kSecValueData)" : self.archivedOAuthCredential ] as NSDictionary let secItemDeleteStatus = SecItemDelete(query as CFDictionary) if secItemDeleteStatus != noErr && secItemDeleteStatus != errSecItemNotFound { throw MBOAuthCredentialError.unknown(Int(secItemDeleteStatus)) } let secItemAddStatus = SecItemAdd(query as CFDictionary, nil) if secItemAddStatus != noErr { throw MBOAuthCredentialError.unknown(Int(secItemAddStatus)) } let userDefaults = UserDefaults.standard userDefaults.set(userIdentifier, forKey: "mb_user_identifier") let synchronizeResult = userDefaults.synchronize() if synchronizeResult == false { throw MBUserDefaultsError.canNotSynchronizeUserDefault } } open class func retreiveCredential( userIdentifier: String? = nil ) throws -> MBOAuthCredential { let identifier: String if let _userIdentifier = userIdentifier { identifier = _userIdentifier } else { guard let _userIdentifier = self.userIdentifierFromNSUserDefaults() else { throw MBOAuthCredentialError.userIdentifierMissing } identifier = _userIdentifier } let searchQuery = [ "\(kSecClass)" : "\(kSecClassGenericPassword)", "\(kSecAttrAccount)" : identifier, "\(kSecReturnData)" : true ] as NSDictionary var result: AnyObject? let secItemCopyStatus = SecItemCopyMatching(searchQuery, &result) if secItemCopyStatus != noErr { throw MBOAuthCredentialError.unknown(Int(secItemCopyStatus)) } guard let retrievedData = result as? Data else { throw MBOAuthCredentialError.canNotCopy } guard let credential = NSKeyedUnarchiver.unarchiveObject(with: retrievedData) as? MBOAuthCredential else { throw MBOAuthCredentialError.canNotUnarchiveObject } return credential } fileprivate class func userIdentifierFromNSUserDefaults() -> String? { let userDefaults = UserDefaults.standard if let identifier = userDefaults.object(forKey: "mb_user_identifier") as? String { return identifier } return nil } // MARK: - Authentication open func isAuthenticated() -> Bool { let hasAccessToken = (self.accessToken != nil) return (hasAccessToken) && (!self.isExpired()) } open func isExpired() -> Bool { if let expirationDate = self.expirationDate { let today = Date() let isExpired = (expirationDate.compare(today) == ComparisonResult.orderedAscending) return isExpired } return false } } public enum MBOAuthCredentialError: MBError { case unknown(Int) case badCredentials case badResults() case userIdentifierMissing case canNotUnarchiveObject case canNotCopy public var code: Int { switch self { case .unknown: return 1000 case .badCredentials: return 1001 case .badResults: return 1002 case .userIdentifierMissing: return 1003 case .canNotUnarchiveObject: return 1004 case .canNotCopy: return 1005 } } public var domain: String { return "OAuthCredentialDomain" } public var description: String { switch self { case .unknown: return "Unknown error." case .badCredentials: return "Bad credentials." case .badResults: return "Bad results." case .userIdentifierMissing: return "User identifier missing" case .canNotUnarchiveObject: return "Can not unarchive object." case .canNotCopy: return "Can not copy." } } public var reason: String { switch self { case .unknown(let status): return "Security function throw error with status : \(status)." case .badCredentials: return "" case .badResults: return "" case .userIdentifierMissing: return "" case .canNotUnarchiveObject: return "" case .canNotCopy: return "" } } }
e434e90157b95a106b61016141fdf043
29.65272
114
0.603877
false
false
false
false
AaronMT/firefox-ios
refs/heads/master
Client/Frontend/Library/HistoryPanel.swift
mpl-2.0
4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import XCGLogger import WebKit private struct HistoryPanelUX { static let WelcomeScreenItemWidth = 170 static let IconSize = 23 static let IconBorderColor = UIColor.Photon.Grey30 static let IconBorderWidth: CGFloat = 0.5 static let actionIconColor = UIColor.Photon.Grey40 // Works for light and dark theme. } private class FetchInProgressError: MaybeErrorType { internal var description: String { return "Fetch is already in-progress" } } @objcMembers class HistoryPanel: SiteTableViewController, LibraryPanel { enum Section: Int { // Showing showing recently closed, and clearing recent history are action rows of this type. case additionalHistoryActions case today case yesterday case lastWeek case lastMonth static let count = 5 var title: String? { switch self { case .today: return Strings.TableDateSectionTitleToday case .yesterday: return Strings.TableDateSectionTitleYesterday case .lastWeek: return Strings.TableDateSectionTitleLastWeek case .lastMonth: return Strings.TableDateSectionTitleLastMonth default: return nil } } } enum AdditionalHistoryActionRow: Int { case clearRecent case showRecentlyClosedTabs // Use to enable/disable the additional history action rows. static func setStyle(enabled: Bool, forCell cell: UITableViewCell) { if enabled { cell.textLabel?.alpha = 1.0 cell.imageView?.alpha = 1.0 cell.selectionStyle = .default cell.isUserInteractionEnabled = true } else { cell.textLabel?.alpha = 0.5 cell.imageView?.alpha = 0.5 cell.selectionStyle = .none cell.isUserInteractionEnabled = false } } } let QueryLimitPerFetch = 100 var libraryPanelDelegate: LibraryPanelDelegate? var groupedSites = DateGroupedTableData<Site>() var refreshControl: UIRefreshControl? var currentFetchOffset = 0 var isFetchInProgress = false var clearHistoryCell: UITableViewCell? var hasRecentlyClosed: Bool { return profile.recentlyClosedTabs.tabs.count > 0 } lazy var emptyStateOverlayView: UIView = createEmptyStateOverlayView() lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(onLongPressGestureRecognized)) }() // MARK: - Lifecycle override init(profile: Profile) { super.init(profile: profile) [ Notification.Name.FirefoxAccountChanged, Notification.Name.PrivateDataClearedHistory, Notification.Name.DynamicFontChanged, Notification.Name.DatabaseWasReopened ].forEach { NotificationCenter.default.addObserver(self, selector: #selector(onNotificationReceived), name: $0, object: nil) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.accessibilityIdentifier = "History List" tableView.prefetchDataSource = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Add a refresh control if the user is logged in and the control was not added before. If the user is not // logged in, remove any existing control. if profile.hasSyncableAccount() && refreshControl == nil { addRefreshControl() } else if !profile.hasSyncableAccount() && refreshControl != nil { removeRefreshControl() } } // MARK: - Refreshing TableView func addRefreshControl() { let control = UIRefreshControl() control.addTarget(self, action: #selector(onRefreshPulled), for: .valueChanged) refreshControl = control tableView.refreshControl = control } func removeRefreshControl() { tableView.refreshControl = nil refreshControl = nil } func endRefreshing() { // Always end refreshing, even if we failed! refreshControl?.endRefreshing() // Remove the refresh control if the user has logged out in the meantime if !profile.hasSyncableAccount() { removeRefreshControl() } } // MARK: - Loading data override func reloadData() { // Can be called while app backgrounded and the db closed, don't try to reload the data source in this case if profile.isShutdown { return } guard !isFetchInProgress else { return } groupedSites = DateGroupedTableData<Site>() currentFetchOffset = 0 fetchData().uponQueue(.main) { result in if let sites = result.successValue { for site in sites { if let site = site, let latestVisit = site.latestVisit { self.groupedSites.add(site, timestamp: TimeInterval.fromMicrosecondTimestamp(latestVisit.date)) } } self.tableView.reloadData() self.updateEmptyPanelState() if let cell = self.clearHistoryCell { AdditionalHistoryActionRow.setStyle(enabled: !self.groupedSites.isEmpty, forCell: cell) } } } } func fetchData() -> Deferred<Maybe<Cursor<Site>>> { guard !isFetchInProgress else { return deferMaybe(FetchInProgressError()) } isFetchInProgress = true return profile.history.getSitesByLastVisit(limit: QueryLimitPerFetch, offset: currentFetchOffset) >>== { result in // Force 100ms delay between resolution of the last batch of results // and the next time `fetchData()` can be called. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) { self.currentFetchOffset += self.QueryLimitPerFetch self.isFetchInProgress = false } return deferMaybe(result) } } func resyncHistory() { profile.syncManager.syncHistory().uponQueue(.main) { syncResult in self.endRefreshing() if syncResult.isSuccess { self.reloadData() } } } // MARK: - Actions func removeHistoryForURLAtIndexPath(indexPath: IndexPath) { guard let site = siteForIndexPath(indexPath) else { return } profile.history.removeHistoryForURL(site.url).uponQueue(.main) { result in guard site == self.siteForIndexPath(indexPath) else { self.reloadData() return } self.tableView.beginUpdates() self.groupedSites.remove(site) self.tableView.deleteRows(at: [indexPath], with: .right) self.tableView.endUpdates() self.updateEmptyPanelState() if let cell = self.clearHistoryCell { AdditionalHistoryActionRow.setStyle(enabled: !self.groupedSites.isEmpty, forCell: cell) } } } func pinToTopSites(_ site: Site) { _ = profile.history.addPinnedTopSite(site).uponQueue(.main) { result in if result.isSuccess { SimpleToast().showAlertWithText(Strings.AppMenuAddPinToTopSitesConfirmMessage, bottomContainer: self.view) } } } func navigateToRecentlyClosed() { guard hasRecentlyClosed else { return } let nextController = RecentlyClosedTabsPanel(profile: profile) nextController.title = Strings.RecentlyClosedTabsButtonTitle nextController.libraryPanelDelegate = libraryPanelDelegate refreshControl?.endRefreshing() navigationController?.pushViewController(nextController, animated: true) } func showClearRecentHistory() { func remove(hoursAgo: Int) { if let date = Calendar.current.date(byAdding: .hour, value: -hoursAgo, to: Date()) { let types = WKWebsiteDataStore.allWebsiteDataTypes() WKWebsiteDataStore.default().removeData(ofTypes: types, modifiedSince: date, completionHandler: {}) self.profile.history.removeHistoryFromDate(date).uponQueue(.main) { _ in self.reloadData() } } } let alert = UIAlertController(title: Strings.ClearHistoryMenuTitle, message: nil, preferredStyle: .actionSheet) // This will run on the iPad-only, and sets the alert to be centered with no arrow. if let popoverController = alert.popoverPresentationController { popoverController.sourceView = view popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) popoverController.permittedArrowDirections = [] } [(Strings.ClearHistoryMenuOptionTheLastHour, 1), (Strings.ClearHistoryMenuOptionToday, 24), (Strings.ClearHistoryMenuOptionTodayAndYesterday, 48)].forEach { (name, time) in let action = UIAlertAction(title: name, style: .destructive) { _ in remove(hoursAgo: time) } alert.addAction(action) } alert.addAction(UIAlertAction(title: Strings.ClearHistoryMenuOptionEverything, style: .destructive, handler: { _ in let types = WKWebsiteDataStore.allWebsiteDataTypes() WKWebsiteDataStore.default().removeData(ofTypes: types, modifiedSince: .distantPast, completionHandler: {}) self.profile.history.clearHistory().uponQueue(.main) { _ in self.reloadData() } self.profile.recentlyClosedTabs.clearTabs() })) let cancelAction = UIAlertAction(title: Strings.CancelString, style: .cancel) alert.addAction(cancelAction) present(alert, animated: true) } // MARK: - Cell configuration func siteForIndexPath(_ indexPath: IndexPath) -> Site? { // First section is reserved for recently closed. guard indexPath.section > Section.additionalHistoryActions.rawValue else { return nil } let sitesInSection = groupedSites.itemsForSection(indexPath.section - 1) return sitesInSection[safe: indexPath.row] } func configureClearHistory(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { clearHistoryCell = cell cell.textLabel?.text = Strings.HistoryPanelClearHistoryButtonTitle cell.detailTextLabel?.text = "" cell.imageView?.image = UIImage.templateImageNamed("forget") cell.imageView?.tintColor = HistoryPanelUX.actionIconColor cell.imageView?.backgroundColor = UIColor.theme.homePanel.historyHeaderIconsBackground cell.accessibilityIdentifier = "HistoryPanel.clearHistory" var isEmpty = true for i in Section.today.rawValue..<tableView.numberOfSections { if tableView.numberOfRows(inSection: i) > 0 { isEmpty = false } } AdditionalHistoryActionRow.setStyle(enabled: !isEmpty, forCell: cell) return cell } func configureRecentlyClosed(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { cell.accessoryType = .disclosureIndicator cell.textLabel?.text = Strings.RecentlyClosedTabsButtonTitle cell.detailTextLabel?.text = "" cell.imageView?.image = UIImage.templateImageNamed("recently_closed") cell.imageView?.tintColor = HistoryPanelUX.actionIconColor cell.imageView?.backgroundColor = UIColor.theme.homePanel.historyHeaderIconsBackground AdditionalHistoryActionRow.setStyle(enabled: hasRecentlyClosed, forCell: cell) cell.accessibilityIdentifier = "HistoryPanel.recentlyClosedCell" return cell } func configureSite(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { if let site = siteForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell { cell.setLines(site.title, detailText: site.url) cell.imageView?.layer.borderColor = HistoryPanelUX.IconBorderColor.cgColor cell.imageView?.layer.borderWidth = HistoryPanelUX.IconBorderWidth cell.imageView?.contentMode = .center cell.imageView?.setImageAndBackground(forIcon: site.icon, website: site.tileURL) { [weak cell] in cell?.imageView?.image = cell?.imageView?.image?.createScaled(CGSize(width: HistoryPanelUX.IconSize, height: HistoryPanelUX.IconSize)) } } return cell } // MARK: - Selector callbacks func onNotificationReceived(_ notification: Notification) { switch notification.name { case .FirefoxAccountChanged, .PrivateDataClearedHistory: reloadData() if profile.hasSyncableAccount() { resyncHistory() } break case .DynamicFontChanged: reloadData() if emptyStateOverlayView.superview != nil { emptyStateOverlayView.removeFromSuperview() } emptyStateOverlayView = createEmptyStateOverlayView() resyncHistory() break case .DatabaseWasReopened: if let dbName = notification.object as? String, dbName == "browser.db" { reloadData() } default: // no need to do anything at all print("Error: Received unexpected notification \(notification.name)") break } } func onLongPressGestureRecognized(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } if indexPath.section != Section.additionalHistoryActions.rawValue { presentContextMenu(for: indexPath) } } func onRefreshPulled() { refreshControl?.beginRefreshing() resyncHistory() } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return Section.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // First section is for recently closed and always has 1 row. guard section > Section.additionalHistoryActions.rawValue else { return 2 } return groupedSites.numberOfItemsForSection(section - 1) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // First section is for recently closed and has no title. guard section > Section.additionalHistoryActions.rawValue else { return nil } // Ensure there are rows in this section. guard groupedSites.numberOfItemsForSection(section - 1) > 0 else { return nil } return Section(rawValue: section)?.title } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) cell.accessoryType = .none // First section is reserved for recently closed. guard indexPath.section > Section.additionalHistoryActions.rawValue else { cell.imageView?.layer.borderWidth = 0 guard let row = AdditionalHistoryActionRow(rawValue: indexPath.row) else { assertionFailure("Bad row number") return cell } switch row { case .clearRecent: return configureClearHistory(cell, for: indexPath) case .showRecentlyClosedTabs: return configureRecentlyClosed(cell, for: indexPath) } } return configureSite(cell, for: indexPath) } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // First section is reserved for recently closed. defer { tableView.deselectRow(at: indexPath, animated: true) } guard indexPath.section > Section.additionalHistoryActions.rawValue else { switch indexPath.row { case 0: showClearRecentHistory() default: navigateToRecentlyClosed() } return } if let site = siteForIndexPath(indexPath), let url = URL(string: site.url) { if let libraryPanelDelegate = libraryPanelDelegate { libraryPanelDelegate.libraryPanel(didSelectURL: url, visitType: VisitType.typed) } return } print("Error: No site or no URL when selecting row.") } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? UITableViewHeaderFooterView { header.textLabel?.textColor = UIColor.theme.tableView.headerTextDark header.contentView.backgroundColor = UIColor.theme.tableView.headerBackground } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // First section is for recently closed and its header has no view. guard section > Section.additionalHistoryActions.rawValue else { return nil } // Ensure there are rows in this section. guard groupedSites.numberOfItemsForSection(section - 1) > 0 else { return nil } return super.tableView(tableView, viewForHeaderInSection: section) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // First section is for recently closed and its header has no height. guard section > Section.additionalHistoryActions.rawValue else { return 0 } // Ensure there are rows in this section. guard groupedSites.numberOfItemsForSection(section - 1) > 0 else { return 0 } return super.tableView(tableView, heightForHeaderInSection: section) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Intentionally blank. Required to use UITableViewRowActions } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if indexPath.section == Section.additionalHistoryActions.rawValue { return [] } let title = NSLocalizedString("Delete", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.") let delete = UITableViewRowAction(style: .default, title: title, handler: { (action, indexPath) in self.removeHistoryForURLAtIndexPath(indexPath: indexPath) }) return [delete] } // MARK: - Empty State func updateEmptyPanelState() { if groupedSites.isEmpty { if emptyStateOverlayView.superview == nil { tableView.tableFooterView = emptyStateOverlayView } } else { tableView.alwaysBounceVertical = true tableView.tableFooterView = nil } } func createEmptyStateOverlayView() -> UIView { let overlayView = UIView() // overlayView becomes the footer view, and for unknown reason, setting the bgcolor is ignored. // Create an explicit view for setting the color. let bgColor = UIView() bgColor.backgroundColor = UIColor.theme.homePanel.panelBackground overlayView.addSubview(bgColor) bgColor.snp.makeConstraints { make in // Height behaves oddly: equalToSuperview fails in this case, as does setting top.equalToSuperview(), simply setting this to ample height works. make.height.equalTo(UIScreen.main.bounds.height) make.width.equalToSuperview() } let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = Strings.HistoryPanelEmptyStateTitle welcomeLabel.textAlignment = .center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight welcomeLabel.textColor = UIColor.theme.homePanel.welcomeScreenText welcomeLabel.numberOfLines = 0 welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(overlayView) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(overlayView).offset(LibraryPanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView).offset(50) make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth) } return overlayView } override func applyTheme() { emptyStateOverlayView.removeFromSuperview() emptyStateOverlayView = createEmptyStateOverlayView() updateEmptyPanelState() super.applyTheme() } } extension HistoryPanel: UITableViewDataSourcePrefetching { func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { guard !isFetchInProgress, indexPaths.contains(where: shouldLoadRow) else { return } fetchData().uponQueue(.main) { result in if let sites = result.successValue { let indexPaths: [IndexPath] = sites.compactMap({ site in guard let site = site, let latestVisit = site.latestVisit else { return nil } let indexPath = self.groupedSites.add(site, timestamp: TimeInterval.fromMicrosecondTimestamp(latestVisit.date)) return IndexPath(row: indexPath.row, section: indexPath.section + 1) }) self.tableView.insertRows(at: indexPaths, with: .automatic) } } } func shouldLoadRow(for indexPath: IndexPath) -> Bool { guard indexPath.section > Section.additionalHistoryActions.rawValue else { return false } return indexPath.row >= groupedSites.numberOfItemsForSection(indexPath.section - 1) - 1 } } extension HistoryPanel: LibraryPanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { return siteForIndexPath(indexPath) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { guard var actions = getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate) else { return nil } let removeAction = PhotonActionSheetItem(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { _, _ in self.removeHistoryForURLAtIndexPath(indexPath: indexPath) }) let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { _, _ in self.pinToTopSites(site) }) actions.append(pinTopSite) actions.append(removeAction) return actions } }
b2b0d4fd8ec416a2693ef886dd769603
37.24961
156
0.64577
false
false
false
false
i-schuetz/SwiftCharts
refs/heads/master
Examples/Examples/BarsExample.swift
apache-2.0
1
// // BarsExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts // This example uses a normal view generator to create bars. This allows a high degree of customization at view level, since any UIView can be used. // Alternatively it's possible to use ChartBarsLayer (see e.g. implementation of BarsChart for a simple example), which provides more ready to use, bar-specific functionality, but is accordingly more constrained. class BarsExample: UIViewController { fileprivate var chart: Chart? let sideSelectorHeight: CGFloat = 50 fileprivate func barsChart(horizontal: Bool) -> Chart { let tuplesXY = [(2, 8), (4, 9), (6, 10), (8, 12), (12, 17)] func reverseTuples(_ tuples: [(Int, Int)]) -> [(Int, Int)] { return tuples.map{($0.1, $0.0)} } let chartPoints = (horizontal ? reverseTuples(tuplesXY) : tuplesXY).map{ChartPoint(x: ChartAxisValueInt($0.0), y: ChartAxisValueInt($0.1))} let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let generator = ChartAxisGeneratorMultiplier(2) let labelsGenerator = ChartAxisLabelsGeneratorFunc {scalar in return ChartAxisLabel(text: "\(scalar)", settings: labelSettings) } let xGenerator = ChartAxisGeneratorMultiplier(2) let xModel = ChartAxisModel(firstModelValue: 0, lastModelValue: 20, axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: labelSettings)], axisValuesGenerator: xGenerator, labelsGenerator: labelsGenerator) let yModel = ChartAxisModel(firstModelValue: 0, lastModelValue: 20, axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())], axisValuesGenerator: generator, labelsGenerator: labelsGenerator) let barViewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsViewsLayer, chart: Chart) -> UIView? in let bottomLeft = layer.modelLocToScreenLoc(x: 0, y: 0) let barWidth: CGFloat = Env.iPad ? 60 : 30 let settings = ChartBarViewSettings(animDuration: 0.5) let (p1, p2): (CGPoint, CGPoint) = { if horizontal { return (CGPoint(x: bottomLeft.x, y: chartPointModel.screenLoc.y), CGPoint(x: chartPointModel.screenLoc.x, y: chartPointModel.screenLoc.y)) } else { return (CGPoint(x: chartPointModel.screenLoc.x, y: bottomLeft.y), CGPoint(x: chartPointModel.screenLoc.x, y: chartPointModel.screenLoc.y)) } }() return ChartPointViewBar(p1: p1, p2: p2, width: barWidth, bgColor: UIColor.blue.withAlphaComponent(0.6), settings: settings) } let frame = ExamplesDefaults.chartFrame(view.bounds) let chartFrame = chart?.frame ?? CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height - sideSelectorHeight) let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame) let chartPointsLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: barViewGenerator) let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, settings: settings) return Chart( frame: chartFrame, innerFrame: innerFrame, settings: chartSettings, layers: [ xAxisLayer, yAxisLayer, guidelinesLayer, chartPointsLayer ] ) } fileprivate func showChart(horizontal: Bool) { self.chart?.clearView() let chart = barsChart(horizontal: horizontal) view.addSubview(chart.view) self.chart = chart } override func viewDidLoad() { showChart(horizontal: false) if let chart = chart { let sideSelector = DirSelector(frame: CGRect(x: 0, y: chart.frame.origin.y + chart.frame.size.height, width: view.frame.size.width, height: sideSelectorHeight), controller: self) view.addSubview(sideSelector) } } class DirSelector: UIView { let horizontal: UIButton let vertical: UIButton weak var controller: BarsExample? fileprivate let buttonDirs: [UIButton : Bool] init(frame: CGRect, controller: BarsExample) { self.controller = controller horizontal = UIButton() horizontal.setTitle("Horizontal", for: UIControl.State()) vertical = UIButton() vertical.setTitle("Vertical", for: UIControl.State()) buttonDirs = [horizontal : true, vertical : false] super.init(frame: frame) addSubview(horizontal) addSubview(vertical) for button in [horizontal, vertical] { button.titleLabel?.font = ExamplesDefaults.fontWithSize(14) button.setTitleColor(UIColor.blue, for: UIControl.State()) button.addTarget(self, action: #selector(DirSelector.buttonTapped(_:)), for: .touchUpInside) } } @objc func buttonTapped(_ sender: UIButton) { let horizontal = sender == self.horizontal ? true : false controller?.showChart(horizontal: horizontal) } override func didMoveToSuperview() { let views = [horizontal, vertical] for v in views { v.translatesAutoresizingMaskIntoConstraints = false } let namedViews = views.enumerated().map{index, view in ("v\(index)", view) } var viewsDict = Dictionary<String, UIView>() for namedView in namedViews { viewsDict[namedView.0] = namedView.1 } let buttonsSpace: CGFloat = Env.iPad ? 20 : 10 let hConstraintStr = namedViews.reduce("H:|") {str, tuple in "\(str)-(\(buttonsSpace))-[\(tuple.0)]" } let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraints(withVisualFormat: "V:|[\($0.0)]", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDict)} addConstraints(NSLayoutConstraint.constraints(withVisualFormat: hConstraintStr, options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: viewsDict) + vConstraits) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
347c186ea7215341d85ad13371d641b7
42.197674
239
0.617227
false
false
false
false
kstaring/swift
refs/heads/upstream-master
test/SILGen/builtins.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CANONICAL %s import Swift protocol ClassProto : class { } struct Pointer { var value: Builtin.RawPointer } // CHECK-LABEL: sil hidden @_TF8builtins3foo func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 { // CHECK: builtin "cmp_eq_Int1" return Builtin.cmp_eq_Int1(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8load_pod func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins8load_obj func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins12load_raw_pod func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @_TF8builtins12load_raw_obj func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @_TF8builtins8load_gen func load_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}} return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_pod func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_obj func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [take] [[ADDR]] // CHECK-NOT: copy_value [[VAL]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_gen func move_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}} return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_pod func destroy_pod(_ x: Builtin.RawPointer) { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box // CHECK-NOT: pointer_to_address // CHECK-NOT: destroy_addr // CHECK-NOT: destroy_value // CHECK: destroy_value [[XBOX]] : $@box // CHECK-NOT: destroy_value return Builtin.destroy(Builtin.Int64, x) // CHECK: return } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_obj func destroy_obj(_ x: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(Builtin.NativeObject, x) } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_gen func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(T.self, x) } // CHECK-LABEL: sil hidden @_TF8builtins10assign_pod func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { var x = x var y = y // CHECK: alloc_box // CHECK: alloc_box // CHECK-NOT: alloc_box // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value // CHECK: destroy_value // CHECK-NOT: destroy_value Builtin.assign(x, y) // CHECK: return } // CHECK-LABEL: sil hidden @_TF8builtins10assign_obj func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins12assign_tuple func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject), y: Builtin.RawPointer) { var x = x var y = y // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject) // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins10assign_gen func assign_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] {{%.*}} to [[ADDR]] : Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_pod func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: store {{%.*}} to [trivial] [[ADDR]] // CHECK-NOT: destroy_value [[ADDR]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_obj func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK-NOT: load [[ADDR]] // CHECK: store [[SRC:%.*]] to [init] [[ADDR]] // CHECK-NOT: destroy_value [[SRC]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_gen func init_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]] // CHECK: destroy_addr [[OTHER_LOC]] Builtin.initialize(x, y) } class C {} class D {} // CHECK-LABEL: sil hidden @_TF8builtins22class_to_native_object func class_to_native_object(_ c:C) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(c) } // CHECK-LABEL: sil hidden @_TF8builtins23class_to_unknown_object func class_to_unknown_object(_ c:C) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(c) } // CHECK-LABEL: sil hidden @_TF8builtins32class_archetype_to_native_object func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins33class_archetype_to_unknown_object func class_archetype_to_unknown_object<T : C>(_ t: T) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins34class_existential_to_native_object func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins35class_existential_to_unknown_object func class_existential_to_unknown_object(_ t:ClassProto) -> Builtin.UnknownObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.UnknownObject return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins24class_from_native_object func class_from_native_object(_ p: Builtin.NativeObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins25class_from_unknown_object func class_from_unknown_object(_ p: Builtin.UnknownObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins34class_archetype_from_native_object func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins35class_archetype_from_unknown_object func class_archetype_from_unknown_object<T : C>(_ p: Builtin.UnknownObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $T // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins41objc_class_existential_from_native_object func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins42objc_class_existential_from_unknown_object func objc_class_existential_from_unknown_object(_ p: Builtin.UnknownObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $AnyObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins20class_to_raw_pointer func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(t) } protocol CP: class {} func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins18obj_to_raw_pointer func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } // CHECK-LABEL: sil hidden @_TF8builtins22class_from_raw_pointer func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T { return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins20obj_from_raw_pointer func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins28unknown_obj_from_raw_pointer func unknown_obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.UnknownObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.UnknownObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins28existential_from_raw_pointer func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins9gep_raw64 func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int64(p, i) } // CHECK-LABEL: sil hidden @_TF8builtins9gep_raw32 func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int32(p, i) } // CHECK-LABEL: sil hidden @_TF8builtins3gep func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word // CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]] // CHECK: return [[A2P]] return Builtin.gep_Word(p, i, e) } public final class Header { } // CHECK-LABEL: sil hidden @_TF8builtins20allocWithTailElems_1 func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_1(Header.self, n, ty) } // CHECK-LABEL: sil hidden @_TF8builtins20allocWithTailElems_3 func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3) } // CHECK-LABEL: sil hidden @_TF8builtins16projectTailElems func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer { // CHECK: bb0([[ARG1:%.*]] : $Header // CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]] // CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1_COPY]] : $Header // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: destroy_value [[ARG1_COPY]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[A2P]] return Builtin.projectTailElems(h, ty) } // CHECK: } // end sil function '_TF8builtins16projectTailElemsurFT1hCS_6Header2tyMx_Bp' // CHECK-LABEL: sil hidden @_TF8builtins11getTailAddr func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2 // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: return [[A2P]] return Builtin.getTailAddr_Word(start, i, ty1, ty2) } // CHECK-LABEL: sil hidden @_TF8builtins8condfail func condfail(_ i: Builtin.Int1) { Builtin.condfail(i) // CHECK: cond_fail {{%.*}} : $Builtin.Int1 } struct S {} @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} protocol P {} // CHECK-LABEL: sil hidden @_TF8builtins10canBeClass func canBeClass<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(O.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(OP1.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompo = OP1 & OP2 // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(ObjCCompo.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(S.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(C.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(P.self) typealias MixedCompo = OP1 & P // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompo.self) // CHECK: builtin "canBeClass"<T> Builtin.canBeClass(T.self) } // FIXME: "T.Type.self" does not parse as an expression // CHECK-LABEL: sil hidden @_TF8builtins18canBeClassMetatype func canBeClassMetatype<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 0 typealias OT = O.Type Builtin.canBeClass(OT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias OP1T = OP1.Type Builtin.canBeClass(OP1T.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompoT = (OP1 & OP2).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(ObjCCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias ST = S.Type Builtin.canBeClass(ST.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias CT = C.Type Builtin.canBeClass(CT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias PT = P.Type Builtin.canBeClass(PT.self) typealias MixedCompoT = (OP1 & P).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias TT = T.Type Builtin.canBeClass(TT.self) } // CHECK-LABEL: sil hidden @_TF8builtins11fixLifetimeFCS_1CT_ : $@convention(thin) (@owned C) -> () { func fixLifetime(_ c: C) { // CHECK: bb0([[ARG:%.*]] : $C): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: fix_lifetime [[ARG_COPY]] : $C // CHECK: destroy_value [[ARG_COPY]] // CHECK: destroy_value [[ARG]] Builtin.fixLifetime(c) } // CHECK: } // end sil function '_TF8builtins11fixLifetimeFCS_1CT_' // CHECK-LABEL: sil hidden @_TF8builtins20assert_configuration func assert_configuration() -> Builtin.Int32 { return Builtin.assert_configuration() // CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32 // CHECK: return [[APPLY]] : $Builtin.Int32 } // CHECK-LABEL: sil hidden @_TF8builtins17assumeNonNegativeFBwBw func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word { return Builtin.assumeNonNegative_Word(x) // CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word // CHECK: return [[APPLY]] : $Builtin.Word } // CHECK-LABEL: sil hidden @_TF8builtins11autoreleaseFCS_1OT_ : $@convention(thin) (@owned O) -> () { // ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it? // CHECK: bb0([[ARG:%.*]] : $O): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: autorelease_value [[ARG_COPY]] // CHECK: destroy_value [[ARG_COPY]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_TF8builtins11autoreleaseFCS_1OT_' func autorelease(_ o: O) { Builtin.autorelease(o) } // The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during // diagnostics. // CHECK-LABEL: sil hidden @_TF8builtins11unreachable // CHECK: builtin "unreachable"() // CHECK: return // CANONICAL-LABEL: sil hidden @_TF8builtins11unreachableFT_T_ : $@convention(thin) () -> () { func unreachable() { Builtin.unreachable() } // CHECK-LABEL: sil hidden @_TF8builtins15reinterpretCastFTCS_1C1xBw_TBwCS_1DGSqS0__S0__ : $@convention(thin) (@owned C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C) // CHECK: bb0([[ARG1:%.*]] : $C, [[ARG2:%.*]] : $Builtin.Word): // CHECK-NEXT: debug_value // CHECK-NEXT: debug_value // CHECK-NEXT: [[ARG1_COPY1:%.*]] = copy_value [[ARG1]] : $C // CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1_COPY1]] : $C to $Builtin.Word // CHECK-NEXT: [[ARG1_COPY2:%.*]] = copy_value [[ARG1]] : $C // CHECK-NEXT: [[ARG1_COPY2_CASTED:%.*]] = unchecked_ref_cast [[ARG1_COPY2]] : $C to $D // CHECK-NEXT: [[ARG1_COPY3:%.*]] = copy_value [[ARG1]] // CHECK-NEXT: [[ARG1_COPY3_CAST:%.*]] = unchecked_ref_cast [[ARG1_COPY3]] : $C to $Optional<C> // CHECK-NEXT: [[ARG2_OBJ_CASTED:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C // CHECK-NEXT: [[ARG2_OBJ_CASTED_COPIED:%.*]] = copy_value [[ARG2_OBJ_CASTED]] : $C // CHECK-NEXT: destroy_value [[ARG1_COPY1]] // CHECK-NEXT: destroy_value [[ARG1]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_COPY2_CASTED]] : $D, [[ARG1_COPY3_CAST]] : $Optional<C>, [[ARG2_OBJ_CASTED_COPIED:%.*]] : $C) // CHECK: return [[RESULT]] func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) { return (Builtin.reinterpretCast(c) as Builtin.Word, Builtin.reinterpretCast(c) as D, Builtin.reinterpretCast(c) as C?, Builtin.reinterpretCast(x) as C) } // CHECK-LABEL: sil hidden @_TF8builtins19reinterpretAddrOnly func reinterpretAddrOnly<T, U>(_ t: T) -> U { // CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_TF8builtins28reinterpretAddrOnlyToTrivial func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int { // CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]] // CHECK: destroy_addr [[INPUT]] return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_TF8builtins27reinterpretAddrOnlyLoadable func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) { // CHECK: [[BUF:%.*]] = alloc_stack $Int // CHECK: store {{%.*}} to [trivial] [[BUF]] // CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T // CHECK: copy_addr [[RES1]] to [initialization] return (Builtin.reinterpretCast(a) as T, // CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int // CHECK: load [trivial] [[RES]] Builtin.reinterpretCast(b) as Int) } // CHECK-LABEL: sil hidden @_TF8builtins18castToBridgeObject // CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word // CHECK: return [[BO]] func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject { return Builtin.castToBridgeObject(c, w) } // CHECK-LABEL: sil hidden @_TF8builtins23castRefFromBridgeObject // CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C { return Builtin.castReferenceFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_TF8builtins30castBitPatternFromBridgeObject // CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word // CHECK: destroy_value [[BO]] func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word { return Builtin.castBitPatternFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_TF8builtins8pinUnpin // CHECK: bb0([[ARG:%.*]] : $Builtin.NativeObject): // CHECK-NEXT: debug_value func pinUnpin(_ object : Builtin.NativeObject) { // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Builtin.NativeObject // CHECK-NEXT: [[HANDLE:%.*]] = strong_pin [[ARG_COPY]] : $Builtin.NativeObject // CHECK-NEXT: debug_value // CHECK-NEXT: destroy_value [[ARG_COPY]] : $Builtin.NativeObject let handle : Builtin.NativeObject? = Builtin.tryPin(object) // CHECK-NEXT: [[HANDLE_COPY:%.*]] = copy_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: strong_unpin [[HANDLE_COPY]] : $Optional<Builtin.NativeObject> // ==> SEMANTIC ARC TODO: This looks like a mispairing or a weird pairing. Builtin.unpin(handle) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[ARG]] : $Builtin.NativeObject // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // NativeObject // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Optional<Builtin.NativeObject> // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.NativeObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.NativeObject // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject pinned // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Optional<Builtin.NativeObject> // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // NativeObject pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.NativeObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.NativeObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // UnknownObject (ObjC) // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Optional<Builtin.UnknownObject>): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Optional<Builtin.UnknownObject> // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.UnknownObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.UnknownObject // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.UnknownObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.UnknownObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.BridgeObject // CHECK: return func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.BridgeObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull native // CHECK-LABEL: sil hidden @_TF8builtins15isUnique_native // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[CAST:%.*]] = unchecked_addr_cast %0 : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: return func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique_native(&ref)) } // BridgeObject pinned nonNull native // CHECK-LABEL: sil hidden @_TF8builtins23isUniqueOrPinned_native // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[CAST:%.*]] = unchecked_addr_cast %0 : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[CAST]] : $*Builtin.NativeObject // CHECK: return func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned_native(&ref)) } // ---------------------------------------------------------------------------- // Builtin.castReference // ---------------------------------------------------------------------------- class A {} protocol PUnknown {} protocol PClass : class {} // CHECK-LABEL: sil hidden @_TF8builtins19refcast_generic_any // CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject func refcast_generic_any<T>(_ o: T) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins17refcast_class_anyFCS_1APs9AnyObject_ : // CHECK: bb0([[ARG:%.*]] : $A): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_CASTED:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $A to $AnyObject // CHECK: destroy_value [[ARG]] // CHECK: return [[ARG_COPY_CASTED]] // CHECK: } // end sil function '_TF8builtins17refcast_class_anyFCS_1APs9AnyObject_' func refcast_class_any(_ o: A) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins20refcast_punknown_any // CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject func refcast_punknown_any(_ o: PUnknown) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins18refcast_pclass_anyFPS_6PClass_Ps9AnyObject_ : // CHECK: bb0([[ARG:%.*]] : $PClass): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_CAST:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $PClass to $AnyObject // CHECK: destroy_value [[ARG]] // CHECK: return [[ARG_COPY_CAST]] // CHECK: } // end sil function '_TF8builtins18refcast_pclass_anyFPS_6PClass_Ps9AnyObject_' func refcast_pclass_any(_ o: PClass) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins20refcast_any_punknown // CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown func refcast_any_punknown(_ o: AnyObject) -> PUnknown { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins22unsafeGuaranteed_class // CHECK: bb0([[P:%.*]] : $A): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A) // CHECK: [[R:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 0 // CHECK: [[K:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 1 // CHECK: destroy_value [[R]] : $A // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: destroy_value [[P]] // CHECK: return [[P_COPY]] : $A // CHECK: } func unsafeGuaranteed_class(_ a: A) -> A { Builtin.unsafeGuaranteed(a) return a } // CHECK-LABEL: _TF8builtins24unsafeGuaranteed_generic // CHECK: bb0([[P:%.*]] : $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: [[R:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0 // CHECK: [[K:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1 // CHECK: destroy_value [[R]] : $T // CHECK: [[P_RETURN:%.*]] = copy_value [[P]] // CHECK: destroy_value [[P]] // CHECK: return [[P_RETURN]] : $T // CHECK: } func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T { Builtin.unsafeGuaranteed(a) return a } // CHECK_LABEL: sil hidden @_TF8builtins31unsafeGuaranteed_generic_return // CHECK: bb0([[P:%.*]] : $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: [[R]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0 // CHECK: [[K]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1 // CHECK: destroy_value [[P]] // CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8) // CHECK: return [[S]] : $(T, Builtin.Int8) // CHECK: } func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) { return Builtin.unsafeGuaranteed(a) } // CHECK-LABEL: sil hidden @_TF8builtins19unsafeGuaranteedEnd // CHECK: bb0([[P:%.*]] : $Builtin.Int8): // CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8) // CHECK: [[S:%.*]] = tuple () // CHECK: return [[S]] : $() // CHECK: } func unsafeGuaranteedEnd(_ t: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(t) } // CHECK-LABEL: sil hidden @_TF8builtins10bindMemory // CHECK: bb0([[P:%.*]] : $Builtin.RawPointer, [[I:%.*]] : $Builtin.Word, [[T:%.*]] : $@thick T.Type): // CHECK: bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T // CHECK: return {{%.*}} : $() // CHECK: } func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) { Builtin.bindMemory(ptr, idx, T.self) }
cbcf338d9d3b542e3b230b28a91831f0
38.743405
192
0.643577
false
false
false
false
LiuSky/RxExtension
refs/heads/master
RxExtension/Classes/UIScrollView+Refresher.swift
mit
1
// // UIScrollView+Refresher.swift // RxExtension // // Created by LiuSky on 03/19/2020. // Copyright (c) 2020 LiuSky. All rights reserved. // import RxSwift import RxCocoa import MJRefresh import Foundation /// MARK: - 底部刷新状态 public enum BottomRefreshState: Int,CustomStringConvertible { case normal case noMoreData case hidden public var description: String { switch self { case .normal: return "默认状态" case .noMoreData: return "没有更多数据" case .hidden: return "隐藏" } } } // MARK: - Refresh public extension UIScrollView { /// 添加下拉刷新 /// /// - Returns: <#return value description#> func pullToRefresh() -> Observable<Void> { let header = MJRefreshNormalHeader() header.lastUpdatedTimeLabel?.isHidden = true header.isAutomaticallyChangeAlpha = true self.mj_header = header return Observable.create({ observer -> Disposable in self.mj_header?.refreshingBlock = { observer.onNext(Void()) } return Disposables.create() }) } /// 添加加载更多 /// /// - Returns: <#return value description#> func loadMoreFooter() -> Observable<Void> { let refreshFooter = MJRefreshAutoNormalFooter() refreshFooter.setTitle(BottomRefreshState.noMoreData.description, for: .noMoreData) self.mj_footer = refreshFooter return Observable.create({ observer -> Disposable in self.mj_footer?.refreshingBlock = { observer.onNext(Void()) } return Disposables.create() }) } } public extension Reactive where Base: UIScrollView { var isRefreshing: Binder<Bool> { return Binder(self.base) { refreshControl, refresh in if refresh { refreshControl.mj_header?.beginRefreshing() } else { refreshControl.mj_header?.endRefreshing() } } } var bottomRefreshState: Binder<BottomRefreshState> { return Binder(self.base) { refreshControl, state in switch state { case .hidden: refreshControl.mj_footer?.isHidden = true case .noMoreData: refreshControl.mj_footer?.isHidden = false refreshControl.mj_footer?.endRefreshingWithNoMoreData() default: refreshControl.mj_footer?.isHidden = false refreshControl.mj_footer?.resetNoMoreData() } } } } public extension Reactive where Base: MJRefreshComponent { /// 正在刷新(正在上拉/下拉) func refreshing() -> ControlEvent<Void> { let source: Observable<Void> = Observable.create { [weak control = self.base] observer in if let control = control { control.refreshingBlock = { observer.on(.next(())) } } return Disposables.create { } } return ControlEvent(events: source) } }
ccbf5f62562040dd678f7ea81771a126
24.148438
91
0.555141
false
false
false
false
jose-gil/ReaderCodeHelper
refs/heads/master
ReaderCodeHelper/Code/Report.swift
mit
1
// // Report.swift // ReaderCodeHelper // // Created by Jose Gil on 8/1/15. // Copyright (c) 2015 Tollaga Software. All rights reserved. // import UIKit public class Report { public struct Notification { public static let FavoriteUpdate = "ReportNotificationFavoriteUpdate" } private struct Constants { struct DictonaryKey { static let Identifier = "identifier" static let Header = "header" static let Body = "body" } struct UserDefaultsKey { static let Favorites = "ReportConstantsUserDefaultKeyFavorites" } } // MARK: Properties public var identifier: String? public var header: String? public var body: String? private var _favorite: Bool? public var favorite: Bool { get { guard let identifier = identifier else { return false } if let favorite = _favorite { return favorite; } if let favorites = UserDefaults.standard.object(forKey: Constants.UserDefaultsKey.Favorites) as? [String] { return favorites.contains(identifier) } return false } set { guard let identifier = identifier else { return } _favorite = newValue var favorites = UserDefaults.standard.object(forKey: Constants.UserDefaultsKey.Favorites) as? [String] ?? [] if let index = favorites.index(of: identifier) { if !_favorite! { favorites.remove(at: index) } } else { if _favorite! { favorites.append(identifier) } } UserDefaults.standard.set(favorites, forKey: Constants.UserDefaultsKey.Favorites) UserDefaults.standard.synchronize() notifyUpdate() } } // MARK: Lifecycle required public init?(dictionary: [String : String]) { if dictionary[Constants.DictonaryKey.Identifier] == nil { return nil } identifier = dictionary[Constants.DictonaryKey.Identifier] header = dictionary[Constants.DictonaryKey.Header] ?? "" body = dictionary[Constants.DictonaryKey.Body] ?? "" } // MARK: Private private func notifyUpdate () { NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notification.FavoriteUpdate), object: self) } }
ae64cf9608b505f86a468434e771c692
28.033708
120
0.564628
false
false
false
false
Acidburn0zzz/firefox-ios
refs/heads/main
Client/Frontend/Browser/Tabs/TabMoreMenuHeader.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit class TabMoreMenuHeader: UIView { lazy var imageView: UIImageView = { let imgView = UIImageView() imgView.contentMode = .scaleAspectFill imgView.clipsToBounds = true imgView.layer.cornerRadius = TabTrayV2ControllerUX.cornerRadius imgView.layer.borderWidth = 1 imgView.layer.borderColor = UIColor.Photon.Grey30.cgColor return imgView }() lazy var titleLabel: UILabel = { let title = UILabel() title.numberOfLines = 2 title.lineBreakMode = .byTruncatingTail title.font = UIFont.systemFont(ofSize: 17, weight: .regular) title.textColor = UIColor.theme.defaultBrowserCard.textColor return title }() lazy var descriptionLabel: UILabel = { let descriptionText = UILabel() descriptionText.text = String.DefaultBrowserCardDescription descriptionText.numberOfLines = 0 descriptionText.lineBreakMode = .byWordWrapping descriptionText.font = UIFont.systemFont(ofSize: 14, weight: .regular) descriptionText.textColor = UIColor.theme.defaultBrowserCard.textColor return descriptionText }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: .zero) setupView() } private func setupView() { addSubview(imageView) addSubview(titleLabel) addSubview(descriptionLabel) imageView.snp.makeConstraints { make in make.height.width.equalTo(100) make.leading.equalToSuperview().offset(TabTrayV2ControllerUX.screenshotMarginLeftRight) make.top.equalToSuperview().offset(TabTrayV2ControllerUX.screenshotMarginTopBottom) make.bottom.equalToSuperview().offset(-TabTrayV2ControllerUX.screenshotMarginTopBottom) } titleLabel.snp.makeConstraints { make in make.leading.equalTo(imageView.snp.trailing).offset(TabTrayV2ControllerUX.screenshotMarginLeftRight) make.top.equalToSuperview().offset(TabTrayV2ControllerUX.textMarginTopBottom) make.bottom.equalTo(descriptionLabel.snp.top) make.trailing.equalToSuperview().offset(-16) } descriptionLabel.snp.makeConstraints { make in make.leading.equalTo(imageView.snp.trailing).offset(TabTrayV2ControllerUX.screenshotMarginLeftRight) make.trailing.equalToSuperview() make.top.equalTo(titleLabel.snp.bottom).offset(3) make.bottom.equalToSuperview().offset(-TabTrayV2ControllerUX.textMarginTopBottom * CGFloat(titleLabel.numberOfLines)) } applyTheme() } func applyTheme() { if #available(iOS 13.0, *) { backgroundColor = UIColor.secondarySystemGroupedBackground titleLabel.textColor = UIColor.label descriptionLabel.textColor = UIColor.secondaryLabel } else { backgroundColor = UIColor.theme.tableView.rowBackground titleLabel.textColor = UIColor.theme.tableView.rowText descriptionLabel.textColor = UIColor.theme.tableView.rowDetailText } } }
abdd347b2bbd2d36ed3dbb5b1ad3e220
38.943182
129
0.673115
false
false
false
false
tectijuana/patrones
refs/heads/master
Bloque1SwiftArchivado/PracticasSwift/PalaciosArlette/Ejercicio16.swift
gpl-3.0
1
/* Palacios Lee Arlette 12211431 Programa para resolver el siguiente problema: 16. Imprimir sen^2 + cos^2 por x = 5°, 10°, 15°, 20°, ..., 85°. Examinar la salida impresa. */ //Librería para utilizar funciones trigonométricas import Foundation //Declaración de variables var variable: Float = 0 //Se imprime el problema print("Problema \n16. Imprimir sen^2 + cos^2 por x = 5°, 10°, 15°, 20°, ..., 85°. Examinar la salida impresa.") //Se crea el ciclo para realizar la impresión del resultado for index in 1...17 { //Se toma la variable vacía y cada que se cumpla un ciclo se le agregara 5 variable = variable + 5 //Se calcula el seno del número var seno = sin(variable * Float.pi / 180) //Se calcula el coseno del número var coseno = cos(variable * Float.pi / 180) //Se eleva al cuadrado el coseno del número var rescos = pow(coseno,2) //Se eleva al cuadrado el seno del número var resseno = pow(seno,2) //Se realiza la suma var suma = resseno + rescos //Se imprime el resultado de cada número print("\n sen^2(\(variable)) + cos^2(\(variable)) = \(suma)") }
28f683cb212280ac360b1e0ea8b661e7
26.35
111
0.687386
false
false
false
false
noahemmet/Grid
refs/heads/master
Playgrounds/Grid.playground/Contents.swift
apache-2.0
1
//: Playground - noun: a place where people can play import UIKit import Grid import XCPlayground var hue: CGFloat = 0 var saturation: CGFloat = 1 let colorIncrement: CGFloat = 0.02 var incrementing = true let grid = Grid(rows: 20, columns: 20) { (row, column) -> UIColor in let color = UIColor(hue: hue, saturation: saturation, brightness: 1.0, alpha: 1.0) saturation -= colorIncrement * (incrementing ? 1 : -1) hue += colorIncrement * (incrementing ? 1 : -1) if hue >= 1 || hue < 0 { incrementing = !incrementing } return color } let visualizer = GridVisualizer<UIColor>(grid: grid) { index in return grid[index] } XCPlaygroundPage.currentPage.liveView = visualizer.collectionView
9718061798601f9126a4667ab010003d
26.84
83
0.716954
false
false
false
false
mspegagne/ToDoReminder-iOS
refs/heads/master
ToDoReminder/ToDoReminder/AddController.swift
mit
1
// // AddController.swift // ToDoReminder // // Created by Mathieu Spegagne on 05/04/2015. // Copyright (c) 2015 Mathieu Spegagne. All rights reserved. // import UIKit import CoreData class AddController: UIViewController { @IBOutlet weak var titleField: UITextField! @IBOutlet weak var textField: UITextField! @IBOutlet weak var saveButton: UIButton! let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func saveListener(sender: AnyObject) { if let moc = self.managedObjectContext { let task = ToDo.save(moc, newTitle: titleField.text, newText: textField.text) titleField.text = "" textField.text = "" let nextViewController : AnyObject! = storyboard?.instantiateViewControllerWithIdentifier("ToDo") self.presentViewController(nextViewController as UIViewController, animated: true, completion:nil) } } }
dbdc0dcf96589997c471ba3aa284a156
28.575
111
0.672866
false
false
false
false
jkereako/InlinePicker
refs/heads/master
Source/DataSources/TableViewDataSource.swift
mit
1
// // TableViewDataSource.swift // InlinePicker // // Created by Jeffrey Kereakoglow on 4/19/16. // Copyright © 2016 Alexis Digital. All rights reserved. // import UIKit /// Helper object whose responsibility is to build the data source for the table view. final class TableViewDataSource: NSObject { var dataSource: [[CellModelType]] = [[ SubtitleCellModel(rowIndex: 0, title: "Title", subTitle: "subtitle"), SubtitleCellModel(rowIndex: 1, title: "Title", subTitle: "subtitle"), SubtitleCellModel(rowIndex: 2, title: "Title", subTitle: "subtitle"), SubtitleCellModel(rowIndex: 3, title: "Title", subTitle: "subtitle"), SubtitleCellModel(rowIndex: 4, title: "Title", subTitle: "subtitle") ]] private enum CellIdentifier: String { case Subtitle = "subtitle" case Picker = "picker" } private var pickerCellIndexPath: NSIndexPath? convenience init(dataSource: [[CellModelType]], pickerCellIndexPath: NSIndexPath?) { self.init() self.dataSource = dataSource self.pickerCellIndexPath = pickerCellIndexPath } } // MARK: - Data source extension TableViewDataSource: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return dataSource.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource[section].count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellModel = dataSource[indexPath.section][indexPath.row] switch cellModel.state { case .Closed: let cell = tableView.dequeueReusableCellWithIdentifier( CellIdentifier.Subtitle.rawValue, forIndexPath: indexPath ) as! SubtitleCell cell.model = cellModel as? SubtitleCellModel return cell case .Open: let cell = tableView.dequeueReusableCellWithIdentifier( CellIdentifier.Picker.rawValue, forIndexPath: indexPath ) as! PickerCell cell.backgroundColor = .clearColor() cell.contentView.alpha = 0.0 cell.model = cellModel as? PickerViewCellModel return cell } } } // MARK: - Delegate extension TableViewDataSource: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cellModel = dataSource[indexPath.section][indexPath.row] var nextRowIndex = indexPath.row + 1 switch cellModel.state { case .Closed: // If we have a picker view cell open, close it. if let pickerIndexPath = pickerCellIndexPath { // The removal of the picker cell only affects the row indexes of rows beneath it. This // check updates the value of `nextRowIndex` if the selected cell is beneath the picker cell. if indexPath.row > pickerIndexPath.row { nextRowIndex = indexPath.row } UIView.animateWithDuration( 0.15, animations: { let cell = tableView.cellForRowAtIndexPath(self.pickerCellIndexPath!)! cell.backgroundColor = .clearColor() cell.contentView.alpha = 0.0 } ) dataSource[pickerIndexPath.section].removeAtIndex(pickerIndexPath.row) tableView.deleteRowsAtIndexPaths([pickerIndexPath], withRowAnimation: .Top) pickerCellIndexPath = nil // Return early if the selected cell is the owner of the picker cell if pickerIndexPath.section == indexPath.section && pickerIndexPath.row == indexPath.row + 1 { return } } // Open a new picker view cell and save its location. let nextCellModel = PickerViewCellModel(rowIndex: nextRowIndex) dataSource[indexPath.section].insert(nextCellModel, atIndex: nextRowIndex) pickerCellIndexPath = NSIndexPath(forRow: nextRowIndex, inSection: indexPath.section) tableView.insertRowsAtIndexPaths([self.pickerCellIndexPath!], withRowAnimation: .Top) UIView.animateWithDuration( 0.5, animations: { let cell = tableView.cellForRowAtIndexPath(self.pickerCellIndexPath!)! cell.backgroundColor = .whiteColor() cell.contentView.alpha = 1.0 } ) case .Open: // Do not respond to a tap on an open row break } } }
2aaa7ae26e38d509d2dc11c6d54be88c
32.415385
101
0.686464
false
false
false
false
stripe/stripe-ios
refs/heads/master
Stripe/STPShippingMethodTableViewCell.swift
mit
1
// // STPShippingMethodTableViewCell.swift // StripeiOS // // Created by Ben Guo on 8/30/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import PassKit @_spi(STP) import StripePayments import UIKit class STPShippingMethodTableViewCell: UITableViewCell { private var _theme: STPTheme? var theme: STPTheme? { get { _theme } set(theme) { _theme = theme updateAppearance() } } func setShippingMethod(_ method: PKShippingMethod, currency: String) { shippingMethod = method titleLabel?.text = method.label subtitleLabel?.text = method.detail var localeInfo = [ NSLocale.Key.currencyCode.rawValue: currency ] localeInfo[NSLocale.Key.languageCode.rawValue] = NSLocale.preferredLanguages.first ?? "" let localeID = NSLocale.localeIdentifier(fromComponents: localeInfo) let locale = NSLocale(localeIdentifier: localeID) numberFormatter?.locale = locale as Locale let amount = method.amount.stp_amount(withCurrency: currency) if amount == 0 { amountLabel?.text = STPLocalizedString("Free", "Label for free shipping method") } else { let number = NSDecimalNumber.stp_decimalNumber( withAmount: amount, currency: currency ) amountLabel?.text = numberFormatter?.string(from: number) } setNeedsLayout() } private weak var titleLabel: UILabel? private weak var subtitleLabel: UILabel? private weak var amountLabel: UILabel? private weak var checkmarkIcon: UIImageView? private var shippingMethod: PKShippingMethod? private var numberFormatter: NumberFormatter? override init( style: UITableViewCell.CellStyle, reuseIdentifier: String? ) { super.init(style: style, reuseIdentifier: reuseIdentifier) theme = STPTheme() let titleLabel = UILabel() self.titleLabel = titleLabel let subtitleLabel = UILabel() self.subtitleLabel = subtitleLabel let amountLabel = UILabel() self.amountLabel = amountLabel let checkmarkIcon = UIImageView(image: STPLegacyImageLibrary.checkmarkIcon()) self.checkmarkIcon = checkmarkIcon let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.usesGroupingSeparator = true numberFormatter = formatter contentView.addSubview(titleLabel) contentView.addSubview(subtitleLabel) contentView.addSubview(amountLabel) contentView.addSubview(checkmarkIcon) updateAppearance() } override var isSelected: Bool { get { return super.isSelected } set(selected) { super.isSelected = selected updateAppearance() } } @objc func updateAppearance() { contentView.backgroundColor = theme?.secondaryBackgroundColor backgroundColor = UIColor.clear titleLabel?.font = theme?.font subtitleLabel?.font = theme?.smallFont amountLabel?.font = theme?.font titleLabel?.textColor = isSelected ? theme?.accentColor : theme?.primaryForegroundColor amountLabel?.textColor = titleLabel?.textColor var subduedAccentColor: UIColor? if #available(iOS 13.0, *) { subduedAccentColor = UIColor(dynamicProvider: { _ in return self.theme?.accentColor.withAlphaComponent(0.6) ?? UIColor.clear }) } else { subduedAccentColor = theme?.accentColor.withAlphaComponent(0.6) } subtitleLabel?.textColor = isSelected ? subduedAccentColor : theme?.secondaryForegroundColor checkmarkIcon?.tintColor = theme?.accentColor checkmarkIcon?.isHidden = !isSelected } override func layoutSubviews() { super.layoutSubviews() let midY = bounds.midY checkmarkIcon?.frame = CGRect(x: 0, y: 0, width: 14, height: 14) checkmarkIcon?.center = CGPoint( x: bounds.width - 15 - (checkmarkIcon?.bounds.midX ?? 0.0), y: midY ) amountLabel?.sizeToFit() amountLabel?.center = CGPoint( x: (checkmarkIcon?.frame.minX ?? 0.0) - 15 - (amountLabel?.bounds.midX ?? 0.0), y: midY ) let labelWidth = (amountLabel?.frame.minX ?? 0.0) - 30 titleLabel?.sizeToFit() titleLabel?.frame = CGRect( x: 15, y: 8, width: labelWidth, height: titleLabel?.frame.size.height ?? 0.0 ) subtitleLabel?.sizeToFit() subtitleLabel?.frame = CGRect( x: 15, y: bounds.size.height - 8 - (subtitleLabel?.frame.size.height ?? 0.0), width: labelWidth, height: subtitleLabel?.frame.size.height ?? 0.0 ) } required init?( coder aDecoder: NSCoder ) { super.init(coder: aDecoder) } }
6d2e91ae8a524aa70a1156f2f82fe80a
33.469388
100
0.616538
false
false
false
false
TH-Brandenburg/University-Evaluation-iOS
refs/heads/master
EdL/SubmitViewController.swift
apache-2.0
1
// // SubmitViewController.swift // EdL // // Created by Daniel Weis on 17.07.16. // // import UIKit import Alamofire class SubmitViewController: UIViewController { var answersDTO: AnswersDTO! var host: String! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var successLabel: UILabel! @IBOutlet weak var failureLabel: UILabel! @IBOutlet weak var qrcodeButton: UIButton! @IBOutlet weak var retryButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.hidesBackButton = true qrcodeButton.layer.backgroundColor = Colors.blue.CGColor qrcodeButton.layer.cornerRadius = 5 retryButton.layer.backgroundColor = Colors.blue.CGColor retryButton.layer.cornerRadius = 5 } override func viewDidAppear(animated: Bool) { self.submit() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func retry(sender: UIButton) { submit() } func submit(){ self.retryButton.hidden = true print("Answers:\n\(answersDTO.toJsonString())") let answers = answersDTO.toJsonString() let images = Helper.zipImages() if images != nil { Alamofire.upload(.POST, "\(self.host)/v1/answers", multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: answers.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: "answers-dto", mimeType: "text/plain; charset=UTF-8") multipartFormData.appendBodyPart(data: images!, name: "images", fileName: "images.zip", mimeType: "multipart/form-data") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in switch response.result { case .Success: Helper.deleteAll() self.failureLabel.hidden = true self.successLabel.hidden = false case .Failure(let error): print(error) self.retryButton.hidden = false self.failureLabel.hidden = false self.successLabel.hidden = true } debugPrint(response) self.activityIndicator?.stopAnimating() } case .Failure(let encodingError): print(encodingError) self.retryButton.hidden = false self.failureLabel.hidden = false self.successLabel.hidden = true } } ) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
2131eab3a4d26a55d13b01cbc87259d4
37.695238
149
0.483141
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
MGDS_Swift/MGDS_Swift/Class/Extesion/Category(扩展)/Array+Extension.swift
mit
2
// // Array+Extension.swift // ProductionReport // // Created by i-Techsys.com on 16/12/22. // Copyright © 2016年 i-Techsys. All rights reserved. // let part = [82, 58, 76, 49, 88, 90].partitionBy{$0 < 60} // part // ([58, 49], [82, 76, 88, 90]) import UIKit // MARK: - 数组过滤 extension Sequence{ /// 然后依次取出原来序列中的元素,根据过滤结果将它放到第一个或第二个部分中。 func anotherPartitionBy(fu: (Self.Iterator.Element)->Bool)->([Self.Iterator.Element],[Self.Iterator.Element]){ return (self.filter(fu),self.filter({!fu($0)})) } typealias Element = Self.Iterator.Element // func partitionBy(fu: (Element)->Bool)->([Element],[Element]){ // var first=[Element]() // var second=[Element]() // for el in self { // if fu(el) { // first.append(el) // }else{ // second.append(el) // } // } // return (first,second) // } /// 第三种方法才实现了 然后依次取出原来序列中的元素,根据过滤结果将它放到第一个或第二个部分中。 // var part3 = [82, 58, 76, 49, 88, 90].reduce( ([],[]), { // (a:([Int],[Int]),n:Int) -> ([Int],[Int]) in // (n<60) ? (a.0+[n],a.1) : (a.0,a.1+[n]) // }) } extension Array { subscript(input: [Int]) -> ArraySlice<Element> { get { var result = ArraySlice<Element>() for i in input { assert(i < self.count, "Index out of range") result.append(self[i]) } return result } set { for (index,i) in input.enumerated() { assert(i < self.count, "Index out of range") self[i] = newValue[index] } } } func test() { var arr = [1,2,3,4,5] print(arr[[0,2,3]]) //[1,3,4] arr[[0,2,3]] = [-1,-3,-4] print(arr) //[-1,2,-3,-4,5] } } // MARK: - 最小值和最大值 的获取 extension Array { //Find the minimum of an array of Ints // [10,-22,753,55,137,-1,-279,1034,77].sorted().first // [10,-22,753,55,137,-1,-279,1034,77].reduce(Int.max, min) // [10,-22,753,55,137,-1,-279,1034,77].min() //Find the maximum of an array of Ints // [10,-22,753,55,137,-1,-279,1034,77].sorted().last // [10,-22,753,55,137,-1,-279,1034,77].reduce(Int.min, max) // [10,-22,753,55,137,-1,-279,1034,77].max() // 我们使用 filter 方法判断一条推文中是否至少含有一个被选中的关键字: // let words = ["Swift","iOS","cocoa","OSX","tvOS"] // let tweet = "This is an example tweet larking about Swift" // // let valid = words.first(where: {tweet.contains($0)})?.isEmpty // 使用析构交换元组中的值 // var a=1,b=2 // // (a,b) = (b,a) } // MARK: - for循环遍历 extension Sequence { /* 一、 stride(from: 0, to: colors.count, by: 2) 返回以0开始到5的数字(上限不包含5),步长为2。对于 for-loop,这是一个好的替代。 二、 如果上限必须包含进来,这里有另外一种函数格式: stride(from: value, through: value, by: value) 。第二个参数的标签是 through , 这个标签是用以指明是包含上限的。 */ /* let numbers = [1, 6, 2, 0, 7], nCount = numbers.count var index = 0 while (index < nCount && numbers[index] != 0) { print(numbers[index]) index += 1 } */ }
4c39d984d0a84093a33062e762233f52
26.929204
114
0.511724
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/combination-sum.swift
mit
2
/** * https://leetcode.com/problems/combination-sum/ * * */ class Solution { func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { var ret: Set<[Int]> = [] process(&ret, [], target, candidates) return Array(ret) } /// Knapsack Problem /// Unlimit use of items in the back. /// fileprivate func process(_ solution: inout Set<[Int]>, _ result: [Int], _ target: Int, _ candidate: [Int]) { if 0 == target { solution.insert(result.sorted()) return } for index in 0 ..< candidate.count { if target >= candidate[index] { process(&solution, result + [candidate[index]], target - candidate[index], candidate) } } } } class Solution { func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { var result = [[Int]]() var current = [Int]() let cand = candidates.sorted() if target >= cand[0] { for n in 1 ... Int(target / cand[0]) { dfs(cand, target, 0, 0, n, &current, &result) } } return result } fileprivate func dfs(_ candidates: [Int], _ target: Int, _ start: Int, _ deepth: Int, _ maxDeepth: Int, _ current: inout [Int], _ result: inout [[Int]]) { if deepth == maxDeepth { if target == 0 { result.append(current) } return } for index in start ..< candidates.count { if candidates[index] > target { break } current.append(candidates[index]) dfs(candidates, target - candidates[index], index, deepth + 1, maxDeepth, &current, &result) current.removeLast() } } }
9a3664f4e30c2d183e2fb940e5325dcf
30.034483
158
0.505
false
false
false
false
kyouko-taiga/anzen
refs/heads/master
Sources/anzen/ConsoleLogger.swift
apache-2.0
1
import AnzenLib import AST import Dispatch import Interpreter import Parser import Sema import SystemKit import Utils public struct ConsoleLogger: Logger { public init(console: Console = System.err) { self.console = console } public let console: Console private var messages: [String] = [] private let messageQueue = DispatchQueue(label: "messageQueue") public func log(_ text: String) { messageQueue.sync { self.console.write(text) } } public func error(_ err: Error) { switch err { case let parseError as ParseError: log(describe(parseError)) case let runtimeError as RuntimeError: log(describe(runtimeError)) default: log("error:".styled("bold,red") + " \(err)\n") } } public func describe(_ err: ParseError) -> String { let range = err.range let filename = ((range.start.source as? TextFile)?.path).map { $0.relative(to: .workingDirectory).pathname } ?? "<unknown>" let heading = "\(filename)::\(range.start.line):\(range.start.column): ".styled("bold") + "error: ".styled("bold,red") + "\(err.cause)\n" return heading + describe(range) } public func describe(_ err: ASTError) -> String { let range = err.node.range let filename = ((range.start.source as? TextFile)?.path).map { $0.relative(to: .workingDirectory).pathname } ?? "<unknown>" var heading = "\(filename)::\(range.start.line):\(range.start.column): ".styled("bold") + "error:".styled("bold,red") switch err.cause { case let semaError as SAError: heading += "\(semaError)\n" default: heading += "\(err.cause)\n" } return heading + describe(range) } /// Logs the given type solver error. public func describe(_ err: SolverFailure) -> String { return "error: ".styled("bold,red") + "type error\n" } public func describe(_ err: RuntimeError) -> String { if let range = err.range { let filename = ((range.start.source as? TextFile)?.path).map { $0.relative(to: .workingDirectory).pathname } ?? "<unknown>" return "\(filename)::\(range.start.line):\(range.start.column): ".styled("bold") + "error: ".styled("bold,red") + "\(err.message)\n" + describe(range) } else { return "<unknown>::".styled("bold") + "error: ".styled("bold,red") + "\(err.message)\n" } } public func describe(_ range: SourceRange) -> String { guard let lines = try? range.start.source.read(lines: range.start.line) else { return "" } guard lines.count == range.start.line else { return "" } let snippet = lines.last! + "\n" let leading = String(repeating: " ", count: range.start.column - 1) var cursor = "" if (range.start.line == range.end.line) && (range.end.column - range.start.column > 1) { let length = range.end.column - range.start.column cursor += String(repeating: "~", count: length) + "\n" } else { cursor += "^\n" } return snippet + leading + cursor.styled("red") } }
5b6e915cbff475416e63a62f18d7b010
27.254545
93
0.603925
false
false
false
false
imindeu/iMindLib.swift
refs/heads/master
Source/iMindLib/Extensions/UIImageView+Extensions.swift
mit
1
// // UIImageView+Extensions.swift // iMindLib // // Created by David Frenkel on 13/02/2017. // Copyright © 2017 iMind. All rights reserved. // #if !os(macOS) && !os(Linux) && !os(watchOS) import Foundation import UIKit extension UIImageView { /// Flashes the UIImageView by animating the alpha property with a 0.4 duration. /// - parameter startAlpha: A CGFLoat representing the start alpha. Default 1.0 /// - parameter endAlpha: A CGFloat representing the end alpha of the animation. Default 0.0 func flashView(startAlpha: CGFloat = 1.0, endAlpha: CGFloat = 0.0) { self.alpha = startAlpha UIView.animate(withDuration: 0.4, delay: 0, options: [.repeat, .autoreverse], animations: { self.alpha = endAlpha }) } /// Makes the UIImageView a circular shape. A border, border width and border color can be set /// - parameter bordered: A Bool to set if the UIImageView should have a border. Default true. /// - parameter borderWidh: A CGFloat that the border width should be, if bordered parameter is true. Default: 2.5. /// - parameter borderColor: A UIColor object that the border color should be. Default is white. func circleShape(bordered: Bool = true, borderWidth: CGFloat = 2.5, borderColor: UIColor = .white) { self.contentMode = .scaleAspectFill self.layer.borderWidth = bordered ? borderWidth : 0.0 self.layer.borderColor = borderColor.cgColor self.layer.cornerRadius = self.frame.size.width / 2 self.clipsToBounds = true } } #endif
6d248fef481d3197c8a5d7b15b39af82
38.425
119
0.680406
false
false
false
false
RyoAbe/PARTNER
refs/heads/master
PARTNER/PARTNER/Core/Model/Status/Status.swift
gpl-3.0
1
// // Status.swift // PARTNER // // Created by RyoAbe on 2015/03/11. // Copyright (c) 2015年 RyoAbe. All rights reserved. // import Foundation class Status: NSObject, NSCoding { let types: StatusTypes! let date: NSDate! init(types: StatusTypes, date: NSDate){ self.types = types self.date = date } required init(coder aDecoder: NSCoder) { let typesNumber = aDecoder.decodeObjectForKey("types") as! NSNumber types = StatusTypes(rawValue: typesNumber.integerValue) date = aDecoder.decodeObjectForKey("date") as! NSDate super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(NSNumber(integer: types.rawValue), forKey: "types") aCoder.encodeObject(date, forKey: "date") } }
efdf5701369eabec15ce8094958315ba
25.433333
79
0.65404
false
false
false
false
kuangniaokuang/Cocktail-Pro
refs/heads/master
smartmixer/smartmixer/Common/Stars.swift
apache-2.0
1
// // Stars.swift // smartmixer // // Created by Koulin Yuan on 8/17/14. // Copyright (c) 2014 Smart Group. All rights reserved. // import UIKit @IBDesignable class Stars : UIView { @IBOutlet weak var star1: UIImageView! @IBOutlet weak var star2: UIImageView! @IBOutlet weak var star3: UIImageView! @IBOutlet weak var star4: UIImageView! @IBOutlet weak var star5: UIImageView! @IBInspectable var value: Int = 3 { didSet { refreshTo(value) } } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if let touch: UITouch = touches.anyObject() as? UITouch { for index in 1...5 { let tview = self.valueForKey("star\(index)") as UIView! if tview.pointInside(touch.locationInView(tview), withEvent: event) { refreshTo(index) break } } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { dealWith(touches, withEvent: event) { index in self.refreshTo(index) } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { dealWith(touches, withEvent: event) { index in self.value = index } } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { dealWith(touches, withEvent: event) { index in self.refreshTo(index) } } func refreshTo(value: Int) { if value < 0 || value > 5 { return } for index in 0...value { (self.valueForKey("star\((index+1))") as UIImageView!)?.image = UIImage(named: "star_on.png") } for index in (value + 1)..<5 { (self.valueForKey("star\((index+1))") as UIImageView!)?.image = UIImage(named: "star.png") } } func dealWith(touches: NSSet!, withEvent event: UIEvent!, callback: (index: Int) -> ()) { if let touch: UITouch = touches?.anyObject() as? UITouch { for index in 1...5 { let tview = self.valueForKey("star\(index)") as UIView! if tview.pointInside(touch.locationInView(tview), withEvent: event) { callback(index: index) break } } } } }
0b043adc92a29cc22ec84fe5835c7e7c
27.976471
105
0.535526
false
false
false
false
seanwoodward/IBAnimatable
refs/heads/master
IBAnimatable/TintDesignable.swift
mit
1
// // Created by Jake Lin on 11/24/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit public protocol TintDesignable { /** Opacity in tint Color (White): from 0 to 1 */ var tintOpacity: CGFloat { get set } /** Opacity in shade Color (Black): from 0 to 1 */ var shadeOpacity: CGFloat { get set } /** tone color */ var toneColor: UIColor? { get set } /** Opacity in tone color: from 0 to 1 */ var toneOpacity: CGFloat { get set } } public extension TintDesignable where Self: UIView { /** configTintedColor method, should be called in layoutSubviews() method */ public func configTintedColor() { if !tintOpacity.isNaN && tintOpacity >= 0 && tintOpacity <= 1 { addColorSubview(UIColor.whiteColor(), opacity: tintOpacity) } if !shadeOpacity.isNaN && shadeOpacity >= 0 && shadeOpacity <= 1 { addColorSubview(UIColor.blackColor(), opacity: shadeOpacity) } if let unwrappedToneColor = toneColor { if !toneOpacity.isNaN && toneOpacity >= 0 && toneOpacity <= 1 { addColorSubview(unwrappedToneColor, opacity: toneOpacity) } } } private func addColorSubview(color: UIColor, opacity: CGFloat) { let subview = UIView(frame: self.bounds) subview.backgroundColor = color subview.alpha = opacity if layer.cornerRadius > 0 { subview.layer.cornerRadius = layer.cornerRadius } subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.insertSubview(subview, atIndex: 0) } }
74a306106d78283fb6265805cc44894b
24.622951
72
0.65579
false
false
false
false
xiaoyouPrince/DYLive
refs/heads/master
DYLive/DYLive/Classes/Main/View/PageContentView.swift
mit
1
// // PageContentView.swift // DYLive // // Created by 渠晓友 on 2017/4/4. // Copyright © 2017年 xiaoyouPrince. All rights reserved. // /* 页面UI分析 1.内部传入几个对应的自控制器,有父控制器统一管理 2.具体展示通过collectionView来展示每个子控制器的view 3.父控制器来统一管理和调节 titleView 和 contentView的逻辑 */ import UIKit private let cellID : String = "CellID" protocol PageContentViewDelegate : class { func pageContentView(_ contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } // MARK:-类的声明 class PageContentView: UIView { // MARK:-定义属性 fileprivate var childVcs : [UIViewController] fileprivate weak var parentVc : UIViewController? //防止强引用导致循环引用 fileprivate var startOffsetX : CGFloat = 0; weak var delegate : PageContentViewDelegate? fileprivate var isForbidScrollDelegate : Bool = false // MARK:-闭包加载collectionView -- 闭包内要对self进行弱化引用,防止循环引用 fileprivate lazy var collectionView : UICollectionView = {[weak self] in // 1.创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: (self?.bounds)!, collectionViewLayout: layout) collectionView.collectionViewLayout = layout collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false // 设置数据源代理-并注册 collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID) return collectionView }() // MARK:-自定义构造行数 init(frame: CGRect, childVcs : [UIViewController] , parentVc : UIViewController) { self.childVcs = childVcs self.parentVc = parentVc // 自定义构造函数必须显式调用 父类的对应方法 super.init(frame:frame) // MARK:-创建UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 设置UI extension PageContentView{ fileprivate func setupUI() { for childVc in childVcs { // 1.添加子控制器 self.parentVc?.addChild(childVc) // 2.设置内部的collectionview addSubview(collectionView) } } } // MARK: - 遵守collectionVIew的DataSource代理 extension PageContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.复用cell let cell : UICollectionViewCell = collectionView .dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) // 2.设置cell内部view for view in cell.contentView.subviews{ view.removeFromSuperview() } let childVc = childVcs[indexPath.item] cell.contentView.addSubview(childVc.view) return cell } } // MARK: - 遵守collectionView的Delegate方法 extension PageContentView : UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate { return } // 1.定义需要获取的数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 左滑 // 1.计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } // 4.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { // 右滑 // 1.计算progress progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) // 2.计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) // 3.计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } // 3.将progress/sourceIndex/targetIndex传递给titleView delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } // MARK:-对外暴露的方法 extension PageContentView{ // 告知它滚到哪个控制器去 func setCurrnetIndex(currentIndex : Int) { isForbidScrollDelegate = true // 当外界点击的时候禁用 // 实际上修改collectionView的offsetx let positionX = CGFloat(currentIndex) * self.frame.width collectionView.setContentOffset(CGPoint(x:positionX,y:0), animated: false) } }
ed8828a62f057a43eda3948d8111d26b
26.557143
122
0.608778
false
false
false
false
vimeo/VimeoUpload
refs/heads/develop
VimeoUpload/Upload/Extensions/NSURL+Upload.swift
mit
1
// // NSURL+Upload.swift // VimeoUpload // // Created by Hanssen, Alfie on 10/16/15. // Copyright © 2015 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation #if os(iOS) import MobileCoreServices #elseif os(OSX) import CoreServices #endif public extension URL { static func uploadURL(documentsFolderURL: URL? = nil, withFileName filename: String, fileType: String) throws -> URL { let url = URL.uploadDirectory(documentsFolderURL: documentsFolderURL) if FileManager.default.fileExists(atPath: url.path) == false { try FileManager.default.createDirectory(atPath: url.path, withIntermediateDirectories: true, attributes: nil) } let unmanagedTag = UTTypeCopyPreferredTagWithClass(fileType as CFString, kUTTagClassFilenameExtension)! let ext = unmanagedTag.takeRetainedValue() as String let path = url.appendingPathComponent(filename).appendingPathExtension(ext) return path } static func uploadDirectory(documentsFolderURL: URL? = nil) -> URL { let documentsURL: URL if let documentsFolderURL = documentsFolderURL { documentsURL = documentsFolderURL } else { do { documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) } catch { fatalError("Failure: Documents folder does not exist.") } } return documentsURL.appendingPathComponent("uploader").appendingPathComponent("videos") } }
fcceadbb7efbdfc887017d2005108b21
36.053333
140
0.680461
false
false
false
false
gaelfoppolo/handicarparking
refs/heads/master
HandiParking/HandiParking/BaseTableView.swift
gpl-3.0
1
// // BaseTableView.swift // HandiCarParking // // Created by Gaël on 11/03/2015. // Copyright (c) 2015 KeepCore. All rights reserved. // /// ViewController commune pour partager un prototype d'UITableViewCell commune entre les sous classes import UIKit class BaseTableViewController: UITableViewController { // MARK: Types struct Constants { struct Nib { static let name = "TableCell" } struct TableViewCell { static let identifier = "cellID" } } override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: Constants.Nib.name, bundle: nil) // Requis si nos sous classes utilisent dequeueReusableCellWithIdentifier:forIndexPath: tableView.registerNib(nib, forCellReuseIdentifier: Constants.TableViewCell.identifier) } /** Configure la cellule avec les données de la place :param: cell la cellule à remplir avec les données :param: place les données utilisées pour remplir */ func configureCell(cell: UITableViewCell, forText text: NSAttributedString) { //cell.textLabel?.text = place.name cell.textLabel?.attributedText = text cell.imageView?.image = UIImage(named: "marker") } }
2ea658c5da4d2f1f424fe21c5bc1beb8
27.717391
102
0.64697
false
false
false
false
allevato/SwiftCGI
refs/heads/master
Sources/SwiftCGI/BufferingInputStream.swift
apache-2.0
1
// Copyright 2015 Tony Allevato // // 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. /// An input stream that internally loads chunks of data into an internal buffer and serves read /// requests from it to improve performance. public class BufferingInputStream: InputStream { /// The default size of the buffer. private static let defaultBufferSize = 16384 /// The input stream from which this buffering stream reads its input. private let inputStream: InputStream /// The buffer that holds data read from the underlying stream. private var inputBuffer: [UInt8] /// The number of bytes in the input buffer that are actually filled with valid data. private var inputBufferCount: Int /// The index into the buffer at which the next data will be read. private var inputBufferOffset: Int /// Creates a new buffering input stream that reads from the given input stream, optionally /// specifying the internal buffer size. public init( inputStream: InputStream, bufferSize: Int = BufferingInputStream.defaultBufferSize) { self.inputStream = inputStream inputBuffer = [UInt8](count: bufferSize, repeatedValue: 0) inputBufferCount = 0 inputBufferOffset = 0 } public func read(inout buffer: [UInt8], offset: Int, count: Int) throws -> Int { if count == 0 { return 0 } // Repeatedly read from the stream until we've gotten the requested number of bytes or reached // the end of the stream. var readSoFar = 0 while readSoFar < count { let remaining = count - readSoFar do { let readThisTime = try readFromUnderlyingStream( &buffer, offset: offset + readSoFar, count: remaining) readSoFar += readThisTime if readThisTime == 0 { return readSoFar } } catch IOError.EOF { // Only allow EOF to be thrown if it's the first time we're trying to read. If we get an EOF // from the underlying stream after successfully reading some data, we just return the count // that was actually read. if readSoFar > 0 { return readSoFar } throw IOError.EOF } } return readSoFar } public func seek(offset: Int, origin: SeekOrigin) throws -> Int { // TODO: Support seeking. throw IOError.Unsupported } public func close() { inputStream.close() } /// Reads data at most once from the underlying stream, filling the buffer if necessary. /// /// - Parameter buffer: The array into which the data should be written. /// - Parameter offset: The byte offset in `buffer` into which to start writing data. /// - Parameter count: The maximum number of bytes to read from the stream. /// - Returns: The number of bytes that were actually read. This can be less than the requested /// number of bytes if that many bytes are not available, or 0 if the end of the stream is /// reached. /// - Throws: `IOError` if an error other than reaching the end of the stream occurs. private func readFromUnderlyingStream( inout buffer: [UInt8], offset: Int, count: Int) throws -> Int { var available = inputBufferCount - inputBufferOffset if available == 0 { // If there is nothing currently in the buffer and the requested count is at least as large as // the buffer, then just read the data directly from the underlying stream. This is acceptable // since the purpose of the buffer is to reduce I/O thrashing, and breaking a larger read into // multiple smaller ones would have the opposite effect. if count >= inputBuffer.count { return try inputStream.read(&buffer, offset: offset, count: count) } // Fill the buffer by reading from the underlying stream. inputBufferCount = try inputStream.read(&inputBuffer, offset: 0, count: inputBuffer.count) inputBufferOffset = 0 available = inputBufferCount if inputBufferCount == 0 { throw IOError.EOF } } let countToCopy = (available < count) ? available : count buffer.replaceRange(offset..<offset + countToCopy, with: inputBuffer[inputBufferOffset..<inputBufferOffset + countToCopy]) inputBufferOffset += countToCopy return countToCopy } }
a2745e206b0e5de517a53fe0e4c6e7fd
37.387097
100
0.694328
false
false
false
false
KordianKL/SongGenius
refs/heads/master
Song Genius/Song.swift
mit
1
// // Song.swift // Song Genius // // Created by Kordian Ledzion on 14.06.2017. // Copyright © 2017 KordianLedzion. All rights reserved. // import RealmSwift class Song: Object { dynamic var name: String = "" dynamic var artist: String = "" dynamic var releaseYear: String = "" dynamic var primaryKey: String = "" dynamic var url: String = "" convenience init(name: String, artist: String, releaseYear: String, url: String = "") { self.init() self.name = name self.artist = artist self.releaseYear = releaseYear self.primaryKey = "\(self.name) by \(self.artist)" self.url = url } convenience init(songEntity: SongEntity) { self.init() self.name = songEntity.name self.artist = songEntity.artist self.releaseYear = songEntity.releaseYear self.primaryKey = songEntity.primaryKey self.url = songEntity.url } var entity: SongEntity { return SongEntity(artist: self.artist, name: self.name, releaseYear: self.releaseYear, url: self.url) } }
6906f99d9e03c011560f7b92ffc45dfe
26.75
109
0.621622
false
false
false
false
imxieyi/iosu
refs/heads/master
iosu/StoryBoard/Renderer/Commands/SBMoveY.swift
mit
1
// // SBMoveY.swift // iosu // // Created by xieyi on 2017/5/16. // Copyright © 2017年 xieyi. All rights reserved. // import Foundation import SpriteKit import SpriteKitEasingSwift class SBMoveY:SBCommand,SBCAction { var starty:Double var endy:Double init(easing:Int,starttime:Int,endtime:Int,starty:Double,endy:Double) { self.starty=StoryBoard.conv(y:starty) self.endy=StoryBoard.conv(y:endy) super.init(type: .moveY, easing: easing, starttime: starttime, endtime: endtime) } func toAction() -> SKAction { if starttime==endtime { return SKAction.moveTo(y: CGFloat(endy), duration: 0) } return SKEase.moveY(easeFunction: easing.function, easeType: easing.type, time: duration, from: CGFloat(starty), to: CGFloat(endy)) /*return SKAction.customAction(withDuration: duration, actionBlock: { (node:SKNode, elapsedTime:CGFloat) -> Void in let from=CGPoint(x: node.position.x, y: CGFloat(self.starty)) let to=CGPoint(x: node.position.x, y: CGFloat(self.endy)) node.run(SKEase.move(easeFunction: self.easing.function, easeType: self.easing.type, time: self.duration, from: from, to: to)) })*/ } }
819a164945c03513c65369a0ffdc6860
33.555556
139
0.663183
false
false
false
false
wuyezhiguhun/DDMusicFM
refs/heads/master
DDMusicFM/DDFound/View/DDHeaderIconView.swift
apache-2.0
1
// // DDHeaderIconView.swift // DDMusicFM // // Created by yutongmac on 2017/9/14. // Copyright © 2017年 王允顶. All rights reserved. // import UIKit class DDHeaderIconView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.iconImageView) self.addSubview(self.titleLabel) self.addViewConstrains() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addViewConstrains() -> Void { self.iconImageView.snp.makeConstraints { (make) in // make.center.equalTo(self) make.centerX.equalTo(self.snp.centerX).offset(0) make.centerY.equalTo(self.snp.centerY).offset(-10) make.width.equalTo(43) make.height.equalTo(43) } self.titleLabel.snp.makeConstraints { (make) in make.top.equalTo(self.iconImageView.snp.bottom).offset(10) make.left.equalTo(self).offset(0) make.right.equalTo(self).offset(0) make.height.equalTo(20) } } var _iconImageView: UIImageView? var iconImageView: UIImageView { get { if _iconImageView == nil { _iconImageView = UIImageView() } return _iconImageView! } set { _iconImageView = newValue } } var _titleLabel: UILabel? var titleLabel: UILabel { get { if _titleLabel == nil { _titleLabel = UILabel() _titleLabel?.font = UIFont.systemFont(ofSize: 13) _titleLabel?.backgroundColor = UIColor.clear _titleLabel?.textColor = UIColor.black _titleLabel?.textAlignment = NSTextAlignment.center } return _titleLabel! } set { _titleLabel = newValue } } var _detailModel: DDFindDiscoverDetailModel? var detailModel: DDFindDiscoverDetailModel { get { if _detailModel == nil { _detailModel = DDFindDiscoverDetailModel() } return _detailModel! } set { _detailModel = newValue self.titleLabel.text = _detailModel?.title self.iconImageView.sd_setImage(with: URL(string: (_detailModel?.coverPath!)!), completed: nil) } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
fd0579be6b5f86a2ff8225a48391ce0f
28.296703
106
0.565266
false
false
false
false
SteeweGriffin/STWCollectionView
refs/heads/master
Example/Example/SettingViewController.swift
mit
1
// // SettingViewController.swift // STWCollectionView // // Created by Steewe MacBook Pro on 16/05/17. // Copyright © 2017 Steewe. All rights reserved. // import UIKit import STWCollectionView enum SettingItemType:String { case spacing = "Spacing" case hPadding = "H-Padding" case vPadding = "V-Padding" case fixedCellsNumber = "Fix-Cells" case fixedSizeWidth = "Fix-Width" case fixedSizeHeight = "Fix-Height" case forceCenterd = "Force Centered" } protocol SettingsDeleagte:class { func didChangeValue(item:SettingItemView) } extension String { func getCGFloat() -> CGFloat { guard let number = NumberFormatter().number(from: self) else { return 0.0 } return CGFloat(truncating: number) } } class SettingItemView: UIView { private let input = UITextField() private let switcher = UISwitch() weak var delegate: SettingsDeleagte? var type:SettingItemType? convenience init(type: SettingItemType) { self.init(frame: CGRect.zero) self.type = type self.translatesAutoresizingMaskIntoConstraints = false self.createUI() } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func createUI(){ //Label let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = self.type?.rawValue self.addSubview(label) if self.type! == .forceCenterd { self.switcher.translatesAutoresizingMaskIntoConstraints = false self.switcher.addTarget(self, action: #selector(switcherDidChange(_:)), for: .valueChanged) self.addSubview(self.switcher) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[switcher]->=0-[label]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["label":label,"switcher":self.switcher])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[label]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["label":label])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[switcher]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["switcher":self.switcher])) } else { //Input self.input.autocorrectionType = .no self.input.spellCheckingType = .no self.input.translatesAutoresizingMaskIntoConstraints = false self.input.keyboardType = .decimalPad self.input.keyboardAppearance = .dark self.input.layer.borderColor = UIColor.gray.cgColor self.input.layer.borderWidth = 1 self.input.textAlignment = .center self.input.addTarget(self, action: #selector(inputDidChange(_:)), for: .editingChanged) self.addSubview(self.input) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[input(>=100)]-[label]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["label":label,"input":self.input])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[label]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["label":label])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[input]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["input":self.input])) } } func updateValue(value:String) { //self.input.text = value self.input.placeholder = value } func updateValue(active:Bool) { //self.input.text = value self.switcher.setOn(active, animated: false) } @objc func inputDidChange(_ sender:UITextField) { self.delegate?.didChangeValue(item: self) } @objc func switcherDidChange(_ sender:UISwitch) { self.delegate?.didChangeValue(item: self) } func getValue() -> CGFloat { guard let placeholder = self.input.placeholder else { return 0.0 } guard let text = self.input.text else { return placeholder.getCGFloat() } guard !text.isEmpty else { return placeholder.getCGFloat() } return text.getCGFloat() } func getBoolValue() -> Bool { return self.switcher.isOn } } class SettingViewController: UIViewController, SettingsDeleagte { weak var collection: STWCollectionView? let stackView = UIStackView() var specificInView:UIView? convenience init(collection:STWCollectionView) { self.init() self.collection = collection } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "Setting" self.view.backgroundColor = .white self.createUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func createUI() { let gesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) self.view.addGestureRecognizer(gesture) //StackView self.stackView.distribution = .equalSpacing self.stackView.axis = .vertical self.stackView.spacing = 20 self.stackView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.stackView) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[stackView]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["stackView":self.stackView])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[stackView]->=0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["stackView":self.stackView])) let labelGeneral = UILabel() labelGeneral.translatesAutoresizingMaskIntoConstraints = false labelGeneral.textAlignment = .center labelGeneral.backgroundColor = .lightGray labelGeneral.text = "General" self.stackView.addArrangedSubview(labelGeneral) //Segment Direction let segmentDirection = UISegmentedControl(items: ["Horizontal","Vertical"]) segmentDirection.selectedSegmentIndex = (self.collection?.direction == .horizontal) ? 0 : 1 segmentDirection.addTarget(self, action: #selector(segmentDirectionDidChange(_:)), for: .valueChanged) self.stackView.addArrangedSubview(segmentDirection) //Spacing Item let spacing = SettingItemView(type: .spacing) spacing.delegate = self spacing.updateValue(value: "\(String(describing: collection!.itemSpacing))") self.stackView.addArrangedSubview(spacing) let labelSpecifics = UILabel() labelSpecifics.translatesAutoresizingMaskIntoConstraints = false labelSpecifics.textAlignment = .center labelSpecifics.backgroundColor = .lightGray labelSpecifics.text = "Specifics" self.stackView.addArrangedSubview(labelSpecifics) //Segment Type let segmentType = UISegmentedControl(items: ["Fixed Cells","Fixed Size"]) segmentType.selectedSegmentIndex = (self.collection?.fixedCellSize == nil) ? 0 : 1 segmentType.addTarget(self, action: #selector(segmentTypeDidChange(_:)), for: .valueChanged) self.stackView.addArrangedSubview(segmentType) self.segmentTypeDidChange(segmentType) } func createColumnsSettings() { self.removeLastViewOnStack() let columnsStackView = UIStackView() columnsStackView.axis = .vertical columnsStackView.spacing = 10 columnsStackView.distribution = .fillEqually columnsStackView.translatesAutoresizingMaskIntoConstraints = false self.stackView.addArrangedSubview(columnsStackView) let columnsItem = SettingItemView(type: .fixedCellsNumber) columnsItem.delegate = self columnsItem.updateValue(value: "\(String(describing: collection!.fixedCellsNumber))") let hPaddingItem = SettingItemView(type: .hPadding) hPaddingItem.delegate = self hPaddingItem.updateValue(value: "\(String(describing: collection!.horizontalPadding))") let vPaddingItem = SettingItemView(type: .vPadding) vPaddingItem.delegate = self vPaddingItem.updateValue(value: "\(String(describing: collection!.verticalPadding))") columnsStackView.addArrangedSubview(columnsItem) columnsStackView.addArrangedSubview(hPaddingItem) columnsStackView.addArrangedSubview(vPaddingItem) self.specificInView = columnsStackView } func createFixedSizeSettings() { self.removeLastViewOnStack() let fixedSizeStackView = UIStackView() fixedSizeStackView.axis = .vertical fixedSizeStackView.spacing = 10 fixedSizeStackView.distribution = .fillEqually fixedSizeStackView.translatesAutoresizingMaskIntoConstraints = false self.stackView.addArrangedSubview(fixedSizeStackView) let widthItem = SettingItemView(type: .fixedSizeWidth) widthItem.delegate = self widthItem.updateValue(value: (self.collection?.fixedCellSize != nil) ? "\(String(describing: collection!.fixedCellSize!.width))" : "0") let heightItem = SettingItemView(type: .fixedSizeHeight) heightItem.delegate = self heightItem.updateValue(value: (self.collection?.fixedCellSize != nil) ? "\(String(describing: collection!.fixedCellSize!.height))" : "0") let paddingItem = SettingItemView(type: (self.collection?.direction == .horizontal) ? .hPadding : .vPadding) paddingItem.delegate = self let paddingValue = (self.collection?.direction == .horizontal) ? collection!.horizontalPadding : collection!.verticalPadding paddingItem.updateValue(value: "\(String(describing: paddingValue))") let forceCentered = SettingItemView(type: .forceCenterd) forceCentered.delegate = self forceCentered.updateValue(active: self.collection!.forceCentered) fixedSizeStackView.addArrangedSubview(widthItem) fixedSizeStackView.addArrangedSubview(heightItem) fixedSizeStackView.addArrangedSubview(paddingItem) fixedSizeStackView.addArrangedSubview(forceCentered) self.specificInView = fixedSizeStackView } func removeLastViewOnStack() { self.specificInView?.removeFromSuperview() } //Gesture @objc func dismissKeyboard(){ self.view.endEditing(true) } //Segment Direction change @objc func segmentDirectionDidChange(_ sender:UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: self.collection?.direction = .horizontal break case 1: self.collection?.direction = .vertical break default: break } if self.collection?.fixedCellSize != nil { self.createFixedSizeSettings() } } //Segment Type change @objc func segmentTypeDidChange(_ sender:UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: self.collection?.fixedCellSize = nil self.createColumnsSettings() break case 1: self.createFixedSizeSettings() break default: break } } //Settings Delegate func didChangeValue(item:SettingItemView){ if let type = item.type { switch type { case .spacing: collection?.itemSpacing = item.getValue() break case .fixedCellsNumber: if item.getValue() <= 0 { self.lunchAlertController(item) }else{ collection?.fixedCellsNumber = Int(item.getValue()) } break case .vPadding: collection?.verticalPadding = item.getValue() break case .hPadding: collection?.horizontalPadding = item.getValue() break case .fixedSizeWidth: let heightValue = (self.collection?.fixedCellSize != nil) ? self.collection?.fixedCellSize?.height : item.getValue() collection?.fixedCellSize = CGSize(width: item.getValue(), height: heightValue!) break case .fixedSizeHeight: let widthValue = (self.collection?.fixedCellSize != nil) ? self.collection?.fixedCellSize?.width : item.getValue() collection?.fixedCellSize = CGSize(width: widthValue!, height: item.getValue()) break case .forceCenterd: collection?.forceCentered = item.getBoolValue() break } } } //Alert Controller func lunchAlertController(_ item:SettingItemView){ let alertController = UIAlertController(title: "Warning!", message: "fixedCellsNumber number not be less then 1", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default) { (action) in item.updateValue(value: "1") } alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } }
007b06219813c5e12d686ee38b42ab91
36.24282
218
0.636708
false
false
false
false
maxim-pervushin/HyperHabit
refs/heads/master
HyperHabit/HyperHabit/Views/MXCalendarView/Views/MXMonthView.swift
mit
1
// // Created by Maxim Pervushin on 15/01/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit class MXMonthView: UIView { // MARK: MXMonthView @IB @IBOutlet weak var collectionView: UICollectionView! static private func daysBeforeInMonth(inMonth: NSDate, calendar: NSCalendar) -> Int { let firstDayWeekday = inMonth.firstDayOfMonth().weekday() return firstDayWeekday >= calendar.firstWeekday ? firstDayWeekday - calendar.firstWeekday : 7 - firstDayWeekday } static private func daysAfterInMonth(inMonth: NSDate, calendar: NSCalendar) -> Int { let days = inMonth.numberOfDaysInMonth() + daysBeforeInMonth(inMonth, calendar: calendar) return days % 7 != 0 ? 7 - days % 7 : 0 } var dateSelectedHandler: ((date:NSDate) -> ())? var cellConfigurationHandler: ((cell:UICollectionViewCell) -> ())? var month: NSDate? { didSet { collectionView.reloadData() } } var startDate: NSDate? var endDate: NSDate? var selectedDate: NSDate? var calendar = NSCalendar.currentCalendar() { didSet { collectionView.reloadData() } } private static var titleFormatter: NSDateFormatter { struct Static { static var onceToken: dispatch_once_t = 0 static var formatter: NSDateFormatter! = nil } dispatch_once(&Static.onceToken) { Static.formatter = NSDateFormatter() Static.formatter.dateFormat = "LLLL YYYY" } return Static.formatter } private static var dayFormatter: NSDateFormatter { struct Static { static var onceToken: dispatch_once_t = 0 static var formatter: NSDateFormatter! = nil } dispatch_once(&Static.onceToken) { Static.formatter = NSDateFormatter() Static.formatter.dateFormat = "EE" } return Static.formatter } private func daysBeforeInMonth(inMonth: NSDate) -> Int { let firstDayWeekday = inMonth.firstDayOfMonth().weekday() return firstDayWeekday >= calendar.firstWeekday ? firstDayWeekday - calendar.firstWeekday : 7 - firstDayWeekday } private func daysAfterInMonth(inMonth: NSDate) -> Int { let days = inMonth.numberOfDaysInMonth() + daysBeforeInMonth(inMonth) return days % 7 != 0 ? 7 - days % 7 : 0 } private func monthTitle() -> String { if let month = month { return MXMonthView.titleFormatter.stringFromDate(month) } return "" } private func dayTitle(dayIndex: Int) -> String { var index = calendar.firstWeekday + dayIndex - 1 while index > 6 { index -= 7 } let title = MXMonthView.dayFormatter.shortWeekdaySymbols[index] return title } } extension MXMonthView { // MARK: Custom cells private func monthTitleCell(collectionView: UICollectionView, indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MXTextCell.defaultReuseIdentifier, forIndexPath: indexPath) as! MXTextCell cell.text = monthTitle() return cell } private func dayTitleCell(collectionView: UICollectionView, indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MXTextCell.defaultReuseIdentifier, forIndexPath: indexPath) as! MXTextCell cell.text = dayTitle(indexPath.row) return cell } private func emptyCell(collectionView: UICollectionView, indexPath: NSIndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCellWithReuseIdentifier(MXEmptyCell.defaultReuseIdentifier, forIndexPath: indexPath) } private func dayCell(collectionView: UICollectionView, indexPath: NSIndexPath, date: NSDate) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MXDayCell.defaultReuseIdentifier, forIndexPath: indexPath) as! MXDayCell cell.date = date cell.selectedDate = selectedDate cellConfigurationHandler?(cell: cell) return cell } private func inactiveDayCell(collectionView: UICollectionView, indexPath: NSIndexPath, date: NSDate) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MXInactiveDayCell.defaultReuseIdentifier, forIndexPath: indexPath) as! MXInactiveDayCell cell.date = date return cell } } extension MXMonthView: UICollectionViewDataSource { public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { guard let _ = month else { return 0 } return 3 } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let month = month else { return 0 } if section == 0 { return 1 } else if section == 1 { return 7 } else { return daysBeforeInMonth(month) + month.numberOfDaysInMonth() + daysAfterInMonth(month) } } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if indexPath.section == 0 { return monthTitleCell(collectionView, indexPath: indexPath) } else if indexPath.section == 1 { return dayTitleCell(collectionView, indexPath: indexPath) } else { guard let month = month else { return emptyCell(collectionView, indexPath: indexPath) } let daysBefore = daysBeforeInMonth(month) let cellDate = month.firstDayOfMonth().dateByAddingDays(indexPath.row - daysBefore) if indexPath.row < daysBefore || indexPath.row >= daysBefore + month.numberOfDaysInMonth() { return emptyCell(collectionView, indexPath: indexPath) } else if let startDate = startDate where cellDate < startDate { return inactiveDayCell(collectionView, indexPath: indexPath, date: cellDate) } else if let endDate = endDate where cellDate > endDate { return inactiveDayCell(collectionView, indexPath: indexPath, date: cellDate) } else { return dayCell(collectionView, indexPath: indexPath, date: cellDate) } } } } extension MXMonthView: UICollectionViewDelegate { public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { collectionView.deselectItemAtIndexPath(indexPath, animated: true) if let dayCell = collectionView.cellForItemAtIndexPath(indexPath) as? MXDayCell, date = dayCell.date { dateSelectedHandler?(date: date) } } } extension MXMonthView: UICollectionViewDelegateFlowLayout { public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let side = collectionView.frame.size.width / 7 if indexPath.section == 0 { return CGSizeMake(collectionView.frame.size.width, side / 2) } else if indexPath.section == 1 { return CGSizeMake(side, side / 2) } return CGSizeMake(side, side) } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsZero } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSizeZero } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSizeZero } }
19244cfcbade50536fc2cd37759d5f97
35.918103
185
0.682975
false
false
false
false