How to secure CVC in STPPaymentCardTextField in Stripe for iOS

Issue #421 private func maskCvcIfAny() { guard let view = paymentTextField.subviews.first(where: { !($0 is UIImageView) }), let cvcField = view.subviews .compactMap({ $0 as? UITextField }) .first(where: { $0.tag == 2 && ($0.accessibilityLabel ?? "").lowercased().contains("cvc") }) else { return } cvcField.isSecureTextEntry = true } where tag is in STPPaymentCardTextFieldViewModel.h typedef NS_ENUM(NSInteger, STPCardFieldType) { STPCardFieldTypeNumber, STPCardFieldTypeExpiration, STPCardFieldTypeCVC, STPCardFieldTypePostalCode, }; Also, need to check accessibilityLabel in STPPaymentCardTextField.m - (NSString *)defaultCVCPlaceholder { if (self.viewModel.brand == STPCardBrandAmex) { return STPLocalizedString(@"CVV", @"Label for entering CVV in text field"); } else { return STPLocalizedString(@"CVC", @"Label for entering CVC in text field"); } }

September 16, 2019 · 1 min · 96 words · Khoa

How to replace all occurrences of a string in Javascript

Issue #420 const normalized = string .replace(/\//g, '') .replace(/\"/g, '') .replace(/\(/g, '') .replace(/\)/g, '')

September 16, 2019 · 1 min · 14 words · Khoa

How to read and write file using fs in node

Issue #419 function write(json) { const data = JSON.stringify(json) const year = json.date.getFullYear() const directory = `collected/${slugify(className)}/${year}` fs.mkdirSync(directory, { recursive: true }) fs.writeFileSync( `${directory}/${slugify(studentName)}`, data, { overwrite: true } ) } async function readAll() { const classes = fs.readdirSync('classes') classes.forEach((class) => { const years = fs.readdirSync(`classes/${class}`) years.forEach((year) => { const students = fs.readdirSync(`classes/${class}/${year}`) students.forEach((student) => { const data = fs.readFileSync(`classes/${class}/${year}/${student}) const json = JSON.parse(data) }) }) }) }

September 16, 2019 · 1 min · 68 words · Khoa

How to get videos from vimeo in node

Issue #418 Code Path for user users/nsspain/videos Path for showcase https://developer.vimeo.com/api/reference/albums#get_album Path for Channels, Groups and Portfolios const Vimeo = require('vimeo').Vimeo const vimeoClient = new Vimeo(vimeoClientId, vimeoClientSecret, vimeoAccessToken) async getVideos(path) { const options = { path: `channels/staffpicks/videos`, query: { page: 1, per_page: 100, fields: 'uri,name,description,created_time,pictures' } } return new Promise((resolve, reject) => { try { vimeoClient.request(options, (error, body, status_code, headers) => { if (isValid(body)) { resolve(body) } else { throw error } }) } catch (e) { reject(e) console....

September 16, 2019 · 2 min · 228 words · Khoa

How to get videos from youtube in node

Issue #417 class Youtube { async getVideos(playlistId, pageToken) { const options = { key: clientKey, part: 'id,contentDetails,snippet', playlistId: playlistId, maxResult: 100, pageToken } return new Promise((resolve, reject) => { try { youtube.playlistItems.list(options, (error, result) => { if (isValid(result)) { resolve(result) } else { throw error } }) } catch (e) { reject(e) } }) } } Response look like { "kind": "youtube#playlistItemListResponse", "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/ZNTrH71d3sV6gR6BWPeamXI1HhE\"", "nextPageToken": "CAUQAA", "pageInfo": { "totalResults": 32, "resultsPerPage": 5 }, "items": [ { "kind": "youtube#playlistItem", "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/pt-bElhU3f7Q6c1Wc0URk9GJN-w\"", "id": "UExDbDVOTTRxRDN1X0w4ZEpyV1liTEI4RmNVYW9BSERGdC4yODlGNEE0NkRGMEEzMEQy", "snippet": { "publishedAt": "2019-04-11T06:09:26....

September 13, 2019 · 1 min · 209 words · Khoa

