repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kharrison/CodeExamples
Swiper/Swiper/ViewController.swift
1
3859
// Created by Keith Harrison https://useyourloaf.com // Copyright (c) 2017 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE 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 HOLDER 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 UIKit class ViewController: UIViewController { @IBOutlet private var fullScreenConstraints: [NSLayoutConstraint]! @IBOutlet private var halfScreenConstraints: [NSLayoutConstraint]! @IBOutlet private var modeSwitch: UISwitch! @IBOutlet private var countDisplay: UILabel! override var prefersStatusBarHidden: Bool { if #available(iOS 11.0, *) { return super.prefersStatusBarHidden } else { return fullScreenMode || super.prefersStatusBarHidden } } override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge { return fullScreenMode ? [.bottom, .top] : UIRectEdge() } private var count = 0 { didSet { countDisplay.text = NumberFormatter.localizedString(from: NSNumber(value: count), number: .decimal) } } private var fullScreenMode: Bool = false { didSet { updateAppearance() } } private func updateAppearance() { view.layoutIfNeeded() updateConstraints() UIView.animate(withDuration: 0.25) { self.updateDeferringSystemGestures() self.view.layoutIfNeeded() } } private func updateDeferringSystemGestures() { if #available(iOS 11.0, *) { setNeedsUpdateOfScreenEdgesDeferringSystemGestures() } else { setNeedsStatusBarAppearanceUpdate() } } private func updateConstraints() { if fullScreenMode { halfScreenConstraints.forEach { $0.isActive = false } fullScreenConstraints.forEach { $0.isActive = true } } else { fullScreenConstraints.forEach { $0.isActive = false } halfScreenConstraints.forEach { $0.isActive = true } } } @IBAction func fullScreen(_ sender: UISwitch) { fullScreenMode = sender.isOn } @IBAction func swipeUp(_ sender: UISwipeGestureRecognizer) { count += 1 } @IBAction func swipeDown(_ sender: UISwipeGestureRecognizer) { count -= 1 } override func viewDidLoad() { super.viewDidLoad() modeSwitch.isOn = fullScreenMode updateAppearance() } }
bsd-3-clause
e25088d57410f251702b3b4ddd7d58ac
35.40566
111
0.685411
4.947436
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Aztec/ViewControllers/UnknownEditorViewController.swift
2
4308
import Foundation import UIKit import Aztec // MARK: - UnknownEditorViewController // class UnknownEditorViewController: UIViewController { /// Save Bar Button /// fileprivate(set) var saveButton: UIBarButtonItem = { let saveTitle = NSLocalizedString("Save", comment: "Save Action") return UIBarButtonItem(title: saveTitle, style: .plain, target: self, action: #selector(saveWasPressed)) }() /// Cancel Bar Button /// fileprivate(set) var cancelButton: UIBarButtonItem = { let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel Action") return UIBarButtonItem(title: cancelTitle, style: .plain, target: self, action: #selector(cancelWasPressed)) }() /// HTML Editor /// fileprivate(set) var editorView: UITextView! /// Raw HTML To Be Edited /// fileprivate let attachment: HTMLAttachment /// Unmodified HTML Text /// fileprivate let pristinePrettyHTML: String /// Closure to be executed whenever the user saves changes performed on the document /// var onDidSave: ((String) -> Void)? /// Closure to be executed whenever the user cancels edition /// var onDidCancel: (() -> Void)? /// Default Initializer /// /// - Parameter rawHTML: HTML To Be Edited /// init(attachment: HTMLAttachment) { self.attachment = attachment self.pristinePrettyHTML = attachment.prettyHTML() super.init(nibName: nil, bundle: nil) } /// Overriden Initializers /// required init?(coder aDecoder: NSCoder) { fatalError("You should use the `init(rawHTML:)` initializer!") } // MARK: - View Methods override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupEditorView() setupMainView() setupConstraints() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) editorView.becomeFirstResponder() } } // MARK: - Private Helpers // private extension UnknownEditorViewController { func setupNavigationBar() { title = NSLocalizedString("Unknown HTML", comment: "Title for Unknown HTML Editor") navigationItem.leftBarButtonItem = cancelButton navigationItem.rightBarButtonItem = saveButton saveButton.isEnabled = false } func setupEditorView() { let storage = HTMLStorage(defaultFont: Constants.defaultContentFont) let layoutManager = NSLayoutManager() let container = NSTextContainer() storage.addLayoutManager(layoutManager) layoutManager.addTextContainer(container) editorView = UITextView(frame: .zero, textContainer: container) editorView.accessibilityLabel = NSLocalizedString("HTML Content", comment: "Post HTML content") editorView.accessibilityIdentifier = "HTMLContentView" editorView.autocorrectionType = .no editorView.delegate = self editorView.translatesAutoresizingMaskIntoConstraints = false editorView.text = pristinePrettyHTML editorView.contentInset = Constants.defaultContentInsets } func setupMainView() { view.addSubview(editorView) } func setupConstraints() { NSLayoutConstraint.activate([ editorView.bottomAnchor.constraint(equalTo: view.bottomAnchor), editorView.topAnchor.constraint(equalTo: view.topAnchor), editorView.leadingAnchor.constraint(equalTo: view.leadingAnchor), editorView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) } } // MARK: - UITextViewDelegate extension UnknownEditorViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { saveButton.isEnabled = textView.text != pristinePrettyHTML } } // MARK: - Actions // extension UnknownEditorViewController { @IBAction func cancelWasPressed() { onDidCancel?() } @IBAction func saveWasPressed() { onDidSave?(editorView.text) } } // MARK: - Constants // extension UnknownEditorViewController { struct Constants { static let defaultContentFont = UIFont.systemFont(ofSize: 14) static let defaultContentInsets = UIEdgeInsetsMake(0, 5, 0, -5) } }
gpl-2.0
59e78439f3cdeaf852cb9b7b2937c58a
26.793548
116
0.674791
5.292383
false
false
false
false
DarrenKong/firefox-ios
UITests/LoginManagerTests.swift
1
32916
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Storage import EarlGrey @testable import Client class LoginManagerTests: KIFTestCase { fileprivate var webRoot: String! override func setUp() { super.setUp() PasscodeUtils.resetPasscode() webRoot = SimplePageServer.start() generateLogins() BrowserUtils.dismissFirstRunUI() BrowserUtils.configEarlGrey() } override func tearDown() { super.tearDown() clearLogins() PasscodeUtils.resetPasscode() BrowserUtils.resetToAboutHome() } fileprivate func openLoginManager() { // Wait until the dialog shows up let menuAppeared = GREYCondition(name: "Wait the Settings dialog to appear", block: { () -> Bool in var errorOrNil: NSError? EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Logins")).assert(grey_notNil(), error: &errorOrNil) let success = errorOrNil == nil return success }) if BrowserUtils.iPad() { EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Menu")).perform(grey_tap()) let settings_button = grey_allOf([grey_accessibilityLabel("Settings"), grey_accessibilityID("menu-Settings")]) EarlGrey.select(elementWithMatcher: settings_button).perform(grey_tap()) } else { let menu_button = grey_allOf([grey_accessibilityLabel("Menu"), grey_accessibilityID("TabToolbar.menuButton")]) EarlGrey.select(elementWithMatcher: menu_button).perform(grey_tap()) EarlGrey.select(elementWithMatcher: grey_text("Settings")).perform(grey_tap()) } let success = menuAppeared?.wait(withTimeout: 20) GREYAssertTrue(success!, reason: "Failed to display settings dialog") EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Logins")).perform(grey_tap()) } fileprivate func closeLoginManager() { EarlGrey.select(elementWithMatcher:grey_allOf([grey_accessibilityLabel("Settings"), grey_kindOfClass(NSClassFromString("UIButtonLabel")!)])).perform(grey_tap()) let DoneAppeared = GREYCondition(name: "Wait for the Done button", block: { () -> Bool in var errorOrNil: NSError? EarlGrey.select(elementWithMatcher: grey_accessibilityID("AppSettingsTableViewController.navigationItem.leftBarButtonItem")) .assert(grey_notNil(), error: &errorOrNil) let success = errorOrNil == nil return success }) let success = DoneAppeared?.wait(withTimeout: 10) GREYAssertTrue(success!, reason: "Failed to see Done button") EarlGrey.select(elementWithMatcher: grey_accessibilityID("AppSettingsTableViewController.navigationItem.leftBarButtonItem")).perform(grey_tap()) } fileprivate func generateLogins() { let profile = (UIApplication.shared.delegate as! AppDelegate).profile! let prefixes = "abcdefghijk" let numRange = (0..<20) let passwords = generateStringListWithFormat("password%@%d", numRange: numRange, prefixes: prefixes) let hostnames = generateStringListWithFormat("http://%@%d.com", numRange: numRange, prefixes: prefixes) let usernames = generateStringListWithFormat("%@%[email protected]", numRange: numRange, prefixes: prefixes) (0..<(numRange.count * prefixes.count)).forEach { index in let login = Login(guid: "\(index)", hostname: hostnames[index], username: usernames[index], password: passwords[index]) login.formSubmitURL = hostnames[index] profile.logins.addLogin(login).value } } func waitForMatcher(name: String) { let matcher = grey_allOf([grey_accessibilityLabel(name), grey_kindOfClass(NSClassFromString("UICalloutBarButton")!), grey_sufficientlyVisible()]) let menuShown = GREYCondition(name: "Wait for " + name) { var errorOrNil: NSError? EarlGrey.select(elementWithMatcher: matcher).assert(grey_notNil(), error: &errorOrNil) let success = errorOrNil == nil return success } let success = menuShown?.wait(withTimeout: 10) GREYAssertTrue(success!, reason: name + " Menu not shown") EarlGrey.select(elementWithMatcher: matcher).perform(grey_tap()) } fileprivate func generateStringListWithFormat(_ format: String, numRange: CountableRange<Int>, prefixes: String) -> [String] { return prefixes.map { char in return numRange.map { num in return String(format: format, "\(char)", num) } } .flatMap { $0 } } fileprivate func clearLogins() { let profile = (UIApplication.shared.delegate as! AppDelegate).profile! profile.logins.removeAll().value } func testListFiltering() { openLoginManager() var list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView // Filter by username tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "Enter Search Mode") tester().waitForAnimationsToFinish() // In simulator, the typing is too fast for the screen to be updated properly // pausing after 'password' (which all login password contains) to update the screen seems to make the test reliable tester().enterText(intoCurrentFirstResponder: "k10") tester().wait(forTimeInterval: 3) // Wait until the table is updated tester().waitForAnimationsToFinish() tester().enterText(intoCurrentFirstResponder: "@email.com") tester().wait(forTimeInterval: 3) // Wait until the table is updated tester().waitForAnimationsToFinish() list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView tester().waitForView(withAccessibilityLabel: "[email protected]") XCTAssertEqual(list.numberOfRows(inSection: 0), 1) tester().tapView(withAccessibilityLabel: "Clear Search") // Filter by hostname tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "Enter Search Mode") tester().waitForAnimationsToFinish() tester().enterText(intoCurrentFirstResponder: "http://k10") tester().waitForAnimationsToFinish() tester().wait(forTimeInterval: 3) // Wait until the table is updated tester().enterText(intoCurrentFirstResponder: ".com") tester().wait(forTimeInterval: 3) // Wait until the table is updated list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView tester().waitForView(withAccessibilityLabel: "[email protected]") XCTAssertEqual(list.numberOfRows(inSection: 0), 1) tester().tapView(withAccessibilityLabel: "Clear Search") // Filter by password tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "Enter Search Mode") tester().waitForAnimationsToFinish() tester().enterText(intoCurrentFirstResponder: "password") tester().waitForAnimationsToFinish() tester().wait(forTimeInterval: 3) // Wait until the table is updated tester().enterText(intoCurrentFirstResponder: "d9") tester().waitForAnimationsToFinish() list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView tester().waitForView(withAccessibilityLabel: "[email protected]") tester().wait(forTimeInterval: 3) // Wait until the table is updated XCTAssertEqual(list.numberOfRows(inSection: 0), 1) tester().tapView(withAccessibilityLabel: "Clear Search") // Filter by something that doesn't match anything tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "Enter Search Mode") tester().enterText(intoCurrentFirstResponder: "thisdoesntmatch") tester().waitForView(withAccessibilityIdentifier: "Login List") // KIFTest has a bug where waitForViewWithAccessibilityLabel causes the lists to appear again on device, // so checking the number of rows instead tester().waitForView(withAccessibilityLabel: "No logins found") let loginCount = countOfRowsInTableView(list) XCTAssertEqual(loginCount, 0) closeLoginManager() } func testListIndexView() { openLoginManager() // Swipe the index view to navigate to bottom section tester().waitForAnimationsToFinish() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().swipeView(withAccessibilityLabel: "table index", in: KIFSwipeDirection.down) tester().waitForView(withAccessibilityLabel: "[email protected], http://k0.com") closeLoginManager() } func testDetailPasswordMenuOptions() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") var passwordField = tester().waitForView(withAccessibilityIdentifier: "passwordField") as! UITextField XCTAssertTrue(passwordField.isSecureTextEntry) // Tap the ‘Reveal’ menu option EarlGrey.select(elementWithMatcher: grey_accessibilityID("passwordField")).perform(grey_tap()) waitForMatcher(name: "Reveal") passwordField = tester().waitForView(withAccessibilityIdentifier: "passwordField") as! UITextField XCTAssertFalse(passwordField.isSecureTextEntry) // Tap the ‘Hide’ menu option EarlGrey.select(elementWithMatcher: grey_accessibilityID("passwordField")).perform(grey_tap()) waitForMatcher(name: "Hide") passwordField = tester().waitForView(withAccessibilityIdentifier: "passwordField") as! UITextField XCTAssertTrue(passwordField.isSecureTextEntry) // Tap the ‘Copy’ menu option EarlGrey.select(elementWithMatcher: grey_accessibilityID("passwordField")).perform(grey_tap()) waitForMatcher(name: "Copy") tester().tapView(withAccessibilityLabel: "Logins") closeLoginManager() XCTAssertEqual(UIPasteboard.general.string, "passworda0") } func testDetailWebsiteMenuCopy() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") EarlGrey.select(elementWithMatcher: grey_accessibilityID("websiteField")).perform(grey_tap()) waitForMatcher(name: "Copy") // Tap the 'Open & Fill' menu option just checks to make sure we navigate to the web page EarlGrey.select(elementWithMatcher: grey_accessibilityID("websiteField")).perform(grey_tap()) waitForMatcher(name: "Open & Fill") tester().wait(forTimeInterval: 2) tester().waitForViewWithAccessibilityValue("a0.com/") XCTAssertEqual(UIPasteboard.general.string, "http://a0.com") } func testOpenAndFillFromNormalContext() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") // Tap the 'Open & Fill' menu option just checks to make sure we navigate to the web page EarlGrey.select(elementWithMatcher: grey_accessibilityID("websiteField")).perform(grey_tap()) waitForMatcher(name: "Open & Fill") tester().wait(forTimeInterval: 10) tester().waitForViewWithAccessibilityValue("a0.com/") } func testOpenAndFillFromPrivateContext() { if BrowserUtils.iPad() { EarlGrey.select(elementWithMatcher: grey_accessibilityID("TopTabsViewController.tabsButton")) .perform(grey_tap()) } else { EarlGrey.select(elementWithMatcher: grey_accessibilityID("TabToolbar.tabsButton")).perform(grey_tap()) } EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Private Mode")).perform(grey_tap()) EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Add Tab")).perform(grey_tap()) EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Menu")).perform(grey_tap()) if BrowserUtils.iPad() { let settings_button = grey_allOf([grey_accessibilityLabel("Settings"), grey_accessibilityID("menu-Settings")]) EarlGrey.select(elementWithMatcher: settings_button).perform(grey_tap()) } else { EarlGrey.select(elementWithMatcher: grey_text("Settings")).perform(grey_tap()) } EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Logins")).perform(grey_tap()) tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") // Tap the 'Open & Fill' menu option just checks to make sure we navigate to the web page EarlGrey.select(elementWithMatcher: grey_accessibilityID("websiteField")).perform(grey_tap()) waitForMatcher(name: "Open & Fill") tester().wait(forTimeInterval: 10) tester().waitForViewWithAccessibilityValue("a0.com/") } func testDetailUsernameMenuOptions() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") // Tap the 'Open & Fill' menu option just checks to make sure we navigate to the web page EarlGrey.select(elementWithMatcher: grey_accessibilityID("usernameField")).perform(grey_tap()) waitForMatcher(name: "Copy") tester().tapView(withAccessibilityLabel: "Logins") closeLoginManager() XCTAssertEqual(UIPasteboard.general.string!, "[email protected]") } func testListSelection() { openLoginManager() tester().waitForAnimationsToFinish() tester().tapView(withAccessibilityLabel: "Edit") tester().waitForAnimationsToFinish() // Select one entry let firstIndexPath = IndexPath(row: 0, section: 0) tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List") tester().waitForView(withAccessibilityLabel: "Delete") let list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView let firstCell = list.cellForRow(at: firstIndexPath)! XCTAssertTrue(firstCell.isSelected) // Deselect first row tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List") XCTAssertFalse(firstCell.isSelected) // Cancel tester().tapView(withAccessibilityLabel: "Cancel") tester().waitForView(withAccessibilityLabel: "Edit") // Select multiple logins tester().tapView(withAccessibilityLabel: "Edit") tester().waitForAnimationsToFinish() let pathsToSelect = (0..<3).map { IndexPath(row: $0, section: 0) } pathsToSelect.forEach { path in tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List") } tester().waitForView(withAccessibilityLabel: "Delete") pathsToSelect.forEach { path in XCTAssertTrue(list.cellForRow(at: path)!.isSelected) } // Deselect only first row tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List") XCTAssertFalse(firstCell.isSelected) // Make sure delete is still showing tester().waitForView(withAccessibilityLabel: "Delete") // Deselect the rest let pathsWithoutFirst = pathsToSelect[1..<pathsToSelect.count] pathsWithoutFirst.forEach { path in tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List") } // Cancel tester().tapView(withAccessibilityLabel: "Cancel") tester().waitForView(withAccessibilityLabel: "Edit") tester().tapView(withAccessibilityLabel: "Edit") // Select all using select all button tester().tapView(withAccessibilityLabel: "Select All") list.visibleCells.forEach { cell in XCTAssertTrue(cell.isSelected) } tester().waitForView(withAccessibilityLabel: "Delete") // Deselect all using button tester().tapView(withAccessibilityLabel: "Deselect All") list.visibleCells.forEach { cell in XCTAssertFalse(cell.isSelected) } tester().tapView(withAccessibilityLabel: "Cancel") tester().waitForView(withAccessibilityLabel: "Edit") // Finally, test selections get persisted after cells recycle tester().tapView(withAccessibilityLabel: "Edit") let firstInEachSection = (0..<3).map { IndexPath(row: 0, section: $0) } firstInEachSection.forEach { path in tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List") } // Go up, down and back up to for some recyling tester().scrollView(withAccessibilityIdentifier: "Login List", byFractionOfSizeHorizontal: 0, vertical: 1) tester().scrollView(withAccessibilityIdentifier: "Login List", byFractionOfSizeHorizontal: 0, vertical: 1) tester().scrollView(withAccessibilityIdentifier: "Login List", byFractionOfSizeHorizontal: 0, vertical: 1) XCTAssertTrue(list.cellForRow(at: firstInEachSection[0])!.isSelected) firstInEachSection.forEach { path in tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List") } tester().tapView(withAccessibilityLabel: "Cancel") tester().waitForView(withAccessibilityLabel: "Edit") closeLoginManager() } func testListSelectAndDelete() { openLoginManager() var list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView let oldLoginCount = countOfRowsInTableView(list) tester().tapView(withAccessibilityLabel: "Edit") tester().waitForAnimationsToFinish() // Select and delete one entry let firstIndexPath = IndexPath(row: 0, section: 0) tester().tapRow(at: firstIndexPath, inTableViewWithAccessibilityIdentifier: "Login List") tester().waitForView(withAccessibilityLabel: "Delete") let firstCell = list.cellForRow(at: firstIndexPath)! XCTAssertTrue(firstCell.isSelected) tester().tapView(withAccessibilityLabel: "Delete") tester().waitForAnimationsToFinish() tester().waitForView(withAccessibilityLabel: "Are you sure?") tester().tapView(withAccessibilityLabel: "Delete") tester().waitForAnimationsToFinish() tester().waitForView(withAccessibilityLabel: "Settings") list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView var newLoginCount = countOfRowsInTableView(list) XCTAssertEqual(oldLoginCount - 1, newLoginCount) // Select and delete multiple entries tester().tapView(withAccessibilityLabel: "Edit") tester().waitForAnimationsToFinish() let multiplePaths = (0..<3).map { IndexPath(row: $0, section: 0) } multiplePaths.forEach { path in tester().tapRow(at: path, inTableViewWithAccessibilityIdentifier: "Login List") } tester().tapView(withAccessibilityLabel: "Delete") tester().waitForAnimationsToFinish() tester().waitForView(withAccessibilityLabel: "Are you sure?") tester().tapView(withAccessibilityLabel: "Delete") tester().waitForAnimationsToFinish() tester().waitForView(withAccessibilityLabel: "Edit") newLoginCount = countOfRowsInTableView(list) XCTAssertEqual(oldLoginCount - 4, newLoginCount) closeLoginManager() } func testSelectAllCancelAndEdit() { openLoginManager() tester().waitForView(withAccessibilityLabel: "Edit") tester().tapView(withAccessibilityLabel: "Edit") // Select all using select all button let list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView tester().tapView(withAccessibilityLabel: "Select All") list.visibleCells.forEach { cell in XCTAssertTrue(cell.isSelected) } tester().waitForView(withAccessibilityLabel: "Deselect All") tester().tapView(withAccessibilityLabel: "Cancel") tester().tapView(withAccessibilityLabel: "Edit") // Make sure the state of the button is 'Select All' since we cancelled midway previously. tester().waitForView(withAccessibilityLabel: "Select All") tester().tapView(withAccessibilityLabel: "Cancel") closeLoginManager() } /* func testLoginListShowsNoResults() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") let list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView let oldLoginCount = countOfRowsInTableView(list) // Find something that doesn't exist tester().tapView(withAccessibilityLabel: "Enter Search Mode") tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "") tester().enterText(intoCurrentFirstResponder: "asdfasdf") // KIFTest has a bug where waitForViewWithAccessibilityLabel causes the lists to appear again on device, // so checking the number of rows instead XCTAssertEqual(oldLoginCount, 220) tester().waitForView(withAccessibilityLabel:"No logins found") tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "") // Erase search and make sure we see results instead tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") closeLoginManager() } */ fileprivate func countOfRowsInTableView(_ tableView: UITableView) -> Int { var count = 0 (0..<tableView.numberOfSections).forEach { section in count += tableView.numberOfRows(inSection: section) } return count } /** This requires the software keyboard to display. Make sure 'Connect Hardware Keyboard' is off during testing. Disabling since db crash is encountered due to a separate db bug */ /* func testEditingDetailUsingReturnForNavigation() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") let list = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView tester().tapView(withAccessibilityLabel: "Edit") // Check that we've selected the username field var firstResponder = UIApplication.shared.keyWindow?.firstResponder() let usernameCell = list.cellForRow(at: IndexPath(row: 1, section: 0)) as! LoginTableViewCell let usernameField = usernameCell.descriptionLabel XCTAssertEqual(usernameField, firstResponder) tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "changedusername") tester().tapView(withAccessibilityLabel: "Next") firstResponder = UIApplication.shared.keyWindow?.firstResponder() let passwordCell = list.cellForRow(at: IndexPath(row: 2, section: 0)) as! LoginTableViewCell let passwordField = passwordCell.descriptionLabel // Check that we've navigated to the password field upon return and that the password is no longer displaying as dots XCTAssertEqual(passwordField, firstResponder) XCTAssertFalse(passwordField.isSecureTextEntry) tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "changedpassword") tester().tapView(withAccessibilityLabel: "Done") // Go back and find the changed login tester().tapView(withAccessibilityLabel: "Back") tester().tapView(withAccessibilityLabel: "Enter Search Mode") tester().enterText(intoCurrentFirstResponder: "changedusername") let loginsList = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView XCTAssertEqual(loginsList.numberOfRows(inSection: 0), 1) closeLoginManager() } */ func testEditingDetailUpdatesPassword() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") let list = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView tester().tapView(withAccessibilityLabel: "Edit") // Check that we've selected the username field var firstResponder = UIApplication.shared.keyWindow?.firstResponder() let usernameCell = list.cellForRow(at: IndexPath(row: 1, section: 0)) as! LoginTableViewCell let usernameField = usernameCell.descriptionLabel XCTAssertEqual(usernameField, firstResponder) tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "changedusername") tester().tapView(withAccessibilityLabel: "Next") firstResponder = UIApplication.shared.keyWindow?.firstResponder() var passwordCell = list.cellForRow(at: IndexPath(row: 2, section: 0)) as! LoginTableViewCell let passwordField = passwordCell.descriptionLabel // Check that we've navigated to the password field upon return and that the password is no longer displaying as dots XCTAssertEqual(passwordField, firstResponder) XCTAssertFalse(passwordField.isSecureTextEntry) tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "changedpassword") tester().tapView(withAccessibilityLabel: "Done") // tapViewWithAcessibilityLabel fails when called directly because the cell is not a descendant in the // responder chain since it's a cell so instead use the underlying tapAtPoint method. let centerOfCell = CGPoint(x: passwordCell.frame.width / 2, y: passwordCell.frame.height / 2) XCTAssertTrue(passwordCell.descriptionLabel.isSecureTextEntry) // Tap the 'Reveal' menu option passwordCell.tap(at: centerOfCell) tester().waitForView(withAccessibilityLabel: "Reveal") tester().tapView(withAccessibilityLabel: "Reveal") passwordCell = list.cellForRow(at: IndexPath(row: 2, section: 0)) as! LoginTableViewCell XCTAssertEqual(passwordCell.descriptionLabel.text, "changedpassword") tester().tapView(withAccessibilityLabel: "Logins") closeLoginManager() } func testDeleteLoginFromDetailScreen() { openLoginManager() var list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView var firstRow = list.cellForRow(at: IndexPath(row: 0, section: 0)) as! LoginTableViewCell XCTAssertEqual(firstRow.descriptionLabel.text, "http://a0.com") tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "Delete") // Verify that we are looking at the nonsynced alert dialog tester().waitForView(withAccessibilityLabel: "Are you sure?") tester().waitForView(withAccessibilityLabel: "Logins will be permanently removed.") tester().tapView(withAccessibilityLabel: "Delete") tester().waitForAnimationsToFinish() list = tester().waitForView(withAccessibilityIdentifier: "Login List") as! UITableView firstRow = list.cellForRow(at: IndexPath(row: 0, section: 0)) as! LoginTableViewCell XCTAssertEqual(firstRow.descriptionLabel.text, "http://a1.com") closeLoginManager() } func testLoginDetailDisplaysLastModified() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") XCTAssertTrue(tester().viewExistsWithLabelPrefixedBy("Last modified")) tester().tapView(withAccessibilityLabel: "Logins") closeLoginManager() } func testPreventBlankPasswordInDetail() { openLoginManager() tester().waitForView(withAccessibilityLabel: "[email protected], http://a0.com") tester().tapView(withAccessibilityLabel: "[email protected], http://a0.com") tester().waitForView(withAccessibilityLabel: "password") let list = tester().waitForView(withAccessibilityIdentifier: "Login Detail List") as! UITableView tester().tapView(withAccessibilityLabel: "Edit") // Check that we've selected the username field var passwordCell = list.cellForRow(at: IndexPath(row: 2, section: 0)) as! LoginTableViewCell var passwordField = passwordCell.descriptionLabel tester().tapView(withAccessibilityLabel: "Next") tester().clearTextFromAndThenEnterText(intoCurrentFirstResponder: "") tester().tapView(withAccessibilityLabel: "Done") passwordCell = list.cellForRow(at: IndexPath(row: 2, section: 0)) as! LoginTableViewCell passwordField = passwordCell.descriptionLabel // Confirm that when entering a blank password we revert back to the original XCTAssertEqual(passwordField.text, "passworda0") tester().tapView(withAccessibilityLabel: "Logins") closeLoginManager() } func testListEditButton() { openLoginManager() // Check that edit button is enabled when entries are present tester().waitForView(withAccessibilityLabel: "Edit") tester().tapView(withAccessibilityLabel: "Edit") // Select all using select all button tester().tapView(withAccessibilityLabel: "Select All") // Delete all entries tester().waitForView(withAccessibilityLabel: "Delete") tester().tapView(withAccessibilityLabel: "Delete") tester().waitForAnimationsToFinish() tester().waitForView(withAccessibilityLabel: "Are you sure?") tester().tapView(withAccessibilityLabel: "Delete") tester().waitForAnimationsToFinish() // Check that edit button has been disabled tester().waitForView(withAccessibilityLabel: "Edit", traits: UIAccessibilityTraitNotEnabled) closeLoginManager() } }
mpl-2.0
6c22b8f76b4588130dccb3b7e03178a7
44.955307
168
0.661591
5.605451
false
true
false
false
peigen/iLife
iLife/AppDelegate.swift
1
1500
// // AppDelegate.swift // iLife // // Created by peigen on 14-6-29. // Copyright (c) 2014 Peigen.info. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var iLifeNC : UINavigationController? var coreDataHelper : CoreDataHelper = CoreDataHelper() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { // self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // self.window!.backgroundColor = UIColor.whiteColor() // self.window!.makeKeyAndVisible() iLifeNC = window!.rootViewController as? UINavigationController; return true } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { appItem() } func applicationWillTerminate(application: UIApplication) { // coreDataHelper.saveContext() } func appItem() { var appNames = ["Chrome","Youku","Weixin","Weibo","Alipay"] var appOpenURLs = ["googlechrome://","YouKu://","weixin://","weibo://","alipays://"] var appMgr:AppManager = AppManager() for i in 0..5 { appMgr.addApp(appNames[i], openURL: appOpenURLs[i]) } if(!appMgr.apps.isEmpty){ for app in appMgr.apps{ app.toString() } } } }
gpl-3.0
31f0f184e6a86b7ec8daa8eab19028dd
22.076923
115
0.718667
3.90625
false
false
false
false
roambotics/swift
test/stmt/yield.swift
2
2473
// RUN: %target-typecheck-verify-swift struct YieldRValue { var property: String { _read { yield "hello" } } } struct YieldVariables { var property: String { _read { yield "" } _modify { var x = "" yield &x } } var wrongTypes: String { _read { yield 0 // expected-error {{cannot convert value of type 'Int' to expected yield type 'String'}} } _modify { var x = 0 yield &x // expected-error {{cannot yield reference to storage of type 'Int' as an inout yield of type 'String'}} } } var rvalue: String { get {} _modify { yield &"" // expected-error {{cannot yield immutable value of type 'String' as an inout yield}} } } var missingAmp: String { get {} _modify { var x = "" yield x // expected-error {{yielding mutable value of type 'String' requires explicit '&'}} } } } protocol HasProperty { associatedtype Value var property: Value { get set } } struct GenericTypeWithYields<T> : HasProperty { var storedProperty: T? var property: T { _read { yield storedProperty! } _modify { yield &storedProperty! } } subscript<U>(u: U) -> (T,U) { _read { yield ((storedProperty!, u)) } _modify { var temp = (storedProperty!, u) yield &temp } } } // 'yield' is a context-sensitive keyword. func yield(_: Int) {} func call_yield() { yield(0) } struct YieldInDefer { var property: String { _read { defer { // expected-warning {{'defer' statement at end of scope always executes immediately}}{{7-12=do}} // FIXME: this recovery is terrible yield "" // expected-error@-1 {{function is unused}} // expected-error@-2 {{consecutive statements on a line must be separated by ';'}} // expected-warning@-3 {{string literal is unused}} } } } } // https://github.com/apple/swift/issues/57393 struct InvalidYieldParsing { var property: String { _read { yield(x: "test") // expected-error {{unexpected label in 'yield' statement}} {{13-16=}} yield(x: "test", y: {0}) // expected-error {{expected 1 yield value(s)}} // expected-error@-1 {{unexpected label in 'yield' statement}} {{13-16=}} // expected-error@-2 {{unexpected label in 'yield' statement}} {{24-29=}} yield(_: "test") // expected-error {{unexpected label in 'yield' statement}} {{13-16=}} } } }
apache-2.0
6e0af0bf48af21b4459555356b69c553
22.11215
119
0.584311
3.787136
false
false
false
false
getstalkr/stalkr-cloud
Tests/StalkrCloudTests/ControllerTests/RoleControllerTest.swift
1
800
// // RoleControllerTests.swift // stalkr-cloud // // Created by Matheus Martins on 5/25/17. // // import XCTest @testable import StalkrCloud import Foundation import Vapor class RoleControllerTest: ControllerTest { static var allTests = [ ("testRoleAll", testRoleAll) ] func testRoleAll() throws { let prefix = "testRoleAll" let roles = (0...3).map { i in RoleBuilder.build { u in u.name = "\(prefix)_role_\(i)" } } try roles.forEach { try $0.save() } let req = Request(method: .get, uri: "/role/all/") let res = try drop.respond(to: req) XCTAssert(try res.body.bytes! == Role.all().makeJSON().makeResponse().body.bytes!) } }
mit
7659c12626a8ce4e144fb5ac30e9e4cc
20.052632
90
0.54625
3.773585
false
true
false
false
josephliccini/dijkstra-swift
Dijkstra/Dijkstra.swift
1
1034
// // Dijkstra.swift // Dijkstra // // Created by joe on 8/23/14. // Copyright (c) 2014 Joseph Liccini. All rights reserved. // import Foundation func solve(var edges: [[Int]], inout vertexA: Vertex, inout vertexB: Vertex) { var minDistances: [Int] = [Int](count: edges.count, repeatedValue: Int.max) var queue = PriorityQueue<Vertex>() /* Perform Dijsktra's Algorithm */ queue.push(0, item: vertexA) while queue.count > 0 { var state = queue.pop() var priority = state.priority var currentVertex = state.item if currentVertex == vertexB { println(priority) return } for v in currentVertex.neighbors { var minDistance = edges[v.id][currentVertex.id] + priority if minDistance < minDistances[v.id] { queue.push(minDistance, item: v) minDistances[v.id] = minDistance } } } println("NO") }
mit
93ec226bad0055658b4961aeaddaa5a1
23.619048
79
0.55029
4.086957
false
false
false
false
shoheiyokoyama/Koyomi
Koyomi/Koyomi.swift
1
26255
// // Koyomi.swift // Pods // // Created by Shohei Yokoyama on 2016/10/09. // // import UIKit // MARK: - KoyomiDelegate - @objc public protocol KoyomiDelegate: class { /** Tells the delegate that the date at the specified index path was selected. - Parameter koyomi: The current Koyomi instance. - Parameter date: The date of the cell that was selected. - Parameter indexPath: The index path of the cell that was selected. */ @objc optional func koyomi(_ koyomi: Koyomi, didSelect date: Date?, forItemAt indexPath: IndexPath) /** Tells the delegate that the displayed month is changed. - Parameter koyomi: The current Koyomi instance. - Parameter dateString: The current date string. */ @objc optional func koyomi(_ koyomi: Koyomi, currentDateString dateString: String) /** The koyomi calls this method before select days - Parameter koyomi: The current Koyomi instance. - Parameter date: The first date in selected date. - Parameter toDate: The end date in selected date. - Parameter length: The length of selected date. - Returns: true if the item should be selected or false if it should not. */ @objc optional func koyomi(_ koyomi: Koyomi, shouldSelectDates date: Date?, to toDate: Date?, withPeriodLength length: Int) -> Bool /** Returns selection color for individual cells. - Parameter koyomi: The current Koyomi instance. - Parameter indexPath: The index path of the cell that was selected. - Parameter date: The date representing current item. - Returns: A color for selection background for item at the `indexPath` or nil for default selection color. */ @objc optional func koyomi(_ koyomi: Koyomi, selectionColorForItemAt indexPath: IndexPath, date: Date) -> UIColor? /** Returns selection text color for individual cells. - Parameter koyomi: The current Koyomi instance. - Parameter indexPath: The index path of the cell that was selected. - Parameter date: The date representing current item. - Returns: A text color for the label for item at the `indexPath` or nil for default selection color. */ @objc optional func koyomi(_ koyomi: Koyomi, selectionTextColorForItemAt indexPath: IndexPath, date: Date) -> UIColor? /** Returns font for individual cells. - Parameter koyomi: The current Koyomi instance. - Parameter indexPath: The index path of the cell that was selected. - Parameter date: The date representing current item. - Returns: A font for item at the indexPath or nil for default font. */ @objc optional func koyomi(_ koyomi: Koyomi, fontForItemAt indexPath: IndexPath, date: Date) -> UIFont? } // MARK: - KoyomiStyle - public enum KoyomiStyle { /// Custom tuple to define your own colors instead of using the built-in schemes public typealias CustomColorScheme = (dayBackgrond: UIColor, weekBackgrond: UIColor, week: UIColor, weekday: UIColor, holiday: (saturday: UIColor, sunday: UIColor), otherMonth: UIColor, separator: UIColor) // Basic color case monotone, standard, red, orange, yellow, tealBlue, blue, purple, green, pink // Deep color case deepBlack, deepRed, deepOrange, deepYellow, deepTealBlue, deepBlue, deepPurple, deepGreen, deepPink // Custom case custom(customColor: CustomColorScheme) var colors: Koyomi.Colors { switch self { // Basic color style case .monotone: return .init(dayBackgrond: .white, weekBackgrond: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray)) case .standard: return .init(dayBackgrond: .white, weekBackgrond: .white, holiday: (UIColor.KoyomiColor.blue, UIColor.KoyomiColor.red)) case .red: return .init(dayBackgrond: .white, weekBackgrond: UIColor.KoyomiColor.red, week: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray), separator: UIColor.KoyomiColor.red) case .orange: return .init(dayBackgrond: .white, weekBackgrond: UIColor.KoyomiColor.orange, week: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray), separator: UIColor.KoyomiColor.orange) case .yellow: return .init(dayBackgrond: .white, weekBackgrond: UIColor.KoyomiColor.yellow, week: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray), separator: UIColor.KoyomiColor.yellow) case .tealBlue: return .init(dayBackgrond: .white, weekBackgrond: UIColor.KoyomiColor.tealBlue, week: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray), separator: UIColor.KoyomiColor.tealBlue) case .blue: return .init(dayBackgrond: .white, weekBackgrond: UIColor.KoyomiColor.blue, week: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray), separator: UIColor.KoyomiColor.blue) case .purple: return .init(dayBackgrond: .white, weekBackgrond: UIColor.KoyomiColor.purple, week: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray), separator: UIColor.KoyomiColor.purple) case .green: return .init(dayBackgrond: .white, weekBackgrond: UIColor.KoyomiColor.green, week: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray), separator: UIColor.KoyomiColor.green) case .pink: return .init(dayBackgrond: .white, weekBackgrond: UIColor.KoyomiColor.pink, week: .white, holiday: (UIColor.KoyomiColor.darkGray, UIColor.KoyomiColor.darkGray), separator: UIColor.KoyomiColor.pink) // Deep color style case .deepBlack: return .init(dayBackgrond: UIColor.KoyomiColor.black, weekBackgrond: UIColor.KoyomiColor.black, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.darkBlack) case .deepRed: return .init(dayBackgrond: UIColor.KoyomiColor.red, weekBackgrond: UIColor.KoyomiColor.red, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.orange) case .deepOrange: return .init(dayBackgrond: UIColor.KoyomiColor.orange, weekBackgrond: UIColor.KoyomiColor.orange, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.yellow) case .deepYellow: return .init(dayBackgrond: UIColor.KoyomiColor.yellow, weekBackgrond: UIColor.KoyomiColor.yellow, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.lightYellow) case .deepTealBlue: return .init(dayBackgrond: UIColor.KoyomiColor.tealBlue, weekBackgrond: UIColor.KoyomiColor.tealBlue, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.blue) case .deepBlue: return .init(dayBackgrond: UIColor.KoyomiColor.blue, weekBackgrond: UIColor.KoyomiColor.blue, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.tealBlue) case .deepPurple: return .init(dayBackgrond: UIColor.KoyomiColor.purple, weekBackgrond: UIColor.KoyomiColor.purple, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.lightPurple) case .deepGreen: return .init(dayBackgrond: UIColor.KoyomiColor.green, weekBackgrond: UIColor.KoyomiColor.green, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.lightGreen) case .deepPink: return .init(dayBackgrond: UIColor.KoyomiColor.pink, weekBackgrond: UIColor.KoyomiColor.pink, week: .white, weekday: .white, holiday: (.white, .white), otherMonth: UIColor.KoyomiColor.lightGray, separator: UIColor.KoyomiColor.lightPink) // Custom color style case .custom(let customColor): return .init(dayBackgrond: customColor.dayBackgrond, weekBackgrond: customColor.weekBackgrond, week: customColor.week, weekday: customColor.weekday, holiday: customColor.holiday, otherMonth: customColor.otherMonth, separator: customColor.separator) } } } // MARK: - SelectionMode - public enum SelectionMode { case single(style: Style), multiple(style: Style), sequence(style: SequenceStyle), none public enum SequenceStyle { case background, circle, line, semicircleEdge } public enum Style { case background, circle, line } } // MARK: - ContentPosition - public enum ContentPosition { case topLeft, topCenter, topRight case left, center, right case bottomLeft, bottomCenter, bottomRight case custom(x: CGFloat, y: CGFloat) } // MARK: - Koyomi - @IBDesignable final public class Koyomi: UICollectionView { struct Colors { let dayBackgrond, weekBackgrond: UIColor let week, weekday: UIColor let holiday: (saturday: UIColor, sunday: UIColor) let otherMonth: UIColor let separator: UIColor init(dayBackgrond: UIColor, weekBackgrond: UIColor, week: UIColor = UIColor.KoyomiColor.black, weekday: UIColor = UIColor.KoyomiColor.black, holiday: (saturday: UIColor, sunday: UIColor) = (UIColor.KoyomiColor.blue, UIColor.KoyomiColor.red), otherMonth: UIColor = UIColor.KoyomiColor.lightGray, separator: UIColor = UIColor.KoyomiColor.lightGray) { self.dayBackgrond = dayBackgrond self.weekBackgrond = weekBackgrond self.week = week self.weekday = weekday self.holiday.saturday = holiday.saturday self.holiday.sunday = holiday.sunday self.otherMonth = otherMonth self.separator = separator } } public var style: KoyomiStyle = .standard { didSet { dayBackgrondColor = style.colors.dayBackgrond weekBackgrondColor = style.colors.weekBackgrond weekColor = style.colors.week weekdayColor = style.colors.weekday holidayColor = style.colors.holiday otherMonthColor = style.colors.otherMonth backgroundColor = style.colors.separator sectionSeparator.backgroundColor = style.colors.separator } } public var selectionMode: SelectionMode = .single(style: .circle) { didSet { model.selectionMode = { switch selectionMode { case .single(_): return .single case .multiple(_): return .multiple case .sequence(_): return .sequence case .none: return .none } }() } } public struct LineView { public enum Position { case top, center, bottom } public var height: CGFloat = 1 public var widthRate: CGFloat = 1 public var position: Position = .center } public var lineView: LineView = .init() @IBInspectable public var isHiddenOtherMonth: Bool = false // Layout properties @IBInspectable public var sectionSpace: CGFloat = 1.5 { didSet { sectionSeparator.frame.size.height = sectionSpace } } @IBInspectable public var cellSpace: CGFloat = 0.5 { didSet { if let layout = collectionViewLayout as? KoyomiLayout, layout.cellSpace != cellSpace { setCollectionViewLayout(self.layout, animated: false) } } } @IBInspectable public var weekCellHeight: CGFloat = 25 { didSet { sectionSeparator.frame.origin.y = inset.top + weekCellHeight if let layout = collectionViewLayout as? KoyomiLayout, layout.weekCellHeight != weekCellHeight { setCollectionViewLayout(self.layout, animated: false) } } } @IBInspectable public var circularViewDiameter: CGFloat = 0.75 { didSet { reloadData() } } public var inset: UIEdgeInsets = .zero { didSet { if let layout = collectionViewLayout as? KoyomiLayout, layout.inset != inset { setCollectionViewLayout(self.layout, animated: false) } } } public var dayPosition: ContentPosition = .center public var weekPosition: ContentPosition = .center // Week cell text public var weeks: (String, String, String, String, String, String, String) { get { return model.weeks } set { model.weeks = newValue reloadData() } } @IBInspectable public var currentDateFormat: String = "M/yyyy" // Color properties of the appearance @IBInspectable public var sectionSeparatorColor: UIColor = UIColor.KoyomiColor.lightGray { didSet { sectionSeparator.backgroundColor = sectionSeparatorColor } } @IBInspectable public var separatorColor: UIColor = UIColor.KoyomiColor.lightGray { didSet { backgroundColor = separatorColor } } @IBInspectable public var weekColor: UIColor = UIColor.KoyomiColor.black @IBInspectable public var weekdayColor: UIColor = UIColor.KoyomiColor.black @IBInspectable public var otherMonthColor: UIColor = UIColor.KoyomiColor.lightGray @IBInspectable public var dayBackgrondColor: UIColor = .white @IBInspectable public var weekBackgrondColor: UIColor = .white public var holidayColor: (saturday: UIColor, sunday: UIColor) = (UIColor.KoyomiColor.blue, UIColor.KoyomiColor.red) @IBInspectable public var selectedStyleColor: UIColor = UIColor.KoyomiColor.red public enum SelectedTextState { case change(UIColor), keeping } public var selectedDayTextState: SelectedTextState = .change(.white) // KoyomiDelegate public weak var calendarDelegate: KoyomiDelegate? // Fileprivate properties fileprivate var highlightedDayColor = UIColor.KoyomiColor.black fileprivate var highlightedDayBackgrondColor: UIColor = .white fileprivate lazy var model: DateModel = .init() fileprivate let sectionSeparator: UIView = .init() fileprivate var layout: UICollectionViewLayout { return KoyomiLayout(inset: inset, cellSpace: cellSpace, sectionSpace: sectionSpace, weekCellHeight: weekCellHeight) } fileprivate var dayLabelFont: UIFont? fileprivate var weekLabelFont: UIFont? // MARK: - Initialization - required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() collectionViewLayout = layout } // Internal initializer for @IBDesignable override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) } public init(frame: CGRect, sectionSpace: CGFloat = 1.5, cellSpace: CGFloat = 0.5, inset: UIEdgeInsets = .zero, weekCellHeight: CGFloat = 25) { super.init(frame: frame, collectionViewLayout: KoyomiLayout(inset: inset, cellSpace: cellSpace, sectionSpace: sectionSpace, weekCellHeight: weekCellHeight)) self.sectionSpace = sectionSpace self.cellSpace = cellSpace self.inset = inset self.weekCellHeight = weekCellHeight configure() } // MARK: - Public Methods - public func display(in month: MonthType) { model.display(in: month) reloadData() calendarDelegate?.koyomi?(self, currentDateString: model.dateString(in: .current, withFormat: currentDateFormat)) } @discardableResult public func setDayFont(fontName name: String = ".SFUIText-Medium", size: CGFloat) -> Self { dayLabelFont = UIFont(name: name, size: size) return self } @discardableResult public func setWeekFont(fontName name: String = ".SFUIText-Medium", size: CGFloat) -> Self { weekLabelFont = UIFont(name: name, size: size) return self } public func currentDateString(withFormat format: String = "M/yyyy") -> String { return model.dateString(in: .current, withFormat: format) } @discardableResult public func select(date: Date, to toDate: Date? = nil) -> Self { model.select(from: date, to: toDate) return self } @discardableResult public func select(dates: [Date]) -> Self { dates.forEach { [weak self] date in self?.select(date: date) } return self } @discardableResult public func unselect(date: Date, to toDate: Date? = nil) -> Self { model.unselect(from: date, to: toDate) return self } @discardableResult public func unselect(dates: [Date]) -> Self { dates.forEach { [weak self] date in self?.unselect(date: date) } return self } @discardableResult public func unselectAll() -> Self { model.unselectAll() return self } @discardableResult public func setDayColor(_ dayColor: UIColor, of date: Date, to toDate: Date? = nil) -> Self { model.setHighlightedDates(from: date, to: toDate) highlightedDayColor = dayColor return self } @discardableResult public func setDayBackgrondColor(_ backgroundColor: UIColor, of date: Date, to toDate: Date? = nil) -> Self { model.setHighlightedDates(from: date, to: toDate) highlightedDayBackgrondColor = backgroundColor return self } // MARK: - Override Method - override public func reloadData() { super.reloadData() setCollectionViewLayout(layout, animated: false) } override public func layoutSubviews() { super.layoutSubviews() sectionSeparator.frame = CGRect(x: inset.left, y: inset.top + weekCellHeight, width: frame.width - (inset.top + inset.left), height: sectionSpace) } } // MARK: - Private Methods - private extension Koyomi { func configure() { delegate = self dataSource = self isScrollEnabled = false backgroundColor = separatorColor register(KoyomiCell.self, forCellWithReuseIdentifier: KoyomiCell.identifier) sectionSeparator.backgroundColor = sectionSeparatorColor addSubview(sectionSeparator) } func configure(_ cell: KoyomiCell, at indexPath: IndexPath) { // Appearance properties let style: KoyomiCell.CellStyle let textColor: UIColor let isSelected: Bool let backgroundColor: UIColor let font: UIFont? let content: String let postion: ContentPosition let date = model.date(at: indexPath) if indexPath.section == 0 { // Configure appearance properties for week cell style = .standard textColor = weekColor isSelected = false backgroundColor = weekBackgrondColor font = weekLabelFont content = model.week(at: indexPath.row) postion = weekPosition } else { // Configure appearance properties for day cell isSelected = model.isSelect(with: indexPath) textColor = { var baseColor: UIColor { if let beginning = model.indexAtBeginning(in: .current), indexPath.row < beginning { return otherMonthColor } else if let end = model.indexAtEnd(in: .current), indexPath.row > end { return otherMonthColor } else if let type = DateModel.WeekType(indexPath), type == .sunday { return holidayColor.sunday } else if let type = DateModel.WeekType(indexPath), type == .saturday { return holidayColor.saturday } else { return weekdayColor } } if isSelected { switch selectedDayTextState { case .change(let color): return color case .keeping: return baseColor } } else if model.isHighlighted(with: indexPath) { return highlightedDayColor } else { return baseColor } }() style = { var sequencePosition: KoyomiCell.CellStyle.SequencePosition { let date = model.date(at: indexPath) if let start = model.sequenceDates.start, let _ = model.sequenceDates.end , date == start { return .left } else if let _ = model.sequenceDates.start, let end = model.sequenceDates.end , date == end { return .right } else { return .middle } } switch (selectionMode, isSelected) { //Not selected or background style of single, multiple, sequence mode case (_, false), (.single(style: .background), true), (.multiple(style: .background), true), (.sequence(style: .background), true): return .standard //Selected and circle style of single, multiple, sequence mode case (.single(style: .circle), true), (.multiple(style: .circle), true), (.sequence(style: .circle), true): return .circle //Selected and sequence mode, semicircleEdge style case (.sequence(style: .semicircleEdge), true): return .semicircleEdge(position: sequencePosition) case (.single(style: .line), true), (.multiple(style: .line), true): // Position is always nil. return .line(position: nil) case (.sequence(style: .line), true): return .line(position: sequencePosition) default: return .standard } }() backgroundColor = model.isHighlighted(with: indexPath) ? highlightedDayBackgrondColor : dayBackgrondColor font = calendarDelegate?.koyomi?(self, fontForItemAt: indexPath, date: date) ?? dayLabelFont content = model.dayString(at: indexPath, isHiddenOtherMonth: isHiddenOtherMonth) postion = dayPosition } // Set cell to appearance properties cell.content = content cell.textColor = { if isSelected { return calendarDelegate?.koyomi?(self, selectionTextColorForItemAt: indexPath, date: date) ?? textColor } else { return textColor } }() cell.contentPosition = postion cell.circularViewDiameter = circularViewDiameter let selectionColor: UIColor = { if isSelected { return calendarDelegate?.koyomi?(self, selectionColorForItemAt: indexPath, date: date) ?? selectedStyleColor } else { return selectedStyleColor } }() if case .line = style { cell.lineViewAppearance = lineView } if let font = font { cell.setContentFont(fontName: font.fontName, size: font.pointSize) } cell.configureAppearanse(of: style, withColor: selectionColor, backgroundColor: backgroundColor, isSelected: isSelected) } } // MARK: - UICollectionViewDelegate - extension Koyomi: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard indexPath.section != 0 else { return } // Other month if isHiddenOtherMonth && model.isOtherMonth(at: indexPath) { return } // KoyomiDelegate properties let date: Date? let toDate: Date? let length: Int switch selectionMode { case .single(_), .multiple(_): date = model.date(at: indexPath) toDate = nil length = 1 case .sequence(_): let willSelectDates = model.willSelectDates(with: indexPath) date = willSelectDates.from toDate = willSelectDates.to length = model.selectedPeriodLength(with: indexPath) case .none: return } if calendarDelegate?.koyomi?(self, shouldSelectDates: date, to: toDate, withPeriodLength: length) == false { return } model.select(with: indexPath) reloadData() calendarDelegate?.koyomi?(self, didSelect: date, forItemAt: indexPath) } } // MARK: - UICollectionViewDataSource - extension Koyomi: UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return section == 0 ? DateModel.dayCountPerRow : DateModel.maxCellCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KoyomiCell.identifier, for: indexPath) as? KoyomiCell else { return .init() } configure(cell, at: indexPath) return cell } }
mit
d41980a55e9592359ea6904aaac7a4f7
42.685524
356
0.638202
4.577232
false
false
false
false
jgonfer/JGFLabRoom
JGFLabRoom/Controller/Information Access/OAuth/SocialViewController.swift
1
2388
// // SocialViewController.swift // JGFLabRoom // // Created by Josep González on 20/1/16. // Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved. // import UIKit class SocialViewController: UITableViewController { var networkSelected: SNetworks? var results = SNetworks.titles var segues = SNetworks.segues override func viewDidLoad() { super.viewDidLoad() setupController() } private func setupController() { Utils.registerStandardXibForTableView(tableView, name: "cell") Utils.cleanBackButtonTitle(navigationController) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let vcToShow = segue.destinationViewController as? SocialOptionsViewController { vcToShow.networkSelected = networkSelected } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 55 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let reuseIdentifier = "cell" var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) if (cell != nil) { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier) } cell!.textLabel!.text = results[indexPath.row] cell?.accessoryType = .None if let _ = segues[indexPath.row] { cell?.accessoryType = .DisclosureIndicator } return cell! } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) networkSelected = SNetworks.types[indexPath.row] performSegueWithIdentifier(kSegueIdSocialOptions, sender: tableView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
74ae9fc214cb59752943c875ee951fe9
32.138889
118
0.678122
5.548837
false
false
false
false
apple/swift-corelibs-foundation
Sources/FoundationNetworking/URLSession/TransferState.swift
1
8554
// Foundation/URLSession/TransferState.swift - URLSession & libcurl // // 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 // // ----------------------------------------------------------------------------- /// /// The state of a single transfer. /// These are libcurl helpers for the URLSession API code. /// - SeeAlso: https://curl.haxx.se/libcurl/c/ /// - SeeAlso: URLSession.swift /// // ----------------------------------------------------------------------------- #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import SwiftFoundation #else import Foundation #endif @_implementationOnly import CoreFoundation extension _NativeProtocol { /// State related to an ongoing transfer. /// /// This contains headers received so far, body data received so far, etc. /// /// There's a strict 1-to-1 relationship between an `EasyHandle` and a /// `TransferState`. /// /// - TODO: Might move the `EasyHandle` into this `struct` ? /// - SeeAlso: `URLSessionTask.EasyHandle` internal struct _TransferState { /// The URL that's being requested let url: URL /// Raw headers received. let parsedResponseHeader: _ParsedResponseHeader /// Once the headers is complete, this will contain the response var response: URLResponse? /// The body data to be sent in the request let requestBodySource: _BodySource? /// Body data received let bodyDataDrain: _DataDrain /// Describes what to do with received body data for this transfer: } } extension _NativeProtocol { enum _DataDrain { /// Concatenate in-memory case inMemory(NSMutableData?) /// Write to file case toFile(URL, FileHandle?) /// Do nothing. Might be forwarded to delegate case ignore } } extension _NativeProtocol._TransferState { /// Transfer state that can receive body data, but will not send body data. init(url: URL, bodyDataDrain: _NativeProtocol._DataDrain) { self.url = url self.parsedResponseHeader = _NativeProtocol._ParsedResponseHeader() self.response = nil self.requestBodySource = nil self.bodyDataDrain = bodyDataDrain } /// Transfer state that sends body data and can receive body data. init(url: URL, bodyDataDrain: _NativeProtocol._DataDrain, bodySource: _BodySource) { self.url = url self.parsedResponseHeader = _NativeProtocol._ParsedResponseHeader() self.response = nil self.requestBodySource = bodySource self.bodyDataDrain = bodyDataDrain } } // specific to HTTP protocol extension _HTTPURLProtocol._TransferState { /// Appends a header line /// /// Will set the complete response once the header is complete, i.e. the /// return value's `isHeaderComplete` will then by `true`. /// /// - Throws: When a parsing error occurs func byAppendingHTTP(headerLine data: Data) throws -> _NativeProtocol._TransferState { // If the line is empty, it marks the end of the header, and the result // is a complete header. Otherwise it's a partial header. // - Note: Appending a line to a complete header results in a partial // header with just that line. func isCompleteHeader(_ headerLine: String) -> Bool { return headerLine.isEmpty } guard let h = parsedResponseHeader.byAppending(headerLine: data, onHeaderCompleted: isCompleteHeader) else { throw _Error.parseSingleLineError } if case .complete(let lines) = h { // Header is complete let response = lines.createHTTPURLResponse(for: url) guard response != nil else { throw _Error.parseCompleteHeaderError } return _NativeProtocol._TransferState(url: url, parsedResponseHeader: _NativeProtocol._ParsedResponseHeader(), response: response, requestBodySource: requestBodySource, bodyDataDrain: bodyDataDrain) } else { return _NativeProtocol._TransferState(url: url, parsedResponseHeader: h, response: nil, requestBodySource: requestBodySource, bodyDataDrain: bodyDataDrain) } } } // specific to FTP extension _FTPURLProtocol._TransferState { enum FTPHeaderCode: Int { case transferCompleted = 226 case openDataConnection = 150 case fileStatus = 213 case syntaxError = 500// 500 series FTP Syntax errors case errorOccurred = 400 // 400 Series FTP transfer errors } /// Appends a header line /// /// Will set the complete response once the header is complete, i.e. the /// return value's `isHeaderComplete` will then by `true`. /// /// - Throws: When a parsing error occurs func byAppendingFTP(headerLine data: Data, expectedContentLength: Int64) throws -> _NativeProtocol._TransferState { guard let line = String(data: data, encoding: String.Encoding.utf8) else { fatalError("Data on command port is nil") } //FTP Status code 226 marks the end of the transfer if (line.starts(with: String(FTPHeaderCode.transferCompleted.rawValue))) { return self } //FTP Status code 213 marks the end of the header and start of the //transfer on data port func isCompleteHeader(_ headerLine: String) -> Bool { return headerLine.starts(with: String(FTPHeaderCode.openDataConnection.rawValue)) } guard let h = parsedResponseHeader.byAppending(headerLine: data, onHeaderCompleted: isCompleteHeader) else { throw _NativeProtocol._Error.parseSingleLineError } if case .complete(let lines) = h { let response = lines.createURLResponse(for: url, contentLength: expectedContentLength) guard response != nil else { throw _NativeProtocol._Error.parseCompleteHeaderError } return _NativeProtocol._TransferState(url: url, parsedResponseHeader: _NativeProtocol._ParsedResponseHeader(), response: response, requestBodySource: requestBodySource, bodyDataDrain: bodyDataDrain) } else { return _NativeProtocol._TransferState(url: url, parsedResponseHeader: _NativeProtocol._ParsedResponseHeader(), response: nil, requestBodySource: requestBodySource, bodyDataDrain: bodyDataDrain) } } } extension _NativeProtocol._TransferState { enum _Error: Error { case parseSingleLineError case parseCompleteHeaderError } var isHeaderComplete: Bool { return response != nil } /// Append body data /// /// - Important: This will mutate the existing `NSMutableData` that the /// struct may already have in place -- copying the data is too /// expensive. This behaviour func byAppending(bodyData buffer: Data) -> _NativeProtocol._TransferState { switch bodyDataDrain { case .inMemory(let bodyData): let data: NSMutableData = bodyData ?? NSMutableData() data.append(buffer) let drain = _NativeProtocol._DataDrain.inMemory(data) return _NativeProtocol._TransferState(url: url, parsedResponseHeader: parsedResponseHeader, response: response, requestBodySource: requestBodySource, bodyDataDrain: drain) case .toFile(_, let fileHandle): //TODO: Create / open the file for writing // Append to the file _ = fileHandle!.seekToEndOfFile() fileHandle!.write(buffer) return self case .ignore: return self } } /// Sets the given body source on the transfer state. /// /// This can be used to either set the initial body source, or to reset it /// e.g. when restarting a transfer. func bySetting(bodySource newSource: _BodySource) -> _NativeProtocol._TransferState { return _NativeProtocol._TransferState(url: url, parsedResponseHeader: parsedResponseHeader, response: response, requestBodySource: newSource, bodyDataDrain: bodyDataDrain) } }
apache-2.0
54f047e46f25673ce486e4b00a77e426
40.931373
210
0.642039
5.088638
false
false
false
false
practicalswift/swift
test/TBD/multi-file.swift
8
3735
// RUN: %empty-directory(%t) // -Onone, non-resilient // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-library -o %t/JustForTBDValidation %s %S/Inputs/multi-file2.swift -wmo -Xfrontend -validate-tbd-against-ir=all // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-library -o %t/JustForTBDValidation %s %S/Inputs/multi-file2.swift -Xfrontend -validate-tbd-against-ir=all // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-tbd-path %t/TBD-wmo.tbd -emit-module-path %t/multifile.swiftmodule %s %S/Inputs/multi-file2.swift -wmo // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-tbd-path %t/TBD-incremental.tbd -emit-module-path %t/multifile.swiftmodule %s %S/Inputs/multi-file2.swift // RUN: diff %t/TBD-wmo.tbd %t/TBD-incremental.tbd // -O, non-resilient // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-library -o %t/JustForTBDValidation %s %S/Inputs/multi-file2.swift -wmo -O -Xfrontend -validate-tbd-against-ir=all // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-library -o %t/JustForTBDValidation %s %S/Inputs/multi-file2.swift -O -Xfrontend -validate-tbd-against-ir=all // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-tbd-path %t/TBD-wmo.tbd -emit-module-path %t/multifile.swiftmodule %s %S/Inputs/multi-file2.swift -wmo -O // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-tbd-path %t/TBD-incremental.tbd -emit-module-path %t/multifile.swiftmodule %s %S/Inputs/multi-file2.swift -O // RUN: diff %t/TBD-wmo.tbd %t/TBD-incremental.tbd // -Onone, resilient // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-library -o %t/JustForTBDValidation %s %S/Inputs/multi-file2.swift -wmo -Xfrontend -enable-resilience -Xfrontend -validate-tbd-against-ir=all // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-library -o %t/JustForTBDValidation %s %S/Inputs/multi-file2.swift -Xfrontend -enable-resilience -Xfrontend -validate-tbd-against-ir=all // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-tbd-path %t/TBD-wmo.tbd -emit-module-path %t/multifile.swiftmodule %s %S/Inputs/multi-file2.swift -wmo -Xfrontend -enable-resilience // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-tbd-path %t/TBD-incremental.tbd -emit-module-path %t/multifile.swiftmodule %s %S/Inputs/multi-file2.swift -Xfrontend -enable-resilience // RUN: diff %t/TBD-wmo.tbd %t/TBD-incremental.tbd // -O, resilient // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-library -o %t/JustForTBDValidation %s %S/Inputs/multi-file2.swift -wmo -O -Xfrontend -enable-resilience -Xfrontend -validate-tbd-against-ir=all // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-library -o %t/JustForTBDValidation %s %S/Inputs/multi-file2.swift -O -Xfrontend -enable-resilience -Xfrontend -validate-tbd-against-ir=all // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-tbd-path %t/TBD-wmo.tbd -emit-module-path %t/multifile.swiftmodule %s %S/Inputs/multi-file2.swift -wmo -O -Xfrontend -enable-resilience // RUN: %target-build-swift -swift-version 4 -module-name multifile -emit-tbd-path %t/TBD-incremental.tbd -emit-module-path %t/multifile.swiftmodule %s %S/Inputs/multi-file2.swift -O -Xfrontend -enable-resilience // RUN: diff %t/TBD-wmo.tbd %t/TBD-incremental.tbd // REQUIRES: objc_interop public func function() {} public class Class { public var property: Int public var propertyWithInit: Int = 0 public init() { property = 0 } public static func staticFunc(default_: Int = 0) {} }
apache-2.0
1071f5b1ccc7e968196a7fce5f0cce51
69.471698
217
0.745917
3.039056
false
false
false
false
Daij-Djan/DDUtils
swift/ddutils-common/model/ReflectionHelper [osx + ios]/ReflectionHelperDemo/TestDummyForBothDemos.swift
2
1171
import Foundation class TestDummy : NSObject{ class Inner { var test = "String" } enum TestMe : Int { case X = 1 case Y = 2 } /** Property that sets the NSLocale used by formatters of this type. It defaults to enUSPOSIX */ ///not using new Locale! var locale = NSLocale(localeIdentifier: "en_US_POSIX") var addressLine1: String? = "adasdLine1" var addressLine2: String? = "tempLine2" var addressMatch: Bool? = true var inner = Inner() var test : TestMe? = TestMe.X var decimalTest : Double = { let numFormatter = NumberFormatter() numFormatter.numberStyle = NumberFormatter.Style.decimal numFormatter.locale = Locale(identifier: "en_US_POSIX") let str = UnsafePointer<CChar>("12.34") let value = "12.34"//String(validatingUTF8:UnsafeRawPointer(str).assumingMemoryBound(to: Int8.self))! let trimmed = value.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines) let d = numFormatter.number(from:trimmed)!.doubleValue let n = NSNumber(value: d) return d }() }
mit
a73ce08aef706b181eed829bb8add2c1
26.880952
109
0.619129
4.418868
false
true
false
false
Paulinechi/Swift-Pauline
day3/day3 递归 recursion.playground/section-1.swift
1
881
class Recursion { func printNumber(N: Int){ print(N) if N > 1{ printNumber(N - 1) } //println(N) } } var tempR = Recursion() tempR.printNumber(5) // func fibonacci(i: Int) -> Int { if i <= 2{ return 1 }else { return fibonacci(i - 1) + fibonacci(i - 2) } } fibonacci(5) // func factorial(i: Int) -> Int { if i == 1 { return 1 }else{ return i * factorial(i - 1) } } factorial(20) // func pow(x: Int, y: Int) -> Int { if(y == 0){ return 1 }else{ return x * pow(x, y-1) } } pow(3, 1) // func gongyue(a: Int , b:Int ) -> Int { if b == 0{ return a } else { if a > b { return gongyue(a - b, b) } else{ return gongyue(a,b - a) } } } gongyue(28 , 35)
mit
5c5ac825ae78d09a0a8eb7ce2f711413
9.244186
50
0.424518
2.917219
false
false
false
false
vector-im/riot-ios
Riot/Modules/KeyVerification/Device/Start/DeviceVerificationStartCoordinator.swift
2
3236
// File created from ScreenTemplate // $ createScreen.sh DeviceVerification/Start DeviceVerificationStart /* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class DeviceVerificationStartCoordinator: DeviceVerificationStartCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private var deviceVerificationStartViewModel: DeviceVerificationStartViewModelType private let deviceVerificationStartViewController: DeviceVerificationStartViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: DeviceVerificationStartCoordinatorDelegate? // MARK: - Setup init(session: MXSession, otherUser: MXUser, otherDevice: MXDeviceInfo) { self.session = session let deviceVerificationStartViewModel = DeviceVerificationStartViewModel(session: self.session, otherUser: otherUser, otherDevice: otherDevice) let deviceVerificationStartViewController = DeviceVerificationStartViewController.instantiate(with: deviceVerificationStartViewModel) self.deviceVerificationStartViewModel = deviceVerificationStartViewModel self.deviceVerificationStartViewController = deviceVerificationStartViewController } // MARK: - Public methods func start() { self.deviceVerificationStartViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.deviceVerificationStartViewController } } // MARK: - DeviceVerificationStartViewModelCoordinatorDelegate extension DeviceVerificationStartCoordinator: DeviceVerificationStartViewModelCoordinatorDelegate { func deviceVerificationStartViewModelDidUseLegacyVerification(_ viewModel: DeviceVerificationStartViewModelType) { self.delegate?.deviceVerificationStartCoordinatorDidCancel(self) } func deviceVerificationStartViewModel(_ viewModel: DeviceVerificationStartViewModelType, didCompleteWithOutgoingTransaction transaction: MXSASTransaction) { self.delegate?.deviceVerificationStartCoordinator(self, didCompleteWithOutgoingTransaction: transaction) } func deviceVerificationStartViewModel(_ viewModel: DeviceVerificationStartViewModelType, didTransactionCancelled transaction: MXSASTransaction) { self.delegate?.deviceVerificationStartCoordinator(self, didTransactionCancelled: transaction) } func deviceVerificationStartViewModelDidCancel(_ viewModel: DeviceVerificationStartViewModelType) { self.delegate?.deviceVerificationStartCoordinatorDidCancel(self) } }
apache-2.0
a70b004b4fe4a0ddf9b0019faec8c5d5
40.487179
160
0.782756
6.175573
false
false
false
false
maxoly/PulsarKit
PulsarKit/PulsarKit/Sources/Plugin/Plugins/KeyboardHandlerPlugin.swift
1
4902
// // KeyboardHandlerPlugin.swift // PulsarKit // // Created by Massimo Oliviero on 25/08/2018. // Copyright © 2019 Nacoon. All rights reserved. // import UIKit open class KeyboardHandlerPlugin: SourcePlugin { public var filter: SourcePluginFilter? { nil } public var events: SourcePluginEvents? { nil } public var lifecycle: SourcePluginLifecycle? { self } private weak var container: UIScrollView? private var keyboardSize: CGSize = .zero public init() {} } extension KeyboardHandlerPlugin: SourcePluginLifecycle { public func activate(in container: UIScrollView) { self.container = container NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } public func deactivate() { NotificationCenter.default.removeObserver(self) } } extension KeyboardHandlerPlugin { @objc func keyboardWillShow(_ notification: Foundation.Notification) { guard let container = container else { return } guard keyboardSize == .zero else { return } guard let window = container.window else { return } guard let firstResponder = container.firstResponder else { return } guard let superview = container.superview else { return } guard firstResponder.isDescendant(of: superview) else { return } guard let info = notification.userInfo else { return } guard let keyboardRectValue = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } guard let animationCurveValue = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber else { return } guard let animationDurationValue = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber else { return } let keyboardRect = keyboardRectValue.cgRectValue let animationCurve = animationCurveValue.intValue let animationDuration = animationDurationValue.doubleValue guard let animation = UIView.AnimationCurve(rawValue: animationCurve) else { return } keyboardSize = keyboardRect.size if let responder = firstResponder as? UITextField, let view = responder.inputAccessoryView { keyboardSize.height += view.frame.height } if let responder = firstResponder as? UITextView, let view = responder.inputAccessoryView { keyboardSize.height += view.frame.height } var inset = container.contentInset inset.bottom += self.keyboardSize.height let boundsWindow = window.convert(firstResponder.bounds, from: firstResponder) let remain = window.bounds.height - inset.bottom let vertical = remain >= boundsWindow.maxY ? container.contentOffset.y : (container.contentOffset.y - (remain - boundsWindow.maxY)) let options: UIView.AnimationOptions = [.beginFromCurrentState, animation.toAnimationOptions] UIView.animate(withDuration: animationDuration, delay: 0, options: options, animations: { container.contentInset = inset container.scrollIndicatorInsets = inset if container.contentOffset.y != vertical { container.setContentOffset(CGPoint(x: 0, y: vertical), animated: true) } }, completion: { _ in }) } @objc func keyboardWillHide(_ notification: Foundation.Notification) { guard let container = container else { return } guard keyboardSize != .zero else { return } guard container.window != nil else { return } if container.contentInset.bottom == 0 { return } guard let info = notification.userInfo else { return } guard let animationCurveValue = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber else { return } guard let animationDurationValue = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber else { return } let animationCurve = animationCurveValue.intValue let animationDuration = animationDurationValue.doubleValue guard let animation = UIView.AnimationCurve(rawValue: animationCurve) else { return } var inset = container.contentInset inset.bottom -= self.keyboardSize.height self.keyboardSize = .zero let options: UIView.AnimationOptions = [.beginFromCurrentState, animation.toAnimationOptions] UIView.animate(withDuration: animationDuration, delay: 0, options: options, animations: { container.contentInset = inset container.scrollIndicatorInsets = inset }, completion: { _ in }) } }
mit
a77ed3550953af652827ac04f2da1869
45.235849
156
0.690063
5.562997
false
false
false
false
tensorflow/examples
lite/examples/object_detection/ios/ObjectDetection/ViewControllers/InferenceViewController.swift
1
8859
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit // MARK: InferenceViewControllerDelegate Method Declarations protocol InferenceViewControllerDelegate { /// Called when the user has changed the model settings. The delegate needs to subsequently /// perform the action on the TFLite model. func viewController( _ viewController: InferenceViewController, didReceiveAction action: InferenceViewController.Action) } class InferenceViewController: UIViewController { enum Action { case changeThreadCount(Int) case changeScoreThreshold(Float) case changeMaxResults(Int) case changeModel(ModelType) } // MARK: Sections and Information to display private enum InferenceSections: Int, CaseIterable { case InferenceInfo } private enum InferenceInfo: Int, CaseIterable { case Resolution case InferenceTime func displayString() -> String { var toReturn = "" switch self { case .Resolution: toReturn = "Resolution" case .InferenceTime: toReturn = "Inference Time" } return toReturn } } // MARK: Storyboard Outlets @IBOutlet weak var tableView: UITableView! @IBOutlet weak var threadStepper: UIStepper! @IBOutlet weak var threadValueLabel: UILabel! @IBOutlet weak var maxResultStepper: UIStepper! @IBOutlet weak var maxResultLabel: UILabel! @IBOutlet weak var thresholdStepper: UIStepper! @IBOutlet weak var thresholdLabel: UILabel! @IBOutlet weak var modelTextField: UITextField! // MARK: Constants private let normalCellHeight: CGFloat = 27.0 private let separatorCellHeight: CGFloat = 42.0 private let bottomSpacing: CGFloat = 21.0 private let bottomSheetButtonDisplayHeight: CGFloat = 60.0 private let infoTextColor = UIColor.black private let lightTextInfoColor = UIColor( displayP3Red: 117.0 / 255.0, green: 117.0 / 255.0, blue: 117.0 / 255.0, alpha: 1.0) private let infoFont = UIFont.systemFont(ofSize: 14.0, weight: .regular) private let highlightedFont = UIFont.systemFont(ofSize: 14.0, weight: .medium) // MARK: Instance Variables var inferenceTime: Double = 0 var resolution: CGSize = CGSize.zero var currentThreadCount: Int = 0 var scoreThreshold: Float = 0.5 var maxResults: Int = 3 var modelSelectIndex: Int = 0 private var modelSelect: ModelType { if modelSelectIndex < ModelType.allCases.count { return ModelType.allCases[modelSelectIndex] } else { return .ssdMobileNetV1 } } // MARK: Delegate var delegate: InferenceViewControllerDelegate? // MARK: Computed properties var collapsedHeight: CGFloat { return bottomSheetButtonDisplayHeight } override func viewDidLoad() { super.viewDidLoad() setupUI() } // MARK: private func private func setupUI() { threadStepper.value = Double(currentThreadCount) threadValueLabel.text = "\(currentThreadCount)" maxResultStepper.value = Double(maxResults) maxResultLabel.text = "\(maxResults)" thresholdStepper.value = Double(scoreThreshold) thresholdLabel.text = "\(scoreThreshold)" modelTextField.text = modelSelect.title let picker = UIPickerView() picker.delegate = self picker.dataSource = self modelTextField.inputView = picker let doneButton = UIButton( frame: CGRect( x: 0, y: 0, width: 60, height: 44)) doneButton.setTitle("Done", for: .normal) doneButton.setTitleColor(.blue, for: .normal) doneButton.addTarget( self, action: #selector(choseModelDoneButtonTouchUpInside(_:)), for: .touchUpInside) let inputAccessoryView = UIView( frame: CGRect( x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44)) inputAccessoryView.backgroundColor = .gray inputAccessoryView.addSubview(doneButton) modelTextField.inputAccessoryView = inputAccessoryView } // MARK: Button Actions /// Delegate the change of number of threads to ViewController and change the stepper display. @IBAction func threadStepperValueChanged(_ sender: UIStepper) { currentThreadCount = Int(sender.value) delegate?.viewController(self, didReceiveAction: .changeThreadCount(currentThreadCount)) threadValueLabel.text = "\(currentThreadCount)" } @IBAction func thresholdStepperValueChanged(_ sender: UIStepper) { scoreThreshold = Float(sender.value) delegate?.viewController(self, didReceiveAction: .changeScoreThreshold(scoreThreshold)) thresholdLabel.text = "\(scoreThreshold)" } @IBAction func maxResultStepperValueChanged(_ sender: UIStepper) { maxResults = Int(sender.value) delegate?.viewController(self, didReceiveAction: .changeMaxResults(maxResults)) maxResultLabel.text = "\(maxResults)" } @objc func choseModelDoneButtonTouchUpInside(_ sender: UIButton) { delegate?.viewController(self, didReceiveAction: .changeModel(modelSelect)) modelTextField.text = modelSelect.title modelTextField.resignFirstResponder() } } // MARK: UITableView Data Source extension InferenceViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return InferenceSections.allCases.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let inferenceSection = InferenceSections(rawValue: section) else { return 0 } var rowCount = 0 switch inferenceSection { case .InferenceInfo: rowCount = InferenceInfo.allCases.count } return rowCount } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { var height: CGFloat = 0.0 guard let inferenceSection = InferenceSections(rawValue: indexPath.section) else { return height } switch inferenceSection { case .InferenceInfo: if indexPath.row == InferenceInfo.allCases.count - 1 { height = separatorCellHeight + bottomSpacing } else { height = normalCellHeight } } return height } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "INFO_CELL") as! InfoCell guard let inferenceSection = InferenceSections(rawValue: indexPath.section) else { return cell } var fieldName = "" var info = "" switch inferenceSection { case .InferenceInfo: let tuple = displayStringsForInferenceInfo(atRow: indexPath.row) fieldName = tuple.0 info = tuple.1 } cell.fieldNameLabel.font = infoFont cell.fieldNameLabel.textColor = infoTextColor cell.fieldNameLabel.text = fieldName cell.infoLabel.text = info return cell } // MARK: Format Display of information in the bottom sheet /** This method formats the display of additional information relating to the inferences. */ func displayStringsForInferenceInfo(atRow row: Int) -> (String, String) { var fieldName: String = "" var info: String = "" guard let inferenceInfo = InferenceInfo(rawValue: row) else { return (fieldName, info) } fieldName = inferenceInfo.displayString() switch inferenceInfo { case .Resolution: info = "\(Int(resolution.width))x\(Int(resolution.height))" case .InferenceTime: info = String(format: "%.2fms", inferenceTime) } return (fieldName, info) } } extension InferenceViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return ModelType.allCases.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if row < ModelType.allCases.count { return ModelType.allCases[row].title } else { return nil } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { modelSelectIndex = row } } class InfoCell: UITableViewCell { @IBOutlet weak var fieldNameLabel: UILabel! @IBOutlet weak var infoLabel: UILabel! }
apache-2.0
67f864bc99c47d9628babf9125a7d8d0
28.53
98
0.714866
4.707226
false
false
false
false
robrix/Madness
Madness/Repetition.swift
1
4157
// Copyright (c) 2015 Rob Rix. All rights reserved. /// Parser `parser` 1 or more times. public func some<C: Collection, T> (_ parser: @escaping Parser<C, T>.Function) -> Parser<C, [T]>.Function { return prepend <^> require(parser) <*> many(parser) } /// Parses 1 or more `parser` separated by `separator`. public func sepBy1<C: Collection, T, U>(_ parser: @escaping Parser<C, T>.Function, _ separator: @escaping Parser<C, U>.Function) -> Parser<C, [T]>.Function { return prepend <^> parser <*> many(separator *> parser) } /// Parses 0 or more `parser` separated by `separator`. public func sepBy<C: Collection, T, U>(_ parser: @escaping Parser<C, T>.Function, _ separator: @escaping Parser<C, U>.Function) -> Parser<C, [T]>.Function { return sepBy1(parser, separator) <|> pure([]) } /// Parses 1 or more `parser` ended by `terminator`. public func endBy1<C: Collection, T, U>(_ parser: @escaping Parser<C, T>.Function, _ terminator: @escaping Parser<C, U>.Function) -> Parser<C, [T]>.Function { return some(parser <* terminator) } /// Parses 0 or more `parser` ended by `terminator`. public func endBy<C: Collection, T, U>(_ parser: @escaping Parser<C, T>.Function, _ terminator: @escaping Parser<C, U>.Function) -> Parser<C, [T]>.Function { return many(parser <* terminator) } /// Parses `parser` the number of times specified in `interval`. /// /// \param interval An interval specifying the number of repetitions to perform. `0...n` means at most `n` repetitions; `m...Int.max` means at least `m` repetitions; and `m...n` means between `m` and `n` repetitions (inclusive). public func * <C: Collection, T> (parser: @escaping Parser<C, T>.Function, interval: CountableClosedRange<Int>) -> Parser<C, [T]>.Function { if interval.upperBound <= 0 { return { .success(([], $1)) } } return (parser >>- { x in { [x] + $0 } <^> (parser * decrement(interval)) }) <|> { interval.lowerBound <= 0 ? .success(([], $1)) : .failure(.leaf("expected at least \(interval.lowerBound) matches", $1)) } } /// Parses `parser` exactly `n` times. /// /// `n` must be > 0 to make any sense. public func * <C: Collection, T> (parser: @escaping Parser<C, T>.Function, n: Int) -> Parser<C, [T]>.Function { return ntimes(parser, n) } /// Parses `parser` the number of times specified in `interval`. /// /// \param interval An interval specifying the number of repetitions to perform. `0..<n` means at most `n-1` repetitions; `m..<Int.max` means at least `m` repetitions; and `m..<n` means at least `m` and fewer than `n` repetitions; `n..<n` is an error. public func * <C: Collection, T> (parser: @escaping Parser<C, T>.Function, interval: Range<Int>) -> Parser<C, [T]>.Function { if interval.isEmpty { return { .failure(.leaf("cannot parse an empty interval of repetitions", $1)) } } return parser * (interval.lowerBound...decrement(interval.upperBound)) } /// Parses `parser` 0 or more times. public func many<C: Collection, T> (_ p: @escaping Parser<C, T>.Function) -> Parser<C, [T]>.Function { return prepend <^> require(p) <*> delay { many(p) } <|> pure([]) } /// Parses `parser` `n` number of times. public func ntimes<C: Collection, T> (_ p: @escaping Parser<C, T>.Function, _ n: Int) -> Parser<C, [T]>.Function { guard n > 0 else { return pure([]) } return prepend <^> p <*> delay { ntimes(p, n - 1) } } // MARK: - Private /// Decrements `x` iff it is not equal to `Int.max`. private func decrement(_ x: Int) -> Int { return (x == Int.max ? Int.max : x - 1) } private func decrement(_ x: CountableClosedRange<Int>) -> CountableClosedRange<Int> { return decrement(x.lowerBound)...decrement(x.upperBound) } /// Fails iff `parser` does not consume input, otherwise pass through its results private func require<C: Collection, T> (_ parser: @escaping Parser<C,T>.Function) -> Parser<C, T>.Function { return { (input, sourcePos) in return parser(input, sourcePos).flatMap { resultInput, resultPos in if sourcePos.index == resultPos.index { return Result.failure(Error.leaf("parser did not consume input when required", sourcePos)) } return Result.success((resultInput, resultPos)) } } } // MARK: - Imports import Result
mit
5cbbab0ccde1c285bce5d60573419abb
44.681319
252
0.666105
3.322942
false
false
false
false
prolificinteractive/Caishen
Pod/Classes/UI/Text Fields/YearInputTextField.swift
1
801
// // YearInputTextField.swift // Caishen // // Created by Daniel Vancura on 3/8/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // import UIKit /// A text field which can be used to enter years and provides validation. open class YearInputTextField: DetailInputTextField { /** Checks the validity of the entered year. - returns: True, if the year is valid. */ internal override func isInputValid(_ year: String, partiallyValid: Bool) -> Bool { if partiallyValid && year.count == 0 { return true } guard let yearInt = UInt(year) else { return false } return yearInt >= 0 && yearInt < 100 && (partiallyValid || year.count == 2) } }
mit
77980b77a58eb0b22af10ef5778c5dff
24
87
0.585
4.347826
false
false
false
false
Motsai/neblina-motiondemo-swift
src/NeblinaControl.swift
2
21283
// // NeblinaControl.swift // // // Created by Hoan Hoang on 2017-04-06. // Copyright © 2017 Motsai. All rights reserved. // import Foundation import CoreBluetooth extension Neblina { // // MARK : **** API // // ******************************** // * Neblina Command API // ******************************** // // *** // *** Subsystem General // *** func getSystemStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS, paramLen: 0, paramData: [0]) } func getFusionStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FUSION_STATUS, paramLen: 0, paramData: [0]) } func getRecorderStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_RECORDER_STATUS, paramLen: 0, paramData: [0]) } func getFirmwareVersion() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION, paramLen: 0, paramData: [0]) } func getDataPortState() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_INTERFACE_STATUS, paramLen: 0, paramData: [0]) } func setDataPort(_ PortIdx : Int, Ctrl : UInt8) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(PortIdx) param[1] = Ctrl // 1 - Open, 0 - Close sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, paramLen: 2, paramData: param) } func getPowerStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_POWER_STATUS, paramLen: 0, paramData: [0]) } func getSensorStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SENSOR_STATUS, paramLen: 0, paramData: [0]) } func disableStreaming() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DISABLE_STREAMING, paramLen: 0, paramData: [0]) } func resetTimeStamp( Delayed : Bool) { var param = [UInt8](repeating: 0, count: 1) if Delayed == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP, paramLen: 1, paramData: param) } func firmwareUpdate() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE, paramLen: 0, paramData: [0]) } func getDeviceName() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_NAME_GET, paramLen: 0, paramData: [0]) } func setDeviceName(name : String) { let param = [UInt8](name.utf8) print("setDeviceName \(name) \(param))") var len = param.count if len > Int(NEBLINA_NAME_LENGTH_MAX) { len = Int(NEBLINA_NAME_LENGTH_MAX) } sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_NAME_SET, paramLen: len, paramData: param) } func shutdown() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_SHUTDOWN, paramLen: 0, paramData: [0]) } func getUnixTime(uTime : UInt32) { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_GET_UNIX_TIMESTAMP, paramLen: 0, paramData: [0]) } func setUnixTime(uTime : UInt32) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(uTime & 0xFF) param[1] = UInt8((uTime >> 8) & 0xFF) param[2] = UInt8((uTime >> 16) & 0xFF) param[3] = UInt8((uTime >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SET_UNIX_TIMESTAMP, paramLen: param.count, paramData: param) } // *** // *** EEPROM // *** func eepromRead(_ pageNo : UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(pageNo & 0xff) param[1] = UInt8((pageNo >> 8) & 0xff) sendCommand(subSys: NEBLINA_SUBSYSTEM_EEPROM, cmd: NEBLINA_COMMAND_EEPROM_READ, paramLen: param.count, paramData: param) } func eepromWrite(_ pageNo : UInt16, data : UnsafePointer<UInt8>) { var param = [UInt8](repeating: 0, count: 10) param[0] = UInt8(pageNo & 0xff) param[1] = UInt8((pageNo >> 8) & 0xff) for i in 0..<8 { param[i + 2] = data[i] } sendCommand(subSys: NEBLINA_SUBSYSTEM_EEPROM, cmd: NEBLINA_COMMAND_EEPROM_WRITE, paramLen: param.count, paramData: param) } // *** LED subsystem commands func getLed() { sendCommand(subSys: NEBLINA_SUBSYSTEM_LED, cmd: NEBLINA_COMMAND_LED_STATUS, paramLen: 0, paramData: [0]) } func setLed(_ LedNo : UInt8, Value:UInt8) { var param = [UInt8](repeating: 0, count: 2) param[0] = LedNo param[1] = Value sendCommand(subSys: NEBLINA_SUBSYSTEM_LED, cmd: NEBLINA_COMMAND_LED_STATE, paramLen: param.count, paramData: param) } // *** Power management sybsystem commands func getTemperature() { sendCommand(subSys: NEBLINA_SUBSYSTEM_POWER, cmd: NEBLINA_COMMAND_POWER_TEMPERATURE, paramLen: 0, paramData: [0]) } func setBatteryChargeCurrent(_ Current: UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Current & 0xFF) param[1] = UInt8((Current >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_POWER, cmd: NEBLINA_COMMAND_POWER_CHARGE_CURRENT, paramLen: param.count, paramData: param) } // *** // *** Fusion subsystem commands // *** func setFusionRate(_ Rate: NeblinaRate_t) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Rate.rawValue & 0xFF) param[1] = UInt8((Rate.rawValue >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_RATE, paramLen: param.count, paramData: param) } func setFusionDownSample(_ Rate: UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Rate & 0xFF) param[1] = UInt8((Rate >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_DOWNSAMPLE, paramLen: param.count, paramData: param) } func streamMotionState(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM, paramLen: param.count, paramData: param) } func streamQuaternion(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM, paramLen: param.count, paramData: param) } func streamEulerAngle(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM, paramLen: param.count, paramData: param) } func streamExternalForce(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM, paramLen: param.count, paramData: param) } func setFusionType(_ Mode:UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = Mode sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_FUSION_TYPE, paramLen: param.count, paramData: param) } func recordTrajectory(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_TRAJECTORY_RECORD, paramLen: param.count, paramData: param) } func streamTrajectoryInfo(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_TRAJECTORY_INFO_STREAM, paramLen: param.count, paramData: param) } func streamPedometer(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM, paramLen: param.count, paramData: param) } func streamSittingStanding(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SITTING_STANDING_STREAM, paramLen: param.count, paramData: param) } func lockHeadingReference() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE, paramLen: 0, paramData: [0]) } func streamFingerGesture(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_FINGER_GESTURE_STREAM, paramLen: param.count, paramData: param) } func streamRotationInfo(_ Enable:Bool, Type : UInt8) { var param = [UInt8](repeating: 0, count: 2) param[1] = Type if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM, paramLen: param.count, paramData: param) } func externalHeadingCorrection(yaw : Int16, error : UInt16 ) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(yaw & 0xFF) param[1] = UInt8((yaw >> 8) & 0xFF) param[2] = UInt8(error & 0xFF) param[3] = UInt8((error >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EXTERNAL_HEADING_CORRECTION, paramLen: param.count, paramData: param) } func resetAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_RESET, paramLen: 0, paramData: [0]) } func calibrateAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_CALIBRATE, paramLen: 0, paramData: [0]) } func createPoseAnalysis(id : UInt8, qtf : [Int16]) { var param = [UInt8](repeating: 0, count: 2 + 8) param[0] = UInt8(id & 0xFF) for i in 0..<4 { param[1 + (i << 1)] = UInt8(qtf[i] & 0xFF) param[2 + (i << 1)] = UInt8((qtf[i] >> 8) & 0xFF) } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_CREATE_POSE, paramLen: param.count, paramData: param) } func setActivePoseAnalysis(id : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = id sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_SET_ACTIVE_POSE, paramLen: param.count, paramData: param) } func getActivePoseAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_GET_ACTIVE_POSE, paramLen: 0, paramData: [0]) } func streamAnalysis(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_STREAM, paramLen: param.count, paramData: param) } func getPoseAnalysisInfo(_ id: UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = id sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_POSE_INFO, paramLen: param.count, paramData: param) } func calibrateForwardPosition() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION, paramLen: 0, paramData: [0]) } func calibrateDownPosition() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION, paramLen: 0, paramData: [0]) } func streamMotionDirection(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_MOTION_DIRECTION_STREAM, paramLen: param.count, paramData: param) } func streamShockSegment(_ Enable:Bool, threshold : UInt8 ) { var param = [UInt8](repeating: 0, count: 2) if Enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = threshold sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM, paramLen: param.count, paramData: param) } func setGolfSwingAnalysisMode(_ mode : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = mode sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SET_GOLFSWING_ANALYSIS_MODE, paramLen: param.count, paramData: param) } func setGolfSwingMaxError(_ count : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = count sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SET_GOLFSWING_MAXIMUM_ERROR, paramLen: param.count, paramData: param) } func streamFunsionClustering(_ enable:Bool, mode : UInt8, sensor : UInt8, downSample : UInt8, snr : UInt8) { var param = [UInt8](repeating: 0, count: 5) if enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = mode param[2] = sensor param[3] = downSample param[4] = snr sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CLUSTERING_INFO_STREAM, paramLen: param.count, paramData: param) } // *** // *** Storage subsystem commands // *** func getSessionCount() { sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_COUNT, paramLen: 0, paramData: [0]) } func getSessionInfo(_ sessionId : UInt16, idx : UInt8) { var param = [UInt8](repeating: 0, count: 3) param[0] = UInt8(sessionId & 0xFF) param[1] = UInt8((sessionId >> 8) & 0xFF) param[2] = idx; sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_GENERAL_INFO, paramLen: param.count, paramData: param) } func getSessionName(_ sessionId : UInt16) { var param = [UInt8](repeating: 0, count: 3) param[0] = UInt8(sessionId & 0xFF) param[1] = UInt8((sessionId >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_NAME, paramLen: param.count, paramData: param) } func eraseStorage(_ quickErase:Bool) { var param = [UInt8](repeating: 0, count: 1) if quickErase == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_ERASE_ALL, paramLen: param.count, paramData: param) } func sessionPlayback(_ Enable:Bool, sessionId : UInt16) { var param = [UInt8](repeating: 0, count: 3) if Enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = UInt8(sessionId & 0xff) param[2] = UInt8((sessionId >> 8) & 0xff) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_PLAYBACK, paramLen: param.count, paramData: param) } func sessionRecord(_ Enable:Bool, info : String) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } print("\(info)") param += info.utf8 print("\(param)") sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_RECORD, paramLen: min(param.count, 16), paramData: param) } func sessionRead(_ SessionId:UInt16, Len:UInt16, Offset:UInt32) { var param = [UInt8](repeating: 0, count: 8) // Command parameter param[0] = UInt8(SessionId & 0xFF) param[1] = UInt8((SessionId >> 8) & 0xFF) param[2] = UInt8(Len & 0xFF) param[3] = UInt8((Len >> 8) & 0xFF) param[4] = UInt8(Offset & 0xFF) param[5] = UInt8((Offset >> 8) & 0xFF) param[6] = UInt8((Offset >> 16) & 0xFF) param[7] = UInt8((Offset >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_READ, paramLen: param.count, paramData: param) } func sessionDownload(_ Start : Bool, SessionId:UInt16, Len:UInt16, Offset:UInt32) { var param = [UInt8](repeating: 0, count: 9) // Command parameter if Start == true { param[0] = 1 } else { param[0] = 0 } param[1] = UInt8(SessionId & 0xFF) param[2] = UInt8((SessionId >> 8) & 0xFF) param[3] = UInt8(Len & 0xFF) param[4] = UInt8((Len >> 8) & 0xFF) param[5] = UInt8(Offset & 0xFF) param[6] = UInt8((Offset >> 8) & 0xFF) param[7] = UInt8((Offset >> 16) & 0xFF) param[8] = UInt8((Offset >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD, paramLen: param.count, paramData: param) } // *** // *** Sensor subsystem commands // *** func sensorSetDownsample(stream : UInt16, factor : UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(stream & 0xFF) param[1] = UInt8(stream >> 8) param[2] = UInt8(factor & 0xFF) param[3] = UInt8(factor >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_DOWNSAMPLE, paramLen: param.count, paramData: param) } func sensorSetRange(type : UInt16, range: UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(type & 0xFF) param[1] = UInt8(type >> 8) param[2] = UInt8(range & 0xFF) param[3] = UInt8(range >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_RANGE, paramLen: param.count, paramData: param) } func sensorSetRate(type : UInt16, rate: UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(type & 0xFF) param[1] = UInt8(type >> 8) param[2] = UInt8(rate & 0xFF) param[3] = UInt8(rate >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_RATE, paramLen: param.count, paramData: param) } func sensorGetDownsample(stream : NeblinaSensorStream_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = stream.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_DOWNSAMPLE, paramLen: param.count, paramData: param) } func sensorGetRange(type : NeblinaSensorType_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = type.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_RANGE, paramLen: param.count, paramData: param) } func sensorGetRate(type : NeblinaSensorType_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = type.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_RATE, paramLen: param.count, paramData: param) } func sensorStreamAccelData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM, paramLen: param.count, paramData: param) } func sensorStreamGyroData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamHumidityData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM, paramLen: param.count, paramData: param) } func sensorStreamMagData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM, paramLen: param.count, paramData: param) } func sensorStreamPressureData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamTemperatureData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamAccelGyroData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamAccelMagData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM, paramLen: param.count, paramData: param) } }
mit
7524c91751cd3276a91923b7a352669d
25.803526
151
0.670473
2.93788
false
false
false
false
donbytyqi/WatchBox
WatchBox Reborn/CastMovieFeedController.swift
1
2504
// // CastMovieFeedController.swift // WatchBox Reborn // // Created by Don Bytyqi on 5/11/17. // Copyright © 2017 Don Bytyqi. All rights reserved. // import UIKit class CastMovieFeedController: UICollectionViewController, UICollectionViewDelegateFlowLayout { var movies = [Movie]() var id: NSNumber? override func viewDidLoad() { super.viewDidLoad() self.movies.removeAll() setupComponents() fetchCastMovieCredits(id: id as! Int) } func setupComponents() { collectionView?.register(MovieCell.self, forCellWithReuseIdentifier: "cell") } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return movies.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MovieCell cell.movie = movies[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ? CGSize(width: collectionView.frame.width / 5, height: 187.5) : CGSize(width: collectionView.frame.width / 3, height: 187.5) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func fetchCastMovieCredits(id: Int) { MovieAPIService.shared.fetchCastMovies(byID: id, isMovie: "movie") { (fetchedMovies: [Movie]) in self.movies = fetchedMovies self.collectionView?.reloadSections(IndexSet(integer: 0)) print(self.movies.count) } MovieAPIService.shared.fetchCastMovies(byID: id, isMovie: "tv") { (fetchedMovies: [Movie]) in for movie in fetchedMovies { self.movies.append(movie) } self.collectionView?.reloadSections(IndexSet(integer: 0)) print(self.movies.count) } } }
mit
fc5962f968285a0e129ff7c8cd501d31
38.109375
194
0.685178
5.056566
false
false
false
false
LiulietLee/Pick-Color
Pick Color/SwiftGif.swift
1
5913
// // Gif.swift // SwiftGif // // Created by Arne Bahlo on 07.06.14. // Copyright (c) 2014 Arne Bahlo. All rights reserved. // import UIKit import ImageIO extension UIImageView { public func loadGif(name: String) { DispatchQueue.global().async { let image = UIImage.gif(name: name) DispatchQueue.main.async { self.image = image } } } } extension UIImage { public class func gif(data: Data) -> UIImage? { // Create source from data guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { print("SwiftGif: Source for the image does not exist") return nil } return UIImage.animatedImageWithSource(source) } public class func gif(url: String) -> UIImage? { // Validate URL guard let bundleURL = URL(string: url) else { print("SwiftGif: This image named \"\(url)\" does not exist") return nil } // Validate data guard let imageData = try? Data(contentsOf: bundleURL) else { print("SwiftGif: Cannot turn image named \"\(url)\" into NSData") return nil } return gif(data: imageData) } public class func gif(name: String) -> UIImage? { // Check for existance of gif guard let bundleURL = Bundle.main .url(forResource: name, withExtension: "gif") else { print("SwiftGif: This image named \"\(name)\" does not exist") return nil } // Validate data guard let imageData = try? Data(contentsOf: bundleURL) else { print("SwiftGif: Cannot turn image named \"\(name)\" into NSData") return nil } return gif(data: imageData) } internal class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double { var delay = 0.06 // Get dictionaries let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0) if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false { return delay } let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self) // Get delay time var delayObject: AnyObject = unsafeBitCast( CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self) if delayObject.doubleValue == 0 { delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self) } delay = delayObject as? Double ?? 0 if delay < 0.01 { delay = 0.01 // Make sure they're not too fast } return delay } internal class func gcdForPair(_ a: Int?, _ b: Int?) -> Int { var a = a var b = b // Check if one of them is nil if b == nil || a == nil { if b != nil { return b! } else if a != nil { return a! } else { return 0 } } // Swap for modulo if a! < b! { let c = a a = b b = c } // Get greatest common divisor var rest: Int while true { rest = a! % b! if rest == 0 { return b! // Found it } else { a = b b = rest } } } internal class func gcdForArray(_ array: Array<Int>) -> Int { if array.isEmpty { return 1 } var gcd = array[0] for val in array { gcd = UIImage.gcdForPair(val, gcd) } return gcd } internal class func animatedImageWithSource(_ source: CGImageSource) -> UIImage? { let count = CGImageSourceGetCount(source) var images = [CGImage]() var delays = [Int]() // Fill arrays for i in 0..<count { // Add image if let image = CGImageSourceCreateImageAtIndex(source, i, nil) { images.append(image) } // At it's delay in cs let delaySeconds = UIImage.delayForImageAtIndex(Int(i), source: source) delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms } // Calculate full duration let duration: Int = { var sum = 0 for val: Int in delays { sum += val } return sum }() // Get frames let gcd = gcdForArray(delays) var frames = [UIImage]() var frame: UIImage var frameCount: Int for i in 0..<count { frame = UIImage(cgImage: images[Int(i)]) frameCount = Int(delays[Int(i)] / gcd) for _ in 0..<frameCount { frames.append(frame) } } // Heyhey let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0) return animation } }
mit
96ca387741d1a9b35304b8fda3c8c414
28.565
155
0.495857
5.279464
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/2-Element/CenterTop.Individual.swift
1
2659
// // CenterTop.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct CenterTop { let center: LayoutElement.Horizontal let top: LayoutElement.Vertical } } // MARK: - Make Frame extension IndividualProperty.CenterTop { private func makeFrame(center: Float, top: Float, size: Size) -> Rect { let left = center - size.width.half let origin = Point(x: left, y: top) let size = size let frame = Rect(origin: origin, size: size) return frame } } // MARK: - Set A Size - // MARK: Size extension IndividualProperty.CenterTop: LayoutPropertyCanStoreSizeToEvaluateFrameType { public func evaluateFrame(size: LayoutElement.Size, parameters: IndividualFrameCalculationParameters) -> Rect { let center = self.center.evaluated(from: parameters) let top = self.top.evaluated(from: parameters) let size = size.evaluated(from: parameters) return self.makeFrame(center: center, top: top, size: size) } } // MARK: - Set A Line - // MARK: Middle extension IndividualProperty.CenterTop: LayoutPropertyCanStoreMiddleType { public func storeMiddle(_ middle: LayoutElement.Vertical) -> IndividualProperty.CenterTopMiddle { let centerTopMiddle = IndividualProperty.CenterTopMiddle(center: self.center, top: self.top, middle: middle) return centerTopMiddle } } // MARK: Bottom extension IndividualProperty.CenterTop: LayoutPropertyCanStoreBottomType { public func storeBottom(_ bottom: LayoutElement.Vertical) -> IndividualProperty.CenterTopBottom { let centerTopBottom = IndividualProperty.CenterTopBottom(center: self.center, top: self.top, bottom: bottom) return centerTopBottom } } // MARK: - Set A Length - // MARK: Width extension IndividualProperty.CenterTop: LayoutPropertyCanStoreWidthType { public func storeWidth(_ width: LayoutElement.Length) -> IndividualProperty.CenterTopWidth { let centerTopWidth = IndividualProperty.CenterTopWidth(center: self.center, top: self.top, width: width) return centerTopWidth } } // MARK: Height extension IndividualProperty.CenterTop: LayoutPropertyCanStoreHeightType { public func storeHeight(_ height: LayoutElement.Length) -> IndividualProperty.CenterTopHeight { let centerTopHeight = IndividualProperty.CenterTopHeight(center: self.center, top: self.top, height: height) return centerTopHeight } }
apache-2.0
10c6ed5be4262a57d8d75bd9fdd73ed1
21.991304
112
0.703101
4.2304
false
false
false
false
orta/eidolon
Kiosk/App/Networking/XAppAuthentication.swift
1
1774
import Foundation /// Request to fetch and store new XApp token if the current token is missing or expired. private func XAppTokenRequest(defaults: NSUserDefaults) -> RACSignal { // I don't like an extension of a class referencing what is essentially a singleton of that class. var appToken = XAppToken(defaults: defaults) let newTokenSignal = Provider.sharedProvider.request(ArtsyAPI.XApp, parameters: ArtsyAPI.XApp.defaultParameters).filterSuccessfulStatusCodes().mapJSON().doNext({ (response) -> Void in if let dictionary = response as? NSDictionary { let formatter = ISO8601DateFormatter() appToken.token = dictionary["xapp_token"] as String? appToken.expiry = formatter.dateFromString(dictionary["expires_in"] as String?) } }).logError().ignoreValues() // Signal that returns whether our current token is valid let validTokenSignal = RACSignal.`return`(appToken.isValid) // If the token is valid, just return an empty signal, otherwise return a signal that fetches new tokens return RACSignal.`if`(validTokenSignal, then: RACSignal.empty(), `else`: newTokenSignal) } /// Request to fetch a given target. Ensures that valid XApp tokens exist before making request func XAppRequest(token: ArtsyAPI, method: Moya.Method = Moya.DefaultMethod(), parameters: [String: AnyObject] = Moya.DefaultParameters(), defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()) -> RACSignal { // First perform XAppTokenRequest(). When it completes, then the signal returned from the closure will be subscribed to. return XAppTokenRequest(defaults).then({ () -> RACSignal! in return Provider.sharedProvider.request(token, method: method, parameters: parameters) }) }
mit
3d16de191530cd9a2fbc7c9d07537570
49.714286
218
0.736753
4.983146
false
false
false
false
stripe/stripe-ios
Stripe/STPPaymentOptionTableViewCell.swift
1
11817
// // STPPaymentOptionTableViewCell.swift // StripeiOS // // Created by Ben Guo on 8/30/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // @_spi(STP) import StripeCore @_spi(STP) import StripePaymentsUI import UIKit class STPPaymentOptionTableViewCell: UITableViewCell { @objc(configureForNewCardRowWithTheme:) func configureForNewCardRow(with theme: STPTheme) { paymentOption = nil self.theme = theme backgroundColor = theme.secondaryBackgroundColor // Left icon leftIcon.image = STPLegacyImageLibrary.addIcon() leftIcon.tintColor = theme.accentColor // Title label titleLabel.font = theme.font titleLabel.textColor = theme.accentColor titleLabel.text = STPLocalizedString("Add New Card…", "Button to add a new credit card.") // Checkmark icon checkmarkIcon.isHidden = true setNeedsLayout() } @objc(configureWithPaymentOption:theme:selected:) func configure( with paymentOption: STPPaymentOption?, theme: STPTheme, selected: Bool ) { self.paymentOption = paymentOption self.theme = theme backgroundColor = theme.secondaryBackgroundColor // Left icon leftIcon.image = paymentOption?.templateImage leftIcon.tintColor = primaryColorForPaymentOption(withSelected: selected) // Title label titleLabel.font = theme.font titleLabel.attributedText = buildAttributedString(with: paymentOption, selected: selected) // Checkmark icon checkmarkIcon.tintColor = theme.accentColor checkmarkIcon.isHidden = !selected // Accessibility if selected { accessibilityTraits.insert(.selected) } else { accessibilityTraits.remove(.selected) } setNeedsLayout() } @objc(configureForFPXRowWithTheme:) func configureForFPXRow(with theme: STPTheme) { paymentOption = nil self.theme = theme backgroundColor = theme.secondaryBackgroundColor // Left icon leftIcon.image = STPImageLibrary.bankIcon() leftIcon.tintColor = primaryColorForPaymentOption(withSelected: false) // Title label titleLabel.font = theme.font titleLabel.textColor = self.theme.primaryForegroundColor titleLabel.text = STPLocalizedString( "Online Banking (FPX)", "Button to pay with a Bank Account (using FPX)." ) // Checkmark icon checkmarkIcon.isHidden = true accessoryType = .disclosureIndicator setNeedsLayout() } private var paymentOption: STPPaymentOption? private var theme: STPTheme = .defaultTheme private var leftIcon = UIImageView() private var titleLabel = UILabel() private var checkmarkIcon = UIImageView(image: STPLegacyImageLibrary.checkmarkIcon()) override init( style: UITableViewCell.CellStyle, reuseIdentifier: String? ) { super.init(style: style, reuseIdentifier: reuseIdentifier) // Left icon leftIcon.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(leftIcon) // Title label titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) // Checkmark icon checkmarkIcon.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(checkmarkIcon) NSLayoutConstraint.activate( [ self.leftIcon.centerXAnchor.constraint( equalTo: contentView.leadingAnchor, constant: kPadding + 0.5 * kDefaultIconWidth ), self.leftIcon.centerYAnchor.constraint( lessThanOrEqualTo: contentView.centerYAnchor ), self.checkmarkIcon.widthAnchor.constraint(equalToConstant: kCheckmarkWidth), self.checkmarkIcon.heightAnchor.constraint( equalTo: self.checkmarkIcon.widthAnchor, multiplier: 1.0 ), self.checkmarkIcon.centerXAnchor.constraint( equalTo: contentView.trailingAnchor, constant: -kPadding ), self.checkmarkIcon.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), // Constrain label to leadingAnchor with the default // icon width so that the text always aligns vertically // even if the icond widths differ self.titleLabel.leadingAnchor.constraint( equalTo: contentView.leadingAnchor, constant: 2.0 * kPadding + kDefaultIconWidth ), self.titleLabel.trailingAnchor.constraint( equalTo: self.checkmarkIcon.leadingAnchor, constant: -kPadding ), self.titleLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), ]) accessibilityTraits.insert(.button) isAccessibilityElement = true } func primaryColorForPaymentOption(withSelected selected: Bool) -> UIColor { let fadedColor: UIColor = { if #available(iOS 13.0, *) { return UIColor(dynamicProvider: { _ in return self.theme.primaryForegroundColor.withAlphaComponent(0.6) }) } else { return theme.primaryForegroundColor.withAlphaComponent(0.6) } }() return (selected ? theme.accentColor : fadedColor) } func buildAttributedString( with paymentOption: STPPaymentOption?, selected: Bool ) -> NSAttributedString { if let paymentOption = paymentOption as? STPCard { return buildAttributedString(with: paymentOption, selected: selected) } else if let source = paymentOption as? STPSource { if source.type == .card && source.cardDetails != nil { return buildAttributedString(withCardSource: source, selected: selected) } } else if let paymentMethod = paymentOption as? STPPaymentMethod { if paymentMethod.type == .card && paymentMethod.card != nil { return buildAttributedString( withCardPaymentMethod: paymentMethod, selected: selected ) } if paymentMethod.type == .FPX && paymentMethod.fpx != nil { return buildAttributedString( with: STPFPXBank.brandFrom(paymentMethod.fpx?.bankIdentifierCode), selected: selected ) } } else if paymentOption is STPApplePayPaymentOption { let label = String.Localized.apple_pay let primaryColor = primaryColorForPaymentOption(withSelected: selected) return NSAttributedString( string: label, attributes: [ NSAttributedString.Key.foregroundColor: primaryColor ] ) } else if let paymentMethodParams = paymentOption as? STPPaymentMethodParams { if paymentMethodParams.type == .card && paymentMethodParams.card != nil { return buildAttributedString( withCardPaymentMethodParams: paymentMethodParams, selected: selected ) } if paymentMethodParams.type == .FPX && paymentMethodParams.fpx != nil { return buildAttributedString( with: paymentMethodParams.fpx?.bank ?? STPFPXBankBrand.unknown, selected: selected ) } } // Unrecognized payment method return NSAttributedString(string: "") } func buildAttributedString(with card: STPCard, selected: Bool) -> NSAttributedString { return buildAttributedString( with: card.brand, last4: card.last4, selected: selected ) } func buildAttributedString(withCardSource card: STPSource, selected: Bool) -> NSAttributedString { return buildAttributedString( with: card.cardDetails?.brand ?? .unknown, last4: card.cardDetails?.last4 ?? "", selected: selected ) } func buildAttributedString( withCardPaymentMethod paymentMethod: STPPaymentMethod, selected: Bool ) -> NSAttributedString { return buildAttributedString( with: paymentMethod.card?.brand ?? .unknown, last4: paymentMethod.card?.last4 ?? "", selected: selected ) } func buildAttributedString( withCardPaymentMethodParams paymentMethodParams: STPPaymentMethodParams, selected: Bool ) -> NSAttributedString { let brand = STPCardValidator.brand(forNumber: paymentMethodParams.card?.number ?? "") return buildAttributedString( with: brand, last4: paymentMethodParams.card?.last4 ?? "", selected: selected ) } func buildAttributedString( with bankBrand: STPFPXBankBrand, selected: Bool ) -> NSAttributedString { let label = (STPFPXBank.stringFrom(bankBrand) ?? "") + " (FPX)" let primaryColor = primaryColorForPaymentOption(withSelected: selected) return NSAttributedString( string: label, attributes: [ NSAttributedString.Key.foregroundColor: primaryColor ] ) } func buildAttributedString( with brand: STPCardBrand, last4: String, selected: Bool ) -> NSAttributedString { let format = String.Localized.card_brand_ending_in_last_4 let brandString = STPCard.string(from: brand) let label = String(format: format, brandString, last4) let primaryColor = selected ? theme.accentColor : theme.primaryForegroundColor let secondaryColor: UIColor = { if #available(iOS 13.0, *) { return UIColor(dynamicProvider: { _ in return primaryColor.withAlphaComponent(0.6) }) } else { return primaryColor.withAlphaComponent(0.6) } }() let attributes: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.foregroundColor: secondaryColor, NSAttributedString.Key.font: self.theme.font, ] let attributedString = NSMutableAttributedString( string: label, attributes: attributes as [NSAttributedString.Key: Any] ) attributedString.addAttribute( .foregroundColor, value: primaryColor, range: (label as NSString).range(of: brandString) ) attributedString.addAttribute( .foregroundColor, value: primaryColor, range: (label as NSString).range(of: last4) ) attributedString.addAttribute( .font, value: theme.emphasisFont, range: (label as NSString).range(of: brandString) ) attributedString.addAttribute( .font, value: theme.emphasisFont, range: (label as NSString).range(of: last4) ) return attributedString } required init?( coder aDecoder: NSCoder ) { super.init(coder: aDecoder) } } private let kDefaultIconWidth: CGFloat = 26.0 private let kPadding: CGFloat = 15.0 private let kCheckmarkWidth: CGFloat = 14.0
mit
9ad1e473b6a7aef940b55ffe2bfc96d3
33.952663
100
0.605383
5.690751
false
false
false
false
daggmano/photo-management-studio
src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/ProgressIndicator.swift
1
973
// // ProgressIndicator.swift // Photo Management Studio // // Created by Darren Oster on 5/04/2016. // Copyright © 2016 Criterion Software. All rights reserved. // import ITProgressIndicator class ProgressIndicator: NSObject { let _progressIndicator: ITProgressIndicator! init(progressIndicator: ITProgressIndicator) { _progressIndicator = progressIndicator _progressIndicator.isIndeterminate = true _progressIndicator.lengthOfLine = 30 _progressIndicator.widthOfLine = 5 _progressIndicator.numberOfLines = 10 _progressIndicator.color = NSColor.lightGrayColor() _progressIndicator.steppedAnimation = true _progressIndicator.progress = 1 _progressIndicator.animationDuration = 1 } func show(makeVisible: Bool) { dispatch_async(dispatch_get_main_queue()) { () -> Void in self._progressIndicator.hidden = !makeVisible } } }
mit
315e540cd4a3e5465d2b279e8ec6aea3
28.454545
65
0.674897
5.0625
false
false
false
false
qichen0401/QCUtilitySwift
QCUtilitySwift/Classes/Common/UIImage+QC.swift
1
2888
// // UIImage+QC.swift // Pods // // Created by Qi Chen on 2/27/17. // // import Foundation import AVFoundation extension UIImage { public convenience init(sampleBuffer: CMSampleBuffer) { let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)! let context = CIContext(options: nil) let cgImage = context.createCGImage(CIImage(cvPixelBuffer: imageBuffer), from: CGRect(x: 0, y: 0, width: CGFloat(CVPixelBufferGetWidth(imageBuffer)), height: CGFloat(CVPixelBufferGetHeight(imageBuffer)))) self.init(cgImage: cgImage!) } public func redraw() -> UIImage { UIGraphicsBeginImageContext(size) self.draw(at: .zero) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } public func write(to url: URL) { do { let image = self.redraw() try UIImagePNGRepresentation(image)?.write(to: url) } catch { print(error) } } public class func load(from url: URL) -> UIImage? { do { let data = try Data(contentsOf: url) return UIImage(data: data) } catch { print(error) } return nil } public class func image(withQRCodeInputMessage inputMessage: String, size: CGSize) -> UIImage { let inputMessageData = inputMessage.data(using: String.Encoding.utf8)! let filter = CIFilter(name: "CIQRCodeGenerator", withInputParameters: ["inputMessage" : inputMessageData])! let outputImage = filter.outputImage! return UIImage(ciImage: outputImage).scale(to: size, interpolationQuality: .none) } public func scale(to size: CGSize) -> UIImage { return self.scale(to: size, interpolationQuality: .default) } public func scale(to size: CGSize, interpolationQuality quality: CGInterpolationQuality) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) UIGraphicsGetCurrentContext()!.interpolationQuality = quality self.draw(in: CGRect(origin: .zero, size: size)) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } public func invertColors() -> UIImage { let imageRect = CGRect(origin: .zero, size: self.size) UIGraphicsBeginImageContext(self.size) let context = UIGraphicsGetCurrentContext()! context.setBlendMode(.copy) self.draw(in: imageRect) context.setBlendMode(.difference) context.setFillColor(UIColor.white.cgColor) context.fill(imageRect) let resultImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return resultImage } }
mit
bc1913f7dbdbbb906470a5c481a8377a
31.818182
212
0.637465
5.194245
false
false
false
false
laszlokorte/reform-swift
ReformExpression/ReformExpression/Value.swift
1
1509
// // Value.swift // ExpressionEngine // // Created by Laszlo Korte on 07.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // public enum Value : Equatable { case stringValue(value: String) case intValue(value: Int) case doubleValue(value: Double) case colorValue(r: UInt8, g:UInt8, b:UInt8, a:UInt8) case boolValue(value: Bool) public init(string: String) { self = .stringValue(value: string) } public init(int: Int) { self = .intValue(value: int) } public init(double: Double) { self = .doubleValue(value: double) } public init(r: UInt8,g: UInt8,b: UInt8,a: UInt8) { self = .colorValue(r:r, g:g, b:b, a:a) } public init(bool: Bool) { self = .boolValue(value: bool) } } public func ==(lhs: Value, rhs: Value) -> Bool { switch (lhs, rhs) { case (.stringValue(let left), .stringValue(let right)) where left == right: return true case (.intValue(let left), .intValue(let right)) where left == right: return true case (.doubleValue(let left), .doubleValue(let right)) where left == right: return true case (.colorValue(let lr, let lg, let lb, let la), .colorValue(let rr, let rg, let rb, let ra)) where lr==rr && lg == rg && lb == rb && la == ra: return true case (.boolValue(let left), .boolValue(let right)) where left == right: return true default: return false } } struct ValueList { let values : [Value] }
mit
5d7505128cad74cfdd3611185b2e0efa
26.925926
161
0.605438
3.531616
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Cloud and portal/List portal group users/GroupUsersViewController.swift
1
5032
// Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class GroupUsersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! private var portal: AGSPortal! private var portalGroup: AGSPortalGroup! private var portalUsers = [AGSPortalUser]() override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["GroupUsersViewController", "GroupUserCell"] // automatic cell sizing for table view self.tableView.rowHeight = UITableView.automaticDimension self.tableView.estimatedRowHeight = 104 // initialize portal with AGOL self.portal = AGSPortal.arcGISOnline(withLoginRequired: false) // load the portal group to be used self.loadPortalGroup() } private func loadPortalGroup() { // show progress hud UIApplication.shared.showProgressHUD(message: "Loading Portal Group") // query group based on owner and title let queryParams = AGSPortalQueryParameters(forGroupsWithOwner: "ArcGISRuntimeSDK", title: "Runtime Group") // find groups with using query params self.portal.findGroups(with: queryParams) { [weak self] (resultSet: AGSPortalQueryResultSet?, error: Error?) in UIApplication.shared.hideProgressHUD() guard let self = self else { return } if let error = error { // show error self.presentAlert(error: error) } else { // fetch users for the resulting group if let groups = resultSet?.results as? [AGSPortalGroup], let group = groups.first { self.portalGroup = group self.fetchGroupUsers() } else { // show error that no groups found self.presentAlert(message: "No groups found") } } } } private func fetchGroupUsers() { // show progress hud UIApplication.shared.showProgressHUD(message: "Fetching Users") // fetch users in group self.portalGroup.fetchUsers { [weak self] (users, _, error) in UIApplication.shared.hideProgressHUD() guard let self = self else { return } if let error = error { // show error self.presentAlert(error: error) } else if let users = users { // if there are users in the group if !users.isEmpty { // initialize AGSPortalUser objects with user names self.portalUsers = users.map { AGSPortalUser(portal: self.portal, username: $0) } // load all users before populating into table view self.loadAllUsers() } else { self.presentAlert(message: "No users found") } } } } private func loadAllUsers() { // show progress hud UIApplication.shared.showProgressHUD(message: "Loading User Data") // load user data AGSLoadObjects(portalUsers) { [weak self] (success) in // dismiss hud UIApplication.shared.hideProgressHUD() if success { // reload table view self?.tableView.reloadData() } else { self?.presentAlert(message: "Error while loading users data") } } } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return portalUsers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "GroupUserCell", for: indexPath) as! GroupUserCell cell.portalUser = portalUsers[indexPath.row] return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Runtime Group" } }
apache-2.0
5f4b726656607fe072c6b265f720d4a5
36
134
0.592806
5.376068
false
false
false
false
ios-archy/Sinaweibo_swift
SinaWeibo_swift/SinaWeibo_swift/Classess/Home/HomeModel/Status.swift
1
1332
// // Status.swift // SinaWeibo_swift // // Created by archy on 16/10/26. // Copyright © 2016年 archy. All rights reserved. // import UIKit class Status : NSObject { //MARK: --属性 var created_at : String? //微博创建时间 var source : String? //微博来源 var text :String? //微博正文 var mid : Int = 0 //微博的id var user : User? //微博对应的用户 var pic_urls : [[String : String]]? //微博的配图 var retweeted_status : Status? //微博对应的转发的微博 //MARK: --对数据的处理的属性 var sourceText : String? var createAtText : String? // MARK:- 自定义构造函数 init(dict :[String : AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) //用户字典转成用户模型 if let userDict = dict["user"] as? [String : AnyObject] { user = User(dict:userDict) } //2.将转发微博字典转成转发微博模型对象 if let retweetedStatusDict = dict["retweeted_status"] as? [String :AnyObject] { retweeted_status = Status(dict: retweetedStatusDict) } } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } }
mit
a15d3adfb74813ce7a70ab31c7a22079
23.702128
87
0.560724
3.976027
false
false
false
false
1170197998/Swift-DEMO
transitioningAnimation/transitioningAnimation/ViewController.swift
1
3263
// // ViewController.swift // 转场动画 // // Created by ShaoFeng on 16/4/26. // Copyright © 2016年 Cocav. All rights reserved. // import UIKit class ViewController: UITableViewController { var array = [Any]() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white let titleButton = TitleButton() titleButton.setTitle("点我 ", for: UIControlState()) titleButton.addTarget(self, action: #selector(ViewController.clickButton), for: UIControlEvents.touchUpInside) navigationItem.titleView = titleButton NotificationCenter.default.addObserver(self, selector: #selector(ViewController.change), name: NSNotification.Name(rawValue: PopoverAnimatorWillShow), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.change), name: NSNotification.Name(rawValue: PopoverAnimatorWillDismiss), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.dataSource(_:)), name: NSNotification.Name(rawValue: dataSourceChange), object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc func dataSource(_ non: Notification) { array = [non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!,non.userInfo!["key"]!] // print(array) // print(array.count) tableView.reloadData() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cells") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cells") } if array.count != 0 { cell?.textLabel?.text = String(describing: array[indexPath.row]) } return cell! } @objc func change() { let titleButton = navigationItem.titleView as! TitleButton titleButton.isSelected = !titleButton.isSelected } @objc func clickButton() { //弹出菜单 let viewController = PopoverTableViewController() viewController.transitioningDelegate = popoverAnimator viewController.modalPresentationStyle = UIModalPresentationStyle.custom present(viewController, animated: true, completion: nil) } //懒加载转场 fileprivate lazy var popoverAnimator: PopoverAnimator = { let pa = PopoverAnimator() //在这里设置弹出菜单的位置和大小 pa.presentFrame = CGRect(x: UIScreen.main.bounds.size.width / 2 - 100, y: 56, width: 200, height: 350) return pa }() }
apache-2.0
3c1adf1a44f3fc239fb4661938cc96d1
36.647059
325
0.654063
4.968944
false
false
false
false
sathyavijayan/SchemaValidator
Pod/Classes/SchemaValidator.swift
1
3522
// // SchemaValidator.swift // SchemaValidator // // Created by Sathyavijayan Vittal on 04/06/2015. // Copyright (c) 2015 CocoaPods. All rights reserved. // import Foundation /** Validators should follow the signature (AnyObject?) -> (Bool,String?) in order to be used in the SchemaValidator. The Bool parameter in the tuple indicates whether the validation passed. The Optional String paramter contains the error message. */ public typealias Validator = (AnyObject?) -> (Bool, String?) /** The schema is a Dictionary of type [String:ValidationRule] The ValidationRule can be an array of Validators, or another Dictionary of type [String:ValidationRule]. The former will apply for fields and the latter to validate child objects. */ public typealias Schema = [String:ValidationRule] public let SchemaValidatorErrorDomain = "SchemaValidator" /** Utility to validate Dictionaries, specifically JSON like objects using a Schema. */ public class SchemaValidator { public static var messageProvider:(forKey: String) -> String = ValidationMessages.message class func applyValidators(obj: AnyObject?, validators: [Validator]) -> [String]? { var errors:[String] = [] for validator in validators { var result = validator(obj) if !result.0 { if let err = result.1 { errors.append(err) } else { errors.append("Unknown Error!") } } } if errors.count > 0 { return errors } else { return nil } } class func validateObject(schema: Schema, object: [String:AnyObject]) -> [String: AnyObject]? { var errors:[String:AnyObject] = [:] for (k,v) in schema { //v.type() could be: //a. Array[Validator] //b. Dictionary[String:VRule] switch(v.type()) { case .Array: if let errs = SchemaValidator.applyValidators(object[k], validators: v.object as! [Validator]) { errors[k] = errs } case .Dictionary: if let subObject = object[k] as? [String:AnyObject] { if let errs = validateObject(v.object as! Schema, object: subObject) { errors[k] = errs } } else if let subObjects = object[k] as? [[String:AnyObject]]{ for (index, subObject) in enumerate(subObjects) { var key = "\(k).\(index)" if let errs = validateObject(v.object as! Schema, object: subObject) { errors[key] = errs } } } else { //Err ! errors[k] = ["Unable to validate value for \(k). Should be an Object or Array of Objects."] } default: errors[k] = ["Invalid Type in schema for \(k)."] } } return (errors.isEmpty) ? nil : errors } public class func validate(schema: Schema, object: [String:AnyObject]) -> NSError? { if let error = validateObject(schema, object: object) { return NSError(domain: SchemaValidatorErrorDomain, code: 0, userInfo: error) } return nil } }
mit
1ff95dad1e7b855d47e989cef26f8d83
31.915888
113
0.539182
4.759459
false
false
false
false
googlearchive/cannonball-ios
Cannonball/Poem.swift
1
3170
// // Copyright (C) 2018 Google, Inc. and other contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import FirebaseDatabase open class Poem { // MARK: Types // String constants used to archive the stored properties of a poem. struct SerializationKeys { // A String (not an array of such) used by Firebase RTDB. static let text : String = "text" static let picture : String = "imageId" static let theme : String = "theme" static let timestamp : String = "creationTimeStamp" static let inverseTimestamp : String = "inverseCreationTimeStamp" } // MARK: Instance variables // The words composing a poem. open var words: [String] = [] // The picture used as a background of a poem. open var picture: String = "" // The theme name of the poem. open var theme: String = "" // The date a poem is completed. open var timestamp = -1 // This poem's node in a Firebase database open var ref : DatabaseReference? // Initialize a Poem instance will all its properties, including a UUID. // Includes default parameters for creating an empty poem. init(words: [String] = [], picture: String = "", theme: String = "", timestamp: Int = -1, ref : DatabaseReference? = nil) { self.words = words self.picture = picture self.theme = theme self.timestamp = timestamp self.ref = ref } // Initialize a Poem from a Firebase database snapshot convenience init(fromSnapshot snap : DataSnapshot) { let poemDict = snap.value as! [String : AnyObject] let text = poemDict[SerializationKeys.text] as! String let words = text.components(separatedBy: " ") let picture = poemDict[SerializationKeys.picture] as! String let theme = poemDict[SerializationKeys.theme] as! String let timestamp = poemDict[SerializationKeys.timestamp] as! Int self.init( words : words, picture : picture, theme : theme, timestamp: timestamp, ref : snap.ref) } // Retrieve the poem words as one sentence. func getSentence() -> String { return words.joined(separator: " ") } // Encode the poem as an NSDictionary usable by Firebase RTDB. open func encode() -> NSDictionary { let data : NSDictionary = [ SerializationKeys.text: getSentence(), SerializationKeys.picture: picture, SerializationKeys.theme: theme, SerializationKeys.timestamp: timestamp, SerializationKeys.inverseTimestamp: timestamp * (-1) ] return data; } }
apache-2.0
cfc63d1619af0fad55cf1ae9ede48f5b
34.222222
127
0.659306
4.567723
false
false
false
false
dunkelstern/unchained
Unchained/responseClasses/mediafile_response.swift
1
1622
// // mediafile_response.swift // unchained // // Created by Johannes Schriewer on 14/12/15. // Copyright © 2015 Johannes Schriewer. All rights reserved. // #if os(Linux) import UnchainedGlibc #else import Darwin #endif import TwoHundred /// Template response, fills a Stencil template with content public class MediaFileResponse: HTTPResponseBase { /// Init with template and context /// /// - parameter path: relative path to media file from configured media file base dir /// - parameter request: HTTPRequest for which to render the response /// - parameter statusCode: (optional) HTTP Status code to send (defaults to `200 Ok`) /// - parameter headers: (optional) additional headers to send /// - parameter contentType: (optional) content type to send (defaults to calling `file --mime` on the file) public init(_ path: String, request: HTTPRequest, statusCode: HTTPStatusCode = .Ok, headers: [HTTPHeader]? = nil, contentType: String? = nil) { super.init() let filename = request.config.mediaFilesDirectory + "/\(path)" if let headers = headers { self.headers.appendContentsOf(headers) } if let ct = MimeType.fromFile(filename) { self.statusCode = statusCode self.body = [.File(filename)] if let contentType = contentType { self.headers.append(HTTPHeader("Content-Type", contentType)) } else { self.headers.append(HTTPHeader("Content-Type", ct)) } } else { self.statusCode = .NotFound } } }
bsd-3-clause
b63aa12eb716817d5f959dfa083f8cf3
32.791667
147
0.640345
4.553371
false
false
false
false
xu6148152/binea_project_for_ios
Calculator/Calculator/ViewController.swift
1
2879
// // ViewController.swift // Calculator // // Created by Binea Xu on 5/30/15. // Copyright (c) 2015 Binea Xu. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var mDisplay: UILabel! var useIsInMiddleOfTypingANumber = false var brain = CalculatorBrain() @IBAction func displayDigit(sender: UIButton) { let digit = sender.currentTitle! println("digit = \(digit)") if(useIsInMiddleOfTypingANumber){ mDisplay.text = mDisplay.text! + digit }else{ mDisplay.text = digit useIsInMiddleOfTypingANumber = true } } @IBAction func operate(sender: UIButton) { if useIsInMiddleOfTypingANumber{ enter() } if let operation = sender.currentTitle{ if let result = brain.performOperation(operation){ displayValue = result } } // switch operation{ // case "C": // numberStack.removeAll(keepCapacity: false) // displayValue = 0 // break // case "±": // // case "%": // println("\(displayValue/100)") // mDisplay.text! = NSNumberFormatter().stringFromNumber(displayValue / 100)! // case "×": // performOperation{$0 * $1} // case "÷": // performOperation{$1 / $0} // case "−": // performOperation{$1 - $0} // case "+": // performOperation{$0 + $1} // case "√": // performOperation{sqrt($0)} // default: // break // } } func performOperation(operation: (Double, Double) ->Double){ if numberStack.count >= 2{ displayValue = operation(numberStack.removeLast(), numberStack.removeLast()) println("\(displayValue)") enter() } } private func performOperation(operation: (Double) ->Double){ if numberStack.count >= 1{ displayValue = operation(numberStack.removeLast()) enter() } } var numberStack = Array<Double>() @IBAction func enter() { useIsInMiddleOfTypingANumber = false // numberStack.append(displayValue) // println("\(numberStack)") if let result = brain.pushOperand(displayValue){ displayValue = result }else{ displayValue = 0 } } var displayValue:Double{ get{ return NSNumberFormatter().numberFromString(mDisplay.text!)!.doubleValue } set{ mDisplay.text = "\(newValue)" useIsInMiddleOfTypingANumber = false } } }
mit
b0debc603a72f3b0089024fabd17ca01
25.109091
92
0.512535
4.884354
false
false
false
false
steelwheels/Coconut
CoconutData/Source/Data/CNSortDescriptors.swift
1
1873
/** * @file CNSortDescriptors.swift * @brief Define CNSortDescriptors class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import Foundation public class CNSortDescriptors { public struct SortDescriptor { public var key: String public var ascending: Bool public init(key kstr: String, ascending asc: Bool){ key = kstr ascending = asc } } private var mSortDescriptors: Array<SortDescriptor> public var descriptors: Array<SortDescriptor> { get { return mSortDescriptors } } public init(){ mSortDescriptors = [] } public func add(key kstr: String, ascending asc: Bool) { /* Copy current descriptors */ var newdescs: Array<SortDescriptor> = [] for desc in mSortDescriptors { if desc.key != kstr { newdescs.append(desc) } } newdescs.append(SortDescriptor(key: kstr, ascending: asc)) /* Replace current descriptor */ mSortDescriptors = newdescs } public func ascending(for key: String) -> Bool? { for desc in mSortDescriptors { if desc.key == key { return desc.ascending } } return nil } public func sort<T>(source src: Array<T>, comparator comp: (_ s0: T, _ s1: T, _ key: String) -> ComparisonResult) -> Array<T> { var arr = src for desc in mSortDescriptors { arr = arr.sorted(by: { (_ s0: T, _ s1: T) -> Bool in let result: Bool switch comp(s0, s1, desc.key) { case .orderedAscending: result = desc.ascending case .orderedDescending: result = !desc.ascending case .orderedSame: result = false } return result }) } return arr } public func toText() -> CNTextSection { let sect = CNTextSection() sect.header = "sort-descriptors: {" sect.footer = "}" for desc in mSortDescriptors { let line = CNTextLine(string: "{key: \(desc.key), ascend:\(desc.ascending)}") sect.add(text: line) } return sect } }
lgpl-2.1
cd67e278fabcfae5b8f5fcbe7b7466d0
21.566265
128
0.660972
3.240484
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/rotate-array.swift
2
1105
/** * https://leetcode.com/problems/rotate-array/ * * */ class Solution { // Complexity: // Space: O(k) // Time: func rotate(_ nums: inout [Int], _ kk: Int) { let n = nums.count let k = kk % n if n==0 || k==0 {return} // O(N), N is the length of resulting array. // subscript time cost is unknown. nums = Array(nums[(n-k)..<n]) + nums // O(k) nums.dropLast(k) } /// Other solution might use reverse array to solve this problem. } /** * https://leetcode.com/problems/rotate-array/ * * */ // Date: Mon May 4 10:06:39 PDT 2020 class Solution { func rotate(_ nums: inout [Int], _ k: Int) { let k = k % nums.count reverse(&nums, 0, nums.count - 1) reverse(&nums, 0, k - 1) reverse(&nums, k, nums.count - 1) } private func reverse(_ nums: inout [Int], _ start: Int, _ end: Int) { var start = start var end = end while start < end { nums.swapAt(start, end) start += 1 end -= 1 } } }
mit
9f0070f9bc74c50a9851795c4fd099bc
23.021739
73
0.495023
3.46395
false
false
false
false
airbnb/lottie-ios
Sources/Private/Utility/Helpers/AnimationContext.swift
3
2361
// // AnimationContext.swift // lottie-swift // // Created by Brandon Withrow on 2/1/19. // import CoreGraphics import Foundation import QuartzCore /// A completion block for animations. `true` is passed in if the animation completed playing. public typealias LottieCompletionBlock = (Bool) -> Void // MARK: - AnimationContext struct AnimationContext { init( playFrom: AnimationFrameTime, playTo: AnimationFrameTime, closure: LottieCompletionBlock?) { self.playTo = playTo self.playFrom = playFrom self.closure = AnimationCompletionDelegate(completionBlock: closure) } var playFrom: AnimationFrameTime var playTo: AnimationFrameTime var closure: AnimationCompletionDelegate } // MARK: Equatable extension AnimationContext: Equatable { /// Whether or not the two given `AnimationContext`s are functionally equivalent /// - This checks whether or not a completion handler was provided, /// but does not check whether or not the two completion handlers are equivalent. static func == (_ lhs: AnimationContext, _ rhs: AnimationContext) -> Bool { lhs.playTo == rhs.playTo && lhs.playFrom == rhs.playFrom && (lhs.closure.completionBlock == nil) == (rhs.closure.completionBlock == nil) } } // MARK: - AnimationContextState enum AnimationContextState { case playing case cancelled case complete } // MARK: - AnimationCompletionDelegate class AnimationCompletionDelegate: NSObject, CAAnimationDelegate { // MARK: Lifecycle init(completionBlock: LottieCompletionBlock?) { self.completionBlock = completionBlock super.init() } // MARK: Public public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { guard ignoreDelegate == false else { return } animationState = flag ? .complete : .cancelled if let animationLayer = animationLayer, let key = animationKey { animationLayer.removeAnimation(forKey: key) if flag { animationLayer.currentFrame = (anim as! CABasicAnimation).toValue as! CGFloat } } if let completionBlock = completionBlock { completionBlock(flag) } } // MARK: Internal var animationLayer: RootAnimationLayer? var animationKey: String? var ignoreDelegate = false var animationState: AnimationContextState = .playing let completionBlock: LottieCompletionBlock? }
apache-2.0
3bbd0a2ef3a63546d267e5114eaed8ca
24.945055
94
0.724693
4.722
false
false
false
false
hdoria/HDNTextField
Example/Pods/Quick/Sources/Quick/World.swift
1
8627
import Foundation /** A closure that, when evaluated, returns a dictionary of key-value pairs that can be accessed from within a group of shared examples. */ public typealias SharedExampleContext = () -> [String: Any] /** A closure that is used to define a group of shared examples. This closure may contain any number of example and example groups. */ public typealias SharedExampleClosure = (@escaping SharedExampleContext) -> () /** A collection of state Quick builds up in order to work its magic. World is primarily responsible for maintaining a mapping of QuickSpec classes to root example groups for those classes. It also maintains a mapping of shared example names to shared example closures. You may configure how Quick behaves by calling the -[World configure:] method from within an overridden +[QuickConfiguration configure:] method. */ final internal class World: NSObject { /** The example group that is currently being run. The DSL requires that this group is correctly set in order to build a correct hierarchy of example groups and their examples. */ internal var currentExampleGroup: ExampleGroup! /** The example metadata of the test that is currently being run. This is useful for using the Quick test metadata (like its name) at runtime. */ internal var currentExampleMetadata: ExampleMetadata? /** A flag that indicates whether additional test suites are being run within this test suite. This is only true within the context of Quick functional tests. */ #if _runtime(_ObjC) // Convention of generating Objective-C selector has been changed on Swift 3 @objc(isRunningAdditionalSuites) internal var isRunningAdditionalSuites = false #else internal var isRunningAdditionalSuites = false #endif private var specs: Dictionary<String, ExampleGroup> = [:] private var sharedExamples: [String: SharedExampleClosure] = [:] private let configuration = Configuration() private var isConfigurationFinalized = false internal var exampleHooks: ExampleHooks {return configuration.exampleHooks } internal var suiteHooks: SuiteHooks { return configuration.suiteHooks } // MARK: Singleton Constructor private override init() {} static let sharedWorld = World() // MARK: Public Interface /** Exposes the World's Configuration object within the scope of the closure so that it may be configured. This method must not be called outside of an overridden +[QuickConfiguration configure:] method. - parameter closure: A closure that takes a Configuration object that can be mutated to change Quick's behavior. */ internal func configure(_ closure: QuickConfigurer) { assert(!isConfigurationFinalized, "Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method.") closure(configuration) } /** Finalizes the World's configuration. Any subsequent calls to World.configure() will raise. */ internal func finalizeConfiguration() { isConfigurationFinalized = true } /** Returns an internally constructed root example group for the given QuickSpec class. A root example group with the description "root example group" is lazily initialized for each QuickSpec class. This root example group wraps the top level of a -[QuickSpec spec] method--it's thanks to this group that users can define beforeEach and it closures at the top level, like so: override func spec() { // These belong to the root example group beforeEach {} it("is at the top level") {} } - parameter cls: The QuickSpec class for which to retrieve the root example group. - returns: The root example group for the class. */ internal func rootExampleGroupForSpecClass(_ cls: AnyClass) -> ExampleGroup { let name = String(describing: cls) if let group = specs[name] { return group } else { let group = ExampleGroup( description: "root example group", flags: [:], isInternalRootExampleGroup: true ) specs[name] = group return group } } /** Returns all examples that should be run for a given spec class. There are two filtering passes that occur when determining which examples should be run. That is, these examples are the ones that are included by inclusion filters, and are not excluded by exclusion filters. - parameter specClass: The QuickSpec subclass for which examples are to be returned. - returns: A list of examples to be run as test invocations. */ internal func examples(_ specClass: AnyClass) -> [Example] { // 1. Grab all included examples. let included = includedExamples // 2. Grab the intersection of (a) examples for this spec, and (b) included examples. let spec = rootExampleGroupForSpecClass(specClass).examples.filter { included.contains($0) } // 3. Remove all excluded examples. return spec.filter { example in !self.configuration.exclusionFilters.reduce(false) { $0 || $1(example) } } } #if _runtime(_ObjC) @objc(examplesForSpecClass:) private func objc_examples(_ specClass: AnyClass) -> [Example] { return examples(specClass) } #endif // MARK: Internal internal func registerSharedExample(_ name: String, closure: @escaping SharedExampleClosure) { raiseIfSharedExampleAlreadyRegistered(name) sharedExamples[name] = closure } internal func sharedExample(_ name: String) -> SharedExampleClosure { raiseIfSharedExampleNotRegistered(name) return sharedExamples[name]! } internal var includedExampleCount: Int { return includedExamples.count } internal var beforesCurrentlyExecuting: Bool { let suiteBeforesExecuting = suiteHooks.phase == .beforesExecuting let exampleBeforesExecuting = exampleHooks.phase == .beforesExecuting var groupBeforesExecuting = false if let runningExampleGroup = currentExampleMetadata?.example.group { groupBeforesExecuting = runningExampleGroup.phase == .beforesExecuting } return suiteBeforesExecuting || exampleBeforesExecuting || groupBeforesExecuting } internal var aftersCurrentlyExecuting: Bool { let suiteAftersExecuting = suiteHooks.phase == .aftersExecuting let exampleAftersExecuting = exampleHooks.phase == .aftersExecuting var groupAftersExecuting = false if let runningExampleGroup = currentExampleMetadata?.example.group { groupAftersExecuting = runningExampleGroup.phase == .aftersExecuting } return suiteAftersExecuting || exampleAftersExecuting || groupAftersExecuting } internal func performWithCurrentExampleGroup(_ group: ExampleGroup, closure: () -> Void) { let previousExampleGroup = currentExampleGroup currentExampleGroup = group closure() currentExampleGroup = previousExampleGroup } private var allExamples: [Example] { var all: [Example] = [] for (_, group) in specs { group.walkDownExamples { all.append($0) } } return all } private var includedExamples: [Example] { let all = allExamples let included = all.filter { example in return self.configuration.inclusionFilters.reduce(false) { $0 || $1(example) } } if included.isEmpty && configuration.runAllWhenEverythingFiltered { return all } else { return included } } private func raiseIfSharedExampleAlreadyRegistered(_ name: String) { if sharedExamples[name] != nil { raiseError("A shared example named '\(name)' has already been registered.") } } private func raiseIfSharedExampleNotRegistered(_ name: String) { if sharedExamples[name] == nil { raiseError("No shared example named '\(name)' has been registered. Registered shared examples: '\(Array(sharedExamples.keys))'") } } }
mit
5078d8dea83d1126e9a8f97f8db5291b
36.185345
243
0.670569
5.295887
false
true
false
false
ViennaRSS/vienna-rss
Vienna/Sources/Main window/TabbedBrowserViewController.swift
2
13275
// // TabbedBrowserViewController.swift // Vienna // // Copyright 2018 Tassilo Karge // // 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 // // https://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 Cocoa import MMTabBarView import WebKit class TabbedBrowserViewController: NSViewController, RSSSource { @IBOutlet private(set) weak var tabBar: MMTabBarView? { didSet { guard let tabBar = self.tabBar else { return } tabBar.setStyleNamed("Mojave") tabBar.onlyShowCloseOnHover = true tabBar.canCloseOnlyTab = false tabBar.disableTabClose = false tabBar.allowsBackgroundTabClosing = true tabBar.hideForSingleTab = true tabBar.showAddTabButton = true tabBar.buttonMinWidth = 120 tabBar.useOverflowMenu = true tabBar.automaticallyAnimates = true // TODO: figure out what this property means tabBar.allowsScrubbing = true } } @IBOutlet private(set) weak var tabView: NSTabView? /// The tab view item configured with the view that shall be in the first /// fixed (e.g. bookmarks). This method will set the primary tab the first /// time it is called. var primaryTab: NSTabViewItem? { didSet { // Temove from tabView if there was a prevous primary tab if let primaryTab = oldValue { self.closeTab(primaryTab) } if let primaryTab = self.primaryTab { tabView?.insertTabViewItem(primaryTab, at: 0) tabBar?.select(primaryTab) } } } var restoredTabs = false var activeTab: Tab? { tabView?.selectedTabViewItem?.viewController as? Tab } var browserTabCount: Int { tabView?.numberOfTabViewItems ?? 0 } weak var rssSubscriber: RSSSubscriber? { didSet { for source in tabView?.tabViewItems ?? [] { (source as? RSSSource)?.rssSubscriber = self.rssSubscriber } } } weak var contextMenuDelegate: BrowserContextMenuDelegate? override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder: NSCoder) { guard let tabBar = coder.decodeObject(of: MMTabBarView.self, forKey: "tabBar"), let tabView = coder.decodeObject(of: NSTabView.self, forKey: "tabView"), let primaryTab = coder.decodeObject(of: NSTabViewItem.self, forKey: "primaryTab") else { return nil } self.tabBar = tabBar self.tabView = tabView self.primaryTab = primaryTab super.init(coder: coder) } override func encode(with aCoder: NSCoder) { aCoder.encode(tabBar, forKey: "tabBar") aCoder.encode(tabBar, forKey: "tabView") aCoder.encode(tabBar, forKey: "primaryTab") } override func viewWillAppear() { super.viewWillAppear() if !restoredTabs { // Defer to avoid loading first tab, because primary tab is set // after view load. restoreTabs() restoredTabs = true } } func restoreTabs() { guard let tabLinks = Preferences.standard.array(forKey: "TabList") as? [String] else { return } let tabTitles = Preferences.standard.object(forKey: "TabTitleDict") as? [String: String] for urlString in tabLinks { guard let url = URL(string: urlString) else { continue } let tab = createNewTab(url, inBackground: true, load: false) as? BrowserTab tab?.title = tabTitles?[urlString] } } func saveOpenTabs() { let tabsOptional = tabBar?.tabView.tabViewItems.compactMap { $0.viewController as? BrowserTab } guard let tabs = tabsOptional else { return } let tabLinks = tabs.compactMap { $0.tabUrl?.absoluteString } let tabTitleList: [(String, String)] = tabs.filter { $0.tabUrl != nil && $0.title != nil }.map { ($0.tabUrl?.absoluteString ?? "", $0.title ?? "") } let tabTitles = Dictionary(tabTitleList) { $1 } Preferences.standard.setArray(tabLinks as [Any], forKey: "TabList") Preferences.standard.setObject(tabTitles, forKey: "TabTitleDict") } func closeTab(_ tabViewItem: NSTabViewItem) { self.tabBar?.close(tabViewItem) } } extension TabbedBrowserViewController: Browser { func createNewTab(_ url: URL?, inBackground: Bool, load: Bool) -> Tab { createNewTab(url, inBackground: inBackground, load: load, insertAt: nil) } func createNewTab(_ request: URLRequest, config: WKWebViewConfiguration, inBackground: Bool, insertAt index: Int? = nil) -> Tab { let newTab = BrowserTab(request, config: config) return initNewTab(newTab, request.url, false, inBackground, insertAt: index) } func createNewTab(_ url: URL? = nil, inBackground: Bool = false, load: Bool = false, insertAt index: Int? = nil) -> Tab { let newTab = BrowserTab() return initNewTab(newTab, url, load, inBackground, insertAt: index) } private func initNewTab(_ newTab: BrowserTab, _ url: URL?, _ load: Bool, _ inBackground: Bool, insertAt index: Int? = nil) -> Tab { newTab.rssSubscriber = self.rssSubscriber let newTabViewItem = TitleChangingTabViewItem(viewController: newTab) newTabViewItem.hasCloseButton = true // This must be executed after setup of titleChangingTabViewItem to // observe new title properly. newTab.tabUrl = url if load { newTab.loadTab() } if let index = index { tabView?.insertTabViewItem(newTabViewItem, at: index) } else { tabView?.addTabViewItem(newTabViewItem) } if !inBackground { tabBar?.select(newTabViewItem) if load { newTab.webView.becomeFirstResponder() } else { newTab.activateAddressBar() } // TODO: make first responder? } newTab.webView.contextMenuProvider = self // TODO: tab view order return newTab } func switchToPrimaryTab() { if self.primaryTab != nil { self.tabView?.selectTabViewItem(at: 0) } } func showPreviousTab() { self.tabView?.selectPreviousTabViewItem(nil) } func showNextTab() { self.tabView?.selectNextTabViewItem(nil) } func closeActiveTab() { if let selectedTabViewItem = self.tabView?.selectedTabViewItem { self.closeTab(selectedTabViewItem) } } func closeAllTabs() { self.tabView?.tabViewItems.filter { $0 != primaryTab } .forEach(closeTab) } func getTextSelection() -> String { // TODO: implement return "" } func getActiveTabHTML() -> String { // TODO: implement return "" } func getActiveTabURL() -> URL? { // TODO: implement return URL(string: "") } } extension TabbedBrowserViewController: MMTabBarViewDelegate { func tabView(_ aTabView: NSTabView, shouldClose tabViewItem: NSTabViewItem) -> Bool { tabViewItem != primaryTab } func tabView(_ aTabView: NSTabView, willClose tabViewItem: NSTabViewItem) { guard let tab = tabViewItem.viewController as? Tab else { return } tab.closeTab() } func tabView(_ aTabView: NSTabView, selectOnClosing tabViewItem: NSTabViewItem) -> NSTabViewItem? { // Select tab item on the right of currently selected item. Cannot // select tab on the right, if selected tab is rightmost one. if let tabView = self.tabBar?.tabView, let selected = tabBar?.selectedTabViewItem, selected == tabViewItem, tabViewItem != tabView.tabViewItems.last, let indexToSelect = tabView.tabViewItems.firstIndex(of: selected)?.advanced(by: 1) { return tabView.tabViewItems[indexToSelect] } else { // Default (left of currently selected item / no change if deleted // item not selected) return nil } } func tabView(_ aTabView: NSTabView, menuFor tabViewItem: NSTabViewItem) -> NSMenu { // TODO: return menu corresponding to browser or primary tab view item return NSMenu() } func tabView(_ aTabView: NSTabView, shouldDrag tabViewItem: NSTabViewItem, in tabBarView: MMTabBarView) -> Bool { tabViewItem != primaryTab } func tabView(_ aTabView: NSTabView, validateDrop sender: NSDraggingInfo, proposedItem tabViewItem: NSTabViewItem, proposedIndex: UInt, in tabBarView: MMTabBarView) -> NSDragOperation { proposedIndex != 0 ? [.every] : [] } func tabView(_ aTabView: NSTabView, validateSlideOfProposedItem tabViewItem: NSTabViewItem, proposedIndex: UInt, in tabBarView: MMTabBarView) -> NSDragOperation { (tabViewItem != primaryTab && proposedIndex != 0) ? [.every] : [] } func addNewTab(to aTabView: NSTabView) { _ = self.createNewTab() } func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { let tab = (tabViewItem?.viewController as? BrowserTab) if let loaded = tab?.loadedTab, !loaded { tab?.loadTab() } } func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MA_Notify_TabChanged"), object: tabViewItem?.view) } } // MARK: WKUIDelegate + BrowserContextMenuDelegate extension TabbedBrowserViewController: CustomWKUIDelegate { // TODO: implement functionality for alerts and maybe peek actions func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { let newTab = self.createNewTab(navigationAction.request, config: configuration, inBackground: false, insertAt: getIndexAfterSelected()) if let webView = webView as? CustomWKWebView { // The listeners are removed from the old webview userContentController on creating the new one, restore them webView.resetScriptListeners() } return (newTab as? BrowserTab)?.webView } func contextMenuItemsFor(purpose: WKWebViewContextMenuContext, existingMenuItems: [NSMenuItem]) -> [NSMenuItem] { var menuItems = existingMenuItems switch purpose { case .page(url: _): break case .link(let url): addLinkMenuCustomizations(&menuItems, url) case .picture: break case .pictureLink(image: _, link: let link): addLinkMenuCustomizations(&menuItems, link) case .text: break } return self.contextMenuDelegate? .contextMenuItemsFor(purpose: purpose, existingMenuItems: menuItems) ?? menuItems } private func addLinkMenuCustomizations(_ menuItems: inout [NSMenuItem], _ url: (URL)) { guard let index = menuItems.firstIndex(where: { $0.identifier == .WKMenuItemOpenLinkInNewWindow }) else { return } menuItems[index].title = NSLocalizedString("Open Link in New Tab", comment: "") let openInBackgroundTitle = NSLocalizedString("Open Link in Background", comment: "") let openInBackgroundItem = NSMenuItem(title: openInBackgroundTitle, action: #selector(openLinkInBackground(menuItem:)), keyEquivalent: "") openInBackgroundItem.identifier = .WKMenuItemOpenLinkInBackground openInBackgroundItem.representedObject = url menuItems.insert(openInBackgroundItem, at: menuItems.index(after: index)) } @objc func openLinkInBackground(menuItem: NSMenuItem) { if let url = menuItem.representedObject as? URL { _ = self.createNewTab(url, inBackground: true, load: true, insertAt: getIndexAfterSelected()) } } @objc func contextMenuItemAction(menuItem: NSMenuItem) { self.contextMenuDelegate?.contextMenuItemAction(menuItem: menuItem) } private func getIndexAfterSelected() -> Int { guard let tabView = tabView, let selectedItem = tabView.selectedTabViewItem else { return 0 } let selectedIndex = tabView.tabViewItems.firstIndex(of: selectedItem) ?? 0 return tabView.tabViewItems.index(after: selectedIndex) } }
apache-2.0
ff1d4933a2cdd5a870ea207cbcb7474b
34.494652
188
0.637213
4.808041
false
false
false
false
superpixelhq/AbairLeat-iOS
Abair Leat/View Controllers/LoginViewController.swift
1
2940
// // LoginViewController.swift // Abair Leat // // Created by Aaron Signorelli on 19/11/2015. // Copyright © 2015 Superpixel. All rights reserved. // import UIKit import FBSDKLoginKit import SVProgressHUD import Firebase class LoginViewController: UIViewController { @IBOutlet weak var loginButton: UIButton! let manager = FBSDKLoginManager() override func viewDidLoad() { super.viewDidLoad() loginButton.hidden = true // check if we're already logged into facebook if let fbAccessToken = FBSDKAccessToken.currentAccessToken() { let fb = AbairLeat.shared.baseFirebaseRef let authData = fb.authData if authData != nil && (authData.auth["uid"] as! String == "facebook:\(fbAccessToken.userID)") { // already logged in AbairLeat.shared.profile.userDidLogin({ (_, _) -> Void in self.loginComplete() }) } else { login(FBSDKAccessToken.currentAccessToken().tokenString) } } else { // user isn't logged in loginButton.hidden = false } } override func prefersStatusBarHidden() -> Bool { return true } @IBAction func loginWithFacebook(sender: AnyObject) { loginButton.hidden = true let permissions = ["public_profile", "user_friends"] manager.logInWithReadPermissions(permissions, fromViewController: self) { (facebookResult, facebookError) -> Void in if facebookError != nil { SVProgressHUD.showErrorWithStatus("Facebook login failed. Error \(facebookError)") self.loginButton.hidden = false } else if facebookResult.isCancelled { // don't need to do anything here. The user knows they cancelled self.loginButton.hidden = false } else { // hide the button whilst we login to Firebase self.loginButton.hidden = true self.login(FBSDKAccessToken.currentAccessToken().tokenString) } } } func login(facebookAccessToken: String) { AbairLeat.shared.profile.login(facebookAccessToken) { (profile, error) -> Void in if error != nil { SVProgressHUD.showErrorWithStatus("Login failed. \(error)") self.loginButton.hidden = false return } self.loginComplete() } } func loginComplete() { self.performSegueWithIdentifier("start_app", sender: self) // Ask the user for permission to send push notifications AbairLeat.shared.profile.requestPushNotificationToken() } @IBAction func unwindToLogin(sender: UIStoryboardSegue) { FBSDKLoginManager().logOut() loginButton.hidden = false } }
apache-2.0
ebfb42b620cb91cc45dbc611e2a7d09f
32.397727
107
0.595781
5.257603
false
false
false
false
ushisantoasobu/CocuLabel
CocuLabel/CocuLabel.swift
1
8244
import UIKit class CocuLabel: UILabel { //priority color private var firstColor :UIColor? private var secondColor :UIColor? private var thirdColor :UIColor? //resolution when analyze color private let resolution :CGFloat = 0.1 // private var saturationCoefficient :CGFloat = 0.75 // var colorThreshold :CGFloat = 0.55 // MARK: - public /** update color */ func updateColor() { var originalHidden = self.hidden self.hidden = true self.dispatch_async_global { var image = self.captureBackImage() var colorList = self.getColorListFromImage(image) var sumColor = self.getSumColor(colorList) self.dispatch_async_main { if self.firstColor == nil || self.secondColor == nil || self.thirdColor == nil { self.textColor = self.getInvertedColor(sumColor) } else { self.textColor = self.getSatisfiedPriorityColor(sumColor) } self.hidden = false if originalHidden == true { self.hidden = true } } } } /** set priority colors */ func setPriorityColor(first :UIColor, second :UIColor, third :UIColor) { self.firstColor = first self.secondColor = second self.thirdColor = third } // MARK: - private /** increase saturation */ private func increaseSaturation(color :UIColor) -> UIColor { var r :CGFloat = self.getRGBFromUIColor(color).r var g :CGFloat = self.getRGBFromUIColor(color).g var b :CGFloat = self.getRGBFromUIColor(color).b r = self.getSaturation(r) g = self.getSaturation(g) b = self.getSaturation(b) return UIColor(red: r, green: g, blue: b, alpha: 1.0) } /** get color for increasing saturation. it's my original, and temporary */ private func getSaturation(a :CGFloat) -> CGFloat { if a > 0.5 { return min(((a - 0.5) * (a - 0.5) * saturationCoefficient + a), 1.0) } else { return max(((a - 0.5) * (a - 0.5) * saturationCoefficient * (-1) + a), 0.0) } } /** capture image of label back */ private func captureBackImage() -> UIImage { var frame = self.frame var top = UIApplication.sharedApplication().keyWindow?.rootViewController while((top?.presentedViewController) != nil) { top = top?.presentedViewController } //add margin for getting more optimized color frame = self.addMargin(frame, parentFrame: top!.view.frame) UIGraphicsBeginImageContextWithOptions(frame.size, false, resolution) var context = UIGraphicsGetCurrentContext() CGContextTranslateCTM(context, -frame.origin.x, -frame.origin.y) var layer = top?.view.layer layer?.renderInContext(context) var capture = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return capture } //test private func addMargin(targetFrame :CGRect, parentFrame :CGRect) -> CGRect { let margin :CGFloat = 40 //TODO return CGRectMake(targetFrame.origin.x - margin, targetFrame.origin.y - margin, targetFrame.width + margin * 2, targetFrame.height + margin * 2) } /** get color list from image */ private func getColorListFromImage(image :UIImage) -> Array<UIColor> { var colorList = Array<UIColor>() var pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage)) var data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) var w = CGImageGetWidth(image.CGImage) var h = CGImageGetHeight(image.CGImage) for var x :UInt = 0; x < w; x++ { for var y :UInt = 0; y < h; y++ { var pixelInfo: Int = Int(w * y + x) * 4 var b = CGFloat(data[pixelInfo]) var g = CGFloat(data[pixelInfo+1]) var r = CGFloat(data[pixelInfo+2]) colorList.append(UIColor(red: r / 255, green: g / 255, blue: b / 255, alpha: 1.0)) } } return colorList } /** get inverted color (complementary color is better?? but complementary color of white is...white??) */ private func getInvertedColor(color :UIColor) -> UIColor { var r :CGFloat = self.getRGBFromUIColor(color).r var g :CGFloat = self.getRGBFromUIColor(color).g var b :CGFloat = self.getRGBFromUIColor(color).b //rgbともに0.5から±0.15におさまるときは //反転してもあまり違いがでないので白か黒に寄せる if abs(r - 0.5) < 0.15 && abs(g - 0.5) < 0.15 && abs(b - 0.5) < 0.15 { var average = (r + g + b) / 3 return average > 0.5 ? UIColor.blackColor() : UIColor.whiteColor() } return self.increaseSaturation(UIColor(red: 1 - r, green: 1 - g, blue: 1 - b, alpha: 1.0)) } /** get sum color from color list WIP!!!! */ private func getSumColor(colorList :Array<UIColor>) -> UIColor { //TODO: what is better Alogolitm!!?? var count = colorList.count var sumR :CGFloat = 0 var sumG :CGFloat = 0 var sumB :CGFloat = 0 for color in colorList { sumR += self.getRGBFromUIColor(color).r sumG += self.getRGBFromUIColor(color).g sumB += self.getRGBFromUIColor(color).b } return UIColor(red: sumR / CGFloat(count), green: sumG / CGFloat(count), blue: sumB / CGFloat(count), alpha: 1.0) } /** get priority color which statisfied */ private func getSatisfiedPriorityColor(targetColor :UIColor) -> UIColor { if self.isThresholdOver(targetColor, targetColor: self.firstColor!, threshold: self.colorThreshold) { return self.firstColor! } else if self.isThresholdOver(targetColor, targetColor: self.secondColor!, threshold: self.colorThreshold) { return self.secondColor! } else if self.isThresholdOver(targetColor, targetColor: self.thirdColor!, threshold: self.colorThreshold) { return self.thirdColor! } else { //if all priority colors don't satisfy, get inverted color return self.getInvertedColor(targetColor) } } /** check the color is threshold over */ private func isThresholdOver(baseColor :UIColor, targetColor :UIColor, threshold :CGFloat) -> Bool { if abs(self.getRGBFromUIColor(targetColor).r - self.getRGBFromUIColor(baseColor).r) < threshold && abs(self.getRGBFromUIColor(targetColor).g - self.getRGBFromUIColor(baseColor).g) < threshold && abs(self.getRGBFromUIColor(targetColor).b - self.getRGBFromUIColor(baseColor).b) < threshold { return false } return true } // MARK: - helper method private func getRGBFromUIColor(color :UIColor) -> (r :CGFloat, g :CGFloat, b :CGFloat) { var r :CGFloat = 0 var g :CGFloat = 0 var b :CGFloat = 0 var a :CGFloat = 1.0 color.getRed(&r, green: &g, blue: &b, alpha: &a) return (r :r, g :g, b :b) } func dispatch_async_main(block: () -> ()) { dispatch_async(dispatch_get_main_queue(), block) } func dispatch_async_global(block: () -> ()) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block) } }
mit
8c7cc228d59e15ebf22420707b6993c0
30.548263
121
0.550851
4.47726
false
false
false
false
kfarst/alarm
alarm/SettingModalView.swift
1
2310
// // SettingModalView.swift // alarm // // Created by Kevin Farst on 3/24/15. // Copyright (c) 2015 Kevin Farst. All rights reserved. // import Foundation class SettingsModalView { private var settingsModal: SettingsModalViewController! private var parentController: UIViewController! private var widthRatio = CGFloat(0.92) private var heightRatio = CGFloat(0.8) private var cornerRadius = CGFloat(6.0) required init(parentVC: UIViewController) { parentController = parentVC settingsModal = SettingsModalViewController(nibName: "SettingsModalViewController", bundle: nil) self.parentController.addChildViewController(settingsModal) settingsModal.view.autoresizingMask = .FlexibleWidth | .FlexibleHeight settingsModal.openPosition = parentController.view.center.y setEdgeDimensionsAndStyling() settingsModal.closedPosition = settingsModal.view.center.y applyPlainShadow(settingsModal.view) parentController.view.addSubview(settingsModal.view) settingsModal.didMoveToParentViewController(parentController) } func toggleInView(hide hidden: Bool) { if hidden { settingsModal.view.center.y = settingsModal.view.center.y + settingsModal.closedPosition } else { settingsModal.view.center.y = settingsModal.closedPosition } } private func applyPlainShadow(view: UIView) { let layer = view.layer layer.shadowPath = UIBezierPath(rect: CGRectMake(0, 0, settingsModal.view.frame.width, settingsModal.view.frame.height)).CGPath layer.shadowColor = UIColor.blackColor().CGColor layer.shadowOffset = CGSize(width: 0, height: 10) layer.shadowOpacity = 0.4 layer.shadowRadius = 5 } private func setEdgeDimensionsAndStyling() { settingsModal.view.frame = CGRectMake( (parentController.view.frame.size.width - (parentController.view.frame.size.width * widthRatio)) / 2.0, parentController.view.frame.size.height - settingsModal.topBorder.frame.minY, parentController.view.frame.size.width * widthRatio, parentController.view.frame.size.height * heightRatio ) settingsModal.view.layer.cornerRadius = cornerRadius settingsModal.view.layer.masksToBounds = true settingsModal.view.clipsToBounds = true } }
mit
dc38ef1374011b778a8fbc2afb3bec47
34.015152
131
0.738528
4.485437
false
false
false
false
benlangmuir/swift
validation-test/compiler_crashers_2_fixed/issue59572.swift
5
239
// RUN: %target-swift-emit-ir %s // https://github.com/apple/swift/issues/59572 func foo<T: RawRepresentable>(src: Any, target: inout T) where T.RawValue == UInt { if let x = src as? UInt, let x = T(rawValue: x) { target = x } }
apache-2.0
f8bd6182ee1b0762545cf7d7d3284b68
25.555556
83
0.635983
2.845238
false
false
false
false
VDKA/JSON
Sources/JSON/JSONRepresentable.swift
2
3608
/// Used to declare that that a type can be represented as JSON public protocol JSONRepresentable { /* NOTE: This should be a throwing method. As if any of JSONRepresentable's fields are FloatingPoint.NaN or .infinity they cannot be represented as valid RFC conforming JSON. This isn't currently throwing because it is called by `*literalType` initializers in order to convert [JSONRepresentable] & [String: JSONRepresentable] */ /// Returns a `JSON` representation of `self` func encoded() -> JSON } // MARK: - JSON Conformance to JSONRepresentable extension JSON: JSONRepresentable { public init(_ value: JSONRepresentable) { self = value.encoded() } } // MARK: - Add `serialized` to `JSONRepresentable` extension JSONRepresentable { public func serialized(options: JSON.Serializer.Option = []) throws -> String { return try JSON.Serializer.serialize(self.encoded(), options: options) } } // NOTE: track http://www.openradar.me/23433955 // MARK: - Add encoded to Optional JSONRepresentables extension Optional where Wrapped: JSONRepresentable { public func encoded() -> JSON { guard let `self` = self else { return JSON.null } return JSON(self) } } // MARK: - Add encoded to RawRepresentable JSONRepresentables extension RawRepresentable where RawValue: JSONRepresentable { public func encoded() -> JSON { return JSON(rawValue) } } // MARK: - Add encoded to Sequences of JSONRepresentable extension Sequence where Iterator.Element: JSONRepresentable { public func encoded() -> JSON { return .array(self.map({ $0.encoded() })) } } // MARK: - Add encoded to Sequences of [String: JSONRepresentable] extension Sequence where Iterator.Element == (key: String, value: JSONRepresentable) { public func encoded() -> JSON { var encoded: [String: JSON] = [:] for (key, value) in self { encoded[key] = value.encoded() } return .object(encoded) } } // MARK: - Bool Conformance to JSONRepresentable extension Bool: JSONRepresentable { public func encoded() -> JSON { return .bool(self) } } // MARK: - String Conformance to JSONRepresentable extension String: JSONRepresentable { public func encoded() -> JSON { return .string(self) } } // MARK: - FloatingPointTypes: JSONRepresentable extension Double: JSONRepresentable { public func encoded() -> JSON { return .double(self) } } extension Float: JSONRepresentable { public func encoded() -> JSON { return .double(Double(self)) } } // MARK: - IntegerTypes: JSONRepresentable // NOTE: This sucks. It is very repetitive and ugly, is there a possiblity of `extension IntegerType: JSONRepresentable` in the future? extension Int: JSONRepresentable { public func encoded() -> JSON { return .integer(Int64(self)) } } extension UInt8: JSONRepresentable { public func encoded() -> JSON { return .integer(Int64(self)) } } extension UInt16: JSONRepresentable { public func encoded() -> JSON { return .integer(Int64(self)) } } extension UInt32: JSONRepresentable { public func encoded() -> JSON { return .integer(Int64(self)) } } extension Int8: JSONRepresentable { public func encoded() -> JSON { return .integer(Int64(self)) } } extension Int16: JSONRepresentable { public func encoded() -> JSON { return .integer(Int64(self)) } } extension Int32: JSONRepresentable { public func encoded() -> JSON { return .integer(Int64(self)) } } extension Int64: JSONRepresentable { public func encoded() -> JSON { return .integer(self) } }
mit
b0ba9f9181bcbb25a9d44ec09e6e474c
19.269663
135
0.692905
4.151899
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/Alamofire/Source/NetworkReachabilityManager.swift
27
9100
// // NetworkReachabilityManager.swift // // Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if !os(watchOS) import Foundation import SystemConfiguration /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and /// WiFi network interfaces. /// /// Reachability can be used to determine background information about why a network operation failed, or to retry /// network requests when a connection is established. It should not be used to prevent a user from initiating a network /// request, as it's possible that an initial request may be required to establish reachability. open class NetworkReachabilityManager { /// Defines the various states of network reachability. /// /// - unknown: It is unknown whether the network is reachable. /// - notReachable: The network is not reachable. /// - reachable: The network is reachable. public enum NetworkReachabilityStatus { case unknown case notReachable case reachable(ConnectionType) } /// Defines the various connection types detected by reachability flags. /// /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. /// - wwan: The connection type is a WWAN connection. public enum ConnectionType { case ethernetOrWiFi case wwan } /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. public typealias Listener = (NetworkReachabilityStatus) -> Void // MARK: - Properties /// Whether the network is currently reachable. open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } /// Whether the network is currently reachable over the WWAN interface. open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } /// Whether the network is currently reachable over Ethernet or WiFi interface. open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } /// The current network reachability status. open var networkReachabilityStatus: NetworkReachabilityStatus { guard let flags = self.flags else { return .unknown } return networkReachabilityStatusForFlags(flags) } /// The dispatch queue to execute the `listener` closure on. open var listenerQueue: DispatchQueue = DispatchQueue.main /// A closure executed when the network reachability status changes. open var listener: Listener? open var flags: SCNetworkReachabilityFlags? { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(reachability, &flags) { return flags } return nil } private let reachability: SCNetworkReachability open var previousFlags: SCNetworkReachabilityFlags // MARK: - Initialization /// Creates a `NetworkReachabilityManager` instance with the specified host. /// /// - parameter host: The host used to evaluate network reachability. /// /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?(host: String) { guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } self.init(reachability: reachability) } /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. /// /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing /// status of the device, both IPv4 and IPv6. /// /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?() { var address = sockaddr_in() address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) address.sin_family = sa_family_t(AF_INET) guard let reachability = withUnsafePointer(to: &address, { pointer in return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) { return SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return nil } self.init(reachability: reachability) } private init(reachability: SCNetworkReachability) { self.reachability = reachability // Set the previous flags to an unreserved value to represent unknown status self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30) } deinit { stopListening() } // MARK: - Listening /// Starts listening for changes in network reachability status. /// /// - returns: `true` if listening was started successfully, `false` otherwise. @discardableResult open func startListening() -> Bool { var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = Unmanaged.passUnretained(self).toOpaque() let callbackEnabled = SCNetworkReachabilitySetCallback( reachability, { (_, flags, info) in let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue() reachability.notifyListener(flags) }, &context ) let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) listenerQueue.async { guard let flags = self.flags else { return } self.notifyListener(flags) } return callbackEnabled && queueEnabled } /// Stops listening for changes in network reachability status. open func stopListening() { SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) } // MARK: - Internal - Listener Notification func notifyListener(_ flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } previousFlags = flags listener?(networkReachabilityStatusForFlags(flags)) } // MARK: - Internal - Network Reachability Status func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { guard isNetworkReachable(with: flags) else { return .notReachable } var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) #if os(iOS) if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } #endif return networkStatus } func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) return isReachable && (!needsConnection || canConnectWithoutUserInteraction) } } // MARK: - extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} /// Returns whether the two network reachability status values are equal. /// /// - parameter lhs: The left-hand side value to compare. /// - parameter rhs: The right-hand side value to compare. /// /// - returns: `true` if the two values are equal, `false` otherwise. public func ==( lhs: NetworkReachabilityManager.NetworkReachabilityStatus, rhs: NetworkReachabilityManager.NetworkReachabilityStatus) -> Bool { switch (lhs, rhs) { case (.unknown, .unknown): return true case (.notReachable, .notReachable): return true case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): return lhsConnectionType == rhsConnectionType default: return false } } #endif
mit
5b22fa6eb28114ef959a209665754893
37.723404
122
0.704396
5.378251
false
false
false
false
strike65/SwiftyStats
SwiftyStats/CommonSource/ProbDist/ProbDist-Poisson.swift
1
5278
// // Created by VT on 20.07.18. // Copyright © 2018 strike65. All rights reserved. /* Copyright (2017-2019) strike65 GNU GPL 3+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation #if os(macOS) || os(iOS) import os.log #endif extension SSProbDist { /// Poisson distribution public enum Poisson { /// Returns a SSProbDistParams struct containing mean, variance, kurtosis and skewness of the Binomial distribution. /// - Parameter n: Number of events /// - Parameter lambda: rate /// - Throws: SSSwiftyStatsError if lambda <= 0, n < 0 public static func para<FPT: SSFloatingPoint & Codable>(numberOfEvents n: Int, rate lambda: FPT) throws -> SSProbDistParams<FPT> { if lambda <= 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("lambda is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if n < 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("n is expected to be >= 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } var result: SSProbDistParams<FPT> = SSProbDistParams<FPT>() result.mean = lambda result.variance = lambda result.kurtosis = 3 + FPT.one / lambda result.skewness = FPT.one / sqrt(lambda) return result } /// Returns the cdf of the Poisson Distribution /// - Parameter k: number of events /// - Parameter lambda: rate /// - Parameter tail: .lower, .upper /// - Throws: SSSwiftyStatsError if lambda <= 0, k < 0 public static func cdf<FPT: SSFloatingPoint & Codable>(k: Int, rate lambda: FPT, tail: SSCDFTail) throws -> FPT { if lambda <= 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("lambda is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if k < 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("k is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } var conv: Bool = false let result: FPT = SSSpecialFunctions.gammaNormalizedQ(x: lambda, a: 1 + Helpers.makeFP(k), converged: &conv) if conv { switch tail { case .lower: return result case .upper: return 1 - result } } else { return FPT.nan } } /// Returns the pdf of the Poisson Distribution /// - Parameter k: number of events /// - Parameter lambda: rate /// - Throws: SSSwiftyStatsError if lambda <= 0, k < 0 public static func pdf<FPT: SSFloatingPoint & Codable>(k: Int, rate lambda: FPT) throws -> FPT { if lambda <= 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("lambda is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } if k < 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("k is expected to be > 0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } let result: FPT = Helpers.makeFP(k) * SSMath.log1(lambda) - lambda - SSMath.logFactorial(k) return SSMath.exp1(result) } } }
gpl-3.0
a5188bb49ccff1995798a59486e10748
40.226563
138
0.545007
4.35396
false
false
false
false
overtake/TelegramSwift
packages/InAppSettings/Sources/InAppSettings/AutoplayPreferences.swift
1
5710
// // AutoplayPreferences.swift // Telegram // // Created by Mikhail Filimonov on 11/02/2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import Postbox import SwiftSignalKit import TelegramCore public class AutoplayMediaPreferences : Codable, Equatable { public let gifs: Bool public let videos: Bool public let soundOnHover: Bool public let preloadVideos: Bool public let loopAnimatedStickers: Bool init(gifs: Bool, videos: Bool, soundOnHover: Bool, preloadVideos: Bool, loopAnimatedStickers: Bool ) { self.gifs = gifs self.videos = videos self.soundOnHover = soundOnHover self.preloadVideos = preloadVideos self.loopAnimatedStickers = loopAnimatedStickers } public static var defaultSettings: AutoplayMediaPreferences { return AutoplayMediaPreferences(gifs: true, videos: true, soundOnHover: true, preloadVideos: true, loopAnimatedStickers: true) } public required init(decoder: PostboxDecoder) { self.gifs = decoder.decodeInt32ForKey("g", orElse: 0) == 1 self.videos = decoder.decodeInt32ForKey("v", orElse: 0) == 1 self.soundOnHover = decoder.decodeInt32ForKey("soh", orElse: 0) == 1 self.preloadVideos = decoder.decodeInt32ForKey("pv", orElse: 0) == 1 self.loopAnimatedStickers = decoder.decodeInt32ForKey("las", orElse: 0) == 1 } public func encode(_ encoder: PostboxEncoder) { encoder.encodeInt32(gifs ? 1 : 0, forKey: "g") encoder.encodeInt32(videos ? 1 : 0, forKey: "v") encoder.encodeInt32(soundOnHover ? 1 : 0, forKey: "soh") encoder.encodeInt32(preloadVideos ? 1 : 0, forKey: "pv") encoder.encodeInt32(loopAnimatedStickers ? 1 : 0, forKey: "las") } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) self.gifs = try container.decode(Int32.self, forKey: "g") == 1 self.videos = try container.decode(Int32.self, forKey: "v") == 1 self.soundOnHover = try container.decode(Int32.self, forKey: "soh") == 1 self.preloadVideos = try container.decode(Int32.self, forKey: "pv") == 1 self.loopAnimatedStickers = try container.decode(Int32.self, forKey: "las") == 1 } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(Int32(self.gifs ? 1 : 0), forKey: "g") try container.encode(Int32(self.videos ? 1 : 0), forKey: "v") try container.encode(Int32(self.soundOnHover ? 1 : 0), forKey: "soh") try container.encode(Int32(self.preloadVideos ? 1 : 0), forKey: "pv") try container.encode(Int32(self.loopAnimatedStickers ? 1 : 0), forKey: "las") } public static func == (lhs: AutoplayMediaPreferences, rhs: AutoplayMediaPreferences) -> Bool { return lhs.gifs == rhs.gifs && lhs.videos == rhs.videos && lhs.soundOnHover == rhs.soundOnHover && lhs.preloadVideos == rhs.preloadVideos && lhs.loopAnimatedStickers == rhs.loopAnimatedStickers } public func withUpdatedAutoplayGifs(_ gifs: Bool) -> AutoplayMediaPreferences { return AutoplayMediaPreferences(gifs: gifs, videos: self.videos, soundOnHover: self.soundOnHover, preloadVideos: self.preloadVideos, loopAnimatedStickers: self.loopAnimatedStickers) } public func withUpdatedAutoplayVideos(_ videos: Bool) -> AutoplayMediaPreferences { return AutoplayMediaPreferences(gifs: self.gifs, videos: videos, soundOnHover: self.soundOnHover, preloadVideos: self.preloadVideos, loopAnimatedStickers: self.loopAnimatedStickers) } public func withUpdatedAutoplaySoundOnHover(_ soundOnHover: Bool) -> AutoplayMediaPreferences { return AutoplayMediaPreferences(gifs: self.gifs, videos: self.videos, soundOnHover: soundOnHover, preloadVideos: self.preloadVideos, loopAnimatedStickers: self.loopAnimatedStickers) } public func withUpdatedAutoplayPreloadVideos(_ preloadVideos: Bool) -> AutoplayMediaPreferences { return AutoplayMediaPreferences(gifs: self.gifs, videos: self.videos, soundOnHover: self.soundOnHover, preloadVideos: preloadVideos, loopAnimatedStickers: self.loopAnimatedStickers) } public func withUpdatedLoopAnimatedStickers(_ loopAnimatedStickers: Bool) -> AutoplayMediaPreferences { return AutoplayMediaPreferences(gifs: self.gifs, videos: self.videos, soundOnHover: self.soundOnHover, preloadVideos: self.preloadVideos, loopAnimatedStickers: loopAnimatedStickers) } } public func updateAutoplayMediaSettingsInteractively(postbox: Postbox, _ f: @escaping (AutoplayMediaPreferences) -> AutoplayMediaPreferences) -> Signal<Void, NoError> { return postbox.transaction { transaction -> Void in transaction.updatePreferencesEntry(key: ApplicationSpecificPreferencesKeys.autoplayMedia, { entry in let currentSettings: AutoplayMediaPreferences if let entry = entry?.get(AutoplayMediaPreferences.self) { currentSettings = entry } else { currentSettings = AutoplayMediaPreferences.defaultSettings } return PreferencesEntry(f(currentSettings)) }) } } public func autoplayMediaSettings(postbox: Postbox) -> Signal<AutoplayMediaPreferences, NoError> { return postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.autoplayMedia]) |> map { views in return views.values[ApplicationSpecificPreferencesKeys.autoplayMedia]?.get(AutoplayMediaPreferences.self) ?? AutoplayMediaPreferences.defaultSettings } }
gpl-2.0
f1000475f61a12de0f4634d034c3e3c4
49.973214
201
0.713435
4.167153
false
false
false
false
natecook1000/swift
test/Inputs/conditional_conformance_basic_conformances.swift
1
20151
public func takes_p1<T: P1>(_: T.Type) {} public protocol P1 { func normal() func generic<T: P3>(_: T) } public protocol P2 {} public protocol P3 {} public struct IsP2: P2 {} public struct IsP3: P3 {} public struct Single<A> {} extension Single: P1 where A: P2 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Single.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$S42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE6normalyyF"(%swift.type* [[A]], i8** [[A_P2]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Single.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$S42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[A]], %swift.type* %"\CF\84_1_0", i8** [[A_P2]], i8** %"\CF\84_1_0.P3") // CHECK-NEXT: ret void // CHECK-NEXT: } public func single_generic<T: P2>(_: T.Type) { takes_p1(Single<T>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S42conditional_conformance_basic_conformances14single_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S42conditional_conformance_basic_conformances6SingleVMa"(i64 0, %swift.type* %T) // CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8 // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @"$S42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlWa"(%swift.type* [[Single_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Witness table accessor for Single : P1 // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} i8** @"$S42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlWa"(%swift.type*, i8***) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLE:%.*]] = call i8** @swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @"$S42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlWG", %swift.type* %0, i8*** %1) // CHECK-NEXT: ret i8** [[TABLE]] // CHECK-NEXT: } public func single_concrete() { takes_p1(Single<IsP2>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S42conditional_conformance_basic_conformances15single_concreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @"$S42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete Single<IsP2> : P1. // CHECK-LABEL: define linkonce_odr hidden i8** @"$S42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$S42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$S42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Single_P1:%.*]] = call i8** @"$S42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlWa"(%swift.type* [[Single_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) [[ATTRS:#[0-9]+]] // CHECK-NEXT: store atomic i8** [[Single_P1]], i8*** @"$S42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Single_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } public struct Double<B, C> {} extension Double: P1 where B: P2, C: P3 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Double.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$S42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8** // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2 // CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3 // CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE6normalyyF"(%swift.type* [[B]], %swift.type* [[C]], i8** [[B_P2]], i8** [[C_P3]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Double.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$S42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP7genericyyqd__AaGRd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8** // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2 // CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3 // CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE7genericyyqd__AaERd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[B]], %swift.type* [[C]], %swift.type* %"\CF\84_1_0", i8** [[B_P2]], i8** [[C_P3]], i8** %"\CF\84_1_0.P3") // CHECK-NEXT: ret void // CHECK-NEXT: } public func double_generic_generic<U: P2, V: P3>(_: U.Type, _: V.Type) { takes_p1(Double<U, V>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S42conditional_conformance_basic_conformances015double_generic_F0yyxm_q_mtAA2P2RzAA2P3R_r0_lF"(%swift.type*, %swift.type*, %swift.type* %U, %swift.type* %V, i8** %U.P2, i8** %V.P3) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %U, %swift.type* %V) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %U.P2, i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** %V.P3, i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @"$S42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlWa"(%swift.type* [[Double_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness table accessor for Double : P1 // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} i8** @"$S42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlWa"(%swift.type*, i8***) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLE:%.*]] = call i8** @swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @"$S42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlWG", %swift.type* %0, i8*** %1) // CHECK-NEXT: ret i8** [[TABLE]] // CHECK-NEXT: } public func double_generic_concrete<X: P2>(_: X.Type) { takes_p1(Double<X, IsP3>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S42conditional_conformance_basic_conformances23double_generic_concreteyyxmAA2P2RzlF"(%swift.type*, %swift.type* %X, i8** %X.P2) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %X, %swift.type* bitcast (i64* getelementptr inbounds (<{ i8**, i64, <{ {{.*}} }>* }>, <{ {{.*}} }>* @"$S42conditional_conformance_basic_conformances4IsP3VMf", i32 0, i32 1) to %swift.type*)) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %X.P2, i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$S42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @"$S42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlWa"(%swift.type* [[Double_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func double_concrete_concrete() { takes_p1(Double<IsP2, IsP3>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S42conditional_conformance_basic_conformances016double_concrete_F0yyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 0) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @"$S42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"() // CHECK-NEXT: call swiftcc void @"$S42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete Double<IsP2, IsP3> : P1. // CHECK-LABEL: define linkonce_odr hidden i8** @"$S42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [2 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$S42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 0) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$S42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$S42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @"$S42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlWa"(%swift.type* [[Double_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]]) // CHECK-NEXT: store atomic i8** [[Double_P1]], i8*** @"$S42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Double_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } // # Witness table instantiators // witness table instantiator for Single : P1 // CHECK-LABEL: define internal void @"$S42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlWI"(i8**, %swift.type* %"Single<A>", i8**) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLES:%.*]] = bitcast i8** %1 to i8*** // CHECK-NEXT: [[A_P2_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 0 // CHECK-NEXT: [[A_P2_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8**, i8*** [[A_P2_SRC]], align 8 // CHECK-NEXT: [[CAST_A_P2_DEST:%.*]] = bitcast i8** [[A_P2_DEST]] to i8*** // CHECK-NEXT: store i8** [[A_P2]], i8*** [[CAST_A_P2_DEST]], align 8 // CHECK-NEXT: ret void // CHECK-NEXT: } // witness table instantiator for Double : P1 // CHECK-LABEL: define internal void @"$S42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlWI"(i8**, %swift.type* %"Double<B, C>", i8**) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLES:%.*]] = bitcast i8** %1 to i8*** // CHECK-NEXT: [[B_P2_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 0 // CHECK-NEXT: [[B_P2_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -1 // CHECK-NEXT: [[B_P2:%.*]] = load i8**, i8*** [[B_P2_SRC]], align 8 // CHECK-NEXT: [[CAST_B_P2_DEST:%.*]] = bitcast i8** [[B_P2_DEST]] to i8*** // CHECK-NEXT: store i8** [[B_P2]], i8*** [[CAST_B_P2_DEST]], align 8 // CHECK-NEXT: [[C_P3_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 1 // CHECK-NEXT: [[C_P3_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -2 // CHECK-NEXT: [[C_P3:%.*]] = load i8**, i8*** [[C_P3_SRC]], align 8 // CHECK-NEXT: [[CAST_C_P3_DEST:%.*]] = bitcast i8** [[C_P3_DEST]] to i8*** // CHECK-NEXT: store i8** [[C_P3]], i8*** [[CAST_C_P3_DEST]], align 8 // CHECK-NEXT: ret void // CHECK-NEXT: } func dynamicCastToP1(_ value: Any) -> P1? { return value as? P1 } protocol P4 {} typealias P4Typealias = P4 protocol P5 {} struct SR7101<T> {} extension SR7101 : P5 where T == P4Typealias {} // CHECK: attributes [[ATTRS]] = { nounwind }
apache-2.0
01b41ff6e107ceb1011b283be8efee28
64.638436
383
0.655898
2.981358
false
false
false
false
mikekavouras/Glowb-iOS
Glowb/Models/Photo.swift
1
3739
// // Photo.swift // Glowb // // Created by Michael Kavouras on 12/12/16. // Copyright © 2016 Michael Kavouras. All rights reserved. // import Alamofire import ObjectMapper import PromiseKit enum PhotoError: Error { case failedToCreate case invalidS3Params case failedToProcessImage } struct Photo: Mappable { var id: Int? var filename: String? var ext: String = "" var mimeType: String? var originalWidth: CGFloat = 0 var originalHeight: CGFloat = 0 var eTag: String = "" var token: String? var url: String? var s3Params: JSON? // MARK: - Life cycle // MARK: - init?(map: Map) {} // MARK: - Mapping // MARK: - mutating func mapping(map: Map) { id <- map["id"] s3Params <- map["params"] originalHeight <- map["original_height"] originalWidth <- map["original_width"] url <- map["url"] token <- map["token"] } func toJSON() -> [String : Any] { return [ "sha" : eTag, "original_width" : originalWidth, "original_height" : originalHeight, ] } // MARK: - API // MARK: - // MARK: create static func create(image: UIImage, uploadProgressHandler: @escaping (Progress) -> Void) -> Promise<Photo> { return Promise { fulfill, reject in guard let jpeg = UIImageJPEGRepresentation(image, 0.9) else { reject(PhotoError.failedToProcessImage) return } Alamofire.request(Router.createPhoto).validate().responseJSON { response in let result = PhotoParser.parseResponse(response) switch result { case .success(var photo): guard let params = photo.s3Params else { reject(PhotoError.invalidS3Params) return } S3ImageUploader.uploadImage(jpeg: jpeg, params: params, progressHandler: uploadProgressHandler).then { eTag -> Void in photo.originalHeight = image.size.height photo.originalWidth = image.size.width photo.eTag = eTag photo.update().then { photo in fulfill(photo) }.catch { error in reject(error) } }.catch { error in reject(error) } case .failure(let error): reject(error) } } } } // MARK: update func update() -> Promise<Photo> { return Promise { fulfill, reject in Alamofire.request(Router.updatePhoto(self)).validate().responseJSON { response in let result = PhotoParser.parseResponse(response) switch result { case .success(let photo): fulfill(photo) case .failure(let error): reject(error) } } } } } private struct PhotoParser: ServerResponseParser { static func parseJSON(_ json: JSON) -> Alamofire.Result<Photo> { guard let photo = Mapper<Photo>().map(JSON: json) else { return .failure(ServerError.invalidJSONFormat) } return .success(photo) } }
mit
1fffbf36080cd1313fa6068253aee0f0
27.318182
138
0.479936
5.302128
false
false
false
false
finder39/Swignals
Source/Swignal5Args.swift
1
1777
// // Swignal5Args.swift // Plug // // Created by Joseph Neuman on 7/6/16. // Copyright © 2016 Plug. All rights reserved. // import Foundation open class Swignal5Args<A,B,C,D,E>: SwignalBase { public override init() { } open func addObserver<L: AnyObject>(_ observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D, _ arg5: E) -> ()) { let observer = Observer5Args(swignal: self, observer: observer, callback: callback) addSwignalObserver(observer) } open func fire(_ arg1: A, arg2: B, arg3: C, arg4: D, arg5: E) { synced(self) { for watcher in self.swignalObservers { watcher.fire(arg1, arg2, arg3, arg4, arg5) } } } } private class Observer5Args<L: AnyObject,A,B,C,D,E>: ObserverGenericBase<L> { let callback: (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D, _ arg5: E) -> () init(swignal: SwignalBase, observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D, _ arg5: E) -> ()) { self.callback = callback super.init(swignal: swignal, observer: observer) } override func fire(_ args: Any...) { if let arg1 = args[0] as? A, let arg2 = args[1] as? B, let arg3 = args[2] as? C, let arg4 = args[3] as? D, let arg5 = args[4] as? E { fire(arg1: arg1, arg2: arg2, arg3: arg3, arg4: arg4, arg5: arg5) } else { assert(false, "Types incorrect") } } fileprivate func fire(arg1: A, arg2: B, arg3: C, arg4: D, arg5: E) { if let observer = observer { callback(observer, arg1, arg2, arg3, arg4, arg5) } } }
mit
628a13ae9461eec7e428111600bc7f3a
31.290909
154
0.54223
3.056799
false
false
false
false
soleiltw/ios-swift-basic
Workshop/Taipei-City-Water-Quality/Taipei-City-Water-Quality/Object/Station.swift
1
2300
// // Station.swift // Taipei-City-Water-Quality // // Created by Edward Chiang on 21/10/2017. // Copyright © 2017 Soleil Software Studio Inc. All rights reserved. // import Foundation class Station { // Swift Advance enum WaterQuality { case normal, notNormal } // Swfit Basic var updateDate: String = "" var updateTime: String = "" var quaId: String = "" var codeName: String = "" var longitude: String = "" var latitude: String = "" var quaCntu: String = "" var quaCl: String = "" var quaPh: String = "" func init_populate(dictionary:Dictionary<String, Any>) { updateDate = dictionary["update_date"] as! String updateTime = dictionary["update_time"] as! String quaId = dictionary["qua_id"] as! String codeName = dictionary["code_name"] as! String longitude = dictionary["longitude"] as! String latitude = dictionary["latitude"] as! String quaCntu = dictionary["qua_cntu"] as! String quaCl = dictionary["qua_cl"] as! String quaPh = dictionary["qua_ph"] as! String } func checkCntu() -> WaterQuality { if Double(self.quaCntu)! < 0.3 { return .normal } else { return .notNormal } } func checkCl() -> WaterQuality { if Double(self.quaCl)! > 0.2 && Double(self.quaCl)! < 2.0 { return .normal } else { return .notNormal } } func checkPh() -> WaterQuality { if Double(self.quaPh)! > 6 && Double(self.quaPh)! < 8.5 { return .normal } else { return .notNormal } } class func DateFromString(dateString:String, timeString:String) -> Date { let dateFormatter = DateFormatter() let enUSPosixLocale = Locale(identifier: "en_US_POSIX") dateFormatter.locale = enUSPosixLocale as Locale! dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return dateFormatter.date(from: "\(dateString) \(timeString)")! } class func populate(dictionary:Dictionary<String, Any>) -> Station { let result = Station() result.init_populate(dictionary: dictionary) return result } }
mit
8668d3b791adfb8e26dab0d3e7302a10
27.382716
75
0.575903
4.134892
false
false
false
false
KasunApplications/susi_iOS
Susi/Model/Client/Constants.swift
1
4410
// // Constants.swift // Susi // // Created by Chashmeet Singh on 31/01/17. // Copyright © 2017 FOSSAsia. All rights reserved. // extension Client { struct APIURLs { static let SusiAPI = "http://api.susi.ai" static let DuckDuckGo = "http://api.duckduckgo.com" static let YoutubeSearch = "https://www.googleapis.com/youtube/v3/search" static let SnowboyTrain = "https://snowboy.kitt.ai/api/v1/train/" } struct Methods { static let Login = "/aaa/login.json" static let Register = "/aaa/signup.json" static let Chat = "/susi/chat.json" static let RecoverPassword = "/aaa/recoverpassword.json" static let Memory = "/susi/memory.json" static let UserSettings = "/aaa/changeUserSettings.json" static let ListUserSettings = "/aaa/listUserSettings.json" static let SendFeedback = "/cms/rateSkill.json" static let ChangePassword = "/aaa/changepassword.json" } struct ResponseMessages { static let InvalidParams = "Email ID / Password incorrect" static let ServerError = "Problem connecting to server!" static let SignedOut = "Successfully logged out" static let PasswordInvalid = "Password chosen is invalid." } struct UserKeys { static let AccessToken = "access_token" static let Message = "message" static let Login = "login" static let SignUp = "signup" static let Password = "password" static let ForgotEmail = "forgotemail" static let ValidSeconds = "valid_seconds" static let EmailOfAccount = "changepassword" static let NewPassword = "newpassword" } struct ChatKeys { static let Answers = "answers" static let Query = "query" static let TimeZoneOffset = "timezoneOffset" static let AnswerDate = "answer_date" static let ResponseType = "type" static let Expression = "expression" static let Actions = "actions" static let Skills = "skills" static let AccessToken = "access-token" static let Latitude = "latitude" static let Longitude = "longitude" static let Zoom = "zoom" static let Language = "language" static let Data = "data" static let Count = "count" static let Title = "title" static let Link = "link" static let Description = "description" static let Text = "text" static let Columns = "columns" static let QueryDate = "query_date" static let ShortenedUrl = "finalUrl" static let Image = "image" static let Cognitions = "cognitions" } struct WebsearchKeys { static let RelatedTopics = "RelatedTopics" static let Icon = "Icon" static let Url = "URL" static let FirstURL = "FirstURL" static let Text = "Text" static let Heading = "Heading" static let Format = "format" static let Query = "q" static let Result = "Result" } struct YoutubeParamKeys { static let Part = "part" static let Query = "q" static let Key = "key" } struct YoutubeParamValues { static let Part = "snippet" static let Key = "AIzaSyAx6TqPYDDL2VekgdEU-8kHHfplJSmqoTw" } struct YoutubeResponseKeys { static let Items = "items" static let ID = "id" static let VideoID = "videoId" } struct WebSearch { static let image = "no-image" static let noData = "No data found" static let duckDuckGo = "https://duckduckgo.com/" static let noDescription = "No Description" } struct FeedbackKeys { static let model = "model" static let group = "group" static let skill = "skill" static let language = "language" static let rating = "rating" } struct HotwordKeys { static let name = "name" static let token = "token" static let microphone = "microphone" static let language = "language" static let voiceSamples = "voice_samples" static let wave = "wave" } struct HotwordValues { static let susi = "susi" static let token = "1b286c615e95d848814144e6ffe0551505fe979c" static let microphone = "iphone microphone" static let language = "en" } }
apache-2.0
46a791b07d11e5776e089e53503c6357
31.419118
81
0.611703
4.268151
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/MarketplaceCommerceAnalytics/MarketplaceCommerceAnalytics_Error.swift
1
1961
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for MarketplaceCommerceAnalytics public struct MarketplaceCommerceAnalyticsErrorType: AWSErrorType { enum Code: String { case marketplaceCommerceAnalyticsException = "MarketplaceCommerceAnalyticsException" } private let error: Code public let context: AWSErrorContext? /// initialize MarketplaceCommerceAnalytics public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// This exception is thrown when an internal service error occurs. public static var marketplaceCommerceAnalyticsException: Self { .init(.marketplaceCommerceAnalyticsException) } } extension MarketplaceCommerceAnalyticsErrorType: Equatable { public static func == (lhs: MarketplaceCommerceAnalyticsErrorType, rhs: MarketplaceCommerceAnalyticsErrorType) -> Bool { lhs.error == rhs.error } } extension MarketplaceCommerceAnalyticsErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
513a88135f1556126bd68ee8dcc96e65
33.403509
124
0.665987
4.890274
false
false
false
false
karnett/CWIT
cwitExample/AppDelegate.swift
1
6012
import UIKit import CoreData @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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack @objc lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.hpe.usps.mobility.cwitExample" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() @objc lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "cwitExample", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() @objc lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() @objc lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support @objc func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
91a947129f324f3f22f921c95e6eb6d7
57.368932
291
0.718563
5.894118
false
false
false
false
barteljan/VISPER
VISPER-Entity/Classes/MemoryEntityStore.swift
1
13091
// // MemoryEntityStore.swift // Pods-VISPER-Entity-Example // // Created by bartel on 06.04.18. // import Foundation open class MemoryEntityStore: EntityStore { public enum StoreError: Error { case cannotExtractIdentifierFrom(item: Any) case functionNotImplementedYet } struct PersistenceItem { let identifier: String let updated: Bool let value: Any? let deleted: Bool let type: Any.Type } var store = [String: [String: PersistenceItem]]() public init(){} public init(_ items: [Any]) throws { for item in items { try self.persist(item, markAsUpdated: false) } } open func isResponsible<T>(for object: T) -> Bool { return true } open func isResponsible<T>(forType type: T.Type) -> Bool { return true } open func get<T>(_ identifier: String) throws -> T? { let typeString = self.typeToKey(type: T.self) guard let typesDict = self.store[typeString] else { return nil } guard let persistenceItem = typesDict[identifier] else { return nil } guard persistenceItem.deleted == false else { return nil } return persistenceItem.value as? T } open func get<T>(_ identifier: String, completion: @escaping (T?) -> Void) throws { let item: T? = try self.get(identifier) completion(item) } open func delete<T>(_ item: T!) throws { guard let item = item else { return } let typeString = self.itemToKey(item: item) var typesDict: [String: PersistenceItem] if let dict = self.store[typeString] { typesDict = dict } else { typesDict = [String: PersistenceItem]() } let identifier = try self.identifierForItem(item: item) let persistenceItem = PersistenceItem(identifier: identifier, updated: false, value: item, deleted: true, type: T.self) typesDict[identifier] = persistenceItem self.store[typeString] = typesDict } open func delete<T>(_ item: T!, completion: @escaping () -> ()) throws { try self.delete(item) completion() } open func delete<T>(_ items: [T]) throws { for item in items { try self.delete(item) } } open func delete<T>(_ identifier: String, type: T.Type) throws { if let item: T = try self.get(identifier){ try self.delete(item) } else { let typeString = self.typeToKey(type: type) var typesDict: [String: PersistenceItem] if let dict = self.store[typeString] { typesDict = dict } else { typesDict = [String: PersistenceItem]() } let persistenceItem = PersistenceItem(identifier: identifier, updated: false, value: nil, deleted: true, type: T.self) typesDict[identifier] = persistenceItem self.store[typeString] = typesDict } } open func persist<T>(_ item: T!) throws { try self.persist(item, markAsUpdated: true) } func persist<T>(_ item: T!, markAsUpdated: Bool) throws { guard let item = item else { return } let typeString = self.itemToKey(item: item) var typesDict: [String: PersistenceItem] if let dict = self.store[typeString] { typesDict = dict } else { typesDict = [String: PersistenceItem]() } let identifier = try self.identifierForItem(item: item) let persistenceItem = PersistenceItem(identifier: identifier, updated: markAsUpdated, value: item, deleted: false, type: T.self) typesDict[identifier] = persistenceItem self.store[typeString] = typesDict } open func persist<T>(_ item: T!, completion: @escaping () -> ()) throws { try self.persist(item) completion() } open func getAll<T>(_ type: T.Type) throws -> [T] { let typeString = self.typeToKey(type: T.self) guard let typesDict = self.store[typeString] else { return [T]() } var result = [T]() for (_,item) in typesDict.enumerated() { if item.value.value != nil && item.value.deleted == false { if let value = item.value.value as? T{ result.append(value) } } } return result } open func getAll<T>(_ type: T.Type, completion: @escaping ([T]) -> Void) throws { let items: [T] = try self.getAll(T.self) completion(items) } open func getAll<T>(_ viewName: String) throws -> [T] { throw StoreError.functionNotImplementedYet } open func getAll<T>(_ viewName: String, completion: @escaping ([T]) -> Void) throws { throw StoreError.functionNotImplementedYet } open func getAll<T>(_ viewName: String, groupName: String) throws -> [T] { throw StoreError.functionNotImplementedYet } open func getAll<T>(_ viewName: String, groupName: String, completion: @escaping ([T]) -> Void) throws { throw StoreError.functionNotImplementedYet } open func exists<T>(_ item: T!) throws -> Bool { let typeString = self.itemToKey(item: item!) guard let typesDict = self.store[typeString] else { return false } let identifier = try self.identifierForItem(item: item) if let item = typesDict[identifier] { if item.value != nil && item.deleted == false { return true } else { return false } } else { return false } } open func exists<T>(_ item: T!, completion: @escaping (Bool) -> Void) throws { let doesExist = try self.exists(item) completion(doesExist) } open func exists<T>(_ identifier: String, type: T.Type) throws -> Bool { let typeString = self.typeToKey(type: T.self) guard let typesDict = self.store[typeString] else { return false } if let item = typesDict[identifier] { if item.value != nil && item.deleted == false { return true } else { return false } } else { return false } } open func exists<T>(_ identifier: String, type: T.Type, completion: @escaping (Bool) -> Void) throws { let doesExist = try self.exists(identifier, type: type) completion(doesExist) } open func filter<T>(_ type: T.Type, includeElement: @escaping (T) -> Bool) throws -> [T] { return try self.getAll(type).filter(includeElement) } open func filter<T>(_ type: T.Type, includeElement: @escaping (T) -> Bool, completion: @escaping ([T]) -> Void) throws { let items = try self.filter(type, includeElement: includeElement) completion(items) } open func addView<T>(_ viewName: String, groupingBlock: @escaping ((String, String, T) -> String?), sortingBlock: @escaping ((String, String, String, T, String, String, T) -> ComparisonResult)) throws { throw StoreError.functionNotImplementedYet } open func transaction(transaction: @escaping (EntityStore) throws -> Void) throws { let allEntities = self.allEntities() let transactionStore = try MemoryEntityStore(allEntities) try transaction(transactionStore) for entity in transactionStore.deletedEntities() { try self.delete(entity) } for entity in transactionStore.updatedEntities() { try self.persist(entity) } } open func allEntities() -> [Any] { var result = [Any]() for persistenceItemDict in self.store.enumerated() { for entry in persistenceItemDict.element.value.enumerated() { let item = entry.element.value if item.value != nil && item.deleted == false { result.append(item.value!) } } } return result } open func updatedEntities() -> [Any] { var result = [Any]() for persistenceItemDict in self.store.enumerated() { for entry in persistenceItemDict.element.value.enumerated() { let item = entry.element.value if item.value != nil && item.updated { result.append(item.value!) } } } return result } open func updatedEntities<T>(type: T.Type) -> [T] { let typeString = self.typeToKey(type: T.self) guard let typesDict = self.store[typeString] else { return [T]() } var result = [T]() for (_,item) in typesDict.enumerated() { if item.value.value != nil && item.value.updated == true { if let value = item.value.value as? T{ result.append(value) } } } return result } open func deletedEntities<T>(type: T.Type) -> [T] { let typeString = self.typeToKey(type: T.self) guard let typesDict = self.store[typeString] else { return [T]() } var result = [T]() for (_,item) in typesDict.enumerated() { if item.value.value != nil && item.value.deleted == true { if let value = item.value.value as? T{ result.append(value) } } } return result } open func deletedIds<T>(type: T.Type) -> [String] { let typeString = self.typeToKey(type: T.self) guard let typesDict = self.store[typeString] else { return [String]() } var result = [String]() for (_,item) in typesDict.enumerated() { if item.value.deleted == true { result.append(item.value.identifier) } } return result } open func deletedEntities() -> [Any] { var result = [Any]() for persistenceItemDict in self.store.enumerated() { for entry in persistenceItemDict.element.value.enumerated() { let item = entry.element.value if item.value != nil && item.deleted { result.append(item.value!) } } } return result } open func cleanDeletedEntitesFromMemory() { var tempStore = [String: [String: PersistenceItem]]() for type in self.store.enumerated() { var typeDict = [String: PersistenceItem]() for item in type.element.value.enumerated() { if item.element.value.deleted == false { typeDict[item.element.key] = item.element.value } } tempStore[type.element.key] = typeDict } self.store = tempStore } func identifierForItem<T>(item: T) throws -> String { if let item = item as? CanBeIdentified { return item.identifier() } if let item = item as? CustomStringConvertible { return item.description } throw StoreError.cannotExtractIdentifierFrom(item: item) } func typeToKey<T>(type aType: T.Type) -> String { return String(reflecting: aType) } func itemToKey(item: Any) -> String { return String(reflecting: type(of:item)) } }
mit
75acdfd690c26542e87570ae039bae51
28.417978
127
0.495913
4.956835
false
false
false
false
danielrcardenas/ac-course-2017
frameworks/SwarmChemistry-Swif/Demo_iOS/Utility.swift
1
1604
// // Utility.swift // SwarmChemistry // // Created by Yamazaki Mitsuyoshi on 2017/08/14. // Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved. // import UIKit extension UIViewController { @IBAction func dismiss(sender: AnyObject!) { dismiss(animated: true, completion: nil) } } extension UIView { func takeScreenshot(_ rect: CGRect? = nil) -> UIImage? { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0) drawHierarchy(in: bounds, afterScreenUpdates: true) let wholeImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let image = wholeImage, let rect = rect else { return wholeImage } let scale = image.scale let scaledRect = CGRect(x: rect.origin.x * scale, y: rect.origin.y * scale, width: rect.size.width * scale, height: rect.size.height * scale) guard let cgImage = image.cgImage?.cropping(to: scaledRect) else { return nil } return UIImage(cgImage: cgImage, scale: scale, orientation: .up) } } extension UIScrollView { var visibleRect: CGRect { var rect = CGRect.init(origin: contentOffset, size: bounds.size) rect.origin.x /= zoomScale rect.origin.y /= zoomScale rect.size.width /= zoomScale rect.size.height /= zoomScale return rect } } class TouchTransparentStackView: UIStackView { override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let hitView = super.hitTest(point, with: event) guard hitView !== self else { return nil } return hitView } }
apache-2.0
de72e14b5a731066a049e5d8d7132465
24.854839
145
0.67748
4.263298
false
false
false
false
amarcu5/PiPer
src/safari/App/InAppPurchaseHelper.swift
1
2739
// // InAppPurchaseHelper.swift // PiPer // // Created by Adam Marcus on 18/11/2018. // Copyright © 2018 Adam Marcus. All rights reserved. // import Foundation import StoreKit class InAppPurchaseHelper: NSObject { static let shared = InAppPurchaseHelper() public typealias RequestProductsCompletionHandler = (_ response: SKProductsResponse?, _ error: Error?) -> () public typealias BuyProductCompletionHandler = (_ transaction: SKPaymentTransaction) -> () private var productsRequestsInProgress = [SKRequest:RequestProductsCompletionHandler]() private var purchasesInProgress = [SKPayment:BuyProductCompletionHandler]() private let paymentQueue = SKPaymentQueue.default() private override init() { super.init() self.paymentQueue.add(self) } deinit { self.paymentQueue.remove(self) } func requestProducts(identifiers: Set<String>, completionHandler: @escaping RequestProductsCompletionHandler) { let request = SKProductsRequest(productIdentifiers: identifiers) self.productsRequestsInProgress[request] = completionHandler request.delegate = self request.start() } func buyProduct(_ product: SKProduct, completionHandler: @escaping BuyProductCompletionHandler) { let payment = SKPayment(product: product) self.purchasesInProgress[payment] = completionHandler self.paymentQueue.add(payment) } func canMakePayments() -> Bool { return SKPaymentQueue.canMakePayments() } } extension InAppPurchaseHelper: SKProductsRequestDelegate { func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { if let completionHandler = self.productsRequestsInProgress[request] { completionHandler(response, .none) } self.productsRequestsInProgress.removeValue(forKey: request) } func request(_ request: SKRequest, didFailWithError error: Error) { if let completionHandler = self.productsRequestsInProgress[request] { completionHandler(.none, error) } self.productsRequestsInProgress.removeValue(forKey: request) } } extension InAppPurchaseHelper: SKPaymentTransactionObserver { func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .purchased, .failed, .restored: if let completionHandler = self.purchasesInProgress[transaction.payment] { completionHandler(transaction) self.purchasesInProgress.removeValue(forKey: transaction.payment) } queue.finishTransaction(transaction) break case .purchasing, .deferred: break } } } }
gpl-3.0
53c38522a8bc08929bd0169f5cdaf35a
30.471264
113
0.734478
5.108209
false
false
false
false
tardieu/swift
test/SILGen/witness_same_type.swift
1
1400
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s // RUN: %target-swift-frontend -emit-ir %s protocol Fooable { associatedtype Bar func foo<T: Fooable where T.Bar == Self.Bar>(x x: T) -> Self.Bar } struct X {} // Ensure that the protocol witness for requirements with same-type constraints // is set correctly. <rdar://problem/16369105> // CHECK-LABEL: sil hidden [transparent] [thunk] @_T017witness_same_type3FooVAA7FooableAaaDP3foo3BarQzqd__1x_tAaDRd__AGQyd__AHRSlFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Fooable, τ_0_0.Bar == X> (@in τ_0_0, @in_guaranteed Foo) -> @out X struct Foo: Fooable { typealias Bar = X func foo<T: Fooable where T.Bar == X>(x x: T) -> X { return X() } } // rdar://problem/19049566 // CHECK-LABEL: sil [transparent] [thunk] @_T017witness_same_type14LazySequenceOfVyxq_Gs0E0AAsADRz8Iterator_7ElementQZRs_r0_lsADP04makeG0AEQzyFTW : $@convention(witness_method) <τ_0_0, τ_0_1 where τ_0_0 : Sequence, τ_0_1 == τ_0_0.Iterator.Element> (@in_guaranteed LazySequenceOf<τ_0_0, τ_0_1>) -> @out AnyIterator<τ_0_1> public struct LazySequenceOf<SS : Sequence, A where SS.Iterator.Element == A> : Sequence { public func makeIterator() -> AnyIterator<A> { var opt: AnyIterator<A>? return opt! } public subscript(i : Int) -> A { get { var opt: A? return opt! } } }
apache-2.0
a62a46412e1b830b322336862919aec8
39.823529
320
0.680836
2.909853
false
false
false
false
codefellows/sea-b23-iOS
Pinchot/Pinchot/ShowImageAnimator.swift
1
2172
// // ShowImageAnimator.swift // Pinchot // // Created by Andrew Shepard on 10/21/14. // Copyright (c) 2014 Andrew Shepard. All rights reserved. // import UIKit class ShowImageAnimator: NSObject, UIViewControllerAnimatedTransitioning { // Rectangle denoting where the animation should start from // Used for positioning the toViewController's view var origin: CGRect? func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 1.0 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // Find references for the two views controllers we're moving between let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as ViewController let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as ImageViewController // Grab the container view from the context let containerView = transitionContext.containerView() // Position the toViewController in it's starting position toViewController.view.frame = self.origin! toViewController.imageView.frame = toViewController.view.bounds // Add the toViewController's view onto the containerView containerView.addSubview(toViewController.view) UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in // During animation, expand the toViewController's view frame // to match the original view controllers // This will cause the toViewController to fill the screen toViewController.view.frame = fromViewController.view.frame toViewController.imageView.frame = toViewController.view.bounds }) { (finished) -> Void in // When finished, hide our fromViewController fromViewController.view.alpha = 0.0 // And tell the transitionContext we're done transitionContext.completeTransition(finished) } } }
mit
23cdf51320e0e1a14defc0ecb5f79ac5
43.326531
132
0.709484
6.170455
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/GCDKit/Sources/GCDSemaphore.swift
3
3443
// // GCDSemaphore.swift // GCDKit // // Copyright © 2014 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** A wrapper and utility class for dispatch_semaphore_t. */ @available(iOS, introduced=7.0) public struct GCDSemaphore { /** Creates new counting semaphore with an initial value. */ public init(_ value: Int) { self.rawObject = dispatch_semaphore_create(value) } /** Creates new counting semaphore with an initial value. */ public init(_ value: UInt) { self.init(Int(value)) } /** Creates new counting semaphore with a zero initial value. */ public init() { self.init(0) } /** Signals (increments) a semaphore. - returns: This function returns non-zero if a thread is woken. Otherwise, zero is returned. */ public func signal() -> Int { return dispatch_semaphore_signal(self.rawObject) } /** Waits for (decrements) a semaphore. */ public func wait() { dispatch_semaphore_wait(self.rawObject, DISPATCH_TIME_FOREVER) } /** Waits for (decrements) a semaphore. - parameter timeout: The number of seconds before timeout. - returns: Returns zero on success, or non-zero if the timeout occurred. */ public func wait(timeout: NSTimeInterval) -> Int { return dispatch_semaphore_wait(self.rawObject, dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSTimeInterval(NSEC_PER_SEC)))) } /** Waits for (decrements) a semaphore. - parameter date: The timeout date. - returns: Returns zero on success, or non-zero if the timeout occurred. */ public func wait(date: NSDate) -> Int { return self.wait(date.timeIntervalSinceNow) } /** Returns the dispatch_semaphore_t object associated with this value. - returns: The dispatch_semaphore_t object associated with this value. */ public func dispatchSemaphore() -> dispatch_semaphore_t { return self.rawObject } private let rawObject: dispatch_semaphore_t } public func ==(lhs: GCDSemaphore, rhs: GCDSemaphore) -> Bool { return lhs.dispatchSemaphore() === rhs.dispatchSemaphore() } extension GCDSemaphore: Equatable { }
apache-2.0
c577893c5c1c1e26f10f2212fdc44d7c
28.672414
135
0.661534
4.418485
false
false
false
false
milseman/swift
validation-test/stdlib/DictionaryBridging.swift
13
3553
// RUN: %empty-directory(%t) // // RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o // RUN: echo '#sourceLocation(file: "%s", line: 1)' > "%t/main.swift" && cat "%s" >> "%t/main.swift" && chmod -w "%t/main.swift" // RUN: %target-build-swift -Xfrontend -disable-access-control -I %S/Inputs/SlurpFastEnumeration/ %t/main.swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift -Xlinker %t/SlurpFastEnumeration.o -o %t.out -O // RUN: %target-run %t.out // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: nonatomic_rc import StdlibUnittest import Foundation import SlurpFastEnumeration struct DictionaryBridge_objectForKey_RaceTest : RaceTestWithPerTrialData { class RaceData { var nsd: NSDictionary init(nsd: NSDictionary) { self.nsd = nsd } } typealias ThreadLocalData = Void typealias Observation = Observation1UInt func makeRaceData() -> RaceData { let nsd = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: 1) return RaceData(nsd: nsd) } func makeThreadLocalData() -> Void { return Void() } let key = TestObjCKeyTy(10) func thread1( _ raceData: RaceData, _ threadLocalData: inout ThreadLocalData ) -> Observation { let nsd = raceData.nsd let v: AnyObject? = nsd.object(forKey: key).map { $0 as AnyObject } return Observation(unsafeBitCast(v, to: UInt.self)) } func evaluateObservations( _ observations: [Observation], _ sink: (RaceTestObservationEvaluation) -> Void ) { sink(evaluateObservationsAllEqual(observations)) } } struct DictionaryBridge_KeyEnumerator_FastEnumeration_ObjC_RaceTest : RaceTestWithPerTrialData { class RaceData { var nsd: NSDictionary init(nsd: NSDictionary) { self.nsd = nsd } } typealias ThreadLocalData = Void typealias Observation = Observation4UInt func makeRaceData() -> RaceData { let nsd = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: 2) return RaceData(nsd: nsd) } func makeThreadLocalData() -> Void { return Void() } func thread1( _ raceData: RaceData, _ threadLocalData: inout ThreadLocalData ) -> Observation { let nsd = raceData.nsd let objcPairs = NSMutableArray() slurpFastEnumerationOfDictionaryFromObjCImpl(nsd, nsd, objcPairs) return Observation( unsafeBitCast(objcPairs[0] as AnyObject, to: UInt.self), unsafeBitCast(objcPairs[1] as AnyObject, to: UInt.self), unsafeBitCast(objcPairs[2] as AnyObject, to: UInt.self), unsafeBitCast(objcPairs[3] as AnyObject, to: UInt.self)) } func evaluateObservations( _ observations: [Observation], _ sink: (RaceTestObservationEvaluation) -> Void ) { sink(evaluateObservationsAllEqual(observations)) } } var DictionaryTestSuite = TestSuite("Dictionary") DictionaryTestSuite.test( "BridgedToObjC.KeyValue_ValueTypesCustomBridged/RaceTest") { runRaceTest(DictionaryBridge_objectForKey_RaceTest.self, trials: 100) } DictionaryTestSuite.test( "BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromObjC/RaceTest") { runRaceTest( DictionaryBridge_KeyEnumerator_FastEnumeration_ObjC_RaceTest.self, trials: 100) } DictionaryTestSuite.setUp { resetLeaksOfDictionaryKeysValues() resetLeaksOfObjCDictionaryKeysValues() } DictionaryTestSuite.tearDown { expectNoLeaksOfDictionaryKeysValues() expectNoLeaksOfObjCDictionaryKeysValues() } runAllTests()
apache-2.0
09f423677ceb24651305382bdd7709b5
27.653226
243
0.731213
4.503169
false
true
false
false
milseman/swift
stdlib/public/core/Equatable.swift
9
10059
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Equatable //===----------------------------------------------------------------------===// /// A type that can be compared for value equality. /// /// Types that conform to the `Equatable` protocol can be compared for equality /// using the equal-to operator (`==`) or inequality using the not-equal-to /// operator (`!=`). Most basic types in the Swift standard library conform to /// `Equatable`. /// /// Some sequence and collection operations can be used more simply when the /// elements conform to `Equatable`. For example, to check whether an array /// contains a particular value, you can pass the value itself to the /// `contains(_:)` method when the array's element conforms to `Equatable` /// instead of providing a closure that determines equivalence. The following /// example shows how the `contains(_:)` method can be used with an array of /// strings. /// /// let students = ["Nora", "Fern", "Ryan", "Rainer"] /// /// let nameToCheck = "Ryan" /// if students.contains(nameToCheck) { /// print("\(nameToCheck) is signed up!") /// } else { /// print("No record of \(nameToCheck).") /// } /// // Prints "Ryan is signed up!" /// /// Conforming to the Equatable Protocol /// ==================================== /// /// Adding `Equatable` conformance to your custom types means that you can use /// more convenient APIs when searching for particular instances in a /// collection. `Equatable` is also the base protocol for the `Hashable` and /// `Comparable` protocols, which allow more uses of your custom type, such as /// constructing sets or sorting the elements of a collection. /// /// To adopt the `Equatable` protocol, implement the equal-to operator (`==`) /// as a static method of your type. The standard library provides an /// implementation for the not-equal-to operator (`!=`) for any `Equatable` /// type, which calls the custom `==` function and negates its result. /// /// As an example, consider a `StreetAddress` structure that holds the parts of /// a street address: a house or building number, the street name, and an /// optional unit number. Here's the initial declaration of the /// `StreetAddress` type: /// /// struct StreetAddress { /// let number: String /// let street: String /// let unit: String? /// /// init(_ number: String, _ street: String, unit: String? = nil) { /// self.number = number /// self.street = street /// self.unit = unit /// } /// } /// /// Now suppose you have an array of addresses that you need to check for a /// particular address. To use the `contains(_:)` method without including a /// closure in each call, extend the `StreetAddress` type to conform to /// `Equatable`. /// /// extension StreetAddress: Equatable { /// static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool { /// return /// lhs.number == rhs.number && /// lhs.street == rhs.street && /// lhs.unit == rhs.unit /// } /// } /// /// The `StreetAddress` type now conforms to `Equatable`. You can use `==` to /// check for equality between any two instances or call the /// `Equatable`-constrained `contains(_:)` method. /// /// let addresses = [StreetAddress("1490", "Grove Street"), /// StreetAddress("2119", "Maple Avenue"), /// StreetAddress("1400", "16th Street")] /// let home = StreetAddress("1400", "16th Street") /// /// print(addresses[0] == home) /// // Prints "false" /// print(addresses.contains(home)) /// // Prints "true" /// /// Equality implies substitutability---any two instances that compare equally /// can be used interchangeably in any code that depends on their values. To /// maintain substitutability, the `==` operator should take into account all /// visible aspects of an `Equatable` type. Exposing nonvalue aspects of /// `Equatable` types other than class identity is discouraged, and any that /// *are* exposed should be explicitly pointed out in documentation. /// /// Since equality between instances of `Equatable` types is an equivalence /// relation, any of your custom types that conform to `Equatable` must /// satisfy three conditions, for any values `a`, `b`, and `c`: /// /// - `a == a` is always `true` (Reflexivity) /// - `a == b` implies `b == a` (Symmetry) /// - `a == b` and `b == c` implies `a == c` (Transitivity) /// /// Moreover, inequality is the inverse of equality, so any custom /// implementation of the `!=` operator must guarantee that `a != b` implies /// `!(a == b)`. The default implementation of the `!=` operator function /// satisfies this requirement. /// /// Equality is Separate From Identity /// ---------------------------------- /// /// The identity of a class instance is not part of an instance's value. /// Consider a class called `IntegerRef` that wraps an integer value. Here's /// the definition for `IntegerRef` and the `==` function that makes it /// conform to `Equatable`: /// /// class IntegerRef: Equatable { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// /// static func == (lhs: IntegerRef, rhs: IntegerRef) -> Bool { /// return lhs.value == rhs.value /// } /// } /// /// The implementation of the `==` function returns the same value whether its /// two arguments are the same instance or are two different instances with /// the same integer stored in their `value` properties. For example: /// /// let a = IntegerRef(100) /// let b = IntegerRef(100) /// /// print(a == a, a == b, separator: ", ") /// // Prints "true, true" /// /// Class instance identity, on the other hand, is compared using the /// triple-equals identical-to operator (`===`). For example: /// /// let c = a /// print(a === c, b === c, separator: ", ") /// // Prints "true, false" public protocol Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. static func == (lhs: Self, rhs: Self) -> Bool } extension Equatable { /// Returns a Boolean value indicating whether two values are not equal. /// /// Inequality is the inverse of equality. For any values `a` and `b`, `a != b` /// implies that `a == b` is `false`. /// /// This is the default implementation of the not-equal-to operator (`!=`) /// for any type that conforms to `Equatable`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @_transparent public static func != (lhs: Self, rhs: Self) -> Bool { return !(lhs == rhs) } } //===----------------------------------------------------------------------===// // Reference comparison //===----------------------------------------------------------------------===// /// Returns a Boolean value indicating whether two references point to the same /// object instance. /// /// This operator tests whether two instances have the same identity, not the /// same value. For value equality, see the equal-to operator (`==`) and the /// `Equatable` protocol. /// /// The following example defines an `IntegerRef` type, an integer type with /// reference semantics. /// /// class IntegerRef: Equatable { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// } /// /// func ==(lhs: IntegerRef, rhs: IntegerRef) -> Bool { /// return lhs.value == rhs.value /// } /// /// Because `IntegerRef` is a class, its instances can be compared using the /// identical-to operator (`===`). In addition, because `IntegerRef` conforms /// to the `Equatable` protocol, instances can also be compared using the /// equal-to operator (`==`). /// /// let a = IntegerRef(10) /// let b = a /// print(a == b) /// // Prints "true" /// print(a === b) /// // Prints "true" /// /// The identical-to operator (`===`) returns `false` when comparing two /// references to different object instances, even if the two instances have /// the same value. /// /// let c = IntegerRef(10) /// print(a == c) /// // Prints "true" /// print(a === c) /// // Prints "false" /// /// - Parameters: /// - lhs: A reference to compare. /// - rhs: Another reference to compare. public func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return Bool(Builtin.cmp_eq_RawPointer( Builtin.bridgeToRawPointer(Builtin.castToUnknownObject(l)), Builtin.bridgeToRawPointer(Builtin.castToUnknownObject(r)) )) case (nil, nil): return true default: return false } } /// Returns a Boolean value indicating whether two references point to /// different object instances. /// /// This operator tests whether two instances have different identities, not /// different values. For value inequality, see the not-equal-to operator /// (`!=`) and the `Equatable` protocol. /// /// - Parameters: /// - lhs: A reference to compare. /// - rhs: Another reference to compare. public func !== (lhs: AnyObject?, rhs: AnyObject?) -> Bool { return !(lhs === rhs) }
apache-2.0
828a3fc54850aa760dd2a51844cb835c
37.102273
81
0.593001
4.251479
false
false
false
false
milseman/swift
test/SILGen/keypath_application.swift
6
4766
// RUN: %target-swift-frontend -enable-experimental-keypath-components -emit-silgen %s | %FileCheck %s class A {} class B {} protocol P {} protocol Q {} // CHECK-LABEL: sil hidden @{{.*}}loadable func loadable(readonly: A, writable: inout A, value: B, kp: KeyPath<A, B>, wkp: WritableKeyPath<A, B>, rkp: ReferenceWritableKeyPath<A, B>) { // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: [[ROOT_BORROW:%.*]] = begin_borrow %0 // CHECK: [[ROOT_COPY:%.*]] = copy_value [[ROOT_BORROW]] // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %3 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[PROJECT]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = readonly[keyPath: kp] _ = writable[keyPath: kp] _ = readonly[keyPath: wkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: wkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: rkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: rkp] // CHECK: function_ref @{{.*}}_projectKeyPathWritable writable[keyPath: wkp] = value // CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable readonly[keyPath: rkp] = value // CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}addressOnly func addressOnly(readonly: P, writable: inout P, value: Q, kp: KeyPath<P, Q>, wkp: WritableKeyPath<P, Q>, rkp: ReferenceWritableKeyPath<P, Q>) { // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: kp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: kp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: wkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: wkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: rkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: rkp] // CHECK: function_ref @{{.*}}_projectKeyPathWritable writable[keyPath: wkp] = value // CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable readonly[keyPath: rkp] = value // CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}reabstracted func reabstracted(readonly: @escaping () -> (), writable: inout () -> (), value: @escaping (A) -> B, kp: KeyPath<() -> (), (A) -> B>, wkp: WritableKeyPath<() -> (), (A) -> B>, rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) { // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: kp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: kp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: wkp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: wkp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: rkp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: rkp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathWritable writable[keyPath: wkp] = value // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable readonly[keyPath: rkp] = value // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}partial func partial<A>(valueA: A, valueB: Int, pkpA: PartialKeyPath<A>, pkpB: PartialKeyPath<Int>, akp: AnyKeyPath) { // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: pkpA] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: pkpB] }
apache-2.0
ad1ea02b1abfb6775b329ca80ac1617f
37.435484
102
0.591691
4.191733
false
false
false
false
gouyz/GYZBaking
baking/Classes/Login/View/GYZLoginInputView.swift
1
1898
// // GYZLoginInputView.swift // baking // 登录界面的输入View // Created by gouyz on 2016/12/1. // Copyright © 2016年 gouyz. All rights reserved. // import UIKit import SnapKit class GYZLoginInputView: UIView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } convenience init(iconName : String,placeHolder: String,isPhone: Bool){ self.init(frame: CGRect.zero) self.backgroundColor = kWhiteColor iconView.image = UIImage(named: iconName) textFiled.placeholder = placeHolder if isPhone { textFiled.keyboardType = .numberPad }else{ textFiled.keyboardType = .default textFiled.isSecureTextEntry = true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setupUI(){ // 添加子控件 addSubview(iconView) addSubview(textFiled) // 布局子控件 iconView.snp.makeConstraints { (make) in make.left.equalTo(self).offset(kMargin) make.centerY.equalTo(self) make.size.equalTo(CGSize(width: 30, height: 30)) } textFiled.snp.makeConstraints { (make) in make.left.equalTo(iconView.snp.right).offset(kMargin) make.top.equalTo(self) make.right.equalTo(self).offset(-kMargin) make.bottom.equalTo(self) } } /// 图标 fileprivate lazy var iconView: UIImageView = UIImageView() /// 输入框 lazy var textFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.clearButtonMode = .whileEditing return textFiled }() }
mit
bc4542066cfe44bc7381f3c883f724e1
25.826087
74
0.590492
4.69797
false
false
false
false
Plasmaworks/Plasmacore
Libraries/Plasmacore/Swift/Plasmacore.swift
1
10396
#if os(OSX) import Cocoa #else import Foundation #endif class Plasmacore { static let _singleton = Plasmacore() static var singleton:Plasmacore { get { let result = _singleton if (result.is_launched) { return result } return result.configure().launch() } } class func onLaunch() { singleton.start() // Sends Application.on_launch message automatically on first start } class func onStop() { singleton.stop() PlasmacoreMessage( type:"Application.on_stop" ).send() } class func onStart() { PlasmacoreMessage( type:"Application.on_start" ).send() singleton.start() } class func onSave() { singleton.stop() PlasmacoreMessage( type:"Application.on_save" ).send() } @discardableResult class func addMessageListener( type:String, listener:@escaping ((PlasmacoreMessage)->Void) )->Int { return singleton.instanceAddMessageListener( type: type, listener: listener ) } class func removeMessageListener( _ listenerID:Int ) { singleton.instanceRemoveMessageListener( listenerID ) } var is_configured = false var is_launched = false var nextListenerID = 1 var idleUpdateFrequency = 0.5 var pending_message_data = [UInt8]() var io_buffer = [UInt8]() var is_sending = false var update_requested = false var listeners = [String:[PlasmacoreMessageListener]]() var listeners_by_id = [Int:PlasmacoreMessageListener]() var reply_listeners = [Int:PlasmacoreMessageListener]() var resources = [Int:AnyObject]() var update_timer : Timer? fileprivate init() { } @discardableResult func instanceAddMessageListener( type:String, listener:@escaping ((PlasmacoreMessage)->Void) )->Int { objc_sync_enter( self ); defer { objc_sync_exit(self) } // @synchronized (self) let info = PlasmacoreMessageListener( listenerID:nextListenerID, type:type, callback:listener ) nextListenerID += 1 listeners_by_id[ info.listenerID ] = info if listeners[ type ] != nil { listeners[ type ]!.append( info ) } else { var list = [PlasmacoreMessageListener]() list.append( info ) listeners[ type ] = list } return info.listenerID } @discardableResult func configure()->Plasmacore { if (is_configured) { return self } is_configured = true instanceAddMessageListener( type: "<reply>", listener: { (m:PlasmacoreMessage) in if let info = Plasmacore.singleton.reply_listeners.removeValue( forKey: m.message_id ) { info.callback( m ) } } ) #if os(OSX) instanceAddMessageListener( type:"Window.create", listener: { (m:PlasmacoreMessage) in let name = m.getString( name:"name" ) var className = name if let bundleID = Bundle.main.bundleIdentifier { if let dotIndex = Plasmacore.lastIndexOf( bundleID, lookFor:"." ) { className = "\(bundleID.substring( from:bundleID.index(bundleID.startIndex,offsetBy:dotIndex+1))).\(name)" } } let controller : NSWindowController if let controllerType = NSClassFromString( className ) as? NSWindowController.Type { NSLog( "Found controller \(className)" ) controller = controllerType.init( windowNibName:name ) } else if let controllerType = NSClassFromString( name ) as? NSWindowController.Type { NSLog( "Found controller \(name)" ) controller = controllerType.init( windowNibName:name ) } else { NSLog( "===============================================================================" ) NSLog( "ERROR" ) NSLog( " No class found named \(name) or \(className)." ) NSLog( "===============================================================================" ) controller = NSWindowController( windowNibName:name ) } Plasmacore.singleton.resources[ m.getInt32(name:"id") ] = controller NSLog( "Controller window:\(String(describing:controller.window))" ) } ) instanceAddMessageListener( type:"Window.show", listener: { (m:PlasmacoreMessage) in let window_id = m.getInt32( name:"id" ) if let window = Plasmacore.singleton.resources[ window_id ] as? NSWindowController { window.showWindow( self ) } } ) #endif // os(OSX) RogueInterface_set_arg_count( Int32(CommandLine.arguments.count) ) for (index,arg) in CommandLine.arguments.enumerated() { RogueInterface_set_arg_value( Int32(index), arg ) } RogueInterface_configure(); return self } func getResourceID( _ resource:AnyObject? )->Int { guard let resource = resource else { return 0 } for (key,value) in resources { if (value === resource) { return key } } return 0 } @discardableResult func launch()->Plasmacore { if (is_launched) { return self } is_launched = true RogueInterface_launch() let m = PlasmacoreMessage( type:"Application.on_launch" ) #if os(OSX) m.set( name:"is_window_based", value:true ) #endif m.send() return self } static func lastIndexOf( _ st:String, lookFor:String )->Int? { if let r = st.range( of: lookFor, options:.backwards ) { return st.characters.distance(from: st.startIndex, to: r.lowerBound) } return nil } func relaunch()->Plasmacore { PlasmacoreMessage( type:"Application.on_launch" ).set( name:"is_window_based", value:true ).send() return self } func instanceRemoveMessageListener( _ listenerID:Int ) { objc_sync_enter( self ); defer { objc_sync_exit(self) } // @synchronized (self) if let listener = listeners_by_id[ listenerID ] { listeners_by_id.removeValue( forKey: listenerID ) if let listener_list = listeners[ listener.type ] { for i in 0..<listener_list.count { if (listener_list[i] === listener) { listeners[ listener.type ]!.remove( at: i ); return; } } } } } func send( _ m:PlasmacoreMessage ) { objc_sync_enter( self ); defer { objc_sync_exit(self) } // @synchronized (self) let size = m.data.count pending_message_data.append( UInt8((size>>24)&255) ) pending_message_data.append( UInt8((size>>16)&255) ) pending_message_data.append( UInt8((size>>8)&255) ) pending_message_data.append( UInt8(size&255) ) for b in m.data { pending_message_data.append( b ) } update() } func send_rsvp( _ m:PlasmacoreMessage, callback:@escaping ((PlasmacoreMessage)->Void) ) { objc_sync_enter( self ); defer { objc_sync_exit(self) } // @synchronized (self) reply_listeners[ m.message_id ] = PlasmacoreMessageListener( listenerID:nextListenerID, type:"<reply>", callback:callback ) nextListenerID += 1 send( m ) } func setIdleUpdateFrequency( _ f:Double )->Plasmacore { idleUpdateFrequency = f if (update_timer != nil) { stop() start() } return self } func start() { if ( !is_launched ) { configure().launch() } if (update_timer === nil) { update_timer = Timer.scheduledTimer( timeInterval: idleUpdateFrequency, target:self, selector: #selector(Plasmacore.update), userInfo:nil, repeats: true ) } update() } func stop() { if (update_timer !== nil) { update_timer!.invalidate() update_timer = nil } } @objc func update() { objc_sync_enter( self ); defer { objc_sync_exit(self) } // @synchronized (self) if (is_sending) { update_requested = true return } is_sending = true // Execute a small burst of message dispatching and receiving. Stop after // 10 iterations or when there are no new messages. Global state updates // are frequency capped to 1/60 second intervals and draws are synced to // the display refresh so this isn't triggering large amounts of extra work. for _ in 1...10 { update_requested = false // Swap pending data with io_buffer data let temp = io_buffer io_buffer = pending_message_data pending_message_data = temp let received_data = RogueInterface_send_messages( io_buffer, Int32(io_buffer.count) ) let count = received_data!.count received_data!.withUnsafeBytes{ ( bytes:UnsafePointer<UInt8>)->Void in //{(bytes: UnsafePointer<CChar>)->Void in //Use `bytes` inside this closure //... var read_pos = 0 while (read_pos+4 <= count) { var size = Int( bytes[read_pos] ) << 24 size |= Int( bytes[read_pos+1] ) << 16 size |= Int( bytes[read_pos+2] ) << 8 size |= Int( bytes[read_pos+3] ) read_pos += 4; if (read_pos + size <= count) { var message_data = [UInt8]() message_data.reserveCapacity( size ) for i in 0..<size { message_data.append( bytes[read_pos+i] ) } let m = PlasmacoreMessage( data:message_data ) //NSLog( "Received message type \(m.type)" ) if let listener_list = listeners[ m.type ] { for listener in listener_list { listener.callback( m ) } } } else { NSLog( "*** Skipping message due to invalid size." ) } read_pos += size } } io_buffer.removeAll() if ( !update_requested ) { break } } is_sending = false if (update_requested) { // There are still some pending messages after 10 iterations. Schedule another round // in 1/60 second instead of the usual 1.0 seconds. Timer.scheduledTimer( timeInterval: 1.0/60.0, target:self, selector: #selector(Plasmacore.update), userInfo:nil, repeats:false ) } } } class PlasmacoreMessageListener { var listenerID : Int var type : String var callback : ((PlasmacoreMessage)->Void) init( listenerID:Int, type:String, callback:@escaping ((PlasmacoreMessage)->Void) ) { self.listenerID = listenerID self.type = type self.callback = callback } }
unlicense
a11475cc623db26048da143c66f2c517
25.252525
160
0.597634
3.975526
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/Placemark.swift
1
2596
// // Placemark.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML Placemark /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="Placemark" type="kml:PlacemarkType" substitutionGroup="kml:AbstractFeatureGroup"/> public class Placemark :SPXMLElement, AbstractFeatureGroup , HasXMLElementValue{ public static var elementName: String = "Placemark" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Document: v.value.abstractFeatureGroup.append(self) case let v as Folder: v.value.abstractFeatureGroup.append(self) case let v as Kml: v.value.abstractFeatureGroup = self case let v as Delete: v.value.abstractFeatureGroup.append(self) default: break } } } } public var value : PlacemarkType public required init(attributes:[String:String]){ self.value = PlacemarkType(attributes: attributes) super.init(attributes: attributes) } public var abstractObject : AbstractObjectType { return self.value } public var abstractFeature : AbstractFeatureType { return self.value } } /// KML PlacemarkType /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <complexType name="PlacemarkType" final="#all"> /// <complexContent> /// <extension base="kml:AbstractFeatureType"> /// <sequence> /// <element ref="kml:AbstractGeometryGroup" minOccurs="0"/> /// <element ref="kml:PlacemarkSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// <element ref="kml:PlacemarkObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// </sequence> /// </extension> /// </complexContent> /// </complexType> /// <element name="PlacemarkSimpleExtensionGroup" abstract="true" type="anySimpleType"/> /// <element name="PlacemarkObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/> public class PlacemarkType: AbstractFeatureType { public var abstractGeometryGroup:AbstractGeometryGroup! public var placemarkSimpleExtensionGroup:[AnyObject] = [] public var placemarkObjectExtensionGroup:[AbstractObjectGroup] = [] }
mit
798ba2bd1c7be24acdbfa82a8538171b
39.951613
115
0.66798
4.055911
false
false
false
false
StormXX/STTableBoard
STTableBoard/Views/TextComposeView.swift
1
5542
// // TextComposeView.swift // STTableBoard // // Created by DangGu on 16/1/4. // Copyright © 2016年 StormXX. All rights reserved. // protocol TextComposeViewDelegate: class { func textComposeViewDidBeginEditing(textComposeView view: TextComposeView) func textComposeView(textComposeView view: TextComposeView, didClickDoneButton button: UIButton, withText text: String) func textComposeView(textComposeView view: TextComposeView, didClickCancelButton button: UIButton) } extension TextComposeViewDelegate { func textComposeViewDidBeginEditing(textComposeView view: TextComposeView) {} } import UIKit class TextComposeView: UIView { weak var delegate: TextComposeViewDelegate? var textFieldHeight: CGFloat = 56.0 lazy var textField: UITextField = { let field = UITextField(frame: CGRect.zero) field.borderStyle = .roundedRect field.font = UIFont.systemFont(ofSize: 15.0) field.textColor = UIColor(red: 56/255.0, green: 56/255.0, blue: 56/255.0, alpha: 1.0) field.delegate = self field.returnKeyType = .done return field }() lazy var cancelButton: UIButton = { let button = UIButton(frame: CGRect.zero) button.setTitle(localizedString["STTableBoard.Cancel"], for: .normal) button.setTitleColor(cancelButtonTextColor, for: .normal) button.backgroundColor = UIColor.clear button.clipsToBounds = true button.addTarget(self, action: #selector(TextComposeView.cancelButtonClicked(_:)), for: .touchUpInside) button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0) return button }() lazy var doneButton: UIButton = { let button = UIButton(frame: CGRect.zero) button.setTitle(localizedString["STTableBoard.Create"], for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.backgroundColor = UIColor.clear button.setBackgroundImage(UIImage(named: "doneButton_background", in: currentBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate), for: .normal) button.clipsToBounds = true button.addTarget(self, action: #selector(TextComposeView.doneButtonClicked(_:)), for: .touchUpInside) button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0) return button }() init(frame: CGRect, textFieldHeight: CGFloat, cornerRadius: CGFloat) { super.init(frame: frame) layer.borderColor = boardBorderColor.cgColor layer.borderWidth = 1.0 layer.masksToBounds = true layer.cornerRadius = cornerRadius backgroundColor = boardBackgroundColor clipsToBounds = true addSubview(textField) addSubview(cancelButton) addSubview(doneButton) textField.translatesAutoresizingMaskIntoConstraints = false cancelButton.translatesAutoresizingMaskIntoConstraints = false doneButton.translatesAutoresizingMaskIntoConstraints = false let views: [String: Any] = ["textField":textField, "cancelButton":cancelButton, "doneButton":doneButton] let fieldHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[textField]-10-|", options: [], metrics: nil, views: views) let fieldVerticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[textField(==textFieldHeight)]-10-[doneButton(==36)]", options: [], metrics: ["textFieldHeight": textFieldHeight], views: views) let buttonHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[cancelButton(==64)]-5-[doneButton(==64)]-10-|", options: [.alignAllCenterY], metrics: nil, views: views) let buttonEqualHeight = NSLayoutConstraint(item: cancelButton, attribute: .height, relatedBy: .equal, toItem: doneButton, attribute: .height, multiplier: 1.0, constant: 0.0) let vflConstraints = fieldHorizontalConstraints + fieldVerticalConstraints + buttonHorizontalConstraints let constraints = [buttonEqualHeight] NSLayoutConstraint.activate(vflConstraints + constraints) } convenience override init(frame: CGRect) { self.init(frame: frame, textFieldHeight: 56.0, cornerRadius: 4.0) } func cancelButtonClicked(_ sender: UIButton) { textField.resignFirstResponder() delegate?.textComposeView(textComposeView: self, didClickCancelButton: sender) } func doneButtonClicked(_ sender: UIButton) { if let text = textField.text { let trimedText = text.trim() if trimedText.characters.count > 0 { delegate?.textComposeView(textComposeView: self, didClickDoneButton: doneButton, withText: trimedText) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TextComposeView: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let text = textField.text { let trimedText = text.trim() if trimedText.characters.count > 0 { delegate?.textComposeView(textComposeView: self, didClickDoneButton: doneButton, withText: trimedText) } else { return false } } return true } func textFieldDidBeginEditing(_ textField: UITextField) { delegate?.textComposeViewDidBeginEditing(textComposeView: self) } }
cc0-1.0
a8d7e52e3bfdff41b321fde1519e9e21
42.273438
224
0.686586
5.01721
false
false
false
false
apple/swift
test/expr/unary/async_await.swift
1
7987
// RUN: %target-swift-frontend -typecheck -verify %s -disable-availability-checking // REQUIRES: concurrency func test1(asyncfp : () async -> Int, fp : () -> Int) async { _ = await asyncfp() _ = await asyncfp() + asyncfp() _ = await asyncfp() + fp() _ = await fp() + 42 // expected-warning {{no 'async' operations occur within 'await' expression}} _ = 32 + asyncfp() + asyncfp() // expected-error {{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-1:12{{call is 'async'}} // expected-note@-2:24{{call is 'async'}} } func getInt() async -> Int { return 5 } // Locations where "await" is prohibited. func test2( defaulted: Int = await getInt() // expected-error{{'async' call cannot occur in a default argument}} ) async { defer { _ = await getInt() // expected-error{{'async' call cannot occur in a defer body}} } print("foo") } func test3() { // expected-note{{add 'async' to function 'test3()' to make it asynchronous}} {{13-13= async}} _ = await getInt() // expected-error{{'async' call in a function that does not support concurrency}} } func test4()throws { // expected-note{{add 'async' to function 'test4()' to make it asynchronous}} {{13-19=async throws}} _ = await getInt() // expected-error{{'async' call in a function that does not support concurrency}} } func test5<T>(_ f : () async throws -> T) rethrows->T { // expected-note{{add 'async' to function 'test5' to make it asynchronous}} {{44-52=async rethrows}} return try await f() // expected-error{{'async' call in a function that does not support concurrency}} } enum SomeEnum: Int { case foo = await 5 // expected-error{{raw value for enum case must be a literal}} } struct SomeStruct { var x = await getInt() // expected-error{{'async' call cannot occur in a property initializer}} static var y = await getInt() // expected-error{{'async' call cannot occur in a global variable initializer}} } func acceptAutoclosureNonAsync(_: @autoclosure () -> Int) async { } func acceptAutoclosureAsync(_: @autoclosure () async -> Int) async { } func acceptAutoclosureAsyncThrows(_: @autoclosure () async throws -> Int) async { } func acceptAutoclosureAsyncThrowsRethrows(_: @autoclosure () async throws -> Int) async rethrows { } func acceptAutoclosureNonAsyncBad(_: @autoclosure () async -> Int) -> Int { 0 } // expected-error@-1{{'async' autoclosure parameter in a non-'async' function}} // expected-note@-2{{add 'async' to function 'acceptAutoclosureNonAsyncBad' to make it asynchronous}} {{67-67= async}} struct HasAsyncBad { init(_: @autoclosure () async -> Int) { } // expected-error@-1{{'async' autoclosure parameter in a non-'async' function}} } func testAutoclosure() async { await acceptAutoclosureAsync(await getInt()) await acceptAutoclosureNonAsync(await getInt()) // expected-error{{'async' call in an autoclosure that does not support concurrency}} await acceptAutoclosureAsync(42 + getInt()) // expected-error@-1:32{{expression is 'async' but is not marked with 'await'}}{{32-32=await }} // expected-note@-2:37{{call is 'async' in an autoclosure argument}} await acceptAutoclosureNonAsync(getInt()) // expected-error{{'async' call in an autoclosure that does not support concurrency}} } // Test inference of 'async' from the body of a closure. func testClosure() { let closure = { await getInt() } let _: () -> Int = closure // expected-error{{invalid conversion from 'async' function of type '() async -> Int' to synchronous function type '() -> Int'}} let closure2 = { () async -> Int in print("here") return await getInt() } let _: () -> Int = closure2 // expected-error{{invalid conversion from 'async' function of type '() async -> Int' to synchronous function type '() -> Int'}} } // Nesting async and await together func throwingAndAsync() async throws -> Int { return 0 } enum HomeworkError : Error { case dogAteIt } func testThrowingAndAsync() async throws { _ = try await throwingAndAsync() _ = await try throwingAndAsync() // expected-warning{{'try' must precede 'await'}}{{7-13=}}{{17-17=await }} _ = await (try throwingAndAsync()) _ = try (await throwingAndAsync()) // Errors _ = await throwingAndAsync() // expected-error{{call can throw but is not marked with 'try'}} // expected-note@-1{{did you mean to use 'try'?}}{{7-7=try }} // expected-note@-2{{did you mean to handle error as optional value?}}{{7-7=try? }} // expected-note@-3{{did you mean to disable error propagation?}}{{7-7=try! }} _ = try throwingAndAsync() // expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{11-11=await }} // expected-note@-2{{call is 'async'}} } func testExhaustiveDoCatch() async { do { _ = try await throwingAndAsync() } catch { } do { _ = try await throwingAndAsync() // expected-error@-1{{errors thrown from here are not handled because the enclosing catch is not exhaustive}} } catch let e as HomeworkError { } // Ensure that we infer 'async' through an exhaustive do-catch. let fn = { do { _ = try await throwingAndAsync() } catch { } } let _: Int = fn // expected-error{{cannot convert value of type '() async -> ()'}} // Ensure that we infer 'async' through a non-exhaustive do-catch. let fn2 = { do { _ = try await throwingAndAsync() } catch let e as HomeworkError { } } let _: Int = fn2 // expected-error{{cannot convert value of type '() async throws -> ()'}} } // String interpolation func testStringInterpolation() async throws { // expected-error@+2:30{{expression is 'async' but is not marked with 'await'}}{{30-30=await }} // expected-note@+1:35{{call is 'async'}} _ = "Eventually produces \(32 + getInt())" _ = "Eventually produces \(await getInt())" _ = await "Eventually produces \(getInt())" } func invalidAsyncFunction() async { _ = try await throwingAndAsync() // expected-error {{errors thrown from here are not handled}} } func validAsyncFunction() async throws { _ = try await throwingAndAsync() } // Async let checking func mightThrow() throws { } func getIntUnsafely() throws -> Int { 0 } func getIntUnsafelyAsync() async throws -> Int { 0 } extension Error { var number: Int { 0 } } func testAsyncLet() async throws { async let x = await getInt() print(x) // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1:9{{reference to async let 'x' is 'async'}} print(await x) do { try mightThrow() } catch let e where e.number == x { // expected-error{{async let 'x' cannot be referenced in a catch guard expression}} } catch { } defer { async let deferX: Int = await getInt() // expected-error {{'async let' cannot be used on declarations in a defer body}} _ = await deferX // expected-error {{async let 'deferX' cannot be referenced in a defer body}} async let _: Int = await getInt() // expected-error {{'async let' cannot be used on declarations in a defer body}} async let _ = await getInt() // expected-error {{'async let' cannot be used on declarations in a defer body}} } async let x1 = getIntUnsafely() // okay, try is implicit here async let x2 = getInt() // okay, await is implicit here async let x3 = try getIntUnsafely() async let x4 = try! getIntUnsafely() async let x5 = try? getIntUnsafely() _ = await x1 // expected-error{{reading 'async let' can throw but is not marked with 'try'}} _ = await x2 _ = try await x3 _ = await x4 _ = await x5 } // expected-note@+1 3{{add 'async' to function 'testAsyncLetOutOfAsync()' to make it asynchronous}} {{30-30= async}} func testAsyncLetOutOfAsync() { async let x = 1 // expected-error{{'async let' in a function that does not support concurrency}} _ = await x // expected-error{{'async let' in a function that does not support concurrency}} _ = x // expected-error{{'async let' in a function that does not support concurrency}} }
apache-2.0
167829445d078c017f41f8d2c0a6d60f
36.674528
158
0.669838
3.924816
false
true
false
false
powerytg/Accented
Accented/UI/Details/Components/CommentsLayout.swift
1
4445
// // CommentsLayout.swift // Accented // // Created by You, Tiangong on 10/21/16. // Copyright © 2016 Tiangong You. All rights reserved. // import UIKit protocol CommentsLayoutDelegate : NSObjectProtocol { func cellStyleForItemAtIndexPath(_ indexPath : IndexPath) -> CommentRendererStyle } class CommentsLayout: InfiniteLoadingLayout<CommentModel> { private var paddingTop : CGFloat = 80 private let darkCellLeftMargin : CGFloat = 50 private let lightCelLeftlMargin : CGFloat = 62 private var rightMargin : CGFloat = 15 private var gap : CGFloat = 10 private var availableWidth : CGFloat = 0 // Layout delegate weak var delegate : CommentsLayoutDelegate? override init() { super.init() initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func initialize() { contentHeight = paddingTop scrollDirection = .vertical } override func prepare() { if collectionView != nil { availableWidth = collectionView!.bounds.width - max(darkCellLeftMargin, lightCelLeftlMargin) - rightMargin } } override var collectionViewContentSize : CGSize { generateLayoutAttributesIfNeeded() guard layoutCache.count != 0 else { return CGSize.zero } return CGSize(width: availableWidth, height: contentHeight) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() generateLayoutAttributesIfNeeded() guard layoutCache.count != 0 else { return nil } for attributes in layoutCache.values { if attributes.frame.intersects(rect) { layoutAttributes.append(attributes.copy() as! UICollectionViewLayoutAttributes) } } return layoutAttributes } override func generateLayoutAttributesIfNeeded() { guard collection != nil else { return } // If there's a previous loading indicator, reset its section height to 0 updateCachedLayoutHeight(cacheKey: loadingIndicatorCacheKey, toHeight: 0) var nextY : CGFloat = paddingTop for (index, comment) in collection!.items.enumerated() { // Ignore if the comment already has a layout let cacheKey = cacheKeyForComment(comment) var attrs = layoutCache[cacheKey] if attrs == nil { let measuredSize = CommentRenderer.estimatedSize(comment, width: availableWidth) let indexPath = IndexPath(item: index, section: 0) let cellStyle = delegate?.cellStyleForItemAtIndexPath(indexPath) var leftMargin : CGFloat = 0 if let cellStyle = cellStyle { switch cellStyle { case .Dark: leftMargin = darkCellLeftMargin case .Light: leftMargin = lightCelLeftlMargin } } else { leftMargin = 0 } attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath) attrs!.frame = CGRect(x: leftMargin, y: nextY, width: measuredSize.width, height: measuredSize.height) layoutCache[cacheKeyForComment(comment)] = attrs! } nextY += attrs!.frame.size.height + gap } // Always show the footer regardless of the loading state // If not loading, then the footer is simply not visible let footerHeight = defaultLoadingIndicatorHeight let footerCacheKey = loadingIndicatorCacheKey let indexPath = IndexPath(item: 0, section: 0) let footerAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, with: indexPath) footerAttributes.frame = CGRect(x: 0, y: nextY, width: availableWidth, height: footerHeight) layoutCache[footerCacheKey] = footerAttributes nextY += footerHeight + gap contentHeight = nextY } private func cacheKeyForComment(_ comment : CommentModel) -> String { return "comment_\(comment.commentId)" } }
mit
174802de72365949954cf2f450e9fc7d
35.42623
146
0.622862
5.734194
false
false
false
false
qiang437587687/Brother
Brother/Brother/CAAnimationTest.swift
1
5232
// // CAAnimationTest.swift // Brother // // Created by zhang on 15/12/10. // Copyright © 2015年 zhang. All rights reserved. // import UIKit class CAAnimationTest: UIViewController { var viewAnimation:UIView = UIView() @IBAction func controllerButton(sender: UIButton) { let pausedTime:CFTimeInterval = viewAnimation.layer.timeOffset viewAnimation.layer.speed = 1.0 viewAnimation.layer.timeOffset = pausedTime let timeSincePause = viewAnimation.layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime viewAnimation.layer.beginTime = timeSincePause } @IBAction func endButton(sender: UIButton, forEvent event: UIEvent) { //暂停动画 viewAnimation.layer.timeOffset = viewAnimation.layer.convertTime(CACurrentMediaTime(), fromLayer: nil) viewAnimation.layer.speed = 0.0 } override func viewDidLoad() { //别同时运行一个一个的实验 // addAnimation() //圆圈动画 // keyrameAnimation() //关键帧动画 sharkAnimation()//抖动动画 } func sharkAnimation() { viewAnimation = UIView(frame: CGRectMake(100, 100, 100, 100)) viewAnimation.backgroundColor = UIColor.yellowColor() self.view.addSubview(viewAnimation) let labelHE = UILabel(frame: CGRectMake(0,35,100,30)) labelHE.text = "和尚" labelHE.textAlignment = NSTextAlignment.Center viewAnimation.addSubview(labelHE) let kfAnimation = CAKeyframeAnimation(keyPath: "transform.rotation") kfAnimation.duration = 0.1 kfAnimation.repeatCount=MAXFLOAT; kfAnimation.fillMode=kCAFillModeForwards; kfAnimation.removedOnCompletion = false; // 29 keyAnima.values=@[@(-angle2Radian(4)),@(angle2Radian(4)),@(-angle2Radian(4))]; kfAnimation.values = [-angleTransfrom(4),angleTransfrom(4),-angleTransfrom(4)] self.viewAnimation.layer.addAnimation(kfAnimation, forKey:"sharkAnimation") } func angleTransfrom(angelOr:Double) -> Double { return angelOr / 180 * M_PI } func keyrameAnimation() { let animation = CAKeyframeAnimation(keyPath: "position") viewAnimation = UIView(frame: CGRectMake(100, 100, 100, 100)) viewAnimation.backgroundColor = UIColor.yellowColor() self.view.addSubview(viewAnimation) //设置5个位置点 let p1 = CGPointMake(0.0, 0.0) let p2 = CGPointMake(300, 0.0) let p3 = CGPointMake(0.0, 400) let p4 = CGPointMake(300, 400) let p5 = CGPointMake(150, 200) //赋值 animation.values = [NSValue(CGPoint: p1), NSValue(CGPoint: p2), NSValue(CGPoint: p3), NSValue(CGPoint: p4), NSValue(CGPoint: p5)] //每个动作的时间百分比 animation.keyTimes = [NSNumber(float: 0.0), NSNumber(float: 0.4), NSNumber(float: 0.6), NSNumber(float: 0.8), NSNumber(float: 1.0), ] animation.delegate = self animation.duration = 6.0 animation.autoreverses = true //这个就看需不需要了 这里面先是false animation.repeatCount = Float(INT_MAX) viewAnimation.layer.addAnimation(animation, forKey: "Image-Move") } func addAnimation() { //小圆点 变大变小动画 viewAnimation = UIView(frame: CGRectMake(100, 100, 100, 100)) viewAnimation.layer.cornerRadius = viewAnimation.frame.size.width/2 viewAnimation.backgroundColor = UIColor.yellowColor() self.view.addSubview(viewAnimation) let animation = CABasicAnimation(keyPath: "opacity") animation.fromValue = 1.0 animation.toValue = 0.0 animation.duration = 3.0 animation.repeatCount = Float(INT_MAX) animation.autoreverses = true //这个就看需不需要了 let animationFrame = CABasicAnimation(keyPath: "bounds") animationFrame.duration = 3.0 animationFrame.fromValue = NSValue(CGRect: CGRectMake(0, 0, 100, 100)) animationFrame.toValue = NSValue(CGRect: CGRectMake(0, 0, 20, 20)) animationFrame.repeatCount = Float(INT_MAX) animationFrame.autoreverses = true let animationCornerRadius = CABasicAnimation(keyPath: "cornerRadius") animationCornerRadius.duration = 3.0 animationCornerRadius.fromValue = 50 animationCornerRadius.toValue = 10 animationCornerRadius.repeatCount = Float(INT_MAX) animationCornerRadius.autoreverses = true viewAnimation.layer.addAnimation(animationCornerRadius, forKey: "Image-animationCornerRadius") viewAnimation.layer.addAnimation(animationFrame, forKey: "Image-frame") viewAnimation.layer.addAnimation(animation, forKey: "Image-opacity") viewAnimation.alpha = 0 } override func animationDidStart(anim: CAAnimation) { print("动画开始") } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { print("动画结束") } }
mit
d3358c2aa188870671c997cbbc6f338a
30.179012
111
0.642249
4.497774
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Command/Command+MultiCluster.swift
1
4498
// // Command+MultiCluster.swift // // // Created by Vladislav Fitc on 25/05/2020. // import Foundation extension Command { enum MultiCluster { struct ListClusters: AlgoliaCommand { let method: HTTPMethod = .get let callType: CallType = .read let path = URL.clustersV1 let requestOptions: RequestOptions? init(requestOptions: RequestOptions?) { self.requestOptions = requestOptions } } struct HasPendingMapping: AlgoliaCommand { let method: HTTPMethod = .get let callType: CallType = .read let path: URL let requestOptions: RequestOptions? init(retrieveMapping: Bool, requestOptions: RequestOptions?) { self.requestOptions = requestOptions.updateOrCreate([.getClusters: String(retrieveMapping)]) self.path = URL .clustersV1 .appending(.mapping) .appending(.pending) } } } } extension Command.MultiCluster { enum User { struct Assign: AlgoliaCommand { let method: HTTPMethod = .post let callType: CallType = .write let path = URL.clustersV1.appending(.mapping) let body: Data? let requestOptions: RequestOptions? init(userID: UserID, clusterName: ClusterName, requestOptions: RequestOptions?) { var updatedRequestOptions = requestOptions ?? .init() updatedRequestOptions.setHeader(userID.rawValue, forKey: .algoliaUserID) self.requestOptions = updatedRequestOptions self.body = ClusterWrapper(clusterName).httpBody } } struct BatchAssign: AlgoliaCommand { let method: HTTPMethod = .post let callType: CallType = .write let path: URL = URL .clustersV1 .appending(.mapping) .appending(.batch) let body: Data? let requestOptions: RequestOptions? init(userIDs: [UserID], clusterName: ClusterName, requestOptions: RequestOptions?) { self.requestOptions = requestOptions self.body = AssignUserIDRequest(clusterName: clusterName, userIDs: userIDs).httpBody } } struct Get: AlgoliaCommand { let method: HTTPMethod = .get let callType: CallType = .read let path: URL let requestOptions: RequestOptions? init(userID: UserID, requestOptions: RequestOptions?) { self.requestOptions = requestOptions self.path = URL .clustersV1 .appending(.mapping) .appending(userID) } } struct GetTop: AlgoliaCommand { let method: HTTPMethod = .get let callType: CallType = .read let path = URL.clustersV1 .appending(.mapping) .appending(.top) let requestOptions: RequestOptions? init(requestOptions: RequestOptions?) { self.requestOptions = requestOptions } } struct GetList: AlgoliaCommand { let method: HTTPMethod = .get let callType: CallType = .read let path = URL.clustersV1 .appending(.mapping) let requestOptions: RequestOptions? init(page: Int?, hitsPerPage: Int?, requestOptions: RequestOptions?) { self.requestOptions = requestOptions.updateOrCreate( [ .page: page.flatMap(String.init), .hitsPerPage: hitsPerPage.flatMap(String.init) ]) } } struct Remove: AlgoliaCommand { let method: HTTPMethod = .delete let callType: CallType = .write let path: URL = URL .clustersV1 .appending(.mapping) let requestOptions: RequestOptions? init(userID: UserID, requestOptions: RequestOptions?) { var updatedRequestOptions = requestOptions ?? .init() updatedRequestOptions.setHeader(userID.rawValue, forKey: .algoliaUserID) self.requestOptions = updatedRequestOptions } } struct Search: AlgoliaCommand { let method: HTTPMethod = .post let callType: CallType = .read let path = URL.clustersV1 .appending(.mapping) .appending(.search) let body: Data? let requestOptions: RequestOptions? init(userIDQuery: UserIDQuery, requestOptions: RequestOptions?) { self.requestOptions = requestOptions self.body = userIDQuery.httpBody } } } } struct AssignUserIDRequest: Codable { let clusterName: ClusterName let userIDs: [UserID] enum CodingKeys: String, CodingKey { case clusterName = "cluster" case userIDs = "users" } }
mit
73e489c57ff08d4fef37fddbc9b9689e
23.313514
100
0.641618
4.769883
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Widgets/SearchInputView.swift
1
6359
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit private struct SearchInputViewUX { static let horizontalSpacing: CGFloat = 16 static let titleFont = UIFont.systemFont(ofSize: 16) static let borderLineWidth: CGFloat = 0.5 static let closeButtonSize: CGFloat = 36 } @objc protocol SearchInputViewDelegate: AnyObject { func searchInputView(_ searchView: SearchInputView, didChangeTextTo text: String) func searchInputViewBeganEditing(_ searchView: SearchInputView) func searchInputViewFinishedEditing(_ searchView: SearchInputView) } class SearchInputView: UIView, Themeable { weak var delegate: SearchInputViewDelegate? var showBottomBorder: Bool = true { didSet { bottomBorder.isHidden = !showBottomBorder } } lazy var inputField: UITextField = { let textField = UITextField() textField.delegate = self textField.addTarget(self, action: #selector(inputTextDidChange), for: .editingChanged) textField.accessibilityLabel = .SearchInputAccessibilityLabel textField.autocorrectionType = .no textField.autocapitalizationType = .none return textField }() lazy var titleLabel: UILabel = { let label = UILabel() label.text = .SearchInputTitle label.font = SearchInputViewUX.titleFont return label }() lazy var searchIcon: UIImageView = { return UIImageView(image: UIImage(named: "quickSearch")) }() fileprivate lazy var closeButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(tappedClose), for: .touchUpInside) button.setImage(UIImage(named: "clear"), for: []) button.accessibilityLabel = .SearchInputClearAccessibilityLabel return button }() fileprivate var centerContainer = UIView() fileprivate lazy var bottomBorder: UIView = { let border = UIView() return border }() fileprivate lazy var overlay: UIView = { let view = UIView() view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedSearch))) view.isAccessibilityElement = true view.accessibilityLabel = .SearchInputEnterSearchMode return view }() fileprivate(set) var isEditing = false { didSet { if isEditing { overlay.isHidden = true inputField.isHidden = false inputField.accessibilityElementsHidden = false closeButton.isHidden = false closeButton.accessibilityElementsHidden = false } else { overlay.isHidden = false inputField.isHidden = true inputField.accessibilityElementsHidden = true closeButton.isHidden = true closeButton.accessibilityElementsHidden = true } } } override init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = true addSubview(inputField) addSubview(closeButton) centerContainer.addSubview(searchIcon) centerContainer.addSubview(titleLabel) overlay.addSubview(centerContainer) addSubview(overlay) addSubview(bottomBorder) setupConstraints() setEditing(false) applyTheme() } fileprivate func setupConstraints() { centerContainer.snp.makeConstraints { make in make.center.equalTo(overlay) } overlay.snp.makeConstraints { make in make.edges.equalTo(self) } searchIcon.snp.makeConstraints { make in make.right.equalTo(titleLabel.snp.left).offset(-SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(centerContainer) } titleLabel.snp.makeConstraints { make in make.center.equalTo(centerContainer) } inputField.snp.makeConstraints { make in make.left.equalTo(self).offset(SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(self) make.right.equalTo(closeButton.snp.left).offset(-SearchInputViewUX.horizontalSpacing) } closeButton.snp.makeConstraints { make in make.right.equalTo(self).offset(-SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(self) make.size.equalTo(SearchInputViewUX.closeButtonSize) } bottomBorder.snp.makeConstraints { make in make.left.right.bottom.equalTo(self) make.height.equalTo(SearchInputViewUX.borderLineWidth) } } // didSet callbacks don't trigger when a property is being set in the init() call // but calling a method that does works fine. fileprivate func setEditing(_ editing: Bool) { isEditing = editing } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { backgroundColor = UIColor.theme.tableView.rowBackground overlay.backgroundColor = backgroundColor titleLabel.textColor = UIColor.theme.tableView.rowText inputField.textColor = titleLabel.textColor } } // MARK: - Selectors extension SearchInputView { @objc func tappedSearch() { isEditing = true inputField.becomeFirstResponder() delegate?.searchInputViewBeganEditing(self) } @objc func tappedClose() { isEditing = false delegate?.searchInputViewFinishedEditing(self) inputField.text = nil inputField.resignFirstResponder() } @objc func inputTextDidChange(_ textField: UITextField) { delegate?.searchInputView(self, didChangeTextTo: textField.text ?? "") } } // MARK: - UITextFieldDelegate extension SearchInputView: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { // If there is no text, go back to showing the title view if textField.text?.isEmpty ?? true { isEditing = false delegate?.searchInputViewFinishedEditing(self) } } }
mpl-2.0
a9195bcca121bf160186cd39aaf64d16
30.325123
104
0.656393
5.500865
false
false
false
false
IAskWind/IAWExtensionTool
Pods/Easy/Easy/Classes/Core/EasyDevice.swift
1
8435
// // EasyDevice.swift // Easy // // Created by OctMon on 2018/10/29. // import UIKit public extension EasyApp { enum DeviceModel: String { /*** iPhone ***/ case iPhone4 case iPhone4S case iPhone5 case iPhone5C case iPhone5S case iPhone6 case iPhone6Plus case iPhone6S case iPhone6SPlus case iPhoneSE case iPhone7 case iPhone7Plus case iPhone8 case iPhone8Plus case iPhoneX case iPhoneXS case iPhoneXS_Max case iPhoneXR /*** iPad ***/ case iPad1 case iPad2 case iPad3 case iPad4 case iPad5 case iPad6 case iPadAir case iPadAir2 case iPadMini case iPadMini2 case iPadMini3 case iPadMini4 case iPadPro9_7Inch case iPadPro10_5Inch case iPadPro12_9Inch /*** iPod ***/ case iPodTouch1Gen case iPodTouch2Gen case iPodTouch3Gen case iPodTouch4Gen case iPodTouch5Gen case iPodTouch6Gen /*** simulator ***/ case simulator /*** unknown ***/ case unknown public var name: String { var model = "\(self)" if model.hasPrefix("iPhone") { model = model.replacingOccurrences(of: "_", with: " ") } else if model.hasPrefix("iPad") { model = model.replacingOccurrences(of: "_", with: ".") } return model } } enum DeviceType: String { case iPhone case iPad case iPod case simulator case unknown } enum DeviceSize: Int, Comparable { case unknownSize = 0 /// iPhone 4, 4s, iPod Touch 4th gen. case screen3_5Inch /// iPhone 5, 5s, 5c, SE, iPod Touch 5-6th gen. case screen4Inch /// iPhone 6, 6s, 7, 8 case screen4_7Inch /// iPhone 6+, 6s+, 7+, 8+ case screen5_5Inch /// iPhone X, Xs case screen5_8Inch /// iPhone Xr case screen6_1Inch /// iPhone Xs Max case screen6_5Inch /// iPad Mini case screen7_9Inch /// iPad case screen9_7Inch /// iPad Pro (10.5-inch) case screen10_5Inch /// iPad Pro (12.9-inch) case screen12_9Inch } } public func <(lhs: EasyApp.DeviceSize, rhs: EasyApp.DeviceSize) -> Bool { return lhs.rawValue < rhs.rawValue } public func ==(lhs: EasyApp.DeviceSize, rhs: EasyApp.DeviceSize) -> Bool { return lhs.rawValue == rhs.rawValue } public extension EasyApp { /// My iPhone static let aboutName = UIDevice.current.name /// iOS/tvOS/watchOS static let systemName = UIDevice.current.systemName /// 12.0 static let systemVersion = UIDevice.current.systemVersion /// 0.0 - 1.0 static let batteryLevel = UIDevice.current.batteryLevel static var deviceMachine: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } return identifier } static var deviceModel: EasyApp.DeviceModel { switch deviceMachine { /*** iPhone ***/ case "iPhone3,1", "iPhone3,2", "iPhone3,3": return .iPhone4 case "iPhone4,1", "iPhone4,2", "iPhone4,3": return .iPhone4S case "iPhone5,1", "iPhone5,2": return .iPhone5 case "iPhone5,3", "iPhone5,4": return .iPhone5C case "iPhone6,1", "iPhone6,2": return .iPhone5S case "iPhone7,2": return .iPhone6 case "iPhone7,1": return .iPhone6Plus case "iPhone8,1": return .iPhone6S case "iPhone8,2": return .iPhone6SPlus case "iPhone8,3", "iPhone8,4": return .iPhoneSE case "iPhone9,1", "iPhone9,3": return .iPhone7 case "iPhone9,2", "iPhone9,4": return .iPhone7Plus case "iPhone10,1", "iPhone10,4": return .iPhone8 case "iPhone10,2", "iPhone10,5": return .iPhone8Plus case "iPhone10,3", "iPhone10,6": return .iPhoneX case "iPhone11,2": return .iPhoneXS case "iPhone11,4", "iPhone11,6": return .iPhoneXS_Max case "iPhone11,8": return .iPhoneXR /*** iPad ***/ case "iPad1,1", "iPad1,2": return .iPad1 case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return .iPad2 case "iPad3,1", "iPad3,2", "iPad3,3": return .iPad3 case "iPad3,4", "iPad3,5", "iPad3,6": return .iPad4 case "iPad6,11", "iPad6,12": return .iPad5 case "iPad7,5", "iPad 7,6": return .iPad6 case "iPad4,1", "iPad4,2", "iPad4,3": return .iPadAir case "iPad5,3", "iPad5,4": return .iPadAir2 case "iPad2,5", "iPad2,6", "iPad2,7": return .iPadMini case "iPad4,4", "iPad4,5", "iPad4,6": return .iPadMini2 case "iPad4,7", "iPad4,8", "iPad4,9": return .iPadMini3 case "iPad5,1", "iPad5,2": return .iPadMini4 case "iPad6,7", "iPad6,8", "iPad7,1", "iPad7,2": return .iPadPro12_9Inch case "iPad7,3", "iPad7,4": return .iPadPro10_5Inch case "iPad6,3", "iPad6,4": return .iPadPro9_7Inch /*** iPod ***/ case "iPod1,1": return .iPodTouch1Gen case "iPod2,1": return .iPodTouch2Gen case "iPod3,1": return .iPodTouch3Gen case "iPod4,1": return .iPodTouch4Gen case "iPod5,1": return .iPodTouch5Gen case "iPod7,1": return .iPodTouch6Gen /*** Simulator ***/ case "i386", "x86_64": return .simulator default: return .unknown } } static var deviceType: EasyApp.DeviceType { let model = deviceMachine if model.contains("iPhone") { return .iPhone } else if model.contains("iPad") { return .iPad } else if model.contains("iPod") { return .iPod } else if model == "i386" || model == "x86_64" { return .simulator } else { return .unknown } } static var deviceSize: EasyApp.DeviceSize { let w = UIScreen.main.bounds.width let h = UIScreen.main.bounds.height let screenHeight = max(w, h) switch screenHeight { case 480: return .screen3_5Inch case 568: return .screen4Inch case 667: return UIScreen.main.scale == 3.0 ? .screen5_5Inch : .screen4_7Inch case 736: return .screen5_5Inch case 812: return .screen5_8Inch case 896: return UIScreen.main.scale == 3.0 ? .screen6_5Inch : .screen6_1Inch case 1024: switch deviceModel { case .iPadMini,.iPadMini2,.iPadMini3,.iPadMini4: return .screen7_9Inch case .iPadPro10_5Inch: return .screen10_5Inch default: return .screen9_7Inch } case 1112: return .screen10_5Inch case 1366: return .screen12_9Inch default: return .unknownSize } } static let isPad = deviceType == .iPad static let isPhone = deviceType == .iPhone static let isPod = deviceType == .iPod static let isSimulator = deviceType == .simulator static let isFaceIDCapableDevices = deviceSize == .screen5_8Inch || deviceSize == .screen6_1Inch || deviceSize == .screen6_5Inch static let safeBottomEdge = CGFloat(isFaceIDCapableDevices ? 34 : 0) }
mit
7bf836db2bf1efe5080e72fd6a7642ff
27.788396
132
0.522347
4.110624
false
false
false
false
justeat/JustPeek
Example/Tests/PeekNativeHandlerTests.swift
1
2839
import UIKit import XCTest @testable import JustPeek @available(iOS 9.0, *) class MockViewController: UIViewController, PeekingDelegate { fileprivate(set) var didCommit = false fileprivate(set) var didRegisterForPreviewing = false let viewController = UIViewController() override func registerForPreviewing(with delegate: UIViewControllerPreviewingDelegate, sourceView: UIView) -> UIViewControllerPreviewing { didRegisterForPreviewing = true return StubPreviewing(delegate: delegate) } func peekContext(_ context: PeekContext, commit viewController: UIViewController) { didCommit = true } func peekContext(_ context: PeekContext, viewControllerForPeekingAt location: CGPoint) -> UIViewController? { return viewController } } @available(iOS 9.0, *) class StubPreviewing: NSObject, UIViewControllerPreviewing { var previewingGestureRecognizerForFailureRelationship: UIGestureRecognizer var delegate: UIViewControllerPreviewingDelegate var sourceView: UIView var sourceRect: CGRect init(delegate: UIViewControllerPreviewingDelegate) { self.previewingGestureRecognizerForFailureRelationship = UIGestureRecognizer() self.sourceView = UIView() self.sourceRect = self.sourceView.bounds self.delegate = delegate super.init() } } @available(iOS 9.0, *) class PeekNativeHandlerTests: XCTestCase { var handler: PeekNativeHandler! override func setUp() { super.setUp() handler = PeekNativeHandler() } override func tearDown() { handler = nil super.tearDown() } func testRegistersForNativeBehaviour() { let mockViewController = MockViewController() handler.register(viewController: mockViewController, forPeekingWithDelegate: mockViewController, sourceView: mockViewController.view) XCTAssertTrue(mockViewController.didRegisterForPreviewing) } func testNativeHandlerReturnsCorrectViewController() { let mockViewController = MockViewController() let previewing = StubPreviewing(delegate: handler) let viewController = handler.previewingContext(previewing, viewControllerForLocation: CGPoint.zero) XCTAssertEqual(viewController, mockViewController.viewController) } func testCommitsDestinationViewController() { let mockViewController = MockViewController() let previewing = StubPreviewing(delegate: handler) handler.register(viewController: mockViewController, forPeekingWithDelegate: mockViewController, sourceView: mockViewController.view) handler.previewingContext(previewing, commit: mockViewController.viewController) XCTAssertTrue(mockViewController.didCommit) } }
apache-2.0
e9dd683fc5a065fa230351acd6a97820
34.049383
142
0.729482
5.926931
false
true
false
false
IngmarStein/swift
test/ClangModules/enum.swift
8
6498
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil %s -verify // -- Check that we can successfully round-trip. // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -D IRGEN -emit-ir %s >/dev/null // REQUIRES: objc_interop import Foundation import user_objc // NS_ENUM var mince = NSRuncingMode.mince var quince = NSRuncingMode.quince var rawMince: UInt = NSRuncingMode.mince.rawValue var rawFoo: CInt = NSUnderlyingType.foo.rawValue var rawNegativeOne: CUnsignedInt = NSUnsignedUnderlyingTypeNegativeValue.negativeOne.rawValue var rawWordBreakA: Int = NSPrefixWordBreak.banjo.rawValue var rawWordBreakB: Int = NSPrefixWordBreak.bandana.rawValue var rawWordBreak2A: Int = NSPrefixWordBreak2.breakBarBas.rawValue var rawWordBreak2B: Int = NSPrefixWordBreak2.breakBareBass.rawValue var rawWordBreak3A: Int = NSPrefixWordBreak3.break1Bob.rawValue var rawWordBreak3B: Int = NSPrefixWordBreak3.break1Ben.rawValue var singleConstant = NSSingleConstantEnum.value var myCoolWaterMelon = MyCoolEnum.waterMelon var hashMince: Int = NSRuncingMode.mince.hashValue if NSRuncingMode.mince != .quince { } var numberBehavior: NumberFormatter.Behavior = .default numberBehavior = .behavior10_4 var postingStyle: NotificationQueue.PostingStyle = .whenIdle postingStyle = .asap func handler(_ formatter: ByteCountFormatter) { // Ensure that the Equality protocol is properly added to an // imported ObjC enum type before the type is referenced by name if (formatter.countStyle == .file) {} } // Unfortunate consequence of treating runs of capitals as a single word. // See <rdar://problem/16768954>. var pathStyle: CFURLPathStyle = .cfurlposixPathStyle pathStyle = .cfurlWindowsPathStyle var URLOrUTI: CFURLOrUTI = .cfurlKind URLOrUTI = .cfutiKind let magnitude: Magnitude = .k2 let magnitude2: MagnitudeWords = .two let objcABI: objc_abi = .v2 let underscoreSuffix: ALL_CAPS_ENUM = .ENUM_CASE_ONE let underscoreSuffix2: ALL_CAPS_ENUM2 = .CASE_TWO var alias1 = NSAliasesEnum.bySameValue var alias2 = NSAliasesEnum.byEquivalentValue var alias3 = NSAliasesEnum.byName var aliasOriginal = NSAliasesEnum.original switch aliasOriginal { case .original: break case .differentValue: break } switch aliasOriginal { case .original: break default: break } switch aliasOriginal { case .bySameValue: break case .differentValue: break } switch aliasOriginal { case .bySameValue: break default: break } switch aliasOriginal { case NSAliasesEnum.bySameValue: break case NSAliasesEnum.differentValue: break } extension NSAliasesEnum { func test() { switch aliasOriginal { case .bySameValue: break case .differentValue: break } } } // Test NS_SWIFT_NAME: _ = XMLNode.Kind.DTDKind == .invalid _ = NSPrefixWordBreakCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSPrefixWordBreak2Custom.problemCase == .goodCase _ = NSPrefixWordBreak2Custom.problemCase == .PrefixWordBreak2DeprecatedBadCase // expected-warning {{deprecated}} _ = NSPrefixWordBreak2Custom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReversedCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReorderedCustom.problemCase == .goodCase _ = NSPrefixWordBreakReorderedCustom.problemCase == .PrefixWordBreakReorderedDeprecatedBadCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReorderedCustom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReordered2Custom.problemCase == .goodCase _ = NSPrefixWordBreakReordered2Custom.problemCase == .PrefixWordBreakReordered2DeprecatedBadCase // expected-warning {{deprecated}} _ = NSPrefixWordBreakReordered2Custom.problemCase == .deprecatedGoodCase // expected-warning {{deprecated}} _ = NSSwiftNameAllTheThings.Foo == .Bar _ = NSSwiftNameBad.`class` #if !IRGEN var qualifiedName = NSRuncingMode.mince var topLevelCaseName = RuncingMince // expected-error{{}} #endif // NS_OPTIONS var withMince: NSRuncingOptions = .enableMince var withQuince: NSRuncingOptions = .enableQuince // When there is a single enum constant, compare it against the type name to // derive the namespaced name. var singleValue: NSSingleOptions = .value // Check OptionSet conformance. var minceAndQuince: NSRuncingOptions = NSRuncingOptions.enableMince.intersection(NSRuncingOptions.enableQuince) var minceOrQuince: NSRuncingOptions = [.enableMince, .enableQuince] minceOrQuince.formIntersection(minceAndQuince) minceOrQuince.formUnion(minceAndQuince) var minceValue: UInt = minceAndQuince.rawValue var minceFromMask: NSRuncingOptions = [] // Strip leading 'k' in "kConstant". let calendarUnit: CFCalendarUnit = [.year, .weekday] // ...unless the next character is a non-identifier. let curve3D: AU3DMixerAttenuationCurve = .k3DMixerAttenuationCurve_Exponential // Match various plurals. let observingOpts: NSKeyValueObservingOptions = [.new, .old] let bluetoothProps: CBCharacteristicProperties = [.write, .writeWithoutResponse] let buzzFilter: AlertBuzzes = [.funk, .sosumi] // Match multi-capital acronym. let bitmapFormat: NSBitmapFormat = [.NSAlphaFirstBitmapFormat, .NS32BitBigEndianBitmapFormat]; let bitmapFormatR: NSBitmapFormatReversed = [.NSAlphaFirstBitmapFormatR, .NS32BitBigEndianBitmapFormatR]; let bitmapFormat2: NSBitmapFormat2 = [.NSU16a , .NSU32a] let bitmapFormat3: NSBitmapFormat3 = [.NSU16b , .NSS32b] let bitmapFormat4: NSUBitmapFormat4 = [.NSU16c , .NSU32c] let bitmapFormat5: NSABitmapFormat5 = [.NSAA16d , .NSAB32d] // Drop trailing underscores when possible. let timeFlags: CMTimeFlags = [.valid , .hasBeenRounded] let timeFlags2: CMTimeFlagsWithNumber = [._Valid, ._888] let audioComponentOpts: AudioComponentInstantiationOptions = [.loadOutOfProcess] let audioComponentFlags: AudioComponentFlags = [.sandboxSafe] let audioComponentFlags2: FakeAudioComponentFlags = [.loadOutOfProcess] let objcFlags: objc_flags = [.taggedPointer, .swiftRefcount] let optionsWithSwiftName: NSOptionsAlsoGetSwiftName = .Case // <rdar://problem/25168818> Don't import None members in NS_OPTIONS types #if !IRGEN let _ = NSRuncingOptions.none // expected-error {{'none' is unavailable: use [] to construct an empty option set}} #endif // ...but do if they have a custom name _ = EmptySet1.default // ...even if the custom name is the same as the name they would have had _ = EmptySet2.none // ...or the original name. _ = EmptySet3.None
apache-2.0
6bf48dd0578488e9b10bcff4baf97edf
32.84375
131
0.783934
3.642377
false
false
false
false
openbuild-sheffield/jolt
Sources/RouteAuth/route.UserAdd.swift
1
3681
import Foundation import PerfectLib import PerfectHTTP import OpenbuildExtensionCore import OpenbuildExtensionPerfect import OpenbuildMysql import OpenbuildRepository import OpenbuildRouteRegistry import OpenbuildSingleton public class RequestUserAdd: OpenbuildExtensionPerfect.RequestProtocol { public var method: String public var uri: String public var description: String = "Add a user." public var validation: OpenbuildExtensionPerfect.RequestValidation public init(method: String, uri: String){ self.method = method self.uri = uri self.validation = OpenbuildExtensionPerfect.RequestValidation() self.validation.addValidators(validators: [ ValidateBodyEmail, ValidateBodyUsername, ValidateBodyPassword ]) } } public let handlerRouteUserAdd = { (request: HTTPRequest, response: HTTPResponse) in guard let handlerResponse = RouteRegistry.getHandlerResponse( uri: request.path.lowercased(), method: request.method, response: response ) else { return } do { var repository = try RepositoryUser() var model = ModelUserCreate( username: request.validatedRequestData?.validated["username"] as! String, email: request.validatedRequestData?.validated["email"] as! String, password: request.validatedRequestData?.validated["password"] as! String ) let user = repository.create( model: model ) if user.errors.isEmpty { if let userPlain = try repository.getByUsername( username: request.validatedRequestData?.validated["username"] as! String ){ //Success handlerResponse.complete( status: 200, model: ModelUser200Entity(entity: userPlain) ) } else { //422 Unprocessable Entity handlerResponse.complete( status: 422, model: ResponseModel422( validation: request.validatedRequestData!, messages: [ "added": true, "error": "Failed to read the created user." ] ) ) } } else { //422 Unprocessable Entity handlerResponse.complete( status: 422, model: ResponseModel422( validation: request.validatedRequestData!, messages: [ "added": false, "errors": user.errors ] ) ) } } catch { print(error) handlerResponse.complete( status: 500, model: ResponseModel500Messages(messages: [ "message": "Failed to generate a successful response." ]) ) } } public class RouteUserAdd: OpenbuildRouteRegistry.FactoryRoute { override public func route() -> NamedRoute? { let handlerResponse = ResponseDefined() handlerResponse.register(status: 200, model: "RouteAuth.ModelUser200Entity") handlerResponse.register(status: 422) handlerResponse.register(status: 500) return NamedRoute( handlerRequest: RequestUserAdd( method: "post", uri: "/api/users" ), handlerResponse: handlerResponse, handlerRoute: handlerRouteUserAdd ) } }
gpl-2.0
3275dbfba6c5a59d59c4aaa046b798ba
25.875912
88
0.564249
5.577273
false
false
false
false
techgrains/TGFramework-iOS
TGFramework/TGFramework/Util/TGUtil.swift
1
4567
import Foundation import UIKit open class TGUtil:NSObject { override init() { super.init() } /** * Check String Of Value * @param stringValue String * @return Boolian */ public class func stringHasValue(_ stringValue: String) -> Bool { if stringValue.isEmpty { return false }else { return true } } /** * Check Array Of Value * @param arrayValue Array * @return Boolian */ public class func arrayHasValue(_ arrayValue: [Any]) -> Bool { if arrayValue.isEmpty { return false } else { return true } } /** * Check Dictionary Of Value * @param dictionaryValue String * @return boolean */ public class func dictionaryHasValue(_ dictionaryValue: [AnyHashable: Any]) -> Bool { if dictionaryValue.isEmpty { return false } else { return true } } /** * Get String From Boolian Of Value * @param boolianValue String * @return String */ public class func getStringFromBoolianValue(_ boolianValue: Bool) -> String { if boolianValue { return "true" }else { return "false" } } /** * Get Boolian From String Of Value * @param boolianText String * @return String */ public class func getBoolianValue(_ boolianText: String) -> Bool { if (boolianText == "true") || (boolianText == "YES") || (boolianText == "1") { return true }else { return false } } /** * Logs provided logText * @param logText String */ public class func log(_ logText: String) { print(logText); } /** * Current Time Stamp in TimeInterval * @return String - formatted string */ public class func currentTimeStamp() -> String { let timeStamp: TimeInterval = (Date().timeIntervalSince1970) return "\(timeStamp)" } /** * Convert Date into String Date * @param date Date * @return String - formatted string */ public class func dateToString(_ date: Date, formate: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.dateFormat = formate return dateFormatter.string(from: date) } /** * Convert Current Date into String Date * @param dateFormat String * @return String - formatted string */ public class func currentDateInString(dateFormat: String) -> String { let date = Date() let dateFormatter = DateFormatter() //dateFormatter.dateStyle = .long dateFormatter.dateFormat = dateFormat return dateFormatter.string(from: date) } /** * Convert Date into TimeInterval * @param intervalSecond Intger * @return String - formatted string */ public class func timeIntervalToDateInString(_ intervalSecond: Int) -> String { let date = Date(timeIntervalSince1970: TimeInterval(intervalSecond)) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium return dateFormatter.string(from: date) } /** * Format Date with pattern * @param inputString String * @param fromFormate String * @param toFormate String * @return String - formatted string */ public class func changeInDateFormat(inputString: String, fromFormate: String, toFormate: String) -> String { let formatter = DateFormatter() formatter.dateFormat = fromFormate let date = formatter.date(from: inputString) formatter.dateFormat = toFormate let outputString: String = formatter.string(from: date!) return outputString } /** * Show alert View * @param title String * @param msg String */ public class func showAlertView(_ title: String, message msg: String) { DispatchQueue.main.async(execute: {() -> Void in let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(ok) let top: UIViewController? = UIApplication.shared.keyWindow?.rootViewController top?.present(alertController, animated: true, completion: { _ in }) }) } }
apache-2.0
0e2bc8a53d4a273ad78a9b47785cf786
27.72327
113
0.589008
4.942641
false
false
false
false
AckeeCZ/ACKategories
ACKategories-iOS/Base/FlowCoordinator.swift
1
11988
import UIKit import os.log extension Base { /// Turn on/off logging of init/deinit of all FCs /// ⚠️ Has no effect when Base.memoryLoggingEnabled is true public static var flowCoordinatorMemoryLoggingEnabled: Bool = true /** Handles view controllers connections and flow Starts with one of `start()` methods and ends with `stop()`. All start methods are supposed to be overridden and property `rootViewController` must be set in the end of the overridden implementation to avoid memory leaks. Don't forget to call super.start(). */ open class FlowCoordinator<DeepLinkType>: NSObject, UINavigationControllerDelegate, UIAdaptivePresentationControllerDelegate { /// Reference to the navigation controller used within the flow public weak var navigationController: UINavigationController? /// First VC of the flow. Must be set when FC starts. public weak var rootViewController: UIViewController! { didSet { rootVCSetter(rootViewController) } } /// When flow coordinator handles modally presented flow, we are interested `rootVC` changes private var rootVCSetter: (UIViewController?) -> () = { _ in } /// Parent coordinator public weak var parentCoordinator: FlowCoordinator? /// Property keeping reference to parent `UINavigationControllerDelegate`, that will be set when /// `self` is stopped. /// /// When multiple flow coordinators manage shared navigation stack, they should be chained propertly /// /// ```ParentFlow -> ChildFlow1 -> ChildFlow2``` /// /// But this is not always easy to achieve, sometimes you end up with hierarchy like this /// ``` /// ParentFlow -> ChildFlow1 /// -> ChildFlow2 /// ``` /// /// This property is set in `start(with navigationController)` /// so it can be used later in `stop` and in `UINavigationControllerDelegate` implementation private weak var parentNavigationDelegate: UINavigationControllerDelegate? /// Array of child coordinators public var childCoordinators = [FlowCoordinator]() /// Currently active coordinator public weak var activeChild: FlowCoordinator? // MARK: - Lifecycle /// Just start and return rootViewController. Object calling this method will connect returned view controller to the flow. @discardableResult open func start() -> UIViewController { checkRootViewController() return UIViewController() } /// Start in window. Window's root VC is supposed to be set. open func start(in window: UIWindow) { checkRootViewController() } /// Start within existing navigation controller. open func start(with navigationController: UINavigationController) { self.navigationController = navigationController parentNavigationDelegate = navigationController.delegate navigationController.delegate = self checkRootViewController() } /// Start by presenting from given VC. This method must be overridden by subclass. open func start(from viewController: UIViewController) { rootVCSetter = { [weak self] rootVC in rootVC?.presentationController?.delegate = self } rootVCSetter(rootViewController) } /// Clean up. Must be called when FC finished the flow to avoid memory leaks and unexpected behavior. open func stop(animated: Bool = false, completion: (() -> Void)? = nil) { let animationGroup = DispatchGroup() // stop all children DispatchQueue.main.async { self.childCoordinators.forEach { animationGroup.enter() $0.stop(animated: animated, completion: animationGroup.leave) } } if rootViewController == nil { ErrorHandlers.rootViewControllerDeallocatedBeforeStop?() } dismissPresentedViewControllerIfPossible(animated: animated, group: animationGroup) /// Determines whether dismiss should be called on `presentingViewController` of root, /// based on whether there are remaining VCs in the navigation stack. let shouldCallDismissOnPresentingVC = popAllViewControllersIfPossible(animated: animated, group: animationGroup) // ensure that dismiss will be called on presentingVC of root only when appropriate, // as presentingVC of root when modally presenting can be UITabBarController, // but the whole navigation shouldn't be dismissed, as there are still VCs // remaining in the navigation stack if shouldCallDismissOnPresentingVC, let presentingViewController = rootViewController?.presentingViewController { // dismiss when root was presented animationGroup.enter() presentingViewController.dismiss(animated: animated, completion: animationGroup.leave) } // stopping FC doesn't need to be nav delegate anymore -> pass it to parent navigationController?.delegate = parentNavigationDelegate parentCoordinator?.removeChild(self) animationGroup.notify(queue: DispatchQueue(label: "animationGroup")) { completion?() } } // MARK: - Stop helpers /// Dismiss all VCs presented from root or nav if possible private func dismissPresentedViewControllerIfPossible(animated: Bool, group: DispatchGroup) { if let rootViewController = rootViewController, rootViewController.presentedViewController != nil { group.enter() rootViewController.dismiss(animated: animated, completion: group.leave) } } /// Pop all view controllers when started within navigation controller /// - Returns: Flag whether dismiss should be called on `presentingViewController` of root, /// based on whether there are remaining VCs in the navigation stack. private func popAllViewControllersIfPossible(animated: Bool, group: DispatchGroup) -> Bool { if let navigationController = navigationController, let rootViewController = rootViewController, let index = navigationController.viewControllers.firstIndex(of: rootViewController) { // VCs to be removed from navigation stack let toRemoveViewControllers = navigationController.viewControllers[index..<navigationController.viewControllers.count] // dismiss all presented VCs on VCs to be removed toRemoveViewControllers.forEach { vc in if vc.presentedViewController != nil { group.enter() vc.dismiss(animated: animated, completion: group.leave) } } // VCs to remain in the navigation stack let remainingViewControllers = Array(navigationController.viewControllers[0..<index]) if remainingViewControllers.isNotEmpty { navigationController.setViewControllers(remainingViewControllers, animated: animated) } // set the appropriate value based on whether there are VCs remaining in the navigation stack return remainingViewControllers.isEmpty } // Return the default value for the flag return true } // MARK: - Child coordinators open func addChild(_ flowController: FlowCoordinator) { if !childCoordinators.contains(where: { $0 === flowController }) { childCoordinators.append(flowController) flowController.parentCoordinator = self } } open func removeChild(_ flowController: FlowCoordinator) { if let index = childCoordinators.firstIndex(where: { $0 === flowController }) { childCoordinators.remove(at: index) } } // MARK: - UINavigationControllerDelegate open func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { // Check if the root is not dead guard let rootViewController = rootViewController else { return } // If the navigation controller is the current root view controller // then this method shouldn't get called. // But that's not possible with our current implementation. guard self.navigationController != rootViewController else { return } // If `rootViewController` is not present in the navigation stack // we have to stop the current flow if !navigationController.viewControllers.contains(rootViewController) { navigationController.delegate = parentNavigationDelegate stop() } } open func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { nil } open func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { nil } // MARK: - UIAdaptivePresentationControllerDelegate open func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { if presentationController.presentedViewController == rootViewController { stop() } } // MARK: - DeepLink /// Handle deep link with currently active coordinator. If not handled, function returns false @discardableResult open func handleDeeplink(_ deeplink: DeepLinkType) -> Bool { activeChild?.handleDeeplink(deeplink) ?? false } // MARK: - Debug override public init() { super.init() if Base.memoryLoggingEnabled && Base.flowCoordinatorMemoryLoggingEnabled { if #available(iOS 10.0, *) { os_log("🔀 👶 %@", log: Logger.lifecycleLog(), type: .info, "\(self)") } else { NSLog("🔀 👶 \(self)") } } } deinit { if Base.memoryLoggingEnabled && Base.flowCoordinatorMemoryLoggingEnabled { if #available(iOS 10.0, *) { os_log("🔀 ⚰️ %@", log: Logger.lifecycleLog(), type: .info, "\(self)") } else { NSLog("🔀 ⚰️ \(self)") } } } /// Wait for a second and check whether rootViewController was set private func checkRootViewController() { let currentQueue = OperationQueue.current?.underlyingQueue assert(currentQueue != nil) currentQueue?.asyncAfter(deadline: .now() + 1) { [weak self] in /// If `self` is nil, then I think we should not care guard let self = self else { return } if self.rootViewController == nil { assertionFailure("rootViewController is nil") } } } } /// Empty class for Base.FlowCoordinator with no deep link handling public enum NoDeepLink {} /// Base VC with no VM open class FlowCoordinatorNoDeepLink: Base.FlowCoordinator<NoDeepLink> { } }
mit
eb621b0afc707b92a0a9ff851f87618f
42.169675
256
0.630038
6.205501
false
false
false
false
google/android-auto-companion-ios
Sources/AndroidAutoConnectedDeviceManagerMocks/TrustAgentManagerStorageFake.swift
1
2477
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation @testable import AndroidAutoConnectedDeviceManager /// A fake `TrustAgentManagerStorage` that stores values in memory. public class TrustAgentManagerStorageFake: TrustAgentManagerStorage { private var unlockHistory = [Car: [Date]]() private var featureStatuses = [Car: Data]() public init() {} /// Adds to the unlock history for the car. /// /// - Parameters: /// - date: The date to add to the unlock history. /// - car: The car that has been unlocked. public func addUnlockDate(_ date: Date, for car: Car) { var history = self.unlockHistory(for: car) history.append(date) unlockHistory[car] = history } /// Clear unlock history for the car. /// /// - Parameter car: The car for which to clear the unlock history. public func clearUnlockHistory(for car: Car) { unlockHistory[car] = [] } /// Clears unlock history for all cars. public func clearAllUnlockHistory() { unlockHistory = [:] } /// Returns the unlock history for a car. /// /// - Parameter car: The car whose unlock history we want to retrieve. /// - Returns: The list of previous unlock dates, or an empty list if there is no history. public func unlockHistory(for car: Car) -> [Date] { return unlockHistory[car, default: []] } /// Stores the status of the trusted device feature for the given car. public func storeFeatureStatus(_ status: Data, for car: Car) { featureStatuses[car] = status } /// Returns any feature status for the given car. public func featureStatus(for car: Car) -> Data? { return featureStatuses[car] } /// Clears any stored feature status for the given car. public func clearFeatureStatus(for car: Car) { featureStatuses[car] = nil } /// Resets back to the default initialization state. public func reset() { unlockHistory = [:] featureStatuses = [:] } }
apache-2.0
e29e9c67b6df8698f68beea49160eb66
31.168831
92
0.696811
4.170034
false
false
false
false
johnpatrickmorgan/Sparse
Sources/SparseTests/CSV/CSVTests.swift
1
3120
// // CSVTests.swift // Sparse // // Created by John Morgan on 14/12/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation @testable import Sparse import Quick import Nimble class CSVSpec: QuickSpec { override func spec() { describe("the cell parser") { let parser = CSVParser.cell it("should parse an unquoted cell as expected") { let input = "a simple cell" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("a simple cell")) } } it("should parse a quoted cell as expected") { let input = "\"a simple cell\"" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("a simple cell")) } } it("should parse a quoted cell with escapes as expected") { let input = "\"a \"\"simple\"\" cell\"" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal("a \"simple\" cell")) } } } describe("the line parser") { let parser = CSVParser.line it("should parse unquoted cells as expected") { let input = "one cell,another" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal(["one cell","another"])) } } it("should parse quoted cells as expected") { let input = "\"one cell\",\"another\"" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal(["one cell","another"])) } } it("should quoted cells with escapes as expected") { let input = "\"one \"\"cell\"\"\",\"\"\"and\"\" another\"" let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { expect(output).to(equal(["one \"cell\"","\"and\" another"])) } } } describe("the csv parser") { let parser = CSVParser.csv it("should parse the test file as expected") { let input = csvExample let stream = Stream(input) if let output = shouldNotThrow({ try parser.parse(stream) }) { for r in 1...8 { for c in 1...8 { expect(output[r-1][c-1]).to(equal("r\(r)c\(c)")) } } } } } } }
mit
48f7e09bb5f26179b7690fb144c02c75
34.443182
80
0.450144
4.958665
false
false
false
false
Google-IO-Extended-Grand-Rapids/conference_ios
ConferenceApp/ConferenceApp/ExploreViewController.swift
1
3547
// // ExploreViewController.swift // ConferenceApp // // Created by Dan McCracken on 3/7/15. // Copyright (c) 2015 GR OpenSource. All rights reserved. // import UIKit class ExploreViewController: UITableViewController { var objects = NSMutableArray() var conferencesDao: ConferencesDao! override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate conferencesDao = appDelegate.conferencesDao! conferencesDao.getAllConferences(receivedConferences) } func receivedConferences(conferences: NSArray) { for conference in conferences { if let conference = conference as? Conference { insertNewObject(conference) } } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) NSLog("receivedConferences") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { let y = sender as? Conference if (y != nil) { objects.insertObject(sender, atIndex: 0) } else { objects.insertObject(NSDate().description, atIndex: 0) } let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = objects[indexPath.row] as! Conference (segue.destinationViewController as! EventDetailsViewController).detailItem = object } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! EventCell let object = objects[indexPath.row] as! Conference let formatter = NSDateFormatter() formatter.dateStyle = NSDateFormatterStyle.MediumStyle cell.nameLabel.text = object.name cell.locationLabel.text = object.location?.name cell.durationLabel.text = String(format: "%@ to %@",formatter.stringFromDate(object.startDate!),formatter.stringFromDate(object.endDate!)) if object.id! % 2 == 0 { cell.backgroundImageView.image = UIImage(named: "GRDark.jpg") } else { cell.backgroundImageView.image = UIImage(named: "GRLight.jpg") } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView .deselectRowAtIndexPath(indexPath, animated: true) } }
apache-2.0
d23fac908c99922b2954dc03f7eff62f
32.471698
146
0.635749
5.358006
false
false
false
false
soffes/Motivation
Motivation/AgeView.swift
1
6187
// // AgeView.swift // Motivation // // Created by Sam Soffes on 8/6/15. // Copyright (c) 2015 Sam Soffes. All rights reserved. // import Foundation import ScreenSaver class AgeView: ScreenSaverView { // MARK: - Properties private let textLabel: NSTextField = { let label = NSTextField() label.translatesAutoresizingMaskIntoConstraints = false label.editable = false label.drawsBackground = false label.bordered = false label.bezeled = false label.selectable = false label.textColor = .whiteColor() return label }() private lazy var configurationWindowController: NSWindowController = { return ConfigurationWindowController() }() private var motivationLevel: MotivationLevel private var birthday: NSDate? { didSet { updateFont() } } // MARK: - Initializers convenience init() { self.init(frame: CGRectZero, isPreview: false) } override init!(frame: NSRect, isPreview: Bool) { motivationLevel = Preferences().motivationLevel super.init(frame: frame, isPreview: isPreview) initialize() } required init?(coder: NSCoder) { motivationLevel = Preferences().motivationLevel super.init(coder: coder) initialize() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - NSView override func drawRect(rect: NSRect) { let backgroundColor: NSColor = .blackColor() backgroundColor.setFill() NSBezierPath.fillRect(bounds) } // If the screen saver changes size, update the font override func resizeWithOldSuperviewSize(oldSize: NSSize) { super.resizeWithOldSuperviewSize(oldSize) updateFont() } // MARK: - ScreenSaverView override func animateOneFrame() { if let birthday = birthday { let age = ageForBirthday(birthday) let format = "%0.\(motivationLevel.decimalPlaces)f" textLabel.stringValue = String(format: format, age) } else { textLabel.stringValue = "Open Screen Saver Options to set your birthday." } } override func hasConfigureSheet() -> Bool { return true } override func configureSheet() -> NSWindow? { return configurationWindowController.window } // MARK: - Private /// Shared initializer private func initialize() { // Set animation time interval animationTimeInterval = 1 / 30 // Recall preferences birthday = Preferences().birthday // Setup the label addSubview(textLabel) addConstraints([ NSLayoutConstraint(item: textLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0), NSLayoutConstraint(item: textLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0) ]) // Listen for configuration changes NSNotificationCenter.defaultCenter().addObserver(self, selector: "motivationLevelDidChange:", name: Preferences.motivationLevelDidChangeNotificationName, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "birthdayDidChange:", name: Preferences.birthdayDidChangeNotificationName, object: nil) } /// Age calculation private func ageForBirthday(birthday: NSDate) -> Double { let calendar = NSCalendar.currentCalendar() let now = NSDate() // An age is defined as the number of years you've been alive plus the number of days, seconds, and nanoseconds // you've been alive out of that many units in the current year. let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Day, NSCalendarUnit.Second, NSCalendarUnit.Nanosecond], fromDate: birthday, toDate: now, options: []) // We calculate these every time since the values can change when you cross a boundary. Things are too // complicated to try to figure out when that is and cache them. NSCalendar is made for this. let daysInYear = Double(calendar.daysInYear(now) ?? 365) let hoursInDay = Double(calendar.rangeOfUnit(NSCalendarUnit.Hour, inUnit: NSCalendarUnit.Day, forDate: now).length) let minutesInHour = Double(calendar.rangeOfUnit(NSCalendarUnit.Minute, inUnit: NSCalendarUnit.Hour, forDate: now).length) let secondsInMinute = Double(calendar.rangeOfUnit(NSCalendarUnit.Second, inUnit: NSCalendarUnit.Minute, forDate: now).length) let nanosecondsInSecond = Double(calendar.rangeOfUnit(NSCalendarUnit.Nanosecond, inUnit: NSCalendarUnit.Second, forDate: now).length) // Now that we have all of the values, assembling them is easy. We don't get minutes and hours from the calendar // since it will overflow nicely to seconds. We need days and years since the number of days in a year changes // more frequently. This will handle leap seconds, days, and years. let seconds = Double(components.second) + (Double(components.nanosecond) / nanosecondsInSecond) let minutes = seconds / secondsInMinute let hours = minutes / minutesInHour let days = Double(components.day) + (hours / hoursInDay) let years = Double(components.year) + (days / daysInYear) return years } /// Motiviation level changed @objc private func motivationLevelDidChange(notification: NSNotification?) { motivationLevel = Preferences().motivationLevel } /// Birthday changed @objc private func birthdayDidChange(notification: NSNotification?) { birthday = Preferences().birthday } /// Update the font for the current size private func updateFont() { if birthday != nil { textLabel.font = fontWithSize(bounds.width / 10) } else { textLabel.font = fontWithSize(bounds.width / 30, monospace: false) } } /// Get a font private func fontWithSize(fontSize: CGFloat, monospace: Bool = true) -> NSFont { let font: NSFont if #available(OSX 10.11, *) { font = .systemFontOfSize(fontSize, weight: NSFontWeightThin) } else { font = NSFont(name: "HelveticaNeue-Thin", size: fontSize)! } let fontDescriptor: NSFontDescriptor if monospace { fontDescriptor = font.fontDescriptor.fontDescriptorByAddingAttributes([ NSFontFeatureSettingsAttribute: [ [ NSFontFeatureTypeIdentifierKey: kNumberSpacingType, NSFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector ] ] ]) } else { fontDescriptor = font.fontDescriptor } return NSFont(descriptor: fontDescriptor, size: fontSize)! } }
mit
d404ac9bd8bf0f739cd70af79c0e90f3
30.566327
177
0.742686
4.033246
false
false
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/Examples/Examples/BarsPlusMinusWithGradientExample.swift
1
7640
// // BarsPlusMinusWithGradientExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class BarsPlusMinusWithGradientExample: UIViewController { fileprivate var chart: Chart? // arc fileprivate let gradientPicker: GradientPicker // to pick the colors of the bars override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { self.gradientPicker = GradientPicker(width: 200) super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { let vals: [(title: String, val: CGFloat)] = [ ("U", -75), ("T", -65), ("S", -50), ("R", -45), ("Q", -40), ("P", -30), ("O", -20), ("N", -10), ("M", -5), ("L", -0), ("K", 10), ("J", 15), ("I", 20), ("H", 30), ("G", 35), ("F", 40), ("E", 50), ("D", 60), ("C", 65), ("B", 70), ("A", 75) ] let (minVal, maxVal): (CGFloat, CGFloat) = vals.reduce((min: CGFloat(0), max: CGFloat(0))) {tuple, val in (min: min(tuple.min, val.val), max: max(tuple.max, val.val)) } let length: CGFloat = maxVal - minVal let zero = ChartAxisValueDouble(0) let bars: [ChartBarModel] = vals.enumerated().map {index, tuple in let percentage = (tuple.val - minVal - 0.01) / length // FIXME without -0.01 bar with 1 (100 perc) is black let color = self.gradientPicker.colorForPercentage(percentage).withAlphaComponent(0.6) return ChartBarModel(constant: ChartAxisValueDouble(Double(index)), axisValue1: zero, axisValue2: ChartAxisValueDouble(Double(tuple.val)), bgColor: color) } let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let xValues = stride(from: (-80), through: 80, by: 20).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)} let yValues = [ChartAxisValueString(order: -1)] + vals.enumerated().map {index, tuple in ChartAxisValueString(tuple.0, order: index, labelSettings: labelSettings)} + [ChartAxisValueString(order: vals.count)] let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds) // calculate coords space in the background to keep UI smooth DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { let coordsSpace = ChartCoordsSpaceLeftTopSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) DispatchQueue.main.async { let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let barsLayer = ChartBarsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, bars: bars, horizontal: true, barWidth: Env.iPad ? 40 : 16, animDuration: 0.5) let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: .x, settings: settings) // create x zero guideline as view to be in front of the bars let dummyZeroXChartPoint = ChartPoint(x: ChartAxisValueDouble(0), y: ChartAxisValueDouble(0)) let xZeroGuidelineLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: [dummyZeroXChartPoint], viewGenerator: {(chartPointModel, layer, chart) -> UIView? in let width: CGFloat = 2 let v = UIView(frame: CGRect(x: chartPointModel.screenLoc.x - width / 2, y: innerFrame.origin.y, width: width, height: innerFrame.size.height)) v.backgroundColor = UIColor(red: 1, green: 69 / 255, blue: 0, alpha: 1) return v }) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, barsLayer, xZeroGuidelineLayer ] ) self.view.addSubview(chart.view) self.chart = chart } } } fileprivate class GradientPicker { let gradientImg: UIImage lazy var imgData: UnsafePointer<UInt8> = { let provider = self.gradientImg.cgImage!.dataProvider let pixelData = provider!.data return CFDataGetBytePtr(pixelData) }() init(width: CGFloat) { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = CGRect(x: 0, y: 0, width: width, height: 1) gradient.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.cyan.cgColor, UIColor.blue.cgColor] gradient.startPoint = CGPoint(x: 0, y: 0.5) gradient.endPoint = CGPoint(x: 1.0, y: 0.5) let imgHeight = 1 let imgWidth = Int(gradient.bounds.size.width) let bitmapBytesPerRow = imgWidth * 4 let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue).rawValue let context = CGContext (data: nil, width: imgWidth, height: imgHeight, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) UIGraphicsBeginImageContext(gradient.bounds.size) gradient.render(in: context!) let gradientImg = UIImage(cgImage: context!.makeImage()!) UIGraphicsEndImageContext() self.gradientImg = gradientImg } func colorForPercentage(_ percentage: CGFloat) -> UIColor { let data = self.imgData let xNotRounded = self.gradientImg.size.width * percentage let x = 4 * (floor(abs(xNotRounded / 4))) let pixelIndex = Int(x * 4) let color = UIColor( red: CGFloat(data[pixelIndex + 0]) / 255.0, green: CGFloat(data[pixelIndex + 1]) / 255.0, blue: CGFloat(data[pixelIndex + 2]) / 255.0, alpha: CGFloat(data[pixelIndex + 3]) / 255.0 ) return color } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
mit
0326b5ce1e73cd2836a7b9e7d7315121
39.855615
214
0.55589
4.99673
false
false
false
false
KYawn/myiOS
UsingData/UsingData/UsersTableViewController.swift
1
3933
// // UsersTableViewController.swift // UsingData // // Created by K.Yawn Xoan on 3/24/15. // Copyright (c) 2015 K.Yawn Xoan. All rights reserved. // import UIKit import CoreData class UsersTableViewController: UITableViewController { var dataArr:Array<AnyObject> = [] var context:NSManagedObjectContext! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext var f = NSFetchRequest(entityName: "Users") dataArr = context.executeFetchRequest(f, error: nil)! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return dataArr.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell // Configure the cell... var label = cell.viewWithTag(2) as UILabel var name: AnyObject? = dataArr[indexPath.row].valueForKey("name") var age: AnyObject? = dataArr[indexPath.row].valueForKey("age") label.text = "name:\(name!),age:\(age!)" return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } 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 } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
apache-2.0
5cee937fc38bf3c254db2d3ecf9c8185
33.2
157
0.674294
5.508403
false
false
false
false
Tim77277/WizardUIKit
WizardUIKit/ActivityIndicatorAlert.swift
1
870
// // ActivityIndicatorAlert.swift // WizardUIKit // // Created by Wei-Ting Lin on 11/19/16. // Copyright © 2016 Wei-Ting Lin. All rights reserved. // import UIKit public struct WizardIndicatorAlert { public var cornerRadius: CGFloat public var backgroundColor : UIColor public var color: UIColor public var dimColor: UIColor public init() { self.cornerRadius = 15 self.color = UIColor.WizardBlueColor() self.backgroundColor = .white self.dimColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) } public init(cornerRadius: CGFloat, backgroundColor: UIColor, color: UIColor, dimColor: UIColor) { self.cornerRadius = cornerRadius self.backgroundColor = backgroundColor self.color = color self.dimColor = dimColor } }
mit
b6286fdf48c5af9e19edc2b176e8a82e
27.966667
101
0.632911
4.30198
false
false
false
false
ACChe/eidolon
Kiosk/App/Models/SaleArtworkViewModel.swift
1
4762
import Foundation import ReactiveCocoa private let kNoBidsString = "0 bids placed" class SaleArtworkViewModel: NSObject { private let saleArtwork: SaleArtwork init (saleArtwork: SaleArtwork) { self.saleArtwork = saleArtwork } } // Extension for computed properties extension SaleArtworkViewModel { // MARK: Computed values we don't expect to ever change. var estimateString: String { // Default to estimateCents if let estimateCents = saleArtwork.estimateCents { let dollars = NSNumberFormatter.currencyStringForCents(estimateCents) return "Estimate: \(dollars)" } // Try to extract non-nil low/high estimates. Return a default otherwise. switch (saleArtwork.lowEstimateCents, saleArtwork.highEstimateCents) { case let (.Some(lowCents), .Some(highCents)): let lowDollars = NSNumberFormatter.currencyStringForCents(lowCents) let highDollars = NSNumberFormatter.currencyStringForCents(highCents) return "Estimate: \(lowDollars)–\(highDollars)" default: return "No Estimate" } } var thumbnailURL: NSURL? { return saleArtwork.artwork.defaultImage?.thumbnailURL() } var thumbnailAspectRatio: CGFloat? { return saleArtwork.artwork.defaultImage?.aspectRatio } var artistName: String? { return saleArtwork.artwork.artists?.first?.name } var titleAndDateAttributedString: NSAttributedString? { return saleArtwork.artwork.titleAndDate } var saleArtworkID: String { return saleArtwork.id } // Signals representing values that change over time. var numberOfBidsSignal: RACSignal { return RACObserve(saleArtwork, "bidCount").map { (optionalBidCount) -> AnyObject! in // Technically, the bidCount is Int?, but the `as?` cast could fail (it never will, but the compiler doesn't know that) // So we need to unwrap it as an optional optional. Yo dawg. let bidCount = optionalBidCount as! Int? if let bidCount = bidCount { let suffix = bidCount == 1 ? "" : "s" return "\(bidCount) bid\(suffix) placed" } else { return kNoBidsString } } } // The language used here is very specific – see https://github.com/artsy/eidolon/pull/325#issuecomment-64121996 for details var numberOfBidsWithReserveSignal: RACSignal { return RACSignal.combineLatest([numberOfBidsSignal, RACObserve(saleArtwork, "reserveStatus"), RACObserve(saleArtwork, "highestBidCents")]).map { (object) -> AnyObject! in let tuple = object as! RACTuple // Ignoring highestBidCents; only there to trigger on bid update. let numberOfBidsString = tuple.first as! String let reserveStatus = ReserveStatus.initOrDefault(tuple.second as? String) // if there is no reserve, just return the number of bids string. if reserveStatus == .NoReserve { return numberOfBidsString } else { if numberOfBidsString == kNoBidsString { // If there are no bids, then return only this string. return "This lot has a reserve" } else if reserveStatus == .ReserveNotMet { return "(\(numberOfBidsString), Reserve not met)" } else { // implicitly, reserveStatus is .ReserveMet return "(\(numberOfBidsString), Reserve met)" } } } } var lotNumberSignal: RACSignal { return RACObserve(saleArtwork, "lotNumber").map { (lotNumber) -> AnyObject! in if let lotNumber = lotNumber as? Int { return "Lot \(lotNumber)" } else { return nil } }.mapNilToEmptyString() } var forSaleSignal: RACSignal { return RACObserve(saleArtwork, "artwork").map { (artwork) -> AnyObject! in let artwork = artwork as! Artwork return Artwork.SoldStatus.fromString(artwork.soldStatus) == .NotSold } } func currentBidSignal(prefix prefix: String = "", missingPrefix: String = "") -> RACSignal { return RACObserve(saleArtwork, "highestBidCents").map { [weak self] (highestBidCents) -> AnyObject! in if let currentBidCents = highestBidCents as? Int { return "\(prefix)\(NSNumberFormatter.currencyStringForCents(currentBidCents))" } else { return "\(missingPrefix)\(NSNumberFormatter.currencyStringForCents(self?.saleArtwork.openingBidCents ?? 0))" } } } }
mit
cc8167af38e8819f62dcf8757502dd2d
36.761905
178
0.624842
5.228571
false
false
false
false
Oyvindkg/swiftydb
Pod/Classes/SwiftyDB.swift
1
15063
// // SwiftyDB.swift // SwiftyDB // // Created by Øyvind Grimnes on 03/11/15. // import Foundation import TinySQLite /** All objects in the database must conform to the 'Storable' protocol */ public protocol Storable { /** Used to initialize an object to get information about its properties */ init() } /** Implement this protocol to use primary keys */ public protocol PrimaryKeys { /** Method used to define a set of primary keys for the types table - returns: set of property names */ static func primaryKeys() -> Set<String> } /** Implement this protocol to ignore arbitrary properties */ public protocol IgnoredProperties { /** Method used to define a set of ignored properties - returns: set of property names */ static func ignoredProperties() -> Set<String> } /** A class wrapping an SQLite3 database abstracting the creation of tables, insertion, update, and retrieval */ public class SwiftyDB { /** The database queue that will be used to access the database */ private let databaseQueue : DatabaseQueue /** Path to the database that should be used */ private let path: String /** A cache containing existing table names */ private var existingTables: Set<String> = [] /** Creates a new instance of SwiftyDB using a database in the documents directory. If the database does not exist, it will be created. - parameter databaseName: name of the database - returns: an instance of SwiftyDB */ public init(databaseName: String) { let documentsDir : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] path = documentsDir+"/\(databaseName).sqlite" databaseQueue = DatabaseQueue(path: path) } // MARK: - Database operations /** Add an object to the database - parameter object: object to be added to the database - parameter update: indicates whether the record should be updated if already present - returns: Result type indicating the success of the query */ public func addObject <S: Storable> (object: S, update: Bool = true) -> Result<Bool> { return self.addObjects([object], update: update) } /** Add objects to the database - parameter objects: objects to be added to the database - parameter update: indicates whether the record should be updated if already present - returns: Result type indicating the success of the query */ public func addObjects <S: Storable> (objects: [S], update: Bool = true) -> Result<Bool> { guard objects.count > 0 else { return Result.Success(true) } do { if !(try tableExistsForType(S)) { createTableForTypeRepresentedByObject(objects.first!) } let insertStatement = StatementGenerator.insertStatementForType(S.self, update: update) try databaseQueue.transaction { (database) -> Void in let statement = try database.prepare(insertStatement) defer { /* If an error occurs, try to finalize the statement */ let _ = try? statement.finalize() } for object in objects { let data = self.dataFromObject(object) try statement.executeUpdate(data) } } } catch let error { return Result.Error(error) } return Result.Success(true) } /** Add objects to the database - parameter object: object to be added to the database - parameter moreObjects: more objects to be added to the database - returns: Result type indicating the success of the query */ public func addObjects <S: Storable> (object: S, _ moreObjects: S...) -> Result<Bool> { return addObjects([object] + moreObjects) } /** Remove objects of a specified type, matching a filter, from the database - parameter filter: `Filter` object containing the filters for the query - parameter type: type of the objects to be deleted - returns: Result type indicating the success of the query */ public func deleteObjectsForType (type: Storable.Type, matchingFilter filter: Filter? = nil) -> Result<Bool> { do { guard try tableExistsForType(type) else { return Result.Success(true) } let deleteStatement = StatementGenerator.deleteStatementForType(type, matchingFilter: filter) try databaseQueue.database { (database) -> Void in try database.prepare(deleteStatement) .executeUpdate(filter?.parameters() ?? [:]) .finalize() } } catch let error { return .Error(error) } return .Success(true) } /** Get data for a specified type, matching a filter, from the database - parameter filter: `Filter` object containing the filters for the query - parameter type: type of the objects for which to retrieve data - returns: Result type wrapping an array with the dictionaries representing objects, or an error if unsuccessful */ public func dataForType <S: Storable> (type: S.Type, matchingFilter filter: Filter? = nil) -> Result<[[String: Value?]]> { var results: [[String: Value?]] = [] do { guard try tableExistsForType(type) else { return Result.Success([]) } /* Generate statement */ let query = StatementGenerator.selectStatementForType(type, matchingFilter: filter) try databaseQueue.database { (database) -> Void in let parameters = filter?.parameters() ?? [:] let statement = try! database.prepare(query) .execute(parameters) /* Create a dummy object used to extract property data */ let object = type.init() let objectPropertyData = PropertyData.validPropertyDataForObject(object) results = statement.map { row in self.parsedDataForRow(row, forPropertyData: objectPropertyData) } try statement.finalize() } } catch let error { return .Error(error) } return .Success(results) } // MARK: - Private functions /** Creates a new table for the specified type based on the provided column definitions The parameter is an object, instead of a type, to avoid forcing the user to implement initialization methods such as 'init' - parameter type: type of objects data in the table represents - returns: Result type indicating the success of the query */ private func createTableForTypeRepresentedByObject <S: Storable> (object: S) -> Result<Bool> { let statement = StatementGenerator.createTableStatementForTypeRepresentedByObject(object) do { try databaseQueue.database({ (database) -> Void in try database.prepare(statement) .executeUpdate() .finalize() }) } catch let error { return .Error(error) } existingTables.insert(tableNameForType(S)) return .Success(true) } /** Serialize the object - parameter object: object containing the data to be extracted - returns: dictionary containing the data from the object */ private func dataFromObject (object: Storable) -> [String: SQLiteValue?] { var dictionary: [String: SQLiteValue?] = [:] for propertyData in PropertyData.validPropertyDataForObject(object) { dictionary[propertyData.name!] = propertyData.value as? SQLiteValue } return dictionary } /** Check whether a table representing a type exists, or not - parameter type: type implementing the Storable protocol - returns: boolean indicating if the table exists */ private func tableExistsForType(type: Storable.Type) throws -> Bool { let tableName = tableNameForType(type) var exists: Bool = existingTables.contains(tableName) /* Return true if the result is cached */ guard !exists else { return exists } try databaseQueue.database({ (database) in exists = try database.containsTable(tableName) }) /* Cache the result */ if exists { existingTables.insert(tableName) } return exists } /** Used to create name of the table representing a type - parameter type: type for which to generate a table name - returns: table name as a String */ private func tableNameForType(type: Storable.Type) -> String { return String(type) } /** Create a dictionary with values matching datatypes based on some property data - parameter row: row, in the form of a wrapped SQLite statement, from which to receive values - parameter propertyData: array containing information about property names and datatypes - returns: dictionary containing data of types matching the properties of the target type */ private func parsedDataForRow(row: Statement, forPropertyData propertyData: [PropertyData]) -> [String: Value?] { var rowData: [String: Value?] = [:] for propertyData in propertyData { rowData[propertyData.name!] = valueForProperty(propertyData, inRow: row) } return rowData } /** Retrieve the value for a property with the correct datatype - parameter propertyData: object containing information such as property name and type - parameter row: row, in the form of a wrapped SQLite statement, from which to retrieve the value - returns: optional value for the property */ private func valueForProperty(propertyData: PropertyData, inRow row: Statement) -> Value? { if row.typeForColumn(propertyData.name!) == .Null { return nil } switch propertyData.type { case is NSDate.Type: return row.dateForColumn(propertyData.name!) as? Value case is NSData.Type: return row.dataForColumn(propertyData.name!) as? Value case is NSNumber.Type: return row.numberForColumn(propertyData.name!) as? Value case is String.Type: return row.stringForColumn(propertyData.name!) as? Value case is NSString.Type: return row.nsstringForColumn(propertyData.name!) as? Value case is Character.Type: return row.characterForColumn(propertyData.name!) as? Value case is Double.Type: return row.doubleForColumn(propertyData.name!) as? Value case is Float.Type: return row.floatForColumn(propertyData.name!) as? Value case is Int.Type: return row.integerForColumn(propertyData.name!) as? Value case is Int8.Type: return row.integer8ForColumn(propertyData.name!) as? Value case is Int16.Type: return row.integer16ForColumn(propertyData.name!) as? Value case is Int32.Type: return row.integer32ForColumn(propertyData.name!) as? Value case is Int64.Type: return row.integer64ForColumn(propertyData.name!) as? Value case is UInt.Type: return row.unsignedIntegerForColumn(propertyData.name!) as? Value case is UInt8.Type: return row.unsignedInteger8ForColumn(propertyData.name!) as? Value case is UInt16.Type: return row.unsignedInteger16ForColumn(propertyData.name!) as? Value case is UInt32.Type: return row.unsignedInteger32ForColumn(propertyData.name!) as? Value case is UInt64.Type: return row.unsignedInteger64ForColumn(propertyData.name!) as? Value case is Bool.Type: return row.boolForColumn(propertyData.name!) as? Value case is NSArray.Type: return NSKeyedUnarchiver.unarchiveObjectWithData(row.dataForColumn(propertyData.name!)!) as? NSArray case is NSDictionary.Type: return NSKeyedUnarchiver.unarchiveObjectWithData(row.dataForColumn(propertyData.name!)!) as? NSDictionary default: return nil } } } extension SwiftyDB { // MARK: - Dynamic initialization /** Get objects of a specified type, matching a filter, from the database - parameter filter: `Filter` object containing the filters for the query - parameter type: type of the objects to be retrieved - returns: Result wrapping the objects, or an error, if unsuccessful */ public func objectsForType <D where D: Storable, D: NSObject> (type: D.Type, matchingFilter filter: Filter? = nil) -> Result<[D]> { let dataResults = dataForType(D.self, matchingFilter: filter) if !dataResults.isSuccess { return .Error(dataResults.error!) } let objects: [D] = dataResults.value!.map { objectWithData($0, forType: D.self) } return .Success(objects) } /** Creates a new dynamic object of a specified type and populates it with data from the provided dictionary - parameter data: dictionary containing data - parameter type: type of object the data represents - returns: object of the provided type populated with the provided data */ private func objectWithData <D where D: Storable, D: NSObject> (data: [String: Value?], forType type: D.Type) -> D { let object = (type as NSObject.Type).init() as! D var validData: [String: AnyObject] = [:] data.forEach { (name, value) -> () in if let validValue = value as? AnyObject { validData[name] = validValue } } object.setValuesForKeysWithDictionary(validData) return object } }
mit
74f85ecd57f6a3fe85a9f65b34d074e2
34.609929
160
0.599323
5.16884
false
false
false
false
pdx-ios/tvOS-workshop
RoShamBo/RoShamBo/Game.swift
1
2813
// // Choice.swift // RoShamBo // // Created by Ryan Arana on 3/26/15. // Copyright (c) 2015 PDX-iOS. All rights reserved. // import Foundation enum Verb: String { case draw = "-draw-" case crushes case disproves case covers case cuts case decapitates case vaporizes case eats case poisons init(_ game: Game) { guard game.winner != game.loser else { self = .draw; return } switch (game.winner, game.loser) { case (.Rock, .Scissors), (.Rock, .Lizard): self = .crushes case (.Paper, .Rock): self = .covers case (.Paper, .Spock): self = .disproves case (.Scissors, .Paper): self = .cuts case (.Scissors, .Lizard): self = .decapitates case (.Lizard, .Spock): self = .poisons case (.Lizard, .Paper): self = .eats case (.Spock, .Rock), (.Spock, .Scissors): self = .vaporizes default: preconditionFailure("Invalid winner/loser combination: \(game.winner) does not beat \(game.loser)") } } } enum Choice: Int { case Rock = 1 case Paper case Scissors case Spock case Lizard var name: String { switch self { case .Rock: return "rock" case .Paper: return "paper" case .Scissors: return "scissors" case .Spock: return "spock" case .Lizard: return "lizard" } } static func all() -> [Choice] { return [.Rock, .Paper, .Scissors, .Spock, .Lizard] } static func random() -> Choice { let c = Int(arc4random_uniform(UInt32(5))) + 1 return Choice(rawValue: c)! } } struct Game { let winner: Choice let loser: Choice var draw: Bool { return winner == loser } var verb: String { return Verb(self).rawValue } init(choices p1: Choice, _ p2: Choice) { guard p1 != p2 else { winner = p1 loser = p2 return } let higher = p1.rawValue > p2.rawValue ? p1 : p2 let lower = higher == p1 ? p2 : p1 if p1.rawValue % 2 == p2.rawValue % 2 { // If both are odd or both are even, the lower one wins winner = lower loser = higher } else { // Otherwise the higher one wins winner = higher loser = lower } } static func play(choice: Choice) -> Game { return Game(choices: choice, Choice.random()) } var summary: String { if draw { return verb.capitalizedString } return "\(winner.name.capitalizedString) \(verb) \(loser.name.capitalizedString)." } }
mit
8621d9a61845ab9b4bcd18cc530f87ae
23.46087
111
0.518308
3.912378
false
false
false
false
lennet/proNotes
app/proNotes/Model/Document.swift
1
5707
// // Document.swift // proNotes // // Created by Leo Thomas on 28/11/15. // Copyright © 2015 leonardthomas. All rights reserved. // import UIKit class Document: UIDocument { private final let metaDataFileName = "note.metaData" private final let pagesDataFileName = "note.pagesData" var name: String { get { return fileURL.fileName(true) ?? "" } } var fileWrapper: FileWrapper? override init(fileURL url: URL) { super.init(fileURL: url) } override var description: String { get { return fileURL.fileName(true) ?? super.description } } var _metaData: DocumentMetaData? var metaData: DocumentMetaData? { get { guard _metaData == nil else { return _metaData } if fileWrapper != nil { _metaData = decodeObject(metaDataFileName) as? DocumentMetaData } if _metaData == nil { _metaData = DocumentMetaData() } return _metaData } set { _metaData = newValue } } var _pages: [DocumentPage]? var pages: [DocumentPage] { get { if _pages == nil { if fileWrapper != nil { _pages = decodeObject(pagesDataFileName) as? [DocumentPage] } if _pages == nil { _pages = [DocumentPage]() } } return _pages! } set { _pages = newValue } } subscript(pageIndex: Int) -> DocumentPage? { get { if pageIndex < pages.count { return pages[pageIndex] } return nil } } var numberOfPages: Int { get { return pages.count } } // MARK - Load Document override func load(fromContents contents: Any, ofType typeName: String?) throws { if let wrapper = contents as? FileWrapper { fileWrapper = wrapper } else if let wrapper = decodeData(contents as! Data) as? FileWrapper { fileWrapper = wrapper } } func decodeObject(_ fileName: String) -> Any? { guard let wrapper = fileWrapper?.fileWrappers?[fileName] else { return nil } guard let data = wrapper.regularFileContents else { return nil } return decodeData(data) } func decodeData(_ data: Data) -> Any? { let unarchiver = NSKeyedUnarchiver(forReadingWith: data) return unarchiver.decodeObject(forKey: "data") } override func save(to url: URL, for saveOperation: UIDocumentSaveOperation, completionHandler: ((Bool) -> Void)?) { super.save(to: url, for: saveOperation, completionHandler: completionHandler) } // MARK - Store Document override func contents(forType typeName: String) throws -> Any { if metaData == nil { return Data() } var wrappers = [String: FileWrapper]() metaData?.thumbImage = pages.first?.previewImage encodeObject(metaData!, prefferedFileName: metaDataFileName, wrappers: &wrappers) encodeObject(pages, prefferedFileName: pagesDataFileName, wrappers: &wrappers) let fileWrapper = FileWrapper(directoryWithFileWrappers: wrappers) return fileWrapper } func encodeObject(_ object: Any, prefferedFileName: String, wrappers: inout [String:FileWrapper]) { let data = encodeObject(object) let wrapper = FileWrapper(regularFileWithContents: data) wrappers[prefferedFileName] = wrapper } func encodeObject(_ object: Any) -> Data { let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: data) archiver.encode(object, forKey: "data") archiver.finishEncoding() return data as Data } func getMaxWidth() -> CGFloat { return (pages.sorted(by: { $0.size.width > $1.size.width }).first?.size.width ?? 0) } override func close(completionHandler: ((Bool) -> Void)?) { if DocumentInstance.sharedInstance.document == self { DocumentInstance.sharedInstance.document = nil } super.close(completionHandler: completionHandler) } // MARK - Pages Manipulation func addPDF(_ url: URL) { guard let pdf = CGPDFDocument(url as CFURL) else { return } let numberOfPages = pdf.numberOfPages for i in 1 ..< numberOfPages + 1 { if let pdfData = PDFUtility.getPageAsData(i, document: pdf) { let size = PDFUtility.getPDFRect(pdf, pageIndex: i).size let page = DocumentPage(pdfData: pdfData as Data, index: pages.count, pdfSize: size) pages.append(page) } } DocumentInstance.sharedInstance.informDelegateDidAddPage(pages.count - 1) } func addEmptyPage() { let page = DocumentPage(index: pages.count) pages.append(page) DocumentInstance.sharedInstance.informDelegateDidAddPage(pages.count - 1) } func swapPagePositions(_ firstIndex: Int, secondIndex: Int) { guard _pages != nil else { return } if firstIndex != secondIndex && firstIndex >= 0 && secondIndex >= 0 && firstIndex < pages.count && secondIndex < pages.count { let tmp = firstIndex pages[firstIndex].index = secondIndex pages[secondIndex].index = tmp swap(&_pages![firstIndex], &_pages![secondIndex]) } } }
mit
9e4929187e3cf88d06c47caab6391d6e
28.112245
134
0.573607
4.81113
false
false
false
false
ninewine/SaturnTimer
SaturnTimer/Model/STTagType.swift
1
1035
// // STTagType.swift // SaturnTimer // // Created by Tidy Nine on 2/29/16. // Copyright © 2016 Tidy Nine. All rights reserved. // import UIKit enum STTagType: String { case SaturnType = "saturn" case SandglassType = "sandglass" case TelevisionType = "television" case PlateType = "plate" func tagTypeTimeIsUpString () -> String { switch self { case .SaturnType: return HelperLocalization.timesupStringSaturnTag case .SandglassType: return HelperLocalization.timesupStringSandglassTag case .TelevisionType: return HelperLocalization.timesupStringTelevisionTag case .PlateType: return HelperLocalization.timesupStringPlateTag } } static func animatableTagClass (_ tagName: String) -> AnyClass? { if let type = STTagType(rawValue: tagName) { switch type { case .SaturnType: return Saturn.self case .SandglassType: return Sandglass.self case .TelevisionType: return Television.self case .PlateType: return Plate.self } } return nil } }
mit
0445325f022f721f624c022b0e49394b
26.210526
78
0.710832
3.773723
false
false
false
false
toggl/superday
teferiTests/NewPersistency/Mocks/MockCoreDataPersistency.swift
1
1195
import XCTest @testable import teferi import CoreData import RxSwift class MockCoreDataPersistency: CoreDataPersistence { var fetchCalled: Bool = false var valueToReturn: AnyObject? = nil var requestFetched: NSFetchRequest<NSFetchRequestResult>? = nil init() { super.init(managedObjectContext: NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)) } override func fetch<R: PersistenceResource>(_ resource: R) -> Observable<[R.ReturnType]> { let coreDataResource = resource as! CoreDataResource<R.ReturnType> fetchCalled = true requestFetched = coreDataResource.request if let valueToReturn = valueToReturn { return Observable.just(valueToReturn as! [R.ReturnType]) } else { return Observable.empty() } } } extension CoreDataResource { var request: NSFetchRequest<NSFetchRequestResult> { let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) request.predicate = predicate request.sortDescriptors = sortDescriptors return request } }
bsd-3-clause
25d8fd0140af350f2763b49e6a9d852d
27.452381
145
0.69205
5.532407
false
false
false
false
sunshineclt/NKU-Helper
NKU Helper/设置/ClassTimePreferenceTableViewController.swift
1
2157
// // ClassTestTimePreferenceTableViewController.swift // NKU Helper // // Created by 陈乐天 on 16/7/27. // Copyright © 2016年 陈乐天. All rights reserved. // import UIKit class ClassTimePreferenceTableViewController: UITableViewController { var courseLoadMethod: Int! override func viewDidLoad() { super.viewDidLoad() courseLoadMethod = CourseLoadMethodAgent.sharedInstance.getData() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.classTimeTablePreferenceCell.identifier)! cell.textLabel?.text = indexPath.row == 0 ? "从课程表获取" : "从选课列表获取" cell.accessoryType = courseLoadMethod == indexPath.row ? .checkmark : .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row != courseLoadMethod { CourseLoadMethodAgent.sharedInstance.save(data: indexPath.row) courseLoadMethod = indexPath.row self.tableView.reloadData() } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "选课课程表加载方式" } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return "从课程表中获取可以在开启新学期选课系统打开之后依然看到这学期的课表,但若同一时间单双周课程不同会无法加载出双周课程。从选课列表获取可以保证获取的数据均准确,但在新学期选课系统打开之后就只能加载下学期的课表。然而有的时候两个课程表会有一些不同,我表示懵逼,如果你知道是为什么请告诉我🙈" } }
gpl-3.0
9a63b0ad84feaef9243c527444359627
34.588235
158
0.699174
4.087838
false
false
false
false
enisinanaj/1-and-1.workouts
1and1.workout/Controllers/ViewController.swift
1
4220
// // ViewController.swift // microtime.tracker // // Created by Eni Sinanaj on 29/10/2016. // Copyright © 2016 Eni Sinanaj. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! let allEntriesViewController = AllEntriesViewController(nibName: "AllEntriesViewController", bundle: nil) let mainPage = MainPageViewController(nibName: "MainPageViewController", bundle: nil) let exercisesPage = ExercisesTableViewController(nibName: "ExercisesTableView", bundle: nil) fileprivate func addExercisesListPage() { exercisesPage.view.frame.origin.x = self.view.frame.width exercisesPage.view.frame.origin.y = 0 exercisesPage.view.frame.size.width = self.view.frame.size.width exercisesPage.view.frame.size.height = self.view.frame.size.height self.addChildViewController(exercisesPage) self.scrollView.addSubview(exercisesPage.view) exercisesPage.didMove(toParentViewController: self) } fileprivate func addTimerPage() { mainPage.view.frame.origin.x = self.view.frame.width * 2 mainPage.view.frame.origin.y = 0 mainPage.view.frame.size.width = self.view.frame.size.width mainPage.view.frame.size.height = self.view.frame.size.height self.addChildViewController(mainPage) self.scrollView.addSubview(mainPage.view) mainPage.didMove(toParentViewController: self) } fileprivate func addAllEntriesPage() { allEntriesViewController.view.frame.origin.x = 0 allEntriesViewController.view.frame.origin.y = 0 allEntriesViewController.view.frame.size.width = self.view.frame.size.width allEntriesViewController.view.frame.size.height = self.view.frame.size.height self.addChildViewController(allEntriesViewController); self.scrollView.addSubview(allEntriesViewController.view) allEntriesViewController.didMove(toParentViewController: self) } override func viewDidLoad() { super.viewDidLoad() print(super.view.frame) self.scrollView.frame.size.width = self.view.frame.size.width self.scrollView.frame.size.height = self.view.frame.size.height self.scrollView.contentOffset = CGPoint(x: self.view.frame.width, y: 0) addExercisesListPage() addTimerPage() addAllEntriesPage() self.mainPage.allEntriesDelegate = self.allEntriesViewController self.exercisesPage.counterPageDelegate = self.mainPage self.exercisesPage.parentController = self self.scrollView.contentSize = CGSize(width: mainPage.view.frame.size.width + allEntriesViewController.view.frame.size.width + exercisesPage.view.frame.size.width , height: self.scrollView.frame.size.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if (motion == .motionShake) { let refreshAlert = UIAlertController(title: "Delete all entries", message: "Are you sure you want to delete all entries? This action is undoable and will result all data will be lost.", preferredStyle: UIAlertControllerStyle.alert) refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in let sql = SQLiteProxy(); sql.initDB(); sql.deleteAllRows(); self.allEntriesViewController.reloadData() })) refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(refreshAlert, animated: true, completion: nil) } } override var canBecomeFirstResponder: Bool { return true } }
mit
454b0eba3426bd8c5c5ee7779c19244b
38.801887
168
0.649917
4.849425
false
false
false
false
chadsy/onebusaway-iphone
Pods/Pulley/PulleyLib/PulleyViewController.swift
1
24069
// // PulleyViewController.swift // Pulley // // Created by Brendan Lee on 7/6/16. // Copyright © 2016 52inc. All rights reserved. // import UIKit /** * The base delegate protocol for Pulley delegates. */ @objc public protocol PulleyDelegate: class { optional func drawerPositionDidChange(drawer: PulleyViewController) optional func makeUIAdjustmentsForFullscreen(progress: CGFloat) optional func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat) } /** * View controllers in the drawer can implement this to receive changes in state or provide values for the different drawer positions. */ @objc public protocol PulleyDrawerViewControllerDelegate: PulleyDelegate { func collapsedDrawerHeight() -> CGFloat func partialRevealDrawerHeight() -> CGFloat } /** * View controllers that are the main content can implement this to receive changes in state. */ @objc public protocol PulleyPrimaryContentControllerDelegate: PulleyDelegate { // Not currently used for anything, but it's here for parity with the hopes that it'll one day be used. } /** Represents a Pulley drawer position. - Collapsed: When the drawer is in its smallest form, at the bottom of the screen. - PartiallyRevealed: When the drawer is partially revealed. - Open: When the drawer is fully open. */ public enum PulleyPosition { case Collapsed case PartiallyRevealed case Open } private let kPulleyDefaultCollapsedHeight: CGFloat = 68.0 private let kPulleyDefaultPartialRevealHeight: CGFloat = 264.0 public class PulleyViewController: UIViewController, UIScrollViewDelegate, PulleyPassthroughScrollViewDelegate { // Interface Builder /// When using with Interface Builder only! Connect a containing view to this outlet. @IBOutlet var primaryContentContainerView: UIView! /// When using with Interface Builder only! Connect a containing view to this outlet. @IBOutlet var drawerContentContainerView: UIView! // Internal private let primaryContentContainer: UIView = UIView() private let drawerContentContainer: UIView = UIView() private let drawerShadowView: UIView = UIView() private let drawerScrollView: PulleyPassthroughScrollView = PulleyPassthroughScrollView() private let backgroundDimmingView: UIView = UIView() private var dimmingViewTapRecognizer: UITapGestureRecognizer? /// The current content view controller (shown behind the drawer). private(set) var primaryContentViewController: UIViewController! { willSet { guard let controller = primaryContentViewController else { return; } controller.view.removeFromSuperview() controller.removeFromParentViewController() } didSet { guard let controller = primaryContentViewController else { return; } controller.view.translatesAutoresizingMaskIntoConstraints = true self.primaryContentContainer.addSubview(controller.view) self.addChildViewController(controller) if self.isViewLoaded() { self.view.setNeedsLayout() } } } /// The current drawer view controller (shown in the drawer). private(set) var drawerContentViewController: UIViewController! { willSet { guard let controller = drawerContentViewController else { return; } controller.view.removeFromSuperview() controller.removeFromParentViewController() } didSet { guard let controller = drawerContentViewController else { return; } controller.view.translatesAutoresizingMaskIntoConstraints = true self.drawerContentContainer.addSubview(controller.view) self.addChildViewController(controller) if self.isViewLoaded() { self.view.setNeedsLayout() } } } /// The content view controller and drawer controller can receive delegate events already. This lets another object observe the changes, if needed. public weak var delegate: PulleyDelegate? /// The current position of the drawer. public private(set) var drawerPosition: PulleyPosition = .Collapsed /// The inset from the top of the view controller when fully open. public var topInset: CGFloat = 50.0 { didSet { if self.isViewLoaded() { self.view.setNeedsLayout() } } } /// The corner radius for the drawer. public var drawerCornerRadius: CGFloat = 13.0 { didSet { if self.isViewLoaded() { self.view.setNeedsLayout() } } } /// The opacity of the drawer shadow. public var shadowOpacity: Float = 0.1 { didSet { if self.isViewLoaded() { self.view.setNeedsLayout() } } } /// The radius of the drawer shadow. public var shadowRadius: CGFloat = 3.0 { didSet { if self.isViewLoaded() { self.view.setNeedsLayout() } } } /// The opaque color of the background dimming view. public var backgroundDimmingColor: UIColor = UIColor.blackColor() { didSet { if self.isViewLoaded() { backgroundDimmingView.backgroundColor = backgroundDimmingColor } } } /// The maximum amount of opacity when dimming. public var backgroundDimmingOpacity: CGFloat = 0.5 { didSet { if self.isViewLoaded() { self.scrollViewDidScroll(drawerScrollView) } } } /** Initialize the drawer controller programmtically. - parameter contentViewController: The content view controller. This view controller is shown behind the drawer. - parameter drawerViewController: The view controller to display inside the drawer. - note: The drawer VC is 20pts too tall in order to have some extra space for the bounce animation. Make sure your constraints / content layout take this into account. - returns: A newly created Pulley drawer. */ required public init(contentViewController: UIViewController, drawerViewController: UIViewController) { super.init(nibName: nil, bundle: nil) ({ self.primaryContentViewController = contentViewController self.drawerContentViewController = drawerViewController })() } /** Initialize the drawer controller from Interface Builder. - note: Usage notes: Make 2 container views in Interface Builder and connect their outlets to -primaryContentContainerView and -drawerContentContainerView. Then use embed segues to place your content/drawer view controllers into the appropriate container. - parameter aDecoder: The NSCoder to decode from. - returns: A newly created Pulley drawer. */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func loadView() { super.loadView() // IB Support if primaryContentContainerView != nil { primaryContentContainerView.removeFromSuperview() } if drawerContentContainerView != nil { drawerContentContainerView.removeFromSuperview() } // Setup primaryContentContainer.backgroundColor = UIColor.whiteColor() drawerScrollView.bounces = false drawerScrollView.delegate = self drawerScrollView.clipsToBounds = false drawerScrollView.showsVerticalScrollIndicator = false drawerScrollView.showsHorizontalScrollIndicator = false drawerScrollView.delaysContentTouches = true drawerScrollView.canCancelContentTouches = true drawerScrollView.backgroundColor = UIColor.clearColor() drawerScrollView.decelerationRate = UIScrollViewDecelerationRateFast drawerScrollView.touchDelegate = self drawerShadowView.layer.shadowOpacity = shadowOpacity drawerShadowView.layer.shadowRadius = shadowRadius drawerShadowView.backgroundColor = UIColor.clearColor() drawerContentContainer.backgroundColor = UIColor.clearColor() backgroundDimmingView.backgroundColor = backgroundDimmingColor backgroundDimmingView.userInteractionEnabled = false backgroundDimmingView.alpha = 0.0 dimmingViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(PulleyViewController.dimmingViewTapRecognizer(_:))) backgroundDimmingView.addGestureRecognizer(dimmingViewTapRecognizer!) drawerScrollView.addSubview(drawerShadowView) drawerScrollView.addSubview(drawerContentContainer) primaryContentContainer.backgroundColor = UIColor.whiteColor() self.view.backgroundColor = UIColor.whiteColor() self.view.addSubview(primaryContentContainer) self.view.addSubview(backgroundDimmingView) self.view.addSubview(drawerScrollView) } public override func viewDidLoad() { super.viewDidLoad() // IB Support if primaryContentViewController == nil || drawerContentViewController == nil { assert(primaryContentContainerView != nil && drawerContentContainerView != nil, "When instantiating from Interface Builder you must provide container views with an embedded view controller.") // Locate main content VC for child in self.childViewControllers { if child.view == primaryContentContainerView.subviews.first { primaryContentViewController = child } if child.view == drawerContentContainerView.subviews.first { drawerContentViewController = child } } assert(primaryContentViewController != nil && drawerContentViewController != nil, "Container views must contain an embedded view controller.") } scrollViewDidScroll(drawerScrollView) } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Layout main content primaryContentContainer.frame = self.view.bounds backgroundDimmingView.frame = self.view.bounds // Layout scrollview drawerScrollView.frame = CGRect(x: 0, y: topInset, width: self.view.bounds.width, height: self.view.bounds.height - topInset) // Layout container var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } let lowestStop = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight].minElement() ?? 0 let bounceOverflowMargin: CGFloat = 20.0 drawerContentContainer.frame = CGRect(x: 0, y: drawerScrollView.bounds.height - lowestStop, width: drawerScrollView.bounds.width, height: drawerScrollView.bounds.height + bounceOverflowMargin) drawerShadowView.frame = drawerContentContainer.frame drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: (drawerScrollView.bounds.height - lowestStop) + drawerScrollView.bounds.height) // Update rounding mask and shadows let borderPath = UIBezierPath(roundedRect: drawerContentContainer.bounds, byRoundingCorners: [.TopLeft, .TopRight], cornerRadii: CGSize(width: drawerCornerRadius, height: drawerCornerRadius)).CGPath let cardMaskLayer = CAShapeLayer() cardMaskLayer.path = borderPath cardMaskLayer.fillColor = UIColor.whiteColor().CGColor cardMaskLayer.backgroundColor = UIColor.clearColor().CGColor drawerContentContainer.layer.mask = cardMaskLayer drawerShadowView.layer.shadowPath = borderPath // Make VC views match frames primaryContentViewController.view.frame = primaryContentContainer.bounds drawerContentViewController.view.frame = CGRect(x: drawerContentContainer.bounds.minX, y: drawerContentContainer.bounds.minY, width: drawerContentContainer.bounds.width, height: drawerContentContainer.bounds.height) } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Configuration Updates /** Set the drawer position, with an option to animate. - parameter position: The position to set the drawer to. - parameter animated: Whether or not to animate the change. (Default: true) */ public func setDrawerPosition(position: PulleyPosition, animated: Bool = true) { drawerPosition = position var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } let stopToMoveTo: CGFloat switch drawerPosition { case .Collapsed: stopToMoveTo = collapsedHeight case .PartiallyRevealed: stopToMoveTo = partialRevealHeight case .Open: stopToMoveTo = (self.view.bounds.size.height - topInset) } let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight] let lowestStop = drawerStops.minElement() ?? 0 if animated { UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: .CurveEaseInOut, animations: { [weak self] () -> Void in self?.drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false) if let drawer = self { drawer.delegate?.drawerPositionDidChange?(drawer) (drawer.drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer) (drawer.primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer) drawer.view.layoutIfNeeded() } }, completion: nil) } else { drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false) delegate?.drawerPositionDidChange?(self) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(self) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(self) } } /** Change the current primary content view controller (The one behind the drawer) - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. Defaults to true. */ public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true) { if animated { UIView.transitionWithView(primaryContentContainer, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { [weak self] () -> Void in self?.primaryContentViewController = controller }, completion: nil) } else { primaryContentViewController = controller } } /** Change the current drawer content view controller (The one inside the drawer) - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. */ public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true) { if animated { UIView.transitionWithView(drawerContentContainer, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { [weak self] () -> Void in self?.drawerContentViewController = controller self?.setDrawerPosition(self?.drawerPosition ?? .Collapsed, animated: false) }, completion: nil) } else { drawerContentViewController = controller setDrawerPosition(drawerPosition, animated: false) } } // MARK: Actions func dimmingViewTapRecognizer(gestureRecognizer: UITapGestureRecognizer) { if gestureRecognizer == dimmingViewTapRecognizer { if gestureRecognizer.state == .Recognized { self.setDrawerPosition(.Collapsed, animated: true) } } } // MARK: UIScrollViewDelegate private var lastDragTargetContentOffset: CGPoint = CGPoint.zero public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if scrollView == drawerScrollView { // Find the closest anchor point and snap there. var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight] let lowestStop = drawerStops.minElement() ?? 0 let distanceFromBottomOfView = lowestStop + lastDragTargetContentOffset.y var currentClosestStop = lowestStop for currentStop in drawerStops { if abs(currentStop - distanceFromBottomOfView) < abs(currentClosestStop - distanceFromBottomOfView) { currentClosestStop = currentStop } } if abs(Float(currentClosestStop - (self.view.bounds.size.height - topInset))) <= FLT_EPSILON { setDrawerPosition(.Open, animated: true) } else if abs(Float(currentClosestStop - collapsedHeight)) <= FLT_EPSILON { setDrawerPosition(.Collapsed, animated: true) } else { setDrawerPosition(.PartiallyRevealed, animated: true) } } } public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if scrollView == drawerScrollView { lastDragTargetContentOffset = targetContentOffset.memory // Halt intertia targetContentOffset.memory = scrollView.contentOffset } } public func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView == drawerScrollView { var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight] let lowestStop = drawerStops.minElement() ?? 0 if scrollView.contentOffset.y > partialRevealHeight - lowestStop { // Calculate percentage between partial and full reveal let fullRevealHeight = (self.view.bounds.size.height - topInset) let progress = (scrollView.contentOffset.y - (partialRevealHeight - lowestStop)) / (fullRevealHeight - (partialRevealHeight)) delegate?.makeUIAdjustmentsForFullscreen?(progress) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress) backgroundDimmingView.alpha = progress * backgroundDimmingOpacity backgroundDimmingView.userInteractionEnabled = true } else { if backgroundDimmingView.alpha >= 0.001 { backgroundDimmingView.alpha = 0.0 delegate?.makeUIAdjustmentsForFullscreen?(0.0) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(0.0) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(0.0) backgroundDimmingView.userInteractionEnabled = false } } delegate?.drawerChangedDistanceFromBottom?(self, distance: scrollView.contentOffset.y + lowestStop) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(self, distance: scrollView.contentOffset.y + lowestStop) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(self, distance: scrollView.contentOffset.y + lowestStop) } } // MARK: Touch Passthrough ScrollView Delegate func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool { let contentDrawerLocation = drawerContentContainer.frame.origin.y if point.y < contentDrawerLocation { return true } return false } func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView) -> UIView { if drawerPosition == .Open { return backgroundDimmingView } return primaryContentContainer } }
apache-2.0
668d38ebc407d3f541915b782711b341
38.198697
260
0.640061
5.947121
false
false
false
false
noveogroup/planetary-system
Planetary System/Planet.swift
1
2683
// // Planet.swift // Planetary System // // Created by Maxim Zabelin on 17/03/15. // Copyright (c) 2015 Noveo. All rights reserved. // import Foundation import SpriteKit class Planet: CelestialBody { // @public // @internal override var category: Category? { get { if (super.category == nil) { self.category = Category.Planet } return super.category } set { super.category = newValue } } override var name: String? { get { if (super.name == nil) { self.name = Name.Planet.rawValue } return super.name } set { super.name = newValue } } override init() { super.init() self.configurePhysicsBody() } override init(texture: SKTexture!, color: UIColor!, size: CGSize) { assert((size.width == size.height), "Only planets of a round shape are supported.") super.init(texture: texture, color: color, size: size) self.configurePhysicsBody() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) assert((self.size.width == self.size.height), "Only planets of a round shape are supported.") self.configurePhysicsBody() } override func configureGravityField() { let scaleFactor: CGFloat = CGFloat(2) let transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor) let fieldSize = CGSizeApplyAffineTransform(self.size, transform) let fieldStrength = Float( (log10(fieldSize.width) + log10(fieldSize.height)) / CGFloat(2) ) let gravityField: SKFieldNode = SKFieldNode.radialGravityField() gravityField.region = SKRegion(size: fieldSize) if (gravityField.strength > fieldStrength) { gravityField.strength = fieldStrength } self.gravityField = gravityField } // @private private func configurePhysicsBody() { let physicsBody: SKPhysicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2) physicsBody.categoryBitMask = CelestialBody.Category.Planet.rawValue physicsBody.collisionBitMask = CelestialBody.Category.Asteroid.rawValue | CelestialBody.Category.Planet.rawValue physicsBody.contactTestBitMask = CelestialBody.Category.Asteroid.rawValue | CelestialBody.Category.Planet.rawValue physicsBody.mass = CGFloat.max physicsBody.dynamic = false self.physicsBody = physicsBody } }
mit
44e9945fa079c4b3a31bfbdcef767073
25.564356
76
0.603802
4.666087
false
false
false
false
grandiere/box
box/Model/Help/Energy/MHelpEnergyIntro.swift
1
1357
import UIKit class MHelpEnergyIntro:MHelpProtocol { private let attributedString:NSAttributedString init() { let attributesTitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:20), NSForegroundColorAttributeName:UIColor.white] let attributesDescription:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:18), NSForegroundColorAttributeName:UIColor(white:1, alpha:0.8)] let stringTitle:NSAttributedString = NSAttributedString( string:NSLocalizedString("MHelpEnergyIntro_title", comment:""), attributes:attributesTitle) let stringDescription:NSAttributedString = NSAttributedString( string:NSLocalizedString("MHelpEnergyIntro_description", comment:""), attributes:attributesDescription) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringTitle) mutableString.append(stringDescription) attributedString = mutableString } var message:NSAttributedString { get { return attributedString } } var image:UIImage { get { return #imageLiteral(resourceName: "assetHelpEnergyIntro") } } }
mit
cc2f83e5f29ef44e03512301c048fa6f
29.840909
81
0.649963
6.031111
false
false
false
false
DianQK/rx-sample-code
Stopwatch/Cell+Rx.swift
1
1692
// // Cell+Rx.swift // Expandable // // Created by DianQK on 8/17/16. // Copyright © 2016 T. All rights reserved. // //import UIKit //import RxSwift //import RxCocoa //extension Reactive where Base: UITableViewCell { // public var prepareForReuse: Observable<Void> { // return Observable.of((base as UITableViewCell).rx.sentMessage(#selector(UITableViewCell.prepareForReuse)).map { _ in }, (base as UITableViewCell).rx.deallocated).merge() // } // // public var prepareForReuseBag: DisposeBag { // return base._rx_prepareForReuseBag // } //} //extension UITableViewCell { // // private struct AssociatedKeys { // static var _disposeBag: Void = () // } // // fileprivate var _rx_prepareForReuse: Observable<Void> { // return Observable.of(self.rx.sentMessage(#selector(UITableViewCell.prepareForReuse)).map { _ in () }, self.rx.deallocated).merge() // } // // fileprivate var _rx_prepareForReuseBag: DisposeBag { // MainScheduler.ensureExecutingOnScheduler() // // if let bag = objc_getAssociatedObject(self, &AssociatedKeys._disposeBag) as? DisposeBag { // return bag // } // // let bag = DisposeBag() // objc_setAssociatedObject(self, &AssociatedKeys._disposeBag, bag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) // // _ = self.rx.sentMessage(#selector(UITableViewCell.prepareForReuse)) // .subscribe(onNext: { [weak self] _ in // let newBag = DisposeBag() // objc_setAssociatedObject(self, &AssociatedKeys._disposeBag, newBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) // }) // // return bag // } //}
mit
1cd792949600008ab04fe3e5d6d6aad1
31.519231
179
0.645772
4.084541
false
false
false
false
VivaReal/Compose
Example/Compose_Example/Classes/Modules/DetailExample/DetailView.swift
1
1502
// // DetailView.swift // Compose_Example // // Created by Bruno Bilescky on 25/10/16. // Copyright © 2016 VivaReal. All rights reserved. // import UIKit import Compose @IBDesignable class DetailView: CollectionStackView { var viewState = DetailViewState() { didSet { self.container.state = ComposeDetailView(with: viewState, expandCallback: self.expandDescription) } } private func expandDescription() { viewState.descriptionExpanded = true } } func ComposeDetailView(with state: DetailViewState, expandCallback:@escaping (()-> Void))-> [ComposingUnit] { var units: [ComposingUnit] = [] units.add { let header = DetailViewUnits.HeaderUnit() let detailUnit = DetailViewUnits.DetailInfoUnit(with: state) let photos = DetailViewUnits.PhotosUnit(colors: state.photos) return [header, detailUnit, photos] } units.add(manyIfLet: state.description) { text in let header = DetailViewUnits.HeaderDescriptionUnit(header: "Descrição do imóvel") let description = DetailViewUnits.DescriptionUnit(text: text, expanded: state.descriptionExpanded) return [header, description] } units.add(if: state.description != nil && !state.descriptionExpanded) { let expand = DetailViewUnits.ExpandDescriptionUnit(callback: expandCallback) return expand } units.append(DetailViewUnits.SpacerUnit(id: "bottom-spacer", height: 40)) return units }
mit
cb5682df60b9ffa76296756d07ab7b5e
30.87234
109
0.690921
4.267806
false
false
false
false
fmscode/JSONtoFoundation
JSONtoFoundation/PreferencesView.swift
1
1320
// // PreferencesView.swift // JSONtoFoundation // // Created by Frank Michael on 12/28/14. // Copyright (c) 2014 Frank Michael Sanchez. All rights reserved. // import Cocoa class PreferencesView: NSWindowController { let nameKey = "fullName" let fileTypeKey = "fileType" @IBOutlet weak var fullNameField: NSTextField! @IBOutlet weak var fileTypeSeg: NSSegmentedControl! override func windowDidLoad() { super.windowDidLoad() if let fullName = NSUserDefaults.standardUserDefaults().objectForKey(self.nameKey) as? String { self.fullNameField.stringValue = fullName } if let fileType = NSUserDefaults.standardUserDefaults().objectForKey(self.fileTypeKey) as? Int { self.fileTypeSeg.selectedSegment = fileType } } @IBAction func saveSettings(sender: AnyObject) { NSUserDefaults.standardUserDefaults().setObject(self.fullNameField.stringValue, forKey: self.nameKey) NSUserDefaults.standardUserDefaults().setObject(self.fileTypeSeg.selectedSegment, forKey: self.fileTypeKey) NSUserDefaults.standardUserDefaults().synchronize() self.closeSettings(sender) } @IBAction func closeSettings(sender: AnyObject) { self.window!.sheetParent!.endSheet(self.window!) } }
mit
bef1819613accee8f40d8c32942e5158
32.846154
115
0.703788
4.888889
false
false
false
false
kbot/imoji-ios-sdk-ui
Examples/Artmoji/artmoji/IMColorSlider.swift
1
5058
// // ImojiSDKUI // // Created by Alex Hoang // Copyright (C) 2015 Imoji // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // import UIKit public class IMColorSlider: UISlider { private var colorView: UIImageView! public var vertical: Bool convenience public init() { self.init(frame: CGRectZero) } override public init(frame: CGRect) { vertical = false super.init(frame: frame) minimumValue = 0 maximumValue = 1.0 setMinimumTrackImage(UIImage(), forState: UIControlState.Normal) setMaximumTrackImage(UIImage(), forState: UIControlState.Normal) UIGraphicsBeginImageContextWithOptions(CGSizeMake(30,30), false, 0) UIColor.clearColor().setFill() UIRectFill(CGRectMake(0,0,1,1)) let blankImg = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() setThumbImage(blankImg, forState: .Normal) colorView = UIImageView() addSubview(colorView) colorView.mas_makeConstraints { make in make.edges.equalTo()(self) } } required public init?(coder aDecoder: NSCoder) { vertical = false super.init(coder: aDecoder) minimumValue = 0 maximumValue = 1.0 setMinimumTrackImage(UIImage(), forState: UIControlState.Normal) setMaximumTrackImage(UIImage(), forState: UIControlState.Normal) UIGraphicsBeginImageContextWithOptions(CGSizeMake(30,30), false, 0) UIColor.clearColor().setFill() UIRectFill(CGRectMake(0,0,1,1)) let blankImg = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() setThumbImage(blankImg, forState: .Normal) colorView = UIImageView() addSubview(colorView) colorView.mas_makeConstraints { make in make.edges.equalTo()(self) } } override public func drawRect(rect: CGRect) { super.drawRect(rect) UIGraphicsBeginImageContext(colorView.frame.size) let context = UIGraphicsGetCurrentContext() colorView.image?.drawInRect(CGRect(x: 0, y: 0, width: colorView.frame.size.width, height: colorView.frame.size.height)) for i in 0...Int(IMArtmojiConstants.SliderWidth) { CGContextMoveToPoint(context, CGFloat(i), frame.size.height / 2.0) CGContextAddLineToPoint(context, CGFloat(i), frame.size.height / 2.0) CGContextSetLineCap(context, CGLineCap.Round) CGContextSetLineWidth(context, 8.0) CGContextSetStrokeColorWithColor(context, UIColor(hue: CGFloat(i) / IMArtmojiConstants.SliderWidth, saturation: 1.0, brightness: 1.0, alpha: 1.0).CGColor) CGContextSetBlendMode(context, CGBlendMode.Normal) CGContextStrokePath(context) } colorView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if vertical { transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) } let outerLayer = CAGradientLayer() outerLayer.frame = UIEdgeInsetsInsetRect(colorView.bounds, UIEdgeInsetsMake(8, -3, 7, -3)) colorView.layer.insertSublayer(outerLayer, atIndex: 0) outerLayer.cornerRadius = 3.0 outerLayer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8).CGColor outerLayer.borderWidth = 1.0 let innerLayer = CAGradientLayer() innerLayer.frame = UIEdgeInsetsInsetRect(colorView.bounds, UIEdgeInsetsMake(9, -2, 8, -2)) colorView.layer.insertSublayer(innerLayer, atIndex: 1) innerLayer.cornerRadius = 3.0 innerLayer.borderColor = UIColor.whiteColor().CGColor innerLayer.borderWidth = 2.0 } override public func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { super.beginTrackingWithTouch(touch, withEvent: event) sendActionsForControlEvents(UIControlEvents.ValueChanged) return true } }
mit
9836a7f0bed592ddbbaa61c415833271
37.610687
166
0.689798
4.785241
false
false
false
false