hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
2ff3acadce8609f22ea79977eeb3d28e0677a1af
1,360
import Cocoa import AuthenticationKit // TODO: Fix example. Should work in theory class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() let success: (accounts: [AccountType]) -> Void = { (accounts) -> Void in print(accounts) } let failure: (error: AccountError) -> Void = { (error) -> Void in print(error) } let twitter = ACAccountProvider.Twitter twitter.fetchAccounts(failure, success: success) let facebook = ACAccountProvider.Facebook(appId: "10153096457889200", permissions: ["email"], audience: Audience.Everyone) facebook.fetchAccounts(failure, success: success) let sinaWeibo = ACAccountProvider.SinaWeibo sinaWeibo.fetchAccounts(failure, success: success) let tencentWeibo = ACAccountProvider.TencentWeibo(appId: "") tencentWeibo.fetchAccounts(failure, success: success) let linkedIn = ACAccountProvider.LinkedIn(appId: "77fe3jliohtjrz", permissions: ["r_basicprofile"]) linkedIn.fetchAccounts(failure, success: success) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } }
29.565217
130
0.614706
c10da17f27dea30f9735e53329049a8d03dc091f
3,979
// // BusinessesViewController.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit class BusinessesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UIScrollViewDelegate { var businesses: [Business]! var isMoreDataLoading = false @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.separatorInset = .zero tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 120 let searchBar = UISearchBar() searchBar.delegate = self searchBar.sizeToFit() navigationItem.titleView = searchBar /* Business.searchWithTerm(term: "Restaurants", completion: { (businesses: [Business]?, error: Error?) -> Void in self.businesses = businesses self.tableView.reloadData() if let businesses = businesses { for business in businesses { print(business.name!) print(business.address!) } } }) */ Business.searchWithTerm(term: "Restaurants", sort: .distance, categories: ["mediterranean", "italian", "asianfusion", "burgers"], deals: true) { (businesses: [Business]!, error: Error!) -> Void in self.businesses = businesses self.tableView.reloadData() for business in businesses { print(business.name!) print(business.address!) } } } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { Business.searchWithTerm(term: searchText, completion: { (businesses: [Business]?, error: Error?) -> Void in self.businesses = businesses self.tableView.reloadData() if let businesses = businesses { for business in businesses { print(business.name!) print(business.address!) } } }) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if businesses != nil { return businesses!.count } else { return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessCell", for: indexPath) as! BusinessCell cell.business = businesses[indexPath.row] return cell } /* func scrollViewDidScroll(_ scrollView: UIScrollView) { if (!isMoreDataLoading) { // Calculate the position of one screen length before the bottom of the results let scrollViewContentHeight = tableView.contentSize.height let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height // When the user has scrolled past the threshold, start requesting if(scrollView.contentOffset.y > scrollOffsetThreshold && tableView.isDragging) { isMoreDataLoading = true loadMoreData() } } } func loadMoreData() { // ... Create the NSURLRequest (myRequest) ... // Configure session so that completion handler is executed on main UI thread let session = URLSession(configuration: URLSessionConfiguration.default, delegate:nil, delegateQueue:OperationQueue.main ) let task : URLSessionDataTask = session.dataTask(with: myRequest, completionHandler: { (data, response, error) in // Update flag self.isMoreDataLoading = false // ... Use the new data to update the data source ... // Reload the tableView now that there is new data self.myTableView.reloadData() }) task.resume() } */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
30.607692
200
0.656195
33a86ff909453f9b2c68094b227b7dcd8c99a813
2,171
// // AppDelegate.swift // dtacComponent // // Created by ragopor on 02/05/2020. // Copyright (c) 2020 ragopor. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.191489
285
0.754491
1ee9c669cbadaee41f3f85efbc47400b1a3156fd
18,292
import SwiftUI import CloudKit import CircularCheckmarkProgress import os.log #if DEBUG && true fileprivate var log = Logger( subsystem: Bundle.main.bundleIdentifier!, category: "RecoveryPhraseView" ) #else fileprivate var log = Logger(OSLog.disabled) #endif struct RecoveryPhraseView: View { @ViewBuilder var body: some View { ScrollViewReader { scrollViewProxy in RecoveryPhraseList(scrollViewProxy: scrollViewProxy) } } } struct RecoveryPhraseList: View { let scrollViewProxy: ScrollViewProxy let encryptedNodeId: String @State var manualBackup_taskDone: Bool @State var backupSeed_enabled: Bool let syncSeedManager: SyncSeedManager @State var syncState: SyncSeedManager_State = .disabled @State var syncStateWasEnabled = false @State var isDecrypting = false @State var revealSeed = false @State var mnemonics: [String] = [] @State var legal_taskDone: Bool @State var legal_lossRisk: Bool @State var animatingLegalToggleColor = false @State var didAppear = false @Namespace var sectionID_warning @Namespace var sectionID_info @Namespace var sectionID_button @Namespace var sectionID_legal @Namespace var sectionID_cloudBackup @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> init(scrollViewProxy: ScrollViewProxy) { self.scrollViewProxy = scrollViewProxy let appDelegate = AppDelegate.get() let encryptedNodeId = appDelegate.encryptedNodeId! self.encryptedNodeId = encryptedNodeId self.syncSeedManager = appDelegate.syncManager!.syncSeedManager let manualBackup_taskDone = Prefs.shared.manualBackup_taskDone(encryptedNodeId: encryptedNodeId) self._manualBackup_taskDone = State<Bool>(initialValue: manualBackup_taskDone) let backupSeed_enabled = Prefs.shared.backupSeed_isEnabled self._backupSeed_enabled = State<Bool>(initialValue: backupSeed_enabled) self._legal_taskDone = State<Bool>(initialValue: manualBackup_taskDone) self._legal_lossRisk = State<Bool>(initialValue: manualBackup_taskDone) } var body: some View { List { if !backupSeed_enabled && !(legal_taskDone && legal_lossRisk) { section_warning() .id(sectionID_warning) } section_info() .id(sectionID_info) section_button() .id(sectionID_button) if !backupSeed_enabled { section_legal() .id(sectionID_legal) } CloudBackupSection( backupSeed_enabled: $backupSeed_enabled, syncState: $syncState, syncStateWasEnabled: $syncStateWasEnabled ) .id(sectionID_cloudBackup) } .listStyle(.insetGrouped) .sheet(isPresented: $revealSeed) { RecoveryPhraseReveal( isShowing: $revealSeed, mnemonics: $mnemonics ) } .navigationBarTitle( NSLocalizedString("Recovery Phrase", comment: "Navigation bar title"), displayMode: .inline ) .onAppear { onAppear() } .onReceive(syncSeedManager.statePublisher) { syncStateChanged($0) } } @ViewBuilder func section_warning() -> some View { Section { Label { HStack(alignment: VerticalAlignment.center, spacing: 0) { VStack(alignment: HorizontalAlignment.leading, spacing: 10) { Text( """ You have not backed up your recovery phrase! """ ) .font(.callout) .bold() Text(styled: NSLocalizedString( """ If you do not back it up and you lose access to Phoenix \ you will **lose your funds**! """, comment: "BackupView" )) .font(.subheadline) } // </VStack> Spacer() // ensure label takes up full width }// </HStack> } icon: { Image(systemName: "exclamationmark.circle") .renderingMode(.template) .imageScale(.large) .foregroundColor(Color.appWarn) } .padding() .overlay( RoundedRectangle(cornerRadius: 10) .strokeBorder(Color.appWarn, lineWidth: 1) ) .listRowBackground(Color.clear) .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) } // </Section> } @ViewBuilder func section_info() -> some View { Section { VStack(alignment: .leading, spacing: 35) { Text( """ The recovery phrase (sometimes called a seed), is a list of 12 English words. \ It allows you to recover full access to your funds if needed. """ ) Text( "Only you alone possess this seed. Keep it private." ) .fontWeight(.bold) Text(styled: NSLocalizedString( """ **Do not share this seed with anyone.** \ Beware of phishing. The developers of Phoenix will never ask for your seed. """, comment: "ManualBackupView" )) Text(styled: NSLocalizedString( """ **Do not lose this seed.** \ Save it somewhere safe (not on this phone). \ If you lose your seed and your phone, you've lost your funds. """, comment: "ManualBackupView" )) } // </VStack> .padding(.vertical, 15) } // </Section> } @ViewBuilder func section_button() -> some View { Section { VStack(alignment: HorizontalAlignment.center, spacing: 0) { Button { decrypt() } label: { HStack { Image(systemName: "key") .imageScale(.medium) Text("Display seed") .font(.headline) } } .disabled(isDecrypting) .padding(.vertical, 5) let enabledSecurity = AppSecurity.shared.enabledSecurity.value if enabledSecurity != .none { Text("(requires authentication)") .font(.footnote) .foregroundColor(.secondary) .padding(.top, 5) .padding(.bottom, 10) } } // </VStack> .frame(maxWidth: .infinity) } // </Section> } @ViewBuilder func section_legal() -> some View { Section(header: Text("Legal")) { Toggle(isOn: $legal_taskDone) { Text( """ I have saved my recovery phrase somewhere safe. """ ) .lineLimit(nil) .alignmentGuide(VerticalAlignment.center) { d in d[VerticalAlignment.firstTextBaseline] } } .toggleStyle(CheckboxToggleStyle( onImage: onImage(), offImage: offImage() )) .padding(.vertical, 5) .onChange(of: legal_taskDone) { _ in legalToggleChanged() } Toggle(isOn: $legal_lossRisk) { Text( """ I understand that if I lose my phone & my recovery phrase, \ then I will lose the funds in my wallet. """ ) .lineLimit(nil) .alignmentGuide(VerticalAlignment.center) { d in d[VerticalAlignment.firstTextBaseline] } } .toggleStyle(CheckboxToggleStyle( onImage: onImage(), offImage: offImage() )) .padding(.vertical, 5) .onChange(of: legal_lossRisk) { _ in legalToggleChanged() } } // </Section> } @ViewBuilder func onImage() -> some View { Image(systemName: "checkmark.square.fill") .imageScale(.large) } @ViewBuilder func offImage() -> some View { Image(systemName: "square") .renderingMode(.template) .imageScale(.large) .foregroundColor(animatingLegalToggleColor ? Color.red : Color.primary) } func onAppear(){ log.trace("onAppear()") if !didAppear { didAppear = true DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { withAnimation(Animation.linear(duration: 1.0).repeatForever(autoreverses: true)) { animatingLegalToggleColor = true } } } } func syncStateChanged(_ newSyncState: SyncSeedManager_State) { log.trace("syncStateChanged()") syncState = newSyncState if newSyncState != .disabled { syncStateWasEnabled = true } if newSyncState == .deleting { log.debug("newSyncState == .deleting") DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { scrollViewProxy.scrollTo(sectionID_cloudBackup, anchor: .top) } } } func decrypt() { log.trace("decrypt()") isDecrypting = true let Succeed = {(result: [String]) in mnemonics = result revealSeed = true isDecrypting = false } let Fail = { isDecrypting = false } let enabledSecurity = AppSecurity.shared.enabledSecurity.value if enabledSecurity == .none { AppSecurity.shared.tryUnlockWithKeychain { (mnemonics, _, _) in if let mnemonics = mnemonics { Succeed(mnemonics) } else { Fail() } } } else { let prompt = NSLocalizedString("Unlock your seed.", comment: "Biometrics prompt") AppSecurity.shared.tryUnlockWithBiometrics(prompt: prompt) { result in if case .success(let mnemonics) = result { Succeed(mnemonics) } else { Fail() } } } } func legalToggleChanged() { log.trace("legalToggleChanged()") let taskDone = legal_taskDone && legal_lossRisk log.debug("taskDone = \(taskDone ? "true" : "false")") if taskDone != manualBackup_taskDone { manualBackup_taskDone = taskDone Prefs.shared.manualBackup_setTaskDone(taskDone, encryptedNodeId: encryptedNodeId) } } } fileprivate struct CloudBackupSection: View { @Binding var backupSeed_enabled: Bool @Binding var syncState: SyncSeedManager_State @Binding var syncStateWasEnabled: Bool @ViewBuilder var body: some View { Section { NavigationLink(destination: CloudBackupView(backupSeed_enabled: $backupSeed_enabled)) { HStack(alignment: VerticalAlignment.center, spacing: 0) { Label("iCloud backup", systemImage: "icloud") Spacer() if backupSeed_enabled { if syncState != .synced { Image(systemName: "exclamationmark.triangle") .renderingMode(.template) .foregroundColor(Color.appWarn) .padding(.trailing, 4) } Image(systemName: "checkmark") .foregroundColor(Color.appAccent) .font(Font.body.weight(Font.Weight.heavy)) } } } // Implicit divider added here if backupSeed_enabled || syncState != .disabled || syncStateWasEnabled { Group { if syncState == .synced { status_uploaded() } else if syncState != .disabled { status_syncState() } else { status_deleted() } } .padding(.vertical, 10) } } } @ViewBuilder func status_uploaded() -> some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Label { VStack(alignment: HorizontalAlignment.leading, spacing: 10) { Text("Your recovery phrase is stored in iCloud.") Text( """ Phoenix can restore your funds automatically. """ ) .foregroundColor(Color.gray) } } icon: { Image(systemName: "externaldrive.badge.checkmark") .renderingMode(.template) .imageScale(.medium) } } } @ViewBuilder func status_deleted() -> some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Label { VStack(alignment: HorizontalAlignment.leading, spacing: 10) { Text("Your recovery phrase was deleted from iCloud.") } } icon: { Image(systemName: "externaldrive.badge.minus") .renderingMode(.template) .imageScale(.medium) } } } @ViewBuilder func status_syncState() -> some View { VStack(alignment: HorizontalAlignment.leading, spacing: 20) { if backupSeed_enabled { Label { Text("Uploading your recovery phrase to iCloud…") } icon: { Image(systemName: "externaldrive.badge.plus") .renderingMode(.template) .imageScale(.medium) } } else { Label { Text("Deleting your recovery phrase from iCloud…") } icon: { Image(systemName: "externaldrive.badge.minus") .renderingMode(.template) .imageScale(.medium) } } if syncState == .uploading { Label { Text("Sending…") } icon: { ProgressView() .progressViewStyle(CircularProgressViewStyle(tint: Color.appAccent)) } } else if syncState == .deleting { Label { Text("Deleting…") } icon: { ProgressView() .progressViewStyle(CircularProgressViewStyle(tint: Color.appAccent)) } } else if case .waiting(let details) = syncState { switch details.kind { case .forInternet: Label { Text("Waiting for internet…") } icon: { ProgressView() .progressViewStyle(CircularProgressViewStyle(tint: Color.appAccent)) } case .forCloudCredentials: Label { Text("Please sign into iCloud") } icon: { Image(systemName: "exclamationmark.triangle.fill") .renderingMode(.template) .foregroundColor(Color.appWarn) } case .exponentialBackoff(let error): SyncErrorDetails(waiting: details, error: error) } // </switch> } // </case .waiting> } // </VStack> } } fileprivate struct SyncErrorDetails: View, ViewName { let waiting: SyncSeedManager_State_Waiting let error: Error let timer = Timer.publish(every: 0.5, on: .current, in: .common).autoconnect() @State var currentDate = Date() @ViewBuilder var body: some View { Label { VStack(alignment: HorizontalAlignment.leading, spacing: 4) { Text("Error - retry in:") HStack(alignment: VerticalAlignment.center, spacing: 8) { let (progress, remaining, total) = progressInfo() ProgressView(value: progress, total: 1.0) .progressViewStyle(CircularCheckmarkProgressViewStyle( strokeStyle: StrokeStyle(lineWidth: 3.0), showGuidingLine: true, guidingLineWidth: 1.0, showPercentage: false, checkmarkAnimation: .trim )) .foregroundColor(Color.appAccent) .frame(width: 20, height: 20, alignment: .center) Text(verbatim: "\(remaining) / \(total)") .font(.system(.callout, design: .monospaced)) Spacer() Button { skipButtonTapped() } label: { HStack(alignment: VerticalAlignment.center, spacing: 4) { Text("Skip") Image(systemName: "arrowshape.turn.up.forward") .imageScale(.medium) } } } .padding(.top, 4) .padding(.bottom, 4) if let errorInfo = errorInfo() { Text(errorInfo) .font(.callout) .multilineTextAlignment(.leading) .lineLimit(2) } } // </VStack> } icon: { Image(systemName: "exclamationmark.triangle.fill") .renderingMode(.template) .foregroundColor(Color.appWarn) } .onReceive(timer) { _ in self.currentDate = Date() } } func progressInfo() -> (Double, String, String) { guard let until = waiting.until else { return (1.0, "0:00", "0:00") } let start = until.startDate.timeIntervalSince1970 let end = until.fireDate.timeIntervalSince1970 let now = currentDate.timeIntervalSince1970 guard start < end, now >= start, now < end else { return (1.0, "0:00", "0:00") } let progressFraction = (now - start) / (end - start) let remaining = formatTimeInterval(end - now) let total = formatTimeInterval(until.delay) return (progressFraction, remaining, total) } func formatTimeInterval(_ value: TimeInterval) -> String { let minutes = Int(value) / 60 let seconds = Int(value) % 60 return String(format: "%d:%02d", minutes, seconds) } func errorInfo() -> String? { guard case .exponentialBackoff(let error) = waiting.kind else { return nil } var result: String? = nil if let ckerror = error as? CKError { switch ckerror.errorCode { case CKError.quotaExceeded.rawValue: result = "iCloud storage is full" default: break } } return result ?? error.localizedDescription } func skipButtonTapped() -> Void { log.trace("[\(viewName)] skipButtonTapped()") waiting.skip() } } fileprivate struct RecoveryPhraseReveal: View { @Binding var isShowing: Bool @Binding var mnemonics: [String] func mnemonic(_ idx: Int) -> String { return (mnemonics.count > idx) ? mnemonics[idx] : " " } var body: some View { ZStack { // close button // (required for landscapse mode, where swipe to dismiss isn't possible) VStack { HStack { Spacer() Button { close() } label: { Image("ic_cross") .resizable() .frame(width: 30, height: 30) } } Spacer() } .padding() main } } var main: some View { VStack { Spacer() Text("KEEP THIS SEED SAFE.") .font(.title2) .multilineTextAlignment(.center) .padding(.bottom, 2) Text("DO NOT SHARE.") .multilineTextAlignment(.center) .font(.title2) Spacer() HStack { Spacer() VStack { ForEach(0..<6, id: \.self) { idx in Text(verbatim: "#\(idx + 1) ") .font(.headline) .foregroundColor(.secondary) .padding(.bottom, 2) } } .padding(.trailing, 2) VStack(alignment: .leading) { ForEach(0..<6, id: \.self) { idx in Text(mnemonic(idx)) .font(.headline) .padding(.bottom, 2) } } .padding(.trailing, 4) // boost spacing a wee bit Spacer() VStack { ForEach(6..<12, id: \.self) { idx in Text(verbatim: "#\(idx + 1) ") .font(.headline) .foregroundColor(.secondary) .padding(.bottom, 2) } } .padding(.trailing, 2) VStack(alignment: .leading) { ForEach(6..<12, id: \.self) { idx in Text(mnemonic(idx)) .font(.headline) .padding(.bottom, 2) } } Spacer() } .padding(.top, 20) .padding(.bottom, 10) Spacer() Spacer() Text("BIP39 seed with standard BIP84 derivation path") .font(.footnote) .foregroundColor(.secondary) } .padding(.top, 20) .padding([.leading, .trailing], 30) .padding(.bottom, 20) } func close() { log.trace("[RecoverySeedReveal] close()") isShowing = false } } class RecoveryPhraseView_Previews: PreviewProvider { @State static var revealSeed: Bool = true @State static var testMnemonics = [ "witch", "collapse", "practice", "feed", "shame", "open", "despair", "creek", "road", "again", "ice", "least" ] static var previews: some View { RecoveryPhraseReveal(isShowing: $revealSeed, mnemonics: $testMnemonics) .preferredColorScheme(.light) .previewDevice("iPhone 8") RecoveryPhraseReveal(isShowing: $revealSeed, mnemonics: $testMnemonics) .preferredColorScheme(.dark) .previewDevice("iPhone 8") } }
23.213198
98
0.640663
119fb781bd44be6a9bed48380f63d64ef173318c
695
// // FormatarNumero.swift // CommonsService // // Created by Leticia Sousa Siqueira on 27/01/21. // import Foundation public class FormataNumero { public init() { } public func formatarCotacao(cotacao: Double) -> String { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 2 formatter.decimalSeparator = "," formatter.groupingSeparator = "." let number = NSNumber(value: cotacao) let formattedValue = formatter.string(from: number)! return "$\(formattedValue)" } }
23.166667
64
0.56259
ab9f85120514d8a8ced90b6c0b5040d4d9e9b7a7
2,997
// // PrivateKey.swift // WalletKit // // Created by yuzushioh on 2018/02/06. // Copyright © 2018 yuzushioh. All rights reserved. // public struct PrivateKey { public let raw: Data public let chainCode: Data public let depth: UInt8 public let fingerprint: UInt32 public let index: UInt32 public let network: Network public init(seed: Data, network: Network) { let output = Crypto.HMACSHA512(key: "Bitcoin seed".data(using: .ascii)!, data: seed) self.raw = output[0..<32] self.chainCode = output[32..<64] self.depth = 0 self.fingerprint = 0 self.index = 0 self.network = network } private init(privateKey: Data, chainCode: Data, depth: UInt8, fingerprint: UInt32, index: UInt32, network: Network) { self.raw = privateKey self.chainCode = chainCode self.depth = depth self.fingerprint = fingerprint self.index = index self.network = network } public var publicKey: PublicKey { return PublicKey(privateKey: self, chainCode: chainCode, network: network, depth: depth, fingerprint: fingerprint, index: index) } public var extended: String { var extendedPrivateKeyData = Data() extendedPrivateKeyData += network.privateKeyVersion.bigEndian extendedPrivateKeyData += depth.littleEndian extendedPrivateKeyData += fingerprint.littleEndian extendedPrivateKeyData += index.littleEndian extendedPrivateKeyData += chainCode extendedPrivateKeyData += UInt8(0) extendedPrivateKeyData += raw let checksum = extendedPrivateKeyData.doubleSHA256.prefix(4) return Base58.encode(extendedPrivateKeyData + checksum) } public func derived(at index: UInt32, hardens: Bool = false) -> PrivateKey { let edge: UInt32 = 0x80000000 guard (edge & index) == 0 else { fatalError("Invalid child index") } var data = Data() if hardens { data += UInt8(0) data += raw } else { data += publicKey.raw } let derivingIndex = hardens ? (edge + index) : index data += derivingIndex.bigEndian let digest = Crypto.HMACSHA512(key: chainCode, data: data) let factor = BInt(data: digest[0..<32]) let curveOrder = BInt(hex: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141")! let derivedPrivateKey = ((BInt(data: raw) + factor) % curveOrder).data let derivedChainCode = digest[32..<64] let fingurePrint: UInt32 = RIPEMD160.hash(publicKey.raw.sha256()).withUnsafeBytes { $0.pointee } return PrivateKey( privateKey: derivedPrivateKey, chainCode: derivedChainCode, depth: depth + 1, fingerprint: fingurePrint, index: derivingIndex, network: network ) } }
34.056818
136
0.620287
9070e7ca3132f201a0660ee449aa1d41069fdb6a
3,810
// // AppDelegate.swift // Notes // // Created by Александр Андреев on 26/06/2019. // Copyright © 2019 Alexander Andreev. All rights reserved. // import UIKit import CocoaLumberjack @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { DDLog.add(DDOSLogger.sharedInstance) DDLogInfo("Notes App Started") let tabBarController = UITabBarController() let img = self.tabBarImage() let notesViewController = NotesViewController(nibName: nil, bundle: nil) let notesNavigationController = UINavigationController(rootViewController: notesViewController) notesNavigationController.tabBarItem = UITabBarItem(title: "Notes", image: img, selectedImage: nil) let galleryViewController = GalleryViewController(nibName: nil, bundle: nil) galleryViewController.tabBarItem = UITabBarItem(title: "Gallery", image: img, selectedImage: nil) tabBarController.viewControllers = [notesNavigationController, galleryViewController] self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = tabBarController self.window?.makeKeyAndVisible() return true } private func tabBarImage() -> UIImage { let size: CGFloat = 20.0 let renderer = UIGraphicsImageRenderer(size: CGSize(width: size, height: size)) let img = renderer.image { ctx in let rectangle = CGRect(x: 0, y: 0, width: size, height: size) ctx.cgContext.addRect(rectangle) ctx.cgContext.drawPath(using: .fill) } return img } 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:. } }
45.903614
285
0.665354
619b96106bf0606c5aa0704ae75ee9c8ac30d666
302
// // ZoomableImageConstant.swift // Buok // // Copyright © 2021 Buok. All rights reserved. // import Foundation @objc public enum ScaleMode: Int { case aspectFill case aspectFit case widthFill case heightFill } @objc public enum Offset: Int { case begining case center }
14.380952
47
0.678808
016d8d596921f54c8169c2e147deea4fd2328b8b
17,265
// // Pushy.swift // Pushy // // Created by Pushy on 10/7/16. // Copyright © 2016 Pushy. All rights reserved. // import UIKit import UserNotifications public class Pushy : NSObject { static var shared: Pushy? private var appDelegate: UIApplicationDelegate private var application: UIApplication private var registrationHandler: ((Error?, String) -> Void)? private var notificationHandler: (([AnyHashable : Any], @escaping ((UIBackgroundFetchResult) -> Void)) -> Void)? public init(_ application: UIApplication) { // Store application and app delegate for later self.application = application self.appDelegate = application.delegate! // Initialize Pushy instance before accessing the self object super.init() // Store Pushy instance for later, but don't overwrite an existing instance if already initialized if Pushy.shared == nil { Pushy.shared = self } } // Define a notification handler to invoke when device receives a notification public func setNotificationHandler(_ notificationHandler: @escaping ([AnyHashable : Any], @escaping ((UIBackgroundFetchResult) -> Void)) -> Void) { // Save the handler for later self.notificationHandler = notificationHandler } // Register for push notifications (called from AppDelegate.didFinishLaunchingWithOptions) public func register(_ registrationHandler: @escaping (Error?, String) -> Void) { // Save the handler for later self.registrationHandler = registrationHandler // Swizzle methods (will call method with same selector in Pushy class) PushySwizzler.swizzleMethodImplementations(self.appDelegate.superclass!, "application:didRegisterForRemoteNotificationsWithDeviceToken:") PushySwizzler.swizzleMethodImplementations(self.appDelegate.superclass!, "application:didFailToRegisterForRemoteNotificationsWithError:") PushySwizzler.swizzleMethodImplementations(self.appDelegate.superclass!, "application:didReceiveRemoteNotification:fetchCompletionHandler:") // Request an APNs token from Apple requestAPNsToken(self.application) } // Backwards-compatible method for requesting an APNs token from Apple private func requestAPNsToken(_ application: UIApplication) { // iOS 10 support if #available(iOS 10, *) { UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in } application.registerForRemoteNotifications() } // iOS 9 support else if #available(iOS 9, *) { UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) UIApplication.shared.registerForRemoteNotifications() } // iOS 8 support else if #available(iOS 8, *) { UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) UIApplication.shared.registerForRemoteNotifications() } // iOS 7 support else { application.registerForRemoteNotifications(matching: [.badge, .sound, .alert]) } } // Called automatically when APNs has assigned the device a unique token @objc public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // Convert token to string let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}).lowercased() // Pass it back to the Pushy instance for conversion Pushy.shared?.registerPushyDevice(apnsToken: deviceTokenString) } // Converts an APNs token to Pushy device token private func registerPushyDevice(apnsToken: String) { // Attempt to fetch persisted Pushy token let token = PushySettings.getString(PushySettings.pushyToken) // First time? if token == nil { // Create a new Pushy device return createNewDevice(apnsToken) } // Validate existing device credentials validateCredentials({ (error, credentialsValid) in // Handle validation errors if error != nil { self.registrationHandler?(error, "") return } // Are credentials invalid? if !credentialsValid { // Create a new device using the token return self.createNewDevice(apnsToken) } // Get previously-stored APNs token if let previousApnsToken = PushySettings.getString(PushySettings.apnsToken) { // Token changed? if (apnsToken != previousApnsToken) { // Update APNs token server-side return self.updateApnsToken(apnsToken) } // APNs token didn't change self.registrationHandler?(nil, token!) } else { // Failed to load APNs token from UserDefaults self.registrationHandler?(PushyRegistrationException.Error("Failed to load persisted APNs token."), "") } }) } // Register a new Pushy device private func createNewDevice(_ apnsToken:String) { // Fetch app bundle ID let bundleID = Bundle.main.bundleIdentifier // Bundle ID fetch failed? guard let appBundleID = bundleID else { registrationHandler?(PushyRegistrationException.Error("Please configure a Bundle ID for your app to use Pushy."), "") return } // Determine if this is a sandbox or production APNs token let pushEnvironment = PushyEnvironment.getEnvironmentString() // Prepare /register API post data let params: [String:Any] = ["app": appBundleID, "platform": "ios", "pushToken": apnsToken, "pushEnvironment": pushEnvironment ] // Execute post request PushyHTTP.postAsync(self.getApiEndpoint() + "/register", params: params) { (err: Error?, response: [String:AnyObject]?) -> () in // JSON parse error? if err != nil { self.registrationHandler?(err, "") return } // Unwrap response json guard let json = response else { self.registrationHandler?(PushyRegistrationException.Error("An invalid response was encountered."), "") return } // If we are here, registration succeeded let deviceToken = json["token"] as! String let deviceAuth = json["auth"] as! String // Store device token and auth in UserDefaults PushySettings.setString(PushySettings.apnsToken, apnsToken) PushySettings.setString(PushySettings.pushyToken, deviceToken) PushySettings.setString(PushySettings.pushyTokenAuth, deviceAuth) // All done self.registrationHandler?(nil, deviceToken) } } // Update remote APNs token private func updateApnsToken(_ apnsToken: String) { // Load device token & auth guard let pushyToken = PushySettings.getString(PushySettings.pushyToken), let pushyTokenAuth = PushySettings.getString(PushySettings.pushyTokenAuth) else { return } // Determine if this is a sandbox or production APNs token let pushEnvironment = PushyEnvironment.getEnvironmentString() // Prepare request params let params: [String:Any] = ["token": pushyToken, "auth": pushyTokenAuth, "pushToken": apnsToken, "pushEnvironment": pushEnvironment] // Execute post request PushyHTTP.postAsync(self.getApiEndpoint() + "/devices/token", params: params) { (err: Error?, response: [String:AnyObject]?) -> () in // JSON parse error? if err != nil { self.registrationHandler?(err, "") return } // Unwrap json guard let json = response else { self.registrationHandler?(PushyRegistrationException.Error("An invalid response was encountered when updating the push token."), "") return } // Get success value let success = json["success"] as! Bool // Verify success if !success { self.registrationHandler?(PushyRegistrationException.Error("An unsuccessful response was encountered when updating the push token."), "") return } // Store new APNS token to avoid re-updating it PushySettings.setString(PushySettings.apnsToken, apnsToken) // Done updating APNS token self.registrationHandler?(nil, pushyToken) } } // Validate device token and auth key private func validateCredentials(_ resultHandler: @escaping (Error?, Bool) -> Void) { // Load device token & auth guard let pushyToken = PushySettings.getString(PushySettings.pushyToken), let pushyTokenAuth = PushySettings.getString(PushySettings.pushyTokenAuth) else { return resultHandler(PushyRegistrationException.Error("Failed to load the device credentials."), false) } // Prepare request params let params: [String:Any] = ["token": pushyToken, "auth": pushyTokenAuth] // Execute post request PushyHTTP.postAsync(self.getApiEndpoint() + "/devices/auth", params: params) { (err: Error?, response: [String:AnyObject]?) -> () in // JSON parse error? if err != nil { // Did we get json["error"] response exception? if err is PushyResponseException { // Auth is invalid return resultHandler(nil, false) } // Throw network error and stop execution return resultHandler(err, false) } // Unwrap json guard let json = response else { return resultHandler(PushyRegistrationException.Error("An invalid response was encountered when validating device credentials."), false) } // Get success value let success = json["success"] as! Bool // Verify credentials validity if !success { return resultHandler(nil, false) } // Credentials are valid! resultHandler(nil, true) } } // Subscribe to single topic public func subscribe(topic: String, handler: @escaping (Error?) -> Void) { // Call multi-topic subscribe function subscribe(topics: [topic], handler: handler) } // Subscribe to multiple topics public func subscribe(topics: [String], handler: @escaping (Error?) -> Void) { // Load device token & auth guard let pushyToken = PushySettings.getString(PushySettings.pushyToken), let pushyTokenAuth = PushySettings.getString(PushySettings.pushyTokenAuth) else { return handler(PushyRegistrationException.Error("Failed to load the device credentials.")) } // Prepare request params let params: [String:Any] = ["token": pushyToken, "auth": pushyTokenAuth, "topics": topics] // Execute post request PushyHTTP.postAsync(self.getApiEndpoint() + "/devices/subscribe", params: params) { (err: Error?, response: [String:AnyObject]?) -> () in // JSON parse error? if err != nil { // Throw network error and stop execution return handler(err) } // Unwrap json guard let json = response else { return handler(PushyPubSubException.Error("An invalid response was encountered when subscribing the device to topic(s).")) } // Get success value let success = json["success"] as! Bool // Verify subscribe success if !success { return handler(PushyPubSubException.Error("An invalid response was encountered.")) } // Subscribe success handler(nil) } } // Unsubscribe from single topic public func unsubscribe(topic: String, handler: @escaping (Error?) -> Void) { // Call multi-topic unsubscribe function unsubscribe(topics: [topic], handler: handler) } // Unsubscribe from multiple topics public func unsubscribe(topics: [String], handler: @escaping (Error?) -> Void) { // Load device token & auth guard let pushyToken = PushySettings.getString(PushySettings.pushyToken), let pushyTokenAuth = PushySettings.getString(PushySettings.pushyTokenAuth) else { return handler(PushyRegistrationException.Error("Failed to load the device credentials.")) } // Prepare request params let params: [String:Any] = ["token": pushyToken, "auth": pushyTokenAuth, "topics": topics] // Execute post request PushyHTTP.postAsync(self.getApiEndpoint() + "/devices/unsubscribe", params: params) { (err: Error?, response: [String:AnyObject]?) -> () in // JSON parse error? if err != nil { // Throw network error and stop execution return handler(err) } // Unwrap json guard let json = response else { return handler(PushyPubSubException.Error("An invalid response was encountered when unsubscribing the device to topic(s).")) } // Get success value let success = json["success"] as! Bool // Verify unsubscribe success if !success { return handler(PushyPubSubException.Error("An invalid response was encountered.")) } // Unsubscribe success handler(nil) } } // Support for Pushy Enterprise public func setEnterpriseConfig(apiEndpoint: String?) { // If nil, clear persisted Pushy Enterprise API endpoint if (apiEndpoint == nil) { return PushySettings.setString(PushySettings.pushyEnterpriseApi, nil) } // Mutable variable var endpoint = apiEndpoint! // Strip trailing slash if endpoint.hasSuffix("/") { endpoint = String(endpoint.prefix(endpoint.count - 1)) } // Fetch previous enterprise endpoint let previousEndpoint = PushySettings.getString(PushySettings.pushyEnterpriseApi) // Check if this is a new API endpoint URL if endpoint != previousEndpoint { // Unregister device PushySettings.setString(PushySettings.apnsToken, nil) PushySettings.setString(PushySettings.pushyToken, nil) PushySettings.setString(PushySettings.pushyTokenAuth, nil) } // Persist enterprise API endpoint PushySettings.setString(PushySettings.pushyEnterpriseApi, endpoint) } // Device registration check public func isRegistered() -> Bool { // Attempt to fetch persisted Pushy token let token = PushySettings.getString(PushySettings.pushyToken) // Check for existance of non-nil token return token != nil; } // API endpoint getter function public func getApiEndpoint() -> String { // Check for a configured enterprise API endpoint let enterpriseApiEndpoint = PushySettings.getString(PushySettings.pushyEnterpriseApi) // Default to public Pushy API if missing if enterpriseApiEndpoint == nil { return PushyConfig.apiBaseUrl } // Return enterprise endpoint return enterpriseApiEndpoint! } // APNs failed to register the device for push notifications @objc public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { // Call the registration handler, if defined (pass empty string as token) Pushy.shared?.registrationHandler?(error, "") } // Device received notification @objc public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // Call the notification handler, if defined Pushy.shared?.notificationHandler?(userInfo, completionHandler) } }
41.90534
212
0.609731
e9b87a3d8bfba3a775674e0a91a0b27ce4b5acdd
4,646
import Foundation /// This is the element for referencing other targets through content proxies. public final class PBXTargetDependency: PBXObject { // MARK: - Attributes /// Target name. public var name: String? /// Target reference. var targetReference: PBXObjectReference? /// Target. public var target: PBXTarget? { get { return targetReference?.getObject() } set { targetReference = newValue?.reference } } /// Target proxy reference. var targetProxyReference: PBXObjectReference? /// Target proxy. public var targetProxy: PBXContainerItemProxy? { get { return targetProxyReference?.getObject() } set { targetProxyReference = newValue?.reference } } /// Product reference. var productReference: PBXObjectReference? /// Product. public var product: XCSwiftPackageProductDependency? { get { return productReference?.getObject() } set { productReference = newValue?.reference } } /// Platform filter attribute. /// Introduced in: Xcode 11 public var platformFilter: String? // MARK: - Init /// Initializes the target dependency with dependencies as objects. /// /// - Parameters: /// - name: Dependency name. /// - platformFilter: Platform filter. /// - target: Target. /// - targetProxy: Target proxy. public init(name: String? = nil, platformFilter: String? = nil, target: PBXTarget? = nil, targetProxy: PBXContainerItemProxy? = nil, product: XCSwiftPackageProductDependency? = nil) { self.name = name self.platformFilter = platformFilter targetReference = target?.reference targetProxyReference = targetProxy?.reference productReference = product?.reference super.init() } // MARK: - Decodable fileprivate enum CodingKeys: String, CodingKey { case name case platformFilter case target case targetProxy case productRef } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let referenceRepository = decoder.context.objectReferenceRepository let objects = decoder.context.objects name = try container.decodeIfPresent(.name) platformFilter = try container.decodeIfPresent(.platformFilter) if let targetReference: String = try container.decodeIfPresent(.target) { self.targetReference = referenceRepository.getOrCreate(reference: targetReference, objects: objects) } if let targetProxyReference: String = try container.decodeIfPresent(.targetProxy) { self.targetProxyReference = referenceRepository.getOrCreate(reference: targetProxyReference, objects: objects) } if let productReference: String = try container.decodeIfPresent(.productRef) { self.productReference = referenceRepository.getOrCreate(reference: productReference, objects: objects) } try super.init(from: decoder) } } // MARK: - PlistSerializable extension PBXTargetDependency: PlistSerializable { func plistKeyAndValue(proj _: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = [:] dictionary["isa"] = .string(CommentedString(PBXTargetDependency.isa)) if let name = name { dictionary["name"] = .string(CommentedString(name)) } if let platformFilter = platformFilter { dictionary["platformFilter"] = .string(CommentedString(platformFilter)) } if let targetReference = targetReference { let targetObject: PBXTarget? = targetReference.getObject() dictionary["target"] = .string(CommentedString(targetReference.value, comment: targetObject?.name)) } if let targetProxyReference = targetProxyReference { dictionary["targetProxy"] = .string(CommentedString(targetProxyReference.value, comment: "PBXContainerItemProxy")) } if let productReference = productReference { dictionary["productRef"] = .string(CommentedString(productReference.value, comment: product?.productName)) } return (key: CommentedString(reference, comment: "PBXTargetDependency"), value: .dictionary(dictionary)) } }
35.465649
126
0.642488
212442e571fbda07109559812a9cc7119935e57e
13,887
import SafariServices final class SafariExtensionHandler: SFSafariExtensionHandler { private let service = SourceKitServiceProxy.shared override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) { switch messageName { case "initialize": let settings = Settings() guard settings.automaticallyCheckoutsRepository else { return } guard let userInfo = userInfo, let url = userInfo["url"] as? String, let owner = userInfo["owner"] as? String, owner != "trending", let repositoryURL = URL(string: url)?.deletingPathExtension().appendingPathExtension("git") else { return } self.service.synchronizeRepository(repositoryURL) { (_, _) in } case "didOpen": guard let userInfo = userInfo, let resource = userInfo["resource"] as? String, let slug = userInfo["slug"] as? String, let filepath = userInfo["filepath"] as? String, let text = userInfo["text"] as? String else { return } service.sendInitializeRequest(resource: resource, slug: slug) { [weak self] (successfully, _) in guard let self = self else { return } if successfully { self.service.sendInitializedNotification(resource: resource, slug: slug) { [weak self] (successfully, _) in guard let self = self else { return } if successfully { self.service.sendDidOpenNotification(resource: resource, slug: slug, path: filepath, text: text) { [weak self] (successfully, _) in guard let self = self else { return } if successfully { self.service.sendDocumentSymbolRequest(resource: resource, slug: slug, path: filepath) { (successfully, response) in guard let value = response["value"] else { return } page.dispatchMessageToScript(withName: "response", userInfo: ["request": "documentSymbol", "result": "success", "value": value]) } } } } } } } case "hover": guard let userInfo = userInfo, let resource = userInfo["resource"] as? String, let slug = userInfo["slug"] as? String, let filepath = userInfo["filepath"] as? String , let line = userInfo["line"] as? Int, let character = userInfo["character"] as? Int, let text = userInfo["text"] as? String else { return } var skip = 0 for character in text { if character == " " || character == "." { skip += 1 } else { break } } service.sendHoverRequest(resource: resource, slug: slug, path: filepath, line: line, character: character + skip) { (successfully, response) in if successfully { if let value = response["value"] as? String { page.dispatchMessageToScript( withName: "response", userInfo: ["request": "hover", "result": "success", "value": value, "line": line, "character": character, "text": text] ) } } else { page.dispatchMessageToScript(withName: "response", userInfo: ["request": "hover", "result": "error"]) } } case "definition": guard let userInfo = userInfo, let resource = userInfo["resource"] as? String, let slug = userInfo["slug"] as? String, let filepath = userInfo["filepath"] as? String , let line = userInfo["line"] as? Int, let character = userInfo["character"] as? Int, let text = userInfo["text"] as? String else { return } var skip = 0 for character in text { if character == " " || character == "." { skip += 1 } else { break } } service.sendDefinitionRequest(resource: resource, slug: slug, path: filepath, line: line, character: character + skip) { (successfully, response) in if successfully { if let value = response["value"] as? [[String: Any]] { let locations = value.compactMap { (location) -> [String: Any]? in guard let uri = location["uri"] as? String, let start = location["start"] as? [String: Any], let line = start["line"] as? Int else { return nil } let filename = location["filename"] ?? "" let lineNumber = line + 1 let content = location["content"] ?? "" if !uri.isEmpty { let ref = uri .replacingOccurrences(of: resource, with: "") .replacingOccurrences(of: slug, with: "") .split(separator: "/") .joined(separator: "/") .appending("#L\(line + 1)") return ["uri": ref, "filename": filename, "lineNumber": lineNumber, "content": content] } else { return ["uri": "", "filename": filename, "lineNumber": lineNumber, "content": content] } } guard !locations.isEmpty else { return } page.dispatchMessageToScript( withName: "response", userInfo: ["request": "definition", "result": "success", "value": ["locations": locations], "line": line, "character": character, "text": text] ) } } else { page.dispatchMessageToScript(withName: "response", userInfo: ["request": "definition", "result": "error"]) } } case "references": guard let userInfo = userInfo, let resource = userInfo["resource"] as? String, let slug = userInfo["slug"] as? String, let filepath = userInfo["filepath"] as? String , let line = userInfo["line"] as? Int, let character = userInfo["character"] as? Int, let text = userInfo["text"] as? String else { return } var skip = 0 for character in text { if character == " " || character == "." { skip += 1 } else { break } } service.sendReferencesRequest(resource: resource, slug: slug, path: filepath, line: line, character: character + skip) { (successfully, response) in if successfully { if let value = response["value"] as? [[String: Any]] { let locations = value.compactMap { (location) -> [String: Any]? in guard let uri = location["uri"] as? String, let start = location["start"] as? [String: Any], let line = start["line"] as? Int else { return nil } let filename = location["filename"] ?? "" let lineNumber = line + 1 let content = location["content"] .flatMap { $0 as? String } .flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines) } ?? "" if !uri.isEmpty { let ref = uri .replacingOccurrences(of: resource, with: "") .replacingOccurrences(of: slug, with: "") .split(separator: "/") .joined(separator: "/") .appending("#L\(lineNumber)") return ["uri": ref, "filename": filename, "lineNumber": lineNumber, "content": content] } else { return ["uri": "", "filename": filename, "lineNumber": lineNumber, "content": content] } } guard !locations.isEmpty else { return } page.dispatchMessageToScript( withName: "response", userInfo: ["request": "references", "result": "success", "value": ["locations": locations], "line": line, "character": character, "text": text] ) } } else { page.dispatchMessageToScript(withName: "response", userInfo: ["request": "references", "result": "error"]) } } case "documentHighlight": guard let userInfo = userInfo, let resource = userInfo["resource"] as? String, let slug = userInfo["slug"] as? String, let filepath = userInfo["filepath"] as? String , let line = userInfo["line"] as? Int, let character = userInfo["character"] as? Int, let text = userInfo["text"] as? String else { return } var skip = 0 for character in text { if character == " " || character == "." { skip += 1 } else { break } } service.sendDocumentHighlightRequest(resource: resource, slug: slug, path: filepath, line: line, character: character + skip) { (successfully, response) in if successfully { if let value = response["value"] as? [[String: Any]] { page.dispatchMessageToScript( withName: "response", userInfo: ["request": "documentHighlight", "result": "success", "value": ["documentHighlights": value], "line": line, "character": character, "text": text] ) } } else { page.dispatchMessageToScript(withName: "response", userInfo: ["request": "documentHighlight", "result": "error"]) } } default: break } } override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) { validationHandler(true, "") } override func popoverWillShow(in window: SFSafariWindow) { let viewController = SafariExtensionViewController.shared viewController.updateUI { [weak self] in guard let self = self else { return } let settings = Settings() if settings.server == .default { self.service.defaultLanguageServerPath { (successfully, response) in if successfully { settings.serverPath = response viewController.serverPath = response } } } self.service.defaultSDKPath(for: settings.sdk.rawValue) { (successfully, response) in if successfully { settings.sdkPath = response viewController.sdkPath = response } } window.getActiveTab { (activeTab) in guard let activeTab = activeTab else { return } activeTab.getActivePage { (activePage) in guard let activePage = activePage else { return } activePage.getPropertiesWithCompletionHandler { [weak self] (properties) in guard let self = self else { return } guard let properties = properties, let url = properties.url else { return } guard let repositoryURL = parseGitHubURL(url) else { viewController.repository = "" return } viewController.repository = repositoryURL.absoluteString viewController.checkoutDirectory = nil viewController.lastUpdate = nil self.service.localCheckoutDirectory(for: repositoryURL) { (successfully, response) in viewController.checkoutDirectory = successfully ? response : nil } self.service.lastUpdate(for: repositoryURL) { (successfully, response) in viewController.lastUpdate = successfully ? response : nil } } } } } } override func popoverViewController() -> SFSafariExtensionViewController { let viewController = SafariExtensionViewController.shared return viewController } }
48.555944
183
0.468136
0a31a122509af75fe1e582be4354a528f4495515
2,378
// // THMainViewController.swift // AudioLooper_Swift // // Created by nathan on 2020/12/25. // import UIKit class THMainViewController: UIViewController,THPlayerControllerDelegate { @IBOutlet var rateKnob: THControlKnob! @IBOutlet weak var playButton: THPlayButton! @IBOutlet weak var playLabel: UILabel! @IBOutlet var panKnobs: [THControlKnob]! @IBOutlet var volumeKnobs: [THControlKnob]! let controller: THPlayerController = THPlayerController.init() override func viewDidLoad() { super.viewDidLoad() controller.delegate = self // self.rateKnob.minimumValue = 0.5 // self.rateKnob.maximumValue = 1.5 // self.rateKnob.value = 1.0 // self.rateKnob.defaultValue = 1.0 for knob in panKnobs { knob.minimumValue = -1.0 knob.maximumValue = 1.0 knob.value = 0.0 knob.defaultValue = 0.0 } for knob in volumeKnobs { knob.minimumValue = 0.0 knob.maximumValue = 1.0 knob.value = 1.0 knob.defaultValue = 1.0 } } @IBAction func play(_ sender: THPlayButton) { if controller.playing { controller.play() playLabel.text = NSLocalizedString("Stop", comment: "") }else{ controller.stop() playLabel.text = NSLocalizedString("Play", comment: "") } playButton.isSelected = !playButton.isSelected } @IBAction func adjustRate(_ sender: THControlKnob) { controller.adjustRate(rate: sender.value!) } @IBAction func adjustPan(_ sender: THOrangeControlKnob) { controller.adjustPan(pan: sender.value!, index: sender.tag) } @IBAction func adjusVolume(_ sender: THOrangeControlKnob) { controller.adjustVolume(volume: sender.value!, index: sender.tag) } func playebackStopped() { playButton.isSelected = false playLabel.text = NSLocalizedString("Play", comment: "") } func playbackBegan() { playButton.isSelected = true playLabel.text = NSLocalizedString("Stop", comment: "") } override var prefersStatusBarHidden: Bool{ get{ return true } } }
25.297872
73
0.584104
f9809d0dc36a7611ed4d3408feaf68b86138e84b
6,627
// // SettingDeviceInfo.swift // Chromatic // // Created by Lakr Aream on 2021/8/28. // Copyright © 2021 Lakr Aream. All rights reserved. // import UIKit extension SettingView { func setupDeviceInfoSection(anchor: inout UIView, safeAnchor: UIView) { let label0 = UILabel() label0.font = .systemFont(ofSize: 18, weight: .semibold) label0.text = NSLocalizedString("DEVICE_INFORMATION", comment: "Device Information") addSubview(label0) label0.snp.makeConstraints { x in x.left.equalTo(safeAnchor) x.right.equalTo(safeAnchor) x.top.equalTo(anchor.snp.bottom) // .offset(20) x.height.equalTo(40) } anchor = label0 let groupEffect0 = UIView() groupEffect0.backgroundColor = UIColor(named: "CARD_BACKGROUND") groupEffect0.layer.cornerRadius = 12 // groupEffect0.dropShadow() let deviceInfo = SettingElement(iconSystemNamed: "info.circle", text: DeviceInfo.current.machine, dataType: .none, initData: nil) { _, _ in } let systemVersion = SettingElement(iconSystemNamed: "", text: UIDevice.current.systemName + " - " + UIDevice.current.systemVersion, dataType: .none, initData: nil) { _, _ in } let udid = SettingElement(iconSystemNamed: "", text: DeviceInfo.current.realDeviceIdentity.uppercased(), dataType: .none, initData: nil, withAction: nil) udid.label.font = .monospacedSystemFont(ofSize: 16, weight: .semibold) let enableRandomDeviceInfo = SettingElement(iconSystemNamed: "eye.slash", text: NSLocalizedString("RANDOM_INDO", comment: "Random Info"), dataType: .switcher, initData: { !DeviceInfo.current.useRealDeviceInfo ? "YES" : "NO" }) { changeValueTo, _ in if changeValueTo ?? false { let alert = UIAlertController(title: "⚠️", message: NSLocalizedString("ENABLE_RANDOM_DEVICE_INFO_WILL_DISABLE_COMMERCIAL_OPERATIONS", comment: "Enable random device info will disable commercial operations"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("CONFIRM", comment: "Confirm"), style: .destructive, handler: { _ in DeviceInfo.current.useRealDeviceInfo = false self.dispatchValueUpdate() })) alert.addAction(UIAlertAction(title: NSLocalizedString("CANCEL", comment: "Cancel"), style: .cancel, handler: { _ in self.dispatchValueUpdate() })) self.parentViewController?.present(alert, animated: true, completion: nil) } else { DeviceInfo.current.useRealDeviceInfo = true self.dispatchValueUpdate() } } let userAgentControl = SettingElement(iconSystemNamed: "grid.circle.fill", text: NSLocalizedString("USER_AGENT", comment: "User Agent"), dataType: .submenuWithAction) { var ret = InterfaceBridge.mainUserAgent if ret.count < 1 { ret = "_" } return ret } withAction: { _, _ in let alert = UIAlertController(title: NSLocalizedString("USER_AGENT", comment: "User Agent"), message: "", preferredStyle: .alert) alert.addTextField { field in field.text = InterfaceBridge.mainUserAgent if field.text?.count ?? 0 < 1 { field.text = "Saily/2.0 Cydia/1.1.32" } } alert.addAction(UIAlertAction(title: NSLocalizedString("CANCEL", comment: "Cancel"), style: .cancel, handler: { _ in self.dispatchValueUpdate() })) alert.addAction(UIAlertAction(title: NSLocalizedString("CONFIRM", comment: "Confirm"), style: .default, handler: { [weak alert, weak self] _ in if let text = alert?.textFields?[0].text { InterfaceBridge.mainUserAgent = text } self?.dispatchValueUpdate() })) self.parentViewController?.present(alert, animated: true, completion: nil) } addSubview(groupEffect0) addSubview(deviceInfo) addSubview(systemVersion) addSubview(udid) addSubview(enableRandomDeviceInfo) addSubview(userAgentControl) deviceInfo.snp.makeConstraints { x in makeElement(constraint: x, widthAnchor: safeAnchor, topAnchor: anchor) } anchor = deviceInfo systemVersion.snp.makeConstraints { x in makeElement(constraint: x, widthAnchor: safeAnchor, topAnchor: anchor) } anchor = systemVersion udid.snp.makeConstraints { x in makeElement(constraint: x, widthAnchor: safeAnchor, topAnchor: anchor) } anchor = udid enableRandomDeviceInfo.snp.makeConstraints { x in makeElement(constraint: x, widthAnchor: safeAnchor, topAnchor: anchor) } anchor = enableRandomDeviceInfo userAgentControl.snp.makeConstraints { x in makeElement(constraint: x, widthAnchor: safeAnchor, topAnchor: anchor) } anchor = userAgentControl groupEffect0.snp.makeConstraints { x in x.left.equalTo(safeAnchor.snp.left) x.right.equalTo(safeAnchor.snp.right) x.top.equalTo(deviceInfo.snp.top).offset(-12) x.bottom.equalTo(anchor.snp.bottom).offset(16) } anchor = groupEffect0 } }
50.587786
210
0.52105
e5f81029387917e6559fdad70c1602717660bf10
1,216
// Copyright © 2017 Oath. All rights reserved. import UIKit import OneMobileSDK import PlayerControls class ViewController: UIViewController { @IBAction func playVideoTouched(_ sender: Any) { OneSDK.Provider.default.getSDK() .then { $0.getPlayer(videoID: "577cc23d50954952cc56bc47") } .dispatch(on: .main) .onSuccess { player in let playerViewController = PlayerViewController() playerViewController.contentControlsViewController = DefaultControlsViewController() playerViewController.player = player self.navigationController?.pushViewController(playerViewController, animated: true) } .onError { error in let alert = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } }
40.533333
100
0.54523
e0130548bac5e04f6eaa90c193d81ad01ce97db8
611
// // UIEdgeInsets.swift // ARQuest // // Created by Anton Poltoratskyi on 30.04.2018. // Copyright © 2018 Anton Poltoratskyi. All rights reserved. // import UIKit extension UIEdgeInsets { public var horizontal: CGFloat { return left + right } public var vertical: CGFloat { return top + bottom } } extension CGRect { public func insetBy(edges: UIEdgeInsets) -> CGRect { return CGRect( x: minX + edges.left, y: minY + edges.top, width: width - edges.horizontal, height: height - edges.vertical ) } }
20.366667
61
0.594108
bfe8201b2fe8ceb4cde8390806b34fc2c63b8adc
431
// // Copyright © 2021 Rosberry. All rights reserved. // public protocol HasGithubService { var githubService: GithubService { get } } public protocol GithubService { func getGitRepoPath(repo: String) throws -> String func downloadFiles(at repo: String, filesHandler: ([FileInfo]) throws -> Void) throws @discardableResult func downloadFiles(at repo: String, to destination: String) throws -> [FileInfo] }
25.352941
89
0.721578
cc9d21f42928dbaaedb034d8aefc22b99ea6098f
5,035
/// Test the generated private textual module interfaces and that the public /// one doesn't leak SPI decls and info. // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module %S/Inputs/spi_helper.swift -module-name SPIHelper -emit-module-path %t/SPIHelper.swiftmodule -swift-version 5 -enable-library-evolution -emit-module-interface-path %t/SPIHelper.swiftinterface -emit-private-module-interface-path %t/SPIHelper.private.swiftinterface /// Make sure that the public swiftinterface of spi_helper doesn't leak SPI. // RUN: %FileCheck -check-prefix=CHECK-HELPER %s < %t/SPIHelper.swiftinterface // CHECK-HELPER-NOT: HelperSPI // CHECK-HELPER-NOT: @_spi // RUN: %target-swift-frontend -emit-module %t/SPIHelper.swiftinterface -emit-module-path %t/SPIHelper-from-public-swiftinterface.swiftmodule -swift-version 5 -module-name SPIHelper -enable-library-evolution /// Test the textual interfaces generated from this test. // RUN: %target-swift-frontend -typecheck %s -emit-module-interface-path %t/main.swiftinterface -emit-private-module-interface-path %t/main.private.swiftinterface -enable-library-evolution -swift-version 5 -I %t // RUN: %FileCheck -check-prefix=CHECK-PUBLIC %s < %t/main.swiftinterface // RUN: %FileCheck -check-prefix=CHECK-PRIVATE %s < %t/main.private.swiftinterface /// Serialize and deserialize this module, then print. // RUN: %target-swift-frontend -emit-module %s -emit-module-path %t/merged-partial.swiftmodule -swift-version 5 -I %t -module-name merged -enable-library-evolution // RUN: %target-swift-frontend -merge-modules %t/merged-partial.swiftmodule -module-name merged -emit-module -emit-module-path %t/merged.swiftmodule -I %t -emit-module-interface-path %t/merged.swiftinterface -emit-private-module-interface-path %t/merged.private.swiftinterface -enable-library-evolution -swift-version 5 -I %t // RUN: %FileCheck -check-prefix=CHECK-PUBLIC %s < %t/merged.swiftinterface // RUN: %FileCheck -check-prefix=CHECK-PRIVATE %s < %t/merged.private.swiftinterface @_spi(HelperSPI) @_spi(OtherSPI) @_spi(OtherSPI) import SPIHelper // CHECK-PUBLIC: import SPIHelper // CHECK-PRIVATE: @_spi(OtherSPI) @_spi(HelperSPI) import SPIHelper public func foo() {} // CHECK-PUBLIC: foo() // CHECK-PRIVATE: foo() @_spi(MySPI) @_spi(MyOtherSPI) public func localSPIFunc() {} // CHECK-PRIVATE: @_spi(MySPI) // CHECK-PRIVATE: localSPIFunc() // CHECK-PUBLIC-NOT: localSPIFunc() // SPI declarations @_spi(MySPI) public class SPIClassLocal { // CHECK-PRIVATE: @_spi(MySPI) public class SPIClassLocal // CHECK-PUBLIC-NOT: class SPIClassLocal public init() {} } @_spi(MySPI) public extension SPIClassLocal { // CHECK-PRIVATE: @_spi(MySPI) extension SPIClassLocal // CHECK-PUBLIC-NOT: extension SPIClassLocal @_spi(MySPI) func extensionMethod() {} // CHECK-PRIVATE: @_spi(MySPI) public func extensionMethod // CHECK-PUBLIC-NOT: func extensionMethod internal func internalExtensionMethod() {} // CHECK-PRIVATE-NOT: internalExtensionMethod // CHECK-PUBLIC-NOT: internalExtensionMethod func inheritedSPIExtensionMethod() {} // CHECK-PRIVATE: inheritedSPIExtensionMethod // CHECK-PUBLIC-NOT: inheritedSPIExtensionMethod } public extension SPIClassLocal { internal func internalExtensionMethode1() {} // CHECK-PRIVATE-NOT: internalExtensionMethod1 // CHECK-PUBLIC-NOT: internalExtensionMethod1 } class InternalClassLocal {} // CHECK-PRIVATE-NOT: InternalClassLocal // CHECK-PUBLIC-NOT: InternalClassLocal private class PrivateClassLocal {} // CHECK-PRIVATE-NOT: PrivateClassLocal // CHECK-PUBLIC-NOT: PrivateClassLocal @_spi(LocalSPI) public func useOfSPITypeOk(_ p: SPIClassLocal) -> SPIClassLocal { fatalError() } // CHECK-PRIVATE: @_spi(LocalSPI) public func useOfSPITypeOk // CHECK-PUBLIC-NOT: useOfSPITypeOk @_spi(LocalSPI) extension SPIClass { // CHECK-PRIVATE: @_spi(LocalSPI) extension SPIClass // CHECK-PUBLIC-NOT: SPIClass @_spi(LocalSPI) public func extensionSPIMethod() {} // CHECK-PRIVATE: @_spi(LocalSPI) public func extensionSPIMethod() // CHECK-PUBLIC-NOT: extensionSPIMethod } // Test the dummy conformance printed to replace private types used in // conditional conformances. rdar://problem/63352700 // Conditional conformances using SPI types should appear in full in the // private swiftinterface. public struct PublicType<T> {} @_spi(LocalSPI) public protocol SPIProto {} private protocol PrivateConstraint {} @_spi(LocalSPI) public protocol SPIProto2 {} @_spi(LocalSPI) extension PublicType: SPIProto2 where T: SPIProto2 {} // CHECK-PRIVATE: extension PublicType : {{.*}}.SPIProto2 where T : {{.*}}.SPIProto2 // CHECK-PUBLIC-NOT: _ConstraintThatIsNotPartOfTheAPIOfThisLibrary // The dummy conformance should be only in the private swiftinterface for // SPI extensions. @_spi(LocalSPI) extension PublicType: SPIProto where T: PrivateConstraint {} // CHECK-PRIVATE: extension {{.*}}.PublicType : {{.*}}.SPIProto where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary // CHECK-PUBLIC-NOT: _ConstraintThatIsNotPartOfTheAPIOfThisLibrary
44.955357
325
0.769017
e80c84f666623992053b009236de120f32787ee8
3,931
// REQUIRES: objc_interop // RUN: rm -rf %t // RUN: mkdir -p %t // FIXME: BEGIN -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/AppKit.swift // FIXME: END -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -I %S/Inputs/custom-modules -o %t %s -disable-objc-attr-requires-foundation-module -swift-version 3 // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library %t/swift3_deprecated_objc_inference.swiftmodule -typecheck -I %S/Inputs/custom-modules -emit-objc-header-path %t/swift3_deprecated_objc_inference.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module -swift-version 3 // RUN: %FileCheck %s < %t/swift3_deprecated_objc_inference.h // RUN: %check-in-clang -I %S/Inputs/custom-modules/ %t/swift3_deprecated_objc_inference.h import Foundation // CHECK-LABEL: @interface A1{{$}} // CHECK-NEXT: init // CHECK-NEXT: @end @objc class A1 { } // CHECK-LABEL: @interface A2{{$}} // CHECK-NEXT: - (nonnull instancetype)initWithA2:(A2 * _Nonnull)a2 OBJC_DESIGNATED_INITIALIZER SWIFT_DEPRECATED_MSG("Swift initializer 'A2.init(a2:)' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint"); // CHECK-NEXT: - (void)foo SWIFT_DEPRECATED_MSG("Swift method 'A2.foo()' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint"); // CHECK-NEXT: + (void)bar SWIFT_DEPRECATED_MSG("Swift method 'A2.bar()' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint"); // CHECK-NEXT: @property (nonatomic, strong) A2 * _Nullable property SWIFT_DEPRECATED_MSG("Swift property 'A2.property' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint"); // CHECK-NEXT: SWIFT_CLASS_PROPERTY(@property (nonatomic, class, strong) A2 * _Nullable static_property SWIFT_DEPRECATED_MSG("Swift property 'A2.static_property' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint");) // CHECK-NEXT: + (A2 * _Nullable)static_property SWIFT_WARN_UNUSED_RESULT SWIFT_DEPRECATED_MSG("Swift property 'A2.static_property' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint"); // CHECK-NEXT: + (void)setStatic_property:(A2 * _Nullable)value SWIFT_DEPRECATED_MSG("Swift property 'A2.static_property' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint"); // CHECK-NEXT: - (A2 * _Nonnull)objectAtIndexedSubscript:(NSInteger)i SWIFT_WARN_UNUSED_RESULT SWIFT_DEPRECATED_MSG("Swift subscript 'A2.subscript(_:)' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint"); // CHECK-NEXT: - (void)setObject:(A2 * _Nonnull)newValue atIndexedSubscript:(NSInteger)i SWIFT_DEPRECATED_MSG("Swift subscript 'A2.subscript(_:)' uses '@objc' inference deprecated in Swift 4; add '@objc' to provide an Objective-C entrypoint"); // CHECK-NEXT: @end @objc class A2 { init(a2: A2) { } func foo() { } class func bar() { } var property: A2? = nil static var static_property: A2? = nil subscript (i: Int) -> A2 { get { return self } set { } } }
83.638298
354
0.736708
9b954132d2ed616fc45a18164d133521aafd0acf
432
import Foundation import MealPorts internal class MockPrice : Price { var students: Double? var employees: Double? var pupils: Double? var others: Double? internal init(students: Double? = nil, employees: Double? = nil, pupils: Double? = nil, others: Double? = nil) { self.students = students self.employees = employees self.pupils = pupils self.others = others } }
25.411765
116
0.634259
1653c9ece50a5cd9d0d07b386f2b4fa7f38cf676
1,735
// // AvailableCardsViewModel.swift // MercadoPagoSDK // // Created by Eden Torres on 29/11/2018. // import Foundation internal class AvailableCardsViewModel { let MARGIN_X_SCROLL_VIEW: CGFloat = 32 let MIN_HEIGHT_PERCENT: CGFloat = 0.73 let screenSize: CGRect let screenHeight: CGFloat let screenWidth: CGFloat var paymentMethods: [PXPaymentMethod]! init(paymentMethods: [PXPaymentMethod]) { self.paymentMethods = paymentMethods self.screenSize = UIScreen.main.bounds self.screenHeight = screenSize.height self.screenWidth = screenSize.width } func getDatailViewFrame() -> CGRect { let availableCardsViewWidth = screenWidth - 2 * MARGIN_X_SCROLL_VIEW let availableCardsViewTotalHeight = getAvailableCardsViewTotalHeight(headerHeight: AvailableCardsDetailView.HEADER_HEIGHT, paymentMethodsHeight: AvailableCardsDetailView.ITEMS_HEIGHT, paymentMethodsCount: CGFloat(self.paymentMethods.count)) let xPos = (self.screenWidth - availableCardsViewWidth) / 2 let yPos = (self.screenHeight - availableCardsViewTotalHeight) / 2 return CGRect(x: xPos, y: yPos, width: availableCardsViewWidth, height: availableCardsViewTotalHeight) } func getEnterCardMessage() -> String { return "Ingresar otra tarjeta".localized } func getAvailableCardsViewTotalHeight(headerHeight: CGFloat, paymentMethodsHeight: CGFloat, paymentMethodsCount: CGFloat) -> CGFloat { var totalHeight = headerHeight + paymentMethodsHeight * paymentMethodsCount if totalHeight > screenHeight * MIN_HEIGHT_PERCENT { totalHeight = screenHeight * MIN_HEIGHT_PERCENT } return totalHeight } }
36.914894
248
0.732565
0125b0a7bce80794489c32d5ab586542a748e021
3,365
// // ViewController.swift // RandomUserGenerator // // Created by Wilson Ding on 10/10/16. // Copyright © 2016 Wilson Ding. All rights reserved. // import UIKit import RandomUserSwift class ViewController: UIViewController { var randomUser: RandomUser! = RandomUser() @IBOutlet weak var thumbnailImage: UIImageView! @IBOutlet weak var genderLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var passwordLabel: UILabel! @IBOutlet weak var saltLabel: UILabel! @IBOutlet weak var md5Label: UILabel! @IBOutlet weak var sha1Label: UILabel! @IBOutlet weak var sha256Label: UILabel! @IBOutlet weak var dobLabel: UILabel! @IBOutlet weak var registeredLabel: UILabel! @IBOutlet weak var homePhoneLabel: UILabel! @IBOutlet weak var cellPhoneLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() randomUser.gender = "female" randomUser.nationality = "us" getNewRandomUser() } @IBAction func newUserButtonPressed(_ sender: AnyObject) { getNewRandomUser() } func getNewRandomUser() { randomUser.getUser { success, user in if success { if let randUser = user as? User { // You can now access every aspect of the user. let imageUrl = URL(string: randUser.pictureLargeURL) let imageData = try? Data(contentsOf: imageUrl!) self.thumbnailImage.image = UIImage(data: imageData!) self.genderLabel.text = "Gender: \(randUser.gender)" self.nameLabel.text = "Name: \(randUser.title.capitalizingFirstLetter()). \(randUser.firstName.capitalizingFirstLetter()) \(randUser.lastName.capitalizingFirstLetter())" self.locationLabel.text = "Location: \(randUser.street) \(randUser.city) \(randUser.state) \(randUser.zip)" self.emailLabel.text = "Email: \(randUser.email)" self.usernameLabel.text = "Username: \(randUser.username)" self.passwordLabel.text = "Password: \(randUser.password)" self.saltLabel.text = "Salt: \(randUser.salt)" self.md5Label.text = "md5: \(randUser.md5)" self.sha1Label.text = "sha1: \(randUser.sha1)" self.sha256Label.text = "sha256: \(randUser.sha256)" self.dobLabel.text = "Date of Birth: \(randUser.dateOfBirth)" self.registeredLabel.text = "Date Registered: \(randUser.dateRegistered)" self.homePhoneLabel.text = "Home Phone: \(randUser.homePhone)" self.cellPhoneLabel.text = "Cell Phone: \(randUser.cellPhone)" } } } } } extension String { func capitalizingFirstLetter() -> String { let first = String(characters.prefix(1)).capitalized let other = String(characters.dropFirst()) return first + other } mutating func capitalizeFirstLetter() { self = self.capitalizingFirstLetter() } }
37.388889
189
0.60416
8f289d04c4d58f1f575a19a6cee17780f397d701
792
// // CoChannelReceiverProtocol.swift // SwiftCoroutine // // Created by Alex Belozierov on 11.05.2020. // Copyright © 2020 Alex Belozierov. All rights reserved. // internal protocol CoChannelReceiverProtocol { associatedtype Output func awaitReceive() throws -> Output func poll() -> Output? func receiveFuture() -> CoFuture<Output> func whenReceive(_ callback: @escaping (Result<Output, CoChannelError>) -> Void) var count: Int { get } var isEmpty: Bool { get } var isClosed: Bool { get } func cancel() var isCanceled: Bool { get } func whenComplete(_ callback: @escaping () -> Void) var maxBufferSize: Int { get } } extension CoChannel: CoChannelReceiverProtocol {} extension CoChannel.Receiver: CoChannelReceiverProtocol {}
28.285714
84
0.693182
643be5c22b65e78e2ee654b1a3d8d8cb333b7638
6,041
// // Codable-DefaultValue.swift // Enhancement // // Created by Weiwenshe on 2018/8/30. // Copyright © 2018 com.weiwenshe. All rights reserved. // import Foundation // MARK: - 参考https://github.com/Pircate/CleanJSON, 使用 Codable 协议时, json 中不存在该key-value时, 可以提供初始值, 而不是自己实现协议 public extension KeyedDecodingContainer { public func decode(_ type: Bool.Type, forKey key: KeyedDecodingContainer.Key) throws -> Bool { return try decodeIfPresent(type, forKey: key) ?? false } public func decode(_ type: String.Type, forKey key: KeyedDecodingContainer.Key) throws -> String { return try decodeIfPresent(type, forKey: key) ?? "" } public func decode(_ type: Double.Type, forKey key: KeyedDecodingContainer.Key) throws -> Double { return try decodeIfPresent(type, forKey: key) ?? 0.0 } public func decode(_ type: Float.Type, forKey key: KeyedDecodingContainer.Key) throws -> Float { return try decodeIfPresent(type, forKey: key) ?? 0.0 } public func decode(_ type: Int.Type, forKey key: KeyedDecodingContainer.Key) throws -> Int { return try decodeIfPresent(type, forKey: key) ?? 0 } public func decode(_ type: UInt.Type, forKey key: KeyedDecodingContainer.Key) throws -> UInt { return try decodeIfPresent(type, forKey: key) ?? 0 } public func decode<T>(_ type: T.Type, forKey key: KeyedDecodingContainer.Key) throws -> T where T : Decodable { if let value = try decodeIfPresent(type, forKey: key) { return value } else if let objectValue = try? JSONDecoder().decode(type, from: "{}".data(using: .utf8)!) { return objectValue } else if let arrayValue = try? JSONDecoder().decode(type, from: "[]".data(using: .utf8)!) { return arrayValue } else if let stringValue = try decode(String.self, forKey: key) as? T { return stringValue } else if let boolValue = try decode(Bool.self, forKey: key) as? T { return boolValue } else if let intValue = try decode(Int.self, forKey: key) as? T { return intValue } else if let uintValue = try decode(UInt.self, forKey: key) as? T { return uintValue } else if let doubleValue = try decode(Double.self, forKey: key) as? T { return doubleValue } else if let floatValue = try decode(Float.self, forKey: key) as? T { return floatValue } let context = DecodingError.Context(codingPath: [key], debugDescription: "Key: <\(key.stringValue)> cannot be decoded") throw DecodingError.dataCorrupted(context) } public func decodeIfPresent(_ type: Bool.Type, forKey key: K) throws -> Bool? { guard contains(key) else { return nil } let decoder = try superDecoder(forKey: key) let container = try decoder.singleValueContainer() return try? container.decode(type) } public func decodeIfPresent(_ type: String.Type, forKey key: K) throws -> String? { guard contains(key) else { return nil } let decoder = try superDecoder(forKey: key) let container = try decoder.singleValueContainer() if let value = try? container.decode(type) { return value } else if let intValue = try? container.decode(Int.self) { return String(intValue) } else if let doubleValue = try? container.decode(Double.self) { return String(doubleValue) } else if let boolValue = try? container.decode(Bool.self) { return String(boolValue) } return nil } public func decodeIfPresent(_ type: Double.Type, forKey key: K) throws -> Double? { guard contains(key) else { return nil } let decoder = try superDecoder(forKey: key) let container = try decoder.singleValueContainer() if let value = try? container.decode(type) { return value } else if let stringValue = try? container.decode(String.self) { return Double(stringValue) } return nil } public func decodeIfPresent(_ type: Float.Type, forKey key: K) throws -> Float? { guard contains(key) else { return nil } let decoder = try superDecoder(forKey: key) let container = try decoder.singleValueContainer() if let value = try? container.decode(type) { return value } else if let stringValue = try? container.decode(String.self) { return Float(stringValue) } return nil } public func decodeIfPresent(_ type: Int.Type, forKey key: K) throws -> Int? { guard contains(key) else { return nil } let decoder = try superDecoder(forKey: key) let container = try decoder.singleValueContainer() if let value = try? container.decode(type) { return value } else if let stringValue = try? container.decode(String.self) { return Int(stringValue) } return nil } public func decodeIfPresent(_ type: UInt.Type, forKey key: K) throws -> UInt? { guard contains(key) else { return nil } let decoder = try superDecoder(forKey: key) let container = try decoder.singleValueContainer() if let value = try? container.decode(type) { return value } else if let stringValue = try? container.decode(String.self) { return UInt(stringValue) } return nil } public func decodeIfPresent<T>(_ type: T.Type, forKey key: K) throws -> T? where T : Decodable { guard contains(key) else { return nil } let decoder = try superDecoder(forKey: key) let container = try decoder.singleValueContainer() return try? container.decode(type) } }
37.521739
127
0.607681
162f031e679081fe80d3a216599e05ff2d8eaf22
179
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(MovieFrameTests.allTests) ] } #endif
17.9
49
0.603352
f9da7be205e676b6c4cf896cbb457c554119a76e
4,935
/* The MIT License * * Copyright (c) 2017 NBCO Yandex.Money LLC * * 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 CoreGraphics import UIKit // MARK: - Extension for generating and changing image extension UIImage { /// Generate image of color of {1, 1} size. /// /// - parameter color: color of new image /// /// - returns: generated image static func image(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("Can't get graphic context") return UIImage() } context.setFillColor(color.cgColor) context.fill(rect) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure("Can't get image from context") return UIImage() } return image } /// Scale image to size. /// /// - parameter size: size for scaling /// /// - returns: new scaled image func scaled(to size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("Can't get graphic context") return self } let rect = CGRect(origin: .zero, size: size) context.clear(rect) draw(in: rect) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure("Can't get image from context") return self } return image } /// Round image with corner radius. /// /// - parameter cornerRadius: corner radius for rounding /// /// - returns: new rounded image image func rounded(cornerRadius: CGFloat) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("Can't get graphic context") return self } let rect = CGRect(origin: .zero, size: size) context.addPath(UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath) context.clip() draw(in: rect) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure("Can't get image from context") return self } return image } } // MARK: - Internal image tools extension UIImage { /// Generate image with tint color /// /// - parameter color: color of new image /// /// - returns: generated image func colorizedImage(color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("Can't get graphic context") return self } context.translateBy(x: 0, y: self.size.height) context.scaleBy(x: 1.0, y: -1.0) context.setBlendMode(CGBlendMode.normal) let rect = CGRect(origin: .zero, size: size) guard let cgImage = self.cgImage else { assertionFailure("Can't get cgimage") return self } context.clip(to: rect, mask: cgImage) color.setFill() context.fill(rect) guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure("Can't get image from context") return self } return newImage } }
33.344595
91
0.638298
16351cb6f9930c6df6131af02d8d340710f4a8c9
278
// // kampanya.swift // JSON-Example // // Created by Caner Uçar on 14.09.2018. // Copyright © 2018 Caner Uçar. All rights reserved. // import Foundation struct Kampanya:Codable{ var baslik:String? var icerik:String? var tarih:String? var resim:String? }
15.444444
53
0.669065
de2dd170278768cb0355ab055a6a9afc1dca2328
1,443
// // Example5ViewController.swift // StellarDemo // // Created by AugustRush on 6/1/16. // Copyright © 2016 August. All rights reserved. // import UIKit class Example5ViewController: UIViewController { @IBOutlet weak var cyanView: UIView! override func viewDidLoad() { super.viewDidLoad() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) let rotation: CGFloat = .pi * 20.0 cyanView.makeSize(CGSize(width: 100, height: 30)).snap() .then().moveY(-100).snap(1) .then().rotate(rotation) .duration(2) .easing(.swiftOut) .makeHeight(100) .cornerRadius(50) .then().moveY(100).gravity() .then().moveY(-80) .then().moveY(80).gravity() .then().moveY(-40) .then().moveY(40).gravity() .then().makeWidth(120) .makeHeight(30) .cornerRadius(15) .easing(.swiftOut) .makeColor(UIColor.brown) .animate() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) //will cancel all remaining animations // cyanView.cancelAllRemaining() } }
28.294118
79
0.534997
d5eab7a5911037e684e70c966ce1b69f2d645c76
1,265
// // VDLBinaryExpressionsAPITests // MockDummyOperand.swift // // // Created by Valeriano Della Longa on 20/02/2020. // Copyright (c) 2020 Valeriano Della Longa // import Foundation import VDLBinaryExpressionsAPI enum MockDummyOperand { case dummy enum Error: Swift.Error { case mapOperandFailed case mapOperatorFailed case mappedOperationFail } static func mapOperand(_ operand: MockBinaryOperator.Operand) throws -> Self { return .dummy } static func mapOperator (_ operator: MockBinaryOperator) throws -> BinaryOperation<MockDummyOperand> { return { _, _ in return .dummy } } static func mapOperandFail (_ operand: MockBinaryOperator.Operand) throws -> Self { throw Error.mapOperandFailed } static func mapOperatorFail (_ operator: MockBinaryOperator) throws -> BinaryOperation<MockDummyOperand> { throw Error.mapOperatorFailed } static func mapOperatorToFailingOperation (_ operator: MockBinaryOperator) throws -> BinaryOperation<MockDummyOperand> { return { _, _ in throw Error.mappedOperationFail } } }
21.810345
65
0.638735
ac337f20bacc53af68ea7f9a8dca7224cbe26b5b
219
import Foundation final class RecursiveLock { private let lock = NSRecursiveLock() func sync<T>(function: () -> T) -> T { lock.lock() defer { lock.unlock() } return function() } }
16.846154
42
0.56621
d618d2a72a97601dedebeae5b39c4de82cf251bd
4,384
// // UnderlinedTextView.swift // StatusApp // // Created by Massimiliano Bigatti on 26/09/14. // Copyright (c) 2014 Massimiliano Bigatti. All rights reserved. // import UIKit import QuartzCore /** Controls that embeds an UITextView and supports highlighting and auto-growth */ class UnderlinedTextView : UIControl, UITextViewDelegate { // MARK: - Public Properties /// current text var text : String { get { return textView.text } set { textView.text = newValue } } /// reference to associated label @IBOutlet var associatedLabel : UILabel? /// active color, used to highlight the text view and associated label when the control is selected var activeColor : UIColor = UIColor.whiteColor() { didSet { updateActiveColor() } } /// calculated control height, used by the containing view controller to adjust the layout of the view var calculatedHeight : CGFloat { get { return textView.calculatedHeight() } } // MARK: - Private Properties /// internal `UITextView` private var textView = UITextView() /// layer used to display the text field underline private let underlineLayer = CALayer() /// underline height when the text view have focus private let underlineHighlightedHeight : CGFloat = 2 // underline height when the text view does not have focus private let underlineNormalHeight : CGFloat = 1 // MARK: - Lifecycle required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } func commonInit() { backgroundColor = UIColor.clearColor() layer.addSublayer(underlineLayer) textView.textColor = UIColor.whiteColor() textView.backgroundColor = UIColor.clearColor() //textView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5) textView.tintColor = UIColor.whiteColor() textView.font = UIFont.systemFontOfSize(17) textView.contentInset = UIEdgeInsets(top: -4, left: -4, bottom: 0, right: 0) textView.scrollEnabled = false textView.delegate = self addSubview(textView) // setup geometry of internal text view layoutSubviews() } // MARK: - UIControl override func layoutSublayersOfLayer(layer: CALayer!) { super.layoutSublayersOfLayer(layer); if (layer == self.layer) { let h = textView.isFirstResponder() ? underlineHighlightedHeight : underlineNormalHeight let frame = CGRect(x: CGFloat(0), y: bounds.size.height - h, width: bounds.size.width, height: h); underlineLayer.frame = frame } } override func layoutSubviews() { let h = textView.isFirstResponder() ? underlineHighlightedHeight : underlineNormalHeight textView.frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width, height: bounds.size.height - h)) updateActiveColor() } /// forward focus management to internal `UITextView` override func becomeFirstResponder() -> Bool { return textView.becomeFirstResponder() } /// forward focus management to internal `UITextView` override func resignFirstResponder() -> Bool { return textView.resignFirstResponder() } // MARK: - UITextViewDelegate func textViewDidBeginEditing(textView: UITextView) { setNeedsLayout() } func textViewDidEndEditing(textView: UITextView) { setNeedsLayout() } func textViewDidChange(textView: UITextView) { sendActionsForControlEvents(.ValueChanged) } // MARK: - Privates /// updates the color of the underline and associated label with the correct color func updateActiveColor() { let color = textView.isFirstResponder() ? activeColor : UIColor.blackColor().colorWithAlphaComponent(0.5) underlineLayer.backgroundColor = color.CGColor if let label = associatedLabel { label.textColor = color } } }
28.653595
126
0.630018
39ec3dfb4eee13f5630b660921aa47192c02262b
1,482
// // Solution.swift // Problem 33 // // Created by sebastien FOCK CHOW THO on 2019-06-27. // Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved. // import Foundation extension Array where Element == Int { func binarySearchInsertIndex(_ element: Int) -> Int { var leftBoundary = 0 var rightBoundary = self.count-1 while leftBoundary <= rightBoundary { let mid = (leftBoundary + rightBoundary) / 2 if self[mid] > element { rightBoundary = mid - 1 } else if self[mid] < element { leftBoundary = mid + 1 } else { return mid } } return leftBoundary } func spawnProgressiveMedians() -> [Double] { var result: [Double] = [] var orderedArray: [Int] = [] for element in self { orderedArray.insert(element, at: orderedArray.binarySearchInsertIndex(element)) if orderedArray.count % 2 == 0 { let median = Double(orderedArray[orderedArray.count/2-1] + orderedArray[orderedArray.count/2]) / 2 result.append(median) print(median) } else { let median = Double(orderedArray[orderedArray.count/2]) result.append(median) print(median) } } return result } }
27.444444
114
0.518893
91692e32b0c32a8999f7801971ba7f3446ae6018
9,963
// // EFIconFontWeatherIcons.swift // EFIconFont // // Created by EyreFree on 2019/3/20. // // Copyright (c) 2019 EyreFree <[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. import Foundation #if canImport(EFIconFontCore) import EFIconFontCore #endif public extension EFIconFont { static let weatherIcons = EFIconFontWeatherIcons.self } extension EFIconFontWeatherIcons: EFIconFontCaseIterableProtocol { public static var name: String { return "weathericons" } public var unicode: String { return self.rawValue } } public enum EFIconFontWeatherIcons: String { case wiSnowflakeCold = "\u{edd6}" case wiSnowWind = "\u{edd5}" case wiSnow = "\u{edd4}" case wiUmbrella = "\u{edd3}" case wiWindBeaufort11 = "\u{edd2}" case wiStormShowers = "\u{edd1}" case wiTornado = "\u{edd0}" case wiTsunami = "\u{edcf}" case wiWindBeaufort2 = "\u{edce}" case wiWindBeaufort3 = "\u{edcd}" case wiThermometerExterior = "\u{edcc}" case wiWindBeaufort4 = "\u{edcb}" case wiWindBeaufort5 = "\u{edca}" case wiTrain = "\u{edc9}" case wiWindBeaufort8 = "\u{edc8}" case wiTime10 = "\u{edc7}" case wiSprinkle = "\u{edc6}" case wiNightStormShowers = "\u{edc5}" case wiWindDeg = "\u{edc4}" case wiWindBeaufort12 = "\u{edc3}" case wiWindBeaufort0 = "\u{edc2}" case wiWindBeaufort10 = "\u{edc1}" case wiRefreshAlt = "\u{edc0}" case wiSolarEclipse = "\u{edbf}" case wiSleet = "\u{edbe}" case wiWindBeaufort9 = "\u{edbd}" case wiWindBeaufort1 = "\u{edbc}" case wiWindy = "\u{edbb}" case wiVolcano = "\u{edba}" case wiRainWind = "\u{edb9}" case wiThunderstorm = "\u{edb8}" case wiNightSnow = "\u{edb7}" case wiWindBeaufort7 = "\u{edb6}" case wiRainMix = "\u{edb5}" case wiWindBeaufort6 = "\u{edb4}" case wiTime7 = "\u{edb3}" case wiTime11 = "\u{edb2}" case wiTime12 = "\u{edb1}" case wiSmoke = "\u{edb0}" case wiShowers = "\u{edaf}" case wiStars = "\u{edae}" case wiTime8 = "\u{edad}" case wiSandstorm = "\u{edac}" case wiTime9 = "\u{edab}" case wiTime4 = "\u{edaa}" case wiTime6 = "\u{eda9}" case wiTime2 = "\u{eda8}" case wiTime1 = "\u{eda7}" case wiTime5 = "\u{eda6}" case wiNightSleet = "\u{eda5}" case wiNightSnowWind = "\u{eda4}" case wiNightSnowThunderstorm = "\u{eda3}" case wiTime3 = "\u{eda2}" case wiStrongWind = "\u{eda1}" case wiThermometerInternal = "\u{eda0}" case wiSunrise = "\u{ed9f}" case wiThermometer = "\u{ed9e}" case wiSunset = "\u{ed9d}" case wiNightSleetStorm = "\u{ed9c}" case wiSmog = "\u{ed9b}" case wiStormWarning = "\u{ed9a}" case wiNightRainMix = "\u{ed99}" case wiNightHail = "\u{ed98}" case wiNightRainWind = "\u{ed97}" case wiSmallCraftAdvisory = "\u{ed96}" case wiNightShowers = "\u{ed95}" case wiRaindrop = "\u{ed94}" case wiRefresh = "\u{ed93}" case wiRain = "\u{ed92}" case wiNightThunderstorm = "\u{ed91}" case wiNightSprinkle = "\u{ed90}" case wiRaindrops = "\u{ed8f}" case wiNightAltSnow = "\u{ed8e}" case wiNightAltThunderstorm = "\u{ed8d}" case wiNightAltSnowWind = "\u{ed8c}" case wiNightAltRainWind = "\u{ed8b}" case wiNightAltStormShowers = "\u{ed8a}" case wiNightAltSnowThunderstorm = "\u{ed89}" case wiNightRain = "\u{ed88}" case wiNightAltSleetStorm = "\u{ed87}" case wiNightAltSprinkle = "\u{ed86}" case wiNightAltRainMix = "\u{ed85}" case wiNightAltShowers = "\u{ed84}" case wiNightAltSleet = "\u{ed83}" case wiNightAltRain = "\u{ed82}" case wiNightAltHail = "\u{ed81}" case wiNightAltCloudyGusts = "\u{ed80}" case wiNightPartlyCloudy = "\u{ed7f}" case wiNightCloudyWindy = "\u{ed7e}" case wiNightLightning = "\u{ed7d}" case wiNightFog = "\u{ed7c}" case wiNightCloudyHigh = "\u{ed7b}" case wiNightCloudy = "\u{ed7a}" case wiNightClear = "\u{ed79}" case wiNightCloudyGusts = "\u{ed78}" case wiNightAltCloudy = "\u{ed77}" case wiMoonWaxingGibbous2 = "\u{ed76}" case wiNightAltPartlyCloudy = "\u{ed75}" case wiNightAltCloudyWindy = "\u{ed74}" case wiNightAltLightning = "\u{ed73}" case wiMoonset = "\u{ed72}" case wiMoonWaxingGibbous4 = "\u{ed71}" case wiMoonWaxingGibbous6 = "\u{ed70}" case wiNightAltCloudyHigh = "\u{ed6f}" case wiMoonWaxingGibbous3 = "\u{ed6e}" case wiMoonAltWaxingGibbous4 = "\u{ed6d}" case wiMoonWaxingGibbous5 = "\u{ed6c}" case wiMoonWaxingCrescent5 = "\u{ed6b}" case wiMoonWaxingCrescent3 = "\u{ed6a}" case wiMoonrise = "\u{ed69}" case wiNa = "\u{ed68}" case wiMoonWaxingCrescent6 = "\u{ed67}" case wiMoonWaningGibbous3 = "\u{ed66}" case wiMoonWaningCrescent4 = "\u{ed65}" case wiMoonWaxingCrescent4 = "\u{ed64}" case wiMoonWaxingCrescent2 = "\u{ed63}" case wiMoonWaxingGibbous1 = "\u{ed62}" case wiMoonWaningGibbous6 = "\u{ed61}" case wiMoonWaxingCrescent1 = "\u{ed60}" case wiMoonWaningGibbous5 = "\u{ed5f}" case wiMoonWaningCrescent5 = "\u{ed5e}" case wiMoonWaningGibbous1 = "\u{ed5d}" case wiMoonThirdQuarter = "\u{ed5c}" case wiMoonFull = "\u{ed5b}" case wiMoonWaningGibbous4 = "\u{ed5a}" case wiMoonWaningCrescent3 = "\u{ed59}" case wiMoonWaningCrescent6 = "\u{ed58}" case wiMoonWaningCrescent2 = "\u{ed57}" case wiMoonFirstQuarter = "\u{ed56}" case wiMoonWaningGibbous2 = "\u{ed55}" case wiMoonWaningCrescent1 = "\u{ed54}" case wiMoonNew = "\u{ed53}" case wiMoonAltWaxingGibbous6 = "\u{ed52}" case wiMoonAltWaxingGibbous5 = "\u{ed51}" case wiMoonAltWaxingGibbous3 = "\u{ed50}" case wiMoonAltWaxingCrescent3 = "\u{ed4f}" case wiMoonAltWaxingCrescent4 = "\u{ed4e}" case wiMoonAltWaxingGibbous2 = "\u{ed4d}" case wiMoonAltWaxingCrescent6 = "\u{ed4c}" case wiMoonAltWaxingGibbous1 = "\u{ed4b}" case wiMoonAltWaxingCrescent5 = "\u{ed4a}" case wiMoonAltWaningGibbous5 = "\u{ed49}" case wiMoonAltWaxingCrescent1 = "\u{ed48}" case wiMoonAltWaningCrescent2 = "\u{ed47}" case wiMoonAltWaningGibbous6 = "\u{ed46}" case wiMoonAltWaxingCrescent2 = "\u{ed45}" case wiMoonAltWaningCrescent6 = "\u{ed44}" case wiMoonAltWaningGibbous3 = "\u{ed43}" case wiMoonAltWaningGibbous4 = "\u{ed42}" case wiHorizon = "\u{ed41}" case wiHot = "\u{ed40}" case wiMoonAltWaningCrescent4 = "\u{ed3f}" case wiMoonAltWaningCrescent3 = "\u{ed3e}" case wiMoonAltWaningGibbous1 = "\u{ed3d}" case wiMoonAltWaningGibbous2 = "\u{ed3c}" case wiMoonAltWaningCrescent5 = "\u{ed3b}" case wiMoonAltWaningCrescent1 = "\u{ed3a}" case wiMoonAltThirdQuarter = "\u{ed39}" case wiMeteor = "\u{ed38}" case wiMoonAltFull = "\u{ed37}" case wiMoonAltNew = "\u{ed36}" case wiMoonAltFirstQuarter = "\u{ed35}" case wiHurricane = "\u{ed34}" case wiHurricaneWarning = "\u{ed33}" case wiLunarEclipse = "\u{ed32}" case wiLightning = "\u{ed31}" case wiHorizonAlt = "\u{ed30}" case wiHumidity = "\u{ed2f}" case wiFire = "\u{ed2e}" case wiHail = "\u{ed2d}" case wiGaleWarning = "\u{ed2c}" case wiFog = "\u{ed2b}" case wiDirectionUpRight = "\u{ed2a}" case wiFlood = "\u{ed29}" case wiFahrenheit = "\u{ed28}" case wiDust = "\u{ed27}" case wiDirectionRight = "\u{ed26}" case wiEarthquake = "\u{ed25}" case wiDirectionUpLeft = "\u{ed24}" case wiDayThunderstorm = "\u{ed23}" case wiDayWindy = "\u{ed22}" case wiDirectionUp = "\u{ed21}" case wiDirectionDownLeft = "\u{ed20}" case wiDirectionDown = "\u{ed1f}" case wiDirectionLeft = "\u{ed1e}" case wiDaySunny = "\u{ed1d}" case wiDirectionDownRight = "\u{ed1c}" case wiDegrees = "\u{ed1b}" case wiDaySunnyOvercast = "\u{ed1a}" case wiDaySprinkle = "\u{ed19}" case wiDaySleet = "\u{ed18}" case wiDayStormShowers = "\u{ed17}" case wiDaySnowThunderstorm = "\u{ed16}" case wiDaySnow = "\u{ed15}" case wiDayShowers = "\u{ed14}" case wiDayRainMix = "\u{ed13}" case wiDaySnowWind = "\u{ed12}" case wiDayRain = "\u{ed11}" case wiDaySleetStorm = "\u{ed10}" case wiDayLightning = "\u{ed0f}" case wiDayHaze = "\u{ed0e}" case wiDayCloudy = "\u{ed0d}" case wiDayRainWind = "\u{ed0c}" case wiDayHail = "\u{ed0b}" case wiDayLightWind = "\u{ed0a}" case wiDayCloudyWindy = "\u{ed09}" case wiCloudyGusts = "\u{ed08}" case wiDayCloudyGusts = "\u{ed07}" case wiDayFog = "\u{ed06}" case wiDayCloudyHigh = "\u{ed05}" case wiCloudy = "\u{ed04}" case wiCloudRefresh = "\u{ed03}" case wiCloud = "\u{ed02}" case wiCloudyWindy = "\u{ed01}" case wiCloudUp = "\u{ed00}" case wiCloudDown = "\u{ecff}" case wiBarometer = "\u{ecfe}" case wiCelsius = "\u{ecfd}" case wiAlien = "\u{ecfc}" }
37.037175
81
0.649905
01b09e31f5a646e5292c682722d9460d11658b80
4,041
// // Notification.swift // PeoplePortal // // Created by Anastasis Germanidis on 10/11/15. // Copyright (c) 2015 Anastasis Germanidis. All rights reserved. // import UIKit class Notification: Comparable { var type : Int? var users : [User]? var tweet : Tweet? var otherTweets: [Tweet]? var seen: Bool = false var ctime: NSDate? init() { ctime = NSDate() } func isFollow() -> Bool { return type == Constants.NOTIFICATION_TYPE_FOLLOW } func isMention() -> Bool { return type == Constants.NOTIFICATION_TYPE_MENTION } func isRetweet() -> Bool { return type == Constants.NOTIFICATION_TYPE_RETWEET } static func deserialize(serialized: Dict) -> Notification { let ret = Notification() ret.type = serialized["type"] as? Int if serialized["users"] != nil { ret.users = (serialized["users"] as! [Dict]).map({ User.deserialize($0) }) } if serialized["tweet"] != nil { ret.tweet = Tweet.deserialize(serialized["tweet"]! as! Dict) } if serialized["other_tweets"] != nil { ret.otherTweets = (serialized["other_tweets"] as! [Dict]).map({Tweet.deserialize($0)}) } ret.seen = serialized["seen"] as! Bool ret.ctime = NSDate.fromString(serialized["created_at"] as! String) return ret } func serialize() -> Dict { var ret = Dict() ret["type"] = self.type! if self.users != nil { ret["users"] = self.users!.map({ $0.serialize() }) } if self.tweet != nil { ret["tweet"] = self.tweet!.serialize() } if self.otherTweets != nil { ret["other_tweets"] = self.otherTweets!.map({ $0.serialize() }) } ret["seen"] = seen ret["created_at"] = ctime!.toString() return ret } var attributedText: NSAttributedString? { if self.isFollow() { let message = NSMutableAttributedString() message.appendAttributedString(Utils.createUserAttributedString(users![0].name!)) if users!.count == 2 { message.appendAttributedString(Utils.regularAttributedString(" and ")) message.appendAttributedString(Utils.createUserAttributedString(users![1].name!)) } var restOfMessage = "" if users!.count > 2 { restOfMessage += " and \(users!.count-1) others" } restOfMessage += " followed you" message.appendAttributedString(Utils.regularAttributedString(restOfMessage)) return message } else if self.isRetweet() { let message = NSMutableAttributedString() let retweeters = otherTweets!.map({$0.user!}) message.appendAttributedString(Utils.createUserAttributedString(retweeters[0].name!)) if retweeters.count == 2 { message.appendAttributedString(Utils.regularAttributedString(" and ")) message.appendAttributedString(Utils.createUserAttributedString(retweeters[1].name!)) } var restOfMessage = "" if retweeters.count > 2 { restOfMessage += " and \(retweeters.count-1) others" } restOfMessage += " retweeted " if tweet?.user?.userId == Session.shared.shadowedUser?.user.userId { restOfMessage += "your tweet" } else { restOfMessage += "a tweet you were mentioned in" } message.appendAttributedString(Utils.regularAttributedString(restOfMessage)) return message } return nil } var text: String? { return attributedText?.string } } func < (lhs: Notification, rhs: Notification) -> Bool { return lhs.ctime < rhs.ctime } func == (lhs: Notification, rhs: Notification) -> Bool { return lhs.ctime == rhs.ctime }
33.675
101
0.571393
906c10534231ba15be677f6f3d88303ac2398962
4,962
// // SwipeableStackView.swift // Swipeable-View-Stack // // Created by Phill Farrugia on 10/21/17. // Copyright © 2017 Phill Farrugia. All rights reserved. // import UIKit class SwipeableCardViewContainer: UIView, SwipeableViewDelegate { static let horizontalInset: CGFloat = 12.0 static let verticalInset: CGFloat = 12.0 var dataSource: SwipeableCardViewDataSource? { didSet { reloadData() } } var delegate: SwipeableCardViewDelegate? private var cardViews: [SwipeableCardViewCard] = [] var visibleCardViews: [SwipeableCardViewCard] { return subviews as? [SwipeableCardViewCard] ?? [] } fileprivate var remainingCards: Int = 0 static let numberOfVisibleCards: Int = 2 override func awakeFromNib() { super.awakeFromNib() backgroundColor = .clear translatesAutoresizingMaskIntoConstraints = false } /// Reloads the data used to layout card views in the /// card stack. Removes all existing card views and /// calls the dataSource to layout new card views. func reloadData() { removeAllCardViews() guard let dataSource = dataSource else { return } let numberOfCards = dataSource.numberOfCards() remainingCards = numberOfCards for index in 0..<min(numberOfCards, SwipeableCardViewContainer.numberOfVisibleCards) { addCardView(cardView: dataSource.card(forItemAtIndex: index), atIndex: index) } if let emptyView = dataSource.viewForEmptyCards() { addEdgeConstrainedSubView(view: emptyView) } setNeedsLayout() } func addCardView(cardView: SwipeableCardViewCard, atIndex index: Int) { cardView.delegate = self setFrame(forCardView: cardView, atIndex: index) cardViews.append(cardView) insertSubview(cardView, at: 0) remainingCards -= 1 } private func removeAllCardViews() { for cardView in visibleCardViews { cardView.removeFromSuperview() } cardViews = [] } /// Sets the frame of a card view provided for a given index. Applies a specific /// horizontal and vertical offset relative to the index in order to create an /// overlay stack effect on a series of cards. /// /// - Parameters: /// - cardView: card view to update frame on /// - index: index used to apply horizontal and vertical insets private func setFrame(forCardView cardView: SwipeableCardViewCard, atIndex index: Int) { var cardViewFrame = bounds let horizontalInset = (CGFloat(index) * SwipeableCardViewContainer.horizontalInset) let verticalInset = CGFloat(index) * SwipeableCardViewContainer.verticalInset cardViewFrame.size.width -= 2 * horizontalInset cardViewFrame.origin.x += horizontalInset cardViewFrame.origin.y += verticalInset cardView.frame = cardViewFrame } } // MARK: - SwipeableViewDelegate extension SwipeableCardViewContainer { func didTap(view: SwipeableView) { if let cardView = view as? SwipeableCardViewCard, let index = cardViews.index(of: cardView) { delegate?.didSelect(card: cardView, atIndex: index) } } func didBeginSwipe(onView view: SwipeableView) { // React to Swipe Began? } func didEndSwipe(onView view: SwipeableView, direction: SwipeDirection) { guard let dataSource = dataSource else { return } if direction == .bottomLeft || direction == .topLeft || direction == .left { self.delegate?.tryedToSwipeLeft() return } // Remove swiped card UIView.animate(withDuration: 0.4, animations: { view.layer.opacity = 0 }) { _ in view.removeFromSuperview() } // Only add a new card if there are cards remaining if remainingCards > 0 { // Calculate new card's index let newIndex = dataSource.numberOfCards() - remainingCards // Add new card as Subview addCardView(cardView: dataSource.card(forItemAtIndex: newIndex), atIndex: 1) } if let cardView = view as? SwipeableCardViewCard { delegate?.didSwipe(card: cardView, toDirection: direction, last: visibleCardViews.count == 1) } // Update all existing card's frames based on new indexes, animate frame change // to reveal new card from underneath the stack of existing cards. for (cardIndex, cardView) in visibleCardViews.reversed().enumerated() { UIView.animate(withDuration: 1, animations: { cardView.center = self.center self.setFrame(forCardView: cardView, atIndex: cardIndex-1) self.layoutIfNeeded() }) } } }
30.819876
105
0.635631
9cc0b83aa47ab1cd9b9465a4a0297cf2c1faff5f
823
// // MainWindowModel.swift // Postgres // // Created by Chris on 17/08/2016. // Copyright © 2016 postgresapp. All rights reserved. // import Cocoa class MainWindowModel: NSObject { @objc dynamic var serverManager = ServerManager.shared @objc dynamic var selectedServerIndices = IndexSet() var firstSelectedServer: Server? { guard let selIdx = selectedServerIndices.first else { return nil } return serverManager.servers[selIdx] } func removeSelectedServer() { guard let selIdx = selectedServerIndices.first else { return } serverManager.servers.remove(at: selIdx) if selIdx > 0 { selectedServerIndices = IndexSet(integer: selIdx-1) } else { selectedServerIndices = IndexSet(integer: 0) } } } protocol MainWindowModelConsumer { var mainWindowModel: MainWindowModel! { get set } }
22.243243
68
0.735115
4833a1e63849038c427feeeb4579b9eb2fda925a
2,154
// // ViewController.swift // ChatClient // // Created by Anisha Jain on 4/12/17. // Copyright © 2017 Anisha Jain. All rights reserved. // import UIKit import Parse class ViewController: UIViewController { @IBOutlet weak var emailText: UITextField! @IBOutlet weak var passwordText: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onSignUp(_ sender: Any) { //let emailId = emailText.text //let password = passwordText.text myMethod() } @IBAction func onLogin(_ sender: Any) { let username = emailText.text let pass = passwordText.text PFUser.logInWithUsername(inBackground: username!, password: pass!) { (user: PFUser?, error: Error?) in if user != nil { print("I am logedin") self.performSegue(withIdentifier: "chatSegue", sender: nil) } else { print("The login failed. Check error to see why.", error?.localizedDescription) } } } func myMethod() { var user = PFUser() user.username = emailText.text user.password = passwordText.text user.email = "[email protected]" // other fields can be set just like with PFObject //user["phone"] = "415-392-0202" user.signUpInBackground(block: { (succeeded: Bool, error: Error?) in if let error = error { //let errorString = error.userInfo["error"] as? NSString print(error.localizedDescription) // Show the errorString somewhere and let the user try again. } else { self.performSegue(withIdentifier: "sigupSegue", sender: nil) // Hooray! Let them use the app now. } }) } }
29.108108
110
0.571959
fbff597c6226e1f57e21f5c7e09da18797a46903
636
import XCTest @testable import Puzzles class SetAndForgetTest: XCTestCase { func testPartOne() { let scanner = SingleValueScanner<Int>(testCaseName: "17", separator: CharacterSet(charactersIn: ",")) let program = scanner.parse() let sut = SetAndForget() XCTAssertEqual(sut.solvePartOne(memory: program), 5068) } func testPartTwo() { let scanner = SingleValueScanner<Int>(testCaseName: "17", separator: CharacterSet(charactersIn: ",")) let program = scanner.parse() let sut = SetAndForget() XCTAssertEqual(sut.solvePartTwo(memory: program), 1415975) } }
31.8
109
0.668239
11be1866dd5791019ee3e4d86b842ed8488e27e9
2,593
/* OSCDispatcher.swift Koboshi MIT LICENSE Copyright 2018 nariakiiwatani 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 SwiftOSC protocol OSCServerDelegateExt : class, OSCServerDelegate { } class OSCDispatcher : OSCServerDelegateExt { var delegates:[OSCServerDelegateExt] = [] func add(_ newDelegate:OSCServerDelegateExt) { delegates.append(newDelegate) } func remove(_ delegate:OSCServerDelegateExt) { delegates = delegates.filter { $0 !== delegate } } func didReceive(_ data: Data) { delegates.forEach { (d:OSCServerDelegateExt) in d.didReceive(data) } } func didReceive(_ bundle: SwiftOSC.OSCBundle) { delegates.forEach { (d:OSCServerDelegateExt) in d.didReceive(bundle) } } func didReceive(_ message: SwiftOSC.OSCMessage) { delegates.forEach { (d:OSCServerDelegateExt) in d.didReceive(message) } } } class OSCServerMulti { private var servers = [Int:(OSCServer,OSCDispatcher)]() private func createServer(port:Int) -> (OSCServer,OSCDispatcher) { let server = OSCServer(address: "", port: port) let dispatcher = OSCDispatcher() server.delegate = dispatcher server.running = true servers.updateValue((server, dispatcher), forKey: port) return servers[port]! } private func getServer(port:Int) -> (OSCServer,OSCDispatcher) { return servers[port] ?? createServer(port: port) } func register(port:Int, receiver:OSCServerDelegateExt) { getServer(port: port).1.add(receiver) } func unregister(port:Int, receiver:OSCServerDelegateExt) { getServer(port: port).1.remove(receiver) } static var global = OSCServerMulti() }
36.013889
460
0.767065
e2e25c474e8ec5448d205a7cd927b375fbdb7d40
2,111
// // AppDelegate.swift // My App // // Created by Guanming Qiao on 6/15/17. // Copyright © 2017 Guanming Qiao. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. } }
44.914894
281
0.776883
ed6274dac00dfbe106b9e1ccd355663dc865a2e3
1,758
// // LoginRouter.swift // Viper // // Created by Shridhar Mali on 7/7/17. // Copyright (c) 2017 Shridhar Mali. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit @objc protocol LoginRoutingLogic { //func routeToSomewhere(segue: UIStoryboardSegue?) } protocol LoginDataPassing { var dataStore: LoginDataStore? { get } } class LoginRouter: NSObject, LoginRoutingLogic, LoginDataPassing { weak var viewController: LoginViewController? var dataStore: LoginDataStore? // MARK: Routing //func routeToSomewhere(segue: UIStoryboardSegue?) //{ // if let segue = segue { // let destinationVC = segue.destination as! SomewhereViewController // var destinationDS = destinationVC.router!.dataStore! // passDataToSomewhere(source: dataStore!, destination: &destinationDS) // } else { // let storyboard = UIStoryboard(name: "Main", bundle: nil) // let destinationVC = storyboard.instantiateViewController(withIdentifier: "SomewhereViewController") as! SomewhereViewController // var destinationDS = destinationVC.router!.dataStore! // passDataToSomewhere(source: dataStore!, destination: &destinationDS) // navigateToSomewhere(source: viewController!, destination: destinationVC) // } //} // MARK: Navigation //func navigateToSomewhere(source: LoginViewController, destination: SomewhereViewController) //{ // source.show(destination, sender: nil) //} // MARK: Passing data //func passDataToSomewhere(source: LoginDataStore, destination: inout SomewhereDataStore) //{ // destination.name = source.name //} }
28.819672
135
0.719568
f91040576b576a9b1d6ef2d9ad1f2bf7e6c0676d
1,742
// // LibraryAPI.swift // PokedexGo // // Created by Yi Gu on 7/10/16. // Copyright © 2016 yigu. All rights reserved. // import UIKit class LibraryAPI: NSObject { static let sharedInstance = LibraryAPI() let persistencyManager = PersistencyManager() private override init() { super.init() NotificationCenter.default .addObserver(self, selector:#selector(LibraryAPI.downloadImage(_:)), name: NSNotification.Name(rawValue: downloadImageNotification), object: nil) } deinit { NotificationCenter.default.removeObserver(self) } func getPokemons() -> [Pokemon] { return pokemons } func downloadImg(_ url: String) -> UIImage { let aUrl = URL(string: url) let data = try? Data(contentsOf: aUrl!) let image = UIImage(data: data!) return image! } @objc func downloadImage(_ notification: Notification) { // retrieve info from notification let userInfo = notification.userInfo as! [String: AnyObject] let pokeImageView = userInfo["pokeImageView"] as! UIImageView? let pokeImageUrl = userInfo["pokeImageUrl"] as! String if let imageViewUnWrapped = pokeImageView { imageViewUnWrapped.image = persistencyManager.getImage(URL(string: pokeImageUrl)!.lastPathComponent) if imageViewUnWrapped.image == nil { DispatchQueue.global().async { let downloadedImage = self.downloadImg(pokeImageUrl) DispatchQueue.main.async { imageViewUnWrapped.image = downloadedImage self.persistencyManager.saveImage(downloadedImage, filename: URL(string: pokeImageUrl)!.lastPathComponent) } } } } } }
28.557377
118
0.654994
d5a09d92d896a5285f7f1e64a01301552b291d02
7,539
// // PhotoPreviewSelectedView.swift // HXPHPickerExample // // Created by Slience on 2020/12/29. // Copyright © 2020 Silence. All rights reserved. // import UIKit protocol PhotoPreviewSelectedViewDelegate: AnyObject { func selectedView(_ selectedView: PhotoPreviewSelectedView, didSelectItemAt photoAsset: PhotoAsset) } class PhotoPreviewSelectedView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { weak var delegate: PhotoPreviewSelectedViewDelegate? lazy var collectionViewLayout: UICollectionViewFlowLayout = { let layout = UICollectionViewFlowLayout.init() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 5 layout.minimumInteritemSpacing = 5 layout.sectionInset = UIEdgeInsets( top: 10, left: 12 + UIDevice.leftMargin, bottom: 5, right: 12 + UIDevice.rightMargin ) return layout }() lazy var collectionView: UICollectionView = { let collectionView = UICollectionView.init(frame: bounds, collectionViewLayout: collectionViewLayout) collectionView.backgroundColor = UIColor.clear collectionView.dataSource = self collectionView.delegate = self collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } return collectionView }() var photoAssetArray: [PhotoAsset] = [] var currentSelectedIndexPath: IndexPath? var tickColor: UIColor? override init(frame: CGRect) { super.init(frame: frame) addSubview(collectionView) } func reloadSectionInset() { if x == 0 { collectionViewLayout.sectionInset = UIEdgeInsets( top: 10, left: 12 + UIDevice.leftMargin, bottom: 5, right: 12 + UIDevice.rightMargin ) } } func reloadData(photoAssets: [PhotoAsset]) { isHidden = photoAssets.isEmpty photoAssetArray = photoAssets collectionView.reloadData() } func reloadData(photoAsset: PhotoAsset) { if let index = photoAssetArray.firstIndex(of: photoAsset) { collectionView.reloadItems(at: [IndexPath(item: index, section: 0)]) collectionView.selectItem( at: currentSelectedIndexPath, animated: false, scrollPosition: .centeredHorizontally ) } } func insertPhotoAsset(photoAsset: PhotoAsset) { let beforeIsEmpty = photoAssetArray.isEmpty let item = photoAssetArray.count let indexPath = IndexPath(item: item, section: 0) photoAssetArray.append(photoAsset) collectionView.insertItems(at: [indexPath]) collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally) currentSelectedIndexPath = indexPath if beforeIsEmpty { alpha = 0 isHidden = false UIView.animate(withDuration: 0.25) { self.alpha = 1 } } } func removePhotoAsset(photoAsset: PhotoAsset) { let beforeIsEmpty = photoAssetArray.isEmpty if let item = photoAssetArray.firstIndex(of: photoAsset) { if item == currentSelectedIndexPath?.item { currentSelectedIndexPath = nil } photoAssetArray.remove(at: item) collectionView.deleteItems(at: [IndexPath(item: item, section: 0)]) } if !beforeIsEmpty && photoAssetArray.isEmpty { UIView.animate(withDuration: 0.25) { self.alpha = 0 } completion: { (isFinish) in if isFinish { self.isHidden = true } } } } func replacePhotoAsset(at index: Int, with photoAsset: PhotoAsset) { photoAssetArray[index] = photoAsset collectionView.reloadItems(at: [IndexPath.init(item: index, section: 0)]) } func scrollTo(photoAsset: PhotoAsset?, isAnimated: Bool = true) { if photoAsset == nil { deselectedCurrentIndexPath() return } if photoAssetArray.contains(photoAsset!) { let item = photoAssetArray.firstIndex(of: photoAsset!) ?? 0 if item == currentSelectedIndexPath?.item { return } let indexPath = IndexPath(item: item, section: 0) collectionView.selectItem(at: indexPath, animated: isAnimated, scrollPosition: .centeredHorizontally) currentSelectedIndexPath = indexPath }else { deselectedCurrentIndexPath() } } func deselectedCurrentIndexPath() { if currentSelectedIndexPath != nil { collectionView.deselectItem(at: currentSelectedIndexPath!, animated: true) currentSelectedIndexPath = nil } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { photoAssetArray.count } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: NSStringFromClass(PhotoPreviewSelectedViewCell.self), for: indexPath ) as! PhotoPreviewSelectedViewCell cell.tickColor = tickColor cell.photoAsset = photoAssetArray[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { currentSelectedIndexPath = indexPath delegate?.selectedView(self, didSelectItemAt: photoAssetArray[indexPath.item]) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let photoAsset = photoAssetArray[indexPath.item] return getItemSize(photoAsset: photoAsset) } func collectionView( _ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath ) { let myCell = cell as! PhotoPreviewSelectedViewCell myCell.cancelRequest() } func getItemSize(photoAsset: PhotoAsset) -> CGSize { let minWidth: CGFloat = 70 - collectionViewLayout.sectionInset.top - collectionViewLayout.sectionInset.bottom // let maxWidth: CGFloat = minWidth / 9 * 16 let maxHeight: CGFloat = minWidth // let aspectRatio = maxHeight / photoAsset.imageSize.height let itemHeight = maxHeight // var itemWidth = photoAsset.imageSize.width * aspectRatio // if itemWidth < minWidth { let itemWidth = minWidth // }else if itemWidth > maxWidth { // itemWidth = maxWidth // } return CGSize(width: itemWidth, height: itemHeight) } override func layoutSubviews() { collectionView.frame = bounds } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
36.597087
117
0.629924
ac8e94d96e43ca1f203461782b4754f7aa104277
508
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import Foundation extension Cameras.Manufacturers.Minolta { public struct DiMAGEA1: CameraModel { public init() {} public let name = "Minolta DiMAGE A1" public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Minolta.self } } public typealias MinoltaDiMAGEA1 = Cameras.Manufacturers.Minolta.DiMAGEA1
28.222222
97
0.73622
5d016edf547dce97527047e1fecc62ba0b8e0c17
1,041
import Foundation #if canImport(MapboxMaps) @testable import MapboxMaps #else import MapboxMapsFoundation @testable import MapboxMapsGestures #endif final class MockCameraManager: CameraManagerProtocol { var mapView: BaseMapView? var mapCameraOptions = MapCameraOptions() struct SetCameraParameters { var camera: CameraOptions var animated: Bool var duration: TimeInterval var completion: ((UIViewAnimatingPosition) -> Void)? } let setCameraStub = Stub<SetCameraParameters, Void>() func setCamera(to camera: CameraOptions, animated: Bool, duration: TimeInterval, completion: ((UIViewAnimatingPosition) -> Void)?) { setCameraStub.call( with: SetCameraParameters(camera: camera, animated: animated, duration: duration, completion: completion)) } func cancelTransitions() { } }
27.394737
70
0.603266
9babc74b11ebc4745a1b3193dfc5209d173dc32e
1,042
// // StatisticsUiStateView.swift // TodoApp // // Created by Shinya Kumagai on 2020/12/09. // import SwiftUI struct StatisticsUiStateView: View { let uiState: StatisticsUiState var body: some View { VStack(spacing: 24) { VStack(spacing: 8) { Text(L10n.Statistics.activeTasks) .font(.title3) .bold() Text("\(uiState.activeTaskCount)") .font(.title3) } VStack(spacing: 8) { Text(L10n.Statistics.completedTasks) .font(.title3) .bold() Text("\(uiState.completedTaskCount)") .font(.title3) } } } } // MARK: - Previews struct StatisticsUiStateView_Previews: PreviewProvider { static var previews: some View { StatisticsUiStateView( uiState: .init( activeTaskCount: 0, completedTaskCount: 1 ) ) } }
22.652174
56
0.492322
1e43469e82b9e5bf727c6d548f4b904689307702
3,666
// // EitherCollection.swift // SwiftSpellBook // // Created by Braden Scothern on 10/30/20. // Copyright © 2020-2021 Braden Scothern. All rights reserved. // public typealias EitherMutableCollection<Left, Right> = EitherCollection<Left, Right> where Left: MutableCollection, Right: MutableCollection, Left.Element == Right.Element extension EitherMutableCollection: MutableCollection { @inlinable public subscript(position: Index) -> Element { // swiftlint doesn't recognize _modify as an accessor //swiftlint:disable:next implicit_getter get { getElement(at: position) } _modify { // This accessor does some extra explicit memory management to help avoid COW overhead. // If you track the reference counts they should go to +1 then back down to +0 right away. // Of course the compiler can choose to place the memory management wherever it wants to so there still might be COW overhead in some cases... defer { _fixLifetime(self) } var left: UnsafeMutablePointer<Left>? var right: UnsafeMutablePointer<Right>? // The LOE says that this instance can only be accessed and mutated by one thing at a time so as long as it is restored at the end it should be fine. // In fact this is what Dave Abrahams had done in this thread: https://forums.swift.org/t/law-of-exclusivity-memory-safety-question/43374 withUnsafeMutablePointer(to: &_value) { value in switch value.move() { case let .left(value): left = .allocate(capacity: 1) left?.initialize(to: value) case let .right(value): right = .allocate(capacity: 1) right?.initialize(to: value) case .none: fatalError("EitherMutableCollection has memory corruption and cannot find a value") } } defer { withUnsafeMutablePointer(to: &_value) { value in if left != nil { value.initialize(to: .left(left.unsafelyUnwrapped.move())) left.unsafelyUnwrapped.deallocate() } else if right != nil { value.initialize(to: .right(right.unsafelyUnwrapped.move())) right.unsafelyUnwrapped.deallocate() } else { fatalError("EitherMutableCollection.\(#function) failed to re-initialize storage") } } } // Since unsafelyUnwrapped is read-only we need to determine what we have, bind it, yield, and unbind it to avoid COW switch (left, right, position.value) { case let (.some, .none, .left(position)): var yieldableLeft = left.unsafelyUnwrapped.move() defer { left.unsafelyUnwrapped.initialize(to: yieldableLeft) } yield &yieldableLeft[position] case let (.none, .some, .right(position)): var yieldableRight = right.unsafelyUnwrapped.move() defer { right.unsafelyUnwrapped.initialize(to: yieldableRight) } yield &yieldableRight[position] case (.none, .none, _): fatalError("EitherMutableCollection.\(#function) unable to find value to mutate") default: fatalError("EitherMutableCollection.\(#function) used with other index type") } } } }
46.405063
172
0.580196
8957a23f07102fe589cf4fb657d7abe4490c78ee
441
protocol ITransactionInfoView: class { func showCopied() } protocol ITransactionInfoViewDelegate: class { func onCopy(value: String) func openFullInfo(coinCode: CoinCode, transactionHash: String) } protocol ITransactionInfoInteractor { func onCopy(value: String) } protocol ITransactionInfoInteractorDelegate: class { } protocol ITransactionInfoRouter { func openFullInfo(transactionHash: String, coinCode: String) }
22.05
66
0.782313
62759d8f5d50122937930a2886bfefd725607a8b
6,215
// // VideoSessionController.swift // camRAWR // // Created by Daniel Love on 05/10/2015. // Copyright © 2015 Shh Love Limited. All rights reserved. // import AVFoundation enum VideoSessionPermission { case Requestable case RestrictedByParent case Denied case Granted } class VideoSessionController : NSObject { let session : AVCaptureSession let previewLayer : AVCaptureVideoPreviewLayer var backCameraDevice : AVCaptureDevice? var frontCameraDevice : AVCaptureDevice? var currentCameraDevice : AVCaptureDevice? var metadataOutput : AVCaptureMetadataOutput var didDetectFacesHandler:((Array<(faceID: Int, frame : CGRect)>)->Void)! let sessionQueue : dispatch_queue_t = dispatch_queue_create("net.daniellove.camRAWR.session_access_queue", DISPATCH_QUEUE_SERIAL) override init() { session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetPhoto previewLayer = AVCaptureVideoPreviewLayer(session: self.session) as AVCaptureVideoPreviewLayer previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill metadataOutput = AVCaptureMetadataOutput() } // MARK: Authorization func checkAuthorizationStatus() -> VideoSessionPermission { let authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) var permission : VideoSessionPermission switch authorizationStatus { case .Authorized: permission = VideoSessionPermission.Granted case .NotDetermined: permission = VideoSessionPermission.Requestable case .Denied: permission = VideoSessionPermission.Denied case .Restricted: permission = VideoSessionPermission.RestrictedByParent } return permission } func requestAuthorization(completionHandler: ((granted : Bool) -> Void)) { AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: completionHandler) } // MARK: Controls func startSession() { performConfiguration { () -> Void in self.session.startRunning() } } func stopSession() { performConfiguration { () -> Void in self.session.stopRunning() } } // MARK: Device Configuration func configureSession() { findCameraDevices() setupDeviceInput() enableContinuousAutoFocus() configureFaceDetection() } func performConfiguration(block: (() -> Void)) { dispatch_async(sessionQueue) { () -> Void in block() } } func performConfigurationOnCurrentCameraDevice(block: ((currentDevice:AVCaptureDevice) -> Void)) { if let currentDevice = self.currentCameraDevice { performConfiguration { () -> Void in do { try currentDevice.lockForConfiguration() block(currentDevice: currentDevice) currentDevice.unlockForConfiguration() } catch let error { NSLog("\(error)") } } } } func findCameraDevices() { performConfiguration { () -> Void in let availableCameraDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in availableCameraDevices as! [AVCaptureDevice] { if device.position == .Back { self.backCameraDevice = device } else if device.position == .Front { self.frontCameraDevice = device } } } } func setupDeviceInput() { performConfiguration { () -> Void in // Prefer the front camera if (self.frontCameraDevice != nil) { self.currentCameraDevice = self.frontCameraDevice } else { self.currentCameraDevice = self.backCameraDevice } let possibleCameraInput: AnyObject? do { possibleCameraInput = try AVCaptureDeviceInput(device: self.currentCameraDevice) } catch let error { NSLog("\(error)") possibleCameraInput = nil } if let cameraInput = possibleCameraInput as? AVCaptureDeviceInput { if self.session.canAddInput(cameraInput) { self.session.addInput(cameraInput) } } } } // MARK: Face Detection func configureFaceDetection() { performConfiguration { () -> Void in self.metadataOutput = AVCaptureMetadataOutput() self.metadataOutput.setMetadataObjectsDelegate(self, queue: self.sessionQueue) if self.session.canAddOutput(self.metadataOutput) { self.session.addOutput(self.metadataOutput) } if let availableMetadataObjectTypes = self.metadataOutput.availableMetadataObjectTypes as? [String] { if availableMetadataObjectTypes.contains(AVMetadataObjectTypeFace) { self.metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeFace] } } } } // MARK: Focus var isAutoFocusContinuousEnabled : Bool { get { return currentCameraDevice!.focusMode == .ContinuousAutoFocus } } func enableContinuousAutoFocus() { performConfigurationOnCurrentCameraDevice { (currentDevice) -> Void in if currentDevice.isFocusModeSupported(.ContinuousAutoFocus) { currentDevice.focusMode = .ContinuousAutoFocus } } } var isAutoFocusLockedEnabled : Bool { get { return currentCameraDevice!.focusMode == .Locked } } func lockFocusAtPointOfInterest(pointInView : CGPoint) { let pointInCamera = previewLayer.captureDevicePointOfInterestForPoint(pointInView) performConfigurationOnCurrentCameraDevice { (currentDevice) -> Void in if currentDevice.focusPointOfInterestSupported { currentDevice.focusPointOfInterest = pointInCamera currentDevice.focusMode = .AutoFocus } } } } extension VideoSessionController: AVCaptureMetadataOutputObjectsDelegate { func captureOutput(captureOutput : AVCaptureOutput!, didOutputMetadataObjects metadataObjects : [AnyObject]!, fromConnection connection : AVCaptureConnection!) { var faces = Array<(faceID: Int, frame : CGRect)>() for metadataObject in metadataObjects as! [AVMetadataObject] { if metadataObject.type != AVMetadataObjectTypeFace { continue } if let faceObject = metadataObject as? AVMetadataFaceObject { let transformedMetadataObject = previewLayer.transformedMetadataObjectForMetadataObject(metadataObject) let face = (faceObject.faceID, transformedMetadataObject.bounds) faces.append(face) } } if let handler = self.didDetectFacesHandler { dispatch_async(dispatch_get_main_queue(), { handler(faces) }) } } }
24.277344
160
0.739019
9b53bd9d86f1c1835b2542d0f827cf9c2d01c959
584
// // iPhoneToggleButton.swift // AudioKitSynthOne // // Created by Matthew Fecher on 1/8/19. // Copyright © 2019 AudioKit. All rights reserved. // @IBDesignable class iPhoneToggleButton: ToggleButton { @IBInspectable open var buttonText: String = "Hello" @IBInspectable open var textSize: Int = 14 public override func draw(_ rect: CGRect) { TopUIButtonStyleKit.drawUIButton(frame: CGRect(x:0,y:0, width: self.bounds.width, height: self.bounds.height), resizing: .aspectFit, isOn: isOn, text: buttonText, textSize: CGFloat(textSize)) } }
27.809524
199
0.700342
1804c969dfeb0b7a2fb4ce5ee7712500f0a030f2
2,095
// RUN: %target-swift-emit-silgen -enable-sil-ownership -enforce-exclusivity=checked %s | %FileCheck %s class C {} struct A {} struct B { var owner: C } var a = A() // CHECK-LABEL: sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { // CHECK: assign {{%.*}} to {{%.*}} : $*A // CHECK: destroy_value {{%.*}} : $B // CHECK: } // end sil function 'main' (a, _) = (A(), B(owner: C())) class D { var child: C = C() } // Verify that the LHS is formally evaluated before the RHS. // CHECK-LABEL: sil hidden @$S10assignment5test1yyF : $@convention(thin) () -> () { func test1() { // CHECK: [[T0:%.*]] = metatype $@thick D.Type // CHECK: [[CTOR:%.*]] = function_ref @$S10assignment1DC{{[_0-9a-zA-Z]*}}fC // CHECK: [[D:%.*]] = apply [[CTOR]]([[T0]]) // CHECK: [[BORROWED_D:%.*]] = begin_borrow [[D]] // CHECK: [[T0:%.*]] = metatype $@thick C.Type // CHECK: [[CTOR:%.*]] = function_ref @$S10assignment1CC{{[_0-9a-zA-Z]*}}fC // CHECK: [[C:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thick C.Type) -> @owned C // CHECK: [[SETTER:%.*]] = class_method [[BORROWED_D]] : $D, #D.child!setter.1 // CHECK: apply [[SETTER]]([[C]], [[BORROWED_D]]) // CHECK: end_borrow [[BORROWED_D]] from [[D]] // CHECK: destroy_value [[D]] D().child = C() } // rdar://32039566 protocol P { var left: Int {get set} var right: Int {get set} } // Verify that the access to the LHS does not begin until after the // RHS is formally evaluated. // CHECK-LABEL: sil hidden @$S10assignment15copyRightToLeft1pyAA1P_pz_tF : $@convention(thin) (@inout P) -> () { func copyRightToLeft(p: inout P) { // CHECK: bb0(%0 : @trivial $*P): // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*P // CHECK: [[READ_OPEN:%.*]] = open_existential_addr immutable_access [[READ]] // CHECK: end_access [[READ]] : $*P // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*P // CHECK: [[WRITE_OPEN:%.*]] = open_existential_addr mutable_access [[WRITE]] // CHECK: end_access [[WRITE]] : $*P p.left = p.right }
38.796296
122
0.595227
4ad0f831d02d4022346b101f66ac48ad193663c2
2,925
//: [Previous](@previous) import Foundation // Build order // Given a list of projects, with their dependencies in pair (A, B) where B depends of A // Print a build order // Input // project list: a, b ,c, d , e, f // project dep (a,d), (f,b), (b,d ), (f, a), (d, c) // output: f, e, a, b, d, c // where: e does not matter, a and b can be permuted /// Simple Stack implentation using Swift Array struct Stack<T>{ private var items: [T] = [] mutating func push(_ item: T) { items.append(item) } @discardableResult mutating func pop() -> T? { return items.removeFirst() } var empty: Bool { return items.isEmpty } } /// State to define where we are at in the DFS to avoid reference cycle enum DFSState { case blank case partial case completed } /// Project class definition final class Project { var name: String var dependencies: [String: Project] = [:] private(set) var state = DFSState.blank init(name: String) { self.name = name } func setState(_ state: DFSState) { self.state = state } func addDep(project: Project) { if dependencies[project.name] == nil { dependencies[project.name] = project } } } /// Tuple to define pair target typealias DependencyPair = (dep: String, target: String) final class Graph { private var projectsMap: [String: Project] = [:] init(projectList: [String], dependencies: [DependencyPair]) { for p in projectList { projectsMap[p] = Project(name: p) } for pair in dependencies { if projectsMap[pair.dep] != nil { projectsMap[pair.target]?.addDep(project: projectsMap[pair.dep]!) } } } func orderedProject() -> Stack<Project>?{ var projectStack = Stack<Project>() for pair in projectsMap { let project = pair.value if project.state == .blank { if !(dfs(project, stack: &projectStack)) { return nil } } } return projectStack } /// Run Depth first search if a cyle is not detected private func dfs(_ project: Project, stack: inout Stack<Project>) -> Bool { // checking for cycle if (project.state == .partial) { return false } if (project.state == .blank) { project.setState(.partial) for dep in project.dependencies { if !(dfs(dep.value, stack: &stack)) { return false } } project.setState(.completed) stack.push(project) } return true } } let projectGraph = Graph(projectList: ["a", "b", "c", "d", "e", "f"], dependencies: [ ("a", "d"), ("f", "b"), ("b", "d"), ("f", "a"), ("d", "c") ]) var buildOrder = projectGraph.orderedProject() while !buildOrder!.empty { print(buildOrder!.pop()!.name) } //: [Next](@next)
22.328244
88
0.571966
d973b4fd60d004786269f60110a3eec566a279b7
1,392
// // SCBreedDataItem.swift // MyCatInfo // // Created by Stephen Cao on 3/8/19. // Copyright © 2019 Stephen Cao. All rights reserved. // import Foundation struct SCBreedData: Codable{ let breeds: [SCBreedDataItem]? let id: String? let url: String? let width: Int? let height: Int? } struct SCBreedDataItem: Codable { let weight: SCBreedWeightItem? let id: String? let name: String? let cfa_url: String? let vetstreet_url: String? let vcahospitals_url: String? let temperament: String? let origin: String? let country_codes: String? let country_code: String? let description: String? let life_span: String? let indoor: Int? let lap: Int? let alt_names: String? let adaptability: Int? let affection_level: Int? let child_friendly: Int? let dog_friendly: Int? let energy_level: Int? let grooming: Int? let health_issues: Int? let intelligence: Int? let shedding_level: Int? let social_needs: Int? let stranger_friendly: Int? let vocalisation: Int? let experimental: Int? let hairless: Int? let natural: Int? let rare: Int? let rex: Int? let suppressed_tail: Int? let short_legs: Int? let wikipedia_url: String? let hypoallergenic: Int? } struct SCBreedWeightItem: Codable{ let imperial: String? let metric: String? }
23.2
54
0.668103
461b5147c2467da4e8ed80c473a5a8151fabdce5
3,424
// // Client.swift // network // // Created by Guilherme Ramos on 03/04/20. // Copyright © 2020 Guilherme Ramos. All rights reserved. // import Foundation struct NetworkClient { typealias RequestHandler<T: Decodable> = (_ result: Result<T, NetworkError>) -> Void static let shared = NetworkClient() private let session: URLSessionProtocol init(session: URLSessionProtocol = URLSession.shared) { self.session = session } /// Execute a request to an endpoint; after finishing the operation it will execute the completion block with a result /// that can be either a swift decodable object or a NetworkError /// - Parameters: /// - endpoint: Object conforming ot the Endpoint protocol, containing information to execute a request /// - type: Type of the object to be returned if the request succeeds /// - completion: completion block executed after the operation finishes func request<T: Decodable>(_ endpoint: Endpoint, for type: T.Type, _ completion: @escaping RequestHandler<T>) { guard let request = endpoint.request else { completion(.failure(.invalidRequest)) return } let task = dataTask(with: request, for: type, completion) task.resume() } /// Creates a URLSessionDataTask object to execute a request to a specific urlRequest /// - Parameters: /// - url: url that will be requested /// - type: type of the object returned as the response /// - completion: completion block taht will lbe executed when the request finishes private func dataTask<T: Decodable>(with request: URLRequest, for type: T.Type, _ completion: @escaping RequestHandler<T>) -> URLSessionDataTask { return session.dataTask(with: request) { data, response, error in guard let data = data else { completion(.failure(.notFound(error))) return } if let error = error { completion(.failure(.generic(error))) return } do { let decoder = JSONDecoder() let decoded = try decoder.decode(type, from: data) completion(.success(decoded)) } catch { completion(.failure(.decoding(error))) } } } /// Creates a URLSessionDataTask object to execute a request to a specific url /// - Parameters: /// - url: url that will be requested /// - type: type of the object returned as the response /// - completion: completion block taht will lbe executed when the request finishes private func dataTask<T: Decodable>(with url: URL, for type: T.Type, completion: @escaping RequestHandler<T>) -> URLSessionDataTask { return session.dataTask(with: url) { data, response, error in guard let data = data else { completion(.failure(.notFound(error))) return } if let error = error { completion(.failure(.generic(error))) return } do { let decoder = JSONDecoder() let decoded = try decoder.decode(type, from: data) completion(.success(decoded)) } catch { completion(.failure(.decoding(error))) } } } }
36.817204
152
0.599883
288da3cfc3bc51ccbcc1a7fe1fb9e7f8037a156a
1,038
// // SessionDataManager.swift // AV TEST AID // // Created by Juan Pablo Mazza on 11/8/16. // Copyright © 2016 Rootstrap. All rights reserved. // import UIKit class SessionManager: NSObject { static var currentSession: Session? { get { if let data = UserDefaults.standard.data(forKey: "AV TEST AID-session"), let session = try? JSONDecoder().decode(Session.self, from: data) { return session } return nil } set { let session = try? JSONEncoder().encode(newValue) UserDefaults.standard.set(session, forKey: "AV TEST AID-session") } } class func start(session: Session) { currentSession = session } class func deleteSession() { UserDefaults.standard.removeObject(forKey: "AV TEST AID-session") } static var validSession: Bool { if let session = currentSession, let token = session.accessToken { return !token.isEmpty } return false } }
24.714286
152
0.599229
14ea9c8ff0e989a5e3c502ed13e5078604798684
8,533
// // UICheckoutRecipientView.swift // PatissierStore // // Created by Roy Hsu on 09/07/2017. // Copyright © 2017 TinyWorld. All rights reserved. // // MARK: - UICheckoutRecipientView public final class UICheckoutRecipientView: UIView, Actionable { @IBOutlet private final weak var firstNameLabel: UILabel! @IBOutlet private final weak var firstNameContentView: UIView! @IBOutlet private final weak var firstNameBottomBorderView: UIView! @IBOutlet private final weak var firstNameTextField: UITextField! @IBOutlet private final weak var lastNameLabel: UILabel! @IBOutlet private final weak var lastNameContentView: UIView! @IBOutlet private final weak var lastNameBottomBorderView: UIView! @IBOutlet private final weak var lastNameTextField: UITextField! @IBOutlet private final weak var personTitleLabel: UILabel! @IBOutlet private final weak var personTitleContentView: UIView! @IBOutlet private final weak var personTitleBottomBorderView: UIView! @IBOutlet private final weak var personTitleLeftBorderView: UIView! @IBOutlet private final weak var personTitleRightBorderView: UIView! @IBOutlet private final weak var personTitleButton: UIButton! @IBOutlet private final weak var phoneNumberLabel: UILabel! @IBOutlet private final weak var phoneNumberContentView: UIView! @IBOutlet private final weak var phoneNumberBottomBorderView: UIView! @IBOutlet private final weak var phoneNumberTextField: UITextField! private final var isLoaded = false public final let actions = Observable<Action>() public final var recipientField: CheckoutRecipientField? { didSet { updateUI() } } fileprivate final func updateUI() { guard isLoaded else { return } firstNameTextField.text = recipientField?.firstNameField.value lastNameTextField.text = recipientField?.lastNameField.value personTitleButton.setTitle( recipientField?.personTitleField.value, for: .normal ) phoneNumberTextField.text = recipientField?.phoneNumberField.value } public final override func awakeFromNib() { super.awakeFromNib() isLoaded.toggle() #warning("TODO: should be defined in the locale system.") setUpTitleLabel( firstNameLabel, title: NSLocalizedString( "First Name", comment: "" ) ) setUpTextField( firstNameTextField, action: #selector(updateFirstName) ) setUpContentView(firstNameContentView) setUpBorderView(firstNameBottomBorderView) #warning("TODO: should be defined in the locale system.") setUpTitleLabel( lastNameLabel, title: NSLocalizedString( "Last Name", comment: "" ) ) setUpTextField( lastNameTextField, action: #selector(updateLastName) ) setUpContentView(lastNameContentView) setUpBorderView(lastNameBottomBorderView) #warning("Should define a better key for localization") #warning("TODO: should be defined in the locale system.") setUpTitleLabel( personTitleLabel, title: NSLocalizedString( "Title", comment: "" ) ) setUpActionButton( personTitleButton, action: #selector(showPersonTitlePicker) ) setUpContentView(personTitleContentView) setUpBorderView(personTitleBottomBorderView) setUpBorderView(personTitleLeftBorderView) setUpBorderView(personTitleRightBorderView) #warning("TODO: should be defined in the locale system.") setUpTitleLabel( phoneNumberLabel, title: NSLocalizedString( "Phone Number", comment: "" ) ) setUpTextField( phoneNumberTextField, action: #selector(updatePhoneNumber) ) setUpContentView(phoneNumberContentView) setUpBorderView(phoneNumberBottomBorderView) updateUI() } fileprivate final func setUpTitleLabel( _ label: UILabel, title: String ) { #warning("TODO: should be defined in the design system.") label.font = UIFont( name: "Georgia", size: 12.0 ) label.numberOfLines = 1 label.text = title label.textAlignment = .left #warning("TODO: should be defined in the design system.") label.textColor = UIColor( red: 165.0 / 255.0, green: 170.0 / 255.0, blue: 178.0 / 255.0, alpha: 1.0 ) label.text = title } fileprivate final func setUpContentView(_ view: UIView) { view.backgroundColor = .white } fileprivate final func setUpBorderView(_ view: UIView) { #warning("TODO: should be defined in the design system.") let borderColor = UIColor( red: 165.0 / 255.0, green: 170.0 / 255.0, blue: 178.0 / 255.0, alpha: 1.0 ) view.backgroundColor = borderColor } fileprivate final func setUpActionButton( _ button: UIButton, action: Selector ) { button.contentEdgeInsets = UIEdgeInsets( top: 10.0, left: 5.0, bottom: 5.0, right: 5.0 ) button.setTitle( nil, for: .normal ) button.titleLabel?.textAlignment = .center #warning("TODO: should be defined in the design system.") button.titleLabel?.font = .systemFont(ofSize: 16.0) #warning("TODO: should be defined in the design system.") button.tintColor = UIColor( red: 82.0 / 255.0, green: 66.0 / 255.0, blue: 64.0 / 255.0, alpha: 1.0 ) button.addTarget( self, action: action, for: .touchUpInside ) } fileprivate final func setUpTextField( _ textField: UITextField, action: Selector ) { textField.borderStyle = .none textField.clearButtonMode = .whileEditing #warning("TODO: should be defined in the design system.") textField.font = .systemFont(ofSize: 16.0) textField.text = nil textField.textAlignment = .left #warning("TODO: should be defined in the design system.") textField.textColor = UIColor( red: 82.0 / 255.0, green: 66.0 / 255.0, blue: 64.0 / 255.0, alpha: 1.0 ) #warning("TODO: should be defined in the design system.") textField.tintColor = UIColor( red: 82.0 / 255.0, green: 66.0 / 255.0, blue: 64.0 / 255.0, alpha: 1.0 ) textField.addTarget( self, action: action, for: .editingChanged ) } @objc public final func updateFirstName(_ textField: UITextField) { recipientField?.firstNameField.value = textField.text guard let field = recipientField else { return } let action: CheckoutRecipientAction = .updateField(field) actions.value = action } @objc public final func updateLastName(_ textField: UITextField) { recipientField?.lastNameField.value = textField.text guard let field = recipientField else { return } let action: CheckoutRecipientAction = .updateField(field) actions.value = action } @objc public final func showPersonTitlePicker(_ button: UIButton) { guard let field = recipientField else { return } let action: CheckoutRecipientAction = .showPersonTitlePicker(field) actions.value = action } @objc public final func updatePhoneNumber(_ textField: UITextField) { recipientField?.phoneNumberField.value = textField.text guard let field = recipientField else { return } let action: CheckoutRecipientAction = .updateField(field) actions.value = action } }
23.378082
93
0.594515
71c48b707456902684aaaf9214768e95a22c481e
10,471
// // GameScene.swift // DoubleTap // // Created by Nikolaos Kechagias on 19/08/15. // Copyright (c) 2015 Nikolaos Kechagias. All rights reserved. // import SpriteKit class GameScene: SKScene { /* 1 */ let soundMessage = SKAction.playSoundFileNamed("Message.m4a", waitForCompletion: false) let soundMatchFailed = SKAction.playSoundFileNamed("MatchCardFailed.m4a", waitForCompletion: false) let soundMatchDone = SKAction.playSoundFileNamed("MatchCardSuccessed.m4a", waitForCompletion: false) let soundLevelDone = SKAction.playSoundFileNamed("LevelCompleted.m4a", waitForCompletion: false) let soundSelect = SKAction.playSoundFileNamed("SelectCard.m4a", waitForCompletion: false) /* 3 Holds the number of cards. */ let totalCards = 17 /* 1 Holds the number of rows of the game board. */ let numRows = 5 /* 2 Holds the number of columns of the game board.*/ let numColumns = 4 /* 4 2-Dimensional array of cards. */ //var cardsArray = [[CardNode]]() /* 5 Holds the first selected card. */ var firstSelectedCard: CardNode? = nil // Holds the second selected card. var secondSelectedCard: CardNode? = nil /* Enable or disable touches */ var enableTouches = true /* 8 */ var isGameOver = false /* 2 */ var scoreLabel = LabelNode(fontNamed: "Gill Sans Bold Italic") var timeLabel = LabelNode(fontNamed: "Gill Sans Bold Italic") /* 3 */ var score: Int = 0 { didSet { /* 4 */ scoreLabel.text = "Score: \(score)" } } /* 1 */ var timedt = 0.0 /* 3 */ var time: Int = 60 { didSet { /* 4 */ timeLabel.text = "Time: \(time)" } } override func didMove(to view: SKView) { /* Add Background */ addBackground() /* Create Game Board */ createGameBoard(filenames: selectRandomCards()) /* Add HUD */ addHUD() } func addHUD() { scoreLabel.fontSize = 40 scoreLabel.fontColor = SKColor.white scoreLabel.zPosition = zOrderValue.hud.rawValue scoreLabel.position = CGPoint(x: size.width * 0.25, y: size.height - scoreLabel.fontSize) scoreLabel.text = "Score: \(score)" addChild(scoreLabel) timeLabel.fontSize = 40 timeLabel.fontColor = SKColor.white timeLabel.zPosition = zOrderValue.hud.rawValue timeLabel.position = CGPoint(x: size.width * 0.75, y: size.height - timeLabel.fontSize) timeLabel.text = "Time: \(time)" addChild(timeLabel) } // MARK: - Game States func showMessage(imageNamed: String) { /* 1 */ let panel = SKSpriteNode(texture: SKTexture(imageNamed: "\(imageNamed).png")) panel.zPosition = zOrderValue.message.rawValue panel.position = CGPoint(x: size.width / 2, y: -size.height) panel.name = imageNamed addChild(panel) /* 2 */ let move = SKAction.move(to: CGPoint(x: size.width / 2, y: size.height / 2), duration: 0.50) panel.run(SKAction.sequence([soundMessage, move])) } func createGameBoard(filenames: [String]) { let backTexture = SKTexture(imageNamed: "back.png") var index = 0 for row in 0 ..< numRows { for column in 0 ..< numColumns { /* 1 */ let card = CardNode(texture: backTexture, row: row, column: column, filename: filenames[index]) card.zPosition = zOrderValue.card.rawValue card.name = "Card" card.zPosition = 1 card.position = calculateCardsPosition(row: row, column: column, cardSize: card.size) /* 2 */ addChild(card) index += 1 } } } func calculateCardsPosition(row: Int, column: Int, cardSize: CGSize) -> CGPoint { let marginX = (size.width - cardSize.width * CGFloat(numColumns)) / 2 let marginY = (size.height - cardSize.height * CGFloat(numRows)) / 2 let x = marginX + cardSize.width / 2 + cardSize.width * CGFloat(column) let y = marginY + cardSize.height / 2 + cardSize.height * CGFloat(row) return CGPoint(x: x, y: y) } func selectRandomCards() -> [String] { /* 1 */ var allCards = [String]() for index in 0 ... totalCards { allCards.append("card_\(index).png") } /* 2 */ var selectedCards = [String]() let numberOfCardsInBoard = numRows * numColumns / 2 for _ in 0 ..< numberOfCardsInBoard { /* 3 */ let num = random(min: 0, max: UInt32(allCards.count)) let filename = allCards[num] /* 4 */ allCards.remove(at: num) /* 5 */ selectedCards.append(filename) selectedCards.append(filename) } /* 6 */ for _ in 0 ..< selectedCards.count { let num1 = random(min: 0, max: UInt32(selectedCards.count)) let num2 = random(min: 0, max: UInt32(selectedCards.count)) let temp = selectedCards[num1] selectedCards[num1] = selectedCards[num2] selectedCards[num2] = temp } /* 7 */ return selectedCards } // MARK: - Library func random(min: UInt32, max: UInt32) -> Int { return Int(arc4random_uniform(max - min) + min) } // MARK: - User Interface func addBackground() { let background = SKSpriteNode(imageNamed: "Background.png") background.name = "Background" background.zPosition = zOrderValue.background.rawValue background.position = CGPoint(x: frame.midX, y: frame.midY) addChild(background) } func newGame() { removeAllChildren() addBackground() firstSelectedCard = nil secondSelectedCard = nil enableTouches = true isGameOver = false createGameBoard(filenames: selectRandomCards()) addHUD() score = 0 time = 60 timedt = 0 } func nextLevel() { removeAllChildren() addBackground() firstSelectedCard = nil secondSelectedCard = nil enableTouches = true isGameOver = false createGameBoard(filenames: selectRandomCards()) addHUD() time = 60 timedt = 0 } func checkIfLevelCompleted() { /* 1 */ if !isGameOver { if let _ = childNode(withName: "Card") { /* 2 */ return } else { /* 3 */ isGameOver = true showMessage(imageNamed: "LevelCompleted") } } } func updateScore() { score += 10 } func checkForMatch() { /* 1 */ if let card1 = firstSelectedCard, let card2 = secondSelectedCard { if card1.filename == card2.filename { /* 2 */ run(soundMatchDone) /* 3 */ let block = SKAction.run({ card1.remove() card2.remove() self.firstSelectedCard = nil self.secondSelectedCard = nil self.enableTouches = true }) let delay = SKAction.wait(forDuration: 1.0) let sequence = SKAction.sequence([block, delay]) run(sequence, completion: { /* Checks if level completed */ self.checkIfLevelCompleted() }) /* Update score */ updateScore() } else { /* 5 */ run(soundMatchFailed) self.firstSelectedCard = nil self.secondSelectedCard = nil /* 6 */ card1.flip() { } card2.flip() { /* 7 */ self.enableTouches = true } } } } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ /* 1 */ if isGameOver { return } /* 2 */ if timedt + 1 < currentTime { timedt = currentTime; time -= 1 /* 3 */ if time <= 0 { showMessage(imageNamed: "GameOver") isGameOver = true } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let location = touches.first?.location(in: self) /* New Game */ let gameOver = childNode(withName: "GameOver") if gameOver != nil { newGame() return } /* Level Completed */ let levelCompleted = childNode(withName: "LevelCompleted") if levelCompleted != nil { nextLevel() return } /* 1 */ if isGameOver || !enableTouches { return } let node = atPoint(location!) if node.name == "Card" { /* 4 */ run(soundSelect) let card = node as! CardNode if !card.isFaceUp { if firstSelectedCard == nil { enableTouches = false card.flip() { self.firstSelectedCard = card self.enableTouches = true } } else { enableTouches = false card.flip() { self.secondSelectedCard = card /* 7 */ self.checkForMatch() } } } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { } }
28.925414
112
0.50148
28ce49f7cb4bab12d5acc933044a68f0a4521f21
743
import UIKit /* 1. 정수 하나를 입력받은 뒤, 해당 숫자와 숫자 1사이에 있는 모든 정수의 합계 구하기 e.g. 5 -> 1 + 2 + 3 + 4 + 5 = 15, -2 -> -2 + -1 + 0 + 1 = -2 */ class Add { let num: Int var sum = 0 init(_ number: Int) { self.num = number addition() } func addition() { if num < 1 { var i = num while i <= 1 { sum += i i += 1 } } else if num > 1 { var i = 1 while i <= num { sum += i i += 1 } } else if num == 1 { sum = 1 } print("총합:\(sum)") } } let a = Add(-2) let b = Add(10) let c = Add(-10) let d = Add(100)
16.886364
64
0.333782
fbcd7c7fd5f745c5cac04b08435bf376afdc26e2
1,659
import Foundation /// A Nimble matcher that succeeds when the actual value is less than the expected value. public func beLessThan<T: Comparable>(_ expectedValue: T?) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>" if let actual = try actualExpression.evaluate(), let expected = expectedValue { return actual < expected } return false } } /// A Nimble matcher that succeeds when the actual value is less than the expected value. public func beLessThan(_ expectedValue: NMBComparable?) -> NonNilMatcherFunc<NMBComparable> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>" let actualValue = try actualExpression.evaluate() let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedAscending return matches } } public func <<T: Comparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beLessThan(rhs)) } public func <(lhs: Expectation<NMBComparable>, rhs: NMBComparable?) { lhs.to(beLessThan(rhs)) } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func beLessThanMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let expr = actualExpression.cast { $0 as? NMBComparable } return try! beLessThan(expected).matches(expr, failureMessage: failureMessage) } } } #endif
39.5
120
0.712477
1a5d119adc2628674fad875b96f1daadd56c45f8
1,534
// // CustomTabbarVC.swift // Travel-IT // // Created by Ankit Singh on 22/03/18. // Copyright © 2018 Ankit Singh. All rights reserved. // import UIKit class CustomTabbarVC: UITabBarController, UITabBarControllerDelegate { var previousSelectedIndex : Int? var selectedTabUnderline : UIView? override func viewDidLoad() { super.viewDidLoad() self.delegate = self self.tabBar.barTintColor = UIColor.loaderColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.delegate = self // Do any additional setup after loading the view. // Add background color to middle tabBarItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { let view = item.value(forKey: "view") as! UIView let icon = view.subviews[0] as! UIImageView self.bounceAnimation(icon: icon) } // bounce animation code func bounceAnimation(icon: UIImageView) { let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale") bounceAnimation.values = [1.0 ,1.4, 0.9, 1.0] bounceAnimation.duration = 0.4 bounceAnimation.calculationMode = kCAAnimationCubic icon.layer.add(bounceAnimation, forKey: "bounceAnimation") } }
29.5
77
0.645372
67b3f95146bec404795ce90f78aca6c5a45c7c01
1,979
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Firebase class FPUser { var uid: String var fullname: String var profilePictureURL: URL? init(snapshot: DataSnapshot) { self.uid = snapshot.key let value = snapshot.value as! [String: Any] self.fullname = value["full_name"] as? String ?? "" guard let profile_picture = value["profile_picture"] as? String, let profilePictureURL = URL(string: profile_picture) else { return } self.profilePictureURL = profilePictureURL } init(dictionary: [String: String]) { self.uid = dictionary["uid"]! self.fullname = dictionary["full_name"] ?? "" guard let profile_picture = dictionary["profile_picture"], let profilePictureURL = URL(string: profile_picture) else { return } self.profilePictureURL = profilePictureURL } private init(user: User) { self.uid = user.uid self.fullname = user.displayName ?? "" self.profilePictureURL = user.photoURL } static func currentUser() -> FPUser { return FPUser(user: Auth.auth().currentUser!) } func author() -> [String: String] { return ["uid": uid, "full_name": fullname, "profile_picture": profilePictureURL?.absoluteString ?? ""] } } extension FPUser: Equatable { static func ==(lhs: FPUser, rhs: FPUser) -> Bool { return lhs.uid == rhs.uid } static func ==(lhs: FPUser, rhs: User) -> Bool { return lhs.uid == rhs.uid } }
30.921875
106
0.686205
e8b2e6bf3d4c372ab17dff72ff9586e4c177d6b0
4,217
// // TableViewController.swift // Notebook with firebase // // Created by Mads Bryde on 26/06/2020. // Copyright © 2020 Mads Bryde. All rights reserved. // import UIKit class TableViewController: UITableViewController { var currentNote:Note? override func viewDidLoad() { super.viewDidLoad() CloudStorage.startListener { (noteList) -> ([Note]) in self.tableView.reloadData() return noteList } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return CloudStorage.notesList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) // Sets each cell to the title of the note from our list cell.textLabel?.text = CloudStorage.notesList[indexPath.row].headline return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Unpacks the id of the element to be deleted at the index of the selected row if let idAtIndex = CloudStorage.notesList[indexPath.row].id{ // remove from array first so tableview knows how many rows it needs to update to CloudStorage.notesList.remove(at: indexPath.row) // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) // remove from database CloudStorage.deleteNote(id: idAtIndex) } } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } // This function selects the row from the table, and saves the data in a variable. then it performs the segue override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { currentNote = CloudStorage.notesList[indexPath.row] //print("row id: \(indexPath.row)") // at the storyboard i named the segue 'showNote' performSegue(withIdentifier: "detailedNote", sender: self) } @IBAction func unwindToThisView(sender: UIStoryboardSegue) { if let sourceViewController = sender.source as? DetailedViewController { let headline = sourceViewController.headlineText.text ?? "Headline Error." let text = sourceViewController.noteText.text ?? "Note Text Error." CloudStorage.update(id: (currentNote?.id)!, dateTime: currentNote?.dateTime ?? "10:10:10 10/10/2010", headline: headline, text: text) //print("\(headline) - \(text)") } } @IBAction func newNoteBtn(_ sender: Any) { CloudStorage.insertNewNote() // at the storyboard i named the segue 'showNote' performSegue(withIdentifier: "detailedNote", sender: nil) } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? DetailedViewController { destination.note = currentNote //print("current node being sent: \(currentNote?.headline ?? "ERROR")") //tableView.deselectRow(at: tableView.indexPathForSelectedRow!, animated: true) } } }
38.688073
145
0.664216
db9f83170d59f7df596202a22cea1cfdd7fbaa5f
246
// // IntervalEventProtocol.swift // ConflictingAppointments // // Created by Rudy Gomez on 3/20/20. // Copyright © 2020 JRudy Gaming. All rights reserved. // import Foundation protocol IntervalProtocol { var interval: Interval { get } }
17.571429
55
0.719512
286c84ed8459fd0c45c2ed36c22c089d280bf617
1,975
// // LoggedOutInteractor.swift // TicTacToe // // Created by Dinh, Nhat on 2019/03/11. // Copyright © 2019 Uber. All rights reserved. // import RIBs import RxSwift protocol LoggedOutRouting: ViewableRouting { // TODO: Declare methods the interactor can invoke to manage sub-tree via the router. } protocol LoggedOutPresentable: Presentable { var listener: LoggedOutPresentableListener? { get set } // TODO: Declare methods the interactor can invoke the presenter to present data. } protocol LoggedOutListener: class { // TODO: Declare methods the interactor can invoke to communicate with other RIBs. } final class LoggedOutInteractor: PresentableInteractor<LoggedOutPresentable>, LoggedOutInteractable, LoggedOutPresentableListener { weak var router: LoggedOutRouting? weak var listener: LoggedOutListener? // TODO: Add additional dependencies to constructor. Do not perform any logic // in constructor. override init(presenter: LoggedOutPresentable) { super.init(presenter: presenter) presenter.listener = self } override func didBecomeActive() { super.didBecomeActive() // TODO: Implement business logic here. } override func willResignActive() { super.willResignActive() // TODO: Pause any business logic. } // MARK: - LoggedOutPresentableListener func login(withPlayer1Name player1Name: String?, player2Name: String?) { let player1NameWithDefault = playerName(player1Name, withDefaultName: "Player 1") let player2NameWithDefault = playerName(player2Name, withDefaultName: "Player 2") print("\(player1NameWithDefault) vs \(player2NameWithDefault)") } private func playerName(_ name: String?, withDefaultName defaultName: String) -> String { if let name = name { return name.isEmpty ? defaultName : name } else { return defaultName } } }
30.859375
131
0.696709
7a37ff84ccb5a6bada80e9598501e29498944a52
1,472
/* * Copyright (c) 2019 Telekom Deutschland AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public typealias ExecCallCompletionHandler = (ExecCallAPIResult<Any?>) -> () public protocol CoreAPI { /// Checks if the device is jailbroken /// /// - Returns: bool value; true if device is jailbroken, false otherwise func isDeviceJailbroken() -> SmartCredentialsAPIResult<Bool> /// Executes a specific action on items /// /// - Parameters: /// - itemEnvelope: item containing configuration of service request /// - actionId: action ID used to identify the action /// - completionHandler: completion handler with result as parameter (.success or .failure with associated error) /// - Returns: Generic enum; success - encrypted text; failure - SmartCredentialsAPIError (enum) func execute(with item: ItemEnvelope, actionId: String, completionHandler: @escaping ExecCallCompletionHandler) }
39.783784
119
0.72894
5dac6af9f1805f075f1703c0517cbe1464764d85
697
// // MobileWalletUITests.swift // MobileWalletUITests // // Created by Jason van den Berg on 2019/10/28. // Copyright © 2019 Jason van den Berg. All rights reserved. // import XCTest class MobileWalletUITests: XCTestCase { private let app = XCUIApplication() override func setUp() { continueAfterFailure = false app.launchArguments = ["-disable-animations"] } override func tearDown() { } func testLaunchPerformance() { // if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { // XCUIApplication().launch() // } // } } }
22.483871
73
0.605452
729911c5263fbfc3398811c7f3d3471604fb8348
339
// // Category.swift // App // // Created by Denis Zubkov on 05/08/2019. // import Fluent import FluentMySQL import Vapor struct Category: Content { var id: UUID? var guid: String var dataVersion: String var name: String var short: String } extension Category: MySQLUUIDModel {} extension Category: Migration { }
14.73913
42
0.687316
398cb0f9b38d46070dcd83b5ff53b5654b4750c4
543
// // PhotoCell.swift // WK1LB1 // // Created by Pedro Daniel Sanchez on 9/10/18. // Copyright © 2018 Pedro Daniel Sanchez. All rights reserved. // import UIKit class PhotoCell: UITableViewCell { @IBOutlet weak var photoImage: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
20.111111
65
0.662983
8f6c674c7e3e493f2ba32ca15db2dd80a9920e3b
531
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // OriginPropertiesParametersProtocol is the JSON object that contains the properties of the origin. public protocol OriginPropertiesParametersProtocol : Codable { var hostName: String? { get set } var httpPort: Int32? { get set } var httpsPort: Int32? { get set } }
44.25
101
0.740113
3a44b87536b921b45efb8783456077c0c6740f11
6,778
// // ObserveOn.swift // RxSwift // // Created by Krunoslav Zaher on 7/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Wraps the source sequence in order to run its observer callbacks on the specified scheduler. This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription actions have side-effects that require to be run on a scheduler, use `subscribeOn`. - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) - parameter scheduler: Scheduler to notify observers on. - returns: The source sequence whose observations happen on the specified scheduler. */ public func observeOn(_ scheduler: ImmediateSchedulerType) -> Observable<E> { if let scheduler = scheduler as? SerialDispatchQueueScheduler { return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: scheduler) } else { return ObserveOn(source: self.asObservable(), scheduler: scheduler) } } } final private class ObserveOn<E>: Producer<E> { let scheduler: ImmediateSchedulerType let source: Observable<E> init(source: Observable<E>, scheduler: ImmediateSchedulerType) { self.scheduler = scheduler self.source = source #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = ObserveOnSink(scheduler: self.scheduler, observer: observer, cancel: cancel) let subscription = self.source.subscribe(sink) return (sink: sink, subscription: subscription) } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } enum ObserveOnState : Int32 { // pump is not running case stopped = 0 // pump is running case running = 1 } final private class ObserveOnSink<O: ObserverType>: ObserverBase<O.E> { typealias E = O.E let _scheduler: ImmediateSchedulerType var _lock = SpinLock() let _observer: O // state var _state = ObserveOnState.stopped var _queue = Queue<Event<E>>(capacity: 10) let _scheduleDisposable = SerialDisposable() let _cancel: Cancelable init(scheduler: ImmediateSchedulerType, observer: O, cancel: Cancelable) { self._scheduler = scheduler self._observer = observer self._cancel = cancel } override func onCore(_ event: Event<E>) { let shouldStart = self._lock.calculateLocked { () -> Bool in self._queue.enqueue(event) switch self._state { case .stopped: self._state = .running return true case .running: return false } } if shouldStart { self._scheduleDisposable.disposable = self._scheduler.scheduleRecursive((), action: self.run) } } func run(_ state: (), _ recurse: (()) -> Void) { let (nextEvent, observer) = self._lock.calculateLocked { () -> (Event<E>?, O) in if !self._queue.isEmpty { return (self._queue.dequeue(), self._observer) } else { self._state = .stopped return (nil, self._observer) } } if let nextEvent = nextEvent, !self._cancel.isDisposed { observer.on(nextEvent) if nextEvent.isStopEvent { self.dispose() } } else { return } let shouldContinue = self._shouldContinue_synchronized() if shouldContinue { recurse(()) } } func _shouldContinue_synchronized() -> Bool { self._lock.lock(); defer { self._lock.unlock() } // { if !self._queue.isEmpty { return true } else { self._state = .stopped return false } // } } override func dispose() { super.dispose() self._cancel.dispose() self._scheduleDisposable.dispose() } } #if TRACE_RESOURCES fileprivate var _numberOfSerialDispatchQueueObservables = AtomicInt(0) extension Resources { /** Counts number of `SerialDispatchQueueObservables`. Purposed for unit tests. */ public static var numberOfSerialDispatchQueueObservables: Int32 { return load(&_numberOfSerialDispatchQueueObservables) } } #endif final private class ObserveOnSerialDispatchQueueSink<O: ObserverType>: ObserverBase<O.E> { let scheduler: SerialDispatchQueueScheduler let observer: O let cancel: Cancelable var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink<O>, event: Event<E>)) -> Disposable)! init(scheduler: SerialDispatchQueueScheduler, observer: O, cancel: Cancelable) { self.scheduler = scheduler self.observer = observer self.cancel = cancel super.init() self.cachedScheduleLambda = { pair in guard !cancel.isDisposed else { return Disposables.create() } pair.sink.observer.on(pair.event) if pair.event.isStopEvent { pair.sink.dispose() } return Disposables.create() } } override func onCore(_ event: Event<E>) { _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!) } override func dispose() { super.dispose() self.cancel.dispose() } } final private class ObserveOnSerialDispatchQueue<E>: Producer<E> { let scheduler: SerialDispatchQueueScheduler let source: Observable<E> init(source: Observable<E>, scheduler: SerialDispatchQueueScheduler) { self.scheduler = scheduler self.source = source #if TRACE_RESOURCES let _ = Resources.incrementTotal() let _ = increment(&_numberOfSerialDispatchQueueObservables) #endif } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel) let subscription = self.source.subscribe(sink) return (sink: sink, subscription: subscription) } #if TRACE_RESOURCES deinit { let _ = Resources.decrementTotal() let _ = decrement(&_numberOfSerialDispatchQueueObservables) } #endif }
29.215517
138
0.62216
9b98daa063125c46fff9423c6e34dcc65eb11110
1,401
// ******************************************* // File Name: DispatchQueue+BQextension.swift // Author: MrBai // Created Date: 2019/8/15 9:26 AM // // Copyright © 2019 baiqiang // All rights reserved // ******************************************* import Foundation typealias TaskBlock = (_ cancel: Bool) -> Void extension DispatchQueue { private static var _onceTracker = [String]() public class func once(token: String, block: () -> Void) { objc_sync_enter(self) if !_onceTracker.contains(token) { _onceTracker.append(token) block() } objc_sync_exit(self) } @discardableResult class func after(_ time: TimeInterval, task: @escaping () -> Void) -> TaskBlock? { func dispatch_later(block: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time, execute: block) } var result: TaskBlock? let delayedClosure: TaskBlock = { cancel in if !cancel { DispatchQueue.main.async(execute: task) } result = nil } result = delayedClosure dispatch_later { if let closure = result { closure(false) } } return result } class func cancel(task: TaskBlock?) { task?(true) } }
26.433962
94
0.523198
e4f49039b10834db36a39fb27b521abafc2aa802
551
import Foundation import WatchKit class InterfaceController: WKInterfaceController { override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
26.238095
90
0.684211
481249126f952b228b9e0b93865fe4ff78728d09
921
// // PickerViewDemoTests.swift // PickerViewDemoTests // // Created by K.Yawn Xoan on 3/20/15. // Copyright (c) 2015 K.Yawn Xoan. All rights reserved. // import UIKit import XCTest class PickerViewDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.891892
111
0.619978
33e77c8653be47fc2ec70154172d7e1006caa0f9
27,493
import Foundation import CoreLocation import MapboxDirections import Polyline import MapboxMobileEvents import Turf protocol RouteControllerDataSource: AnyObject { var location: CLLocation? { get } var locationProvider: NavigationLocationManager.Type { get } } @available(*, deprecated, renamed: "RouteController") open class LegacyRouteController: NSObject, Router, InternalRouter, CLLocationManagerDelegate { public weak var delegate: RouterDelegate? public unowned var dataSource: RouterDataSource /** The Directions object used to create the route. */ public var directions: Directions /** The threshold used when we determine when the user has arrived at the waypoint. By default, we claim arrival 5 seconds before the user is physically estimated to arrive. */ public var waypointArrivalThreshold: TimeInterval = 5.0 public var reroutesProactively = true public var refreshesRoute: Bool = true var didFindFasterRoute = false var lastProactiveRerouteDate: Date? var lastRouteRefresh: Date? public var routeProgress: RouteProgress { get { return _routeProgress } set { if let location = self.location { delegate?.router(self, willRerouteFrom: location) } _routeProgress = newValue announce(reroute: routeProgress.route, at: location, proactive: didFindFasterRoute) } } private var _routeProgress: RouteProgress { didSet { movementsAwayFromRoute = 0 } } public var indexedRoute: IndexedRoute { get { return routeProgress.indexedRoute } set { routeProgress.indexedRoute = newValue } } public var route: Route { return indexedRoute.0 } var isRerouting = false var isRefreshing = false var lastRerouteLocation: CLLocation? var routeTask: URLSessionDataTask? var lastLocationDate: Date? var hasFoundOneQualifiedLocation = false var movementsAwayFromRoute = 0 var previousArrivalWaypoint: Waypoint? var isFirstLocation: Bool = true var userSnapToStepDistanceFromManeuver: CLLocationDistance? required public init(along route: Route, routeIndex: Int, options: RouteOptions, directions: Directions = Directions.shared, dataSource source: RouterDataSource) { self.directions = directions self._routeProgress = RouteProgress(route: route, routeIndex: routeIndex, options: options) self.dataSource = source self.refreshesRoute = options.profileIdentifier == .automobileAvoidingTraffic && options.refreshingEnabled UIDevice.current.isBatteryMonitoringEnabled = true super.init() checkForUpdates() checkForLocationUsageDescription() } deinit { if let del = delegate, del.routerShouldDisableBatteryMonitoring(self) { UIDevice.current.isBatteryMonitoringEnabled = false } } public var location: CLLocation? { // If there is no snapped location, and the rawLocation course is unqualified, use the user's heading as long as it is accurate. if snappedLocation == nil, let heading = heading, let loc = rawLocation, !loc.course.isQualified, heading.trueHeading.isQualified { return CLLocation(coordinate: loc.coordinate, altitude: loc.altitude, horizontalAccuracy: loc.horizontalAccuracy, verticalAccuracy: loc.verticalAccuracy, course: heading.trueHeading, speed: loc.speed, timestamp: loc.timestamp) } return snappedLocation ?? rawLocation } /** The raw location, snapped to the current route. - important: If the rawLocation is outside of the route snapping tolerances, this value is nil. */ var snappedLocation: CLLocation? { return rawLocation?.snapped(to: routeProgress) } var heading: CLHeading? /** The most recently received user location. - note: This is a raw location received from `locationManager`. To obtain an idealized location, use the `location` property. */ public var rawLocation: CLLocation? { didSet { if isFirstLocation == true { isFirstLocation = false } updateDistanceToManeuver() } } func updateDistanceToManeuver() { guard let shape = routeProgress.currentLegProgress.currentStep.shape, let coordinate = rawLocation?.coordinate else { userSnapToStepDistanceFromManeuver = nil return } userSnapToStepDistanceFromManeuver = shape.distance(from: coordinate) } public var reroutingTolerance: CLLocationDistance { guard let intersections = routeProgress.currentLegProgress.currentStepProgress.intersectionsIncludingUpcomingManeuverIntersection else { return RouteControllerMaximumDistanceBeforeRecalculating } guard let userLocation = rawLocation else { return RouteControllerMaximumDistanceBeforeRecalculating } for intersection in intersections { let absoluteDistanceToIntersection = userLocation.coordinate.distance(to: intersection.location) if absoluteDistanceToIntersection <= RouteControllerManeuverZoneRadius { return RouteControllerMaximumDistanceBeforeRecalculating / 2 } } return RouteControllerMaximumDistanceBeforeRecalculating } /** Monitors the user's course to see if it is consistantly moving away from what we expect the course to be at a given point. */ func userCourseIsOnRoute(_ location: CLLocation) -> Bool { let nearbyPolyline = routeProgress.nearbyShape guard let calculatedCourseForLocationOnStep = location.interpolatedCourse(along: nearbyPolyline) else { return true } let maxUpdatesAwayFromRouteGivenAccuracy = Int(location.horizontalAccuracy / Double(RouteControllerIncorrectCourseMultiplier)) if movementsAwayFromRoute >= max(RouteControllerMinNumberOfInCorrectCourses, maxUpdatesAwayFromRouteGivenAccuracy) { return false } else if location.shouldSnap(toRouteWith: calculatedCourseForLocationOnStep) { movementsAwayFromRoute = 0 } else { movementsAwayFromRoute += 1 } return true } public func userIsOnRoute(_ location: CLLocation) -> Bool { guard let destination = routeProgress.currentLeg.destination else { preconditionFailure("Route legs used for navigation must have destinations") } // If the user has arrived, do not continue monitor reroutes, step progress, etc if routeProgress.currentLegProgress.userHasArrivedAtWaypoint && (delegate?.router(self, shouldPreventReroutesWhenArrivingAt: destination) ?? RouteController.DefaultBehavior.shouldPreventReroutesWhenArrivingAtWaypoint) { return true } let isCloseToCurrentStep = userIsWithinRadiusOfRoute(location: location) guard !isCloseToCurrentStep || !userCourseIsOnRoute(location) else { return true } // Check and see if the user is near a future step. guard let nearestStep = routeProgress.currentLegProgress.closestStep(to: location.coordinate) else { return false } if nearestStep.distance < RouteControllerUserLocationSnappingDistance { // Only advance the stepIndex to a future step if the step is new. Otherwise, the user is still on the current step. if nearestStep.index != routeProgress.currentLegProgress.stepIndex { advanceStepIndex(to: nearestStep.index) } return true } return false } internal func userIsWithinRadiusOfRoute(location: CLLocation) -> Bool { let radius = max(reroutingTolerance, RouteControllerManeuverZoneRadius) let isCloseToCurrentStep = location.isWithin(radius, of: routeProgress.currentLegProgress.currentStep) return isCloseToCurrentStep } public func advanceLegIndex() { precondition(!routeProgress.isFinalLeg, "Can not increment leg index beyond final leg.") routeProgress.legIndex += 1 } // MARK: CLLocationManagerDelegate methods public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { heading = newHeading } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let filteredLocations = locations.filter { return $0.isQualified } if !filteredLocations.isEmpty, hasFoundOneQualifiedLocation == false { hasFoundOneQualifiedLocation = true } let currentStepProgress = routeProgress.currentLegProgress.currentStepProgress var potentialLocation: CLLocation? // `filteredLocations` contains qualified locations if let lastFiltered = filteredLocations.last { potentialLocation = lastFiltered // `filteredLocations` does not contain good locations and we have found at least one good location previously. } else if hasFoundOneQualifiedLocation { if let lastLocation = locations.last, delegate?.router(self, shouldDiscard: lastLocation) ?? RouteController.DefaultBehavior.shouldDiscardLocation { // Allow the user puck to advance. A stationary puck is not great. self.rawLocation = lastLocation return } // This case handles the first location. // This location is not a good location, but we need the rest of the UI to update and at least show something. } else if let lastLocation = locations.last { potentialLocation = lastLocation } guard let location = potentialLocation else { return } self.rawLocation = location updateIntersectionIndex(for: currentStepProgress) // Notify observers if the step’s remaining distance has changed. update(progress: routeProgress, with: self.location!, rawLocation: location) updateDistanceToIntersection(from: location) updateRouteStepProgress(for: location) updateRouteLegProgress(for: location) updateVisualInstructionProgress() if !userIsOnRoute(location) && delegate?.router(self, shouldRerouteFrom: location) ?? RouteController.DefaultBehavior.shouldRerouteFromLocation { reroute(from: location, along: routeProgress) return } updateSpokenInstructionProgress() // Check for faster route proactively (if reroutesProactively is enabled) refreshAndCheckForFasterRoute(from: location, routeProgress: routeProgress) } private func update(progress: RouteProgress, with location: CLLocation, rawLocation: CLLocation) { progress.updateDistanceTraveled(with: rawLocation) //Fire the delegate method delegate?.router(self, didUpdate: progress, with: location, rawLocation: rawLocation) //Fire the notification (for now) NotificationCenter.default.post(name: .routeControllerProgressDidChange, object: self, userInfo: [ RouteController.NotificationUserInfoKey.routeProgressKey: progress, RouteController.NotificationUserInfoKey.locationKey: location, //guaranteed value RouteController.NotificationUserInfoKey.rawLocationKey: rawLocation, //raw ]) } func updateIntersectionIndex(for currentStepProgress: RouteStepProgress) { guard let intersectionDistances = currentStepProgress.intersectionDistances else { return } let upcomingIntersectionIndex = intersectionDistances.firstIndex { $0 > currentStepProgress.distanceTraveled } ?? intersectionDistances.endIndex currentStepProgress.intersectionIndex = upcomingIntersectionIndex > 0 ? intersectionDistances.index(before: upcomingIntersectionIndex) : 0 } func updateRouteLegProgress(for location: CLLocation) { let legProgress = routeProgress.currentLegProgress guard let currentDestination = legProgress.leg.destination else { preconditionFailure("Route legs used for navigation must have destinations") } guard let remainingVoiceInstructions = legProgress.currentStepProgress.remainingSpokenInstructions else { return } // We are at least at the "You will arrive" instruction if legProgress.remainingSteps.count <= 1 && remainingVoiceInstructions.count <= 1 && currentDestination != previousArrivalWaypoint { //Have we actually arrived? Last instruction is "You have arrived" if remainingVoiceInstructions.count == 0, legProgress.durationRemaining <= waypointArrivalThreshold { previousArrivalWaypoint = currentDestination legProgress.userHasArrivedAtWaypoint = true let advancesToNextLeg = delegate?.router(self, didArriveAt: currentDestination) ?? RouteController.DefaultBehavior.didArriveAtWaypoint guard !routeProgress.isFinalLeg && advancesToNextLeg else { return } advanceLegIndex() updateDistanceToManeuver() } else { //we are approaching the destination delegate?.router(self, willArriveAt: currentDestination, after: legProgress.durationRemaining, distance: legProgress.distanceRemaining) } } } public func reroute(from location: CLLocation, along progress: RouteProgress) { if let lastRerouteLocation = lastRerouteLocation { guard location.distance(from: lastRerouteLocation) >= RouteControllerMaximumDistanceBeforeRecalculating else { return } } if isRerouting { return } isRerouting = true delegate?.router(self, willRerouteFrom: location) NotificationCenter.default.post(name: .routeControllerWillReroute, object: self, userInfo: [ RouteController.NotificationUserInfoKey.locationKey: location, ]) self.lastRerouteLocation = location getDirections(from: location, along: progress) { [weak self] (session, result) in guard let strongSelf = self else { return } strongSelf.isRerouting = false switch result { case let .failure(error): strongSelf.delegate?.router(strongSelf, didFailToRerouteWith: error) NotificationCenter.default.post(name: .routeControllerDidFailToReroute, object: self, userInfo: [ RouteController.NotificationUserInfoKey.routingErrorKey: error, ]) return case let .success(response): guard case let .route(options) = response.options, let route = response.routes?.first else { return } strongSelf.indexedRoute = (route, 0) // unconditionally getting the first route above strongSelf._routeProgress = RouteProgress(route: route, routeIndex: 0, options: options, legIndex: 0) strongSelf._routeProgress.currentLegProgress.stepIndex = 0 strongSelf.announce(reroute: route, at: location, proactive: false) } } } private func checkForUpdates() { #if TARGET_IPHONE_SIMULATOR guard (NSClassFromString("XCTestCase") == nil) else { return } // Short-circuit when running unit tests guard let version = Bundle(for: RouteController.self).object(forInfoDictionaryKey: "CFBundleShortVersionString") else { return } let latestVersion = String(describing: version) _ = URLSession.shared.dataTask(with: URL(string: "https://docs.mapbox.com/ios/navigation/latest_version.txt")!, completionHandler: { (data, response, error) in if let _ = error { return } guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { return } guard let data = data, let currentVersion = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .newlines) else { return } if latestVersion != currentVersion { let updateString = NSLocalizedString("UPDATE_AVAILABLE", bundle: .mapboxCoreNavigation, value: "Mapbox Navigation SDK for iOS version %@ is now available.", comment: "Inform developer an update is available") print(String.localizedStringWithFormat(updateString, latestVersion), "https://github.com/mapbox/mapbox-navigation-ios/releases/tag/v\(latestVersion)") } }).resume() #endif } private func checkForLocationUsageDescription() { guard let _ = Bundle.main.bundleIdentifier else { return } if Bundle.main.locationAlwaysUsageDescription == nil && Bundle.main.locationWhenInUseUsageDescription == nil && Bundle.main.locationAlwaysAndWhenInUseUsageDescription == nil { preconditionFailure("This application’s Info.plist file must include a NSLocationWhenInUseUsageDescription. See https://developer.apple.com/documentation/corelocation for more information.") } } func updateDistanceToIntersection(from location: CLLocation) { guard var intersections = routeProgress.currentLegProgress.currentStepProgress.step.intersections else { return } let currentStepProgress = routeProgress.currentLegProgress.currentStepProgress // The intersections array does not include the upcoming maneuver intersection. if let upcomingStep = routeProgress.currentLegProgress.upcomingStep, let upcomingIntersection = upcomingStep.intersections, let firstUpcomingIntersection = upcomingIntersection.first { intersections += [firstUpcomingIntersection] } routeProgress.currentLegProgress.currentStepProgress.intersectionsIncludingUpcomingManeuverIntersection = intersections guard let shape = currentStepProgress.step.shape else { return } if let upcomingIntersection = routeProgress.currentLegProgress.currentStepProgress.upcomingIntersection { routeProgress.currentLegProgress.currentStepProgress.userDistanceToUpcomingIntersection = shape.distance(from: location.coordinate, to: upcomingIntersection.location) } if routeProgress.currentLegProgress.currentStepProgress.intersectionDistances == nil { routeProgress.currentLegProgress.currentStepProgress.intersectionDistances = [CLLocationDistance]() updateIntersectionDistances() } } func updateRouteStepProgress(for location: CLLocation) { guard routeProgress.currentLegProgress.remainingSteps.count > 0 else { return } guard let userSnapToStepDistanceFromManeuver = userSnapToStepDistanceFromManeuver else { return } var courseMatchesManeuverFinalHeading = false // Bearings need to normalized so when the `finalHeading` is 359 and the user heading is 1, // we count this as within the `RouteControllerMaximumAllowedDegreeOffsetForTurnCompletion` if let upcomingStep = routeProgress.currentLegProgress.upcomingStep, let finalHeading = upcomingStep.finalHeading, let initialHeading = upcomingStep.initialHeading { let initialHeadingNormalized = initialHeading.wrap(min: 0, max: 360) let finalHeadingNormalized = finalHeading.wrap(min: 0, max: 360) let expectedTurningAngle = initialHeadingNormalized.difference(from: finalHeadingNormalized) // If the upcoming maneuver is fairly straight, // do not check if the user is within x degrees of the exit heading. // For ramps, their current heading will very close to the exit heading. // We need to wait until their moving away from the maneuver location instead. // We can do this by looking at their snapped distance from the maneuver. // Once this distance is zero, they are at more moving away from the maneuver location if expectedTurningAngle <= RouteControllerMaximumAllowedDegreeOffsetForTurnCompletion { courseMatchesManeuverFinalHeading = userSnapToStepDistanceFromManeuver == 0 } else if location.course.isQualified { let userHeadingNormalized = location.course.wrap(min: 0, max: 360) courseMatchesManeuverFinalHeading = finalHeadingNormalized.difference(from: userHeadingNormalized) <= RouteControllerMaximumAllowedDegreeOffsetForTurnCompletion } } let step = routeProgress.currentLegProgress.upcomingStep?.maneuverLocation ?? routeProgress.currentLegProgress.currentStep.maneuverLocation let userAbsoluteDistance = step.distance(to: location.coordinate) let lastKnownUserAbsoluteDistance = routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation if userSnapToStepDistanceFromManeuver <= RouteControllerManeuverZoneRadius && (courseMatchesManeuverFinalHeading || (userAbsoluteDistance > lastKnownUserAbsoluteDistance && lastKnownUserAbsoluteDistance > RouteControllerManeuverZoneRadius)) { advanceStepIndex() } routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation = userAbsoluteDistance } func updateSpokenInstructionProgress() { guard let userSnapToStepDistanceFromManeuver = userSnapToStepDistanceFromManeuver else { return } guard let spokenInstructions = routeProgress.currentLegProgress.currentStepProgress.remainingSpokenInstructions else { return } // Always give the first voice announcement when beginning a leg. let firstInstructionOnFirstStep = routeProgress.currentLegProgress.stepIndex == 0 && routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex == 0 for spokenInstruction in spokenInstructions { if userSnapToStepDistanceFromManeuver <= spokenInstruction.distanceAlongStep || firstInstructionOnFirstStep { delegate?.router(self, didPassSpokenInstructionPoint: spokenInstruction, routeProgress: routeProgress) NotificationCenter.default.post(name: .routeControllerDidPassSpokenInstructionPoint, object: self, userInfo: [ RouteController.NotificationUserInfoKey.routeProgressKey: routeProgress, RouteController.NotificationUserInfoKey.spokenInstructionKey: spokenInstruction, ]) routeProgress.currentLegProgress.currentStepProgress.spokenInstructionIndex += 1 return } } } func updateVisualInstructionProgress() { guard let userSnapToStepDistanceFromManeuver = userSnapToStepDistanceFromManeuver else { return } let currentStepProgress = routeProgress.currentLegProgress.currentStepProgress guard let visualInstructions = currentStepProgress.remainingVisualInstructions else { return } for visualInstruction in visualInstructions { if userSnapToStepDistanceFromManeuver <= visualInstruction.distanceAlongStep || isFirstLocation { delegate?.router(self, didPassVisualInstructionPoint: visualInstruction, routeProgress: routeProgress) NotificationCenter.default.post(name: .routeControllerDidPassVisualInstructionPoint, object: self, userInfo: [ RouteController.NotificationUserInfoKey.routeProgressKey: routeProgress, RouteController.NotificationUserInfoKey.visualInstructionKey: visualInstruction, ]) currentStepProgress.visualInstructionIndex += 1 return } } } func advanceStepIndex(to: Array<RouteStep>.Index? = nil) { if let forcedStepIndex = to { guard forcedStepIndex < routeProgress.currentLeg.steps.count else { return } routeProgress.currentLegProgress.stepIndex = forcedStepIndex } else { routeProgress.currentLegProgress.stepIndex += 1 } updateIntersectionDistances() updateDistanceToManeuver() } func updateIntersectionDistances() { if let shape = routeProgress.currentLegProgress.currentStep.shape, let intersections = routeProgress.currentLegProgress.currentStep.intersections { let distances: [CLLocationDistance] = intersections.compactMap { shape.distance(from: shape.coordinates.first, to: $0.location) } routeProgress.currentLegProgress.currentStepProgress.intersectionDistances = distances } } // MARK: Obsolete methods @available(swift, obsoleted: 0.1, message: "MapboxNavigationService is now the point-of-entry to MapboxCoreNavigation. Direct use of RouteController is no longer reccomended. See MapboxNavigationService for more information.") /// :nodoc: Obsoleted method. public convenience init(along route: Route, directions: Directions = Directions.shared, dataSource: NavigationLocationManager = NavigationLocationManager(), eventsManager: NavigationEventsManager) { fatalError() } @available(swift, obsoleted: 0.1, message: "RouteController no longer manages a location manager directly. Instead, the Router protocol conforms to CLLocationManagerDelegate, and RouteControllerDataSource provides access to synchronous location requests.") /// :nodoc: obsoleted public final var locationManager: NavigationLocationManager! { get { fatalError() } set { fatalError() } } @available(swift, obsoleted: 0.1, message: "NavigationViewController no longer directly manages a TunnelIntersectionManager. See MapboxNavigationService, which contains a reference to the locationManager, for more information.") /// :nodoc: obsoleted public final var tunnelIntersectionManager: Any! { get { fatalError() } set { fatalError() } } @available(swift, obsoleted: 0.1, renamed: "navigationService.eventsManager", message: "NavigationViewController no longer directly manages a NavigationEventsManager. See MapboxNavigationService, which contains a reference to the eventsManager, for more information.") /// :nodoc: obsoleted public final var eventsManager: NavigationEventsManager! { get { fatalError() } set { fatalError() } } /// Required through `Router` protocol. No-op public func enableLocationRecording() { // no-op } /// Required through `Router` protocol. No-op public func disableLocationRecording() { // no-op } /// Required through `Router` protocol. No-op public func locationHistory() -> String? { return nil } }
46.677419
272
0.691558
461c37d77419d612b4311d3b062a37f749366030
2,497
// // This object stays in memory runtime and holds key data and operations on Schedules. // The obect is the model for the Schedules but also acts as Controller when // the ViewControllers reads or updates data. // // Created by Thomas Evensen on 09/05/16. // Copyright © 2016 Thomas Evensen. All rights reserved. // import Cocoa import Foundation class Schedules: ScheduleWriteLoggData { // Return reference to Schedule data // self.Schedule is privat data func getSchedule() -> [ConfigurationSchedule]? { return self.schedules } // Function deletes all Schedules by hiddenID. Invoked when Configurations are // deleted. When a Configuration are deleted all tasks connected to // Configuration has to be deleted. // - parameter hiddenID : hiddenID for task func deletescheduleonetask(hiddenID: Int) { var delete: Bool = false for i in 0 ..< (self.schedules?.count ?? 0) where self.schedules?[i].hiddenID == hiddenID { // Mark Schedules for delete // Cannot delete in memory, index out of bound is result self.schedules?[i].delete = true delete = true } if delete { PersistentStorageScheduling(profile: self.profile).savescheduleInMemoryToPersistentStore() // Send message about refresh tableView self.reloadtable(vcontroller: .vctabmain) } } // Test if Schedule record in memory is set to delete or not func delete(dict: NSDictionary) { if let hiddenID = dict.value(forKey: DictionaryStrings.hiddenID.rawValue) as? Int { if let schedule = dict.value(forKey: DictionaryStrings.schedule.rawValue) as? String { if let datestart = dict.value(forKey: DictionaryStrings.dateStart.rawValue) as? String { if let i = self.schedules?.firstIndex(where: { $0.hiddenID == hiddenID && $0.schedule == schedule && $0.dateStart == datestart }) { self.schedules?[i].delete = true } } } } } override init(profile: String?) { super.init(profile: profile) self.profile = profile let schedulesdata = SchedulesData(profile: profile, validhiddenID: self.configurations?.validhiddenID) self.schedules = schedulesdata.schedules } }
39.634921
104
0.614337
676ec637a470334d96fff99ce0c0f2e91efc590e
5,468
// // FiatServiceTest.swift // XWalletTests // // Created by loj on 11.03.18. // import XCTest import iVault class FiatServiceTest: XCTestCase { private var testee: FiatService! private var fiatProviderMock: FiatProviderMock! private var dateProviderMock: DateProviderMock! private var propertyStoreMock: PropertyStoreMock! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. self.fiatProviderMock = FiatProviderMock() self.dateProviderMock = DateProviderMock() self.propertyStoreMock = PropertyStoreMock() self.testee = FiatService(fiatProvider: self.fiatProviderMock, dateProvider: self.dateProviderMock, propertyStore: self.propertyStoreMock) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() self.testee.stopUpdating() } func test_WhenNeverStarted_AndAskingForXMREquivalent_ThenReturnsNone() { let fiatValue = 22.08 let expectedXMRValue = FiatEquivalent<UInt64>.none self.testee.stopUpdating() let xmrValue = self.testee.getXMR(forFiatValue: fiatValue) XCTAssertTrue(FiatServiceTest.areEqual(lhs: xmrValue, rhs: expectedXMRValue)) } func test_WhenNeverStarted_AndAskingForFiatEquivalent_ThenReturnsNone() { let xmrValue: UInt64 = 2208 let expectedFiatValue = FiatEquivalent<Double>.none self.testee.stopUpdating() let fiatValue = self.testee.getFiat(forXMRValue: xmrValue) XCTAssertTrue(FiatServiceTest.areEqual(lhs: fiatValue, rhs: expectedFiatValue)) } func test_WhenStopped_ThenReturnsLastKnown() { let fiatValue = 22080.0 let expectedAge = FiatAge.recent let expectedXMRValue: UInt64 = 2208_000_000_000_000 let lastUpdate = Date() let lastFactor = 10.0 self.dateProviderMock.fakeNow = lastUpdate self.propertyStoreMock.lastFiatUpdate = lastUpdate self.propertyStoreMock.lastFiatFactor = lastFactor let expectedResult = FiatEquivalent<UInt64>.value(age: expectedAge, amount: expectedXMRValue) self.testee.stopUpdating() let currentResult = self.testee.getXMR(forFiatValue: fiatValue) XCTAssertTrue(FiatServiceTest.areEqual(lhs: currentResult, rhs: expectedResult)) } func test_WhenStarted_AndDidNotifiy_ThenGetsRecentFiatValue() { let fiatValue = 22080.0 let xmrValue: UInt64 = 2208_000_000_000_000 let fiatFactor = 10.0 self.fiatProviderMock.factor = fiatFactor let expectedFiatValue = FiatEquivalent.value(age: .recent, amount: fiatValue) self.testee.startUpdating(withIntervalInSeconds: 60, notificationHandler: { let receivedFiatValue = self.testee.getFiat(forXMRValue: xmrValue) XCTAssertTrue(FiatServiceTest.areEqual(lhs: receivedFiatValue, rhs: expectedFiatValue)) }) } func test_WhenStarted_AndDidNotifiy_ThenGetsRecentXMRValue() { let fiatValue = 22080.0 let xmrValue: UInt64 = 2208_000_000_000_000 let fiatFactor = 10.0 self.fiatProviderMock.factor = fiatFactor let expectedXMRValue = FiatEquivalent.value(age: .recent, amount: xmrValue) self.testee.startUpdating(withIntervalInSeconds: 60, notificationHandler: { let receivedXMRValue = self.testee.getXMR(forFiatValue: fiatValue) XCTAssertTrue(FiatServiceTest.areEqual(lhs: receivedXMRValue, rhs: expectedXMRValue)) }) } private class FiatProviderMock: FiatProviderProtocol { public var factor: Double = 1.0 func getFiatEquivalent(forCurrency currency: String, completionHandler: @escaping (Double, String) -> Void, failedHandler: @escaping () -> Void) { completionHandler(factor, currency) } } private class DateProviderMock: DateProviderProtocol { public var fakeNow = Date() func now() -> Date { return self.fakeNow } } private class PropertyStoreMock: PropertyStoreProtocol { func wipeAll() {} var deprecatedAppPin: String? var onboardingIsFinished: Bool = true var language: String = "" var currency: String = "" var nodeAddress: String = "" var lastFiatUpdate: Date? = nil var lastFiatFactor: Double? = nil var feeInAtomicUnits: UInt64 = 0 } } extension FiatServiceTest { private static func areEqual<T>(lhs: FiatEquivalent<T>, rhs: FiatEquivalent<T>) -> Bool where T: Comparable { switch (lhs, rhs) { case (.none, .none): return true case let (.value(age1, amount1), .value(age2, amount2)): return age1 == age2 && amount1 == amount2 default: return false } } }
33.546012
123
0.622714
39f982f92d877e346c8e9d3e55e1c912de107784
4,322
// // ServiceGenerationTests.swift // // // Created by Dmitry Demyanov on 13.11.2020. // import XCTest @testable import SurfGenKit import PathKit import Stencil /// Tests for generating full service code from prepared GAST tree class ServiceGenerationTests: XCTestCase { let serviceGenerator = ServiceGenerator.defaultGenerator(for: .swift) var environment: Environment { let path = Path(#file) + "../../../../Templates/Swift" let loader = FileSystemLoader(paths: [path]) return Environment(loader: loader) } func testGeneratedUrlRouteMatchesExpected() throws { // given let expectedCode = TestService.pet.getCode(for: .urlRoute) let expectedFileName = TestService.pet.fileName(for: .urlRoute) // when let generatedService = try serviceGenerator.generateCode(for: NodesBuilder.formTestServiceDeclarationNode(), withServiceName: TestService.pet.rawValue, parts: ServicePart.allCases, environment: environment) guard let generatedRoute = generatedService[.urlRoute] else { XCTFail("Route was not generated") return } // then XCTAssertEqual(generatedRoute.fileName, expectedFileName, "File name is not equal to expected one. Resulted value:\n\(generatedRoute.fileName)") XCTAssertEqual(generatedRoute.code, expectedCode, FileComparator().getDifference(for: generatedRoute.code, expectedFile: expectedCode)) } func testGeneratedServiceProtocolMatchesExpected() throws { // given let expectedCode = TestService.pet.getCode(for: .protocol) let expectedFileName = TestService.pet.fileName(for: .protocol) let generator = ServiceGenerator.defaultGenerator(for: .swift) // when let generatedService = try generator.generateCode(for: NodesBuilder.formTestServiceDeclarationNode(), withServiceName: TestService.pet.rawValue, parts: ServicePart.allCases, environment: environment) guard let generatedProtocol = generatedService[.protocol] else { XCTFail("Protocol was not generated") return } // then XCTAssertEqual(generatedProtocol.fileName, expectedFileName, "File name is not equal to expected one. Resulted value:\n\(generatedProtocol.fileName)") XCTAssertEqual(generatedProtocol.code, expectedCode, FileComparator().getDifference(for: generatedProtocol.code, expectedFile: expectedCode)) } func testGeneratedServiceImplementationMatchesExpected() throws { // given let expectedCode = TestService.pet.getCode(for: .service) let expectedFileName = TestService.pet.fileName(for: .service) let generator = ServiceGenerator.defaultGenerator(for: .swift) // when let generatedService = try generator.generateCode(for: NodesBuilder.formTestServiceDeclarationNode(), withServiceName: TestService.pet.rawValue, parts: ServicePart.allCases, environment: environment) guard let generatedImplementation = generatedService[.service] else { XCTFail("Service was not generated") return } // then XCTAssertEqual(generatedImplementation.fileName, expectedFileName, "File name is not equal to expected one. Resulted value:\n\(generatedImplementation.fileName)") XCTAssertEqual(generatedImplementation.code, expectedCode, FileComparator().getDifference(for: generatedImplementation.code, expectedFile: expectedCode)) } }
43.22
118
0.583526
abe52ab76f146980fe4686e6d15e109861e12df9
713
// // RouteCollection\.swift // SampleRoutingPackageDescription // // Created by satoutakeshi on 2017/10/09. // import Foundation import Vapor import HTTP import Routing public class V3Collection: RouteCollection, EmptyInitializable { public required init() {} public func build(_ builder: RouteBuilder) { let v3 = builder.grouped("v3") let users = v3.grouped("users") let articles = v3.grouped("articles") users.get { request in return "Requested all users." } articles.get(String.parameter){ request in let articleName = try request.parameters.next(String.self) return "Requested \(articleName)" } } }
25.464286
70
0.646564
1dbe6527ea89d651a8da8ae45730f126294b4636
1,127
// Copyright © 2018 Refrakt <[email protected]> // All rights reserved. // // This source code is licensed under the BSD 3-Clause license found in the // LICENSE file in the root directory of this source tree. import UIKit import WebKit class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate { private var webView: WKWebView! override func loadView() { let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = self webView.navigationDelegate = self view = webView } override func viewDidLoad() { super.viewDidLoad() if let fileURL = fileURL { webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL.deletingLastPathComponent()) } } var fileURL: URL? { didSet { if isViewLoaded { if let fileURL = fileURL { webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL.deletingLastPathComponent()) } } } } }
28.175
107
0.63354
7a3a144240b02b8fdaa0550c5f019790dd520673
8,216
// // BuildableItem.swift // SmartAILibrary // // Created by Michael Rommel on 05.02.20. // Copyright © 2020 Michael Rommel. All rights reserved. // import Foundation public enum BuildableItemType: Int, Codable { case unit case building case wonder case district case project } public class BuildableItem: Codable { enum CodingKeys: CodingKey { case type case unit case building case wonder case district case project case location case production } public let type: BuildableItemType // one or the other public let unitType: UnitType? public let buildingType: BuildingType? public let wonderType: WonderType? public let districtType: DistrictType? public let projectType: ProjectType? public let location: HexPoint? // for districts and wonders public var production: Double public init(unitType: UnitType) { self.type = .unit self.unitType = unitType self.buildingType = nil self.wonderType = nil self.districtType = nil self.projectType = nil self.location = nil self.production = 0.0 } public init(buildingType: BuildingType) { self.type = .building self.unitType = nil self.buildingType = buildingType self.wonderType = nil self.districtType = nil self.projectType = nil self.location = nil self.production = 0.0 } public init(wonderType: WonderType, at location: HexPoint) { self.type = .wonder self.unitType = nil self.buildingType = nil self.wonderType = wonderType self.districtType = nil self.projectType = nil self.location = location self.production = 0.0 } public init(districtType: DistrictType, at location: HexPoint) { self.type = .district self.unitType = nil self.buildingType = nil self.wonderType = nil self.districtType = districtType self.projectType = nil self.location = location self.production = 0.0 } public init(projectType: ProjectType) { self.type = .building self.unitType = nil self.buildingType = nil self.wonderType = nil self.districtType = nil self.projectType = projectType self.location = nil self.production = 0.0 } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.type = try container.decode(BuildableItemType.self, forKey: .type) switch self.type { case .unit: self.unitType = try container.decode(UnitType.self, forKey: .unit) self.buildingType = nil self.wonderType = nil self.districtType = nil self.projectType = nil self.location = nil case .building: self.unitType = nil self.buildingType = try container.decode(BuildingType.self, forKey: .building) self.wonderType = nil self.districtType = nil self.projectType = nil self.location = nil case .wonder: self.unitType = nil self.buildingType = nil self.wonderType = try container.decode(WonderType.self, forKey: .wonder) self.districtType = nil self.projectType = nil self.location = try container.decode(HexPoint.self, forKey: .location) case .district: self.unitType = nil self.buildingType = nil self.wonderType = nil self.districtType = try container.decode(DistrictType.self, forKey: .district) self.projectType = nil self.location = try container.decode(HexPoint.self, forKey: .location) case .project: self.unitType = nil self.buildingType = nil self.wonderType = nil self.districtType = nil self.projectType = try container.decode(ProjectType.self, forKey: .project) self.location = nil } self.production = try container.decode(Double.self, forKey: .production) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.type, forKey: .type) try container.encode(self.unitType, forKey: .unit) try container.encode(self.buildingType, forKey: .building) try container.encode(self.wonderType, forKey: .wonder) try container.encode(self.districtType, forKey: .district) try container.encode(self.projectType, forKey: .project) try container.encode(self.production, forKey: .production) try container.encode(self.location, forKey: .location) } func add(production productionDelta: Double) { self.production += productionDelta } func productionLeft() -> Double { switch self.type { case .unit: if let unitType = self.unitType { return Double(unitType.productionCost()) - self.production } return 0.0 case .building: if let buildingType = self.buildingType { return Double(buildingType.productionCost()) - self.production } return 0.0 case .wonder: if let wonderType = self.wonderType { return Double(wonderType.productionCost()) - self.production } return 0.0 case .district: if let districtType = self.districtType { return Double(districtType.productionCost()) - self.production } return 0.0 case .project: if let projectType = self.projectType { return Double(projectType.productionCost()) - self.production } return 0.0 } } func ready() -> Bool { return self.productionLeft() <= 0 } } extension BuildableItem: Hashable { public static func == (lhs: BuildableItem, rhs: BuildableItem) -> Bool { if lhs.type != rhs.type { return false } switch lhs.type { case .unit: return lhs.unitType == rhs.unitType case .building: return lhs.buildingType == rhs.buildingType case .wonder: return lhs.wonderType == rhs.wonderType && lhs.location! == rhs.location! case .project: return lhs.projectType == rhs.projectType case .district: return lhs.districtType == rhs.districtType && lhs.location! == rhs.location! } } public func hash(into hasher: inout Hasher) { hasher.combine(self.type) hasher.combine(self.unitType) hasher.combine(self.buildingType) hasher.combine(self.wonderType) hasher.combine(self.projectType) hasher.combine(self.districtType) hasher.combine(self.location) } } extension BuildableItem: CustomDebugStringConvertible { public var debugDescription: String { switch self.type { case .unit: if let unitType = self.unitType { return "Unit: \(unitType)" } return "Unit: ???" case .building: if let buildingType = self.buildingType { return "Building: \(buildingType)" } return "Building: ???" case .wonder: if let wonderType = self.wonderType { return "wonder: \(wonderType) at: \(self.location!)" } return "wonder: ???" case .district: if let districtType = self.districtType { return "District: \(districtType) at: \(self.location!)" } return "District: ???" case .project: if let projectType = self.projectType { return "Project: \(projectType)" } return "Project: n/a" } } }
27.295681
90
0.584713
1f03b98dc66064fba985746d6d62587eec835c5b
2,176
// // AppDelegate.swift // Flappy Felipe // // Created by Rudrank Riyam on 22/06/19. // Copyright © 2019 Rudrank. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. } }
46.297872
285
0.755055
fbf005bbc7feba237996b7c443254a585390a49f
2,851
// // PJComposeToolBar.swift // WeiBo // // Created by 潘金强 on 16/7/19. // Copyright © 2016年 潘金强. All rights reserved. // import UIKit enum composeToolBarButtonType :Int{ case Picture = 0 case Mention = 1 case Trend = 2 case Emotion = 3 case Add = 4 } class PJComposeToolBar: UIStackView { var emotoinButton :UIButton? var selectClosure :((type: composeToolBarButtonType) -> ())? override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { //设置布局 axis = .Horizontal distribution = .FillEqually backgroundColor = UIColor.redColor() addButton("compose_toolbar_picture", type: .Picture) addButton("compose_mentionbutton_background", type: .Mention) addButton("compose_trendbutton_background", type: .Trend) emotoinButton = addButton("compose_emoticonbutton_background", type: .Emotion) addButton("compose_add_background", type: .Add) } private func addButton(imageName: String,type: composeToolBarButtonType) -> UIButton{ let button = UIButton() button.tag = type.rawValue button.addTarget(self, action: "clickButton:", forControlEvents: .TouchUpInside) // 设置图片 button.setImage(UIImage(named: imageName), forState: .Normal) button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: .Highlighted) // 设置背景图片 button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: .Normal) button.adjustsImageWhenHighlighted = false // addSubview(button) addArrangedSubview(button) return button } @objc private func clickButton(button: UIButton){ let type = composeToolBarButtonType(rawValue: button.tag)! selectClosure?(type: type) } func showEnmotion(isEmotion: Bool){ if isEmotion { emotoinButton?.setImage(UIImage(named: "compose_keyboardbutton_background"), forState: .Normal) emotoinButton?.setImage(UIImage(named: "compose_keyboardbutton_background_highlighted"), forState: .Highlighted) } else { emotoinButton?.setImage(UIImage(named: "compose_emoticonbutton_background"), forState: .Normal) emotoinButton?.setImage(UIImage(named: "compose_emoticonbutton_background_highlighted"), forState: .Highlighted) } } }
24.577586
124
0.597685
e67a5180e269abe5f15cf9367f71ef589b5edd3c
3,230
// // DetailView.swift // Scrumdinger // // Created by Andrew Morgan on 22/12/2020. // import SwiftUI struct DetailView: View { @Binding var scrum: DailyScrum @State private var data = DailyScrum.Data() @State private var isPresented = false var body: some View { List { Section(header: Text("Meeting Info")) { NavigationLink( destination: MeetingView(scrum: $scrum)) { Label("Start Meeting", systemImage: "timer") .font(.headline) .foregroundColor(.accentColor) .accessibilityLabel(Text("Start meeting")) } HStack { Label("Length", systemImage: "clock") Spacer() Text("\(scrum.lengthInMinutes) minutes") } HStack { Label("Color", systemImage: "paintpalette") Spacer() Image(systemName: "checkmark.circle.fill") .foregroundColor(scrum.color) } .accessibilityElement(children: .ignore) } Section(header: Text("Attendees")) { ForEach(scrum.attendees, id: \.self) { attendee in Label(attendee, systemImage: "person") .accessibilityLabel(Text("Person")) .accessibilityValue(Text(attendee)) } } Section(header: Text("History")) { if scrum.history.isEmpty { Label("No meetings yet", systemImage: "calendar.badge.exclamationmark") } ForEach(scrum.history) { history in NavigationLink(destination: HistoryView(history: history )) { HStack { Image(systemName: "calendar") Text(history.date, style: .date) } } } } } .listStyle(InsetGroupedListStyle()) .navigationBarItems(trailing: Button("Edit") { isPresented = true data = scrum.data }) .navigationTitle(scrum.title) .fullScreenCover(isPresented: $isPresented) { NavigationView { EditView(scrumData: $data) .navigationTitle(scrum.title) .navigationBarItems(leading: Button("Cancel") { isPresented = false }, trailing: Button("Done") { isPresented = false scrum.update(from: data) }) } } } } struct DetailView_Previews: PreviewProvider { static var previews: some View { NavigationView { DetailView(scrum: .constant(DailyScrum.data[0])) } } }
37.126437
316
0.435913
dd642d9a4366795094780e5b90c9f8b903a3324f
38,775
// Foundation/URLSession/URLSessionTask.swift - URLSession API // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// URLSession API code. /// - SeeAlso: URLSession.swift /// // ----------------------------------------------------------------------------- import CoreFoundation import Dispatch /// A cancelable object that refers to the lifetime /// of processing a given request. open class URLSessionTask : NSObject, NSCopying { public var countOfBytesClientExpectsToReceive: Int64 { NSUnimplemented() } public var countOfBytesClientExpectsToSend: Int64 { NSUnimplemented() } public var earliestBeginDate: Date? { NSUnimplemented() } /// How many times the task has been suspended, 0 indicating a running task. internal var suspendCount = 1 internal var session: URLSessionProtocol! //change to nil when task completes internal let body: _Body fileprivate var _protocol: URLProtocol? = nil private let syncQ = DispatchQueue(label: "org.swift.URLSessionTask.SyncQ") /// All operations must run on this queue. internal let workQueue: DispatchQueue public override init() { // Darwin Foundation oddly allows calling this initializer, even though // such a task is quite broken -- it doesn't have a session. And calling // e.g. `taskIdentifier` will crash. // // We set up the bare minimum for init to work, but don't care too much // about things crashing later. session = _MissingURLSession() taskIdentifier = 0 originalRequest = nil body = .none workQueue = DispatchQueue(label: "URLSessionTask.notused.0") super.init() } /// Create a data task. If there is a httpBody in the URLRequest, use that as a parameter internal convenience init(session: URLSession, request: URLRequest, taskIdentifier: Int) { var urlRequest = request // If inputStream in use and 'Content-Length' contains in headers, use data instead of stream(because of Transfer-Encoding: chunked for InputStream) if let inputStream = urlRequest.httpBodyStream, let contentLength = URLSessionTask.getContentLengthFromHeader(urlRequest) { let data = URLSessionTask.inputStreamToData(inputStream, contentLength: contentLength) urlRequest.httpBody = data } if let bodyData = urlRequest.httpBody { urlRequest.setValue(String(bodyData.count), forHTTPHeaderField: "Content-Length") // Update content length self.init(session: session, request: urlRequest, taskIdentifier: taskIdentifier, body: _Body.data(createDispatchData(bodyData))) } else if let bodyStream = urlRequest.httpBodyStream { self.init(session: session, request: urlRequest, taskIdentifier: taskIdentifier, body: _Body.stream(bodyStream)) } else { self.init(session: session, request: urlRequest, taskIdentifier: taskIdentifier, body: .none) } } internal init(session: URLSession, request: URLRequest, taskIdentifier: Int, body: _Body) { self.session = session /* make sure we're actually having a serial queue as it's used for synchronization */ self.workQueue = DispatchQueue.init(label: "org.swift.URLSessionTask.WorkQueue", target: session.workQueue) self.taskIdentifier = taskIdentifier self.originalRequest = request self.body = body super.init() if session.configuration.protocolClasses != nil { guard let protocolClasses = session.configuration.protocolClasses else { fatalError() } if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) { guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() } self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil) } else { guard let protocolClasses = URLProtocol.getProtocols() else { fatalError() } if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) { guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() } self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil) } } } else { guard let protocolClasses = URLProtocol.getProtocols() else { fatalError() } if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) { guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError() } self._protocol = urlProtocol.init(task: self, cachedResponse: nil, client: nil) } } } deinit { //TODO: Do we remove the EasyHandle from the session here? This might run on the wrong thread / queue. } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone?) -> Any { return self } /// An identifier for this task, assigned by and unique to the owning session open private(set) var taskIdentifier: Int /// May be nil if this is a stream task /*@NSCopying*/ open private(set) var originalRequest: URLRequest? /// If there's an authentication failure, we'd need to create a new request with the credentials supplied by the user var authRequest: URLRequest? = nil /// Authentication failure count fileprivate var previousFailureCount = 0 fileprivate var protectionSpaces: [URLProtectionSpace] = [] fileprivate var protectionSpacesInited = false /// May differ from originalRequest due to http server redirection /*@NSCopying*/ open internal(set) var currentRequest: URLRequest? { get { return self.syncQ.sync { return self._currentRequest } } set { self.syncQ.sync { self._currentRequest = newValue } } } fileprivate var _currentRequest: URLRequest? = nil /*@NSCopying*/ open internal(set) var response: URLResponse? { get { return self.syncQ.sync { return self._response } } set { self.syncQ.sync { self._response = newValue } } } fileprivate var _response: URLResponse? = nil /* Byte count properties may be zero if no body is expected, * or URLSessionTransferSizeUnknown if it is not possible * to know how many bytes will be transferred. */ /// Number of body bytes already received open internal(set) var countOfBytesReceived: Int64 { get { return self.syncQ.sync { return self._countOfBytesReceived } } set { self.syncQ.sync { self._countOfBytesReceived = newValue } } } fileprivate var _countOfBytesReceived: Int64 = 0 /// Number of body bytes already sent */ open internal(set) var countOfBytesSent: Int64 { get { return self.syncQ.sync { return self._countOfBytesSent } } set { self.syncQ.sync { self._countOfBytesSent = newValue } } } fileprivate var _countOfBytesSent: Int64 = 0 /// Number of body bytes we expect to send, derived from the Content-Length of the HTTP request */ open internal(set) var countOfBytesExpectedToSend: Int64 = 0 /// Number of bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */ open internal(set) var countOfBytesExpectedToReceive: Int64 = 0 /// The taskDescription property is available for the developer to /// provide a descriptive label for the task. open var taskDescription: String? /* -cancel returns immediately, but marks a task as being canceled. * The task will signal -URLSession:task:didCompleteWithError: with an * error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some * cases, the task may signal other work before it acknowledges the * cancelation. -cancel may be sent to a task that has been suspended. */ open func cancel() { workQueue.sync { self._cancel() } } /* * The current state of the task within the session. */ open var state: URLSessionTask.State { get { return self.syncQ.sync { self._state } } set { self.syncQ.sync { self._state = newValue } } } fileprivate var _state: URLSessionTask.State = .suspended /* * The error, if any, delivered via -URLSession:task:didCompleteWithError: * This property will be nil in the event that no error occured. */ /*@NSCopying*/ open internal(set) var error: Error? /// Suspend the task. /// /// Suspending a task will prevent the URLSession from continuing to /// load data. There may still be delegate calls made on behalf of /// this task (for instance, to report data received while suspending) /// but no further transmissions will be made on behalf of the task /// until -resume is sent. The timeout timer associated with the task /// will be disabled while a task is suspended. -suspend and -resume are /// nestable. open func suspend() { // suspend / resume is implemented simply by adding / removing the task's // easy handle fromt he session's multi-handle. // // This might result in slightly different behaviour than the Darwin Foundation // implementation, but it'll be difficult to get complete parity anyhow. // Too many things depend on timeout on the wire etc. // // TODO: It may be worth looking into starting over a task that gets // resumed. The Darwin Foundation documentation states that that's what // it does for anything but download tasks. // We perform the increment and call to `updateTaskState()` // synchronous, to make sure the `state` is updated when this method // returns, but the actual suspend will be done asynchronous to avoid // dead-locks. workQueue.sync { self.suspendCount += 1 guard self.suspendCount < Int.max else { fatalError("Task suspended too many times \(Int.max).") } self.updateTaskState() if self.suspendCount == 1 { self.workQueue.async { self._protocol?.stopLoading() } } } } /// Resume the task. /// /// - SeeAlso: `suspend()` open func resume() { workQueue.sync { self.suspendCount -= 1 guard 0 <= self.suspendCount else { assert(false, "Resuming a task that's not suspended. Calls to resume() / suspend() need to be matched.") return } self.updateTaskState() if self.suspendCount == 0 { self.workQueue.async { if let _protocol = self._protocol { _protocol.startLoading() } else if self.error == nil { var userInfo: [String: Any] = [NSLocalizedDescriptionKey: "unsupported URL"] if let url = self.originalRequest?.url { userInfo[NSURLErrorFailingURLErrorKey] = url userInfo[NSURLErrorFailingURLStringErrorKey] = url.absoluteString } let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorUnsupportedURL, userInfo: userInfo)) self.error = urlError _ProtocolClient().urlProtocol(task: self, didFailWithError: urlError) } } } } } /// The priority of the task. /// /// Sets a scaling factor for the priority of the task. The scaling factor is a /// value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest /// priority and 1.0 is considered the highest. /// /// The priority is a hint and not a hard requirement of task performance. The /// priority of a task may be changed using this API at any time, but not all /// protocols support this; in these cases, the last priority that took effect /// will be used. /// /// If no priority is specified, the task will operate with the default priority /// as defined by the constant URLSessionTask.defaultPriority. Two additional /// priority levels are provided: URLSessionTask.lowPriority and /// URLSessionTask.highPriority, but use is not restricted to these. open var priority: Float { get { return self.workQueue.sync { return self._priority } } set { self.workQueue.sync { self._priority = newValue } } } fileprivate var _priority: Float = URLSessionTask.defaultPriority } internal extension URLSessionTask { func _cancel() { guard self.state == .running || self.state == .suspended else { return } self.state = .canceling self.workQueue.async { let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil)) self.error = urlError self._protocol?.stopLoading() self._protocol?.client?.urlProtocol(self._protocol!, didFailWithError: urlError) } } } extension URLSessionTask { public enum State : Int { /// The task is currently being serviced by the session case running case suspended /// The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message. case canceling /// The task has completed and the session will receive no more delegate notifications case completed } } extension URLSessionTask : ProgressReporting { public var progress: Progress { NSUnimplemented() } } extension URLSessionTask { /// Updates the (public) state based on private / internal state. /// /// - Note: This must be called on the `workQueue`. internal func updateTaskState() { func calculateState() -> URLSessionTask.State { if suspendCount == 0 { return .running } else { return .suspended } } state = calculateState() } } internal extension URLSessionTask { enum _Body { case none case data(DispatchData) /// Body data is read from the given file URL case file(URL) case stream(InputStream) } } internal extension URLSessionTask._Body { enum _Error : Error { case fileForBodyDataNotFound } /// - Returns: The body length, or `nil` for no body (e.g. `GET` request). func getBodyLength() throws -> UInt64? { switch self { case .none: return 0 case .data(let d): return UInt64(d.count) /// Body data is read from the given file URL case .file(let fileURL): guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else { throw _Error.fileForBodyDataNotFound } return s.uint64Value case .stream: return nil } } } fileprivate extension URLSessionTask { class func inputStreamToData(_ inputStream: InputStream, contentLength: UInt) -> Data { var data = Data() let bufferSize = 1024 var avaibleContentLenght = Int(contentLength) let buffer = malloc(bufferSize).assumingMemoryBound(to: UInt8.self) while inputStream.hasBytesAvailable { let readBytes = inputStream.read(buffer, maxLength: bufferSize) if readBytes > 0 && avaibleContentLenght > 0 { data.append(buffer, count: min(avaibleContentLenght, readBytes)) avaibleContentLenght -= readBytes } } free(buffer) return data } class func getContentLengthFromHeader(_ request: URLRequest) -> UInt? { if let headers = request.allHTTPHeaderFields { for (key, val) in headers { if key.lowercased() == "content-length" { return UInt(val) } } } return nil } } fileprivate func errorCode(fileSystemError error: Error) -> Int { func fromCocoaErrorCode(_ code: Int) -> Int { switch code { case CocoaError.fileReadNoSuchFile.rawValue: return NSURLErrorFileDoesNotExist case CocoaError.fileReadNoPermission.rawValue: return NSURLErrorNoPermissionsToReadFile default: return NSURLErrorUnknown } } switch error { case let e as NSError where e.domain == NSCocoaErrorDomain: return fromCocoaErrorCode(e.code) default: return NSURLErrorUnknown } } extension URLSessionTask { /// The default URL session task priority, used implicitly for any task you /// have not prioritized. The floating point value of this constant is 0.5. public static let defaultPriority: Float = 0.5 /// A low URL session task priority, with a floating point value above the /// minimum of 0 and below the default value. public static let lowPriority: Float = 0.25 /// A high URL session task priority, with a floating point value above the /// default value and below the maximum of 1.0. public static let highPriority: Float = 0.75 } /* * An URLSessionDataTask does not provide any additional * functionality over an URLSessionTask and its presence is merely * to provide lexical differentiation from download and upload tasks. */ open class URLSessionDataTask : URLSessionTask { } /* * An URLSessionUploadTask does not currently provide any additional * functionality over an URLSessionDataTask. All delegate messages * that may be sent referencing an URLSessionDataTask equally apply * to URLSessionUploadTasks. */ open class URLSessionUploadTask : URLSessionDataTask { } /* * URLSessionDownloadTask is a task that represents a download to * local storage. */ open class URLSessionDownloadTask : URLSessionTask { internal var fileLength = -1.0 /* Cancel the download (and calls the superclass -cancel). If * conditions will allow for resuming the download in the future, the * callback will be called with an opaque data blob, which may be used * with -downloadTaskWithResumeData: to attempt to resume the download. * If resume data cannot be created, the completion handler will be * called with nil resumeData. */ open func cancel(byProducingResumeData completionHandler: @escaping (Data?) -> Void) { super.cancel() /* * In Objective-C, this method relies on an Apple-maintained XPC process * to manage the bookmarking of partially downloaded data. Therefore, the * original behavior cannot be directly ported, here. * * Instead, we just call the completionHandler directly. */ completionHandler(nil) } } /* * An URLSessionStreamTask provides an interface to perform reads * and writes to a TCP/IP stream created via URLSession. This task * may be explicitly created from an URLSession, or created as a * result of the appropriate disposition response to a * -URLSession:dataTask:didReceiveResponse: delegate message. * * URLSessionStreamTask can be used to perform asynchronous reads * and writes. Reads and writes are enquened and executed serially, * with the completion handler being invoked on the sessions delegate * queuee. If an error occurs, or the task is canceled, all * outstanding read and write calls will have their completion * handlers invoked with an appropriate error. * * It is also possible to create InputStream and OutputStream * instances from an URLSessionTask by sending * -captureStreams to the task. All outstanding read and writess are * completed before the streams are created. Once the streams are * delivered to the session delegate, the task is considered complete * and will receive no more messsages. These streams are * disassociated from the underlying session. */ open class URLSessionStreamTask : URLSessionTask { /* Read minBytes, or at most maxBytes bytes and invoke the completion * handler on the sessions delegate queue with the data or an error. * If an error occurs, any outstanding reads will also fail, and new * read requests will error out immediately. */ open func readData(ofMinLength minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: @escaping (Data?, Bool, Error?) -> Void) { NSUnimplemented() } /* Write the data completely to the underlying socket. If all the * bytes have not been written by the timeout, a timeout error will * occur. Note that invocation of the completion handler does not * guarantee that the remote side has received all the bytes, only * that they have been written to the kernel. */ open func write(_ data: Data, timeout: TimeInterval, completionHandler: @escaping (Error?) -> Void) { NSUnimplemented() } /* -captureStreams completes any already enqueued reads * and writes, and then invokes the * URLSession:streamTask:didBecomeInputStream:outputStream: delegate * message. When that message is received, the task object is * considered completed and will not receive any more delegate * messages. */ open func captureStreams() { NSUnimplemented() } /* Enqueue a request to close the write end of the underlying socket. * All outstanding IO will complete before the write side of the * socket is closed. The server, however, may continue to write bytes * back to the client, so best practice is to continue reading from * the server until you receive EOF. */ open func closeWrite() { NSUnimplemented() } /* Enqueue a request to close the read side of the underlying socket. * All outstanding IO will complete before the read side is closed. * You may continue writing to the server. */ open func closeRead() { NSUnimplemented() } /* * Begin encrypted handshake. The hanshake begins after all pending * IO has completed. TLS authentication callbacks are sent to the * session's -URLSession:task:didReceiveChallenge:completionHandler: */ open func startSecureConnection() { NSUnimplemented() } /* * Cleanly close a secure connection after all pending secure IO has * completed. */ open func stopSecureConnection() { NSUnimplemented() } } /* Key in the userInfo dictionary of an NSError received during a failed download. */ public let URLSessionDownloadTaskResumeData: String = "NSURLSessionDownloadTaskResumeData" extension _ProtocolClient: URLProtocolClient { func urlProtocol(_ protocol: URLProtocol, didReceive response: URLResponse, cacheStoragePolicy policy: URLCache.StoragePolicy) { guard let task = `protocol`.task else { fatalError("Received response, but there's no task.") } task.response = response let session = task.session as! URLSession guard let dataTask = task as? URLSessionDataTask else { return } switch session.behaviour(for: task) { case .taskDelegate(let delegate as URLSessionDataDelegate): session.delegateQueue.addOperation { delegate.urlSession(session, dataTask: dataTask, didReceive: response, completionHandler: { _ in URLSession.printDebug("warning: Ignoring disposition from completion handler.") }) } case .noDelegate, .taskDelegate, .dataCompletionHandler, .downloadCompletionHandler: break } } func createProtectionSpace(_ response: HTTPURLResponse) -> URLProtectionSpace? { let host = response.url?.host ?? "" let port = response.url?.port ?? 80 //we're doing http let _protocol = response.url?.scheme if response.allHeaderFields["WWW-Authenticate"] != nil { let wwwAuthHeaderValue = response.allHeaderFields["WWW-Authenticate"] as! String let authMethod = wwwAuthHeaderValue.components(separatedBy: " ")[0] let realm = String(String(wwwAuthHeaderValue.components(separatedBy: "realm=")[1].dropFirst()).dropLast()) return URLProtectionSpace(host: host, port: port, protocol: _protocol, realm: realm, authenticationMethod: authMethod) } else { return nil } } func urlProtocolDidFinishLoading(_ protocol: URLProtocol) { guard let task = `protocol`.task else { fatalError("task cannot be nil") } guard let session = task.session as? URLSession else { fatalError("session cannot be nil") } guard let response = task.response as? HTTPURLResponse else { assert(false, "No response") return } if response.statusCode == 401, `protocol`.containsTaskDelegate() { // Concat protection space from header with all possibles protection spaces if !task.protectionSpacesInited { // init protection spaces var allPossibleProtectionSpaces = AuthProtectionSpace.createAllPossible(using: response) if let protectionSpaceFromHeader = AuthProtectionSpace.createByHeaders(using: response) { allPossibleProtectionSpaces.insert(protectionSpaceFromHeader, at: 0) } task.protectionSpaces = allPossibleProtectionSpaces task.protectionSpacesInited = true } if let sender = `protocol` as? URLAuthenticationChallengeSender, task.protectionSpaces.isEmpty == false { let protectionSpace = task.protectionSpaces.removeFirst() let authenticationChallenge = URLAuthenticationChallenge(protectionSpace: protectionSpace, proposedCredential: nil, previousFailureCount: task.previousFailureCount, failureResponse: response, error: NSError(domain: NSURLErrorDomain, code: NSURLErrorUserAuthenticationRequired), sender: sender) urlProtocol(`protocol`, didReceive: authenticationChallenge) return } } switch session.behaviour(for: task) { case .taskDelegate(let delegate): if let downloadDelegate = delegate as? URLSessionDownloadDelegate, let downloadTask = task as? URLSessionDownloadTask { session.delegateQueue.addOperation { downloadDelegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: `protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as! URL) } } session.delegateQueue.addOperation { delegate.urlSession(session, task: task, didCompleteWithError: nil) task.state = .completed session.workQueue.async { session.taskRegistry.remove(task) } } case .noDelegate: task.state = .completed session.taskRegistry.remove(task) case .dataCompletionHandler(let completion): session.delegateQueue.addOperation { completion(`protocol`.properties[URLProtocol._PropertyKey.responseData] as? Data ?? Data(), task.response, nil) task.state = .completed session.workQueue.async { session.taskRegistry.remove(task) } } case .downloadCompletionHandler(let completion): session.delegateQueue.addOperation { completion(`protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as? URL, task.response, nil) task.state = .completed session.workQueue.async { session.taskRegistry.remove(task) } } } task._protocol = nil } func urlProtocol(_ protocol: URLProtocol, didCancel challenge: URLAuthenticationChallenge) { NSUnimplemented() } func urlProtocol(_ protocol: URLProtocol, didReceive challenge: URLAuthenticationChallenge) { guard let task = `protocol`.task else { fatalError("task cannot be nil") } guard let session = task.session as? URLSession else { fatalError("session need to be an instance of URLSession") } switch session.behaviour(for: task) { case .taskDelegate(let delegate): session.delegateQueue.addOperation { let authScheme = challenge.protectionSpace.authenticationMethod delegate.urlSession(session, task: task, didReceive: challenge) { disposition, credential in switch disposition { case .useCredential: task.suspend() // Read props from protocol var protocolCredentials: URLCredential? var protocolTrust: Bool? if let taskProtocol = task._protocol as? _HTTPURLProtocol { protocolCredentials = taskProtocol.urlCredentials protocolTrust = taskProtocol.trustAllCertificates } // Read from completionHandler // URLCredentials holds credentials OR trustAllCertificates if let credential = credential { if let trust = credential._trustAllCertificated { // Trust field is set task.previousFailureCount = 0 protocolTrust = trust } else { protocolCredentials = credential } } task._protocol = _HTTPURLProtocol(task: task, cachedResponse: nil, client: nil) if let credential = protocolCredentials { task.setCredentials(credential) } if let trustAllCertificate = protocolTrust { task.setTrustAllCertificates(trustAllCertificate) } if authScheme != NSURLAuthenticationMethodServerTrust && !task.setAuthMethod(authScheme) { NSLog("\(authScheme) is not supported") } task.resume() case .performDefaultHandling: task.protectionSpaces = [] session.workQueue.async { let error = challenge.error ?? NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown) self.urlProtocol(task: task, didFailWithError: error) } case .rejectProtectionSpace: session.workQueue.async { task._protocol?.client?.urlProtocolDidFinishLoading(`protocol`) } case .cancelAuthenticationChallenge: task.protectionSpaces = [] task.cancel() } } } default: return } } func urlProtocol(_ protocol: URLProtocol, didLoad data: Data) { `protocol`.properties[.responseData] = data guard let task = `protocol`.task else { fatalError("task cannot be nil") } guard let session = task.session as? URLSession else { fatalError("session cannot be nil") } switch session.behaviour(for: task) { case .taskDelegate(let delegate): let dataDelegate = delegate as? URLSessionDataDelegate let dataTask = task as? URLSessionDataTask session.delegateQueue.addOperation { dataDelegate?.urlSession(session, dataTask: dataTask!, didReceive: data) } default: return } } func urlProtocol(_ protocol: URLProtocol, didFailWithError error: Error) { guard let task = `protocol`.task else { fatalError() } let certificateErrors = [NSURLErrorServerCertificateUntrusted, NSURLErrorServerCertificateWrongHost] if certificateErrors.contains(error._code) && `protocol`.containsTaskDelegate() { let protectionSpace = URLProtectionSpace(host: "", port: 443, protocol: "https", realm: "", authenticationMethod: NSURLAuthenticationMethodServerTrust) if let sender = `protocol` as? URLAuthenticationChallengeSender { let authenticationChallenge = URLAuthenticationChallenge(protectionSpace: protectionSpace, proposedCredential: nil, previousFailureCount: task.previousFailureCount, failureResponse: nil, error: error, sender: sender) task.previousFailureCount += 1 urlProtocol(`protocol`, didReceive: authenticationChallenge) return } } urlProtocol(task: task, didFailWithError: error) } func urlProtocol(task: URLSessionTask, didFailWithError error: Error) { guard let session = task.session as? URLSession else { fatalError() } switch session.behaviour(for: task) { case .taskDelegate(let delegate): session.delegateQueue.addOperation { delegate.urlSession(session, task: task, didCompleteWithError: error as Error) task.state = .completed session.workQueue.async { session.taskRegistry.remove(task) } } case .noDelegate: task.state = .completed session.taskRegistry.remove(task) case .dataCompletionHandler(let completion): session.delegateQueue.addOperation { completion(nil, nil, error) task.state = .completed session.workQueue.async { session.taskRegistry.remove(task) } } case .downloadCompletionHandler(let completion): session.delegateQueue.addOperation { completion(nil, nil, error) task.state = .completed session.workQueue.async { session.taskRegistry.remove(task) } } } task._protocol = nil } func urlProtocol(_ protocol: URLProtocol, cachedResponseIsValid cachedResponse: CachedURLResponse) { NSUnimplemented() } func urlProtocol(_ protocol: URLProtocol, wasRedirectedTo request: URLRequest, redirectResponse: URLResponse) { NSUnimplemented() } } extension URLSessionTask { typealias _AuthHandler = ((URLSessionTask, URLSession.AuthChallengeDisposition, URLCredential?) -> ()) static func authHandler(for authScheme: String) -> _AuthHandler? { let handlers: [String : _AuthHandler] = [ "Basic" : basicAuth, "Digest": digestAuth ] return handlers[authScheme] } //Authentication handlers static func basicAuth(_ task: URLSessionTask, _ disposition: URLSession.AuthChallengeDisposition, _ credential: URLCredential?) { //TODO: Handle disposition. For now, we default to .useCredential let user = credential?.user ?? "" let password = credential?.password ?? "" let encodedString = "\(user):\(password)".data(using: .utf8)?.base64EncodedString() task.authRequest = task.originalRequest task.authRequest?.setValue("Basic \(encodedString!)", forHTTPHeaderField: "Authorization") } static func digestAuth(_ task: URLSessionTask, _ disposition: URLSession.AuthChallengeDisposition, _ credential: URLCredential?) { NSUnimplemented() } } private extension URLSessionTask { func setCredentials(_ credential: URLCredential) { guard let httpUrlProtocol = _protocol as? _HTTPURLProtocol else { fatalError("protocol need to be an instance of _HTTPURLProtocol") } httpUrlProtocol.set(credential: credential) } func setAuthMethod(_ authMethod: String) -> Bool { guard let httpUrlProtocol = _protocol as? _HTTPURLProtocol else { fatalError("protocol need to be an instance of _HTTPURLProtocol") } let status = httpUrlProtocol.set(authMethod: authMethod) return status } func setTrustAllCertificates(_ trustAll: Bool) { guard let httpUrlProtocol = _protocol as? _HTTPURLProtocol else { fatalError("protocol need to be an instance of _HTTPURLProtocol") } httpUrlProtocol.set(trustAllCertificates: trustAll) } } fileprivate extension URLProtocol { func containsTaskDelegate() -> Bool { guard let task = self.task else { return false } guard let session = task.session as? URLSession else { return false } switch session.behaviour(for: task) { case .taskDelegate(_): return true default: return false } } } extension URLProtocol { enum _PropertyKey: String { case responseData case temporaryFileURL } }
41.738428
182
0.62499
896f2a6b5f4fdebde19e77158e38946a9ce3a01d
2,715
// RUN: %target-swift-frontend -typecheck -verify -dump-ast -enable-resilience %s 2>&1 | %FileCheck --check-prefix=RESILIENCE-ON %s // RUN: %target-swift-frontend -typecheck -verify -dump-ast -enable-resilience -enable-testing %s 2>&1 | %FileCheck --check-prefix=RESILIENCE-ON %s // RUN: not %target-swift-frontend -typecheck -dump-ast %s 2>&1 | %FileCheck --check-prefix=RESILIENCE-OFF %s // RUN: not %target-swift-frontend -typecheck -dump-ast %s -enable-testing 2>&1 | %FileCheck --check-prefix=RESILIENCE-OFF %s // // Public types with @_fixed_layout are always fixed layout // // RESILIENCE-ON: struct_decl "Point" interface type='Point.Type' access=public non-resilient // RESILIENCE-OFF: struct_decl "Point" interface type='Point.Type' access=public non-resilient @_fixed_layout public struct Point { let x, y: Int } // RESILIENCE-ON: enum_decl "ChooseYourOwnAdventure" interface type='ChooseYourOwnAdventure.Type' access=public non-resilient // RESILIENCE-OFF: enum_decl "ChooseYourOwnAdventure" interface type='ChooseYourOwnAdventure.Type' access=public non-resilient @_frozen public enum ChooseYourOwnAdventure { case JumpIntoRabbitHole case EatMushroom } // // Public types are resilient when -enable-resilience is on // // RESILIENCE-ON: struct_decl "Size" interface type='Size.Type' access=public resilient // RESILIENCE-OFF: struct_decl "Size" interface type='Size.Type' access=public non-resilient public struct Size { let w, h: Int } // RESILIENCE-ON: enum_decl "TaxCredit" interface type='TaxCredit.Type' access=public resilient // RESILIENCE-OFF: enum_decl "TaxCredit" interface type='TaxCredit.Type' access=public non-resilient public enum TaxCredit { case EarnedIncome case MortgageDeduction } // // Internal types are always fixed layout // // RESILIENCE-ON: struct_decl "Rectangle" interface type='Rectangle.Type' access=internal non-resilient // RESILIENCE-OFF: struct_decl "Rectangle" interface type='Rectangle.Type' access=internal non-resilient struct Rectangle { let topLeft: Point let bottomRight: Size } // // Diagnostics // @_fixed_layout struct InternalStruct { // expected-error@-1 {{'@_fixed_layout' attribute can only be applied to '@_versioned' or public declarations, but 'InternalStruct' is internal}} @_fixed_layout public struct NestedStruct {} } @_fixed_layout fileprivate struct FileprivateStruct {} // expected-error@-1 {{'@_fixed_layout' attribute can only be applied to '@_versioned' or public declarations, but 'FileprivateStruct' is fileprivate}} @_fixed_layout private struct PrivateStruct {} // expected-error@-1 {{'@_fixed_layout' attribute can only be applied to '@_versioned' or public declarations, but 'PrivateStruct' is private}}
41.136364
151
0.765746
21d848020adb98738853b5c81cb8db9cc6885f07
530
import Foundation import SwiftClient /// AuthenticationError error. open class AuthenticationError: UpholdClientError { /** Constructor. - parameter code: The HTTP status code. - parameter message: The error message being shown to the user. - parameter response: The HTTP response. */ public init(code: Int, message: String, response: Response) { let info: [String: String] = ["Authentication error": message] super.init(code: code, info: info, response: response) } }
25.238095
70
0.673585
71a861efa4ab13027b7b408076cb831c0afe7197
6,269
// // Copyright © 2017 Jan Gorman. All rights reserved. // import UIKit public enum CacheType { case none, memory, disk } /// The class responsible for caching images. Images will be cached both in memory and on disk. public final class Cache { private static let prefix = "com.schnaub.Cache." /// The default `Cache` singleton public static let `default` = Cache(name: "default") public let cachePath: String private let memory = NSCache<NSString, AnyObject>() private let fileManager = FileManager.default private let diskQueue: DispatchQueue /// The max age to cache images on disk in seconds. Defaults to 7 days. public var maxCacheAgeSeconds: TimeInterval = 60 * 60 * 24 * 7 /// Construct a new instance of the cache /// /// - Parameter name: The name of the cache. Used to construct a unique path on disk to store images in public init(name: String) { let cacheName = Cache.prefix + name memory.name = cacheName diskQueue = DispatchQueue(label: cacheName, qos: .background) let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! cachePath = (path as NSString).appendingPathComponent(name) NotificationCenter.default.addObserver(self, selector: #selector(clearMemory), name: .UIApplicationDidReceiveMemoryWarning, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(cleanDisk), name: .UIApplicationWillTerminate, object: nil) } /// Stores an image in the cache. Images will be added to both memory and disk. /// /// - Parameters /// - image: The image to cache /// - key: The unique identifier of the image /// - transformerId: An optional transformer ID appended to the key to uniquely identify the image /// - completion: An optional closure called once the image has been persisted to disk. Runs on the main queue. public func store(_ image: UIImage, data: Data? = nil, forKey key: String, transformerId: String? = nil, completion: (() -> Void)? = nil) { let cacheKey = makeCacheKey(key, identifier: transformerId) memory.setObject(image, forKey: cacheKey as NSString) diskQueue.async { defer { DispatchQueue.main.async { completion?() } } if let data = data ?? UIImagePNGRepresentation(image) { self.storeDataToDisk(data, key: cacheKey) } } } private func storeToMemory(_ image: UIImage, forKey key: String, transformerId: String? = nil) { let cacheKey = makeCacheKey(key, identifier: transformerId) memory.setObject(image, forKey: cacheKey as NSString) } private func makeCacheKey(_ key: String, identifier: String?) -> String { let fileSafeKey = key.replacingOccurrences(of: "/", with: "-") guard let identifier = identifier, !identifier.isEmpty else { return fileSafeKey } return fileSafeKey + "-" + identifier } private func storeDataToDisk(_ data: Data, key: String) { createCacheDirectoryIfNeeded() let path = (cachePath as NSString).appendingPathComponent(key) fileManager.createFile(atPath: path, contents: data, attributes: nil) } private func createCacheDirectoryIfNeeded() { guard !fileManager.fileExists(atPath: cachePath) else { return } _ = try? fileManager.createDirectory(atPath: cachePath, withIntermediateDirectories: true, attributes: nil) } /// Retrieve an image from cache. Will look in both memory and on disk. When the image is only available on disk /// it will be stored again in memory for faster access. /// /// - Parameters /// - key: The unique identifier of the image /// - transformerId: An optional transformer ID appended to the key to uniquely identify the image /// - completion: The completion called once the image has been retrieved from the cache public func retrieveImage(forKey key: String, transformerId: String? = nil, completion: (UIImage?, CacheType) -> Void) { let cacheKey = makeCacheKey(key, identifier: transformerId) if let image = memory.object(forKey: cacheKey as NSString) as? UIImage { completion(image, .memory) return } if let image = retrieveImageFromDisk(forKey: cacheKey) { storeToMemory(image, forKey: cacheKey, transformerId: transformerId) completion(image, .disk) return } completion(nil, .none) } private func retrieveImageFromDisk(forKey key: String) -> UIImage? { let url = URL(fileURLWithPath: cachePath).appendingPathComponent(key) guard let data = try? Data(contentsOf: url), let image = UIImage(data: data) else { return nil } return image } @objc public func clearMemory() { memory.removeAllObjects() } /// Clear the disk cache. /// /// - Parameter completion: An optional closure called once the cache has been cleared. Runs on the main queue. public func clearDisk(_ completion: (() -> Void)? = nil) { diskQueue.async { defer { DispatchQueue.main.async { completion?() } } _ = try? self.fileManager.removeItem(atPath: self.cachePath) self.createCacheDirectoryIfNeeded() } } @objc private func cleanDisk() { diskQueue.async { for url in self.expiredFileUrls() { _ = try? self.fileManager.removeItem(at: url) } } } public func expiredFileUrls() -> [URL] { let cacheDirectory = URL(fileURLWithPath: cachePath) let keys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey] let contents = try? fileManager.contentsOfDirectory(at: cacheDirectory, includingPropertiesForKeys: Array(keys), options: .skipsHiddenFiles) guard let files = contents else { return [] } let expirationDate = Date(timeIntervalSinceNow: -maxCacheAgeSeconds) let expiredFileUrls = files.filter { url in let resource = try? url.resourceValues(forKeys: keys) let isDirectory = resource?.isDirectory guard let lastAccessDate = resource?.contentAccessDate else { return true } return isDirectory == false && lastAccessDate < expirationDate } return expiredFileUrls } }
37.993939
141
0.68097
fb39d6542ea91915d986cfb7f936a35b9fa98a54
432
// // level6.swift // baekjun-star // // Created by SwiftMan on 2021/09/06. // import Foundation /* 첫째 줄에는 별 2×N-1개, 둘째 줄에는 별 2×N-3개, ..., N번째 줄에는 별 1개를 찍는 문제 별은 가운데를 기준으로 대칭이어야 한다. ********* ******* ***** *** * */ func level6() { let num = Int(readLine()!)! var j = num * 2 - 1 for i in 0 ..< num { print(String(repeating: " ", count: i) + String(repeating: "*", count: j)) j = j - 2 } }
15.428571
78
0.490741
75d52e812f8b1a7ee5b1f0f3efbeda4fa37b5288
581
// // ViewPrintable.swift // UnitHelper // // Created by tsuf on 2019/9/17. // Copyright © 2019 upmer. All rights reserved. // import UIKit protocol ViewPrintable { func treeDescription(_ level: Int) -> String } extension UIView: ViewPrintable { func treeDescription(_ level: Int = 0) -> String { var res = "" var indentation = "" for _ in 0..<level { indentation += " →" } res += indentation res += self.description for subview in subviews { res += "\n" res += subview.treeDescription(level + 1) } return res } }
18.741935
52
0.607573
69ac63e2684fafab14b5d6c2a7cd7b531b7ff558
1,976
// // MaskViewVC.swift // UIScrollViewDemo // // Created by xiAo_Ju on 2018/10/27. // Copyright © 2018 伯驹 黄. All rights reserved. // import UIKit class MaskViewVC: UIViewController { private lazy var maskView: MaskView = { var rect = self.view.bounds rect.size.height = 400 let maskView = MaskView(frame: rect) maskView.maskColor = UIColor(white: 0, alpha: 0.6) return maskView }() private lazy var maskView2: MaskView = { let maskView2 = MaskView(frame: CGRect(x: 100, y: 500, width: 52, height: 52)) maskView2.maskColor = UIColor.red return maskView2 }() private lazy var shapeMaskLayer: ShapeMaskLayer = { let shapeMaskLayer = ShapeMaskLayer(rect: CGRect(x: 200, y: 500, width: 52, height: 52)) shapeMaskLayer.maskColor = UIColor.green return shapeMaskLayer }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white maskView.addTransparentRect(CGRect(x: 20, y: 100, width: 100, height: 100)) maskView.addTransparentRoundedRect(CGRect(x: 20, y: 220, width: 100, height: 100), cornerRadius: 50) maskView.addTransparentRoundedRect(CGRect(x: 140, y: 100, width: 100, height: 100), byRoundingCorners: [.topLeft, .bottomLeft], cornerRadii: CGSize(width: 20, height: 20)) maskView.addTransparentOvalRect(CGRect(x: 140, y: 220, width: 150, height: 100)) view.addSubview(maskView) maskView2.addTransparentRoundedRect(CGRect(x: 2, y: 2, width: 48, height: 48), byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize(width: 2, height: 2)) view.addSubview(maskView2) shapeMaskLayer.addTransparentRoundedRect(CGRect(x: 2, y: 2, width: 48, height: 48), byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize(width: 2, height: 2)) view.layer.addSublayer(shapeMaskLayer) } }
38.745098
179
0.652328
75c63e2f672ee92a66e0d1a5ad47e8301dfbac06
143
import Foundation extension Date { func toString() -> String { return CoreLogger.dateFormatter.string(from: self as Date) } }
17.875
66
0.671329
22b9cd50756ab124eca7f5f49ece8ef41418b694
1,105
// // PBHexTest.swift // PBKit // // Created by pebble8888 on 2017/06/10. // Copyright © 2017年 pebble8888. All rights reserved. // import XCTest import PBKit class PBHexTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testData() { let s = "abc" guard let d = s.data(using: .utf8) else { return XCTFail() } XCTAssertEqual(d.hexDescription(), "616263") } func test2() { let a:UInt8 = 10 XCTAssertEqual(a.hexDescription(), "0a") let b: Int32 = 10 XCTAssertEqual(b.hexDescription(), "0000000a") let v: [UInt8] = [10, 11, 12] XCTAssertEqual(v.hexDescription(), "0a0b0c") let data: Data = Data(bytes: [11, 12, 13]) XCTAssertEqual(data.hexDescription(), "0b0c0d") } }
25.113636
111
0.6
cc907776999bd98d9338e39bec330de820096718
600
// // CityNameView.swift // WeatherApp // // Created by Gourav on 14/02/21. // import SwiftUI struct CityNameView: View { var city:String var date:String var body: some View { HStack{ VStack(alignment: .center, spacing: 10, content: { Text(city) .font(.title) .bold() Text(date) }) .foregroundColor(.white) } } } struct CityNameView_Previews: PreviewProvider { static var previews: some View { CityNameView(city: "dfd", date: "dfdf") } }
19.354839
62
0.52
f7bbb18cb24005ed1e8721ddcb5d902f46037148
1,565
// // TreeHeightofaBinaryTree.swift // HackerRank // // Created by Fabrizio Duroni on 13/12/2016. // // https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree import Foundation class Node { var data: Int var left: Node? var right: Node? init(d : Int) { data = d } } class Tree { func insert(root: Node?, data: Int) -> Node? { if root == nil { return Node(d: data) } if data <= (root?.data)! { root?.left = insert(root: root?.left, data: data) } else { root?.right = insert(root: root?.right, data: data) } return root } /*! I just noted that i already solved this challenge in 30 days of code, but here I created a more elegant solution :). - param root: root node. - return the tree height. */ func getHeight(root: Node?) -> Int { var countLeft = 0 var countRight = 0 if let left = root?.left { countLeft = 1 + getHeight(root: left) } if let right = root?.right { countRight = 1 + getHeight(root: right) } return countLeft > countRight ? countLeft : countRight } } var root: Node? var tree = Tree() var t = Int(readLine()!)! while t > 0 { root = tree.insert(root: root, data: Int(readLine()!)!) t = t - 1 } print(tree.getHeight(root: root))
19.085366
70
0.497764
72a3a7de5bef333b4c358dbb07e55da6b9b70ccb
7,111
// // ViewController.swift // WebRTC // // Created by Stasel on 20/05/2018. // Copyright © 2018 Stasel. All rights reserved. // import UIKit import AVFoundation import WebRTC class MainViewController: UIViewController { deinit { print("MainViewController 🔥") } private let signalClient = SignalingClient.build() private let webRTCClient = WebRTCClient.build() private lazy var videoViewController = VideoViewController(webRTCClient: self.webRTCClient) @IBOutlet private weak var speakerButton: UIButton? @IBOutlet private weak var signalingStatusLabel: UILabel? @IBOutlet private weak var localSdpStatusLabel: UILabel? @IBOutlet private weak var localCandidatesLabel: UILabel? @IBOutlet private weak var remoteSdpStatusLabel: UILabel? @IBOutlet private weak var remoteCandidatesLabel: UILabel? @IBOutlet private weak var muteButton: UIButton? @IBOutlet private weak var webRTCStatusLabel: UILabel? private var signalingConnected: Bool = false { didSet { DispatchQueue.main.async { if self.signalingConnected { self.signalingStatusLabel?.text = "Connected" self.signalingStatusLabel?.textColor = UIColor.green } else { self.signalingStatusLabel?.text = "Not connected" self.signalingStatusLabel?.textColor = UIColor.red } } } } private var hasLocalSdp: Bool = false { didSet { DispatchQueue.main.async { self.localSdpStatusLabel?.text = self.hasLocalSdp ? "✅" : "❌" } } } private var localCandidateCount: Int = 0 { didSet { DispatchQueue.main.async { self.localCandidatesLabel?.text = "\(self.localCandidateCount)" } } } private var hasRemoteSdp: Bool = false { didSet { DispatchQueue.main.async { self.remoteSdpStatusLabel?.text = self.hasRemoteSdp ? "✅" : "❌" } } } private var remoteCandidateCount: Int = 0 { didSet { DispatchQueue.main.async { self.remoteCandidatesLabel?.text = "\(self.remoteCandidateCount)" } } } private var speakerOn: Bool = false { didSet { let title = "Speaker: \(self.speakerOn ? "On" : "Off" )" self.speakerButton?.setTitle(title, for: .normal) } } private var mute: Bool = false { didSet { let title = "Mute: \(self.mute ? "on" : "off")" self.muteButton?.setTitle(title, for: .normal) } } private var remoteCandidates: [RTCIceCandidate] = [] { didSet { print(remoteCandidates) } } init() { super.init(nibName: String(describing: MainViewController.self), bundle: Bundle.main) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "WebRTC Demo" self.signalingConnected = false self.hasLocalSdp = false self.hasRemoteSdp = false self.localCandidateCount = 0 self.remoteCandidateCount = 0 self.speakerOn = false self.webRTCStatusLabel?.text = "New" self.webRTCClient.delegate = self self.signalClient.delegate = self self.signalClient.connect() } override func willMove(toParent parent: UIViewController?) { if parent == nil { self.signalClient.disconnect() } } @IBAction private func offerDidTap(_ sender: UIButton) { self.webRTCClient.offer { (sdp) in self.hasLocalSdp = true self.signalClient.send(sdp: sdp) } } @IBAction private func answerDidTap(_ sender: UIButton) { if webRTCStatusLabel?.textColor == .green { self.webRTCClient.disconnect() } else { self.webRTCClient.answer { (localSdp) in self.hasLocalSdp = true self.signalClient.send(sdp: localSdp) } } } @IBAction private func speakerDidTap(_ sender: UIButton) { if self.speakerOn { self.webRTCClient.speakerOff() } else { self.webRTCClient.speakerOn() } self.speakerOn = !self.speakerOn } @IBAction private func videoDidTap(_ sender: UIButton) { self.present(videoViewController, animated: true, completion: nil) } @IBAction private func muteDidTap(_ sender: UIButton) { self.mute = !self.mute if self.mute { self.webRTCClient.muteAudio() } else { self.webRTCClient.unmuteAudio() } print(remoteCandidates) } @IBAction func sendDataDidTap(_ sender: UIButton) { signalClient.test() let alert = UIAlertController(title: "Send a message to the other peer", message: "This will be transferred over WebRTC data channel", preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "Message to send" } alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Send", style: .default, handler: { [weak self, unowned alert] _ in guard let dataToSend = alert.textFields?.first?.text?.data(using: .utf8) else { return } self?.webRTCClient.sendData(dataToSend) })) self.present(alert, animated: true, completion: nil) } } extension MainViewController: SignalClientDelegate { func signalClientDidConnect(_ signalClient: SignalingClient) { self.signalingConnected = true } func signalClientDidDisconnect(_ signalClient: SignalingClient) { self.signalingConnected = false } func signalClient(_ signalClient: SignalingClient, didReceiveRemoteSdp sdp: RTCSessionDescription) { print("Received remote sdp") self.webRTCClient.set(remoteSdp: sdp) { (error) in self.hasRemoteSdp = true } } func signalClient(_ signalClient: SignalingClient, didReceiveCandidate candidate: RTCIceCandidate) { self.webRTCClient.set(remoteCandidate: candidate) { error in // if !self.remoteCandidates.contains(candidate) { // self.remoteCandidates.append(candidate) // } print("Received remote candidate") self.remoteCandidateCount += 1 } } } extension MainViewController: WebRTCClientDelegate { func webRTCClient(_ client: WebRTCClient, didDiscoverLocalCandidate candidate: RTCIceCandidate) { print("discovered local candidate") if !self.remoteCandidates.contains(candidate) { self.remoteCandidates.append(candidate) } self.localCandidateCount += 1 self.signalClient.send(candidate: candidate) } func webRTCClient(_ client: WebRTCClient, didChangeConnectionState state: RTCIceConnectionState) { let textColor: UIColor switch state { case .connected, .completed: textColor = .green case .disconnected: textColor = .orange case .failed, .closed: textColor = .red case .new, .checking, .count: textColor = .black @unknown default: textColor = .black } DispatchQueue.main.async { self.webRTCStatusLabel?.text = state.description.capitalized self.webRTCStatusLabel?.textColor = textColor } } func webRTCClient(_ client: WebRTCClient, didReceiveData data: Data) { DispatchQueue.main.async { let message = String(data: data, encoding: .utf8) ?? "(Binary: \(data.count) bytes)" let alert = UIAlertController(title: "Message from WebRTC", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } }
27.35
106
0.715089
610b24ab7e23f99131765e6efc5b494a67dbb026
3,315
// // SceneDelegate.swift // Bookworm10 // // Created by Viettasc on 2/1/20. // Copyright © 2020 Viettasc. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Get the managed object context from the shared persistent container. let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath. // Add `@Environment(\.managedObjectContext)` in the views that will need the context. let contentView = ContentView().environment(\.managedObjectContext, context) // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
46.041667
147
0.714329
fb4b00f6fc516d215dc4019c84e1f856656a84a9
19,665
// // Extensions.swift // MozoSDK // // Created by Hoang Nguyen on 8/28/18. // Copyright © 2018 Hoang Nguyen. All rights reserved. // import Foundation import UIKit public extension Bool { var toString: String { let value = self return "\(value)" } } public extension String { func asMozoImage() -> UIImage? { return UIImage(named: self, in: BundleManager.mozoBundle(), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) } func isValidReceiveFormat() -> Bool{ let regex = try? NSRegularExpression(pattern: "^[a-zA-Z]+:[a-zA-Z0-9]+\\?[a-zA-Z]+=[0-9.]*$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.count)) != nil } func isValidDecimalFormat() -> Bool{ let text = self.toTextNumberWithoutGrouping() return Float(text) != nil } func isValidDecimalMinValue(decimal: Int) -> Bool { let divisor = pow(10.0, Double(decimal)) return Float(self)! >= Float(1 / divisor) } func isValidName() -> Bool { let regex = try? NSRegularExpression(pattern: "^[a-zA-Z0-9_-]*$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.count)) != nil } func isValidEmail() -> Bool { // Old regex: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" // The new regex follow RFC 5322 standard let regex = try? NSRegularExpression(pattern: "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" + "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" + "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" + "z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" + "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" + "9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" + "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.count)) != nil } func isValidPhoneNumber() -> Bool { let regex = try? NSRegularExpression(pattern: "^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\\s\\./0-9]*$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.count)) != nil } var toBool: Bool? { let trueValues = ["true", "yes", "1"] let falseValues = ["false", "no", "0"] let lowerSelf = self.lowercased() if trueValues.contains(lowerSelf) { return true } else if falseValues.contains(lowerSelf) { return false } else { return nil } } func replace(_ originalString:String, withString newString:String) -> String { let replaced = self.replacingOccurrences(of: originalString, with: newString) return replaced } func capitalizingFirstLetter() -> String { return prefix(1).uppercased() + dropFirst() } func hasPrefix(_ prefix: String, caseSensitive: Bool) -> Bool { if !caseSensitive { return hasPrefix(prefix) } return self.lowercased().hasPrefix(prefix.lowercased()) } func censoredMiddle() -> String { let prefix = self[0..<3] let middle = "********" let end = self[count - 3..<count] return "\(prefix)\(middle)\(end)" } func toDoubleValue() -> Double { // FIX ISSUE: [MOZO-254] Round Issue in swift return NSDecimalNumber(string: self).doubleValue + (1 / pow(10, 15)) } func toTextNumberWithoutGrouping() -> String { let decimalSeparator = NSLocale.current.decimalSeparator ?? "." let groupingSeparator = NSLocale.current.groupingSeparator ?? "," return self.replace(groupingSeparator, withString: "").replace(decimalSeparator, withString: ".") } func hasValidSchemeForQRCode() -> Bool { return hasPrefix(AppType.Retailer.scheme) || hasPrefix(AppType.Shopper.scheme) } var isMozoErrorWithContact: Bool { return contains(" (email + phone)") || contains(" (phone + email)") || contains(" (이메일 + 전화)") || contains(" (전화 + 이메일)") } private var convertHtmlToNSAttributedString: NSAttributedString? { guard let data = data(using: .utf8) else { return nil } do { return try NSAttributedString(data: data,options: [.documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) } catch { print(error.localizedDescription) return nil } } func convertHtmlToAttributedStringWithCSS(font: UIFont? , csscolor: String , lineheight: Int, csstextalign: String) -> NSAttributedString? { guard let font = font else { return convertHtmlToNSAttributedString } let modifiedString = "<style>body{font-family: '\(font.fontName)'; font-size:\(font.pointSize)px; color: \(csscolor); line-height: \(lineheight)px; text-align: \(csstextalign); }</style>\(self)"; guard let data = modifiedString.data(using: .utf8) else { return nil } do { return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) } catch { print(error) return nil } } func log() { if MozoSDK.network() != .MainNet { print("[Mozo] \(self)") } } func split(usingRegex pattern: String) -> [String] { //### Crashes when you pass invalid `pattern` let regex = try! NSRegularExpression(pattern: pattern) let matches = regex.matches(in: self, range: NSRange(0..<utf16.count)) let ranges = [startIndex..<startIndex] + matches.map{Range($0.range, in: self)!} + [endIndex..<endIndex] return (0...matches.count).map {String(self[ranges[$0].upperBound..<ranges[$0+1].lowerBound])} } func summary() -> String { let result = self.split(usingRegex: "\\.|\r\n|\n") return (result.first ?? self) + ((result.count > 1 && !result[1].isEmpty) ? "…" : "") } } internal extension String { subscript (bounds: CountableClosedRange<Int>) -> String { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(startIndex, offsetBy: bounds.upperBound) return String(self[start...end]) } subscript (bounds: CountableRange<Int>) -> String { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(startIndex, offsetBy: bounds.upperBound) return String(self[start..<end]) } var hasOnlyNewlineSymbols: Bool { return trimmingCharacters(in: CharacterSet.newlines).isEmpty } } public extension Data { var deviceToken: String { return self.reduce("", {$0 + String(format: "%02X", $1)}) } } public extension UIViewController { func isModal() -> Bool { if let navigationController = self.navigationController{ if navigationController.viewControllers.first != self{ return false } } if self.presentingViewController != nil { return true } if self.navigationController?.presentingViewController?.presentedViewController == self.navigationController { return true } if self.tabBarController?.presentingViewController is UITabBarController { return true } return false } } public extension UIColor { convenience init(hexString: String) { let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let a, r, g, b: UInt32 switch hex.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (255, 0, 0, 0) } self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } } public extension UIView { func roundedAvatar() { roundedCircle() layer.borderWidth = 1 layer.borderColor = UIColor(hexString: "cacaca").cgColor } func roundCorners(cornerRadius: CGFloat = 0.02, borderColor: UIColor, borderWidth: CGFloat) { layer.cornerRadius = cornerRadius * bounds.size.width layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor clipsToBounds = true } func roundedCircle() { layer.cornerRadius = bounds.height / 2 clipsToBounds = true } func roundCornersBezier(frame: CGRect, corners: UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: frame, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath layer.mask = mask } func dropShadow(scale: Bool = true, color: UIColor = UIColor.black, isOnlyBottom: Bool = false) { layer.masksToBounds = false layer.shadowColor = color.cgColor layer.shadowOpacity = 0.5 layer.shadowOffset = isOnlyBottom ? CGSize(width: 0.0, height: 3.0) : CGSize.zero layer.shadowRadius = isOnlyBottom ? 1.5 : 3 layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath layer.shouldRasterize = true layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } func addGradientLayer(colors: [CGColor], locations: [NSNumber]? = nil, frame: CGRect) { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = frame gradient.colors = colors gradient.locations = locations layer.sublayers?.forEach { $0.removeFromSuperlayer() } layer.insertSublayer(gradient, at: 0) } } public extension Decimal { var toDouble:Double { return NSDecimalNumber(decimal:self).doubleValue } var significantFractionalDecimalDigits: Int { return max(-exponent, 0) } } public extension UIWindow { var visibleViewController: UIViewController? { return UIWindow.getVisibleViewControllerFrom(self.rootViewController) } static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? { if let nc = vc as? UINavigationController { if let visibleViewController = nc.visibleViewController { return UIWindow.getVisibleViewControllerFrom(visibleViewController) } if let lastViewController = nc.viewControllers.last { return UIWindow.getVisibleViewControllerFrom(lastViewController) } return vc } else if let tc = vc as? UITabBarController { return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController) } else { if let pvc = vc?.presentedViewController { return UIWindow.getVisibleViewControllerFrom(pvc) } else { return vc } } } } public extension UINavigationController { var rootViewController : UIViewController? { return self.viewControllers.first } } public extension Array { //MARK: - using this method to avoid out of index func getElement(_ index: Int) -> Element? { return (0 <= index && index < self.count ? self[index] : nil) } } internal extension Int { func times(f: () -> ()) { if self > 0 { for _ in 0..<self { f() } } } func times( f: @autoclosure () -> ()) { if self > 0 { for _ in 0..<self { f() } } } } public extension Int { func addCommas() -> String { let number = NSNumber(value: self) return number.addCommas() } } public extension Int64 { func addCommas() -> String { let number = NSNumber(value: self) return number.addCommas() } } public extension Double { func convertTokenValue(decimal: Int) -> NSNumber{ let retValue = NSNumber(value: self * Double(truncating: pow(10, decimal) as NSNumber)) return retValue } /// Rounds the double to decimal places value func rounded(toPlaces places:Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } func roundAndAddCommas(toPlaces places:Int = 2) -> String { let roundedBalance = self.rounded(toPlaces: places) let number = NSNumber(value: roundedBalance) return number.addCommas() } func addCommas() -> String { let number = NSNumber(value: self) return number.addCommas() } func removeZerosFromEnd(maximumFractionDigits: Int = 16) -> String { let formatter = NumberFormatter() let number = NSNumber(value: self) formatter.numberStyle = .decimal formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = maximumFractionDigits //maximum digits in Double after dot (maximum precision) return String(formatter.string(from: number) ?? " ") } var clean: String { return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self) } } public extension NSNumber { func convertOutputValue(decimal: Int) -> Double { let retValue = Double(truncating: self) / Double(truncating: pow(10, decimal) as NSNumber) return retValue } func addCommas() -> String { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal let formattedNumber = numberFormatter.string(from: self) return formattedNumber ?? "0" } func roundAndAddCommas(toPlaces places:Int = 2) -> String { let decimalNumber = NSDecimalNumber(decimal: self.decimalValue) let rounded = decimalNumber.rounding(accordingToBehavior: NSDecimalNumberHandler(roundingMode: .up, scale: Int16(places), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)) return rounded.addCommas() } } public extension Dictionary { var queryString: String { var output: String = "" for (key,value) in self { output += "\(key)=\(value)&" } return output } } public extension URL { var queryParameters: [String: String]? { guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else { return nil } var parameters = [String: String]() for item in queryItems { parameters[item.name] = item.value } return parameters } mutating func appendQueryItem(name: String, value: String?) { guard var urlComponents = URLComponents(string: absoluteString) else { return } // Create array of existing query items var queryItems: [URLQueryItem] = urlComponents.queryItems ?? [] // Create query item let queryItem = URLQueryItem(name: name, value: value) // Append the new query item in the existing query items array if let index = queryItems.index(of: queryItem) { queryItems.remove(at: index) } queryItems.append(queryItem) // Append updated query items array in the url component object urlComponents.queryItems = queryItems // Returns the url from new url components self = urlComponents.url! } } public extension Date { func timeAgoDisplay() -> String { let calendar = Calendar.current let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())! let hourAgo = calendar.date(byAdding: .hour, value: -1, to: Date())! let dayAgo = calendar.date(byAdding: .day, value: -1, to: Date())! let weekAgo = calendar.date(byAdding: .day, value: -7, to: Date())! if minuteAgo < self { let diff = Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0 if diff < 30 { return "Just now".localized } return "%d sec(s) ago".localizedFormat(diff) } else if hourAgo < self { let diff = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0 return "%d min(s) ago".localizedFormat(diff) } else if dayAgo < self { let diff = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0 return "%d hour(s) ago".localizedFormat(diff) } else if weekAgo < self { let diff = Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0 return "%d day(s) ago".localizedFormat(diff) } let diff = Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0 return "%d week(s) ago".localizedFormat(diff) } } public extension Notification.Name { static let didAuthenticationSuccessWithMozo = Notification.Name("didAuthenticationSuccessWithMozo") static let didLogoutFromMozo = Notification.Name("didLogoutFromMozo") static let didCloseAllMozoUI = Notification.Name("didCloseAllMozoUI") static let didChangeBalance = Notification.Name("didChangeBalance") static let didConvertSuccessOnchainToOffchain = Notification.Name("didConvertSuccessOnchainToOffchain") static let didReceiveDetailDisplayItem = Notification.Name("didReceiveDetailDisplayItem") static let didLoadTokenInfoFailed = Notification.Name("didLoadTokenInfoFailed") static let didReceiveOnchainDetailDisplayItem = Notification.Name("didReceiveOnchainDetailDisplayItem") static let didReceiveETHDetailDisplayItem = Notification.Name("didReceiveETHDetailDisplayItem") static let didReceiveETHOffchainDetailDisplayItem = Notification.Name("didReceiveETHOffchainDetailDisplayItem") static let didLoadETHOnchainTokenInfoFailed = Notification.Name("didLoadETHOnchainTokenInfoFailed") static let didReceiveExchangeInfo = Notification.Name("didReceiveExchangeInfo") static let didChangeAddressBook = Notification.Name("didChangeAddressBook") static let didChangeStoreBook = Notification.Name("didChangeStoreBook") static let didChangeProfile = Notification.Name("didChangeProfile") static let didMeetMaintenance = Notification.Name("didMeetMaintenance") static let didMaintenanceComplete = Notification.Name("didMaintenanceComplete") static let didExpiredToken = Notification.Name("didExpiredToken") static let openStoreDetailsFromHistory = Notification.Name("openStoreDetailsFromHistory") }
38.03675
232
0.615713
6a7fc7c506bf32a31a25000a82ec3ea36ae97952
1,239
// // StringExtension.swift // Pods-SwiftyOptional_Example // // Created by Elsayed Hussein on 11/8/18. // import Foundation extension Optional where Wrapped == String { //MARK: Unwrapping public var swiftyValue: String { return self ?? "" } public func swiftyDefault(value: String) -> String { return self ?? value } //MARK: Convert public var intValue: Int { let value = Int(self.swiftyValue) return value.swiftyValue } public func intValue(default: Int) -> Int { let value = Int(self.swiftyValue) return value.swiftyDefault(value: `default`) } public var doubleValue: Double { let value = Double(self.swiftyValue) return value.swiftyValue } public func DoubleValue(default: Double) -> Double { let value = Double(self.swiftyValue) return value.swiftyDefault(value: `default`) } public var floatValue: Float { let value = Float(self.swiftyValue) return value.swiftyValue } public func floatValue(default: Float) -> Float { let value = Float(self.swiftyValue) return value.swiftyDefault(value: `default`) } }
23.826923
56
0.614205
ed3325257114f95c2d4bc9d7b0dd8489e3021fb9
8,395
/* Copyright (c) 2019, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation import UIKit import CareKit class CareViewController: OCKDailyPageViewController<OCKStore> { override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Care Team", style: .plain, target: self, action: #selector(presentContactsListViewController)) } @objc private func presentContactsListViewController() { let viewController = OCKContactsListViewController(storeManager: storeManager) viewController.title = "Care Team" viewController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(dismissContactsListViewController)) let navigationController = UINavigationController(rootViewController: viewController) present(navigationController, animated: true, completion: nil) } @objc private func dismissContactsListViewController() { dismiss(animated: true, completion: nil) } // This will be called each time the selected date changes. // Use this as an opportunity to rebuild the content shown to the user. override func dailyPageViewController<S>( _ dailyPageViewController: OCKDailyPageViewController<S>, prepare listViewController: OCKListViewController, for date: Date) where S: OCKStoreProtocol { let identifiers = ["doxylamine", "nausea", "kegels"] let anchor = OCKTaskAnchor.taskIdentifiers(identifiers) let query = OCKTaskQuery(for: date, excludesTasksWithNoEvents: true) storeManager.store.fetchTasks(anchor, query: query) { result in switch result { case .failure(let error): print("Error: \(error)") case .success(let tasks): // Add a non-CareKit view into the list let tipTitle = "Benefits of exercising" let tipText = "Learn how activity can promote a healthy pregnancy." // Only show the tip view on the current date if Calendar.current.isDate(date, inSameDayAs: Date()) { let tipView = TipView() tipView.headerView.titleLabel.text = tipTitle tipView.headerView.detailLabel.text = tipText tipView.imageView.image = UIImage(named: "exercise.jpg") listViewController.appendView(tipView, animated: false) } // Since the kegel task is only sheduled every other day, there will be cases // where it is not contained in the tasks array returned from the query. if let kegelsTask = tasks.first(where: { $0.identifier == "kegels" }) { let kegelsCard = OCKSimpleTaskViewController(storeManager: self.storeManager, task: kegelsTask, eventQuery: OCKEventQuery(for: date)) listViewController.appendViewController(kegelsCard, animated: false) } // Create a card for the doxylamine task if there are events for it on this day. if let doxylamineTask = tasks.first(where: { $0.identifier == "doxylamine" }) { let doxylamineCard = OCKChecklistTaskViewController( storeManager: self.storeManager, task: doxylamineTask, eventQuery: OCKEventQuery(for: date)) listViewController.appendViewController(doxylamineCard, animated: false) } // Create a card for the nausea task if there are events for it on this day. // Its OCKSchedule was defined to have daily events, so this task should be // found in `tasks` every day after the task start date. if let nauseaTask = tasks.first(where: { $0.identifier == "nausea" }) { // Create a plot comparing nausea to medication adherence. let nauseaDataSeries = OCKCartesianChartViewController<OCKStore>.DataSeriesConfiguration( taskIdentifier: "nausea", legendTitle: "Nausea", gradientStartColor: #colorLiteral(red: 0.9176470588, green: 0.3529411765, blue: 0.4588235294, alpha: 1), gradientEndColor: #colorLiteral(red: 0.9020889401, green: 0.5339772701, blue: 0.4407126009, alpha: 1), markerSize: 10, eventAggregator: OCKEventAggregator.countOutcomeValues) let doxylamineDataSeries = OCKCartesianChartViewController<OCKStore>.DataSeriesConfiguration( taskIdentifier: "doxylamine", legendTitle: "Doxylamine", gradientStartColor: #colorLiteral(red: 0.7372466922, green: 0.7372466922, blue: 0.7372466922, alpha: 1), gradientEndColor: #colorLiteral(red: 0.7372466922, green: 0.7372466922, blue: 0.7372466922, alpha: 1), markerSize: 10, eventAggregator: OCKEventAggregator.countOutcomeValues) let insightsCard = OCKCartesianChartViewController( storeManager: self.storeManager, dataSeriesConfigurations: [nauseaDataSeries, doxylamineDataSeries], date: date, plotType: .bar) let titleText = "Nausea & Doxylamine Intake" let detailText = "This Week" insightsCard.chartView.headerView.titleLabel.text = titleText insightsCard.chartView.headerView.detailLabel.text = detailText listViewController.appendViewController(insightsCard, animated: false) // Also create a card that displays a single event. // The event query passed into the initializer specifies that only // today's log entries should be displayed by this log task view controller. let nauseaCard = OCKSimpleLogTaskViewController( storeManager: self.storeManager, task: nauseaTask, eventQuery: OCKEventQuery(for: date)) listViewController.appendViewController(nauseaCard, animated: true) } } } } }
53.814103
128
0.625372
e4f5dc7c17f2d130d13c0ea8203dd767f1d9495d
14,521
// // FeaturedPackageView.swift // Sileo // // Created by CoolStar on 7/6/19. // Copyright © 2019 Sileo Team. All rights reserved. // import UIKit import Evander class FeaturedPackageView: FeaturedBaseView, PackageQueueButtonDataProvider { let imageView: PackageIconView let titleLabel, authorLabel, versionLabel: UILabel static let featuredPackageReload = Notification.Name("FeaturedPackageReload") let repoName: String let packageButton: PackageQueueButton let package: String var separatorView: UIView? var separatorHeightConstraint: NSLayoutConstraint? var isUpdatingPurchaseStatus: Bool = false var icon: String? var packageObject: Package? required init?(dictionary: [String: Any], viewController: UIViewController, tintColor: UIColor, isActionable: Bool) { guard let package = dictionary["package"] as? String else { return nil } guard let packageIcon = dictionary["packageIcon"] as? String else { return nil } self.icon = packageIcon guard let packageName = dictionary["packageName"] as? String else { return nil } guard let packageAuthor = dictionary["packageAuthor"] as? String else { return nil } guard let repoName = dictionary["repoName"] as? String else { return nil } self.package = package self.repoName = repoName imageView = PackageIconView(frame: .zero) titleLabel = SileoLabelView(frame: .zero) authorLabel = UILabel(frame: .zero) versionLabel = UILabel(frame: .zero) packageButton = PackageQueueButton() separatorView = UIView(frame: .zero) super.init(dictionary: dictionary, viewController: viewController, tintColor: tintColor, isActionable: isActionable) imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true if !packageIcon.isEmpty { imageView.image = EvanderNetworking.shared.image(packageIcon, size: CGSize(width: 128, height: 128)) { [weak self] refresh, image in if refresh, let strong = self, let image = image, strong.icon == packageIcon { DispatchQueue.main.async { strong.imageView.image = image } } } ?? UIImage(named: "Tweak Icon") } else { imageView.image = UIImage(named: "Tweak Icon") } titleLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold) titleLabel.text = packageName authorLabel.text = packageAuthor authorLabel.font = UIFont.systemFont(ofSize: 13, weight: .medium) authorLabel.textColor = UIColor(red: 143.0/255.0, green: 142.0/255.0, blue: 148.0/255.0, alpha: 1.0) versionLabel.text = String(format: "%@ · %@", String(localizationKey: "Loading"), repoName) versionLabel.textColor = UIColor(red: 143.0/255.0, green: 142.0/255.0, blue: 148.0/255.0, alpha: 1.0) versionLabel.font = UIFont.systemFont(ofSize: 11) let titleStackView = UIStackView(arrangedSubviews: [titleLabel, authorLabel, versionLabel]) titleStackView.spacing = 2 titleStackView.axis = .vertical titleStackView.setCustomSpacing(4, after: authorLabel) packageButton.shouldCheckPurchaseStatus = true if let buttonText = dictionary["buttonText"] as? String { packageButton.overrideTitle = buttonText } packageButton.dataProvider = self packageButton.viewControllerForPresentation = viewController packageButton.setContentHuggingPriority(.required, for: .horizontal) let stackView = UIStackView(arrangedSubviews: [imageView, titleStackView, packageButton]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.spacing = 16 stackView.alignment = .center self.addSubview(stackView) stackView.topAnchor.constraint(greaterThanOrEqualTo: self.topAnchor, constant: 8).isActive = true stackView.bottomAnchor.constraint(lessThanOrEqualTo: self.bottomAnchor, constant: -8).isActive = true stackView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 16).isActive = true stackView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -16).isActive = true let useSeparator = (dictionary["useSeparator"] as? Bool) ?? true if useSeparator { let separatorView = UIView(frame: .zero) separatorView.translatesAutoresizingMaskIntoConstraints = false separatorView.backgroundColor = .sileoSeparatorColor self.addSubview(separatorView) weak var weakSelf = self NotificationCenter.default.addObserver(weakSelf as Any, selector: #selector(updateSileoColors), name: SileoThemeManager.sileoChangedThemeNotification, object: nil) self.separatorView = separatorView separatorView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true separatorView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true separatorView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true let separatorHeightConstraint = separatorView.heightAnchor.constraint(equalToConstant: 1) separatorHeightConstraint.isActive = true self.separatorHeightConstraint = separatorHeightConstraint } self.isAccessibilityElement = true self.accessibilityLabel = String(format: String(localizationKey: "Package_By_Author"), titleLabel.text ?? "", authorLabel.text ?? "") self.accessibilityTraits = .button let tap = UITapGestureRecognizer(target: self, action: #selector(FeaturedPackageView.openDepiction)) tap.delaysTouchesBegan = false self.addGestureRecognizer(tap) viewController.registerForPreviewing(with: self, sourceView: self) if #available(iOS 13, *) { let interaction = UIContextMenuInteraction(delegate: self) self.addInteraction(interaction) } self.reloadPackage() NotificationCenter.default.addObserver(self, selector: #selector(FeaturedPackageView.reloadPackage), name: PackageListManager.reloadNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(FeaturedPackageView.reloadPackage), name: FeaturedPackageView.featuredPackageReload, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(FeaturedPackageView.reloadPackage), name: Notification.Name("ShowProvisional"), object: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func updateSileoColors() { self.separatorView?.backgroundColor = .sileoSeparatorColor } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { updateSileoColors() } override func didMoveToWindow() { super.didMoveToWindow() packageButton.tintColor = UINavigationBar.appearance().tintColor if let separatorHeightConstraint = self.separatorHeightConstraint { separatorHeightConstraint.constant = 1 / (self.window?.screen.scale ?? 1) } } override func layoutSubviews() { super.layoutSubviews() // If our container has a bigger width, give us a pleasant corner radius self.layer.cornerRadius = (self.superview?.bounds.width ?? 0) > self.bounds.width ? 4 : 0 } override func depictionHeight(width: CGFloat) -> CGFloat { 81 } override func accessibilityActivate() -> Bool { openDepiction(packageButton) return true } @objc func openDepiction(_ : Any?) { if let package = packageObject { self.parentViewController?.navigationController?.pushViewController(NativePackageViewController.viewController(for: package), animated: true) } else { let title = String(localizationKey: "Package_Unavailable") let message = String(format: String(localizationKey: "Package_Unavailable"), repoName) let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: String(localizationKey: "OK"), style: .cancel, handler: { _ in alertController.dismiss(animated: true, completion: nil) })) self.parentViewController?.present(alertController, animated: true, completion: nil) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) self.highlighted = true } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) self.highlighted = false } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) self.highlighted = false } public var highlighted: Bool = false { didSet { self.backgroundColor = highlighted ? .sileoHighlightColor : nil } } @objc public func reloadPackage() { let package: Package? = { if let holder = PackageListManager.shared.newestPackage(identifier: self.package, repoContext: nil) { return holder } else if let provisional = CanisterResolver.shared.package(for: self.package) { return provisional } return nil }() if let package = package { self.versionLabel.text = String(format: "%@ · %@", package.version, self.repoName) self.packageButton.package = package self.packageButton.isEnabled = true self.packageObject = package } else { self.versionLabel.text = String(localizationKey: "Package_Unavailable") self.packageButton.package = nil self.packageButton.isEnabled = false } } @objc public func updatePurchaseStatus() { if isUpdatingPurchaseStatus { return } guard let package = PackageListManager.shared.newestPackage(identifier: self.package, repoContext: nil) else { return } isUpdatingPurchaseStatus = true guard let repo = package.sourceRepo else { return } PaymentManager.shared.getPaymentProvider(for: repo) { error, provider in if error != nil { let info = PaymentPackageInfo(price: String(localizationKey: "Package_Paid"), purchased: false, available: true) DispatchQueue.main.async { self.isUpdatingPurchaseStatus = false self.packageButton.paymentInfo = info } } provider?.getPackageInfo(forIdentifier: self.package) { error, info in var info = info if error != nil { info = PaymentPackageInfo(price: String(localizationKey: "Package_Paid"), purchased: false, available: true) } DispatchQueue.main.async { self.isUpdatingPurchaseStatus = false if let info = info { self.packageButton.paymentInfo = info } } } } } } extension FeaturedPackageView: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { if let package = PackageListManager.shared.newestPackage(identifier: self.package, repoContext: nil) { return NativePackageViewController.viewController(for: package) } return nil } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { self.parentViewController?.navigationController?.pushViewController(viewControllerToCommit, animated: false) } } @available(iOS 13.0, *) extension FeaturedPackageView: UIContextMenuInteractionDelegate { func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { if let package = PackageListManager.shared.newestPackage(identifier: self.package, repoContext: nil) { let packageViewController = NativePackageViewController.viewController(for: package) let actions = packageViewController.actions() return UIContextMenuConfiguration(identifier: nil, previewProvider: { packageViewController }, actionProvider: {_ in UIMenu(title: "", image: nil, options: .displayInline, children: actions) }) } return nil } func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) { if let controller = animator.previewViewController { animator.addAnimations { self.parentViewController?.show(controller, sender: self) } } } }
43.346269
204
0.621927
9b3e180cdfdecdc9548c7d41051a917ce4d936ba
427
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck var d struct d<i>var f:d=r f
42.7
79
0.749415