How to convert callback to Promise in Javascript

Issue #416 // @flow const toPromise = (f: (any) => void) => { return new Promise<any>((resolve, reject) => { try { f((result) => { resolve(result) }) } catch (e) { reject(e) } }) } const videos = await toPromise(callback) If a function accepts many parameters, we need to curry https://onmyway133.github.io/blog/Curry-in-Swift-and-Javascript/ function curry2(f) { return (p1) => { return (p2) => { return f(p1, p2) } } } const callback = curry2(aFunctionThatAcceptsOptionsAndCallback)(options) const items = await toPromise(callback)

September 13, 2019 · 1 min · 76 words · Khoa

How to fix electron issues

Issue #415 Electron require() is not defined https://stackoverflow.com/questions/44391448/electron-require-is-not-defined function createWindow () { win = new BrowserWindow({ title: 'MyApp', width: 600, height: 500, resizable: false, icon: __dirname + '/Icon/Icon.icns', webPreferences: { nodeIntegration: true } }) } DevTools was disconnected from the page npm install babel-cli@latest --save-dev npm install react@16.2.0 win.openDevTools() This leads to Cannot find module 'react/lib/ReactComponentTreeHook' If we’re using binary, then rebuild, it is the problem that cause devTools not work...

September 12, 2019 · 1 min · 152 words · Khoa

How to easily parse deep json in Swift

Issue #414 Codable is awesome, but sometimes we just need to quickly get value in a deepy nested JSON. In the same way I did for Dart How to resolve deep json object in Dart, let’s make that in Swift. See https://github.com/onmyway133/Omnia/blob/master/Sources/Shared/JSON.swift public func resolve<T>(_ jsonDictionary: [String: Any], keyPath: String) -> T? { var current: Any? = jsonDictionary keyPath.split(separator: ".").forEach { component in if let maybeInt = Int(component), let array = current as?...

September 12, 2019 · 1 min · 177 words · Khoa

How to work with Hardened runtime and sandbox in macOS

Issue #413 Hardened Runtime and Sandboxing Resolving Common Notarization Issues macOS Code Signing In Depth

September 11, 2019 · 1 min · 15 words · Khoa

How to speed up GMSMarker in Google Maps for iOS

Issue #412 Google Maps with a lot of pin, and no clustering can have bad performance if there are complex view in the marker. The workaround is to use manual layout and rasterization shouldRasterize When the value of this property is true, the layer is rendered as a bitmap in its local coordinate space and then composited to the destination with any other content. Shadow effects and any filters in the filters property are rasterized and included in the bitmap....

September 10, 2019 · 2 min · 345 words · Khoa

How to support drag and drop in UICollectionView iOS

Issue #411 See DragAndDrop example class ViewController: UIViewController, UICollectionViewDropDelegate, UICollectionViewDragDelegate { // MARK: - UICollectionViewDragDelegate func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { let controller = leftController let provider = NSItemProvider( object: controller.imageForCell(indexPath: indexPath) ) let dragItem = UIDragItem(itemProvider: provider) dragItem.localObject = indexPath return [dragItem] } // MARK: - UICollectionViewDropDelegate func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) { let destinationIndexPath: IndexPath if let indexPath = coordinator....

September 10, 2019 · 1 min · 114 words · Khoa

How to support drag and drop in NSView

Issue #410 import AppKit import Anchors class DraggingView: NSView { var didDrag: ((FileInfo) -> Void)? let highlightView = NSView() override init(frame frameRect: NSRect) { super.init(frame: frameRect) registerForDraggedTypes([ .fileURL ]) highlightView.isHidden = true addSubview(highlightView) activate(highlightView.anchor.edges) highlightView.wantsLayer = true highlightView.layer?.borderColor = NSColor(hex: "#FF6CA8").cgColor highlightView.layer?.borderWidth = 6 } required init?(coder decoder: NSCoder) { fatalError() } override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { highlightView.isHidden = false return NSDragOperation() } override func draggingEnded(_ sender: NSDraggingInfo) { guard let pathAlias = sender....

September 10, 2019 · 1 min · 163 words · Khoa

How to use NSStepper in Appkit

Issue #409 let stepper = NSStepper() let textField = NSTextField(wrappingLabelWithString: "\(myLocalCount)") stepper.integerValue = myLocalCount stepper.minValue = 5 stepper.maxValue = 24 stepper.valueWraps = false stepper.target = self stepper.action = #selector(onStepperChange(_:)) @objc func onStepperChange(_ sender: NSStepper) { myLocalCount = sender.integerValue textField.stringValue = "\(sender.integerValue)" }

September 8, 2019 · 1 min · 42 words · Khoa

How to handle shortcut in AppKit

Issue #408 Podfile pod 'MASShortcut' let shortcut = MASShortcut(keyCode: kVK_ANSI_K, modifierFlags: [.command, .shift]) MASShortcutMonitor.shared()?.register(shortcut, withAction: { self.showPopover(sender: self.statusItem.button) })

September 8, 2019 · 1 min · 19 words · Khoa

How to select file in its directory in AppKit

Issue #407 https://developer.apple.com/documentation/appkit/nsworkspace/1524399-selectfile In macOS 10.5 and later, this method does not follow symlinks when selecting the file. If the fullPath parameter contains any symlinks, this method selects the symlink instead of the file it targets. If you want to select the target file, use the resolvingSymlinksInPath method to resolve any symlinks before calling this method. It is safe to call this method from any thread of your app. NSWorkspace.shared.selectFile( url....

September 7, 2019 · 1 min · 73 words · Khoa

How to use NSProgressIndicator in AppKit

Issue #406 let progressIndicator = NSProgressIndicator() progressIndicator.isIndeterminate = true progressIndicator.style = .spinning progressIndicator.startAnimation(nil)

September 7, 2019 · 1 min · 13 words · Khoa

How to show save panel in AppKit

Issue #405 Enable Read/Write for User Selected File under Sandbox to avoid bridge absent error func showSave( name: String, window: NSWindow ) async -> URL? { let panel = NSSavePanel() panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser panel.nameFieldStringValue = name let response = await panel.beginSheetModal(for: window) if response == .OK { return panel.url } else { return nil } } To save multiple files, use NSOpenPanel let panel = NSOpenPanel() panel.canChooseFiles = false panel.allowsMultipleSelection = false panel....

September 7, 2019 · 1 min · 83 words · Khoa

How to animate NSView using keyframe

Issue #404 let animation = CAKeyframeAnimation(keyPath: "position.y") animation.values = [50, 20, 50] animation.keyTimes = [0.0, 0.5, 1.0] animation.duration = 2 animation.repeatCount = Float.greatestFiniteMagnitude animation.autoreverses = true myView.wantsLayer = true myView.layer?.add(animation, forKey: "bounce")

September 6, 2019 · 1 min · 32 words · Khoa

How to quit macOS on last window closed

Issue #403 https://developer.apple.com/documentation/appkit/nsapplicationdelegate/1428381-applicationshouldterminateafterl?language=objc The application sends this message to your delegate when the application’s last window is closed. It sends this message regardless of whether there are still panels open. (A panel in this case is defined as being an instance of NSPanel or one of its subclasses.) If your implementation returns NO, control returns to the main event loop and the application is not terminated. If you return YES, your delegate’s applicationShouldTerminate: method is subsequently invoked to confirm that the application should be terminated....

September 6, 2019 · 1 min · 95 words · Khoa

How to test Date with timezone aware in Swift

Issue #402 I want to test if a date has passed another date let base = Date(timeIntervalSince1970: 1567756697) XCTAssertEqual(validator.hasPassed(event: event, date: base), true) My hasPassed is using Calendar.current func minuteSinceMidnight(date: Date) -> MinuteSinceMidnight { let calendar = Calendar.current let start = calendar.startOfDay(for: date) return Int(date.timeIntervalSince(start)) / 60 } But the minute is always having timezone applied. Even if I try with DateComponents func minuteSinceMidnight(date: Date) -> MinuteSinceMidnight { let components = calendar....

September 6, 2019 · 2 min · 230 words · Khoa