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
belkhadir/Beloved
Beloved/FriendSearchViewController.swift
1
8707
// // FriendSearchViewController.swift // Beloved // // Created by Anas Belkhadir on 21/01/2016. // Copyright © 2016 Anas Belkhadir. All rights reserved. // import UIKit import CoreData class FriendSearchViewController: UITableViewController{ @IBOutlet weak var activityIndicator: UIActivityIndicatorView! let searchController = UISearchController(searchResultsController: nil) var friendUsers = [Friend]() var currentUser: CurrentUserConnected? //it's make easy to know fetchAllFriendFromFirebase function start getting data from the server var startGettingFriendFromFirebase: Bool = false { didSet { if startGettingFriendFromFirebase { activityIndicator.startAnimating() activityIndicator.hidden = false }else{ activityIndicator.stopAnimating() activityIndicator.hidden = true } } } override func viewDidLoad() { super.viewDidLoad() self.activityIndicator.hidden = true self.activityIndicator.stopAnimating() navigationController?.navigationBar.topItem?.title = "Logout" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .Plain, target: self, action: "logOut:") tableView.tableHeaderView = searchController.searchBar searchController.searchBar.delegate = self friendUsers = fetchedAllFriend() //if ther's no friend saved in CoreData look at his friend on the server if friendUsers.count == 0 { fetchAllFriendFromFirebase() } } //fetch all friend from the server func fetchAllFriendFromFirebase() { //Mark- start getting data from server startGettingFriendFromFirebase = true FirebaseHelper.sharedInstance().getAllCurrentUserFirends({ userIdKey in for element in self.friendUsers { if element.uid == userIdKey! { self.startGettingFriendFromFirebase = false return } } FirebaseHelper.sharedInstance().getSingleUser(userIdKey!, completionHandler: { (error, userFriend) in guard error == nil else{ self.startGettingFriendFromFirebase = false self.showAlert(.custom("erro occur", error!)) return } //The user friend was picked from the server //we need to make a new Friend. To be easy to save in CoreData //The easiest way to do that is to make a dictionary. let dictionary: [String : AnyObject] = [ Friend.Keys.username: userFriend!.userName!, Friend.Keys.uid: userIdKey!, ] // Insert the Friend on the main thread dispatch_async(dispatch_get_main_queue(), { //Init - Friend user let friendToBeAdd = Friend(parameter: dictionary, context: self.sharedContext) friendToBeAdd.currentUser = CurrentUser.sharedInstance().currentUserConnected! self.friendUsers.append(friendToBeAdd) self.tableView.reloadData() self.startGettingFriendFromFirebase = false //Save in the context CoreDataStackManager.sharedInstance().saveContext() }) }) }) startGettingFriendFromFirebase = false //Mark- finishing getting data from server } var sharedContext: NSManagedObjectContext { return CoreDataStackManager.sharedInstance().managedObjectContext } //fetch all friend from the CoreData func fetchedAllFriend() -> [Friend] { let fetchedRequest = NSFetchRequest(entityName: "Friend") let predicate = NSPredicate(format: "currentUser = %@", CurrentUser.sharedInstance().currentUserConnected!) fetchedRequest.predicate = predicate do { return try sharedContext.executeFetchRequest(fetchedRequest) as! [Friend] }catch _ { return [Friend]() } } func logOut() { FirebaseHelper.sharedInstance().messageRef.removeAllObservers() FirebaseHelper.sharedInstance().userRef.removeAllObservers() FirebaseHelper.sharedInstance().ref.unauth() //using presentViewController instead of pushViewController because: //when the first time user singUp and try to logout it's showing the //previews task . let nvg = storyboard?.instantiateViewControllerWithIdentifier("singInViewController") as! SingInViewController navigationController?.presentViewController(nvg, animated: true, completion: nil) } // MARK: - Table View override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return friendUsers.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userCell") as! FriendSearchTableViewCell cell.user = friendUsers[indexPath.row] cell.delegate = self return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedUser = friendUsers[indexPath.row] let listOfMessageVC = self.storyboard?.instantiateViewControllerWithIdentifier("StartchattingViewController") as! StartChattingViewController listOfMessageVC.friend = selectedUser listOfMessageVC.senderId = CurrentUser.sharedInstance().user?.userName dispatch_async(dispatch_get_main_queue(), { self.navigationController?.pushViewController(listOfMessageVC, animated: true) }) } } extension FriendSearchViewController: FriendSearchTableViewCellDelegate { func cell(cell: FriendSearchTableViewCell, didSelectFriendUser user: Friend) { FirebaseHelper.sharedInstance().canBecomeFirend(user.uid!, willAccept: true, willBecomeFriend: { (_,_) in }) } func cell(cell: FriendSearchTableViewCell, didSelectUnFriendUser user: Friend){ FirebaseHelper.sharedInstance().canBecomeFirend(user.uid!, willAccept: false, willBecomeFriend:{ _,_ in }) } } extension FriendSearchViewController: UISearchBarDelegate{ func searchBarSearchButtonClicked(searchBar: UISearchBar) { if !isConnectedToNetwork() { showAlert(.connectivity) return } activityIndicator.startAnimating() activityIndicator.hidden = false let lowercaseSearchBarText = searchBar.text?.lowercaseString // Check to see if we already have this friend . If so , return if let _ = friendUsers.indexOf({$0.username == lowercaseSearchBarText}) { return } FirebaseHelper.sharedInstance().searchByUserName(lowercaseSearchBarText!, didPickUser: { (exist, user) in if exist { // Insert the Friend on the main thread dispatch_async(dispatch_get_main_queue()) { //init the friend user let userFriend = Friend(parameter: user!, context: self.sharedContext) //Mark - relation userFriend.currentUser = CurrentUser.sharedInstance().currentUserConnected! // append friendUser to array self.friendUsers.insert(userFriend, atIndex: 0) self.tableView.reloadData() // Save the context. do { try self.sharedContext.save() } catch _ {} } } self.activityIndicator.hidden = true self.activityIndicator.stopAnimating() }) } }
mit
e23819d53639c9d0d8145cd8254cff57
30.773723
149
0.583735
6.11806
false
false
false
false
shuoli84/RxSwift
RxSwift/RxSwift/Observables/Observable+Single.swift
15
4400
// // Observable+Single.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // as observable public func asObservable<E> (source: Observable<E>) -> Observable<E> { if let asObservable = source as? AsObservable<E> { return asObservable.omega() } else { return AsObservable(source: source) } } // distinct until changed public func distinctUntilChangedOrDie<E: Equatable>(source: Observable<E>) -> Observable<E> { return distinctUntilChangedOrDie({ success($0) }, { success($0 == $1) })(source) } public func distinctUntilChangedOrDie<E, K: Equatable> (keySelector: (E) -> RxResult<K>) -> (Observable<E> -> Observable<E>) { return { source in return distinctUntilChangedOrDie(keySelector, { success($0 == $1) })(source) } } public func distinctUntilChangedOrDie<E> (comparer: (lhs: E, rhs: E) -> RxResult<Bool>) -> (Observable<E> -> Observable<E>) { return { source in return distinctUntilChangedOrDie({ success($0) }, comparer)(source) } } public func distinctUntilChangedOrDie<E, K> (keySelector: (E) -> RxResult<K>, comparer: (lhs: K, rhs: K) -> RxResult<Bool>) -> (Observable<E> -> Observable<E>) { return { source in return DistinctUntilChanged(source: source, selector: keySelector, comparer: comparer) } } public func distinctUntilChanged<E: Equatable>(source: Observable<E>) -> Observable<E> { return distinctUntilChanged({ $0 }, { ($0 == $1) })(source) } public func distinctUntilChanged<E, K: Equatable> (keySelector: (E) -> K) -> (Observable<E> -> Observable<E>) { return { source in return distinctUntilChanged(keySelector, { ($0 == $1) })(source) } } public func distinctUntilChanged<E> (comparer: (lhs: E, rhs: E) -> Bool) -> (Observable<E> -> Observable<E>) { return { source in return distinctUntilChanged({ ($0) }, comparer)(source) } } public func distinctUntilChanged<E, K> (keySelector: (E) -> K, comparer: (lhs: K, rhs: K) -> Bool) -> (Observable<E> -> Observable<E>) { return { source in return DistinctUntilChanged(source: source, selector: {success(keySelector($0)) }, comparer: { success(comparer(lhs: $0, rhs: $1))}) } } // do public func doOrDie<E> (eventHandler: (Event<E>) -> RxResult<Void>) -> (Observable<E> -> Observable<E>) { return { source in return Do(source: source, eventHandler: eventHandler) } } public func `do`<E> (eventHandler: (Event<E>) -> Void) -> (Observable<E> -> Observable<E>) { return { source in return Do(source: source, eventHandler: { success(eventHandler($0)) }) } } // doOnNext public func doOnNext<E> (actionOnNext: E -> Void) -> (Observable<E> -> Observable<E>) { return { source in return source >- `do` { event in switch event { case .Next(let boxedValue): let value = boxedValue.value actionOnNext(value) default: break } } } } // startWith // Prefixes observable sequence with `firstElement` element. // The same functionality could be achieved using `concat([returnElement(prefix), source])`, // but this is significantly more efficient implementation. public func startWith<E> (firstElement: E) -> (Observable<E> -> Observable<E>) { return { source in return StartWith(source: source, element: firstElement) } } // retry public func retry<E> (source: Observable<E>) -> Observable<E> { return SequenceOf(InifiniteSequence(repeatedValue: source)) >- catch } public func retry<E> (retryCount: Int) -> Observable<E> -> Observable<E> { return { source in return SequenceOf(Repeat(count: retryCount, repeatedValue: source)) >- catch } } // scan public func scan<E, A> (seed: A, accumulator: (A, E) -> A) -> Observable<E> -> Observable<A> { return { source in return Scan(source: source, seed: seed, accumulator: { success(accumulator($0, $1)) }) } } public func scanOrDie<E, A> (seed: A, accumulator: (A, E) -> RxResult<A>) -> Observable<E> -> Observable<A> { return { source in return Scan(source: source, seed: seed, accumulator: accumulator) } }
mit
43add717272775e5dcc21eebc8d2ccf4
25.835366
140
0.619318
3.793103
false
false
false
false
tjw/swift
test/IRGen/sil_witness_tables.swift
1
3946
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module -o %t %S/sil_witness_tables_external_conformance.swift // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -I %t -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 import sil_witness_tables_external_conformance // FIXME: This should be a SIL test, but we can't parse sil_witness_tables // yet. protocol A {} protocol P { associatedtype Assoc: A static func staticMethod() func instanceMethod() } protocol Q : P { func qMethod() } protocol QQ { func qMethod() } struct AssocConformer: A {} struct Conformer: Q, QQ { typealias Assoc = AssocConformer static func staticMethod() {} func instanceMethod() {} func qMethod() {} } // CHECK: [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE:@"\$S39sil_witness_tables_external_conformance17ExternalConformerVAA0F1PAAWP"]] = external global i8*, align 8 // CHECK: [[CONFORMER_Q_WITNESS_TABLE:@"\$S18sil_witness_tables9ConformerVAA1QAAWP"]] = hidden constant [3 x i8*] [ // CHECK: i8* bitcast ([5 x i8*]* [[CONFORMER_P_WITNESS_TABLE:@"\$S18sil_witness_tables9ConformerVAA1PAAWP"]] to i8*), // CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @"$S18sil_witness_tables9ConformerVAA1QA2aDP7qMethod{{[_0-9a-zA-Z]*}}FTW" to i8*) // CHECK: ] // CHECK: [[CONFORMER_P_WITNESS_TABLE]] = hidden constant [5 x i8*] [ // CHECK: i8* bitcast (%swift.metadata_response (i64)* @"$S18sil_witness_tables14AssocConformerVMa" to i8*), // CHECK: i8* bitcast (i8** ()* @"$S18sil_witness_tables14AssocConformerVAA1AAAWa" to i8*) // CHECK: i8* bitcast (void (%swift.type*, %swift.type*, i8**)* @"$S18sil_witness_tables9ConformerVAA1PA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW" to i8*), // CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @"$S18sil_witness_tables9ConformerVAA1PA2aDP14instanceMethod{{[_0-9a-zA-Z]*}}FTW" to i8*) // CHECK: ] // CHECK: [[CONFORMER2_P_WITNESS_TABLE:@"\$S18sil_witness_tables10Conformer2VAA1PAAWP"]] = hidden constant [5 x i8*] struct Conformer2: Q { typealias Assoc = AssocConformer static func staticMethod() {} func instanceMethod() {} func qMethod() {} } // CHECK-LABEL: define hidden swiftcc void @"$S18sil_witness_tables7erasure1cAA2QQ_pAA9ConformerV_tF"(%T18sil_witness_tables2QQP* noalias nocapture sret) // CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T18sil_witness_tables2QQP, %T18sil_witness_tables2QQP* %0, i32 0, i32 2 // CHECK-NEXT: store i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@"\$S.*WP"]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8 func erasure(c: Conformer) -> QQ { return c } // CHECK-LABEL: define hidden swiftcc void @"$S18sil_witness_tables15externalErasure1c0a1_b1_c1_D12_conformance9ExternalP_pAD0G9ConformerV_tF"(%T39sil_witness_tables_external_conformance9ExternalPP* noalias nocapture sret) // CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T39sil_witness_tables_external_conformance9ExternalPP, %T39sil_witness_tables_external_conformance9ExternalPP* %0, i32 0, i32 2 // CHECK-NEXT: store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8 func externalErasure(c: ExternalConformer) -> ExternalP { return c } // FIXME: why do these have different linkages? // CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$S18sil_witness_tables14AssocConformerVMa"(i64) // CHECK: ret %swift.metadata_response { %swift.type* bitcast (i64* getelementptr inbounds {{.*}} @"$S18sil_witness_tables14AssocConformerVMf", i32 0, i32 1) to %swift.type*), i64 0 } // CHECK-LABEL: define hidden i8** @"$S18sil_witness_tables9ConformerVAA1PAAWa"() // CHECK: ret i8** getelementptr inbounds ([5 x i8*], [5 x i8*]* @"$S18sil_witness_tables9ConformerVAA1PAAWP", i32 0, i32 0)
apache-2.0
fc677683304079b21b8ef9fae6dc4943
48.325
222
0.713127
3.215974
false
false
false
false
kentya6/Fuwari
Fuwari/PreferencesWindowController.swift
1
3491
// // PreferencesWindowController.swift // Fuwari // // Created by Kengo Yokoyama on 2016/12/11. // Copyright © 2016年 AppKnop. All rights reserved. // import Cocoa class PreferencesWindowController: NSWindowController { static let shared = PreferencesWindowController(windowNibName: "PreferencesWindowController") @IBOutlet private weak var toolBar: NSView! @IBOutlet private weak var generalImageView: NSImageView! @IBOutlet private weak var shortcutImageView: NSImageView! @IBOutlet private weak var generalTextField: NSTextField! @IBOutlet private weak var shortcutTextField: NSTextField! @IBOutlet private weak var generalButton: NSButton! @IBOutlet private weak var shortcutButton: NSButton! private let defaults = UserDefaults.standard private let viewController = [GeneralPreferenceViewController(nibName: "GeneralPreferenceViewController", bundle: nil), ShortcutsPreferenceViewController(nibName: "ShortcutsPreferenceViewController", bundle: nil)] override func windowDidLoad() { super.windowDidLoad() window?.collectionBehavior = .canJoinAllSpaces if #available(OSX 10.10, *) { window?.titlebarAppearsTransparent = true } toolBarItemTapped(generalButton) generalButton.sendAction(on: .leftMouseDown) shortcutButton.sendAction(on: .leftMouseDown) } override func showWindow(_ sender: Any?) { super.showWindow(sender) window?.makeKeyAndOrderFront(self) } @IBAction private func toolBarItemTapped(_ sender: NSButton) { selectedTab(sender.tag) switchView(sender.tag) } } extension PreferencesWindowController: NSWindowDelegate { func windowWillClose(_ notification: Notification) { if let window = window, !window.makeFirstResponder(window) { window.endEditing(for: nil) } NSApp.deactivate() } } // MARK: - Layout private extension PreferencesWindowController { private func resetImages() { generalImageView.image = NSImage(named: Constants.ImageName.generalOff) shortcutImageView.image = NSImage(named: Constants.ImageName.shortcutOff) generalTextField.textColor = .tabTitle shortcutTextField.textColor = .tabTitle } func selectedTab(_ index: Int) { resetImages() switch index { case 0: generalImageView.image = NSImage(named: Constants.ImageName.generalOn) generalTextField.textColor = .main case 1: shortcutImageView.image = NSImage(named: Constants.ImageName.shortcutOn) shortcutTextField.textColor = .main default: break } } func switchView(_ index: Int) { let newView = viewController[index].view // Remove current views without toolbar window?.contentView?.subviews.forEach { view in if view != toolBar { view.removeFromSuperview() } } // Resize view let frame = window!.frame var newFrame = window!.frameRect(forContentRect: newView.frame) newFrame.origin = frame.origin newFrame.origin.y += frame.height - newFrame.height - toolBar.frame.height newFrame.size.height += toolBar.frame.height window?.setFrame(newFrame, display: true) window?.contentView?.addSubview(newView) } }
mit
348119f885cdcdcf51dbe0c054d66b8a
34.232323
131
0.667718
5.182764
false
false
false
false
Acidburn0zzz/firefox-ios
WidgetKit/OpenTabs/OpenTabsWidget.swift
1
4563
/* 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 SwiftUI import WidgetKit import UIKit import Combine struct OpenTabsWidget: Widget { private let kind: String = "Quick View" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: TabProvider()) { entry in OpenTabsView(entry: entry) } .supportedFamilies([.systemMedium, .systemLarge]) .configurationDisplayName(String.QuickViewGalleryTitle) .description(String.QuickViewGalleryDescriptionV2) } } struct OpenTabsView: View { let entry: OpenTabsEntry @Environment(\.widgetFamily) var widgetFamily @ViewBuilder func lineItemForTab(_ tab: SimpleTab) -> some View { let query = widgetFamily == .systemMedium ? "widget-tabs-medium-open-url" : "widget-tabs-large-open-url" VStack(alignment: .leading) { Link(destination: linkToContainingApp("?uuid=\(tab.uuid)", query: query)) { HStack(alignment: .center, spacing: 15) { if (entry.favicons[tab.imageKey] != nil) { (entry.favicons[tab.imageKey])!.resizable().frame(width: 16, height: 16) } else { Image("placeholderFavicon") .foregroundColor(Color.white) .frame(width: 16, height: 16) } Text(tab.title!) .foregroundColor(Color.white) .multilineTextAlignment(.leading) .lineLimit(1) .font(.system(size: 15, weight: .regular, design: .default)) }.padding(.horizontal) } Rectangle() .fill(Color(UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 0.3))) .frame(height: 0.5) .padding(.leading, 45) } } var openFirefoxButton: some View { HStack(alignment: .center, spacing: 15) { Image("openFirefox").foregroundColor(Color.white) Text("Open Firefox").foregroundColor(Color.white).lineLimit(1).font(.system(size: 13, weight: .semibold, design: .default)) Spacer() }.padding([.horizontal]) } var numberOfTabsToDisplay: Int { if widgetFamily == .systemMedium { return 3 } else { return 8 } } var body: some View { Group { if entry.tabs.isEmpty { VStack { Text(String.NoOpenTabsLabel) HStack { Spacer() Image("openFirefox") Text(String.OpenFirefoxLabel).foregroundColor(Color.white).lineLimit(1).font(.system(size: 13, weight: .semibold, design: .default)) Spacer() }.padding(10) }.foregroundColor(Color.white) } else { VStack(spacing: 8) { ForEach(entry.tabs.suffix(numberOfTabsToDisplay), id: \.self) { tab in lineItemForTab(tab) } if (entry.tabs.count > numberOfTabsToDisplay) { HStack(alignment: .center, spacing: 15) { Image("openFirefox").foregroundColor(Color.white).frame(width: 16, height: 16) Text(String.localizedStringWithFormat(String.MoreTabsLabel, (entry.tabs.count - numberOfTabsToDisplay))) .foregroundColor(Color.white).lineLimit(1).font(.system(size: 13, weight: .semibold, design: .default)) Spacer() }.padding([.horizontal]) } else { openFirefoxButton } Spacer() }.padding(.top, 14) } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background((Color(UIColor(red: 0.11, green: 0.11, blue: 0.13, alpha: 1.00)))) } private func linkToContainingApp(_ urlSuffix: String = "", query: String) -> URL { let urlString = "\(scheme)://\(query)\(urlSuffix)" return URL(string: urlString)! } }
mpl-2.0
bf158fdd2d75e4d73b44b1df52f78364
39.026316
156
0.516327
4.823467
false
false
false
false
xedin/swift
stdlib/public/Darwin/Accelerate/vDSP_Interpolation.swift
2
12834
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// extension vDSP { /// Vector linear interpolation between vectors; single-precision. /// /// - Parameter vectorA: The `A` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter vectorB: The `B` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter interpolationConstant: The `C` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Returns: The `D` in `D[n] = A[n] + C * (B[n] - A[n])`. @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) @inlinable public static func linearInterpolate<T, U>(_ vectorA: T, _ vectorB: U, using interpolationConstant: Float) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float{ let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in linearInterpolate(vectorA, vectorB, using: interpolationConstant, result: &buffer) initializedCount = vectorA.count } return result } /// Vector linear interpolation between vectors; single-precision. /// /// - Parameter vectorA: The `A` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter vectorB: The `B` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter interpolationConstant: The `C` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter result: The `D` in `D[n] = A[n] + C * (B[n] - A[n])`. @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) @inlinable public static func linearInterpolate<T, U, V>(_ vectorA: T, _ vectorB: U, using interpolationConstant: Float, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { precondition(vectorA.count == result.count) precondition(vectorB.count == result.count) let n = vDSP_Length(result.count) vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in result.withUnsafeMutableBufferPointer { dest in vDSP_vintb(a.baseAddress!, 1, b.baseAddress!, 1, [interpolationConstant], dest.baseAddress!, 1, n) } } } } /// Vector linear interpolation between vectors; double-precision. /// /// - Parameter vectorA: The `A` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter vectorB: The `B` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter interpolationConstant: The `C` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Returns: The `D` in `D[n] = A[n] + C * (B[n] - A[n])`. @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) @inlinable public static func linearInterpolate<T, U>(_ vectorA: T, _ vectorB: U, using interpolationConstant: Double) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double{ let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) { buffer, initializedCount in linearInterpolate(vectorA, vectorB, using: interpolationConstant, result: &buffer) initializedCount = vectorA.count } return result } /// Vector linear interpolation between vectors; double-precision. /// /// - Parameter vectorA: The `A` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter vectorB: The `B` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter interpolationConstant: The `C` in `D[n] = A[n] + C * (B[n] - A[n])`. /// - Parameter result: The `D` in `D[n] = A[n] + C * (B[n] - A[n])`. @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) @inlinable public static func linearInterpolate<T, U, V>(_ vectorA: T, _ vectorB: U, using interpolationConstant: Double, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { precondition(vectorA.count == result.count) precondition(vectorB.count == result.count) let n = vDSP_Length(result.count) vectorA.withUnsafeBufferPointer { a in vectorB.withUnsafeBufferPointer { b in result.withUnsafeMutableBufferPointer { dest in vDSP_vintbD(a.baseAddress!, 1, b.baseAddress!, 1, [interpolationConstant], dest.baseAddress!, 1, n) } } } } /// Vector linear interpolation between neighboring elements; single-precision. /// /// This function interpolates between the elements of `vector` using the following: /// /// for (n = 0; n < N; ++n) { /// b = trunc(B[n]); /// a = B[n] - b; /// C[n] = A[b] + a * (A[b+1] - A[b]); /// } /// /// Where `A` is the input vector, `B` is the control vector, and /// `C` is the output vector. /// /// - Parameter vector: Input values. /// - Parameter controlVector: Vector that controls interpolation. /// - Returns: Output values. @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) @inlinable public static func linearInterpolate<T, U>(elementsOf vector: T, using controlVector: U) -> [Float] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Float, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: controlVector.count) { buffer, initializedCount in linearInterpolate(elementsOf: vector, using: controlVector, result: &buffer) initializedCount = controlVector.count } return result } /// Vector linear interpolation between neighboring elements; single-precision. /// /// This function interpolates between the elements of `vector` using the following: /// /// for (n = 0; n < N; ++n) { /// b = trunc(B[n]); /// a = B[n] - b; /// C[n] = A[b] + a * (A[b+1] - A[b]); /// } /// /// Where `A` is the input vector, `B` is the control vector, and /// `C` is the output vector. /// /// - Parameter vector: Input values. /// - Parameter controlVector: Vector that controls interpolation. /// - Parameter result: Output values. @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) @inlinable public static func linearInterpolate<T, U, V>(elementsOf vector: T, using controlVector: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Float, U.Element == Float, V.Element == Float { precondition(controlVector.count == result.count) let n = vDSP_Length(result.count) let m = vDSP_Length(vector.count) vector.withUnsafeBufferPointer { a in controlVector.withUnsafeBufferPointer { b in result.withUnsafeMutableBufferPointer { dest in vDSP_vlint(a.baseAddress!, b.baseAddress!, 1, dest.baseAddress!, 1, n, m) } } } } /// Vector linear interpolation between neighboring elements; double-precision. /// /// This function interpolates between the elements of `vector` using the following: /// /// for (n = 0; n < N; ++n) { /// b = trunc(B[n]); /// a = B[n] - b; /// C[n] = A[b] + a * (A[b+1] - A[b]); /// } /// /// Where `A` is the input vector, `B` is the control vector, and /// `C` is the output vector. /// /// - Parameter vector: Input values. /// - Parameter controlVector: Vector that controls interpolation. /// - Returns: Output values. @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) @inlinable public static func linearInterpolate<T, U>(elementsOf vector: T, using controlVector: U) -> [Double] where T: AccelerateBuffer, U: AccelerateBuffer, T.Element == Double, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: controlVector.count) { buffer, initializedCount in linearInterpolate(elementsOf: vector, using: controlVector, result: &buffer) initializedCount = controlVector.count } return result } /// Vector linear interpolation between neighboring elements; double-precision. /// /// This function interpolates between the elements of `vector` using the following: /// /// for (n = 0; n < N; ++n) { /// b = trunc(B[n]); /// a = B[n] - b; /// C[n] = A[b] + a * (A[b+1] - A[b]); /// } /// /// Where `A` is the input vector, `B` is the control vector, and /// `C` is the output vector. /// /// - Parameter vector: Input values. /// - Parameter controlVector: Vector that controls interpolation. /// - Parameter result: Output values. @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) @inlinable public static func linearInterpolate<T, U, V>(elementsOf vector: T, using controlVector: U, result: inout V) where T: AccelerateBuffer, U: AccelerateBuffer, V: AccelerateMutableBuffer, T.Element == Double, U.Element == Double, V.Element == Double { precondition(controlVector.count == result.count) let n = vDSP_Length(result.count) let m = vDSP_Length(vector.count) vector.withUnsafeBufferPointer { a in controlVector.withUnsafeBufferPointer { b in result.withUnsafeMutableBufferPointer { dest in vDSP_vlintD(a.baseAddress!, b.baseAddress!, 1, dest.baseAddress!, 1, n, m) } } } } }
apache-2.0
5c4853072878a38fc1583ca44dfc8a33
40.4
95
0.465093
4.857684
false
false
false
false
poetmountain/MotionMachine
Sources/PhysicsSystem.swift
1
7256
// // PhysicsSystem.swift // MotionMachine // // Created by Brett Walker on 5/16/16. // Copyright © 2016-2018 Poet & Mountain, LLC. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public protocol PhysicsSolving { /** * The velocity value to use in physics calculations. */ var velocity: Double { get set } /** * The friction value to be applied in physics calculations. */ var friction: Double { get set } /** * This method updates 1D positions using physics calculations. * * - parameters: * - positions: The current positions of the physics object being modeled. * - currentTime: The current timestamp. * * - returns: An array of updated positions in the same order as the array passed in. */ func solve(forPositions positions: [Double], timestamp: TimeInterval) -> [Double] /** * This method should reset the physics system to its initial velocity and clear the timestamp used to calculate the current step. */ func reset() /** * This method should pause the physics system, preventing any new calculations. */ func pause() /** * This method should resume the physics system. */ func resume() /** * This method should reverse the direction of the velocity. */ func reverseDirection() } public class PhysicsSystem: PhysicsSolving { // default timestep for accumulator static let TIMESTEP: Double = 0.0001 /** * The velocity value to use in physics calculations. */ public var velocity: Double { get { return _velocity } set(newValue) { _velocity = newValue if (initialVelocity == 0.0 || _velocity != 0.0) { initialVelocity = _velocity } } } private var _velocity: Double = 0.0 /** * The friction value to be applied in physics calculations. */ public var friction: Double { get { return _friction } set(newValue) { // if we allowed 0.0, we'd get divide by zero errors // besides with 0.0 friction our value would sail to the stars with a constant velocity _friction = (newValue > 0.0) ? newValue : 0.000001; _friction = min(1.0, _friction) // pow is used here to compensate for floating point errors over time frictionMultiplier = pow(1 - _friction, PhysicsSystem.TIMESTEP) } } private var _friction: Double = 0.0 public var timestamp: TimeInterval = 0.0 // MARK: Private properties /// The initial velocity value set. Used when resetting the system. private var initialVelocity: Double = 0.0 /// The last timestamp sent via the `solve` method. private var lastTimestamp: TimeInterval = 0.0 /// Boolean value representing whether the physics system is currently paused. private var paused: Bool = false /// Multiplier to apply to velocity for each time step. private var frictionMultiplier: Double = 0.0 // MARK: Initialization /** * Initializer. * * - parameters: * - velocity: The velocity used to calculate new values in physics system. Any values are accepted due to the differing ranges of velocity magnitude required for various motion applications. Experiment to see what suits your needs best. * - friction: The friction used to calculate new values in the physics system. Acceptable values are 0.0 (no friction) to 1.0 (no movement); values outside of this range will be clamped to the nearest edge. */ public init(velocity: Double, friction: Double) { self.velocity = velocity self.friction = friction initialVelocity = velocity } // MARK: PhysicsSolving methods public func solve(forPositions positions: [Double], timestamp: TimeInterval) -> [Double] { var time_delta = timestamp - lastTimestamp time_delta = max(0.0, time_delta) time_delta = min(0.2, time_delta) var new_positions: [Double] = [] if (!paused && time_delta > 0.0) { for position in positions { var new_position = position var previous_position = position if (lastTimestamp > 0.0) { // only run system after first timestamp var accumulator: Double = time_delta while (accumulator >= PhysicsSystem.TIMESTEP) { previous_position = new_position _velocity *= frictionMultiplier // add just the portion of current velocity that occurred during this time delta new_position += (_velocity * PhysicsSystem.TIMESTEP); // decrement the accumulator by the fixed timestep amount accumulator -= PhysicsSystem.TIMESTEP; } // interpolate the remaining time delta to get the final state of position value let blending = accumulator / PhysicsSystem.TIMESTEP; new_position = new_position * blending + (previous_position * (1.0 - blending)); new_positions.append(new_position) } lastTimestamp = timestamp } } return new_positions } public func reset() { _velocity = initialVelocity resume() } public func pause() { paused = true } public func resume() { lastTimestamp = 0.0 paused = false } public func reverseDirection() { initialVelocity *= -1 _velocity *= -1 } }
mit
b6a353bcdbcdc7cde914af1d1d4ab877
33.061033
246
0.588697
5.041696
false
false
false
false
uber/rides-ios-sdk
examples/Swift SDK/Swift SDK/NativeLoginExampleViewController.swift
1
5433
// // NativeLoginExampleViewController.swift // Swift SDK // // Copyright © 2015 Uber Technologies, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import UberCore import UberRides import CoreLocation /// This class provides an example for using the LoginButton to do Native Login (SSO with the Uber App) open class NativeLoginExampleViewController: ButtonExampleViewController, LoginButtonDelegate { let scopes: [UberScope] let loginManager: LoginManager let blackLoginButton: LoginButton let whiteLoginButton: LoginButton override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { scopes = [.profile, .places, .request] loginManager = LoginManager(loginType: .native) blackLoginButton = LoginButton(frame: CGRect.zero, scopes: scopes, loginManager: loginManager) whiteLoginButton = LoginButton(frame: CGRect.zero, scopes: scopes, loginManager: loginManager) whiteLoginButton.colorStyle = .white super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) blackLoginButton.presentingViewController = self whiteLoginButton.presentingViewController = self blackLoginButton.delegate = self whiteLoginButton.delegate = self } public required init?(coder aDecoder: NSCoder) { fatalError("init?(coder aDecoder: NSCoder) is not supported") } override open func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "SSO" topView.addSubview(blackLoginButton) bottomView.addSubview(whiteLoginButton) addBlackLoginButtonConstraints() addWhiteLoginButtonConstraints() } // Mark: Private Interface fileprivate func addBlackLoginButtonConstraints() { blackLoginButton.translatesAutoresizingMaskIntoConstraints = false let centerYConstraint = NSLayoutConstraint(item: blackLoginButton, attribute: .centerY, relatedBy: .equal, toItem: topView, attribute: .centerY, multiplier: 1.0, constant: 0.0) let centerXConstraint = NSLayoutConstraint(item: blackLoginButton, attribute: .centerX, relatedBy: .equal, toItem: topView, attribute: .centerX, multiplier: 1.0, constant: 0.0) let widthConstraint = NSLayoutConstraint(item: blackLoginButton, attribute: .width, relatedBy: .equal, toItem: topView, attribute: .width, multiplier: 1.0, constant: -20.0) topView.addConstraints([centerYConstraint, centerXConstraint, widthConstraint]) } fileprivate func addWhiteLoginButtonConstraints() { whiteLoginButton.translatesAutoresizingMaskIntoConstraints = false let centerYConstraint = NSLayoutConstraint(item: whiteLoginButton, attribute: .centerY, relatedBy: .equal, toItem: bottomView, attribute: .centerY, multiplier: 1.0, constant: 0.0) let centerXConstraint = NSLayoutConstraint(item: whiteLoginButton, attribute: .centerX, relatedBy: .equal, toItem: bottomView, attribute: .centerX, multiplier: 1.0, constant: 0.0) let widthConstraint = NSLayoutConstraint(item: whiteLoginButton, attribute: .width, relatedBy: .equal, toItem: bottomView, attribute: .width, multiplier: 1.0, constant: -20.0) bottomView.addConstraints([centerYConstraint, centerXConstraint, widthConstraint]) } fileprivate func showMessage(_ message: String) { let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.alert) let okayAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil) alert.addAction(okayAction) self.present(alert, animated: true, completion: nil) } // Mark: LoginButtonDelegate open func loginButton(_ button: LoginButton, didLogoutWithSuccess success: Bool) { if success { showMessage("Logout") } } open func loginButton(_ button: LoginButton, didCompleteLoginWithToken accessToken: AccessToken?, error: NSError?) { if let _ = accessToken { showMessage("Saved access token!") } else if let error = error { showMessage(error.localizedDescription) } else { showMessage("Error") } } }
mit
5ded5899d82bf3f44625d7c611ffa368
44.647059
187
0.709315
5.148815
false
false
false
false
vhbit/MastodonKit
Sources/MastodonKit/Foundation/DateFormatter.swift
1
372
import Foundation extension DateFormatter { static let mastodonFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ" dateFormatter.timeZone = TimeZone(abbreviation: "UTC") dateFormatter.locale = Locale(identifier: "en_US_POSIX") return dateFormatter }() }
mit
2df3aa2b826905af4edf3a462b67f63f
27.615385
64
0.680108
4.65
false
false
false
false
natecook1000/swift
test/SILGen/builtins.swift
1
33994
// RUN: %target-swift-emit-silgen -enable-sil-ownership -parse-stdlib %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s // RUN: %target-swift-emit-sil -enable-sil-ownership -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck -check-prefix=CANONICAL %s import Swift protocol ClassProto : class { } struct Pointer { var value: Builtin.RawPointer } // CHECK-LABEL: sil hidden @$S8builtins3foo{{[_0-9a-zA-Z]*}}F func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 { // CHECK: builtin "cmp_eq_Int1" return Builtin.cmp_eq_Int1(x, y) } // CHECK-LABEL: sil hidden @$S8builtins8load_pod{{[_0-9a-zA-Z]*}}F func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @$S8builtins8load_obj{{[_0-9a-zA-Z]*}}F func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @$S8builtins12load_raw_pod{{[_0-9a-zA-Z]*}}F func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @$S8builtins12load_raw_obj{{[_0-9a-zA-Z]*}}F func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @$S8builtins18load_invariant_pod{{[_0-9a-zA-Z]*}}F func load_invariant_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadInvariant(x) } // CHECK-LABEL: sil hidden @$S8builtins18load_invariant_obj{{[_0-9a-zA-Z]*}}F func load_invariant_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadInvariant(x) } // CHECK-LABEL: sil hidden @$S8builtins8load_gen{{[_0-9a-zA-Z]*}}F func load_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}} return Builtin.load(x) } // CHECK-LABEL: sil hidden @$S8builtins8move_pod{{[_0-9a-zA-Z]*}}F func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @$S8builtins8move_obj{{[_0-9a-zA-Z]*}}F func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [take] [[ADDR]] // CHECK-NOT: copy_value [[VAL]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @$S8builtins8move_gen{{[_0-9a-zA-Z]*}}F func move_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}} return Builtin.take(x) } // CHECK-LABEL: sil hidden @$S8builtins11destroy_pod{{[_0-9a-zA-Z]*}}F func destroy_pod(_ x: Builtin.RawPointer) { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box // CHECK-NOT: pointer_to_address // CHECK-NOT: destroy_addr // CHECK-NOT: destroy_value // CHECK: destroy_value [[XBOX]] : ${{.*}}{ // CHECK-NOT: destroy_value return Builtin.destroy(Builtin.Int64.self, x) // CHECK: return } // CHECK-LABEL: sil hidden @$S8builtins11destroy_obj{{[_0-9a-zA-Z]*}}F func destroy_obj(_ x: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(Builtin.NativeObject.self, x) } // CHECK-LABEL: sil hidden @$S8builtins11destroy_gen{{[_0-9a-zA-Z]*}}F func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(T.self, x) } // CHECK-LABEL: sil hidden @$S8builtins10assign_pod{{[_0-9a-zA-Z]*}}F func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { var x = x var y = y // CHECK: alloc_box // CHECK: alloc_box // CHECK-NOT: alloc_box // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value // CHECK: destroy_value // CHECK-NOT: destroy_value Builtin.assign(x, y) // CHECK: return } // CHECK-LABEL: sil hidden @$S8builtins10assign_obj{{[_0-9a-zA-Z]*}}F func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: assign {{%.*}} to [[ADDR]] // CHECK-NOT: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @$S8builtins12assign_tuple{{[_0-9a-zA-Z]*}}F func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject), y: Builtin.RawPointer) { var x = x var y = y // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject) // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @$S8builtins10assign_gen{{[_0-9a-zA-Z]*}}F func assign_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] {{%.*}} to [[ADDR]] : Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @$S8builtins8init_pod{{[_0-9a-zA-Z]*}}F func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: store {{%.*}} to [trivial] [[ADDR]] // CHECK-NOT: destroy_value [[ADDR]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @$S8builtins8init_obj{{[_0-9a-zA-Z]*}}F func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK-NOT: load [[ADDR]] // CHECK: store [[SRC:%.*]] to [init] [[ADDR]] // CHECK-NOT: destroy_value [[SRC]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @$S8builtins8init_gen{{[_0-9a-zA-Z]*}}F func init_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]] // CHECK-NOT: destroy_addr [[OTHER_LOC]] Builtin.initialize(x, y) } class C {} class D {} // CHECK-LABEL: sil hidden @$S8builtins22class_to_native_object{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @guaranteed $C): // CHECK-NEXT: debug_value // CHECK-NEXT: [[OBJ:%.*]] = unchecked_ref_cast [[ARG:%.*]] to $Builtin.NativeObject // CHECK-NEXT: [[OBJ_COPY:%.*]] = copy_value [[OBJ]] // CHECK-NEXT: return [[OBJ_COPY]] func class_to_native_object(_ c:C) -> Builtin.NativeObject { return Builtin.castToNativeObject(c) } // CHECK-LABEL: sil hidden @$S8builtins32class_archetype_to_native_object{{[_0-9a-zA-Z]*}}F func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NEXT: [[OBJ_COPY:%.*]] = copy_value [[OBJ]] // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ_COPY]] return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @$S8builtins34class_existential_to_native_object{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassProto): // CHECK-NEXT: debug_value // CHECK-NEXT: [[REF:%[0-9]+]] = open_existential_ref [[ARG]] : $ClassProto // CHECK-NEXT: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject // CHECK-NEXT: [[PTR_COPY:%.*]] = copy_value [[PTR]] // CHECK-NEXT: return [[PTR_COPY]] func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject { return Builtin.unsafeCastToNativeObject(t) } // CHECK-LABEL: sil hidden @$S8builtins24class_from_native_object{{[_0-9a-zA-Z]*}}F func class_from_native_object(_ p: Builtin.NativeObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK: [[C_RETURN:%.*]] = copy_value [[C]] // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C_RETURN]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @$S8builtins34class_archetype_from_native_object{{[_0-9a-zA-Z]*}}F func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T // CHECK: [[C_RETURN:%.*]] = copy_value [[C]] // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C_RETURN]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @$S8builtins41objc_class_existential_from_native_object{{[_0-9a-zA-Z]*}}F func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject // CHECK: [[C_RETURN:%.*]] = copy_value [[C]] // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C_RETURN]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @$S8builtins20class_to_raw_pointer{{[_0-9a-zA-Z]*}}F func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(t) } protocol CP: class {} func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(p) } // CHECK-LABEL: sil hidden @$S8builtins18obj_to_raw_pointer{{[_0-9a-zA-Z]*}}F func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } // CHECK-LABEL: sil hidden @$S8builtins22class_from_raw_pointer{{[_0-9a-zA-Z]*}}F func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T { return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @$S8builtins20obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @$S8builtins28existential_from_raw_pointer{{[_0-9a-zA-Z]*}}F func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @$S8builtins9gep_raw64{{[_0-9a-zA-Z]*}}F func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int64(p, i) } // CHECK-LABEL: sil hidden @$S8builtins9gep_raw32{{[_0-9a-zA-Z]*}}F func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int32(p, i) } // CHECK-LABEL: sil hidden @$S8builtins3gep{{[_0-9a-zA-Z]*}}F func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word // CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]] // CHECK: return [[A2P]] return Builtin.gep_Word(p, i, e) } public final class Header { } // CHECK-LABEL: sil hidden @$S8builtins20allocWithTailElems_1{{[_0-9a-zA-Z]*}}F func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_1(Header.self, n, ty) } // CHECK-LABEL: sil hidden @$S8builtins20allocWithTailElems_3{{[_0-9a-zA-Z]*}}F func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3) } // CHECK-LABEL: sil hidden @$S8builtins16projectTailElems{{[_0-9a-zA-Z]*}}F func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer { // CHECK: bb0([[ARG1:%.*]] : @guaranteed $Header // CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1]] : $Header // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: return [[A2P]] return Builtin.projectTailElems(h, ty) } // CHECK: } // end sil function '$S8builtins16projectTailElems1h2tyBpAA6HeaderC_xmtlF' // CHECK-LABEL: sil hidden @$S8builtins11getTailAddr{{[_0-9a-zA-Z]*}}F func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2 // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: return [[A2P]] return Builtin.getTailAddr_Word(start, i, ty1, ty2) } // CHECK-LABEL: sil hidden @$S8builtins25beginUnpairedModifyAccess{{[_0-9a-zA-Z]*}}F func beginUnpairedModifyAccess<T1>(address: Builtin.RawPointer, scratch: Builtin.RawPointer, ty1: T1.Type) { // CHECK: [[P2A_ADDR:%.*]] = pointer_to_address %0 // CHECK: [[P2A_SCRATCH:%.*]] = pointer_to_address %1 // CHECK: begin_unpaired_access [modify] [dynamic] [builtin] [[P2A_ADDR]] : $*T1, [[P2A_SCRATCH]] : $*Builtin.UnsafeValueBuffer // CHECK: [[RESULT:%.*]] = tuple () // CHECK: [[RETURN:%.*]] = tuple () // CHECK: return [[RETURN]] : $() Builtin.beginUnpairedModifyAccess(address, scratch, ty1); } // CHECK-LABEL: sil hidden @$S8builtins30performInstantaneousReadAccess{{[_0-9a-zA-Z]*}}F func performInstantaneousReadAccess<T1>(address: Builtin.RawPointer, scratch: Builtin.RawPointer, ty1: T1.Type) { // CHECK: [[P2A_ADDR:%.*]] = pointer_to_address %0 // CHECK: [[SCRATCH:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: begin_unpaired_access [read] [dynamic] [no_nested_conflict] [builtin] [[P2A_ADDR]] : $*T1, [[SCRATCH]] : $*Builtin.UnsafeValueBuffer // CHECK-NOT: end_{{.*}}access // CHECK: [[RESULT:%.*]] = tuple () // CHECK: [[RETURN:%.*]] = tuple () // CHECK: return [[RETURN]] : $() Builtin.performInstantaneousReadAccess(address, ty1); } // CHECK-LABEL: sil hidden @$S8builtins8condfail{{[_0-9a-zA-Z]*}}F func condfail(_ i: Builtin.Int1) { Builtin.condfail(i) // CHECK: cond_fail {{%.*}} : $Builtin.Int1 } struct S {} @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} protocol P {} // CHECK-LABEL: sil hidden @$S8builtins10canBeClass{{[_0-9a-zA-Z]*}}F func canBeClass<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(O.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(OP1.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompo = OP1 & OP2 // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(ObjCCompo.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(S.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(C.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(P.self) typealias MixedCompo = OP1 & P // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompo.self) // CHECK: builtin "canBeClass"<T> Builtin.canBeClass(T.self) } // FIXME: "T.Type.self" does not parse as an expression // CHECK-LABEL: sil hidden @$S8builtins18canBeClassMetatype{{[_0-9a-zA-Z]*}}F func canBeClassMetatype<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 0 typealias OT = O.Type Builtin.canBeClass(OT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias OP1T = OP1.Type Builtin.canBeClass(OP1T.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompoT = (OP1 & OP2).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(ObjCCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias ST = S.Type Builtin.canBeClass(ST.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias CT = C.Type Builtin.canBeClass(CT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias PT = P.Type Builtin.canBeClass(PT.self) typealias MixedCompoT = (OP1 & P).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias TT = T.Type Builtin.canBeClass(TT.self) } // CHECK-LABEL: sil hidden @$S8builtins11fixLifetimeyyAA1CCF : $@convention(thin) (@guaranteed C) -> () { func fixLifetime(_ c: C) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $C): // CHECK: fix_lifetime [[ARG]] : $C Builtin.fixLifetime(c) } // CHECK: } // end sil function '$S8builtins11fixLifetimeyyAA1CCF' // CHECK-LABEL: sil hidden @$S8builtins20assert_configuration{{[_0-9a-zA-Z]*}}F func assert_configuration() -> Builtin.Int32 { return Builtin.assert_configuration() // CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32 // CHECK: return [[APPLY]] : $Builtin.Int32 } // CHECK-LABEL: sil hidden @$S8builtins17assumeNonNegativeyBwBwF func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word { return Builtin.assumeNonNegative_Word(x) // CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word // CHECK: return [[APPLY]] : $Builtin.Word } // CHECK-LABEL: sil hidden @$S8builtins11autoreleaseyyAA1OCF : $@convention(thin) (@guaranteed O) -> () { // ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it? // CHECK: bb0([[ARG:%.*]] : @guaranteed $O): // CHECK: unmanaged_autorelease_value [[ARG]] // CHECK: } // end sil function '$S8builtins11autoreleaseyyAA1OCF' func autorelease(_ o: O) { Builtin.autorelease(o) } // The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during // diagnostics. // CHECK-LABEL: sil hidden @$S8builtins11unreachable{{[_0-9a-zA-Z]*}}F // CHECK: builtin "unreachable"() // CHECK: return // CANONICAL-LABEL: sil hidden @$S8builtins11unreachableyyF : $@convention(thin) () -> () { func unreachable() { Builtin.unreachable() } // CHECK-LABEL: sil hidden @$S8builtins15reinterpretCast_1xBw_AA1DCAA1CCSgAGtAG_BwtF : $@convention(thin) (@guaranteed C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C) // CHECK: bb0([[ARG1:%.*]] : @guaranteed $C, [[ARG2:%.*]] : @trivial $Builtin.Word): // CHECK-NEXT: debug_value // CHECK-NEXT: debug_value // CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1]] : $C to $Builtin.Word // CHECK-NEXT: [[ARG1_D:%.*]] = unchecked_ref_cast [[ARG1]] : $C to $D // CHECK-NEXT: [[ARG1_OPT:%.*]] = unchecked_ref_cast [[ARG1]] : $C to $Optional<C> // CHECK-NEXT: [[ARG2_FROM_WORD:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C // CHECK-NEXT: [[ARG2_FROM_WORD_COPY:%.*]] = copy_value [[ARG2_FROM_WORD]] // CHECK-NEXT: [[ARG1_D_COPY:%.*]] = copy_value [[ARG1_D]] // CHECK-NEXT: [[ARG1_OPT_COPY:%.*]] = copy_value [[ARG1_OPT]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_D_COPY]] : $D, [[ARG1_OPT_COPY]] : $Optional<C>, [[ARG2_FROM_WORD_COPY:%.*]] : $C) // CHECK: return [[RESULT]] func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) { return (Builtin.reinterpretCast(c) as Builtin.Word, Builtin.reinterpretCast(c) as D, Builtin.reinterpretCast(c) as C?, Builtin.reinterpretCast(x) as C) } // CHECK-LABEL: sil hidden @$S8builtins19reinterpretAddrOnly{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnly<T, U>(_ t: T) -> U { // CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @$S8builtins28reinterpretAddrOnlyToTrivial{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int { // CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]] // CHECK-NOT: destroy_addr [[INPUT]] return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @$S8builtins27reinterpretAddrOnlyLoadable{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) { // CHECK: [[BUF:%.*]] = alloc_stack $Int // CHECK: store {{%.*}} to [trivial] [[BUF]] // CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T // CHECK: copy_addr [[RES1]] to [initialization] return (Builtin.reinterpretCast(a) as T, // CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int // CHECK: load [trivial] [[RES]] Builtin.reinterpretCast(b) as Int) } // CHECK-LABEL: sil hidden @$S8builtins18castToBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word // CHECK: [[BO_COPY:%.*]] = copy_value [[BO]] // CHECK: return [[BO_COPY]] func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject { return Builtin.castToBridgeObject(c, w) } // CHECK-LABEL: sil hidden @$S8builtins23castRefFromBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C { return Builtin.castReferenceFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @$S8builtins30castBitPatternFromBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word // CHECK-NOT: destroy_value [[BO]] func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word { return Builtin.castBitPatternFromBridgeObject(bo) } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // NativeObject // CHECK-LABEL: sil hidden @$S8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Optional<Builtin.NativeObject>): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Builtin.NativeObject> // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<Builtin.NativeObject> // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject nonNull // CHECK-LABEL: sil hidden @$S8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.NativeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.NativeObject // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) // CHECK-LABEL: sil hidden @$S8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Optional<Builtin.UnknownObject>): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<Builtin.UnknownObject> // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) nonNull // CHECK-LABEL: sil hidden @$S8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.UnknownObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.UnknownObject // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject nonNull // CHECK-LABEL: sil hidden @$S8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.BridgeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.BridgeObject // CHECK: return func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject nonNull native // CHECK-LABEL: sil hidden @$S8builtins15isUnique_native{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.BridgeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[CAST:%.*]] = unchecked_addr_cast [[WRITE]] : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: return func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique_native(&ref)) } // ---------------------------------------------------------------------------- // Builtin.castReference // ---------------------------------------------------------------------------- class A {} protocol PUnknown {} protocol PClass : class {} // CHECK-LABEL: sil hidden @$S8builtins19refcast_generic_any{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject func refcast_generic_any<T>(_ o: T) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @$S8builtins17refcast_class_anyyyXlAA1ACF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $A): // CHECK: [[ARG_CASTED:%.*]] = unchecked_ref_cast [[ARG]] : $A to $AnyObject // CHECK: [[ARG_CASTED_COPY:%.*]] = copy_value [[ARG_CASTED]] // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[ARG_CASTED_COPY]] // CHECK: } // end sil function '$S8builtins17refcast_class_anyyyXlAA1ACF' func refcast_class_any(_ o: A) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @$S8builtins20refcast_punknown_any{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject func refcast_punknown_any(_ o: PUnknown) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @$S8builtins18refcast_pclass_anyyyXlAA6PClass_pF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $PClass): // CHECK: [[ARG_CAST:%.*]] = unchecked_ref_cast [[ARG]] : $PClass to $AnyObject // CHECK: [[ARG_CAST_COPY:%.*]] = copy_value [[ARG_CAST]] // CHECK: return [[ARG_CAST_COPY]] // CHECK: } // end sil function '$S8builtins18refcast_pclass_anyyyXlAA6PClass_pF' func refcast_pclass_any(_ o: PClass) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @$S8builtins20refcast_any_punknown{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown func refcast_any_punknown(_ o: AnyObject) -> PUnknown { return Builtin.castReference(o) } // => SEMANTIC ARC TODO: This function is missing a borrow + extract + copy. // // CHECK-LABEL: sil hidden @$S8builtins22unsafeGuaranteed_class{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @guaranteed $A): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A) // CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]] // CHECK: destroy_value [[R]] // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: return [[P_COPY]] : $A // CHECK: } func unsafeGuaranteed_class(_ a: A) -> A { Builtin.unsafeGuaranteed(a) return a } // CHECK-LABEL: $S8builtins24unsafeGuaranteed_generic{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @guaranteed $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]] // CHECK: destroy_value [[R]] // CHECK: [[P_RETURN:%.*]] = copy_value [[P]] // CHECK: return [[P_RETURN]] : $T // CHECK: } func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T { Builtin.unsafeGuaranteed(a) return a } // CHECK_LABEL: sil hidden @$S8builtins31unsafeGuaranteed_generic_return{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @guaranteed $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]] // CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8) // CHECK: return [[S]] : $(T, Builtin.Int8) // CHECK: } func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) { return Builtin.unsafeGuaranteed(a) } // CHECK-LABEL: sil hidden @$S8builtins19unsafeGuaranteedEnd{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @trivial $Builtin.Int8): // CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8) // CHECK: [[S:%.*]] = tuple () // CHECK: return [[S]] : $() // CHECK: } func unsafeGuaranteedEnd(_ t: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(t) } // CHECK-LABEL: sil hidden @$S8builtins10bindMemory{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @trivial $Builtin.RawPointer, [[I:%.*]] : @trivial $Builtin.Word, [[T:%.*]] : @trivial $@thick T.Type): // CHECK: bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T // CHECK: return {{%.*}} : $() // CHECK: } func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) { Builtin.bindMemory(ptr, idx, T.self) } //===----------------------------------------------------------------------===// // RC Operations //===----------------------------------------------------------------------===// // SILGen test: // // CHECK-LABEL: sil hidden @$S8builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () { // CHECK: bb0([[P:%.*]] : @guaranteed $Builtin.NativeObject): // CHECK: unmanaged_retain_value [[P]] // CHECK: } // end sil function '$S8builtins6retain{{[_0-9a-zA-Z]*}}F' // SIL Test. This makes sure that we properly clean up in -Onone SIL. // CANONICAL-LABEL: sil hidden @$S8builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () { // CANONICAL: bb0([[P:%.*]] : $Builtin.NativeObject): // CANONICAL: strong_retain [[P]] // CANONICAL-NOT: retain // CANONICAL-NOT: release // CANONICAL: } // end sil function '$S8builtins6retain{{[_0-9a-zA-Z]*}}F' func retain(ptr: Builtin.NativeObject) { Builtin.retain(ptr) } // SILGen test: // // CHECK-LABEL: sil hidden @$S8builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () { // CHECK: bb0([[P:%.*]] : @guaranteed $Builtin.NativeObject): // CHECK: unmanaged_release_value [[P]] // CHECK-NOT: destroy_value [[P]] // CHECK: } // end sil function '$S8builtins7release{{[_0-9a-zA-Z]*}}F' // SIL Test. Make sure even in -Onone code, we clean this up properly: // CANONICAL-LABEL: sil hidden @$S8builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () { // CANONICAL: bb0([[P:%.*]] : $Builtin.NativeObject): // CANONICAL-NEXT: debug_value // CANONICAL-NEXT: strong_release [[P]] // CANONICAL-NEXT: tuple // CANONICAL-NEXT: tuple // CANONICAL-NEXT: return // CANONICAL: } // end sil function '$S8builtins7release{{[_0-9a-zA-Z]*}}F' func release(ptr: Builtin.NativeObject) { Builtin.release(ptr) } //===----------------------------------------------------------------------===// // Other Operations //===----------------------------------------------------------------------===// func once_helper() {} // CHECK-LABEL: sil hidden @$S8builtins4once7controlyBp_tF // CHECK: [[T0:%.*]] = function_ref @$S8builtins11once_helperyyFTo : $@convention(c) () -> () // CHECK-NEXT: builtin "once"(%0 : $Builtin.RawPointer, [[T0]] : $@convention(c) () -> ()) func once(control: Builtin.RawPointer) { Builtin.once(control, once_helper) } // CHECK-LABEL: sil hidden @$S8builtins19valueToBridgeObjectyBbSuF : $@convention(thin) (UInt) -> @owned Builtin.BridgeObject { // CHECK: bb0([[UINT:%.*]] : @trivial $UInt): // CHECK: [[CAST:%.*]] = value_to_bridge_object [[UINT]] : $UInt // CHECK: [[RET:%.*]] = copy_value [[CAST]] : $Builtin.BridgeObject // CHECK: return [[RET]] : $Builtin.BridgeObject // CHECK: } // end sil function '$S8builtins19valueToBridgeObjectyBbSuF' func valueToBridgeObject(_ x: UInt) -> Builtin.BridgeObject { return Builtin.valueToBridgeObject(x) }
apache-2.0
f951be8184b3f9987112719cbc456568
40.710429
193
0.62511
3.213651
false
false
false
false
uberbruns/UBRDeltaUI
UBRDeltaUI/DeltaLib/UBRDelta+Types.swift
1
3041
// // UBRDelta+Types.swift // // Created by Karsten Bruns on 27/08/15. // Copyright © 2015 bruns.me. All rights reserved. // import Foundation public typealias ComparisonChanges = [String:Bool] public enum DeltaComparisonLevel { case same, different, changed(ComparisonChanges) var isSame: Bool { return self != .different } var isChanged: Bool { return self != .different && self != .same } } extension DeltaComparisonLevel : Equatable { } public func ==(lhs: DeltaComparisonLevel, rhs: DeltaComparisonLevel) -> Bool { switch (lhs, rhs) { case (.different, .different) : return true case (.same, .same) : return true case (.changed(let a), .changed(let b)) : return a == b default : return false } } extension DeltaComparisonLevel { /** Convenience function that allows you to check if a property did change. The default return value is `true`. Usage: ``` let comparison = anItem.compareTo(anotherItem) let valueDidChange = comparison.propertyDidChange("value") ``` */ public func propertyDidChange(_ property: String) -> Bool { switch self { case .same : return false case .changed(let changes) : return changes[property] ?? true default : return true } } } public struct DeltaComparisonResult { public let insertionIndexes: [Int] public let deletionIndexes: [Int] public let duplicatedIndexes: [Int]? public let reloadIndexMap: [Int:Int] // Old Index, New Index public let moveIndexMap: [Int:Int] public let oldItems: [ComparableItem] public let unmovedItems: [ComparableItem] public let newItems: [ComparableItem] init(insertionIndexes: [Int], deletionIndexes: [Int], reloadIndexMap: [Int:Int], moveIndexMap: [Int:Int], oldItems: [ComparableItem], unmovedItems: [ComparableItem], newItems: [ComparableItem], duplicatedIndexes: [Int]? = nil) { self.insertionIndexes = insertionIndexes self.deletionIndexes = deletionIndexes self.reloadIndexMap = reloadIndexMap self.moveIndexMap = moveIndexMap self.oldItems = oldItems self.unmovedItems = unmovedItems self.newItems = newItems self.duplicatedIndexes = duplicatedIndexes } } struct DeltaMatrix<T> { var rows = [Int:[Int:T]]() subscript(row: Int, col: Int) -> T? { get { guard let cols = rows[row] else { return nil } return cols[col] } set(newValue) { var cols = rows[row] ?? [Int:T]() cols[col] = newValue rows[row] = cols } } init() {} mutating func removeAll(_ keepCapicity: Bool) { rows.removeAll(keepingCapacity: keepCapicity) } }
mit
67169a43b4912792d57f38e7d9dc46d0
23.126984
78
0.585855
4.437956
false
false
false
false
ps2/rileylink_ios
MinimedKit/Messages/GetHistoryPageCarelinkMessageBody.swift
1
956
// // GetHistoryPageCarelinkMessageBody.swift // RileyLink // // Created by Pete Schwamb on 3/14/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public class GetHistoryPageCarelinkMessageBody: CarelinkLongMessageBody { public let lastFrame: Bool public let frameNumber: Int public let frame: Data public required init?(rxData: Data) { guard rxData.count == type(of: self).length else { return nil } frameNumber = Int(rxData[0]) & 0b1111111 lastFrame = (rxData[0]) & 0b10000000 > 0 frame = rxData.subdata(in: 1..<65) super.init(rxData: rxData) } public required init(pageNum: Int) { let numArgs = 1 lastFrame = false frame = Data() frameNumber = 0 let data = Data(hexadecimalString: String(format: "%02x%02x", numArgs, UInt8(pageNum)))! super.init(rxData: data)! } }
mit
7e997ca3c187f715d10c588b31313317
26.285714
96
0.620942
4.012605
false
false
false
false
ivankorobkov/net
swift/Netx/Pipe.swift
2
2880
// // BufferedPipe.swift // Netx // // Created by Ivan Korobkov on 18/02/16. // Copyright © 2016 Ivan Korobkov. All rights reserved. // import Foundation public class Pipe : ReadWriteCloser { private let queue: dispatch_queue_t private var reads: [(data: NSMutableData, callback: ReadCallback, index: Int)] private var writes: [(data: NSData, callback: WriteCallback, index: Int)] private var closed: Bool init() { self.queue = dispatch_queue_create("com.github.ivankorobkov.netx", DISPATCH_QUEUE_SERIAL) self.reads = [] self.writes = [] self.closed = false } public func read(data: NSMutableData, callback: ReadCallback) { dispatch_async(self.queue) { () -> Void in self.reads.append((data, callback, 0)) self.flush() } } public func write(data: NSData, callback: WriteCallback) { dispatch_async(self.queue) { () -> Void in guard !self.closed else { callback(0, IOError.BrokenPipe) return } self.writes.append((data, callback, 0)) self.flush() } } public func close() { dispatch_async(self.queue) { () -> Void in guard !self.closed else { return } self.closed = true self.flush() } } private func flush() { // Copy data from the writes to the reads. while self.reads.count > 0 && self.writes.count > 0 { var read = self.reads[0] var write = self.writes[0] // Compute how much data can be copied. var len = read.data.length - read.index let wlen = write.data.length - write.index if len > wlen { len = wlen } // Copy the data. memcpy(read.data.mutableBytes + read.index, write.data.bytes + write.index, len) self.reads[0].index += len self.writes[0].index += len // Maybe remove the read. read = self.reads[0] if read.data.length == read.index { self.reads.removeFirst() read.callback(read.index, nil) } // Maybe remove the write. write = self.writes[0] if write.data.length == write.index { self.writes.removeFirst() write.callback(write.index, nil) } } // Pass EOF to the reads if closed and no more writes. if self.closed && self.writes.count == 0 { for read in self.reads { read.callback(read.index, IOError.EOF) } self.reads.removeAll() } } }
apache-2.0
c9ad43a875d2841ed8f8ac26f1e0fa2a
28.989583
97
0.507815
4.362121
false
false
false
false
zasia3/archivervapor
Sources/App/Routes.swift
1
1521
import Vapor final class Routes: RouteCollection { func build(_ builder: RouteBuilder) throws { builder.get("hello") { req in var json = JSON() try json.set("hello", "world") return json } builder.get("plaintext") { req in return "Hello, world!" } // response to requests to /info domain // with a description of the request builder.get("info") { req in return req.description } builder.get("description") { req in return req.description } builder.get("me") { req in return try req.user().name } let errorBuilder = builder.grouped(RequestErrorMiddleware()) let authController = AuthController() authController.addRoutes(to: errorBuilder) try errorBuilder.resource("users", UserController.self) let grouped = errorBuilder.grouped(AuthenticationMiddleware()) let receiptsController = ReceiptController() receiptsController.addRoutes(to: grouped) try grouped.resource("receipts", ReceiptController.self) try grouped.resource("photos", PhotoController.self) try grouped.resource("shops", ShopController.self) } } /// Since Routes doesn't depend on anything /// to be initialized, we can conform it to EmptyInitializable /// /// This will allow it to be passed by type. extension Routes: EmptyInitializable { }
mit
16e28012c3cb369a73b6475fb5d353e0
30.6875
70
0.60881
5.019802
false
false
false
false
karappo/PlayTheWheels
PlayTheWheels/ViewController.swift
1
35804
// // ViewController.swift // PlayTheWheels // // Created by Naokazu Terada on 2015/08/13. // Copyright (c) 2015年 Karappo Inc. All rights reserved. // import UIKit import AVFoundation import CoreMotion let DEBUG = false class ViewController: UIViewController, ESTBeaconManagerDelegate { // UserDefaults let UD = UserDefaults.standard let UD_KEY_KONASHI = "konashi" let UD_KEY_INSTRUMENT_COLOR_HUE = "instrument_color_hue" let UD_KEY_INSTRUMENT_COLOR_SATURATION = "instrument_color_saturation" let UD_KEY_EFFECT_COLOR_HUE = "effect_color_hue" let UD_KEY_EFFECT_COLOR_SATURATION = "effect_color_saturation" let UD_KEY_LED_DIVIDE = "led_divide" let UD_KEY_LED_POSITION = "led_position" var updateRotationFlag = false var devices = [String: [String: String]]() var colors = [String: [String: Float]]() var beaconLastUpdate = Date() // beaconManagerの更新があまり頻繁にならないように var beaconAccuracies = [Float]() var commandLastCalls = [String: Date]() // commandの最後に送信された時刻を記録 @IBOutlet weak var arrow: UIImageView! // # Konashi Section @IBOutlet weak var konashiBtn: UIButton! var konashiBtnDefaultLabel = "Find Konashi" var manualDisconnection: Bool = false // Disconnectされた際に手動で切断されたのかどうかを判定するためのフラグ var connectionCheckTimer: Timer! var lastSendedCommand: NSString! @IBOutlet weak var uuidLabel: UILabel! // # Beacon Section @IBOutlet weak var beaconSliderBlueberry1: UISlider! @IBOutlet weak var beaconSliderBlueberry2: UISlider! @IBOutlet weak var beaconSliderIce1: UISlider! @IBOutlet weak var beaconSliderIce2: UISlider! @IBOutlet weak var beaconSliderMint1: UISlider! @IBOutlet weak var beaconSliderMint2: UISlider! @IBOutlet weak var beaconSwitchBlueberry1: UISwitch! @IBOutlet weak var beaconSwitchBlueberry2: UISwitch! @IBOutlet weak var beaconSwitchIce1: UISwitch! @IBOutlet weak var beaconSwitchIce2: UISwitch! @IBOutlet weak var beaconSwitchMint1: UISwitch! @IBOutlet weak var beaconSwitchMint2: UISwitch! // # Color Section @IBOutlet weak var colorView: UIView! @IBOutlet weak var hueSlider: UISlider! @IBOutlet weak var hueLabel: UILabel! @IBOutlet weak var saturationSlider: UISlider! @IBOutlet weak var saturationLabel: UILabel! @IBOutlet weak var colorView2: UIView! @IBOutlet weak var hueSlider2: UISlider! @IBOutlet weak var hueLabel2: UILabel! @IBOutlet weak var saturationSlider2: UISlider! @IBOutlet weak var saturationLabel2: UILabel! @IBOutlet weak var brightnessLabel: UILabel! @IBOutlet weak var brightnessSlider: UISlider! @IBOutlet weak var divideSlider: UISlider! @IBOutlet weak var divideLabel: UILabel! @IBOutlet weak var positionSlider: UISlider! @IBOutlet weak var positionLabel: UILabel! var instrumentColor: UIColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) var effectColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) // # Tone Section @IBOutlet weak var toneNameBtn: UIButton! @IBOutlet weak var tonePlayerTypeLabel: UILabel! @IBOutlet weak var toneCountLabel: UILabel! enum PlayerType: String { case OneShot = "One Shot" case LongShot = "Long Shot" } var playerType = PlayerType.OneShot var toneDirs: [String] = [] // # Effect Section // Delay @IBOutlet weak var delayDryWetSlider: UISlider! @IBOutlet weak var delayDelayTimeSlider: UISlider! @IBOutlet weak var delayFeedbackSlider: UISlider! @IBOutlet weak var delayLowPassCutOffSlider: UISlider! @IBOutlet weak var delayDryWetLabel: UILabel! @IBOutlet weak var delayDelayTimeLabel: UILabel! @IBOutlet weak var delayFeedbackLabel: UILabel! @IBOutlet weak var delayLowPassCutOffLabel: UILabel! // Beacon let beaconManager = ESTBeaconManager() let beaconRegion = CLBeaconRegion(proximityUUID: UUID(uuidString: "B8A63B91-CB83-4701-8093-62084BFA40B4")!, identifier: "ranged region") let effectBeacons = [ // "major:minor":"key" "9152:49340" :"blueberry1", "21461:51571":"blueberry2", "30062:7399" :"ice1", "13066:17889":"ice2", "38936:27676":"mint1", "4274:29174" :"mint2" ] var beaconUIs:[String: [AnyObject]]! let FM = FileManager.default let MM: CMMotionManager = CMMotionManager() let MM_UPDATE_INTERVAL = 0.01 // 更新周期 100Hz var engine: AVAudioEngine = AVAudioEngine() var delay: AVAudioUnitDelay! var mixer: AVAudioMixerNode! var players: Array<AVAudioPlayerNode> = [] var layeredPlayers: Array<AVAudioPlayerNode> = [] var layeredPlayerVol: Float = 0.0 var audioFiles: Array<AVAudioFile> = [] var current_index: Int = 0 let SLIT_COUNT = 8 // 円周を何分割してplayerPointsにするか var prevDeg: Double = 0.0 var playerPoints: Array<Double> = [] // 分割数に応じて360度を当分した角度を保持しておく配列 override func viewDidLoad() { super.viewDidLoad() initialize() // load settings // ============= let uuid = UIDevice.current.identifierForVendor!.uuidString NSLog("uuid:\(uuid)") uuidLabel.text = "uuid:\(uuid)" let device = devices[uuid] if let konashi = device?["konashi"] { konashiBtnDefaultLabel = "Find Konashi (\(konashi))" konashiBtn.setTitle(konashiBtnDefaultLabel, for: UIControlState()) } // Sound // Delay delay = AVAudioUnitDelay() setDelayWetDry(0) // 可変 0-80 setDelayDelayTime(0.295) // 不変 setDelayFeedback(0) // 可変 0-90 setDelayLowPassCutOff(700) // 不変 setBrightnessMin(0.15) mixer = AVAudioMixerNode() engine.attach(delay) engine.attach(mixer) // AudioPlayerの準備 // OneShot var toneDir: String = toneDirs.first! if let tone = device?["tone"] { toneDir = tone } let format: AVAudioFormat = initPlayers(toneDir as String) engine.connect(mixer, to: delay, format: format) engine.connect(delay, to: engine.mainMixerNode, format: format) do { try engine.start() } catch { NSLog("AVAudioEngine start error") } // モーションセンサー if MM.isDeviceMotionAvailable { MM.deviceMotionUpdateInterval = MM_UPDATE_INTERVAL MM.startDeviceMotionUpdates(to: OperationQueue(), withHandler:{ deviceManager, error in let rotation = atan2(deviceManager!.gravity.x, deviceManager!.gravity.y) - .pi self.updateRotation(rotation) }) } // Color loadInstrumentColor(toneDir as NSString) hueSlider2.setValue(0.66, animated: true) saturationSlider2.setValue(1.0, animated: true) divideSlider.setValue(Float(UD.integer(forKey: UD_KEY_LED_DIVIDE)), animated: true) changeDivide(divideSlider) positionSlider.setValue(Float(UD.integer(forKey: UD_KEY_LED_POSITION)), animated: true) changePosition(positionSlider) sendInstrumentColor() sendEffectColor() setBrightnessMin(self.brightnessSlider.value) // Konashi関係 logKonashiStatus() Konashi.shared().connectedHandler = { NSLog("[Konashi] Connected!") } Konashi.shared().disconnectedHandler = { NSLog("[Konashi] Disconnected") // button self.konashiBtn.setTitle(self.konashiBtnDefaultLabel, for: []) // // 勝手に切断された場合にリトライする // if self.manualDisconnection == false { // // UserDefaultsから前回接続したKonashiを読み、接続を試みる // if let previously_connected_konashi = self.UD.stringForKey(self.UD_KEY_KONASHI) { // NSLog("[Konashi] Retry connecting to \(previously_connected_konashi) (previus connection) ...") // self.findKonashiWithName(previously_connected_konashi) // } // } // self.manualDisconnection = false } Konashi.shared().readyHandler = { NSLog("[Konashi] Ready...") // stop timer if self.connectionCheckTimer != nil && self.connectionCheckTimer.isValid { NSLog("[Konashi] Stop connection check") self.connectionCheckTimer.invalidate() } self.logKonashiStatus() let konashiName: String = Konashi.peripheralName() self.UD.set(konashiName, forKey: self.UD_KEY_KONASHI) // button self.konashiBtn.setTitle("[Connected] \(konashiName)", for: []) // Konashi setting Konashi.uartMode(KonashiUartMode.enable, baudrate: KonashiUartBaudrate.rate9K6) Konashi.pinMode(KonashiDigitalIOPin.digitalIO1, mode: KonashiPinMode.output) // LED2を点灯 Konashi.digitalWrite(KonashiDigitalIOPin.digitalIO1, value: KonashiLevel.high) self.sendPlayerType() self.sendEffectColor() self.sendInstrumentColor() self.setBrightnessMin(self.brightnessSlider.value) } // Konashi.shared().uartRxCompleteHandler = {(data: NSData!) -> Void in // NSLog("[Konashi] UartRx \(data.description)") // } if let default_konashi = device?["konashi"] { NSLog("[Konashi] Auto connecting to \(default_konashi) (default) ...") findKonashiWithName(default_konashi) } } func initialize() { // "{IPHONE-UUIDString}":["tone":"{TONE-NAME}","konashi":"{KONASHI-ID}",["color":["hue":{val},"saturation":{val}]]] // [注意] defaults = [["DAE4E972-9F4D-4EDB-B511-019B0214944F":["tone":"A-L"],..],...] みたいな書き方をするとindexingが止まらなくなる 参考:http://qiita.com/osamu1203/items/270fc716883d86d8f3b7 devices["07ECFB6E-B9B9-40FB-AFCA-CDFD8E6BCBBF"] = ["tone":"A-L", "konashi":"konashi2-f01d0f"] devices["3300EBFB-C3D0-452B-870C-13E99CDB06F0"] = ["tone":"A-R", "konashi":"konashi2-f01b54"] devices["5D4108ED-F723-4829-81B3-DAD178C486B3"] = ["tone":"B-L", "konashi":"konashi2-f01c12"] devices["CFC3C20E-EBE1-4972-9B01-967A7BF8C395"] = ["tone":"B-R", "konashi":"konashi2-f01c3d"] devices["F6946F2C-8AB6-4E13-A3C3-9325BA2E5148"] = ["tone":"C-L", "konashi":"konashi2-f01cc5"] devices["48ABB92F-E323-4ECB-AC08-F059C6F4C3C2"] = ["tone":"C-R", "konashi":"konashi2-f01cc9"] devices["3385AAF7-648E-419F-9065-7721BF801A5D"] = ["tone":"D-L", "konashi":"konashi2-f01cf9"] devices["92C5D75D-41B3-4CBB-902E-4EDFE108CFA4"] = ["tone":"D-R", "konashi":"konashi2-f01bf3"] devices["C6CDC907-1C68-4CC5-8BDE-1D77DC24C5D9"] = ["tone":"E-L", "konashi":"konashi2-f01bf5"] devices["217C0F21-0D07-4208-AA18-642B41AE776B"] = ["tone":"E-R", "konashi":"konashi2-f01c78"] // 予備 devices["3E2B4AF5-2EAB-421B-B71A-7A795D0422A7"] = ["tone":"F-L", "konashi":"konashi2-f01d7a"] devices["16462C30-3AB7-4872-88B6-651A42ADD56A"] = ["tone":"F-R", "konashi":"konashi2-f01c3d"] // iPhone devices["9F90BB54-9DA8-454A-9744-C590D9195F12"] = ["tone":"F-L", "konashi":"konashi2-f01d7a"] colors["A"] = ["hue":0.412, "saturation":1.0] colors["B"] = ["hue":0.190, "saturation":1.0] colors["C"] = ["hue":0.893, "saturation":0.966] colors["D"] = ["hue":0.0, "saturation":1.0] colors["E"] = ["hue":0.070, "saturation":1.0] colors["F"] = ["hue":0.678, "saturation":1.0] do { toneDirs = try FM.contentsOfDirectory(atPath: "\(Bundle.main.resourcePath!)/tones") toneDirs.remove(at: toneDirs.index(of: "README.md")!) } catch { // do nothing NSLog("Cannot load toneDirs !") } // Estimote Beacon beaconManager.delegate = self beaconManager.requestAlwaysAuthorization() beaconUIs = [ "blueberry1":[beaconSwitchBlueberry1, beaconSliderBlueberry1], "blueberry2":[beaconSwitchBlueberry2, beaconSliderBlueberry2], "ice1":[beaconSwitchIce1, beaconSliderIce1], "ice2":[beaconSwitchIce2, beaconSliderIce2], "mint1":[beaconSwitchMint1, beaconSliderMint1], "mint2":[beaconSwitchMint2, beaconSliderMint2] ] // playerPoints for i in 0..<SLIT_COUNT { playerPoints += [360.0/Double(SLIT_COUNT)*Double(i)] } } func findKonashiWithName(_ konashiName: String) { let res = Konashi.find(withName: konashiName) if res == KonashiResult.success { // 呼び出しが正しく行われただけで、接続されたわけではない // NSLog("[Konashi] Konashi.findWithName called and success") // if connectionCheckTimer == nil || connectionCheckTimer.valid == false { // NSLog("[Konashi] Start connection check") // // 接続出来たかどうかの監視を開始 // connectionCheckTimer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: "checkConnection", userInfo: ["konashi": konashiName], repeats: true) // } } else { NSLog("[Konashi] Konashi.findWithName called and failed...") } } func checkConnection(){ NSLog("[Konashi] Retry connecting") let userInfo = connectionCheckTimer.userInfo as! Dictionary<String, AnyObject> let konashi = userInfo["konashi"] as! String findKonashiWithName(konashi) } func sendPlayerType() { switch playerType { case PlayerType.OneShot: uart("t:1;") case PlayerType.LongShot: uart("t:2;") } } // toneDirから該当する色を読み込む func loadInstrumentColor(_ toneDirStr: NSString) { let alphabet = toneDirStr.substring(to: 1) if let color: [String: Float] = colors[alphabet] { setHue(color["hue"]!) setSaturation(color["saturation"]!) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) beaconManager.startRangingBeacons(in: beaconRegion) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) beaconManager.stopRangingBeacons(in: beaconRegion) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func logKonashiStatus() { NSLog("--------------------------------") NSLog("[Konashi] connected: \(Konashi.isConnected())") NSLog("[Konashi] ready: \(Konashi.isReady())") NSLog("[Konashi] module: \(Konashi.peripheralName())") NSLog("--------------------------------") } // Beacon func beaconManager(_ manager: Any!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { if let _beacons = beacons as? [CLBeacon] { var accuracy_min: Float? // 最小値を保持しておいて、あとでEffectに適用する // var nearestBeacon: String? for _beacon: CLBeacon in _beacons { let beaconKey = "\(_beacon.major):\(_beacon.minor)" if let beaconName = effectBeacons[beaconKey] as String! { let beaconUI = self.beaconUIs[beaconName] let _switch: UISwitch = beaconUI?[0] as! UISwitch let _slider: UISlider = beaconUI?[1] as! UISlider let accuracy = _beacon.accuracy if 0 < accuracy { if _switch.isOn { if accuracy_min == nil || Float(accuracy) < accuracy_min! { accuracy_min = Float(accuracy) // nearestBeacon = beaconName } } _slider.setValue(Float(-accuracy), animated: true) } } } if accuracy_min != nil { // beaconの値が結構あてにならないし、ここの処理のせいでLEDがチカチカするのでここで間引く let now = Date() if 3 < Float(now.timeIntervalSince(beaconLastUpdate)) { beaconLastUpdate = now if 0 < beaconAccuracies.count { accuracy_min = beaconAccuracies.reduce(0, +) / Float(beaconAccuracies.count) beaconAccuracies.removeAll() } } else { beaconAccuracies.append(accuracy_min!) return } let accuracy = Float(Int(accuracy_min! * 100.0)) / 100.0 // 小数点第1位まで let beacon_min: Float = 1.3 let beacon_max: Float = 0.8 let drywet = map(accuracy, in_min:beacon_min, in_max:beacon_max, out_min:0, out_max:60) let feedback = map(accuracy, in_min:beacon_min, in_max:beacon_max, out_min:0, out_max:80) let float_val = map(accuracy, in_min:beacon_min, in_max:beacon_max, out_min:0.0, out_max:1.0) setDelayFeedback(feedback) delayFeedbackSlider.setValue(feedback, animated: true) setDelayWetDry(drywet) delayDryWetSlider.setValue(drywet, animated: true) layeredPlayerVol = float_val uart("E:\(float_val);") // for debug -------- if(DEBUG) { // NSLog(nearestBeacon) NSLog(NSString(format: "%.3f ", accuracy) as String) let percent = Int(map(accuracy, in_min:beacon_min, in_max:beacon_max, out_min:0, out_max:100)) let arr = Array(repeating: "*", count: percent) if 0<arr.count { if 100<=percent { NSLog(arr.joined(separator: "")) NSLog("") } else { NSLog(arr.joined(separator: "")) } } else { NSLog("") } } // / for debug -------- } } } // in_min~in_max内のxをout_min〜out_max内の値に変換して返す fileprivate func map(_ x: Float, in_min: Float, in_max: Float, out_min: Float, out_max: Float) -> Float{ // restrict 'x' in 'in' range let x_in_range = in_min < in_max ? max(min(x, in_max), in_min) : max(min(x, in_min), in_max) return (x_in_range - in_min) * (out_max - out_min) / (in_max - in_min) + out_min } @IBAction func tapFind(_ sender: UIButton) { if Konashi.isConnected() { let alertController = UIAlertController(title: "Disconnect Konashi", message: "You are disconnecting \(Konashi.peripheralName()). Are you sure?", preferredStyle: .alert) let otherAction = UIAlertAction(title: "Disconnect", style: .default) { action in // LED2を消灯 Konashi.digitalWrite(KonashiDigitalIOPin.digitalIO1, value: KonashiLevel.low) // LEDが消灯するのに時間が必要なので遅延させる Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.disconnectKonashi), userInfo: nil, repeats: false) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { action in NSLog("[Konashi] Cancel disconnecting \(Konashi.peripheralName())") } // addActionした順に左から右にボタンが配置されます alertController.addAction(otherAction) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } else { Konashi.find() } } func disconnectKonashi() { NSLog("[Konashi] Disconnect \(Konashi.peripheralName())") // 接続解除 self.manualDisconnection = true Konashi.disconnect() } // Color @IBAction func changeHue(_ sender: UISlider) { setHue(sender.value) } fileprivate func setHue(_ val: Float) { hueLabel.text = "\(val)" hueSlider.setValue(val, animated: true) UD.set(CGFloat(val), forKey: UD_KEY_INSTRUMENT_COLOR_HUE) sendInstrumentColor() } @IBAction func changeSaturation(_ sender: UISlider) { setSaturation(sender.value) } fileprivate func setSaturation(_ val: Float) { saturationLabel.text = "\(val)" saturationSlider.setValue(val, animated: true) UD.set(CGFloat(val), forKey: UD_KEY_INSTRUMENT_COLOR_SATURATION) sendInstrumentColor() } @IBAction func tapBlack(_ sender: UIButton) { uart("i:000,000,000;\n") instrumentColor = UIColor(hue: 0.0, saturation: 0.0, brightness: 0.0, alpha: 1.0) colorView.backgroundColor = instrumentColor sendInstrumentColor() } @IBAction func changeHue2(_ sender: UISlider) { setHue2(sender.value) } func setHue2(_ val: Float) { hueLabel2.text = "\(val)" hueSlider2.setValue(val, animated: true) UD.set(CGFloat(val), forKey: UD_KEY_EFFECT_COLOR_HUE) sendEffectColor() } @IBAction func changeSaturation2(_ sender: UISlider) { setSaturation2(sender.value) } func setSaturation2(_ val: Float) { saturationLabel2.text = "\(val)" saturationSlider2.setValue(val, animated: true) UD.set(CGFloat(val), forKey: UD_KEY_EFFECT_COLOR_SATURATION) sendEffectColor() } @IBAction func tapBlack2(_ sender: UIButton) { uart("e:000,000,000;\n") effectColor = UIColor(hue: 0.0, saturation: 0.0, brightness: 0.0, alpha: 1.0) colorView2.backgroundColor = effectColor } @IBAction func changeBrightnessMin(_ sender: UISlider) { setBrightnessMin(sender.value) } func setBrightnessMin(_ val: Float) { brightnessLabel.text = "\(val)" sendBrightness() } @IBAction func changeDivide(_ sender: UISlider) { let val = Int(sender.value) UD.set(val, forKey: UD_KEY_LED_DIVIDE) divideLabel.text = "\(val)" sendDivide() } @IBAction func changePosition(_ sender: UISlider) { let val = Int(sender.value) UD.set(val, forKey: UD_KEY_LED_POSITION) positionLabel.text = "\(val)" sendPosition() } @IBAction func sendColorSettings(_ sender: UIButton) { sendInstrumentColor() sendEffectColor() sendDivide() sendPosition() } // Send to Konashi func sendInstrumentColor() { let hue = CGFloat(hueSlider.value) let saturation = CGFloat(saturationSlider.value) instrumentColor = UIColor(hue: hue, saturation: saturation, brightness: 1.0, alpha: 1.0) colorView.backgroundColor = instrumentColor let r = NSString(format: "%03d", Int(instrumentColor.getRed())) let g = NSString(format: "%03d", Int(instrumentColor.getGreen())) let b = NSString(format: "%03d", Int(instrumentColor.getBlue())) uart("i:\(r).\(g).\(b);") } func sendEffectColor() { let hue = CGFloat(hueSlider2.value) let saturation = CGFloat(saturationSlider2.value) effectColor = UIColor(hue: hue, saturation: saturation, brightness: 1.0, alpha: 1.0) colorView2.backgroundColor = effectColor let r = NSString(format: "%03d", Int(effectColor.getRed())) let g = NSString(format: "%03d", Int(effectColor.getGreen())) let b = NSString(format: "%03d", Int(effectColor.getBlue())) uart("e:\(r).\(g).\(b);") } func sendDivide() { uart("t:0;d:\(UD.integer(forKey: UD_KEY_LED_DIVIDE));") } func sendPosition() { uart("t:0;p:\(Float(UD.integer(forKey: UD_KEY_LED_POSITION))/100);") } func sendBrightness() { uart("b:\(self.brightnessSlider.value);") } // Tone @IBAction func tapToneName(_ sender: UIButton) { let initial: Int = toneDirs.index(of: toneNameBtn.titleLabel!.text!)! ActionSheetStringPicker.show(withTitle: "Tone", rows: toneDirs, initialSelection: initial, doneBlock: { picker, value, index in let key: String = index as! String self.initPlayers(key) return }, cancel: { ActionStringCancelBlock in return }, origin: sender) } // AVAudioPlayerNode の生成やAudioFileの設定 // その他のノードの初期化のために、最初のAudioFileのAVAudioFormatを返す @discardableResult func initPlayers(_ toneDir: String) -> AVAudioFormat!{ toneNameBtn.setTitle(toneDir, for: UIControlState()) var format: AVAudioFormat! = nil if 1<audioFiles.count { audioFiles.removeAll(keepingCapacity: false) } // cleanup players for player in players { if player.isPlaying { player.stop() } engine.disconnectNodeInput(player) } players.removeAll(keepingCapacity: false) // ------------ var items: [String] = []; do { items = try FM.contentsOfDirectory(atPath: "\(Bundle.main.resourcePath!)/tones/\(toneDir)") } catch { NSLog("Cannot load items !") } // wavファイル以外は無視 items = items.filter { (name: String) -> Bool in let regex = try! NSRegularExpression(pattern: ".wav$", options: []) return regex.firstMatch(in: name, options: [], range: NSMakeRange(0, name.utf8.count)) != nil } let itemsCount = items.count toneCountLabel.text = "\(itemsCount)" if 0 < itemsCount { // 左用の音かどうか判定(Lで終わっていたら左) let regex = try! NSRegularExpression(pattern: "L$", options: []) let isLeft: Bool = regex.firstMatch(in: toneDir, options: [], range: NSMakeRange(0, toneDir.utf8.count)) != nil let _tones = isLeft ? ["02","01"] : ["01","02"] // switch player type if itemsCount == 2 { setTonePlayerType(PlayerType.LongShot) for (_, file) in _tones.enumerated() { let filePath: String = Bundle.main.path(forResource: "tones/\(toneDir)/\(file)", ofType: "wav")! let fileURL: URL = URL(fileURLWithPath: filePath) do { let audioFile = try AVAudioFile(forReading: fileURL) let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat, frameCapacity: UInt32(audioFile.length)) do { try audioFile.read(into: audioFileBuffer) let player = AVAudioPlayerNode() engine.attach(player) engine.connect(player, to: mixer, format: audioFile.processingFormat) player.volume = 0.0 player.scheduleBuffer(audioFileBuffer, at: nil, options:.loops, completionHandler: nil) players += [player] if format == nil { format = audioFile.processingFormat } } catch { NSLog("Cannot AVAudioFile read") } } catch { NSLog("Cannot load audioFile !") } } } else { setTonePlayerType(PlayerType.OneShot) for i in 1..<itemsCount+1 { let num = NSString(format: "%02d", isLeft ? itemsCount+1 - i : i) // 左車輪の音だったら反転し、2桁で0埋め let url = Bundle.main.path(forResource: "tones/\(toneDir)/\(num)", ofType: "wav")! do { let audioFile = try AVAudioFile(forReading: URL(fileURLWithPath: url)) audioFiles += [audioFile] let player = AVAudioPlayerNode() engine.attach(player) engine.connect(player, to: mixer, format: audioFile.processingFormat) player.volume = 9.0 players += [player] if format == nil { format = audioFile.processingFormat } } catch { NSLog("Cannot init AVAudioFile") } } } // set layeredPlayer for (_, file) in _tones.enumerated() { var layeredTones: [String] = []; do { layeredTones = try FM.contentsOfDirectory(atPath: "\(Bundle.main.resourcePath!)/tones/\(toneDir)/layered") } catch { // do nothing NSLog("Cannot load layeredTones !") } if 0 < layeredTones.count { let filePath = Bundle.main.path(forResource: "tones/\(toneDir)/layered/\(file)", ofType: "wav")! let fileURL = URL(fileURLWithPath: filePath) do { let audioFile = try AVAudioFile(forReading: fileURL) let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat, frameCapacity: UInt32(audioFile.length)) do { try audioFile.read(into: audioFileBuffer) let player = AVAudioPlayerNode() engine.attach(player) engine.connect(player, to: mixer, format: audioFile.processingFormat) player.volume = 0.0 player.scheduleBuffer(audioFileBuffer, at: nil, options:.loops, completionHandler: nil) layeredPlayers += [player] } catch { NSLog("Cannot AVAudioFile read") } } catch{ NSLog("Cannot init AVAudioFile") } } } } sendPlayerType() // Color loadInstrumentColor(toneDir as NSString) return format } func setTonePlayerType(_ type: PlayerType) { playerType = type tonePlayerTypeLabel.text = type.rawValue } // Effect // ====== // Delay @IBAction func changeDelayWetDry(_ sender: UISlider) { setDelayWetDry(sender.value) } func setDelayWetDry(_ val: Float) { delay.wetDryMix = val delayDryWetLabel.text = "\(val)" } @IBAction func changeDelayDelayTime(_ sender: UISlider) { setDelayDelayTime(sender.value) } func setDelayDelayTime(_ val: Float) { delay.delayTime = TimeInterval(val) delayDelayTimeLabel.text = "\(val)" } @IBAction func changeDelayFeedback(_ sender: UISlider) { setDelayFeedback(sender.value) } func setDelayFeedback(_ val: Float) { delay.feedback = val delayFeedbackLabel.text = "\(val)" } @IBAction func changeDelayLowPassCutOff(_ sender: UISlider) { setDelayLowPassCutOff(sender.value) } func setDelayLowPassCutOff(_ val: Float) { delay.lowPassCutoff = val delayLowPassCutOffLabel.text = "\(val)" } // シリアル通信で送信 func uart(_ str: String){ if Konashi.isConnected() { // コマンド毎の連続送信時間で制限をかける(Bコマンドなどが大量に送られるとKonashiとの接続が切れる) let cmd = (str as NSString).substring(to: 1) if let lastCall = commandLastCalls[cmd] { if 0.1 < Float(Date().timeIntervalSince(lastCall)) { if Konashi.uartWrite(str) == KonashiResult.success { commandLastCalls[cmd] = Date() } } } else { if Konashi.uartWrite(str) == KonashiResult.success { commandLastCalls[cmd] = Date() } } } } func updateRotation(_ radian: Double) { if(updateRotationFlag) { return } updateRotationFlag = true let currentDeg = radiansToDegrees(radian) let variation = getVariation(currentDeg) arrow.transform = CGAffineTransform(rotationAngle: CGFloat(radian)) // 変化量 // 実際の車輪のスピードの範囲とうまくマッピングする // 実際にクルマイスに乗って試したところ前進でvariationは最大で5くらいだった let vol = 9.0 * min(abs(variation)/5,1) switch playerType { case PlayerType.OneShot: let passed_slit = slitIndexInRange(currentDeg) if 0 < passed_slit.count { let audioIndexes = Array(0..<audioFiles.count) var passed_players: Array<Int> = [] for i in current_index..<current_index+passed_slit.count { passed_players += [audioIndexes.get(i)!] } let _idx = current_index + passed_slit.count*(0<variation ? 1 : -1) current_index = audioFiles.relativeIndex(_idx) for index in passed_players { // Sound let audioFile: AVAudioFile = audioFiles[index] as AVAudioFile let player: AVAudioPlayerNode = players[index] as AVAudioPlayerNode if player.isPlaying { player.stop() } // playerにオーディオファイルを設定 ※ 再生直前にセットしないと再生されない? player.scheduleFile(audioFile, at: nil, completionHandler: nil) // 再生開始 player.play() // Konashi通信 uart("s:;") } } case PlayerType.LongShot: for player in players { if !player.isPlaying { player.play() } } for player in layeredPlayers { if !player.isPlaying { player.play() } } if(players.count == 2) { if 0 < variation { players[0].volume = 0 players[1].volume = vol } else { players[0].volume = vol players[1].volume = 0 } } // Konashi通信 let brightness = map(vol, in_min:0.0, in_max:9.0, out_min:0.2, out_max:1.0) uart("B:\(brightness);") } // layered players if 0 < variation { layeredPlayers[0].volume = 0 layeredPlayers[1].volume = vol*layeredPlayerVol } else { layeredPlayers[0].volume = vol*layeredPlayerVol layeredPlayers[1].volume = 0 } prevDeg = currentDeg updateRotationFlag = false } func radiansToDegrees(_ value: Double) -> Double { return value * 180.0 / .pi + 360.0 } // 0 <= value < 360 の範囲に値を収める fileprivate func restrict(_ value: Double) -> Double { var deg = value if deg < 0.0 { deg += 360 } else if 360 < deg { deg -= 360*(floor(deg/360)) } return deg } // 引数で与えた角度の中に含まれるスリットのindexを配列にして返す private func slitIndexInRange(_ currentDeg: Double) -> Array<Int> { if prevDeg == currentDeg { return [] } let _prev = restrict(prevDeg) let _current = restrict(currentDeg) let _min = min(_prev, _current) let _max = max(_prev, _current) var result: Array<Int> = [] // range内にあるslit var rest: Array<Int> = [] // range外にあるslit for i in 0..<SLIT_COUNT { let slit = playerPoints[i] if _min <= slit && slit <= _max { result += [i] } else { rest += [i] } } // 回転が早く通過slitが多い場合は、どちら向きか判定しにくいので、数の少ない方を返す return ((rest.count < result.count) ? rest : result) } // 変化量を計算(359°->2°などに変化した時に正しく回転方向を算出) // [left wheel] forward: plus, back: minus // [right wheel] forward: minus, back: plus private func getVariation(_ currentDeg: Double) -> Float { let diff = abs(prevDeg - currentDeg) if 180 < diff { if 180 < prevDeg { return Float((360 - prevDeg) + currentDeg) } else { return Float((360.0 - currentDeg) + prevDeg) } } return Float(prevDeg - currentDeg) } } internal extension Array { // If the index is out of bounds it's assumed relative func relativeIndex (_ index: Int) -> Int { var _index = (index % count) if _index < 0 { _index = count + _index } return _index } func get (_ index: Int) -> Element? { let _index = relativeIndex(index) return _index < count ? self[_index] : nil } } // // http://qiita.com/KeitaMoromizato/items/59cb25925642822c6ec9 // 経過時間を調べる class ElapsedTimeCounter { class var instance: ElapsedTimeCounter { struct Static { static let instance = ElapsedTimeCounter() } return Static.instance } fileprivate var lastDate: Date? func getMillisec() -> Int? { let now = Date() if let date = lastDate { let elapsed = now.timeIntervalSince(date) lastDate = now return Int(elapsed * 1000.0) } lastDate = now return nil } }
mit
4dd6db0c87e8ab8b9b455e0bdcd2aa69
30.970233
175
0.620286
3.704247
false
false
false
false
wireapp/wire-ios
Wire-iOS Tests/CallStatusViewTests.swift
1
9782
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire struct MockStatusViewConfiguration: CallStatusViewInputType { var state: CallStatusViewState var isVideoCall: Bool var variant: ColorSchemeVariant var isConstantBitRate: Bool let title: String let userEnabledCBR: Bool let isForcedCBR: Bool var classification: SecurityClassification } final class CallStatusViewTests: ZMSnapshotTestCase { private var sut: CallStatusView! override func setUp() { super.setUp() snapshotBackgroundColor = .white sut = CallStatusView(configuration: MockStatusViewConfiguration(state: .connecting, isVideoCall: false, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none)) sut.translatesAutoresizingMaskIntoConstraints = false sut.widthAnchor.constraint(equalToConstant: 320).isActive = true sut.setNeedsLayout() sut.layoutIfNeeded() } override func tearDown() { sut = nil super.tearDown() } func testLongTitleMargins() { // When sut.configuration = MockStatusViewConfiguration( state: .connecting, isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Amazing Way Too Long Group Conversation Name", userEnabledCBR: false, isForcedCBR: false, classification: .none ) // Then verify(view: sut) } func testConnectingAudioCallLight() { // When sut.configuration = MockStatusViewConfiguration(state: .connecting, isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testConnectingAudioCallDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .connecting, isVideoCall: false, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testIncomingAudioLight() { // When sut.configuration = MockStatusViewConfiguration(state: .ringingIncoming(name: "Ulrike"), isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testIncomingAudioLightOneOnOne() { // When sut.configuration = MockStatusViewConfiguration(state: .ringingIncoming(name: nil), isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Miguel", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testIncomingAudioDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .ringingIncoming(name: "Ulrike"), isVideoCall: false, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testIncomingVideoLight() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .ringingIncoming(name: "Ulrike"), isVideoCall: true, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testIncomingVideoDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .ringingIncoming(name: "Ulrike"), isVideoCall: true, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testOutgoingLight() { // When sut.configuration = MockStatusViewConfiguration(state: .ringingOutgoing, isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testOutgoingDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .ringingOutgoing, isVideoCall: true, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testEstablishedBriefLight() { // When sut.configuration = MockStatusViewConfiguration(state: .established(duration: 42), isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testEstablishedBriefDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .established(duration: 42), isVideoCall: true, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testEstablishedLongLight() { // When sut.configuration = MockStatusViewConfiguration(state: .established(duration: 321), isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testEstablishedLongDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .established(duration: 321), isVideoCall: true, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testConstantBitRateLight() { // When sut.configuration = MockStatusViewConfiguration(state: .established(duration: 321), isVideoCall: false, variant: .light, isConstantBitRate: true, title: "Italy Trip", userEnabledCBR: true, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testConstantBitRateDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .established(duration: 321), isVideoCall: true, variant: .dark, isConstantBitRate: true, title: "Italy Trip", userEnabledCBR: true, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testVariableBitRateLight() { // When sut.configuration = MockStatusViewConfiguration(state: .established(duration: 321), isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: true, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testVariableBitRateDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .established(duration: 321), isVideoCall: true, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: true, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testReconnectingLight() { // When sut.configuration = MockStatusViewConfiguration(state: .reconnecting, isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testReconnectingDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .reconnecting, isVideoCall: true, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testEndingLight() { // When sut.configuration = MockStatusViewConfiguration(state: .terminating, isVideoCall: false, variant: .light, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } func testEndingDark() { // When snapshotBackgroundColor = .black sut.configuration = MockStatusViewConfiguration(state: .terminating, isVideoCall: true, variant: .dark, isConstantBitRate: false, title: "Italy Trip", userEnabledCBR: false, isForcedCBR: false, classification: .none) // Then verify(view: sut) } }
gpl-3.0
47260e1ca9d2f7f4ceecfeba440f3381
38.443548
246
0.680842
4.592488
false
true
false
false
exponent/exponent
packages/expo-dev-menu/ios/Tests/DevMenuExpoApiClientTests.swift
2
8886
import XCTest @testable import EXDevMenu private class MockedDataTask: URLSessionDataTask { private let completionHandler: () -> Void init(_ completionHandler: @escaping () -> Void) { self.completionHandler = completionHandler super.init() } override func resume() { completionHandler() } } private class MockedSession: URLSession { var requestInspector: (URLRequest) -> Void = { _ in } var completionHandlerSeeder: ((Data?, URLResponse?, Error?) -> Void) -> Void = { $0(nil, nil, nil) } override func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { requestInspector(request) return MockedDataTask { self.completionHandlerSeeder(completionHandler) } } } class DevMenuExpoApiClientTests: XCTestCase { func test_queryDevSessionsAsync() { let expectedData = Data() let expect = expectation(description: "request callback should be called") let apiClient = DevMenuExpoApiClient() let mockedSession = MockedSession() mockedSession.requestInspector = { XCTAssertEqual($0.url?.absoluteString, "https://exp.host/--/api/v2/development-sessions") XCTAssertEqual($0.httpMethod, "GET") } mockedSession.completionHandlerSeeder = { $0(expectedData, nil, nil) } apiClient.session = mockedSession apiClient.queryDevSessionsAsync(nil, completionHandler: { data, _, _ in XCTAssertIdentical(data as AnyObject, expectedData as AnyObject) expect.fulfill() }) waitForExpectations(timeout: 0) } func test_queryDevSessionsAsync_installationID() { let expectedData = Data() let expect = expectation(description: "request callback should be called") let apiClient = DevMenuExpoApiClient() let mockedSession = MockedSession() mockedSession.requestInspector = { XCTAssertEqual($0.url?.absoluteString, "https://exp.host/--/api/v2/development-sessions?deviceId=test-installation-id") XCTAssertEqual($0.httpMethod, "GET") } mockedSession.completionHandlerSeeder = { $0(expectedData, nil, nil) } apiClient.session = mockedSession apiClient.queryDevSessionsAsync("test-installation-id", completionHandler: { data, _, _ in XCTAssertIdentical(data as AnyObject, expectedData as AnyObject) expect.fulfill() }) waitForExpectations(timeout: 0) } func test_if_isLoggedIn_returns_correct_values() { let apiClient = DevMenuExpoApiClient() XCTAssertFalse(apiClient.isLoggedIn()) apiClient.sessionSecret = "secret" XCTAssertTrue(apiClient.isLoggedIn()) } func test_if_session_token_is_attached_to_the_request() { let expect = expectation(description: "request callback should be called") let apiClient = DevMenuExpoApiClient() apiClient.sessionSecret = "secret" let mockedSession = MockedSession() mockedSession.requestInspector = { XCTAssertEqual($0.value(forHTTPHeaderField: "expo-session"), "secret") } apiClient.session = mockedSession apiClient.queryDevSessionsAsync(nil, completionHandler: { _, _, _ in expect.fulfill() }) waitForExpectations(timeout: 0) } func test_if_queryUpdateBranches_converts_response_to_object() { let serverResponse = """ { "data": { "app": { "byId": { "updateBranches": [ { "id": "0455d584-9130-4b7a-a9c0-f20bffe4ffb4", "updates": [ { "id": "04264159-e4d4-4085-8633-24400e1188dd", "runtimeVersion": "1", "platform": "android", "message": "Update 2", "updatedAt": "2021-04-07T09:46:37.803Z", "createdAt": "2021-04-07T09:46:37.803Z" }, { "id": "14fccc96-9d7f-4689-a69f-8de9ad207c53", "runtimeVersion": "1", "platform": "ios", "message": "Update 2", "updatedAt": "2021-04-07T09:46:37.803Z", "createdAt": "2021-04-07T09:46:37.803Z" }, { "id": "07b89cef-fdf8-40f6-9ba1-0827f46bbd75", "runtimeVersion": "1", "platform": "android", "message": "Update 1", "updatedAt": "2021-04-07T09:43:06.917Z", "createdAt": "2021-04-07T09:43:06.917Z" }, { "id": "f45db62a-221e-45c1-b340-7ab5cfa097a1", "runtimeVersion": "1", "platform": "ios", "message": "Update 1", "updatedAt": "2021-04-07T09:43:06.917Z", "createdAt": "2021-04-07T09:43:06.917Z" } ] } ] } } } } """.data(using: .utf8) let expect = expectation(description: "request callback should be called") let apiClient = DevMenuExpoApiClient() let mockedSession = MockedSession() mockedSession.completionHandlerSeeder = { $0(serverResponse, nil, nil) } mockedSession.requestInspector = { XCTAssertEqual($0.httpMethod, "POST") } apiClient.session = mockedSession apiClient.queryUpdateBranches(appId: "app_id", completionHandler: { branches, _, error in XCTAssertNil(error) let branches = branches! XCTAssertEqual(branches.count, 1) let branch = branches[0] XCTAssertEqual(branch.id, "0455d584-9130-4b7a-a9c0-f20bffe4ffb4") XCTAssertEqual(branch.updates.count, 4) XCTAssertEqual(branch.updates[0].id, "04264159-e4d4-4085-8633-24400e1188dd") XCTAssertEqual(branch.updates[0].createdAt, "2021-04-07T09:46:37.803Z") XCTAssertEqual(branch.updates[0].updatedAt, "2021-04-07T09:46:37.803Z") XCTAssertEqual(branch.updates[0].platform, "android") XCTAssertEqual(branch.updates[0].runtimeVersion, "1") expect.fulfill() }) waitForExpectations(timeout: 0) } func test_if_queryUpdateChannels_converts_response_to_object() { let serverResponse = """ { "data": { "app": { "byId": { "updateChannels": [ { "name": "main", "id": "a7c1bad5-1d21-4930-8660-f56b9cfc10bc", "createdAt": "2021-04-01T08:37:05.013Z", "updatedAt": "2021-04-01T08:37:05.013Z" } ] } } } } """.data(using: .utf8) let expect = expectation(description: "request callback should be called") let apiClient = DevMenuExpoApiClient() let mockedSession = MockedSession() mockedSession.completionHandlerSeeder = { $0(serverResponse, nil, nil) } mockedSession.requestInspector = { XCTAssertEqual($0.httpMethod, "POST") } apiClient.session = mockedSession apiClient.queryUpdateChannels(appId: "app_id", completionHandler: { updates, _, error in XCTAssertNil(error) let updates = updates! XCTAssertEqual(updates.count, 1) let update = updates[0] XCTAssertEqual(update.id, "a7c1bad5-1d21-4930-8660-f56b9cfc10bc") XCTAssertEqual(update.name, "main") XCTAssertEqual(update.createdAt, "2021-04-01T08:37:05.013Z") XCTAssertEqual(update.updatedAt, "2021-04-01T08:37:05.013Z") expect.fulfill() }) waitForExpectations(timeout: 0) } func test_if_client_do_not_parse_response_if_error_is_present() { let serverResponse = """ { "data": { "app": { "byId": { "updateChannels": [ { "name": "main", "id": "a7c1bad5-1d21-4930-8660-f56b9cfc10bc", "createdAt": "2021-04-01T08:37:05.013Z", "updatedAt": "2021-04-01T08:37:05.013Z" } ] } } } } """.data(using: .utf8) let expect = expectation(description: "request callback should be called") let apiClient = DevMenuExpoApiClient() let mockedSession = MockedSession() mockedSession.completionHandlerSeeder = { $0(serverResponse, nil, NSError(domain: "Error", code: 123, userInfo: nil)) } mockedSession.requestInspector = { XCTAssertEqual($0.httpMethod, "POST") } apiClient.session = mockedSession apiClient.queryUpdateChannels(appId: "app_id", completionHandler: { updates, _, error in XCTAssertNil(updates) XCTAssertNotNil(error) expect.fulfill() }) waitForExpectations(timeout: 0) } }
bsd-3-clause
38c26900e58ed71f8243d76f85471b41
31.549451
142
0.589467
4.057534
false
true
false
false
leannenorthrop/markdown-swift
Markdown/GruberDialect.swift
1
37449
// // GruberDialect.swift // Markdown // // Created by Leanne Northrop on 16/06/2015. // Copyright (c) 2015 Leanne Northrop. All rights reserved. // import Foundation import Markdown class GruberDialect : Dialect { // Key values determine block handler orders static let ATX_HEADER_HANDLER_KEY = "0_atxHeader" static let EXT_HEADER_HANDLER_KEY = "1_extHeader" static let HORZ_RULE_HANDLER_KEY = "3_horizRule" static let CODE_HANDLER_KEY = "4_code" static let BLOCK_QUOTE_HANDLER_KEY = "5_block_quote" static let DEF_LIST_HANDLER_KEY = "6_def_list" static let LIST_HANDLER_KEY = "7_list" static let PARA_HANDLER_KEY = "9_para" static let __escape__ = "^\\\\[\\\\\\`\\*_{}<>\\[\\]()#\\+.!\\-]" override init() { super.init() self.__inline_call__ = { (str : String, pattern : String?) -> [AnyObject] in var out : [AnyObject] = [] if pattern != nil { var text : String = str var res : [AnyObject] = [] while ( count(text) > 0 ) { res = super.oneElement(text, patterns: pattern!) var strCount = res.removeAtIndex(0) as! Int text = strCount >= count(text) ? "" : text.substr(strCount) for element in res { if out.isEmpty { out.append(element) } else { if element as? String != nil && out.last as? String != nil { var s : String = out.removeLast() as! String s += element as! String out.append(s) } else { out.append(element) } } } } } return out } self.block[GruberDialect.ATX_HEADER_HANDLER_KEY] = { (block : Line, inout next : Lines) -> [AnyObject]? in var regEx = "^(#{1,6})\\s*(.*?)\\s*#*\\s*(?:\n|$)" if !block._text.isMatch(regEx) { return nil } else { var matches = block._text.matches(regEx) var level : Int = count(matches[1]) var header : [AnyObject] = ["header", ["level": String(level)]] var processedHeader = self.processInline(matches[2], patterns: nil) if (processedHeader.count == 1 && processedHeader[0] as? String != nil) { header.append(processedHeader[0] as! String) } else { header.append(processedHeader) } if (count(matches[0]) < count(block._text)) { var l = Line(text: block._text.substr(count(matches[0])), lineNumber: block._lineNumber + 2, trailing:block._trailing) next.unshift(l) } return [header] } } self.block[GruberDialect.EXT_HEADER_HANDLER_KEY] = { (block : Line, inout next : Lines) -> [AnyObject]? in var regEx = "^(.*)\n([-=])\\2\\2+(?:\n|$)" if !block._text.isMatch(regEx) { return nil } var matches = block._text.matches(regEx) var level = (matches[2] == "=") ? 1 : 2 var header : [AnyObject] = ["header", ["level" : String(level)]] var processedHeader = self.processInline(matches[1], patterns: nil) if (processedHeader.count == 1 && processedHeader[0] as? String != nil) { header.append(processedHeader[0] as! String) } else { header.append(processedHeader) } var length : Int = count(matches[0]) if length < count(block._text) { next.unshift(Line(text: block._text.substr(length), lineNumber: block._lineNumber + 2, trailing: block._trailing)) } return [header] } self.block[GruberDialect.HORZ_RULE_HANDLER_KEY] = { (block : Line, inout next : Lines) -> [AnyObject]? in let regEx = "^(?:([\\s\\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\\2){2,}[ \t]*(?:\n([\\s\\S]*))?$" if !block._text.isMatch(regEx) { return nil } // this needs to find any hr in the block to handle abutting blocks var matches = block._text.matches(regEx) var jsonml : [AnyObject] = [["hr"]] // if there's a leading abutting block, process it if matches.count >= 2 { var contained = matches[1] if count(contained) > 0 { var nodes = super.toTree(contained, root: [] ) jsonml = [nodes,["hr"]] } } // if there's a trailing abutting block, stick it into next if matches.count >= 4 { if count(matches[3]) > 0 { next.unshift(Line(text: matches[3], lineNumber: block._lineNumber + 1, trailing: block._trailing)) } } return jsonml } self.block[GruberDialect.CODE_HANDLER_KEY] = { (block : Line, inout next : Lines) -> [AnyObject]? in // | Foo // |bar // should be a code block followed by a paragraph. Fun // // There might also be adjacent code block to merge. var text = block._text var ret : [String] = [] let regEx = "^(?: {0,3}\t| {4})(.*)\n?" // 4 spaces + content if !text.isMatch(regEx) { return ret } do { // Now pull out the rest of the lines var b = super.loop_re_over_block(regEx, block: text, cb: { (m : [String]) -> () in ret.append(m[1]) }) if count(b) > 0 { // Case alluded to in first comment. push it back on as a new block next.unshift(Line(text: b, lineNumber: block._lineNumber, trailing: block._trailing)) break } else if !next.isEmpty() { // Check the next block - it might be code too if !next.line(0)._text.isMatch(regEx) { break } // Pull how how many blanks lines follow - minus two to account for .join ret.append(block._trailing.replaceByRegEx("[^\\n]", replacement: "").substr(2)) let line = next.shift() if line != nil { text = line!._text } } else { break } } while true return [["code_block", "\n".join(ret)]] } self.block[GruberDialect.PARA_HANDLER_KEY] = { (block : Line, inout next : Lines) -> [AnyObject]? in var arr : [AnyObject] = ["para"] arr += self.processInline(block._text, patterns: nil) return [arr] } /*self.block[GruberDialect.LIST_HANDLER_KEY] = { [unowned self] (var block : Line, inout next : Lines) -> [AnyObject]? in var any_list = "[*+-]|\\d+\\." var bullet_list = "[*+-]" // Capture leading indent as it matters for determining nested lists. var is_list_re = "^( {0,3})(" + any_list + ")[ \t]+" var indent_re = "(?: {0,3}\\t| {4})" // TODO: Cache this regexp for certain depths. // Create a regexp suitable for matching an li for a given stack depth func regex_for_depth(depth : Int) -> String { // m[1] = indent, m[2] = list_type m[3] = cont return "(?:^(\(indent_re){0,\(depth)} {0,3})(\(any_list))\\s+)|(^\(indent_re){0,\(depth-1)}[ ]{0,4})" } func expand_tab(input : String) -> String { return input.replaceByRegEx(" {0,3}\t", replacement: " " ) } // Add inline content `inline` to `li`. inline comes from processInline // so is an array of content func add(inout li:[AnyObject], loose : Bool, inout inline : [AnyObject], nl : String?) { if loose { var nextLi : [AnyObject] = ["para"] nextLi.extend(inline) li.append(nextLi) return } if li.count < 0 { return } // Hmmm, should this be any block level element or just paras? var lastItem : AnyObject = li[li.count-1] var add_to : [AnyObject] if (lastItem is [AnyObject]) && (lastItem[0] === "para") { add_to = lastItem as! [AnyObject] } else { add_to = li } // If there is already some content in this list, add the new line in if nl != nil && (li.count > 1) { inline.insert(nl!, atIndex: 0) } for var i = 0; i < inline.count; i++ { var what: AnyObject = inline[i] var is_str = what is String var endItem: AnyObject = add_to[add_to.count-1] if ( is_str && add_to.count > 1 && endItem is String) { add_to[add_to.count-1] = (endItem as! String) + (what as! String) } else { add_to.append(what) } } } // contained means have an indent greater than the current one. On // *every* line in the block func get_contained_blocks(depth : Int, inout blocks : Lines) -> Lines { var re = "^(\(indent_re){\(depth)}.*?\\n?)*$" var replace = "^\(indent_re){\(depth)}" var ret = Lines() while !blocks.isEmpty() { if blocks.line(0)._text.isMatch(re) { var b : Line = blocks.shift()! // Now remove that indent var x = b._text.replaceByRegEx(replace, replacement: "") ret.unshift(Line(text: x, lineNumber: b._lineNumber, trailing: b._trailing)) } else { break } } return ret } // passed to stack.forEach to turn list items up the stack into paras func paragraphify(inout s : [String:AnyObject], i : Int, stack : [AnyObject]) { /*var list = s["list"] as! [AnyObject] var last_li = list[list.count-1] var item : [AnyObject]? = last_li[1] as? [AnyObject] if (item != nil) { var s = item[0] as? String if (s === "para") { return } } todo if ( i + 1 === stack.count ) { // Last stack frame // Keep the same array, but replace the contents last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ) ); } else { var sublist = last_li.pop(); last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ), sublist ); }*/ } func make_list(matches : [String], inout s : [AnyObject]) -> [AnyObject] { var list = matches[2].isMatch(bullet_list) ? ["bulletlist"] : ["numberlist"] s.append(["list" : list, "indent": matches[1]]) return list } if !block._text.isMatch(is_list_re) { return [] } var matches = block._text.matches(is_list_re) var stack : [AnyObject] = [] // Stack of lists for nesting. var list = make_list(matches, &stack) var last_li : [AnyObject] = [] var loose = false var ret : [AnyObject] = [list] var i:Int // Loop to search over block looking for inner block elements and loose lists loose_search: while true { // Split into lines preserving new lines at end of line var listlines = block._text.split("\n") listlines.map({$0 + "\n"}) // We have to grab all lines for a li and call processInline on them // once as there are some inline things that can span lines. var li_accumulate = "" var nl = "" // Loop over the lines in this block looking for tight lists. tight_search: for var line_no = 0; line_no < listlines.count; line_no++ { nl = "" var l = listlines[line_no] if l.isMatch("^\n") { nl = "\n" l = "" } // TODO: really should cache this var line_re = regex_for_depth(stack.count) matches = l.matches(line_re) //print( "line:", uneval(l), "\nline match:", uneval(m) ); // We have a list item if matches[1] != "" { // Process the previous list item, if any if count(li_accumulate) > 0 { //todo add( last_li, loose, this.processInline( li_accumulate ), nl ); ************************************** // Loose mode will have been dealt with. Reset it loose = false li_accumulate = "" } matches[1] = expand_tab(matches[1]) var d = Double(count(matches[1])/4) var wanted_depth = Int(floor(d))+1 println("want:\(wanted_depth) stack:\(stack.count)") if wanted_depth > stack.count { // Deep enough for a nested list outright //print ( "new nested list" ); list = make_list(matches, &stack) last_li.append(list) //last_li = list[1] = [ "listitem" ];*************************************************************** } else { // We aren't deep enough to be strictly a new level. This is // where Md.pl goes nuts. If the indent matches a level in the // stack, put it there, else put it one deeper then the // wanted_depth deserves. var found = false for ( i = 0; i < stack.count; i++ ) { //if ( stack[ i ]["indent"] != matches[1] ) { // continue //} //list = stack[i]["list"] //stack.splice( i+1, stack.length - (i+1) );**************************************************** found = true break } if (!found) { //print("not found. l:", uneval(l)); wanted_depth++; if wanted_depth <= stack.count { //stack.splice(wanted_depth, stack.count - wanted_depth) //print("Desired depth now", wanted_depth, "stack:", stack.length); //list = stack[wanted_depth-1]["list"] //print("list:", uneval(list) ); } else { //print ("made new stack for messy indent"); list = make_list(matches, &stack) last_li.append(list) } } //print( uneval(list), "last", list === stack[stack.length-1].list ); last_li = [ "listitem" ] list.append(last_li) } // end depth of shenegains nl = ""; } // Add content if count(l) > count(matches[0]) { li_accumulate += nl + l.substr(count(matches[0])) } } // tight_search if count(li_accumulate) > 0{ var emptyLines = Lines() var contents = self.processBlock(Line(text:li_accumulate, lineNumber:0, trailing:""), next: &emptyLines) if contents != nil { //firstBlock = contents![0] //firstBlock.removeAtIndex(0) var arr : [AnyObject] = [0,1] //arr.extend(firstBlock) //contents.splice.apply(contents, [0, 1].concat(firstBlock));***************************************** //add( last_li, loose, contents, nl ); // Let's not creating a trailing \n after content in the li //if last_li[last_li.count-1] === "\n" { // last_li.removeLast() //} // Loose mode will have been dealt with. Reset it loose = false li_accumulate = "" } } // Look at the next block - we might have a loose list. Or an extra // paragraph for the current li var contained = get_contained_blocks(stack.count, &next) // Deal with code blocks or properly nested lists if !contained.isEmpty() { // Make sure all listitems up the stack are paragraphs var j : Int = 0 for item in stack { var s : [String:AnyObject] = item as! [String:AnyObject] paragraphify(&s, j++, stack) } last_li.append(self.toTree(contained.text(), root:[])) } var next_block = "" if !next.isEmpty() { next_block = next.line(0)._text } if next_block.isMatch(is_list_re) || next_block.isMatch("^ ") { block = next.shift()! // Check for an HR following a list: features/lists/hr_abutting /*var hr = this.dialect.block.horizRule.call( this, block, next );*************************************** if ( hr ) { ret.push.apply(ret, hr); break; } // Add paragraphs if the indentation level stays the same if (stack[stack.length-1].indent === block.match("^\s*")[0]) { forEach( stack, paragraphify, this); }*/ loose = true; continue loose_search; } break } // loose_search return ret }*/ self.block[GruberDialect.DEF_LIST_HANDLER_KEY] = { [unowned self] (var block : Line, inout next : Lines) -> [AnyObject]? in var regEx = "^\\s*\\[([^\\[\\]]+)\\]:\\s*(\\S+)(?:\\s+(?:(['\"])(.*)\\3|\\((.*?)\\)))?\n?" // interesting matches are [ , ref_id, url, , title, title ] if !block._text.isMatch(regEx) { return [] } var b = self.loop_re_over_block(regEx, block: block._text) { (matches: [String]) -> () in self.create_reference(matches) } if count(b) > 0 { next.unshift(Line(text:b,lineNumber:0,trailing:block._trailing)) } return [] } self.block[GruberDialect.BLOCK_QUOTE_HANDLER_KEY] = { (var block : Line, inout next : Lines) -> [AnyObject]? in // Handle quotes that have spaces before them var text = block._text var m = text.matches("(^|\n) +(\\>[\\s\\S]*)") if !m.isEmpty && (m.count >= 3) && (count(m[2]) > 0) { var blockContents = text.replaceByRegEx("(^|\n) +\\>", replacement: ">"); next.unshift(Line(text: blockContents, lineNumber: block._lineNumber, trailing: block._trailing)) return [] } if !text.isMatch("^>") { return [] } var jsonml : [AnyObject] = [] // separate out the leading abutting block, if any. I.e. in this case: // // a // > b // if !text.isMatch("^>") { var newLines = text.split("\n") var prev : [Line] = [] var line_no = block._lineNumber; // keep shifting lines until you find a crotchet while !newLines.isEmpty && !newLines[0].isMatch("^>") { prev.append(Line(text: newLines.removeAtIndex(0), lineNumber: 0, trailing: "\n")) line_no++ } var abutting = Line(text: prev.reduce("", combine: {$0 + "\n" + $1._text}), lineNumber: block._lineNumber, trailing: "\n") var emptyNextLines = Lines() jsonml.append(self.processBlock(abutting, next: &emptyNextLines)!) // reassemble new block of just block quotes! block = Line(text: "\n".join(newLines), lineNumber: line_no, trailing: block._trailing) text = block._text } // if the next block is also a blockquote merge it in while !next.isEmpty() && next.line(0)._text.isMatch("$>") { var b = next.shift()! block = Line(text: text + block._trailing + b._text, lineNumber: block._lineNumber, trailing: b._trailing) text = block._text } // Strip off the leading "> " and re-process as a block. var input = text.replaceByRegEx("^> ?", replacement: "").replace("\n>", replacement: "\n") var old_tree = self.tree var processedBlock = self.toTree(input, root: ["blockquote"]) /*var attr = self.extract_attr( processedBlock ) // If any link references were found get rid of them if ( attr && attr.references ) { delete attr.references; // And then remove the attribute object if it's empty if ( isEmpty( attr ) ) processedBlock.splice( 1, 1 ); }*/ jsonml.append(processedBlock) return jsonml } // These characters are interesting elsewhere, so have rules for them so that // chunks of plain text blocks don't include them self.inline["]"] = { (text : String) -> [AnyObject] in return [] } self.inline["}"] = { (text : String) -> [AnyObject] in return [] } self.inline["\\"] = { (var text : String) -> [AnyObject] in // [ length of input processed, node/children to add... ] // Only esacape: \ ` * _ { } [ ] ( ) # * + - . ! if text.isMatch(GruberDialect.__escape__) { let idx1 = advance(text.startIndex, 1) var str : String = String(text.removeAtIndex(idx1)) return [2, str] } else { // Not an esacpe return [1, "\\"] } } self.inline["!["] = { [unowned self] (text : String) -> [AnyObject] in // Unlike images, alt text is plain text only. no other elements are // allowed in there // ![Alt text](/path/to/img.jpg "Optional title") // 1 2 3 4 <--- captures // // First attempt to use a strong URL regexp to catch things like parentheses. If it misses, use the // old one. let newRegExPattern = "^!\\[(.*?)][ \\t]*\\((" + self.URL_REG_EX + ")\\)([ \\t])*([\"'].*[\"'])?" let oldRegExPattern = "^!\\[(.*?)\\][ \\t]*\\([ \\t]*([^\")]*?)(?:[ \\t]+([\"'])(.*?)\\3)?[ \\t]*\\)" let matchesNewRegEx = text.isMatch(newRegExPattern) let matchesOldRegEx = text.isMatch(oldRegExPattern) if matchesNewRegEx || matchesOldRegEx { var m : [String] = matchesNewRegEx ? text.matches(newRegExPattern) : text.matches(oldRegExPattern) if m.count > 2 && !m[2].isBlank() { var m2 = m[2] if m2.isMatch("^<") && m2.isMatch(">$") { m[2] = m2.substr(1, length: count(m2)-1) } } var processedText = self.processInline(m[2], patterns: "\\") m[2] = processedText.count == 0 ? "" : processedText[0] as! String var attrs : [String:String] = ["alt" : m[1], "href" : m[2]] if m.count > 5 && !m[4].isBlank() { attrs["title"] = m[4] } return [count(m[0]), ["img", attrs]] } // ![Alt text][id] if text.isMatch("^!\\[(.*?)\\][ \\t]*\\[(.*?)\\]"){ var m = text.matches("^!\\[(.*?)\\][ \\t]*\\[(.*?)\\]") // We can't check if the reference is known here as it likely wont be // found till after. Check it in md tree->hmtl tree conversion return [count(m[0]), ["img_ref", ["alt" : m[1], "ref" : m[2].lowercaseString, "original" : m[0]]]] } // Just consume the '![' return [2, "!["] } self.inline["["] = { [unowned self] (var text : String) -> [AnyObject] in var open = 1; for c in text { if (c == "[") { open++; } if (c == "]") { open--; } if (open > 3) { return [1, "["] } } var orig = String(text); // Inline content is possible inside `link text` var linkText:String = text.substr(1) var res = self.inline_until_char(linkText, want: "]") // No closing ']' found. Just consume the [ var index = res[0] as! Int if index > count(linkText) { var result : [AnyObject] = [index + 1, "["] result += res[2] as! [AnyObject] return result } // empty link if index == 1 { return [ 2, "[]" ] } var consumed = 1 + index var children = res[1] as! [AnyObject] var link : [AnyObject] = [] var attrs : [String:String] = [:] // At this point the first [...] has been parsed. See what follows to find // out which kind of link we are (reference or direct url) text = text.substr(consumed) // [link text](/path/to/img.jpg "Optional title") // 1 2 3 <--- captures // This will capture up to the last paren in the block. We then pull // back based on if there a matching ones in the url // ([here](/url/(test)) // The parens have to be balanced let regEx = "^\\s*\\([ \\t]*([^\"']*)(?:[ \\t]+([\"'])(.*?)\\2)?[ \\t]*\\)" if text.isMatch(regEx) { var m = text.matches(regEx) var url = m[1].replaceByRegEx("\\s+$", replacement: "") consumed += count(m[0]) var urlCount = count(url) if (urlCount > 0) { if url.isMatch("^<") && url.isMatch(">$") { url = url.substr(1, length: urlCount - 1) } } // If there is a title we don't have to worry about parens in the url if m.count < 3 { var open_parens = 1 // One open that isn't in the capture for var len : Int = 0; len < urlCount; len++ { var firstChar : String = url![len] switch firstChar { case "(": open_parens++ case ")": if --open_parens == 0 { consumed -= urlCount - len url = url.substr(0, length: len) } default: println(firstChar) } } } // Process escapes only url = self.__inline_call__(url, "\\")[0] as! String attrs = ["href": url] if m.count >= 3 { attrs["title"] = m[3] as String } link = ["link", attrs] link.extend(children) return [consumed, link] } // [Alt text][id] // [Alt text] [id] if text.isMatch("^\\s*\\[(.*?)\\]"){ var m = text.matches("^\\s*\\[(.*?)\\]") consumed += count(m[0]) // [links][] uses links as its reference var ref = children.reduce("", combine: {$0 + $1.description}) if m.count >= 2 { ref = m[1] } attrs = ["ref" : ref.lowercaseString, "original" : orig.substr(0, length: consumed)] if children.count > 0 { link = ["link_ref", attrs] link.extend(children) // We can't check if the reference is known here as it likely wont be // found till after. Check it in md tree->hmtl tree conversion. // Store the original so that conversion can revert if the ref isn't found. return [consumed, link] } } // Another check for references var regExp = "^\\s*\\[(.*?)\\]:\\s*(\\S+)(?:\\s+(?:(['\"])(.*?)\\3|\\((.*?)\\)))?\\n?" if orig.isMatch(regExp) { var m : [String] = orig.matches(regExp) self.create_reference(m) return [count(m[0])] } // [id] // Only if id is plain (no formatting.) if ( children.count == 1 && children[0] is String) { var id = children[0] as! String var normalized = id.lowercaseString.replaceByRegEx("\\s+", replacement: " ") attrs = ["ref" : normalized, "original" : orig.substr(0, length: consumed)] link = ["link_ref", attrs, id] return [consumed, link] } // Just consume the "[" return [1, "["] } self.inline["<"] = { (text : String) -> [AnyObject] in if text.isMatch("^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\\.[a-zA-Z]+))>") { let m = text.matches("^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\\.[a-zA-Z]+))>") if m.count == 4 && !m[3].isBlank() { return [count(m[0]), [ "link", ["href": "mailto:" + m[3]], m[3]]] } else if m.count > 3 && m[2] == "mailto" { return [count(m[0]), [ "link", ["href": m[1]], m[1].substr(count("mailto:"))]] } else { return [count(m[0]), [ "link", ["href": m[1]], m[1]]] } } return [1, "<"] } self.inline["`"] = { (text : String) -> [AnyObject] in // Inline code block. as many backticks as you like to start it // Always skip over the opening ticks. var regEx = "(`+)(([\\s\\S]*?)\\1)" if text.isMatch(regEx) { var m = text.matches(regEx) var length = count(m[1]) + count(m[2]) return [length, [ "inlinecode", m[3]]] } else { // TODO: No matching end code found - warn! return [1, "`"] } } self.inline["\n"] = { (text : String) -> [AnyObject] in return [3, ["linebreak"]] } self.inline["**"] = super.strong_em("strong", md: "**") self.inline["__"] = super.strong_em("strong", md: "__") self.inline["*"] = super.strong_em("em", md: "*") self.inline["_"] = super.strong_em("em", md: "_") buildBlockOrder() buildInlinePatterns() } // Create references for attributes func create_reference(details: [String]) { var href = details[2] if details.count >= 3 && details[2].isMatch("^<") && details[2].isMatch(">$") { href = details[2].substr(1, length: count(details[2]) - 1) } var title = "" if details.count == 5 && count(details[4]) > 0 { title = details[4] } else if details.count == 6 && count(details[5]) > 0 { title = details[5] } var ref = Ref(rid: details[1].lowercaseString, title: title, href: href) addRef(ref) } }
gpl-2.0
2345576753ed2a65cdb1e3df4796980b
42.495935
145
0.389463
4.863506
false
false
false
false
ianyh/Amethyst
Amethyst/Layout/Layouts/WidescreenTallLayout.swift
1
4922
// // WidescreenTallLayout.swift // Amethyst // // Created by Ian Ynda-Hummel on 12/15/15. // Copyright © 2015 Ian Ynda-Hummel. All rights reserved. // import Silica class WidescreenTallLayout<Window: WindowType>: Layout<Window> { class var isRight: Bool { fatalError("Must be implemented by subclass") } enum CodingKeys: String, CodingKey { case mainPaneCount case mainPaneRatio } private(set) var mainPaneCount: Int = 1 private(set) var mainPaneRatio: CGFloat = 0.5 required init() { super.init() } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.mainPaneCount = try values.decode(Int.self, forKey: .mainPaneCount) self.mainPaneRatio = try values.decode(CGFloat.self, forKey: .mainPaneRatio) super.init() } override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(mainPaneCount, forKey: .mainPaneCount) try container.encode(mainPaneRatio, forKey: .mainPaneRatio) } override func frameAssignments(_ windowSet: WindowSet<Window>, on screen: Screen) -> [FrameAssignmentOperation<Window>]? { let windows = windowSet.windows if windows.count == 0 { return [] } let mainPaneCount = min(windows.count, self.mainPaneCount) let secondaryPaneCount = windows.count - mainPaneCount let hasSecondaryPane = secondaryPaneCount > 0 let screenFrame = screen.adjustedFrame() let mainPaneWindowHeight = screenFrame.height let secondaryPaneWindowHeight = hasSecondaryPane ? round(screenFrame.height / CGFloat(secondaryPaneCount)) : 0.0 let mainPaneWidth = round(screenFrame.size.width * (hasSecondaryPane ? CGFloat(mainPaneRatio) : 1.0)) let mainPaneWindowWidth = round(mainPaneWidth / CGFloat(mainPaneCount)) let secondaryPaneWindowWidth = screenFrame.width - mainPaneWidth return windows.reduce([]) { frameAssignments, window -> [FrameAssignmentOperation<Window>] in var assignments = frameAssignments var windowFrame = CGRect.zero let windowIndex = frameAssignments.count let isMain = windowIndex < mainPaneCount let scaleFactor: CGFloat if isMain { scaleFactor = CGFloat(screenFrame.size.width / mainPaneWindowWidth) / CGFloat(mainPaneCount) windowFrame.origin.x = screenFrame.origin.x + mainPaneWindowWidth * CGFloat(windowIndex) if type(of: self).isRight { windowFrame.origin.x += secondaryPaneWindowWidth } windowFrame.origin.y = screenFrame.origin.y windowFrame.size.width = mainPaneWindowWidth windowFrame.size.height = mainPaneWindowHeight } else { scaleFactor = CGFloat(screenFrame.size.width / secondaryPaneWindowWidth) windowFrame.origin.x = screenFrame.origin.x + mainPaneWidth windowFrame.origin.y = screenFrame.origin.y + (secondaryPaneWindowHeight * CGFloat(windowIndex - mainPaneCount)) windowFrame.size.width = secondaryPaneWindowWidth windowFrame.size.height = secondaryPaneWindowHeight if type(of: self).isRight { windowFrame.origin.x = screenFrame.origin.x } } let resizeRules = ResizeRules(isMain: isMain, unconstrainedDimension: .horizontal, scaleFactor: scaleFactor) let frameAssignment = FrameAssignment<Window>( frame: windowFrame, window: window, screenFrame: screenFrame, resizeRules: resizeRules ) assignments.append(FrameAssignmentOperation(frameAssignment: frameAssignment, windowSet: windowSet)) return assignments } } } extension WidescreenTallLayout: PanedLayout { func recommendMainPaneRawRatio(rawRatio: CGFloat) { mainPaneRatio = rawRatio } func increaseMainPaneCount() { mainPaneCount += 1 } func decreaseMainPaneCount() { mainPaneCount = max(1, mainPaneCount - 1) } } class WidescreenTallLayoutLeft<Window: WindowType>: WidescreenTallLayout<Window> { override class var isRight: Bool { return false } override static var layoutName: String { return "Widescreen Tall" } override static var layoutKey: String { return "widescreen-tall" } } class WidescreenTallLayoutRight<Window: WindowType>: WidescreenTallLayout<Window> { override class var isRight: Bool { return true } override static var layoutName: String { return "Widescreen Tall Right" } override static var layoutKey: String { return "widescreen-tall-right" } }
mit
4f62447df2c0dc719809f72e256aab46
38.055556
128
0.66328
4.586207
false
false
false
false
aleph7/PlotKit
PlotKit/Views/DataView.swift
1
1932
// Copyright © 2016 Venture Media Labs. All rights reserved. // // This file is part of PlotKit. The full PlotKit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import Cocoa open class DataView: NSView { /// The inverval of x values to render open var xInterval: ClosedRange<Double> = 0...1 { didSet { needsDisplay = true } } /// The inverval of y values to render open var yInterval: ClosedRange<Double> = 0...1 { didSet { needsDisplay = true } } /// Return the data value at the specified location in the view or `nil` if there is no data point at that location open func pointAt(_ location: NSPoint) -> Point? { return nil } /// Converts a point from the data's coordinate system to the view's coordinate system open func convertDataPointToView(_ dataPoint: Point) -> CGPoint { let boundsXInterval = Double(bounds.minX)...Double(bounds.maxX) let boundsYInterval = Double(bounds.minY)...Double(bounds.maxY) return CGPoint( x: mapValue(dataPoint.x, fromInterval: xInterval, toInterval: boundsXInterval), y: mapValue(dataPoint.y, fromInterval: yInterval, toInterval: boundsYInterval) ) } /// Converts a point from the view's coordinate system to the data's coordinate system open func convertViewPointToData(_ viewPoint: CGPoint) -> Point { let boundsXInterval = Double(bounds.minX)...Double(bounds.maxX) let boundsYInterval = Double(bounds.minY)...Double(bounds.maxY) return Point( x: mapValue(Double(viewPoint.x), fromInterval: boundsXInterval, toInterval: xInterval), y: mapValue(Double(viewPoint.y), fromInterval: boundsYInterval, toInterval: yInterval) ) } }
mit
3a0581835d668625e6dcc18754e82dcc
39.229167
119
0.668048
4.418764
false
false
false
false
LoopKit/LoopKit
LoopKitUI/CarbKit/DecimalTextFieldTableViewCell.swift
1
1131
// // DecimalTextFieldTableViewCell.swift // CarbKit // // Created by Nathan Racklyeft on 1/15/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit public class DecimalTextFieldTableViewCell: TextFieldTableViewCell { @IBOutlet weak var titleLabel: UILabel! var numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() public var number: NSNumber? { get { return numberFormatter.number(from: textField.text ?? "") } set { if let value = newValue { textField.text = numberFormatter.string(from: value) } else { textField.text = nil } } } // MARK: - UITextFieldDelegate public override func textFieldDidEndEditing(_ textField: UITextField) { if let number = number { textField.text = numberFormatter.string(from: number) } else { textField.text = nil } super.textFieldDidEndEditing(textField) } }
mit
323484145f9fee046fb2e71119b30f04
23.042553
75
0.6
5.255814
false
false
false
false
LoopKit/LoopKit
LoopKit/NotificationSettings.swift
1
9485
// // NotificationSettings.swift // LoopKit // // Created by Darin Krauss on 9/17/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import Foundation import UserNotifications public struct NotificationSettings: Equatable { public enum AuthorizationStatus: String, Codable { case notDetermined case denied case authorized case provisional case ephemeral case unknown public init(_ authorizationStatus: UNAuthorizationStatus) { switch authorizationStatus { case .notDetermined: self = .notDetermined case .denied: self = .denied case .authorized: self = .authorized case .provisional: self = .provisional case .ephemeral: self = .ephemeral @unknown default: self = .unknown } } } public enum NotificationSetting: String, Codable { case notSupported case disabled case enabled case unknown public init(_ notificationSetting: UNNotificationSetting) { switch notificationSetting { case .notSupported: self = .notSupported case .disabled: self = .disabled case .enabled: self = .enabled @unknown default: self = .unknown } } } public enum AlertStyle: String, Codable { case none case banner case alert case unknown public init(_ alertStyle: UNAlertStyle) { switch alertStyle { case .none: self = .none case .banner: self = .banner case .alert: self = .alert @unknown default: self = .unknown } } } public enum ShowPreviewsSetting: String, Codable { case always case whenAuthenticated case never case unknown public init(_ showPreviewsSetting: UNShowPreviewsSetting) { switch showPreviewsSetting { case .always: self = .always case .whenAuthenticated: self = .whenAuthenticated case .never: self = .never @unknown default: self = .unknown } } } public let authorizationStatus: AuthorizationStatus public let soundSetting: NotificationSetting public let badgeSetting: NotificationSetting public let alertSetting: NotificationSetting public let notificationCenterSetting: NotificationSetting public let lockScreenSetting: NotificationSetting public let carPlaySetting: NotificationSetting public let alertStyle: AlertStyle public let showPreviewsSetting: ShowPreviewsSetting public let criticalAlertSetting: NotificationSetting public let providesAppNotificationSettings: Bool public let announcementSetting: NotificationSetting public let timeSensitiveSetting: NotificationSetting public let scheduledDeliverySetting: NotificationSetting public init(authorizationStatus: AuthorizationStatus, soundSetting: NotificationSetting, badgeSetting: NotificationSetting, alertSetting: NotificationSetting, notificationCenterSetting: NotificationSetting, lockScreenSetting: NotificationSetting, carPlaySetting: NotificationSetting, alertStyle: AlertStyle, showPreviewsSetting: ShowPreviewsSetting, criticalAlertSetting: NotificationSetting, providesAppNotificationSettings: Bool, announcementSetting: NotificationSetting, timeSensitiveSetting: NotificationSetting, scheduledDeliverySetting: NotificationSetting) { self.authorizationStatus = authorizationStatus self.soundSetting = soundSetting self.badgeSetting = badgeSetting self.alertSetting = alertSetting self.notificationCenterSetting = notificationCenterSetting self.lockScreenSetting = lockScreenSetting self.carPlaySetting = carPlaySetting self.alertStyle = alertStyle self.showPreviewsSetting = showPreviewsSetting self.criticalAlertSetting = criticalAlertSetting self.providesAppNotificationSettings = providesAppNotificationSettings self.announcementSetting = announcementSetting self.timeSensitiveSetting = timeSensitiveSetting self.scheduledDeliverySetting = scheduledDeliverySetting } } extension NotificationSettings: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.init( authorizationStatus: try container.decode(AuthorizationStatus.self, forKey: .authorizationStatus), soundSetting: try container.decode(NotificationSetting.self, forKey: .soundSetting), badgeSetting: try container.decode(NotificationSetting.self, forKey: .badgeSetting), alertSetting: try container.decode(NotificationSetting.self, forKey: .alertSetting), notificationCenterSetting: try container.decode(NotificationSetting.self, forKey: .notificationCenterSetting), lockScreenSetting: try container.decode(NotificationSetting.self, forKey: .lockScreenSetting), carPlaySetting: try container.decode(NotificationSetting.self, forKey: .carPlaySetting), alertStyle: try container.decode(AlertStyle.self, forKey: .alertStyle), showPreviewsSetting: try container.decode(ShowPreviewsSetting.self, forKey: .showPreviewsSetting), criticalAlertSetting: try container.decode(NotificationSetting.self, forKey: .criticalAlertSetting), providesAppNotificationSettings: try container.decode(Bool.self, forKey: .providesAppNotificationSettings), announcementSetting: try container.decode(NotificationSetting.self, forKey: .announcementSetting), timeSensitiveSetting: try container.decodeIfPresent(NotificationSetting.self, forKey: .timeSensitiveSetting) ?? .unknown, scheduledDeliverySetting: try container.decodeIfPresent(NotificationSetting.self, forKey: .scheduledDeliverySetting) ?? .unknown) } // public func encode(to encoder: Encoder) throws { // let bloodGlucoseUnit = self.bloodGlucoseUnit ?? StoredSettings.codingGlucoseUnit // var container = encoder.container(keyedBy: CodingKeys.self) // try container.encode(date, forKey: .date) // try container.encode(controllerTimeZone, forKey: .controllerTimeZone) // try container.encode(dosingEnabled, forKey: .dosingEnabled) // try container.encodeIfPresent(glucoseTargetRangeSchedule, forKey: .glucoseTargetRangeSchedule) // try container.encodeIfPresent(preMealTargetRange?.doubleRange(for: bloodGlucoseUnit), forKey: .preMealTargetRange) // try container.encodeIfPresent(workoutTargetRange?.doubleRange(for: bloodGlucoseUnit), forKey: .workoutTargetRange) // try container.encodeIfPresent(overridePresets, forKey: .overridePresets) // try container.encodeIfPresent(scheduleOverride, forKey: .scheduleOverride) // try container.encodeIfPresent(preMealOverride, forKey: .preMealOverride) // try container.encodeIfPresent(maximumBasalRatePerHour, forKey: .maximumBasalRatePerHour) // try container.encodeIfPresent(maximumBolus, forKey: .maximumBolus) // try container.encodeIfPresent(suspendThreshold, forKey: .suspendThreshold) // try container.encodeIfPresent(insulinType, forKey: .insulinType) // try container.encodeIfPresent(deviceToken, forKey: .deviceToken) // try container.encodeIfPresent(defaultRapidActingModel, forKey: .defaultRapidActingModel) // try container.encodeIfPresent(basalRateSchedule, forKey: .basalRateSchedule) // try container.encodeIfPresent(insulinSensitivitySchedule, forKey: .insulinSensitivitySchedule) // try container.encodeIfPresent(carbRatioSchedule, forKey: .carbRatioSchedule) // try container.encodeIfPresent(notificationSettings, forKey: .notificationSettings) // try container.encodeIfPresent(controllerDevice, forKey: .controllerDevice) // try container.encodeIfPresent(cgmDevice.map { CodableDevice($0) }, forKey: .cgmDevice) // try container.encodeIfPresent(pumpDevice.map { CodableDevice($0) }, forKey: .pumpDevice) // try container.encode(bloodGlucoseUnit.unitString, forKey: .bloodGlucoseUnit) // try container.encode(automaticDosingStrategy, forKey: .automaticDosingStrategy) // try container.encode(syncIdentifier, forKey: .syncIdentifier) // } private enum CodingKeys: String, CodingKey { case authorizationStatus case soundSetting case badgeSetting case alertSetting case notificationCenterSetting case lockScreenSetting case carPlaySetting case alertStyle case showPreviewsSetting case criticalAlertSetting case providesAppNotificationSettings case announcementSetting case timeSensitiveSetting case scheduledDeliverySetting } }
mit
60f3e0e8285ea46b0cd3a741391e85af
43.111628
141
0.682412
5.635175
false
false
false
false
PureSwift/GATT
Sources/GATT/AsyncStream.swift
1
2177
// // AsyncStream.swift // // // Created by Alsey Coleman Miller on 4/17/22. // import Foundation import Bluetooth public struct AsyncCentralScan <Central: CentralManager>: AsyncSequence { public typealias Element = ScanData<Central.Peripheral, Central.Advertisement> let stream: AsyncIndefiniteStream<Element> public init( bufferSize: Int = 100, _ build: @escaping ((Element) -> ()) async throws -> () ) { self.stream = .init(bufferSize: bufferSize, build) } public init( bufferSize: Int = 100, onTermination: @escaping () -> (), _ build: (AsyncIndefiniteStream<Element>.Continuation) -> () ) { self.stream = .init(bufferSize: bufferSize, onTermination: onTermination, build) } public func makeAsyncIterator() -> AsyncIndefiniteStream<Element>.AsyncIterator { stream.makeAsyncIterator() } public func stop() { stream.stop() } public var isScanning: Bool { return stream.isExecuting } } public extension AsyncCentralScan { func first() async throws -> Element? { for try await element in self { self.stop() return element } return nil } } public struct AsyncCentralNotifications <Central: CentralManager>: AsyncSequence { public typealias Element = Data let stream: AsyncIndefiniteStream<Element> public init( bufferSize: Int = 100, _ build: @escaping ((Element) -> ()) async throws -> () ) { self.stream = .init(bufferSize: bufferSize, build) } public init( bufferSize: Int = 100, onTermination: @escaping () -> (), _ build: (AsyncIndefiniteStream<Element>.Continuation) -> () ) { self.stream = .init(bufferSize: bufferSize, onTermination: onTermination, build) } public func makeAsyncIterator() -> AsyncIndefiniteStream<Element>.AsyncIterator { stream.makeAsyncIterator() } public func stop() { stream.stop() } public var isNotifying: Bool { return stream.isExecuting } }
mit
378672f9f28930bcb201127d85f03000
23.738636
88
0.607258
4.753275
false
true
false
false
asm-products/voicesrepo
Voices/Voices/App/Onboarding/OnboardingChildViewController.swift
1
2158
// // OnboardingChildViewController.swift // Voices // // Created by Eliot Fowler on 1/18/15. // Copyright (c) 2015 Assembly. All rights reserved. // import UIKit class OnboardingChildViewController: UIViewController { @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var voicesLabel: UILabel! var message: String? var image: UIImage? var index: Int? override func viewDidLoad() { super.viewDidLoad() gradientSetup() if(message != nil && messageLabel != nil) { messageLabel.text = message } if(image != nil && imageView != nil) { imageView.image = image } } func gradientSetup() { let startColor = UIColor(red: 220 / 255.0, green: 142 / 255.0, blue: 54 / 255.0, alpha: 1) let endColor = UIColor(red: 213 / 255.0, green: 71 / 255.0, blue: 123 / 255.0, alpha: 1) if(messageLabel != nil) { messageLabel.textColor = self.horizontalGradient(startColor, toColor: endColor) } if(voicesLabel != nil) { voicesLabel.textColor = self.horizontalGradient(startColor, toColor: endColor) } } func horizontalGradient(fromColor: UIColor, toColor: UIColor) -> UIColor { let labelTextWidth = messageLabel!.intrinsicContentSize().width let labelTextHeight = messageLabel!.intrinsicContentSize().height let size = CGSizeMake(labelTextWidth, 1) UIGraphicsBeginImageContextWithOptions(size, false, 0) let context = UIGraphicsGetCurrentContext() let colorspace = CGColorSpaceCreateDeviceRGB() let colors = [fromColor.CGColor, toColor.CGColor] let gradient = CGGradientCreateWithColors(colorspace, colors, nil) CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(labelTextWidth, 0), 0) let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext() return UIColor(patternImage: image) } }
agpl-3.0
d137789ea3b06bb588e46afb3a7de6a0
32.2
108
0.630213
4.97235
false
false
false
false
chenchangqing/segmentPageView
SSASideMenu+HMSegment+SwipeView/SSASideMenu+HMSegment+SwipeView/ViewController.swift
1
6276
// // ViewController.swift // SSASideMenu+HMSegment+SwipeView // // Created by green on 15/9/15. // Copyright (c) 2015年 chenchangqing. All rights reserved. // import UIKit class ViewController: UIViewController, SwipeViewDataSource, SwipeViewDelegate, SSASideMenuDelegate { // MARK: - UI HMSegmentedControl/SwipeView @IBOutlet var segmentedControl : HMSegmentedControl! @IBOutlet var swipeView : SwipeView! // MARK: - 侧边栏是否显示 var sideMenuIsShow = false // MARK: - 水平向左触发下一页最小移动距离 let kHorizontalToLeftMinMoveDistance:CGFloat = 30 // MARK: - 页面切换时间 let kDuration:Double = 0.3 // MARK: - Items var items:OrderedDictionary<NSNumber,UIColor> = { var items = OrderedDictionary<NSNumber,UIColor>() items[0] = UIColor.greenColor() items[1] = UIColor.redColor() items[2] = UIColor.grayColor() items[3] = UIColor.blueColor() items[4] = UIColor.magentaColor() return items }() // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setUp() } deinit { swipeView.delegate = nil swipeView.dataSource = nil self.sideMenuViewController?.delegate = nil } // MARK: - Set Up private func setUp() { setUpSegmentedControl() setUpSwipeView() setUpSSASideMenu() } // MARK: - Set Up SegmentedControl private func setUpSegmentedControl() { segmentedControl.sectionTitles = ["景点","餐饮","购物","酒店","活动"] segmentedControl.selectionIndicatorHeight = 2.0 segmentedControl.selectionIndicatorColor = UIColor.blueColor() segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown segmentedControl.backgroundColor = UIColor.lightGrayColor() segmentedControl.titleTextAttributes = [NSFontAttributeName:UIFont.systemFontOfSize(14)] segmentedControl.shouldAnimateUserSelection = true segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe segmentedControl.indexChangeBlock = { (index:NSInteger) in self.swipeView.scrollToPage(index, duration: self.kDuration) } self.view.addSubview(segmentedControl) } // MARK: - Set Up SwipeView private func setUpSwipeView() { swipeView.delegate = self swipeView.dataSource = self swipeView.bounces = false swipeView.scrollEnabled = false } // MARK: - Set Up SSASideMenu private func setUpSSASideMenu() { self.sideMenuViewController?.delegate = self } // MARK: - SwipeViewDataSource func swipeView(swipeView: SwipeView!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! { var label:UILabel? var resultView = view if resultView == nil { resultView = UIView(frame: self.swipeView.bounds) resultView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth label = UILabel(frame: self.swipeView.bounds) label?.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth label?.backgroundColor = UIColor.clearColor() label?.textAlignment = NSTextAlignment.Center label?.font = label?.font.fontWithSize(50) label?.tag = 1 resultView.addSubview(label!) } else { label = view.viewWithTag(1) as? UILabel } let key = items.keys[index] let value = items[key] label?.text = "\(key)" resultView.backgroundColor = value return resultView } func numberOfItemsInSwipeView(swipeView: SwipeView!) -> Int { return items.count } // MARK: - SwipeViewDelegate func swipeViewItemSize(swipeView: SwipeView!) -> CGSize { return self.swipeView.bounds.size } func swipeViewDidScroll(swipeView: SwipeView!) { updateScollEnabled() } func swipeViewCurrentItemIndexDidChange(swipeView: SwipeView!) { self.segmentedControl.setSelectedSegmentIndex(UInt(swipeView.currentItemIndex), animated: true) } private func updateScollEnabled() { if swipeView.scrollOffset == 0 { swipeView.scrollEnabled = false } if swipeView.scrollOffset == 1 { swipeView.scrollEnabled = true } } // MARK: - SSASideMenuDelegate func sideMenuDidRecognizePanGesture(sideMenu: SSASideMenu, recongnizer: UIPanGestureRecognizer) { let translation = recongnizer.translationInView(self.swipeView) if translation.x >= 0 || sideMenuIsShow || swipeView.scrolling || swipeView.decelerating { return } let percent = fabs(translation.x)/self.swipeView.bounds.width if percent > swipeView.scrollOffset { swipeView.scrollOffset = percent } if recongnizer.state == UIGestureRecognizerState.Ended { if fabs(translation.x) > kHorizontalToLeftMinMoveDistance { swipeView.scrollToPage(1, duration: kDuration) } else { swipeView.scrollToPage(0, duration: kDuration) } } } func sideMenuDidShowMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController) { sideMenuIsShow = true } func sideMenuDidHideMenuViewController(sideMenu: SSASideMenu, menuViewController: UIViewController) { sideMenuIsShow = false } }
apache-2.0
661cc142a41798f7e664775845782e8d
27.694444
112
0.592288
5.639672
false
false
false
false
SheepYo/HAYO
iOS/HAYO/Alert.swift
1
4996
// // Alert.swift // MagoCamera // // Created by mono on 8/16/14. // Copyright (c) 2014 mono. All rights reserved. // import Foundation struct TitleAction { var title: String var action: () -> () init(title: String, action: () -> () = {}) { self.title = title self.action = action } } class Alert: NSObject, UIAlertViewDelegate { var cancelBlockOld: (() -> ())? var okBlockOld: (() -> ())! class var sharedInstance : Alert { struct Static { static let instance = Alert() } return Static.instance } // MARK: alert view func showAlertView(sourceViewController: UIViewController, title: String, message: String, okBlock: () -> (), cancelBlock: (() -> ())?) { if NSClassFromString("UIAlertController") != nil { showAlertViewImpl(sourceViewController, title: title, message: message, okBlock: okBlock, cancelBlock: cancelBlock) return } showAlertViewImplOld(sourceViewController, title: title, message: message, okBlock: okBlock, cancelBlock: cancelBlock) } private func showAlertViewImpl(sourceViewController: UIViewController, title: String, message: String, okBlock: () -> (), cancelBlock: (() -> ())?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: okString, style: .Default) { action in okBlock() }) if let cancel = cancelBlock { alert.addAction(UIAlertAction(title: cancelString, style: .Cancel) { action in cancel() }) } sourceViewController.presentViewController(alert, animated: true) { } } private func showAlertViewImplOld(sourceViewController: UIViewController, title: String, message: String, okBlock: () -> (), cancelBlock: (() -> ())?) { self.okBlockOld = okBlock self.cancelBlockOld = cancelBlock let alert = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: cancelBlock == nil ? nil : cancelString, otherButtonTitles: okString) alert.show() } func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) { if cancelBlockOld != nil && buttonIndex == 0 { cancelBlockOld?() return } okBlockOld() } func alertViewCancel(alertView: UIAlertView!) { cancelBlockOld?() } // MARK: action sheet func showActionSheet(sourceViewController: UIViewController, title: String, normalButtonActions: [TitleAction] = [], destructiveTitleAction: TitleAction? = nil, cancelBlock: () -> () = {}) { if NSClassFromString("UIAlertController") != nil { self.showActionSheetImpl(sourceViewController, title: title, normalButtonActions: normalButtonActions, destructiveTitleAction: destructiveTitleAction, cancelBlock: cancelBlock) return } self.showActionSheetImplOld(sourceViewController, title: title, normalButtonActions: normalButtonActions, destructiveTitleAction: destructiveTitleAction, cancelBlock: cancelBlock) } private func showActionSheetImpl(sourceViewController: UIViewController, title: String, normalButtonActions: [TitleAction] = [], destructiveTitleAction: TitleAction? = nil, cancelBlock: () -> () = {}) { let sheet = UIAlertController(title: nil, message: title, preferredStyle: .ActionSheet) for normal in normalButtonActions { sheet.addAction(UIAlertAction(title: normal.title, style: .Default, handler: { action in normal.action() })) } if let destructive = destructiveTitleAction { sheet.addAction(UIAlertAction(title: destructive.title, style: .Destructive, handler: { action in destructive.action() })) } sheet.addAction(UIAlertAction(title: cancelString, style: .Cancel, handler: { action in cancelBlock() })) sourceViewController.presentViewController(sheet, animated: true) { } } private func showActionSheetImplOld(sourceViewController: UIViewController, title: String, normalButtonActions: [TitleAction] = [], destructiveTitleAction: TitleAction? = nil, cancelBlock: () -> () = {}) { let sheet = UIActionSheet.bk_actionSheetWithTitle(title) as UIActionSheet for normal in normalButtonActions { sheet.bk_addButtonWithTitle(normal.title) { normal.action() } } if let destructive = destructiveTitleAction { sheet.bk_setDestructiveButtonWithTitle(destructive.title) { destructive.action() } } sheet.bk_setCancelButtonWithTitle(cancelString) { cancelBlock() } sheet.showInView(UIApplication.sharedApplication().delegate!.window!) } }
mit
fa9c3ade8faf0733a380530a3fa23d17
40.991597
209
0.638911
5.092762
false
false
false
false
cardstream/iOS-SDK
cardstream-ios-sdk/CryptoSwift-0.7.2/Sources/CryptoSwift/UInt16+Extension.swift
5
1680
// // UInt16+Extension.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /** array of bytes */ extension UInt16 { @_specialize(exported: true, where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T) where T.Iterator.Element == UInt8, T.Index == Int { self = UInt16(bytes: bytes, fromIndex: bytes.startIndex) } @_specialize(exported: true, where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Iterator.Element == UInt8, T.Index == Int { let val0 = UInt16(bytes[index.advanced(by: 0)]) << 8 let val1 = UInt16(bytes[index.advanced(by: 1)]) self = val0 | val1 } func bytes(totalBytes: Int = MemoryLayout<UInt16>.size) -> Array<UInt8> { return arrayOfBytes(value: self, length: totalBytes) } }
gpl-3.0
341f4fe613ea7367c8bdb11653f0e111
45.638889
217
0.70816
4.026379
false
false
false
false
xaviermerino/XMSegmentedControl
Pod/Classes/XMSegmentedControl.swift
1
20218
// // XMSegmentedControl.swift // XMSegmentedControl // // Created by Xavier Merino on 9/29/15. // Updated by Xavier Merino on 9/23/16. // Swift 3 // Copyright © 2015 Xavier Merino. All rights reserved. // import UIKit ///The delegate of `XMSegmentedControl` must adopt `XMSegmentedControlDelegate` protocol. It allows retrieving information on which segment was tapped. public protocol XMSegmentedControlDelegate: class { /// Tells the delegate that a specific segment is now selected. func xmSegmentedControl(_ xmSegmentedControl: XMSegmentedControl, selectedSegment: Int) } /** Highlighted Styles for the selected segments. - Background: The background of the selected segment is highlighted. - TopEdge: The top edge of the selected segment is highlighted. - BottomEdge: The bottom edge of the selected segmenet is highlighted. */ public enum XMSelectedItemHighlightStyle { case background case topEdge case bottomEdge } /** Content Type for the segmented control. - Text: The segmented control displays only text. - Icon: The segmented control displays only icons/images. - Hybrid: The segmented control displays icons and text. - HybridVertical: The segmented control displays icons and text in vertical arrangement. */ public enum XMContentType { case text case icon case hybrid case hybridVertical } /** Content distribution for the segmented control - Fixed: The segmented control item has a fixed width at `totalWidth / 6`, where 6 is maximum number of segment items. - HalfFixed: The segmented control item has a width equal to `totalWidth / 6`, if number of segment items > 2, and `totalWidth / 4` otherwise. - Flexible: The segmented control item has a width equal to `totalWidth / segmentCount` */ public enum XMSegmentItemWidthDistribution { case fixed case halfFixed case flexible } @IBDesignable open class XMSegmentedControl: UIView { weak open var delegate: XMSegmentedControlDelegate? fileprivate var highlightView: UIView! /** Defines the height of the highlighted edge if `selectedItemHighlightStyle` is either `TopEdge` or `BottomEdge` - Note: Changes only take place if `selectedItemHighlightStyle` is either `TopEdge` or `BottomEdge` */ open var edgeHighlightHeight: CGFloat = 5.0 /// Changes the background of the selected segment. @IBInspectable open var highlightColor = UIColor(red: 42/255, green: 132/255, blue: 210/255, alpha: 1) { didSet { self.update() } } /// Changes the font color or the icon tint color for the segments. @IBInspectable open var tint = UIColor.white { didSet { self.update() } } /// Changes the font color or the icon tint for the selected segment. @IBInspectable open var highlightTint = UIColor.white { didSet { self.update() } } /** Sets the segmented control content type to `Text` and uses the content of the array to create the segments. - Note: Only six elements will be displayed. */ open var segmentTitle: [String] = []{ didSet { segmentTitle = segmentTitle.count > 6 ? Array(segmentTitle[0..<6]) : segmentTitle contentType = .text self.update() } } /** Sets the segmented control content type to `Icon` and uses the content of the array to create the segments. - Note: Only six elements will be displayed. */ open var segmentIcon: [UIImage] = []{ didSet { segmentIcon = segmentIcon.count > 6 ? Array(segmentIcon[0..<6]) : segmentIcon contentType = .icon self.update() } } /** Sets the segmented control content type to `Hybrid` (i.e. displaying icons and text) and uses the content of the tuple to create the segments. - Note: Only six elements will be displayed. */ open var segmentContent: (text: [String], icon: [UIImage]) = ([], []) { didSet { guard segmentContent.text.count == segmentContent.icon.count else { print("Text and Icon arrays out of sync.") return } if segmentContent.text.count > 6 { segmentContent.text = Array(segmentContent.text[0..<6]) } else { segmentContent.text = segmentContent.text } if segmentContent.icon.count > 6 { segmentContent.icon = Array(segmentContent.icon[0..<6]) } else { segmentContent.icon = segmentContent.icon } segmentContent.icon = segmentContent.icon.map(resizeImage) contentType = .hybrid self.update() } } /** Sets the segmented control content type to `HybridVertical` (i.e. displaying icons and text in vertical arrangement) and uses the content of the tuple to create the segments. - Note: Only six elements will be displayed. */ open func setupVerticalSegmentContent(_ content: (text: [String], icon: [UIImage])) { segmentContent = content contentType = .hybridVertical self.update() } /// The segment index of the selected item. When set it animates the current highlight to the button with index = selectedSegment. open var selectedSegment: Int = 0 { didSet { func isUIButton(_ view: UIView) -> Bool { return view is UIButton ? true : false } UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.curveEaseOut, animations: { switch(self.contentType) { case .icon, .hybrid, .hybridVertical: ((self.subviews.filter(isUIButton)) as! [UIButton]).forEach { if $0.tag == self.selectedSegment { $0.tintColor = self.highlightTint self.highlightView.frame.origin.x = $0.frame.origin.x } else { $0.tintColor = self.tint } } case .text: ((self.subviews.filter(isUIButton)) as! [UIButton]).forEach { if $0.tag == self.selectedSegment { $0.setTitleColor(self.highlightTint, for: UIControlState()) self.highlightView.frame.origin.x = $0.frame.origin.x } else { $0.setTitleColor(self.tint, for: UIControlState()) } } } }, completion:nil) } } /** Sets the font for the text displayed in the segmented control if `contentType` is `Text` - Note: Changes only take place if `contentType` is `Text` */ open var font = UIFont(name: "AvenirNext-DemiBold", size: 15)! /// Sets the segmented control selected item highlight style to `Background`, `TopEdge` or `BottomEdge`. open var selectedItemHighlightStyle: XMSelectedItemHighlightStyle = .background /// Sets the segmented control content type to `Text` or `Icon` open var contentType: XMContentType = .text /// Sets the segmented control item width distribution to `Fixed`, `HalfFixed` or `Flexible` open var itemWidthDistribution:XMSegmentItemWidthDistribution = .flexible /// Initializes and returns a newly allocated XMSegmentedControl object with the specified frame rectangle. It sets the segments of the control from the given `segmentTitle` array and the highlight style for the selected item. public init (frame: CGRect, segmentTitle: [String], selectedItemHighlightStyle: XMSelectedItemHighlightStyle) { super.init (frame: frame) self.commonInit(segmentTitle, highlightStyle: selectedItemHighlightStyle) } /// Initializes and returns a newly allocated XMSegmentedControl object with the specified frame rectangle. It sets the segments of the control from the given `segmentIcon` array and the highlight style for the selected item. public init (frame: CGRect, segmentIcon: [UIImage], selectedItemHighlightStyle: XMSelectedItemHighlightStyle) { super.init (frame: frame) self.commonInit(segmentIcon, highlightStyle: selectedItemHighlightStyle) } /// Initializes and returns a newly allocated XMSegmentedControl object with the specified frame rectangle. It sets the segments of the control from the given `segmentContent` tuple and the highlight style for the selected item. Notice that the tuple consists of an array containing the titles and another array containing the icons. The two arrays must be the same size. public init (frame: CGRect, segmentContent: ([String], [UIImage]), selectedItemHighlightStyle: XMSelectedItemHighlightStyle) { super.init (frame: frame) self.commonInit(segmentContent, highlightStyle: selectedItemHighlightStyle) } /** Initializes and returns a newly allocated XMSegmentedControl object with the specified frame rectangle. It sets the segments of the control from the given `verticalSegmentContent` tuple and the highlight style for the selected item. Notice that the tuple consists of an array containing the titles and another array containing the icons. The two arrays must be the same size. The `contentType` is `HybridVertical` */ public convenience init (frame: CGRect, verticalSegmentContent: ([String], [UIImage]), selectedItemHighlightStyle:XMSelectedItemHighlightStyle) { self.init (frame: frame, segmentContent: verticalSegmentContent, selectedItemHighlightStyle: selectedItemHighlightStyle) setupVerticalSegmentContent(verticalSegmentContent) } /// Common initializer. fileprivate func commonInit(_ data: Any, highlightStyle: XMSelectedItemHighlightStyle) { if let segmentTitle = data as? [String] { self.segmentTitle = segmentTitle } else if let segmentIcon = data as? [UIImage] { self.segmentIcon = segmentIcon } else if let segmentContent = data as? ([String], [UIImage]) { self.segmentContent = segmentContent } backgroundColor = UIColor(red: 45/255, green: 62/255, blue: 100/255, alpha: 1) selectedItemHighlightStyle = highlightStyle } public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(red: 45/255, green: 62/255, blue: 100/255, alpha: 1) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor(red: 45/255, green: 62/255, blue: 100/255, alpha: 1) } /// Prepares the render of the view for the Storyboard. override open func prepareForInterfaceBuilder() { segmentTitle = ["Only", "For", "Show"] backgroundColor = UIColor(red: 45/255, green: 62/255, blue: 100/255, alpha: 1) } override open func layoutSubviews() { self.update() } /// Forces the segmented control to reload. open func update() { func addSegments(startingPosition starting: CGFloat, sections: Int, width: CGFloat, height: CGFloat) { for i in 0..<sections { let frame = CGRect(x: starting + (CGFloat(i) * width), y: 0, width: width, height: height) let tab = UIButton(type: UIButtonType.system) tab.frame = frame switch contentType { case .icon: tab.imageEdgeInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) tab.imageView?.contentMode = UIViewContentMode.scaleAspectFit tab.tintColor = i == selectedSegment ? highlightTint : tint tab.setImage(segmentIcon[i], for: UIControlState()) case .text: tab.setTitle(segmentTitle[i], for: UIControlState()) tab.setTitleColor(i == selectedSegment ? highlightTint : tint, for: UIControlState()) tab.titleLabel?.font = font case .hybrid: let insetAmount: CGFloat = 8 / 2.0 tab.imageEdgeInsets = UIEdgeInsetsMake(12, -insetAmount, 12, insetAmount) tab.titleEdgeInsets = UIEdgeInsetsMake(0, insetAmount*2, 0, 0) tab.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount) tab.contentHorizontalAlignment = .center tab.setTitle(segmentContent.text[i], for: UIControlState()) tab.setImage(segmentContent.icon[i], for: UIControlState()) tab.titleLabel?.font = font tab.imageView?.contentMode = .scaleAspectFit tab.tintColor = i == selectedSegment ? highlightTint : tint case .hybridVertical: let image: UIImage = segmentContent.icon[i] let imageSize = image.size let text: String = segmentContent.text[i] let halfSizeFont = UIFont(name: font.fontName, size: font.pointSize / 2.0) let textSize = NSString(string: text).size(attributes: [NSFontAttributeName: halfSizeFont]) let spacing: CGFloat = 12 let imageHorizontalInset: CGFloat = (width - imageSize.width)/2 tab.imageEdgeInsets = UIEdgeInsetsMake(spacing, imageHorizontalInset, spacing + textSize.height + edgeHighlightHeight, imageHorizontalInset) tab.titleEdgeInsets = UIEdgeInsetsMake(spacing, -imageSize.width, -imageSize.height + spacing, 0) tab.contentEdgeInsets = UIEdgeInsets.zero tab.contentHorizontalAlignment = .center tab.contentVerticalAlignment = .center tab.setTitle(text, for: .normal) tab.setImage(image, for: .normal) tab.titleLabel?.font = halfSizeFont tab.titleLabel?.textAlignment = .center tab.titleLabel?.numberOfLines = 0 tab.imageView?.contentMode = .scaleAspectFit tab.tintColor = i == selectedSegment ? highlightTint : tint } tab.tag = i tab.addTarget(self, action: #selector(XMSegmentedControl.segmentPressed(_:)), for: .touchUpInside) self.addSubview(tab) } } func addHighlightView(startingPosition starting: CGFloat, width: CGFloat) { switch selectedItemHighlightStyle { case .background: highlightView = UIView(frame: CGRect(x: starting, y: 0, width: width, height: frame.height)) case .topEdge: highlightView = UIView(frame: CGRect(x: starting, y: 0, width: width, height: edgeHighlightHeight)) case .bottomEdge: highlightView = UIView(frame: CGRect(x: starting, y: frame.height - edgeHighlightHeight, width: width, height: edgeHighlightHeight)) } highlightView.backgroundColor = highlightColor self.addSubview(highlightView) } (subviews as [UIView]).forEach { $0.removeFromSuperview() } let totalWidth = frame.width func startingPositionAndWidth(_ totalWidth: CGFloat, distribution: XMSegmentItemWidthDistribution, segmentCount: Int) -> (startingPosition: CGFloat, sectionWidth: CGFloat) { switch distribution { case .fixed: let width = totalWidth / 6 let availableSpace = totalWidth - (width * CGFloat(segmentCount)) let position = (totalWidth - availableSpace) / 2 return (position, width) case .halfFixed: var width = totalWidth / 4 if segmentCount > 2 { width = totalWidth / 6 } let availableSpace = totalWidth - (width * CGFloat(segmentCount)) let position = (totalWidth - availableSpace) / 2 return (position, width) case .flexible: let width = totalWidth / CGFloat(segmentCount) return (0, width) } } if contentType == .text { guard segmentTitle.count > 0 else { print("segment titles (segmentTitle) are not set") return } let tabBarSections = segmentTitle.count let sectionWidth = totalWidth / CGFloat(tabBarSections) addHighlightView(startingPosition: CGFloat(selectedSegment) * sectionWidth, width: sectionWidth) addSegments(startingPosition: 0, sections: tabBarSections, width: sectionWidth, height: frame.height) } else if contentType == .icon { let tabBarSections:Int = segmentIcon.count let positionWidth = startingPositionAndWidth(totalWidth, distribution: itemWidthDistribution, segmentCount: tabBarSections) addHighlightView(startingPosition: CGFloat(selectedSegment) * positionWidth.sectionWidth, width: positionWidth.sectionWidth) addSegments(startingPosition: positionWidth.startingPosition, sections: tabBarSections, width: positionWidth.sectionWidth, height: self.frame.height) } else if contentType == .hybrid { let tabBarSections:Int = segmentContent.text.count let positionWidth = startingPositionAndWidth(totalWidth, distribution: itemWidthDistribution, segmentCount: tabBarSections) addHighlightView(startingPosition: CGFloat(selectedSegment) * positionWidth.sectionWidth, width: positionWidth.sectionWidth) addSegments(startingPosition: 0, sections: tabBarSections, width: positionWidth.sectionWidth, height: self.frame.height) } else if contentType == .hybridVertical { let tabBarSections:Int = segmentContent.text.count let positionWidth = startingPositionAndWidth(totalWidth, distribution: itemWidthDistribution, segmentCount: tabBarSections) addHighlightView(startingPosition: CGFloat(selectedSegment) * positionWidth.sectionWidth, width: positionWidth.sectionWidth) addSegments(startingPosition: positionWidth.startingPosition, sections: tabBarSections, width: positionWidth.sectionWidth, height: self.frame.height) } } /// Called whenever a segment is pressed. Sends the information to the delegate. @objc fileprivate func segmentPressed(_ sender: UIButton) { selectedSegment = sender.tag delegate?.xmSegmentedControl(self, selectedSegment: selectedSegment) } /// Press indexed tab open func pressTabWithIndex(_ index: Int) { for subview in self.subviews where subview.tag == index { if subview is UIButton { segmentPressed(subview as! UIButton) return } } } /// Scales an image if it's over the maximum size of `frame height / 2`. It takes into account alpha. And it uses the screen's scale to resize. fileprivate func resizeImage(_ image:UIImage) -> UIImage { let maxSize = CGSize(width: frame.height / 2, height: frame.height / 2) // If the original image is within the maximum size limit, just return immediately without manual scaling if image.size.width <= maxSize.width && image.size.height <= maxSize.height { return image } let ratio = image.size.width / image.size.height let size = CGSize(width: maxSize.width*ratio, height: maxSize.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) image.draw(in: CGRect(origin: CGPoint.zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } }
mit
6cafe1bb65e672e2e0a5a95b86b9c8b6
45.798611
380
0.637681
5.052987
false
false
false
false
Legoless/Alpha
Demo/UIKitCatalog/AlertFormViewController.swift
1
6132
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that demonstrates how to implement text entry using `UIAlertController`. */ import UIKit class AlertFormViewController: UIViewController { // MARK: Properties private weak var secureTextAlertAction: UIAlertAction? // MARK: IB Actions @IBAction func showSimpleForm(_ sender: AnyObject) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let acceptButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Add two text fields for text entry. alertController.addTextField { textField in // Customize the text field. textField.placeholder = NSLocalizedString("Name", comment: "") // Specify a custom input accessory view with a descriptive title. let inputAccessoryView = CustomInputAccessoryView(title: NSLocalizedString("Enter your name", comment: "")) textField.inputAccessoryView = inputAccessoryView } alertController.addTextField { textField in // Customize the text field. textField.keyboardType = .emailAddress textField.placeholder = NSLocalizedString("[email protected]", comment: "") // Specify a custom input accessory view with a descriptive title. let inputAccessoryView = CustomInputAccessoryView(title: "Enter your email address") textField.inputAccessoryView = inputAccessoryView } // Create the actions. let acceptAction = UIAlertAction(title: acceptButtonTitle, style: .default) {[unowned alertController] _ in print("The \"Text Entry\" alert's other action occured.") if let enteredText = alertController.textFields?.first?.text { print("The text entered into the \"Text Entry\" alert's text field was \"\(enteredText)\"") } } /* The cancel action is created the the `Cancel` style and no title. This will allow us to capture the user clicking the menu button to cancel the alert while not showing a specific cancel button. */ let cancelAction = UIAlertAction(title: nil, style: .cancel) { _ in print("The \"Text Entry\" alert's cancel action occured.") } // Add the actions. alertController.addAction(acceptAction) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } /** Show a secure text entry alert with "OK" and "Cancel" buttons. The "OK" button is only enabled when at least 5 characters have been entered into the text field. */ @IBAction func showSecureTextEntry(_ sender: AnyObject) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let acceptButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Add the text field for the secure text entry. alertController.addTextField { textField in // Customize the text field. textField.placeholder = NSLocalizedString("Password", comment: "") textField.isSecureTextEntry = true // Specify a custom input accessory view with a descriptive title. let inputAccessoryView = CustomInputAccessoryView(title: "Enter at least 5 characters") textField.inputAccessoryView = inputAccessoryView /* Add a target that is called when the text field's text is changed so that we can toggle the `otherAction` enabled property based on whether the user has entered a long enough string. */ textField.addTarget(self, action: #selector(AlertFormViewController.handleTextFieldTextDidChangeNotification(_:)), for: .editingChanged) } // Create the actions. let acceptAction = UIAlertAction(title: acceptButtonTitle, style: .default) { _ in print("The \"Secure Text Entry\" alert's other action occured.") } /* The cancel action is created with the `Cancel` style and no title. This will allow us to capture the user clicking the menu button to cancel the alert while not showing a specific cancel button. */ let cancelAction = UIAlertAction(title: nil, style: .cancel) { _ in print("The \"Text Entry\" alert's cancel action occured.") } // The text field initially has no text in the text field, so we'll disable it. acceptAction.isEnabled = false /* Hold onto the secure text alert action to toggle the enabled / disabled state when the text changed. */ secureTextAlertAction = acceptAction // Add the actions. alertController.addAction(acceptAction) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } // MARK: Convenience func handleTextFieldTextDidChangeNotification(_ textField: UITextField) { guard let secureTextAlertAction = secureTextAlertAction else { fatalError("secureTextAlertAction has not been set") } // Enforce a minimum length of >= 5 characters for secure text alerts. let text = textField.text ?? "" secureTextAlertAction.isEnabled = text.characters.count >= 5 } }
mit
5da87f4a36d443e25eb3ed92f23a1290
42.785714
148
0.635073
5.7397
false
false
false
false
pkkup/Pkkup-iOS
Pkkup/viewControllers/MyGamesViewController.swift
1
5377
// // MyGamesViewController.swift // Pkkup // // Created by Deepak on 10/19/14. // Copyright (c) 2014 Pkkup. All rights reserved. // import UIKit enum MyGamesSegmentedControlEnum: Int { case Upcoming = 0 case Saved = 1 case Locations = 2 } class MyGamesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var currentPlayer: PkkupPlayer! var gamesConfirmed: [PkkupGame]! var gamesMaybe: [PkkupGame]! var gamesRecent: [PkkupGame]! var myLocations: [PkkupLocation]! @IBOutlet weak var myGamesSegControl: UISegmentedControl! var selectedSegment: MyGamesSegmentedControlEnum = MyGamesSegmentedControlEnum.Upcoming @IBOutlet weak var gamesTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() gamesTableView.dataSource = self gamesTableView.delegate = self gamesTableView.rowHeight = UITableViewAutomaticDimension gamesTableView.estimatedRowHeight = 80.0 myGamesSegControl.tintColor = _THEME_COLOR self.navigationController?.navigationBar.barTintColor = _THEME_COLOR // Do any additional setup after loading the view. //Temp Current Player self.currentPlayer = _PLAYERS[7] //println(self.currentPlayer.playerDictionary) gamesConfirmed = self.currentPlayer.getGamesConfirmed() gamesMaybe = self.currentPlayer.getGamesMaybe() //println(gamesMaybe) myLocations = self.currentPlayer.getLocations() //println(myLocations) //gamesRecent = self.currentPlayer.getGamesRecent() var tblView = UIView(frame: CGRectZero) gamesTableView.tableFooterView = tblView gamesTableView.tableFooterView?.hidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onMyGamesSegControlTap(sender: AnyObject) { self.selectedSegment = MyGamesSegmentedControlEnum(rawValue: self.myGamesSegControl.selectedSegmentIndex)! NSLog("myGamesSegControl index :\(selectedSegment)") gamesTableView.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch self.selectedSegment { case .Upcoming: return self.gamesConfirmed.count case .Saved: return self.gamesMaybe.count case .Locations: return self.myLocations.count default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch self.selectedSegment { case .Upcoming: var cell = gamesTableView.dequeueReusableCellWithIdentifier("GamesCell") as GamesCell var game = self.gamesConfirmed[indexPath.row] cell.game = game return cell case .Saved: var cell = gamesTableView.dequeueReusableCellWithIdentifier("GamesCell") as GamesCell var game = self.gamesMaybe[indexPath.row] cell.game = game return cell case .Locations: var cell = gamesTableView.dequeueReusableCellWithIdentifier("LocationCell") as LocationCell var location = self.myLocations[indexPath.row] cell.location = location return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if ( self.selectedSegment != .Locations) { return } var location = myLocations[indexPath.row] var storyboard = UIStoryboard(name: "Main", bundle: nil) var locationDetailsViewController = storyboard.instantiateViewControllerWithIdentifier("LocationDetailsViewController") as LocationDetailsViewController locationDetailsViewController.view.layoutSubviews() locationDetailsViewController.location = location self.navigationController?.pushViewController(locationDetailsViewController, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "gameDetailSegue1") { let gameDetailsViewController = segue.destinationViewController as GameDetailsViewController var indexPath = self.gamesTableView.indexPathForSelectedRow()?.row switch self.selectedSegment { case .Upcoming: var game = self.gamesConfirmed[indexPath!] gameDetailsViewController.game = game case .Saved: var game = self.gamesMaybe[indexPath!] gameDetailsViewController.game = game default: println("default case error") } } } /* // 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. } */ }
mit
4b794bbfdb50f51dea94befccd0f6fdf
37.407143
160
0.661335
5.543299
false
false
false
false
gang462234887/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendLikeCell.swift
1
3283
// // CBRecommendLikeCell.swift // TestKitchen // // Created by gaokunpeng on 16/8/17. // Copyright © 2016年 apple. All rights reserved. // import UIKit class CBRecommendLikeCell: UITableViewCell { //显示数据 var model: CBRecommendWidgeListModel? { didSet { //显示图片和文字 showData() } } //显示图片和文字 func showData(){ for var i in 0..<8 { //i 0 2 4 6 //图片 if model?.widget_data?.count > i { let imageModel = model?.widget_data![i] if imageModel?.type == "image" { //获取图片视图 //tag:200 201 202 203 let index = i/2 let subView = self.contentView.viewWithTag(200+index) if ((subView?.isKindOfClass(UIImageView.self)) == true) { let imageView = subView as! UIImageView let url = NSURL(string: (imageModel?.content)!) imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } } //文字 if model?.widget_data?.count > i+1 { let textModel = model?.widget_data![i+1] if textModel?.type == "text" { //tag:300 301 302 303 let subView = self.contentView.viewWithTag(300+i/2) if ((subView?.isKindOfClass(UILabel.self)) == true) { let label = subView as! UILabel label.text = textModel?.content } } } //每次遍历两个 i += 1 } } //创建cell的方法 class func createLikeCellFor(tableView: UITableView, atIndexPath indexPath:NSIndexPath, withListModel listModel: CBRecommendWidgeListModel) -> CBRecommendLikeCell { //猜你喜欢 let cellId = "recommendLikeCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBRecommendLikeCell if nil == cell { cell = NSBundle.mainBundle().loadNibNamed("CBRecommendLikeCell", owner: nil, options: nil).last as? CBRecommendLikeCell } cell?.model = listModel return cell! } @IBAction func clickBtn(sender: UIButton) { } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
7aaccd318ee26320a4962bc34007a2be
25.840336
170
0.453663
5.744604
false
false
false
false
uptech/Constraid
Sources/Constraid/ProxyExtensions/ConstraidProxy+ExpandFromEdge.swift
1
7193
#if os(iOS) import UIKit #else import AppKit #endif extension ConstraidProxy { /** Constrains the object's leading edge to expand outward from the leading edge of `item` - parameter item: The `item` you want to constrain base against - parameter multiplier: The ratio altering the constraint relative to leading edge of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func expand(fromLeadingEdgeOf item: Any?, times multiplier: CGFloat = 1.0, offsetBy offset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.expand(self.base, fromLeadingEdgeOf: item, times: multiplier, offsetBy: offset, priority: priority)) return self } /** Constrains the object's trailing edge to expand outward from the leading edge of `item` - parameter item: The `item` you want to constrain base against - parameter multiplier: The ratio altering the constraint relative to trailing edge of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func expand(fromTrailingEdgeOf item: Any?, times multiplier: CGFloat = 1.0, offsetBy offset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.expand(self.base, fromTrailingEdgeOf: item, times: multiplier, offsetBy: offset, priority: priority)) return self } /** Constrains the object's top edge to outward from the top edge of `item` - parameter item: The `item` you want to constrain base against - parameter multiplier: The ratio altering the constraint relative to top edge of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func expand(fromTopEdgeOf item: Any?, times multiplier: CGFloat = 1.0, offsetBy offset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.expand(self.base, fromTopEdgeOf: item, times: multiplier, offsetBy: offset, priority: priority)) return self } /** Constrains the object's bottom edge to outward from the bottom edge of `item` - parameter item: The `item` you want to constrain base against - parameter multiplier: The ratio altering the constraint relative to bottom edge of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func expand(fromBottomEdgeOf item: Any?, times multiplier: CGFloat = 1.0, offsetBy offset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.expand(self.base, fromBottomEdgeOf: item, times: multiplier, offsetBy: offset, priority: priority)) return self } /** Constrains the object's top & bottom edges to expand outward from the top & bottom edges of `item` - parameter item: The `item` you want to constrain base against - parameter multiplier: The ratio altering the constraint relative to top & bottom edge of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func expand(fromHorizontalEdgesOf item: Any?, times multiplier: CGFloat = 1.0, offsetBy offset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.expand(self.base, fromHorizontalEdgesOf: item, times: multiplier, offsetBy: offset, priority: priority)) return self } /** Constrains the object's leading & trailing edges to expand outward from the leading & trailing edge of `item` - parameter item: The `item` you want to constrain base against - parameter multiplier: The ratio altering the constraint relative to leading & trailing edge of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func expand(fromVerticalEdgesOf item: Any?, times multiplier: CGFloat = 1.0, offsetBy offset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.expand(self.base, fromVerticalEdgesOf: item, times: multiplier, offsetBy: offset, priority: priority)) return self } /** Constrains the object's top, bottom, leading & trailing edges to expand outward from the top, bottom, leading & trailing edge of `item` - parameter item: The `item` you want to constrain base against - parameter multiplier: The ratio altering the constraint relative to top, bottom, leading & trailing edge of the item prior to the `constant` being applied. - parameter constant: The amount to add to the constraint equation after the multiplier. - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func expand(fromEdgesOf item: Any?, times multiplier: CGFloat = 1.0, offsetBy offset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.expand(self.base, fromEdgesOf: item, times: multiplier, offsetBy: offset, priority: priority)) return self } }
mit
3c9e926d0477cc13c658c5988dd96deb
50.014184
202
0.727235
5.051264
false
false
false
false
0xfeedface1993/Xs8-Safari-Block-Extension-Mac
Sex8BlockExtension/SwiftToaster/SwiftToaster-macOS/SwiftyToast-macOS.swift
1
6480
// // SwiftToaster-macOS.swift // SwiftToaster // // Created by Meniny on 12/08/16. // Copyright © 2016 Meniny. All rights reserved. // //#if os(iOS) //#else import Cocoa open class SwiftToasterDefault { static var message: String = "" static var cornerRadius: CGFloat = 10 static var textColor: NSColor = NSColor.white static var backgroundColor: NSColor = NSColor.black static var alpha: CGFloat = 1 static var fadeInTime: TimeInterval = 0.250 static var fadeOutTime: TimeInterval = 0.250 static var duration: TimeInterval = 1.25 } open class SwiftToaster: NSObject { // Variables fileprivate var message: String = SwiftToasterDefault.message fileprivate var cornerRadius: CGFloat = SwiftToasterDefault.cornerRadius fileprivate var textColor: NSColor = SwiftToasterDefault.textColor fileprivate var backgroundColor: NSColor = SwiftToasterDefault.backgroundColor fileprivate var alpha: CGFloat = SwiftToasterDefault.alpha open var fadeInTime: TimeInterval = SwiftToasterDefault.fadeInTime open var fadeOutTime: TimeInterval = SwiftToasterDefault.fadeOutTime open var duration: TimeInterval = SwiftToasterDefault.duration // fileprivate var animateFromBottom: Bool = true // NS Components fileprivate var toastView: SwiftToasterView! // MARK: Initializations static let shared = SwiftToaster() public override init() {} public init(_ message: String, duration: TimeInterval?, textColor: NSColor?, backgroundColor: NSColor?, alpha: CGFloat?) { // duration = SwiftToasterDefault.duration // textColor = SwiftToasterDefault.textColor, // backgroundColor = SwiftToasterDefault.backgroundColor, // alpha = SwiftToasterDefault.alpha self.message = message self.textColor = textColor ?? SwiftToasterDefault.textColor self.backgroundColor = backgroundColor ?? SwiftToasterDefault.backgroundColor self.alpha = alpha ?? SwiftToasterDefault.alpha } open func show(inView aView: NSView) { self.toastView = SwiftToasterView(message: self.message, textColor: self.textColor, backgroundColor: self.backgroundColor, cornerRadius: self.cornerRadius) aView.addSubview(self.toastView) if let toast = self.toastView { self.toastView.addConstraint(NSLayoutConstraint(item: toast, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .width, multiplier: 1, constant: 300)) aView.addConstraint(NSLayoutConstraint(item: toast, attribute: .centerX, relatedBy: .equal, toItem: aView, attribute: .centerX, multiplier: 1, constant: 0)) } self.toastView.useVFLs(["V:[self]-20-|"]) self.toastView.alphaValue = 0 self.toastView.animator().alphaValue = self.alpha self.perform(#selector(self.hide), with: nil, afterDelay: self.duration) } open func show(inController viewController: NSViewController) { self.show(inView: viewController.view) } @objc fileprivate func hide() { self.toastView.animator().alphaValue = 0 self.toastView.removeFromSuperview() } } // Toast View fileprivate class SwiftToasterView: NSView { fileprivate var toastLabel: NSTextField! // Init init(message: String, textColor: NSColor, backgroundColor: NSColor, cornerRadius: CGFloat) { super.init(frame:CGRect.zero) self.wantsLayer = true self.layer?.cornerRadius = cornerRadius self.layer?.backgroundColor = backgroundColor.cgColor self.toastLabel = NSTextField() self.toastLabel.isBordered = false self.toastLabel.isEditable = false self.toastLabel.drawsBackground = false self.toastLabel.stringValue = message self.toastLabel.textColor = textColor self.toastLabel.alignment = .center self.toastLabel.lineBreakMode = .byCharWrapping // self.toastLabel.numberOfLines = 0 self.toastLabel.backgroundColor = NSColor.clear self.addSubview(self.toastLabel) self.toastLabel.useVFLs(["V:|-15-[self]-15-|", "H:|-10-[self]-10-|"]) } // Decode required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } // MARK: NSView Extensions extension NSView { // Set Constraints public func useVFLs(_ vfls: [String], options opts: NSLayoutConstraint.FormatOptions = [NSLayoutConstraint.FormatOptions.alignAllBottom], metrics: [String : NSNumber]? = nil, views: [String: Any]? = nil) { self.translatesAutoresizingMaskIntoConstraints = false for vfl in vfls { let constraints = NSLayoutConstraint.constraints(withVisualFormat: vfl, options: opts , metrics: metrics, views: views == nil ? ["self": self, "super": self.superview!] : views!) NSLayoutConstraint.activate(constraints) } } public func toast(_ message: String, textColor: NSColor = NSColor.white, backgroundColor: NSColor = NSColor.black, alpha: CGFloat = 1) { let t = SwiftToaster(message, duration: SwiftToasterDefault.duration, textColor: textColor, backgroundColor: backgroundColor, alpha: alpha) t.show(inView: self) } } extension NSViewController { public func toast(_ message: String, textColor: NSColor = NSColor.white, backgroundColor: NSColor = NSColor.black, alpha: CGFloat = 1) { let t = SwiftToaster(message, duration: SwiftToasterDefault.duration, textColor: textColor, backgroundColor: backgroundColor, alpha: alpha) t.show(inController: self) } } //#endif
apache-2.0
97f12f883110fcd6a7b75b2ead5b6f21
41.625
209
0.606729
5.319376
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/ChatItems/MessageMainThreadChatItem.swift
1
1862
// // MessageMainThreadChatItem.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 03/04/19. // Copyright © 2019 Rocket.Chat. All rights reserved. // import Foundation import DifferenceKit import RocketChatViewController final class MessageMainThreadChatItem: BaseMessageChatItem, ChatItem, Differentiable { var relatedReuseIdentifier: String { return MessageMainThreadCell.identifier } override init(user: UnmanagedUser?, message: UnmanagedMessage?) { super.init(user: nil, message: message) } var buttonTitle: String { guard let message = message else { return "" } if message.threadMessagesCount == 0 { return localized("threads.no_replies") } else if message.threadMessagesCount == 1 { return localized("threads.1_reply") } return String(format: localized("threads.x_replies"), message.threadMessagesCount.humanized()) } var threadLastMessageDate: String { if let lastMessageDate = message?.threadLastMessage { return formatLastMessageDate(lastMessageDate) } return "" } func formatLastMessageDate(_ date: Date) -> String { let calendar = Calendar.current if calendar.isDateInYesterday(date) { return localized("subscriptions.list.date.yesterday") } if calendar.isDateInToday(date) { return RCDateFormatter.time(date) } return RCDateFormatter.date(date, dateStyle: .short) } var differenceIdentifier: String { return message?.identifier ?? "" } func isContentEqual(to source: MessageMainThreadChatItem) -> Bool { guard let message = message, let sourceMessage = source.message else { return false } return message == sourceMessage } }
mit
df1f6f9aa4860cbb7d13a97a6f66f35d
26.776119
102
0.656099
4.821244
false
false
false
false
ColinConduff/BlocFit
BlocFit/Supporting Files/Supporting Models/BFUserDefaults.swift
1
2292
// // BFUserDefaults.swift // BlocFit // // Created by Colin Conduff on 11/8/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import Foundation struct BFUserDefaults { static let unitSetting = "unitsSetting" static let friendsDefaultTrusted = "friendsDefaultTrusted" static let shareFirstNameWithTrusted = "shareFirstNameWithTrusted" static func stringFor(unitsSetting isImperialUnits: Bool) -> String { if isImperialUnits { return "Imperial (mi)" } else { return "Metric (km)" } } static func getUnitsSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.unitSetting) } static func set(isImperial: Bool) { let defaults = UserDefaults.standard defaults.set(isImperial, forKey: BFUserDefaults.unitSetting) } static func stringFor(friendsWillDefaultToTrusted defaultTrusted: Bool) -> String { if defaultTrusted { return "New friends are trusted by default" } else { return "New friends are untrusted by default" } } static func getNewFriendDefaultTrustedSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.friendsDefaultTrusted) } static func set(friendsWillDefaultToTrusted defaultTrusted: Bool) { let defaults = UserDefaults.standard defaults.set(defaultTrusted, forKey: BFUserDefaults.friendsDefaultTrusted) } static func stringFor(willShareFirstNameWithTrustedFriends willShareName: Bool) -> String { if willShareName { return "Share first name with trusted friends" } else { return "Do not share first name with trusted friends" } } static func getShareFirstNameWithTrustedSetting() -> Bool { let defaults = UserDefaults.standard return defaults.bool(forKey: BFUserDefaults.shareFirstNameWithTrusted) } static func set(willShareFirstNameWithTrustedFriends willShareName: Bool) { let defaults = UserDefaults.standard defaults.set(willShareName, forKey: BFUserDefaults.shareFirstNameWithTrusted) } }
mit
b2c9b38a3fff8941017b8f24c51978c0
31.728571
95
0.672632
4.802935
false
false
false
false
Tommy1990/swiftWibo
SwiftWibo/SwiftWibo/Classes/View/Compose/View/EmojView/EPMEmotionPageView.swift
1
1926
// // EPMEmotionPageView.swift // SwiftWibo // // Created by 马继鵬 on 17/3/30. // Copyright © 2017年 7TH. All rights reserved. // import UIKit class EPMEmotionPageView: UICollectionView { override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { let flowLayOut = UICollectionViewFlowLayout() flowLayOut.itemSize = CGSize(width: screenWidth, height: 216 - 35) // 垂直和水平间距 flowLayOut.minimumLineSpacing = 0 flowLayOut.minimumInteritemSpacing = 0 // 滚动方向 flowLayOut.scrollDirection = .horizontal super.init(frame: frame, collectionViewLayout: flowLayOut) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setupUI(){ dataSource = self register(EPMEmotionPageCell.self, forCellWithReuseIdentifier: "cell") } } extension EPMEmotionPageView:UICollectionViewDataSource{ func numberOfSections(in collectionView: UICollectionView) -> Int { return EPMEmotionTool.sheardTool.allEmotions.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return EPMEmotionTool.sheardTool.allEmotions[section].count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! EPMEmotionPageCell backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!) // cell.backgroundColor = getRandomColor() cell.emoticons = EPMEmotionTool.sheardTool.allEmotions[indexPath.section][indexPath.item] cell.indexpath = indexPath return cell } }
mit
0193ccd5903582a1db585eda7d2a18f7
34.092593
121
0.700264
4.834184
false
false
false
false
SakibRabbany/projects
Money Manager/FirstApp/ViewController.swift
1
5767
import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var amounts:[Double] = [] var categories:[String] = [] var selection:[String] = [ "Select Category", "Entertainment", "Food", "Grocery", "Clothing", "Bills", "Miscellaneous" ] var total: Double = 0 var expenses:[Cater] = [ Cater(kind: "Entertainment", numArr: [Double]() , pct: 0, subTot: 0), Cater(kind: "Food", numArr: [Double]() , pct: 0, subTot: 0), Cater(kind: "Grocery", numArr: [Double]() , pct: 0, subTot: 0), Cater(kind: "Clothing", numArr: [Double]() , pct: 0, subTot: 0), Cater(kind: "Bills", numArr: [Double]() , pct: 0, subTot: 0), Cater(kind: "Miscellaneous", numArr: [Double]() , pct: 0, subTot: 0), ] @IBOutlet weak var amount: UITextField! @IBOutlet weak var category: UITextField! @IBOutlet weak var selectedCategory: UITextField! var select = UIPickerView() var picked = 0; override func viewDidLoad() { super.viewDidLoad() select.delegate = self select.dataSource = self selectedCategory.inputView = select } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) // first responder } @IBAction func insert(_ sender: UIButton) { if (amount.text?.isEmpty)! || (selectedCategory.text?.isEmpty)! { print("error") return } let num:Double? = Double(amount.text!) amounts.append(Double(num!)) categories.append(selectedCategory.text!) total += num! for i in (0..<expenses.count){ if expenses[i].kind == selectedCategory.text!{ expenses[i].numArr.append(num!) expenses[i].subTot += num! expenses[i].pct = Int((expenses[i].subTot / total) * 100) } else { expenses[i].pct = Int((expenses[i].subTot / total) * 100) } } amount.text = "" selectedCategory.text = "" return } @IBAction func show(_ sender: UIButton) { if amounts.count == 0{ print("error") return } for i in (0..<amounts.count).reversed() { print(amounts[i], terminator:" ") print(categories[i]) } } @IBAction func addCategory(_ sender: UIButton) { let categor:String = category.text! if (category.text?.isEmpty)! { print("Error") return } for i in (0..<selection.count){ if categor == selection[i]{ print("error") return } } selection.append(categor) let newCater = Cater(kind: categor, numArr: [Double](), pct: 0, subTot: 0) expenses.append(newCater) category.text = "" select.reloadAllComponents() } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return selection[row] } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return selection.count } public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { picked = row if row == 0 { selectedCategory.text = "" } else { selectedCategory.text = selection[row] } } @IBAction func deleteCategory(_ sender: UIButton) { if (selectedCategory.text?.isEmpty)! { print("error") return } let toRemove:String = selectedCategory.text! selection.remove(at: picked) select.reloadAllComponents() for i in 0..<categories.count { if categories[i] == toRemove { categories[i] = "Miscellaneous" } } var toRemoveSubTot : Double = 0 var toRemoveArr : [Double] = [] var toRemovePct : Int = 0 var index = 0 for i in 0..<expenses.count { if toRemove == expenses[i].kind { toRemoveSubTot = expenses[i].subTot toRemoveArr += expenses[i].numArr toRemovePct = expenses[i].pct index = i } } for i in 0..<expenses.count { if "Miscellaneous" == expenses[i].kind { expenses[i].subTot += toRemoveSubTot expenses[i].numArr += toRemoveArr expenses[i].pct += toRemovePct } } expenses.remove(at: index) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "DifferentExpenses" { let destViewContrl = segue.destination as! ExpensesViewController destViewContrl.expenseArray = expenses } else if segue.identifier == "AllExpenses" { let destViewContrl = segue.destination as! AllExpensesViewController destViewContrl.amts = amounts destViewContrl.cats = categories } } }
gpl-3.0
85d4641060dcd4977399f352f2a506f9
24.860987
111
0.510664
4.825941
false
false
false
false
leuski/Coiffeur
Coiffeur/src/formatter/UncrustifyController.swift
1
8113
// // UncrustifyController.swift // Coiffeur // // Created by Anton Leuski on 4/5/15. // Copyright (c) 2015 Anton Leuski. 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 Foundation class UncrustifyController: CoiffeurController { private struct Private { static var VersionArgument = "--version" static var ShowDocumentationArgument = "--update-config-with-doc" static var ShowDefaultConfigArgument = "--update-config" static var QuietFlag = "-q" static var ConfigPathFlag = "-c" static var LanguageFlag = "-l" static var FragmentFlag = "--frag" static var PageGuideKey = "code_width" static var Comment = "#" static var NumberOptionType = "number" static var DocumentType = "Uncrustify Style File" static var ExecutableName = "uncrustify" static var ExecutableURLUDKey = "UncrustifyExecutableURL" static var ExecutableTitleUDKey = "Uncrustify Executable" static var Options: String? } override var pageGuideColumn: Int { if let value = self.optionWithKey(Private.PageGuideKey)?.stringValue, let int = Int(value) { return int } return super.pageGuideColumn } var versionString: String? override class var localizedExecutableTitle: String { return NSLocalizedString(Private.ExecutableTitleUDKey, comment: "") } override class var documentType: String { return Private.DocumentType } override class var currentExecutableName: String { return Private.ExecutableName } override class var currentExecutableURLUDKey: String { return Private.ExecutableURLUDKey } override class var currentExecutableURL: URL? { didSet { Private.Options = nil } } override class func contentsIsValidInString(_ string: String) -> Bool { let keyValue = NSRegularExpression.aml_re_WithPattern( "^\\s*[a-zA-Z_]+\\s*=\\s*[^#\\s]") return nil != keyValue.firstMatchInString(string) } private static func _options(_ controller: CoiffeurController) throws -> String { if let options = Private.Options { return options } let options: String = try Process( controller.executableURL, arguments: [Private.ShowDocumentationArgument]) .run() Private.Options = options if let uncrustifyController = controller as? UncrustifyController { uncrustifyController.versionString = try Process( controller.executableURL, arguments: [Private.VersionArgument]).run() } return options } override class func createCoiffeur() throws -> CoiffeurController { let controller = try super.createCoiffeur() try controller.readOptionsFromString(try _options(controller)) return controller } override func readOptionsFromLineArray(_ lines: [String]) throws { var count = 0 var currentSection: ConfigSection? var currentComment: String = "" for aline in lines { count += 1 if count == 1 { continue } var line = aline.trim() if line.isEmpty { currentComment = currentComment.trim() if !currentComment.isEmpty { if nil != currentComment.rangeOfCharacter( from: CharacterSet.newlines) { } else { currentSection = ConfigSection.objectInContext( self.managedObjectContext, parent: self.root, title: currentComment) } currentComment = "" } } else if line.hasPrefix(Private.Comment) { line = line.stringByTrimmingPrefix(Private.Comment) currentComment += "\(line)\n" } else if let range = line.range(of: Private.Comment) { let keyValue = String(line[line.startIndex..<range.lowerBound]) var type = String(line[range.upperBound...]) if let (key, value) = _keyValuePairFromString(keyValue) { type = type.trim().replacingOccurrences(of: "/", with: ConfigNode.typeSeparator) currentComment = currentComment.trim() let option = ConfigOption.objectInContext( self.managedObjectContext, parent: currentSection, title: currentComment.components(separatedBy: CharacterSet.newlines)[0]) option.indexKey = key option.stringValue = value option.documentation = currentComment if type == "number" { option.type = OptionType.signed.rawValue } else { option.type = type } } currentComment = "" } } } private func _keyValuePairFromString(_ string: String) -> (key: String, value: String)? { var line = string if let range = line.range(of: Private.Comment) { line = String(line[line.startIndex..<range.lowerBound]) } if let range = line.range(of: "=") { line = line.replacingCharacters(in: range, with: " ") } while let range = line.range(of: ",") { line = line.replacingCharacters(in: range, with: " ") } let tokens = line.commandLineComponents if tokens.count == 0 { return nil } if tokens.count == 1 { NSLog("Warning: wrong number of arguments %@", line) return nil } let head = tokens[0] switch head { case "type", "define", "macro-open", "macro-close", "macro-else", "set", "include", "file_ext": break default: return (key:head, value:tokens[1]) } return nil } override func readValuesFromLineArray(_ lines: [String]) throws { for aline in lines { let line = aline.trim() if line.isEmpty { continue } if line.hasPrefix(Private.Comment) { continue } if let (key, value) = _keyValuePairFromString(line) { if let option = self.optionWithKey(key) { option.stringValue = value } else { NSLog("Warning: unknown token %@ on line %@", key, line) } } } } override func writeValuesToURL(_ absoluteURL: URL) throws { var data="" if let version = self.versionString { data += "\(Private.Comment) \(version)\n" } let allOptions = try self.managedObjectContext.fetch(ConfigOption.self, sortDescriptors: [CoiffeurController.keySortDescriptor]) for option in allOptions { if var value = option.stringValue { value = value.stringByQuoting() data += "\(option.indexKey) = \(value)\n" } } try data.write(to: absoluteURL, atomically: true, encoding: String.Encoding.utf8) } override func format(_ arguments: Arguments, completionHandler: @escaping (_:StringResult) -> Void) -> Bool { let workingDirectory = NSTemporaryDirectory() let configURL = URL(fileURLWithPath: workingDirectory).appendingPathComponent( UUID().uuidString) do { try self.writeValuesToURL(configURL) } catch let error { completionHandler(StringResult(error)) return false } var args = [Private.QuietFlag, Private.ConfigPathFlag, configURL.path] args.append(Private.LanguageFlag) args.append(arguments.language.uncrustifyID) if arguments.fragment { args.append(Private.FragmentFlag) } Process( self.executableURL, arguments: args, workingDirectory: workingDirectory) .runAsync(arguments.text) { (result: StringResult) -> Void in try? FileManager.default.removeItem(at: configURL) completionHandler(result) } return true } }
apache-2.0
91cad61e74020c1948564535f13c8dad
27.268293
113
0.641809
4.460143
false
false
false
false
quen2404/absolute0
Sources/App/Controllers/PostController.swift
1
1616
import Vapor import HTTP final class PostController: ResourceRepresentable { func index(request: Request) throws -> ResponseRepresentable { return try PostModel.all().makeNode().converted(to: JSON.self) } func create(request: Request) throws -> ResponseRepresentable { var todo = try request.post() try todo.save() return todo } func show(request: Request, post: PostModel) throws -> ResponseRepresentable { return post } func delete(request: Request, post: PostModel) throws -> ResponseRepresentable { try post.delete() return JSON([:]) } func clear(request: Request) throws -> ResponseRepresentable { try PostModel.query().delete() return JSON([]) } func update(request: Request, post: PostModel) throws -> ResponseRepresentable { let new = try request.post() var post = post post.content = new.content try post.save() return post } func replace(request: Request, post: PostModel) throws -> ResponseRepresentable { try post.delete() return try create(request: request) } func makeResource() -> Resource<PostModel> { return Resource( index: index, store: create, show: show, replace: replace, modify: update, destroy: delete, clear: clear ) } } extension Request { func post() throws -> PostModel { guard let json = json else { throw Abort.badRequest } return try PostModel(node: json) } }
mit
808227514b84e777a67c00e18bb4efaa
25.933333
85
0.602104
4.809524
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Views/AAConvActionSheet.swift
4
10756
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit import Photos public protocol AAConvActionSheetDelegate { func actionSheetPickedImages(_ images:[(Data,Bool)]) func actionSheetPickCamera() func actionSheetPickGallery() func actionSheetCustomButton(_ index: Int) } open class AAConvActionSheet: UIView, AAThumbnailViewDelegate { open var delegate: AAConvActionSheetDelegate? fileprivate let sheetView = UIView() fileprivate let backgroundView = UIView() fileprivate var sheetViewHeight: CGFloat = 0 fileprivate var thumbnailView: AAThumbnailView! fileprivate var buttons = [UIButton]() fileprivate var btnCamera: UIButton! fileprivate var btnLibrary: UIButton! fileprivate var btnCancel: UIButton! fileprivate weak var presentedInController: UIViewController! = nil open var enablePhotoPicker: Bool = true fileprivate var customActions = [String]() public init() { super.init(frame: CGRect.zero) self.backgroundColor = UIColor.clear } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func addCustomButton(_ title: String){ customActions.append(title) } open func presentInController(_ controller: UIViewController) { if controller.navigationController != nil { self.presentedInController = controller.navigationController } else { self.presentedInController = controller } if let navigation = presentedInController as? UINavigationController { navigation.interactivePopGestureRecognizer?.isEnabled = false } else if let navigation = presentedInController.navigationController { navigation.interactivePopGestureRecognizer?.isEnabled = false } frame = presentedInController.view.bounds presentedInController.view.addSubview(self) setupAllViews() self.sheetView.frame = CGRect(x: 0, y: self.frame.height, width: self.frame.width, height: sheetViewHeight) self.backgroundView.alpha = 0 dispatchOnUi { () -> Void in UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: UIViewAnimationOptions(), animations: { self.sheetView.frame = CGRect(x: 0, y: self.frame.height - self.sheetViewHeight, width: self.frame.width, height: self.sheetViewHeight) self.backgroundView.alpha = 1 }, completion: nil) } } open func dismiss() { var nextFrame = self.sheetView.frame nextFrame.origin.y = self.presentedInController.view.height if let navigation = presentedInController as? UINavigationController { navigation.interactivePopGestureRecognizer?.isEnabled = true } else if let navigation = presentedInController.navigationController { navigation.interactivePopGestureRecognizer?.isEnabled = true } UIView.animate(withDuration: 0.25, animations: { () -> Void in self.sheetView.frame = nextFrame self.backgroundView.alpha = 0}, completion: { (bool) -> Void in self.delegate = nil if self.thumbnailView != nil { self.thumbnailView.dismiss() self.thumbnailView = nil } self.removeFromSuperview() }) } fileprivate func setupAllViews() { // // Root Views // let superWidth = presentedInController.view.width let superHeight = presentedInController.view.height self.backgroundView.frame = presentedInController.view.bounds self.backgroundView.backgroundColor = UIColor.alphaBlack(0.7) self.backgroundView.alpha = 0 self.addSubview(self.backgroundView) // // Init Action Views // self.sheetViewHeight = 10 self.buttons.removeAll() if enablePhotoPicker { self.thumbnailView = AAThumbnailView(frame: CGRect(x: 0, y: 5, width: superWidth, height: 90)) self.thumbnailView.delegate = self self.thumbnailView.open() self.btnCamera = { let button = UIButton(type: UIButtonType.system) button.tintColor = UIColor(red: 5.0/255.0, green: 124.0/255.0, blue: 226.0/255.0, alpha: 1) button.titleLabel?.font = UIFont.systemFont(ofSize: 17) button.setTitle(AALocalized("PhotoCamera"), for: UIControlState()) button.addTarget(self, action: #selector(AAConvActionSheet.btnCameraAction), for: UIControlEvents.touchUpInside) return button }() self.buttons.append(self.btnCamera) self.btnLibrary = { let button = UIButton(type: UIButtonType.system) button.tintColor = UIColor(red: 5.0/255.0, green: 124.0/255.0, blue: 226.0/255.0, alpha: 1) button.titleLabel?.font = UIFont.systemFont(ofSize: 17) button.setTitle(AALocalized("PhotoLibrary"), for: UIControlState()) button.addTarget(self, action: #selector(AAConvActionSheet.btnLibraryAction), for: UIControlEvents.touchUpInside) return button }() self.buttons.append(self.btnLibrary) sheetViewHeight = 100 } for i in 0..<customActions.count { let b = customActions[i] self.buttons.append({ let button = UIButton(type: UIButtonType.system) button.tintColor = UIColor(red: 5.0/255.0, green: 124.0/255.0, blue: 226.0/255.0, alpha: 1) button.titleLabel?.font = UIFont.systemFont(ofSize: 17) button.setTitle(AALocalized(b), for: UIControlState()) button.tag = i button.addTarget(self, action: #selector(AAConvActionSheet.btnCustomAction(_:)), for: UIControlEvents.touchUpInside) return button }()) } self.btnCancel = { let button = UIButton(type: UIButtonType.system) button.tintColor = UIColor(red: 5.0/255.0, green: 124.0/255.0, blue: 226.0/255.0, alpha: 1) button.titleLabel?.font = UIFont.systemFont(ofSize: 17) button.setTitle(AALocalized("AlertCancel"), for: UIControlState()) button.addTarget(self, action: #selector(AAConvActionSheet.btnCloseAction), for: UIControlEvents.touchUpInside) return button }() self.buttons.append(self.btnCancel) sheetViewHeight += CGFloat(self.buttons.count * 50) // // Adding Elements // for b in self.buttons { self.sheetView.addSubview(b) } if self.thumbnailView != nil { self.sheetView.addSubview(self.thumbnailView) } // // Layouting // self.sheetView.frame = CGRect(x: 0, y: superHeight - sheetViewHeight, width: superWidth, height: sheetViewHeight) self.sheetView.backgroundColor = UIColor.white self.addSubview(self.sheetView) var topOffset: CGFloat = 10 if self.thumbnailView != nil { self.thumbnailView.frame = CGRect(x: 0, y: 5, width: superWidth, height: 90) topOffset += 90 } for b in self.buttons { b.frame = CGRect(x: 0, y: topOffset, width: superWidth, height: 50) let spearator = UIView(frame: CGRect(x: 0, y: topOffset - 1, width: superWidth, height: 1)) spearator.backgroundColor = UIColor(red: 223.9/255.0, green: 223.9/255.0, blue: 223.9/255.0, alpha: 0.6) self.sheetView.addSubview(spearator) topOffset += 50 } } open func thumbnailSelectedUpdated(_ selectedAssets: [(PHAsset,Bool)]) { if selectedAssets.count > 0 { var sendString:String if selectedAssets.count == 1 { sendString = AALocalized("AttachmentsSendPhoto").replace("{count}", dest: "\(selectedAssets.count)") } else { sendString = AALocalized("AttachmentsSendPhotos").replace("{count}", dest: "\(selectedAssets.count)") } // // remove target // self.btnCamera.removeTarget(self, action: #selector(AAConvActionSheet.btnCameraAction), for: UIControlEvents.touchUpInside) // // add new target // self.btnCamera.setTitle(sendString, for: UIControlState()) self.btnCamera.addTarget(self, action:#selector(AAConvActionSheet.sendPhotos), for: UIControlEvents.touchUpInside) self.btnCamera.titleLabel?.font = UIFont(name: "HelveticaNeue-Medium", size: 17) } else { // // remove target // self.btnCamera.removeTarget(self, action: #selector(AAConvActionSheet.sendPhotos), for: UIControlEvents.touchUpInside) // // add new target // self.btnCamera.setTitle(AALocalized("PhotoCamera"), for: UIControlState()) self.btnCamera.addTarget(self, action: #selector(AAConvActionSheet.btnCameraAction), for: UIControlEvents.touchUpInside) self.btnCamera.titleLabel?.font = UIFont.systemFont(ofSize: 17) } } // // Actions // func sendPhotos() { if self.thumbnailView != nil { self.thumbnailView.getSelectedAsImages { (images:[(Data,Bool)]) -> () in (self.delegate?.actionSheetPickedImages(images))! } } dismiss() } func btnCameraAction() { delegate?.actionSheetPickCamera() dismiss() } func btnLibraryAction() { delegate?.actionSheetPickGallery() dismiss() } func btnCustomAction(_ sender: UIButton) { delegate?.actionSheetCustomButton(sender.tag) dismiss() } func btnCloseAction() { dismiss() } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { dismiss() } }
agpl-3.0
14c0661b962f140904c469cf8683dfb9
35.835616
155
0.587393
4.977325
false
false
false
false
kelvincobanaj/mubu
Pods/Hakuba/Source/MYTableViewCell.swift
1
3448
// // MYTableViewCell.swift // Hakuba // // Created by Le Van Nghia on 1/13/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // import UIKit public class MYCellModel : MYViewModel { let identifier: String internal(set) var row: Int = 0 internal(set) var section: Int = 0 public var cellHeight: CGFloat = 44 public var cellSelectionEnabled = true public var editable = false public var calculatedHeight: CGFloat? public var dynamicHeightEnabled: Bool = false { didSet { calculatedHeight = nil } } public init(cellClass: AnyClass, height: CGFloat = 44, userData: AnyObject?, selectionHandler: MYSelectionHandler? = nil) { self.identifier = String.my_className(cellClass) self.cellHeight = height super.init(userData: userData, selectionHandler: selectionHandler) } public func slide(_ animation: MYAnimation = .None) -> Self { delegate?.reloadView(row, section: section, animation: animation) return self } } public class MYTableViewCell : UITableViewCell, MYBaseViewProtocol { class var identifier: String { return String.my_className(self) } var cellSelectionEnabled = true private weak var delegate: MYBaseViewDelegate? weak var cellModel: MYCellModel? public override init() { super.init() setup() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } public func setup() { } public func configureCell(data: MYCellModel) { cellModel = data delegate = data cellSelectionEnabled = data.cellSelectionEnabled unhighlight(false) } public func emitSelectedEvent(view: MYBaseViewProtocol) { delegate?.didSelect(view) } public func willAppear(data: MYCellModel) { } public func didDisappear(data: MYCellModel) { } } // MARK - Hightlight public extension MYTableViewCell { // ignore the default handling override func setHighlighted(highlighted: Bool, animated: Bool) { } override func setSelected(selected: Bool, animated: Bool) { } public func highlight(animated: Bool) { super.setHighlighted(true, animated: animated) } public func unhighlight(animated: Bool) { super.setHighlighted(false, animated: animated) } } // MARK - Touch events public extension MYTableViewCell { override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) if cellSelectionEnabled { highlight(false) } } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { super.touchesCancelled(touches, withEvent: event) if cellSelectionEnabled { unhighlight(false) } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { super.touchesEnded(touches, withEvent: event) if cellSelectionEnabled { emitSelectedEvent(self) } } }
mit
0eeb9d39153ced5135f108aa45e10170
26.373016
127
0.642981
4.723288
false
false
false
false
dche/FlatCG
Sources/Sphere.swift
1
1920
// // FlatCG - Sphere.swift // // Copyright (c) 2016 The GLMath authors. // Licensed under MIT License. import GLMath /// The (_n-sphere_)[https://en.wikipedia.org/wiki/N-sphere], which is the /// generalized concept of circle and sphere. public struct Nsphere<T: Point>: Equatable, CustomDebugStringConvertible { /// Center of the n-sphere. public let center: T /// Radius of the n-sphere. public let radius: T.VectorType.Component /// Constructs a `Nsphere` with given `center` and `radius`. /// /// Returns `nil` if `radius` is negative. public init? (center: T, radius: T.VectorType.Component) { guard radius >= 0 else { return nil } self.center = center self.radius = radius } } extension Nsphere { public static func == (lhs: Nsphere, rhs: Nsphere) -> Bool { return lhs.center == rhs.center && lhs.radius == rhs.radius } public var debugDescription: String { return "Nsphere(center: \(center), radius: \(radius))" } } // MARK: Sphere point relationship. extension Nsphere { /// Returns `true` if the `point` is inside the receiver. public func contains(point: T) -> Bool { return (point - self.center).squareLength < self.radius * self.radius } } extension Nsphere where T.VectorType: Vector2 { public init? ( x: T.VectorType.Component, y: T.VectorType.Component, radius: T.VectorType.Component ) { self.init(center: T(T.VectorType(x, y)), radius: radius) } } extension Nsphere where T.VectorType: Vector3 { public init? ( x: T.VectorType.Component, y: T.VectorType.Component, z: T.VectorType.Component, radius: T.VectorType.Component ) { self.init(center: T(T.VectorType(x, y, z)), radius: radius) } } public typealias Circle = Nsphere<Point2D> public typealias Sphere = Nsphere<Point3D>
mit
655b19704b71d54b2789f180b0927c92
24.6
77
0.636458
3.764706
false
false
false
false
radex/swift-compiler-crashes
crashes-duplicates/00207-swift-parser-parseexprcallsuffix.swift
12
1110
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } class f<p : k, p : k n p.d> : o { } class fclass func i() } i (d() as e).j.i() d protocol i : d { func d a=1 as a=1 } func a<g>() -> (g, g -> g) -> g { var b: ((g, g -> g) -> g)! return b } func f<g : d { return !(a) enum g { func g var _ = g func f<T : BooleanType>(b: T) { } f(true as BooleanType) struct c<d: SequenceType, b where Optional<b> == d.Generator.Element> var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) classwhere A.B == D>(e: A.B) { } } func a() as a).dynamicType.c() func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } } struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h } protocol a : a { } funcol n { j q } protocol k : k { } class k<f : l, q : l p f.q == q> { } protocol l { j q j o } struct n<r : l> class c { func b((Any, c))(a: (Any, AnyObject)) { b(a) } }
mit
e6484ba3f0d002f83b9ef34282515d66
16.076923
87
0.521622
2.557604
false
false
false
false
MrSuperJJ/JJMediatorDemo
JJMediatorDemo/Module/SwiftModule/Target_Action/Target_Swift.swift
1
1332
// // Target_Swfit.swift // JJMediator // // Created by yejiajun on 2017/5/9. // Copyright © 2017年 yejiajun. All rights reserved. // import UIKit class Target_Swift: NSObject { // 无入参无返回值 public func Action_swiftModuleMethod() { let swiftModule = SwiftModule() swiftModule.moduleMethod() } // 无入参返回对象类型 public func Action_swiftFetchNameFromModuleMethod() -> String? { let swiftModule = SwiftModule() let name = swiftModule.fetchNameFromModuleMethod() return name } // 有入参无返回值 public func Action_swiftModuleMethod(parameters: Dictionary<String, Any>) { let swiftModule = SwiftModule() let name = parameters["name"] as? String let callback = parameters["callback"] as? (String?) -> Void swiftModule.moduleMethod(withName: name, callback: callback) } // 有入参返回基本类型 public func Action_swiftFetchNumberFromModuleMethod(parameters: Dictionary<String, Any>) -> NSNumber { let swiftModule = SwiftModule() let number = parameters["number"] as! Int let result = swiftModule.fetchNumberFromModuleMethod(withNumber: number) let resultNumber = NSNumber(value: result) return resultNumber } }
mit
621a420ae0348410e51b72eb5daf5b90
28.418605
106
0.656917
4.216667
false
false
false
false
dnseitz/YAPI
YAPI/YAPI/YelpAPIFactory.swift
1
5908
// // YelpAPIFactory.swift // Chowroulette // // Created by Daniel Seitz on 7/25/16. // Copyright © 2016 Daniel Seitz. All rights reserved. // import Foundation import CoreLocation /** Factory class that generates Yelp requests and responses for use. */ public enum YelpAPIFactory { public enum V2 { /** Set the authentication keys that will be used to generate requests. These keys are needed in order for the Yelp API to successfully authenticate your requests, if you generate a request without these set the request will fail to send - Parameters: - consumerKey: The OAuth consumer key - consumerSecret: The OAuth consumer secret - token: The OAuth token - tokenSecret: The OAuth token secret */ public static func setAuthenticationKeys(consumerKey: String, consumerSecret: String, token: String, tokenSecret: String) { AuthKeys.consumerKey = consumerKey AuthKeys.consumerSecret = consumerSecret AuthKeys.token = token AuthKeys.tokenSecret = tokenSecret } /// The parameters to use when determining localization public static var localeParameters: YelpV2LocaleParameters? /// The parameters to use to determine whether to show action links public static var actionlinkParameters: YelpV2ActionlinkParameters? /** Build a search request with the specified request parameters - Parameter parameters: A struct containing information with which to create a request - Returns: A fully formed request that can be sent immediately */ public static func makeSearchRequest(with parameters: YelpV2SearchParameters) -> YelpV2SearchRequest { return YelpV2SearchRequest(search: parameters, locale: self.localeParameters, actionlink: self.actionlinkParameters) } /** Build a business request searching for the specified businessId - Parameter businessId: The Yelp businessId to search for - Returns: A fully formed request that can be sent immediately */ public static func makeBusinessRequest(with businessId: String) -> YelpV2BusinessRequest { return YelpV2BusinessRequest(businessId: businessId, locale: self.localeParameters, actionlink: self.actionlinkParameters) } /** Build a phone search request searching for a business with a certain phone number - Parameter parameters: A struct containing information with which to create a request - Returns: A fully formed request that can be sent immediately */ public static func makePhoneSearchRequest(with parameters: YelpV2PhoneSearchParameters) -> YelpV2PhoneSearchRequest { return YelpV2PhoneSearchRequest(phoneSearch: parameters) } } public enum V3 { public static func authenticate(appId: String, clientSecret: String, completionBlock: @escaping (_ error: YelpError?) -> Void) { AuthKeys.consumerKey = appId AuthKeys.consumerSecret = clientSecret let clientId = YelpV3TokenParameters.ClientID(internalValue: appId) let clientSecret = YelpV3TokenParameters.ClientSecret(internalValue: clientSecret) let request = makeTokenRequest(with: YelpV3TokenParameters(grantType: .clientCredentials, clientId: clientId, clientSecret: clientSecret)) request.send { result in switch result { case .ok(let response): AuthKeys.token = response.accessToken completionBlock(response.error) case .err(let error): completionBlock(error) } } } private static func makeTokenRequest(with parameters: YelpV3TokenParameters) -> YelpV3TokenRequest { return YelpV3TokenRequest(token: parameters) } public static func makeSearchRequest(with parameters: YelpV3SearchParameters) -> YelpV3SearchRequest { return YelpV3SearchRequest(searchParameters: parameters) } } /** Build a response from the JSON body recieved from making a request. - Parameter json: A dictionary containing the JSON body recieved in the Yelp response - Parameter request: The request that was sent in order to recieve this response - Returns: A valid response object, populated with businesses or an error */ static func makeResponse<T: YelpRequest>(withJSON json: [String: AnyObject], from request: T) -> Result<T.Response, YelpError> { do { return try .ok(T.Response.init(withJSON: json)) } catch let error as YelpParseError { return .err(YelpResponseError.failedToParse(cause: error)) } catch let error as YelpError { return .err(error) } catch { return .err(YelpResponseError.unknownError(cause: error)) } } /** Build a response from the still encoded body recieved from making a request. - Parameter data: An NSData object of the data recieved from a Yelp response - Parameter request: The request that was sent in order to recieve this response - Returns: A valid response object, or nil if the data cannot be parsed */ static func makeResponse<T: YelpRequest>(with data: Data, from request: T) -> Result<T.Response, YelpError> { do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) return YelpAPIFactory.makeResponse(withJSON: json as! [String: AnyObject], from: request) } catch { return .err(YelpResponseError.failedToParse(cause: .invalidJson(cause: error))) } } }
mit
621d3e12476f10477fa8c7c8764c6267
37.357143
130
0.663958
5.083477
false
false
false
false
devpunk/velvet_room
Source/Model/Connecting/Socket/Abstract/MConnectingSocketStart.swift
1
1242
import Foundation extension MConnectingSocket { //MARK: private private func asyncStart() { guard let modelTcp:MConnectingSocketTcp = factoryTcp() else { failedTcpSocket() return } guard let modelUdp:MConnectingSocketUdp = factoryUdp() else { modelTcp.cancel() failedUdpSocket() return } self.modelTcp = modelTcp self.modelUdp = modelUdp } private func failedTcpSocket() { let message:String = String.localizedModel( key:"MConnectingSocket_failedTcpSocket") model?.foundError(errorMessage:message) } private func failedUdpSocket() { let message:String = String.localizedModel( key:"MConnectingSocket_failedUdpSocket") model?.foundError(errorMessage:message) } //MARK: internal func start() { DispatchQueue.global( qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.asyncStart() } } }
mit
a7eab3a1720e1447c42776a765186de6
19.360656
60
0.509662
5.240506
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/MediaProgressCoordinatorTests.swift
1
10115
import Foundation import XCTest @testable import WordPress class MediaProgressCoordinatorTests: CoreDataTestCase { var mediaProgressCoordinator: MediaProgressCoordinator! fileprivate func makeTestMedia() -> Media { return NSEntityDescription.insertNewObject(forEntityName: Media.classNameWithoutNamespaces(), into: mainContext) as! Media } fileprivate func makeTestError() -> NSError { return NSError(domain: "org.wordpress.media-tests", code: 1, userInfo: nil) } override func setUp() { super.setUp() mediaProgressCoordinator = MediaProgressCoordinator() } override func tearDown() { mediaProgressCoordinator = nil super.tearDown() } func testSimpleOneUpload() { let mediaProgressCoordinator = MediaProgressCoordinator() mediaProgressCoordinator.track(numberOfItems: 1) XCTAssertTrue(mediaProgressCoordinator.isRunning, "Coordinator should be running") let progress = Progress.discreteProgress(totalUnitCount: 4) mediaProgressCoordinator.track(progress: progress, of: makeTestMedia(), withIdentifier: "progress") XCTAssertTrue(mediaProgressCoordinator.isRunning, "Coordinator should be running") XCTAssertTrue(mediaProgressCoordinator.cancelledMediaIDs.isEmpty, "No canceled ids") XCTAssertTrue(mediaProgressCoordinator.failedMediaIDs.isEmpty, "No failed ids") XCTAssertEqual(0, mediaProgressCoordinator.totalProgress, "Total progress should be 0") progress.completedUnitCount += 1 XCTAssertEqual(0.25, mediaProgressCoordinator.totalProgress, "Total progress should be 0.25") progress.completedUnitCount += 1 XCTAssertEqual(0.5, mediaProgressCoordinator.totalProgress, "Total progress should be 0.5") progress.completedUnitCount += 1 XCTAssertEqual(0.75, mediaProgressCoordinator.totalProgress, "Total progress should be 0.75") progress.completedUnitCount += 1 XCTAssertEqual(1, mediaProgressCoordinator.totalProgress, "Total progress should be 1") XCTAssertFalse(mediaProgressCoordinator.isRunning, "Coordinator should be stopped") XCTAssertFalse(mediaProgressCoordinator.hasFailedMedia, "Coordinator should not have failed media") } func testSimpleOneUploadThatIsCancelled() { let mediaProgressCoordinator = MediaProgressCoordinator() mediaProgressCoordinator.track(numberOfItems: 1) XCTAssertTrue(mediaProgressCoordinator.isRunning, "Coordinator should be running") let progress = Progress.discreteProgress(totalUnitCount: 4) mediaProgressCoordinator.track(progress: progress, of: makeTestMedia(), withIdentifier: "progress1") XCTAssertTrue(mediaProgressCoordinator.isRunning, "Coordinator should be running") XCTAssertEqual(0, mediaProgressCoordinator.totalProgress, "Total progress should be 0") progress.completedUnitCount += 1 XCTAssertEqual(0.25, mediaProgressCoordinator.totalProgress, "Total progress should be 0.25") progress.completedUnitCount += 1 XCTAssertEqual(0.5, mediaProgressCoordinator.totalProgress, "Total progress should be 0.5") progress.completedUnitCount += 1 XCTAssertEqual(0.75, mediaProgressCoordinator.totalProgress, "Total progress should be 0.75") progress.cancel() XCTAssertEqual(0.75, mediaProgressCoordinator.totalProgress, "Total progress should be 0.75") XCTAssertFalse(mediaProgressCoordinator.isRunning, "Coordinator should be stopped") XCTAssertFalse(mediaProgressCoordinator.hasFailedMedia, "Coordinator should have failed media") } func testTwoUploads() { let mediaProgressCoordinator = MediaProgressCoordinator() mediaProgressCoordinator.track(numberOfItems: 2) XCTAssertTrue(mediaProgressCoordinator.isRunning, "Coordinator should be running") let progress1 = Progress.discreteProgress(totalUnitCount: 2) let progress2 = Progress.discreteProgress(totalUnitCount: 2) mediaProgressCoordinator.track(progress: progress1, of: makeTestMedia(), withIdentifier: "progress1") mediaProgressCoordinator.track(progress: progress2, of: makeTestMedia(), withIdentifier: "progress2") XCTAssertTrue(mediaProgressCoordinator.isRunning, "Coordinator should be running") XCTAssertEqual(0, mediaProgressCoordinator.totalProgress, "Total progress should be 0") progress1.completedUnitCount += 1 XCTAssertEqual(0.25, mediaProgressCoordinator.totalProgress, "Total progress should be 0.25") progress1.completedUnitCount += 1 XCTAssertEqual(0.5, mediaProgressCoordinator.totalProgress, "Total progress should be 0.5") progress2.completedUnitCount += 1 XCTAssertEqual(0.75, mediaProgressCoordinator.totalProgress, "Total progress should be 0.75") progress2.completedUnitCount += 1 XCTAssertEqual(1, mediaProgressCoordinator.totalProgress, "Total progress should be 1") XCTAssertFalse(mediaProgressCoordinator.isRunning, "Coordinator should be stopped") XCTAssertFalse(mediaProgressCoordinator.hasFailedMedia, "Coordinator should not have failed media") } func testAddToMediaProgress() { let totalItems = 10 mediaProgressCoordinator.track(numberOfItems: totalItems) XCTAssertNotNil(mediaProgressCoordinator.mediaGlobalProgress, "Progress should exist") XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.totalUnitCount == Int64(totalItems), "There should a total number of 10 items") XCTAssertTrue(mediaProgressCoordinator.isRunning) for index in 1...totalItems { let progress = Progress.discreteProgress(totalUnitCount: 1) mediaProgressCoordinator.track(progress: progress, of: makeTestMedia(), withIdentifier: "\(index)") progress.completedUnitCount = 1 XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.completedUnitCount == Int64(index)) } XCTAssertFalse(mediaProgressCoordinator.isRunning) } func testMediaProgressThatFails() { mediaProgressCoordinator.track(numberOfItems: 1) XCTAssertNotNil(mediaProgressCoordinator.mediaGlobalProgress, "Progress should exist") XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.totalUnitCount == 1, "There should 1 item") let progress = Progress.discreteProgress(totalUnitCount: 1) mediaProgressCoordinator.track(progress: progress, of: makeTestMedia(), withIdentifier: "1") XCTAssertTrue(mediaProgressCoordinator.isRunning) // simulate a failed request progress.completedUnitCount = 0 mediaProgressCoordinator.attach(error: makeTestError(), toMediaID: "1") XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.completedUnitCount == 0) XCTAssertFalse(mediaProgressCoordinator.isRunning) } func testMultipleMediaProgressAllFailed() { mediaProgressCoordinator.track(numberOfItems: 3) XCTAssertNotNil(mediaProgressCoordinator.mediaGlobalProgress, "Progress should exist") XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.totalUnitCount == 3, "There should be 3 items") for index in 1...3 { let progress = Progress.discreteProgress(totalUnitCount: 1) mediaProgressCoordinator.track(progress: progress, of: makeTestMedia(), withIdentifier: "\(index)") } XCTAssertTrue(mediaProgressCoordinator.isRunning) // Fail all the requests mediaProgressCoordinator.mediaInProgress.values.enumerated().forEach({ index, progress in progress.completedUnitCount = 0 mediaProgressCoordinator.attach(error: makeTestError(), toMediaID: "\(index+1)") }) XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.completedUnitCount == 0) XCTAssertFalse(mediaProgressCoordinator.isRunning) } func testMultipleMediaProgressPartiallyFailed() { mediaProgressCoordinator.track(numberOfItems: 3) XCTAssertNotNil(mediaProgressCoordinator.mediaGlobalProgress, "Progress should exist") XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.totalUnitCount == 3, "There should be 3 items") for index in 1...3 { let progress = Progress.discreteProgress(totalUnitCount: 1) mediaProgressCoordinator.track(progress: progress, of: makeTestMedia(), withIdentifier: "\(index)") } XCTAssertTrue(mediaProgressCoordinator.isRunning) // Fail 2 of the requests mediaProgressCoordinator.mediaInProgress["1"]!.completedUnitCount = 0 mediaProgressCoordinator.mediaInProgress["2"]!.completedUnitCount = 0 mediaProgressCoordinator.attach(error: makeTestError(), toMediaID: "1") mediaProgressCoordinator.attach(error: makeTestError(), toMediaID: "2") XCTAssertTrue(mediaProgressCoordinator.isRunning) // Complete the 3rd mediaProgressCoordinator.mediaInProgress["3"]!.completedUnitCount = 1 XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.completedUnitCount == 1) XCTAssertFalse(mediaProgressCoordinator.isRunning) } func testMediaProgressThatIsCanceled() { mediaProgressCoordinator.track(numberOfItems: 1) XCTAssertNotNil(mediaProgressCoordinator.mediaGlobalProgress, "Progress should exist") XCTAssertTrue(mediaProgressCoordinator.mediaGlobalProgress!.totalUnitCount == Int64(1), "There should 1 item") let progress = Progress.discreteProgress(totalUnitCount: 1) mediaProgressCoordinator.track(progress: progress, of: makeTestMedia(), withIdentifier: "\(String(describing: index))") XCTAssertTrue(mediaProgressCoordinator.isRunning) // simulate a canceled request progress.cancel() XCTAssertFalse(mediaProgressCoordinator.mediaGlobalProgress!.isCancelled) XCTAssertFalse(mediaProgressCoordinator.isRunning) } }
gpl-2.0
9120a63b6c958b11c6679150dc56e69c
43.170306
147
0.738507
5.988751
false
true
false
false
kickstarter/ios-oss
Library/ViewModels/SignupViewModel.swift
1
7774
import Foundation import KsApi import Prelude import ReactiveSwift public protocol SignupViewModelInputs { /// Call when the user enters a new email address. func emailChanged(_ email: String) /// Call when the user returns from email text field. func emailTextFieldReturn() /// Call when the environment has been logged into func environmentLoggedIn() /// Call when the user enters a new name. func nameChanged(_ name: String) /// Call when the user returns from the name text field. func nameTextFieldReturn() /// Call when the user enters a new password. func passwordChanged(_ password: String) /// Call when the user returns from the password text field. func passwordTextFieldReturn() /// Call when the user taps signup. func signupButtonPressed() /// Call when link tapped on disclaimer textView func tapped(_ url: URL) /// Call when the view did load. func viewDidLoad() /// Call when the user toggles weekly newsletter. func weeklyNewsletterChanged(_ weeklyNewsletter: Bool) } public protocol SignupViewModelOutputs { /// Sets whether the email text field is the first responder. var emailTextFieldBecomeFirstResponder: Signal<(), Never> { get } /// Emits true when the signup button should be enabled, false otherwise. var isSignupButtonEnabled: Signal<Bool, Never> { get } /// Emits an access token envelope that can be used to update the environment. var logIntoEnvironment: Signal<AccessTokenEnvelope, Never> { get } /// Sets whether the name text field is the first responder. var nameTextFieldBecomeFirstResponder: Signal<(), Never> { get } /// Emits when a help link from a disclaimer should be opened. var notifyDelegateOpenHelpType: Signal<HelpType, Never> { get } /// Sets whether the password text field is the first responder. var passwordTextFieldBecomeFirstResponder: Signal<(), Never> { get } /// Emits when a notification should be posted. var postNotification: Signal<Notification, Never> { get } /// Emits the value for the weekly newsletter. var setWeeklyNewsletterState: Signal<Bool, Never> { get } /// Emits when a signup error has occurred and a message should be displayed. var showError: Signal<String, Never> { get } } public protocol SignupViewModelType { var inputs: SignupViewModelInputs { get } var outputs: SignupViewModelOutputs { get } } public final class SignupViewModel: SignupViewModelType, SignupViewModelInputs, SignupViewModelOutputs { public init() { let initialText = self.viewDidLoadProperty.signal.mapConst("") let name = Signal.merge( self.nameChangedProperty.signal, initialText ) let email = Signal.merge( self.emailChangedProperty.signal, initialText ) let password = Signal.merge( self.passwordChangedProperty.signal, initialText ) let isSubscribed = Signal.merge( self.viewDidLoadProperty.signal.mapConst(false), self.weeklyNewsletterChangedProperty.signal.skipNil() ) let nameIsPresent = name.map { !$0.isEmpty } let emailIsPresent = email.map { !$0.isEmpty } let passwordIsPresent = password.map { !$0.isEmpty } self.nameTextFieldBecomeFirstResponder = self.viewDidLoadProperty.signal self.emailTextFieldBecomeFirstResponder = self.nameTextFieldReturnProperty.signal self.passwordTextFieldBecomeFirstResponder = self.emailTextFieldReturnProperty.signal self.isSignupButtonEnabled = Signal.combineLatest(nameIsPresent, emailIsPresent, passwordIsPresent) .map { $0 && $1 && $2 } .skipRepeats() self.setWeeklyNewsletterState = isSubscribed.take(first: 1) let attemptSignup = Signal.merge( self.passwordTextFieldReturnProperty.signal, self.signupButtonPressedProperty.signal ) let signupEvent = Signal.combineLatest(name, email, password, isSubscribed) .takeWhen(attemptSignup) .switchMap { name, email, password, newsletter in AppEnvironment.current.apiService.signup( name: name, email: email, password: password, passwordConfirmation: password, sendNewsletters: newsletter ) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .materialize() } let signupError = signupEvent.errors() .map { $0.errorMessages.first ?? Strings.signup_error_something_wrong() } self.showError = signupError self.logIntoEnvironment = signupEvent.values() self.postNotification = self.environmentLoggedInProperty.signal .mapConst(Notification(name: .ksr_sessionStarted)) self.notifyDelegateOpenHelpType = self.tappedUrlProperty.signal.skipNil().map { url -> HelpType? in HelpType.allCases.first(where: { url.absoluteString == $0.url( withBaseUrl: AppEnvironment.current.apiService.serverConfig.webBaseUrl )?.absoluteString }) } .skipNil() // Tracking isSubscribed.takeWhen(attemptSignup) .observeValues { isSubscribed in AppEnvironment.current.ksrAnalytics.trackSignupSubmitButtonClicked(isSubscribed: isSubscribed) } self.viewDidLoadProperty.signal .observeValues { AppEnvironment.current.ksrAnalytics.trackSignupPageViewed() } } fileprivate let emailChangedProperty = MutableProperty("") public func emailChanged(_ email: String) { self.emailChangedProperty.value = email } fileprivate let emailTextFieldReturnProperty = MutableProperty(()) public func emailTextFieldReturn() { self.emailTextFieldReturnProperty.value = () } fileprivate let environmentLoggedInProperty = MutableProperty(()) public func environmentLoggedIn() { self.environmentLoggedInProperty.value = () } fileprivate let nameChangedProperty = MutableProperty("") public func nameChanged(_ name: String) { self.nameChangedProperty.value = name } fileprivate let nameTextFieldReturnProperty = MutableProperty(()) public func nameTextFieldReturn() { self.nameTextFieldReturnProperty.value = () } fileprivate let passwordChangedProperty = MutableProperty("") public func passwordChanged(_ password: String) { self.passwordChangedProperty.value = password } fileprivate let passwordTextFieldReturnProperty = MutableProperty(()) public func passwordTextFieldReturn() { self.passwordTextFieldReturnProperty.value = () } fileprivate let signupButtonPressedProperty = MutableProperty(()) public func signupButtonPressed() { self.signupButtonPressedProperty.value = () } private let tappedUrlProperty = MutableProperty<(URL)?>(nil) public func tapped(_ url: URL) { self.tappedUrlProperty.value = url } fileprivate let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } fileprivate let weeklyNewsletterChangedProperty = MutableProperty<Bool?>(nil) public func weeklyNewsletterChanged(_ weeklyNewsletter: Bool) { self.weeklyNewsletterChangedProperty.value = weeklyNewsletter } public let emailTextFieldBecomeFirstResponder: Signal<(), Never> public let isSignupButtonEnabled: Signal<Bool, Never> public let logIntoEnvironment: Signal<AccessTokenEnvelope, Never> public let nameTextFieldBecomeFirstResponder: Signal<(), Never> public let notifyDelegateOpenHelpType: Signal<HelpType, Never> public let passwordTextFieldBecomeFirstResponder: Signal<(), Never> public let postNotification: Signal<Notification, Never> public let setWeeklyNewsletterState: Signal<Bool, Never> public let showError: Signal<String, Never> public var inputs: SignupViewModelInputs { return self } public var outputs: SignupViewModelOutputs { return self } }
apache-2.0
12ec5acf9f8d8cf5395d0e4d9fdf5ebf
33.096491
104
0.738359
4.96424
false
false
false
false
DianQK/Flix
Flix/Builder/_TableViewBuilder.swift
1
10709
// // _TableViewBuilder.swift // Flix // // Created by DianQK on 22/10/2017. // Copyright © 2017 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources protocol _TableViewBuilder: Builder { var disposeBag: DisposeBag { get } var delegateProxy: TableViewDelegateProxy { get } var tableView: UITableView { get } var nodeProviders: [String: _TableViewMultiNodeProvider] { get } var footerSectionProviders: [String: _SectionPartionTableViewProvider] { get } var headerSectionProviders: [String: _SectionPartionTableViewProvider] { get } } protocol FlixSectionModelType: SectionModelType { associatedtype Section var model: Section { get } init(model: Section, items: [Item]) } extension AnimatableSectionModel: FlixSectionModelType { } extension SectionModel: FlixSectionModelType { } extension _TableViewBuilder { func build<S: FlixSectionModelType>(dataSource: TableViewSectionedDataSource<S>) where S.Item: _Node, S.Section: _SectionNode { dataSource.canEditRowAtIndexPath = { [weak tableView, weak self] (dataSource, indexPath) in guard let tableView = tableView else { return false } let node = dataSource[indexPath] guard let provider = self?.nodeProviders[node.providerIdentity] else { return false } if let provider = provider as? _TableViewEditable { return provider._tableView(tableView, canEditRowAt: indexPath, node: node) } else { return false } } dataSource.canMoveRowAtIndexPath = { [weak tableView, weak self] (dataSource, indexPath) in guard let tableView = tableView else { return false } let node = dataSource[indexPath] guard let provider = self?.nodeProviders[node.providerIdentity] else { return false } if let provider = provider as? _TableViewMoveable { return provider._tableView(tableView, canMoveRowAt: indexPath, node: node) } else { return false } } tableView.rx.itemSelected .subscribe(onNext: { [weak tableView, unowned self] (indexPath) in guard let tableView = tableView else { return } let node = dataSource[indexPath] let provider = self.nodeProviders[node.providerIdentity] provider?._itemSelected(tableView, indexPath: indexPath, node: node) }) .disposed(by: disposeBag) tableView.rx.itemDeselected .subscribe(onNext: { [weak tableView, unowned self] (indexPath) in guard let tableView = tableView else { return } let node = dataSource[indexPath] let provider = self.nodeProviders[node.providerIdentity] provider?._itemDeselected(tableView, indexPath: indexPath, node: node) }) .disposed(by: disposeBag) tableView.rx.itemDeleted .subscribe(onNext: { [weak tableView, unowned self] (indexPath) in guard let tableView = tableView else { return } let node = dataSource[indexPath] let provider = self.nodeProviders[node.providerIdentity]! as? _TableViewDeleteable provider?._tableView(tableView, itemDeletedForRowAt: indexPath, node: node) }) .disposed(by: disposeBag) tableView.rx.itemMoved .subscribe(onNext: { [weak tableView, unowned self] (itemMovedEvent) in guard let tableView = tableView else { return } let node = dataSource[itemMovedEvent.destinationIndex] guard let provider = self.nodeProviders[node.providerIdentity] as? _TableViewMoveable else { return } provider._tableView( tableView, moveRowAt: itemMovedEvent.sourceIndex.row - node.providerStartIndexPath.row, to: itemMovedEvent.destinationIndex.row - node.providerStartIndexPath.row, node: node ) }) .disposed(by: disposeBag) tableView.rx.itemInserted .subscribe(onNext: { [weak tableView, unowned self] (indexPath) in guard let tableView = tableView else { return } let node = dataSource[indexPath] let provider = self.nodeProviders[node.providerIdentity]! as? _TableViewInsertable provider?._tableView(tableView, itemInsertedForRowAt: indexPath, node: node) }) .disposed(by: disposeBag) self.delegateProxy.heightForRowAt = { [unowned self] tableView, indexPath in let node = dataSource[indexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! return provider._tableView(tableView, heightForRowAt: indexPath, node: node) } self.delegateProxy.editActionsForRowAt = { [unowned self] tableView, indexPath in let node = dataSource[indexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! if let provider = provider as? _TableViewEditable { return provider._tableView(tableView, editActionsForRowAt: indexPath, node: node) } else { return nil } } if #available(iOS 11.0, *) { self.delegateProxy.leadingSwipeActionsConfigurationForRowAt = { [unowned self] tableView, indexPath in let node = dataSource[indexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! if let provider = provider as? _TableViewSwipeable { return provider._tableView(tableView, leadingSwipeActionsConfigurationForRowAt: indexPath, node: node) } else { return nil } } self.delegateProxy.trailingSwipeActionsConfigurationForRowAt = { [unowned self] tableView, indexPath in let node = dataSource[indexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! if let provider = provider as? _TableViewSwipeable { return provider._tableView(tableView, trailingSwipeActionsConfigurationForRowAt: indexPath, node: node) } else { return nil } } } self.delegateProxy.targetIndexPathForMoveFromRowAt = { [unowned self] tableView, sourceIndexPath, proposedDestinationIndexPath in let node = dataSource[sourceIndexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! if let _ = provider as? _TableViewMoveable { if (proposedDestinationIndexPath <= node.providerStartIndexPath) { return node.providerStartIndexPath } else if (proposedDestinationIndexPath >= node.providerEndIndexPath) { return node.providerEndIndexPath } else { return proposedDestinationIndexPath } } else { return proposedDestinationIndexPath } } self.delegateProxy.titleForDeleteConfirmationButtonForRowAt = { [unowned self] tableView, indexPath in let node = dataSource[indexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! if let provider = provider as? _TableViewDeleteable { return provider._tableView(tableView, titleForDeleteConfirmationButtonForRowAt: indexPath, node: node) } else { return nil } } self.delegateProxy.editingStyleForRowAt = { [unowned self] tableView, indexPath in let node = dataSource[indexPath] let providerIdentity = node.providerIdentity let provider = self.nodeProviders[providerIdentity]! if let provider = provider as? _TableViewEditable { return provider._tableView(tableView, editingStyleForRowAt: indexPath, node: node) } else { return UITableViewCell.EditingStyle.none } } self.delegateProxy.heightForHeaderInSection = { [unowned self] tableView, section in guard let headerNode = dataSource[section].model.headerNode else { return nil } let providerIdentity = headerNode.providerIdentity let provider = self.headerSectionProviders[providerIdentity]! return provider._tableView(tableView, heightInSection: section, node: headerNode) } self.delegateProxy.viewForHeaderInSection = { [unowned self] tableView, section in guard let node = dataSource[section].model.headerNode else { return UIView() } let provider = self.headerSectionProviders[node.providerIdentity]! let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: provider._flix_identity)! provider._configureSection(tableView, view: view, viewInSection: section, node: node) return view } self.delegateProxy.viewForFooterInSection = { [unowned self] tableView, section in guard let node = dataSource[section].model.footerNode else { return UIView() } let provider = self.footerSectionProviders[node.providerIdentity]! let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: provider._flix_identity)! provider._configureSection(tableView, view: view, viewInSection: section, node: node) return view } self.delegateProxy.heightForFooterInSection = { [unowned self] tableView, section in guard let footerNode = dataSource[section].model.footerNode else { return nil } let providerIdentity = footerNode.providerIdentity let provider = self.footerSectionProviders[providerIdentity]! return provider._tableView(tableView, heightInSection: section, node: footerNode) } tableView.rx.setDelegate(self.delegateProxy).disposed(by: disposeBag) } }
mit
d97e38d63e634dfbbd1c64180ac2e22b
45.556522
137
0.625233
5.585811
false
false
false
false
apple/swift-nio
Tests/NIOPosixTests/UniversalBootstrapSupportTest+XCTest.swift
1
1228
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // UniversalBootstrapSupportTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension UniversalBootstrapSupportTest { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (UniversalBootstrapSupportTest) -> () throws -> Void)] { return [ ("testBootstrappingWorks", testBootstrappingWorks), ("testBootstrapOverrideOfShortcutOptions", testBootstrapOverrideOfShortcutOptions), ] } }
apache-2.0
65c15970130ea97e2bd63fbcff26da06
34.085714
162
0.62785
5.07438
false
true
false
false
emadhegab/GenericDataSource
Sources/SegmentedDataSource.swift
3
30255
// // SegmentedDataSource.swift // GenericDataSource // // Created by Mohamed Afifi on 11/13/16. // Copyright © 2016 mohamede1945. All rights reserved. // import Foundation /// The composite data source class that is responsible for managing a set of children data sources. /// Delegating requests to the selected child data source to respond. /// If the `selectedDataSource` is nil, calls to `DataSource` methods will crash. open class SegmentedDataSource: AbstractDataSource, CollectionDataSource { /// Returns a string that describes the contents of the receiver. open override var description: String { let properties: [(String, Any?)] = [ ("selectedDataSource", selectedDataSource), ("scrollViewDelegate", scrollViewDelegate), ("supplementaryViewCreator", supplementaryViewCreator)] return describe(self, properties: properties) } private var childrenReusableDelegate: _DelegatedGeneralCollectionView! /// Creates new instance. public override init() { super.init() let mapping = _SegmentedGeneralCollectionViewMapping(parentDataSource: self) childrenReusableDelegate = _DelegatedGeneralCollectionView(mapping: mapping) } // MARK: - Children DataSources /// Represents the selected data source index or `NSNotFound` if no data source selected. open var selectedDataSourceIndex: Int { set { precondition(newValue < dataSources.count, "[GenericDataSource] invalid selectedDataSourceIndex, should be less than \(dataSources.count)") precondition(newValue >= 0, "[GenericDataSource] invalid selectedDataSourceIndex, should be greater than or equal to 0.") selectedDataSource = dataSources[newValue] } get { return dataSources.index { $0 === selectedDataSource } ?? NSNotFound } } /// Represents the selected data source or nil if not selected. open var selectedDataSource: DataSource? private var unsafeSelectedDataSource: DataSource { guard let selectedDataSource = selectedDataSource else { fatalError("[\(type(of: self))]: Calling SegmentedDataSource methods with nil selectedDataSource") } return selectedDataSource } /// Returns the list of children data sources. open private(set) var dataSources: [DataSource] = [] /** Adds a new data source to the list of children data sources. - parameter dataSource: The new data source to add. */ open func add(_ dataSource: DataSource) { dataSource.ds_reusableViewDelegate = childrenReusableDelegate dataSources.append(dataSource) if selectedDataSource == nil { selectedDataSource = dataSource } } /** Inserts the data source to the list of children data sources at specific index. - parameter dataSource: The new data source to add. - parameter index: The index to insert the new data source at. */ open func insert(_ dataSource: DataSource, at index: Int) { dataSource.ds_reusableViewDelegate = childrenReusableDelegate dataSources.insert(dataSource, at: index) if selectedDataSource == nil { selectedDataSource = dataSource } } /** Removes a data source from the children data sources list. - parameter dataSource: The data source to remove. */ open func remove(_ dataSource: DataSource) { guard let index = index(of: dataSource) else { return } remove(at: index) } @discardableResult open func remove(at index: Int) -> DataSource { let dataSource = dataSources.remove(at: index) if dataSource === selectedDataSource { selectedDataSource = dataSources.first } return dataSource } /// Clear the collection of data sources. open func removeAllDataSources() { dataSources.removeAll() selectedDataSource = nil } /** Returns the data source at certain index. - parameter index: The index of the data source to return. - returns: The data source at specified index. */ open func dataSource(at index: Int) -> DataSource { return dataSources[index] } /** Check if a data source exists or not. - parameter dataSource: The data source to check. - returns: `true``, if the data source exists. Otherwise `false`. */ open func contains(_ dataSource: DataSource) -> Bool { return dataSources.contains { $0 === dataSource } } /** Gets the index of a data source or `nil` if not exist. - parameter dataSource: The data source to get the index for. - returns: The index of the data source. */ open func index(of dataSource: DataSource) -> Int? { return dataSources.index { $0 === dataSource } } // MARK: - Responds /// Asks the data source if it responds to a given selector. /// /// This method returns `true` if the selected data source can respond to the selector. /// /// - Parameter selector: The selector to check if the instance repsonds to. /// - Returns: `true` if the instance responds to the passed selector, otherwise `false`. open override func ds_responds(to selector: DataSourceSelector) -> Bool { // we always define last one as DataSource selector. let theSelector = dataSourceSelectorToSelectorMapping[selector]!.last! // check if the subclass implemented the selector, always return true if subclassHasDifferentImplmentation(type: SegmentedDataSource.self, selector: theSelector) { return true } return selectedDataSource?.ds_responds(to: selector) ?? false } // MARK: - IndexPath and Section translations /** Converts a section value relative to a specific data source to a section value relative to the composite data source. - parameter section: The local section relative to the passed data source. - parameter dataSource: The data source that is the local section is relative to it. Should be a child data source. - returns: The global section relative to the composite data source. */ open func globalSectionForLocalSection(_ section: Int, dataSource: DataSource) -> Int { return section } /** Converts a section value relative to the composite data source to a section value relative to a specific data source. - parameter section: The section relative to the compsite data source. - parameter dataSource: The data source that is the returned local section is relative to it. Should be a child data source. - returns: The global section relative to the composite data source. */ open func localSectionForGlobalSection(_ section: Int, dataSource: DataSource) -> Int { return section } /** Converts an index path value relative to a specific data source to an index path value relative to the composite data source. - parameter indexPath: The local index path relative to the passed data source. - parameter dataSource: The data source that is the local index path is relative to it. Should be a child data source. - returns: The global index path relative to the composite data source. */ open func globalIndexPathForLocalIndexPath(_ indexPath: IndexPath, dataSource: DataSource) -> IndexPath { return indexPath } /** Converts an index path value relative to the composite data source to an index path value relative to a specific data source. - parameter indexPath: The index path relative to the compsite data source. - parameter dataSource: The data source that is the returned local index path is relative to it. Should be a child data source. - returns: The global index path relative to the composite data source. */ open func localIndexPathForGlobalIndexPath(_ indexPath: IndexPath, dataSource: DataSource) -> IndexPath { return indexPath } // MARK: - Cell /** Asks the data source to return the number of sections. `1` for Single Section. `dataSources.count` for Multi section. - returns: The number of sections. */ open override func ds_numberOfSections() -> Int { return unsafeSelectedDataSource.ds_numberOfSections() } /** Asks the data source to return the number of items in a given section. - parameter section: An index number identifying a section. - returns: The number of items in a given section */ open override func ds_numberOfItems(inSection section: Int) -> Int { return unsafeSelectedDataSource.ds_numberOfItems(inSection: section) } /** Asks the data source for a cell to insert in a particular location of the general collection view. - parameter collectionView: A general collection view object requesting the cell. - parameter indexPath: An index path locating an item in the view. - returns: An object conforming to ReusableCell that the view can use for the specified item. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, cellForItemAt indexPath: IndexPath) -> ReusableCell { return unsafeSelectedDataSource.ds_collectionView(collectionView, cellForItemAt: indexPath) } // MARK: - Size /** Asks the data source for the size of a cell in a particular location of the general collection view. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. - returns: The size of the cell in a given location. For `UITableView`, the width is ignored. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, sizeForItemAt indexPath: IndexPath) -> CGSize { return unsafeSelectedDataSource.ds_collectionView!(collectionView, sizeForItemAt: indexPath) } // MARK: - Selection /** Asks the delegate if the specified item should be highlighted. `true` if the item should be highlighted or `false` if it should not. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. - returns: `true` if the item should be highlighted or `false` if it should not. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, shouldHighlightItemAt: indexPath) } /** Tells the delegate that the specified item was highlighted. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, didHighlightItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, didHighlightItemAt: indexPath) } /** Tells the delegate that the highlight was removed from the item at the specified index path. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, didUnhighlightItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, didUnhighlightItemAt: indexPath) } /** Asks the delegate if the specified item should be selected. `true` if the item should be selected or `false` if it should not. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. - returns: `true` if the item should be selected or `false` if it should not. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, shouldSelectItemAt: indexPath) } /** Tells the delegate that the specified item was selected. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, didSelectItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, didSelectItemAt: indexPath) } /** Asks the delegate if the specified item should be deselected. `true` if the item should be deselected or `false` if it should not. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. - returns: `true` if the item should be deselected or `false` if it should not. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, shouldDeselectItemAt: indexPath) } /** Tells the delegate that the specified item was deselected. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, didDeselectItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, didDeselectItemAt: indexPath) } // MARK: - Header/Footer /// Retrieves the supplementary view for the passed kind at the passed index path. /// /// - Parameters: /// - collectionView: The collectionView requesting the supplementary view. /// - kind: The kind of the supplementary view. /// - indexPath: The indexPath at which the supplementary view is requested. /// - Returns: The supplementary view for the passed index path. open override func ds_collectionView(_ collectionView: GeneralCollectionView, supplementaryViewOfKind kind: String, at indexPath: IndexPath) -> ReusableSupplementaryView? { // if, supplementaryViewCreator is not configured use it, otherwise delegate to one of the child data sources if supplementaryViewCreator != nil { return super.ds_collectionView(collectionView, supplementaryViewOfKind: kind, at: indexPath) } return unsafeSelectedDataSource.ds_collectionView(collectionView, supplementaryViewOfKind: kind, at: indexPath) } /// Gets the size of supplementary view for the passed kind at the passed index path. /// /// * For `UITableView` just supply the height width is don't care. /// * For `UICollectionViewFlowLayout` supply the height if it's vertical scrolling, or width if it's horizontal scrolling. /// * Specifying `CGSize.zero`, means don't display a supplementary view and `viewOfKind` will not be called. /// /// - Parameters: /// - collectionView: The collectionView requesting the supplementary view. /// - kind: The kind of the supplementary view. /// - indexPath: The indexPath at which the supplementary view is requested. /// - Returns: The size of the supplementary view. open override func ds_collectionView(_ collectionView: GeneralCollectionView, sizeForSupplementaryViewOfKind kind: String, at indexPath: IndexPath) -> CGSize { // if, it's configured use it, otherwise delegate to one of the child data sources if supplementaryViewCreator != nil { return super.ds_collectionView(collectionView, sizeForSupplementaryViewOfKind: kind, at: indexPath) } return unsafeSelectedDataSource.ds_collectionView(collectionView, sizeForSupplementaryViewOfKind: kind, at: indexPath) } /// Supplementary view is about to be displayed. Called exactly before the supplementary view is displayed. /// /// - parameter collectionView: The general collection view requesting the index path. /// - parameter view: The supplementary view that will be displayed. /// - parameter kind: The kind of the supplementary view. For `UITableView`, it can be either /// `UICollectionElementKindSectionHeader` or `UICollectionElementKindSectionFooter` for /// header and footer views respectively. /// - parameter indexPath: The index path at which the supplementary view is. open override func ds_collectionView(_ collectionView: GeneralCollectionView, willDisplaySupplementaryView view: ReusableSupplementaryView, ofKind kind: String, at indexPath: IndexPath) { // if, it's configured use it, otherwise delegate to one of the child data sources if supplementaryViewCreator != nil { return super.ds_collectionView(collectionView, willDisplaySupplementaryView: view, ofKind: kind, at: indexPath) } return unsafeSelectedDataSource.ds_collectionView(collectionView, willDisplaySupplementaryView: view, ofKind: kind, at: indexPath) } /// Supplementary view has been displayed and user scrolled it out of the screen. /// Called exactly after the supplementary view is scrolled out of the screen. /// /// - parameter collectionView: The general collection view requesting the index path. /// - parameter view: The supplementary view that will be displayed. /// - parameter kind: The kind of the supplementary view. For `UITableView`, it can be either /// `UICollectionElementKindSectionHeader` or `UICollectionElementKindSectionFooter` for /// header and footer views respectively. /// - parameter indexPath: The index path at which the supplementary view is. open override func ds_collectionView(_ collectionView: GeneralCollectionView, didEndDisplayingSupplementaryView view: ReusableSupplementaryView, ofKind kind: String, at indexPath: IndexPath) { // if, it's configured use it, otherwise delegate to one of the child data sources if supplementaryViewCreator != nil { return super.ds_collectionView(collectionView, didEndDisplayingSupplementaryView: view, ofKind: kind, at: indexPath) } return unsafeSelectedDataSource.ds_collectionView(collectionView, didEndDisplayingSupplementaryView: view, ofKind: kind, at: indexPath) } // MARK: - Reordering /// Asks the delegate if the item can be moved for a reoder operation. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. /// - Returns: `true` if the item can be moved, otherwise `false`. open override func ds_collectionView(_ collectionView: GeneralCollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, canMoveItemAt: indexPath) } /// Performs the move operation of an item from `sourceIndexPath` to `destinationIndexPath`. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - sourceIndexPath: An index path locating the start position of the item in the view. /// - destinationIndexPath: An index path locating the end position of the item in the view. open override func ds_collectionView(_ collectionView: GeneralCollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, moveItemAt: sourceIndexPath, to: destinationIndexPath) } // MARK: - Cell displaying /// The cell will is about to be displayed or moving into the visible area of the screen. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - cell: The cell that will be displayed /// - indexPath: An index path locating an item in the view. open override func ds_collectionView(_ collectionView: GeneralCollectionView, willDisplay cell: ReusableCell, forItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, willDisplay: cell, forItemAt: indexPath) } /// The cell will is already displayed and will be moving out of the screen. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - cell: The cell that will be displayed /// - indexPath: An index path locating an item in the view. open override func ds_collectionView(_ collectionView: GeneralCollectionView, didEndDisplaying cell: ReusableCell, forItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, didEndDisplaying: cell, forItemAt: indexPath) } // MARK: - Copy/Paste /// Whether the copy/paste/etc. menu should be shown for the item or not. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. /// - Returns: `true` if the item should show the copy/paste/etc. menu, otherwise `false`. open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, shouldShowMenuForItemAt: indexPath) } /// Check whether an action/selector can be performed for a specific item or not. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - action: The action that is requested to check if it can be performed or not. /// - indexPath: An index path locating an item in the view. /// - sender: The sender of the action. open override func ds_collectionView(_ collectionView: GeneralCollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender) } /// Executes an action for a specific item with the passed sender. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - action: The action that is requested to be executed. /// - indexPath: An index path locating an item in the view. /// - sender: The sender of the action. open override func ds_collectionView(_ collectionView: GeneralCollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { return unsafeSelectedDataSource.ds_collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender) } // MARK: - Focus /// Whether or not the item can have focus. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. /// - Returns: `true` if the item can have focus, otherwise `false`. @available(iOS 9.0, *) open override func ds_collectionView(_ collectionView: GeneralCollectionView, canFocusItemAt indexPath: IndexPath) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, canFocusItemAt: indexPath) } /// Whether or not should we update the focus. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - context: The focus context. /// - Returns: `true` if the item can be moved, otherwise `false`. @available(iOS 9.0, *) open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldUpdateFocusIn context: GeneralCollectionViewFocusUpdateContext) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, shouldUpdateFocusIn: context) } /// The focus is has been updated. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - context: The focus context. /// - coordinator: The focus animation coordinator. @available(iOS 9.0, *) open override func ds_collectionView(_ collectionView: GeneralCollectionView, didUpdateFocusIn context: GeneralCollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { return unsafeSelectedDataSource.ds_collectionView(collectionView, didUpdateFocusIn: context, with: coordinator) } /// Gets the index path of the preferred focused view. /// /// - Parameter collectionView: A general collection view object initiating the operation. @available(iOS 9.0, *) open override func ds_indexPathForPreferredFocusedView(in collectionView: GeneralCollectionView) -> IndexPath? { return unsafeSelectedDataSource.ds_indexPathForPreferredFocusedView(in: collectionView) } // MARK: - Editing /// Check whether the item can be edited or not. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. /// - Returns: `true` if the item can be moved, otherwise `false`. open override func ds_collectionView(_ collectionView: GeneralCollectionView, canEditItemAt indexPath: IndexPath) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, canEditItemAt: indexPath) } /// Executes the editing operation for the item at the specified index pass. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - editingStyle: The /// - indexPath: An index path locating an item in the view. open override func ds_collectionView(_ collectionView: GeneralCollectionView, commit editingStyle: UITableViewCellEditingStyle, forItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, commit: editingStyle, forItemAt: indexPath) } /// Gets the editing style for an item. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. /// - Returns: The editing style. open override func ds_collectionView(_ collectionView: GeneralCollectionView, editingStyleForItemAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return unsafeSelectedDataSource.ds_collectionView(collectionView, editingStyleForItemAt: indexPath) } /// Gets the localized title for the delete button to show for editing an item (e.g. swipe to delete). /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. /// - Returns: The localized title string. open override func ds_collectionView(_ collectionView: GeneralCollectionView, titleForDeleteConfirmationButtonForItemAt indexPath: IndexPath) -> String? { return unsafeSelectedDataSource.ds_collectionView(collectionView, titleForDeleteConfirmationButtonForItemAt: indexPath) } /// Gets the list of editing actions to use for editing an item. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. /// - Returns: The list of editing actions. open override func ds_collectionView(_ collectionView: GeneralCollectionView, editActionsForItemAt indexPath: IndexPath) -> [UITableViewRowAction]? { return unsafeSelectedDataSource.ds_collectionView(collectionView, editActionsForItemAt: indexPath) } /// Check whether to indent the item while editing or not. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. /// - Returns: `true` if the item can be indented while editing, otherwise `false`. open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldIndentWhileEditingItemAt indexPath: IndexPath) -> Bool { return unsafeSelectedDataSource.ds_collectionView(collectionView, shouldIndentWhileEditingItemAt: indexPath) } /// The item is about to enter into the editing mode. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. open override func ds_collectionView(_ collectionView: GeneralCollectionView, willBeginEditingItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, willBeginEditingItemAt: indexPath) } /// The item did leave the editing mode. /// /// - Parameters: /// - collectionView: A general collection view object initiating the operation. /// - indexPath: An index path locating an item in the view. open override func ds_collectionView(_ collectionView: GeneralCollectionView, didEndEditingItemAt indexPath: IndexPath) { return unsafeSelectedDataSource.ds_collectionView(collectionView, didEndEditingItemAt: indexPath) } }
mit
c68f6d21d5450caac6393c36a2eb7365
48.113636
197
0.707939
5.286388
false
false
false
false
imsz5460/DouYu
DYZB/DYZB/Classes/Main/Model/AnchorModel.swift
1
814
// // Anchor.swift // DYZB // // Created by shizhi on 17/2/28. // Copyright © 2017年 shizhi. All rights reserved. // import UIKit class AnchorModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间图片对应的URLString var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播 1 : 手机直播 var isVertical : Int = 0 /// 房间名称 var room_name : String = "" /// 主播昵称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" init(dict : [String : NSObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} }
mit
99e97e0ec49e9136b4b810b72a26c7b3
20.147059
77
0.566064
3.631313
false
false
false
false
emadhegab/GenericDataSource
GenericDataSourceTests/BasicDataSourceTests.swift
2
12833
// // BasicDataSourceTests.swift // GenericDataSource // // Created by Mohamed Afifi on 9/16/15. // Copyright © 2016 mohamede1945. All rights reserved. // import XCTest import GenericDataSource class BasicDataSourceTests: XCTestCase { func testDescription() { class __ScrollViewDelegate: NSObject, UIScrollViewDelegate {} let instance = ReportBasicDataSource<TextReportTableViewCell>() instance.scrollViewDelegate = __ScrollViewDelegate() XCTAssertTrue(instance.description.contains("ReportBasicDataSource<TextReportTableViewCell>")) XCTAssertTrue(instance.description.contains("__ScrollViewDelegate")) XCTAssertTrue(instance.description.contains("scrollViewDelegate")) XCTAssertTrue(!instance.description.contains("itemSize")) instance.itemSize = CGSize(width: 1, height: 1) XCTAssertTrue(instance.description.contains("itemSize")) XCTAssertTrue(instance.description.contains(CGSize(width: 1, height: 1).debugDescription)) XCTAssertTrue(instance.debugDescription.contains("ReportBasicDataSource<TextReportTableViewCell>")) XCTAssertTrue(instance.debugDescription.contains("__ScrollViewDelegate")) XCTAssertTrue(instance.debugDescription.contains("scrollViewDelegate")) XCTAssertTrue(instance.debugDescription.contains("itemSize")) XCTAssertTrue(instance.debugDescription.contains(CGSize(width: 1, height: 1).debugDescription)) } func testIndexPathForItem() { let dataSource = ReportBasicDataSource<TextReportTableViewCell>() dataSource.items = [Report(id: 1, name: "name1"), Report(id: 2, name: "name2"), Report(id: 3, name: "name3"), Report(id: 4, name: "name4")] XCTAssertEqual(IndexPath(item: 2, section: 0), dataSource.indexPath(for: Report(id: 3, name: "name3"))) XCTAssertNil(dataSource.indexPath(for: Report(id: 222, name: "name222"))) } func testCanEditOverriden() { class Test: ReportBasicDataSource<TextReportCollectionViewCell> { override func ds_collectionView(_ collectionView: GeneralCollectionView, canEditItemAt indexPath: IndexPath) -> Bool { return true } } let dataSource = Test() XCTAssertTrue(dataSource.responds(to: #selector(DataSource.ds_collectionView(_:canEditItemAt:)))) XCTAssertTrue(dataSource.ds_responds(to: .canEdit)) let tableView = MockTableView() let result = dataSource.tableView(tableView, canEditRowAt: IndexPath(item: 0, section: 0)) XCTAssertEqual(true, result) } func testCanEditNotOverriden() { class Test: ReportBasicDataSource<TextReportCollectionViewCell> { } let dataSource = Test() XCTAssertFalse(dataSource.responds(to: #selector(DataSource.ds_collectionView(_:canEditItemAt:)))) XCTAssertFalse(dataSource.ds_responds(to: .canEdit)) let tableView = MockTableView() let result = dataSource.tableView(tableView, canEditRowAt: IndexPath(item: 0, section: 0)) XCTAssertEqual(true, result) } func testItemSizeFunctionOverriden() { class Test: ReportBasicDataSource<TextReportCollectionViewCell> { fileprivate override func ds_collectionView(_ collectionView: GeneralCollectionView, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 100, height: 100) } } let dataSource = Test() XCTAssertTrue(dataSource.responds(to: #selector(DataSource.ds_collectionView(_:sizeForItemAt:)))) XCTAssertTrue(dataSource.ds_responds(to: .size)) let collectionView = MockCollectionView() let actualSize = dataSource.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: IndexPath(item: 0, section: 0)) XCTAssertEqual(CGSize(width: 100, height: 100), actualSize) } func testItemSize() { let dataSource = ReportBasicDataSource<TextReportCollectionViewCell>() XCTAssertFalse(dataSource.responds(to: #selector(DataSource.ds_collectionView(_:sizeForItemAt:)))) XCTAssertFalse(dataSource.ds_responds(to: .size)) let size = CGSize(width: 10, height: 20) dataSource.itemSize = size XCTAssertEqual(size, dataSource.itemSize) XCTAssertTrue(dataSource.responds(to: #selector(DataSource.ds_collectionView(_:sizeForItemAt:)))) XCTAssertTrue(dataSource.ds_responds(to: .size)) let collectionView = MockCollectionView() let actualSize = dataSource.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: IndexPath(item: 0, section: 0)) XCTAssertEqual(size, actualSize) } func testCellHeight() { let dataSource = ReportBasicDataSource<TextReportTableViewCell>() XCTAssertFalse(dataSource.responds(to: #selector(DataSource.ds_collectionView(_:sizeForItemAt:)))) XCTAssertFalse(dataSource.ds_responds(to: .size)) let height: CGFloat = 150 dataSource.itemHeight = height XCTAssertEqual(height, dataSource.itemHeight) XCTAssertTrue(dataSource.responds(to: #selector(DataSource.ds_collectionView(_:sizeForItemAt:)))) XCTAssertTrue(dataSource.ds_responds(to: .size)) let tableView = MockTableView() let actualHeight = dataSource.tableView(tableView, heightForRowAt: IndexPath(item: 0, section: 0)) XCTAssertEqual(height, actualHeight) } func testItems() { // test items let reports = Report.generate(numberOfReports: 20) let dataSource = ReportBasicDataSource<TextReportTableViewCell>() dataSource.items = reports XCTAssertEqual(dataSource.items, reports) } func testItemAtIndexPath() { let reports = Report.generate(numberOfReports: 20) let dataSource = ReportBasicDataSource<TextReportTableViewCell>() dataSource.items = reports let fifth = dataSource.item(at: IndexPath(item: 4, section: 0)) XCTAssertEqual(reports[4], fifth) } func testReplaceItemAtIndexPath() { let reports = Report.generate(numberOfReports: 20) let dataSource = ReportBasicDataSource<TextReportTableViewCell>() dataSource.items = reports let test = Report(id: 1945, name: "mohamed") dataSource.replaceItem(at: IndexPath(item: 15, section: 0), with: test) var mutableReports = reports mutableReports[15] = test XCTAssertEqual(dataSource.items, mutableReports) } func testQueryForCellsWithTableView() { let tableView = MockTableView() tableView.numberOfReuseCells = 10 let dataSource = ReportBasicDataSource<TextReportTableViewCell>() let reports = Report.generate(numberOfReports: 200) dataSource.items = reports // assign as data source tableView.dataSource = dataSource // register the cell dataSource.registerReusableViewsInCollectionView(tableView) // execute the test tableView.queryDataSource() // assert XCTAssertEqual(1, tableView.numberOfSections) XCTAssertEqual(reports.count, tableView.ds_numberOfItems(inSection: 0)) let cells = tableView.cells[0] as! [TextReportTableViewCell] for (index, cell) in cells.enumerated() { XCTAssertTrue(cell.reports.contains(Report(id: index + 1, name: "report-\(index + 1)")), "Invalid report at index: \(index)") XCTAssertTrue(cell.indexPaths.contains(IndexPath(item: index, section: 0)), "Invalid index path at index: \(index)") } } func testQueryForCellsWithCollectionView() { let collectionView = MockCollectionView() collectionView.numberOfReuseCells = 10 let dataSource = ReportBasicDataSource<TextReportCollectionViewCell>() let reports = Report.generate(numberOfReports: 200) dataSource.items = reports // assign as data source collectionView.dataSource = dataSource // register the cell dataSource.registerReusableViewsInCollectionView(collectionView) // execute the test collectionView.queryDataSource() // assert XCTAssertEqual(1, collectionView.numberOfSections) XCTAssertEqual(reports.count, collectionView.ds_numberOfItems(inSection: 0)) let cells = collectionView.cells[0] as! [TextReportCollectionViewCell] for (index, cell) in cells.enumerated() { XCTAssertTrue(cell.reports.contains(Report(id: index + 1, name: "report-\(index + 1)")), "Invalid report at index: \(index)") XCTAssertTrue(cell.indexPaths.contains(IndexPath(item: index, section: 0)), "Invalid index path at index: \(index)") } } func testSelectionShouldHighlightNoSelector() { let tableView = MockTableView() let collectionView = MockCollectionView() let tableDataSource = ReportBasicDataSource<TextReportTableViewCell>() let collectionDataSource = ReportBasicDataSource<TextReportCollectionViewCell>() let indexPath = IndexPath(item: 20, section: 10) XCTAssertTrue(tableDataSource.tableView(tableView, shouldHighlightRowAt: indexPath)) XCTAssertTrue(collectionDataSource.collectionView(collectionView, shouldHighlightItemAt: indexPath)) } func testSelectionDidHighlightNoSelector() { let tableView = MockTableView() let collectionView = MockCollectionView() let tableDataSource = ReportBasicDataSource<TextReportTableViewCell>() let collectionDataSource = ReportBasicDataSource<TextReportCollectionViewCell>() let indexPath = IndexPath(item: 20, section: 10) tableDataSource.tableView(tableView, didHighlightRowAt: indexPath) collectionDataSource.collectionView(collectionView, didHighlightItemAt: indexPath) } func testSelectionDidUnhighlightNoSelector() { let tableView = MockTableView() let collectionView = MockCollectionView() let tableDataSource = ReportBasicDataSource<TextReportTableViewCell>() let collectionDataSource = ReportBasicDataSource<TextReportCollectionViewCell>() let indexPath = IndexPath(item: 20, section: 10) tableDataSource.tableView(tableView, didUnhighlightRowAt: indexPath) collectionDataSource.collectionView(collectionView, didUnhighlightItemAt: indexPath) } func testSelectionShouldSelectNoSelector() { let tableView = MockTableView() let collectionView = MockCollectionView() let tableDataSource = ReportBasicDataSource<TextReportTableViewCell>() let collectionDataSource = ReportBasicDataSource<TextReportCollectionViewCell>() let indexPath = IndexPath(item: 20, section: 10) XCTAssertEqual(indexPath, tableDataSource.tableView(tableView, willSelectRowAt: indexPath)) XCTAssertTrue(collectionDataSource.collectionView(collectionView, shouldSelectItemAt: indexPath)) } func testSelectionDidSelectNoSelector() { let tableView = MockTableView() let collectionView = MockCollectionView() let tableDataSource = ReportBasicDataSource<TextReportTableViewCell>() let collectionDataSource = ReportBasicDataSource<TextReportCollectionViewCell>() let indexPath = IndexPath(item: 20, section: 10) tableDataSource.tableView(tableView, didSelectRowAt: indexPath) collectionDataSource.collectionView(collectionView, didSelectItemAt: indexPath) } func testSelectionWillDeselectNoSelector() { let tableView = MockTableView() let collectionView = MockCollectionView() let tableDataSource = ReportBasicDataSource<TextReportTableViewCell>() let collectionDataSource = ReportBasicDataSource<TextReportCollectionViewCell>() let indexPath = IndexPath(item: 20, section: 10) XCTAssertEqual(indexPath, tableDataSource.tableView(tableView, willDeselectRowAt: indexPath)) XCTAssertTrue(collectionDataSource.collectionView(collectionView, shouldDeselectItemAt: indexPath)) } func testSelectionDidDeselectNoSelector() { let tableView = MockTableView() let collectionView = MockCollectionView() let tableDataSource = ReportBasicDataSource<TextReportTableViewCell>() let collectionDataSource = ReportBasicDataSource<TextReportCollectionViewCell>() let indexPath = IndexPath(item: 20, section: 10) tableDataSource.tableView(tableView, didDeselectRowAt: indexPath) collectionDataSource.collectionView(collectionView, didDeselectItemAt: indexPath) } }
mit
307877f5c7b581f9712296511c2b9872
38.975078
158
0.70519
5.581557
false
true
false
false
wanghdnku/Whisper
Whisper/PopTransitionAnimator.swift
1
2688
// // PopTransitionAnimator.swift // NavTransition // // Created by Hayden on 2016/10/19. // Copyright © 2016年 AppCoda. All rights reserved. // import UIKit class PopTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { let duration = 0.7 var isPresenting = false func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)! let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let container = transitionContext.containerView // guard let container = transitionContext.containerView else { // return // } let minimise = CGAffineTransform(scaleX: 0, y: 0) let offScreenDown = CGAffineTransform(translationX: 0, y: container.frame.height) let shiftDown = CGAffineTransform(translationX: 0, y: 15) let scaleDown = shiftDown.scaledBy(x: 0.95, y: 0.95) toView.transform = minimise if isPresenting { container.addSubview(fromView) container.addSubview(toView) } else { container.addSubview(toView) container.addSubview(fromView) } // Perform the animation UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: [], animations: { if self.isPresenting { fromView.transform = scaleDown fromView.alpha = 1.0 toView.transform = CGAffineTransform.identity } else { fromView.transform = offScreenDown fromView.alpha = 1.0 toView.transform = CGAffineTransform.identity } }, completion: { finished in transitionContext.completeTransition(true) }) } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } }
mit
c5ff0614d642115e571ea7f7b285c752
31.349398
170
0.620484
6.102273
false
false
false
false
phatblat/dotfiles
.liftoff/templates/AppDelegate.swift
1
485
// // AppDelegate.swift // <%= project_name %> // // Created by <%= author %> on <%= Time.now.strftime("%-m/%-d/%y") %> // Copyright (c) <%= Time.now.strftime('%Y') %> <%= company %>. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } }
mit
d6571ec95784c8c164bbfd37c4ffc57d
25.944444
127
0.653608
4.041667
false
false
false
false
TerryCK/GogoroBatteryMap
GogoroMap/LocationManageable.swift
1
3875
// // LocationManager.swift // GogoroMap // // Created by 陳 冠禎 on 2017/8/9. // Copyright © 2017年 陳 冠禎. All rights reserved. // import MapKit import CoreLocation import Crashlytics protocol LocationManageable: MKMapViewDelegate { func authrizationStatus() func setCurrentLocation(latDelta: Double, longDelta: Double) func setTracking(mode: MKUserTrackingMode) } extension MapViewController: LocationManageable { func authrizationStatus() { switch CLLocationManager.authorizationStatus() { case .notDetermined: locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() case .denied: let alertController = UIAlertController(title: "定位權限已關閉", message: "如要變更權限,請至 設定 > 隱私權 > 定位服務 開啟", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "確認", style: .default)) present(alertController, animated: true, completion: nil) case .authorizedWhenInUse: locationManager.startUpdatingLocation() default: break } setCurrentLocation(latDelta: 0.05, longDelta: 0.05) mapView.userLocation.title = "😏 \("here".localize())" } func setCurrentLocation(latDelta: Double, longDelta: Double) { currentUserLocation = locationManager.location ?? CLLocation(latitude: 25.047908, longitude: 121.517315) mapView.setRegion(MKCoordinateRegion(center: currentUserLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta)), animated: false) } func setTracking(mode: MKUserTrackingMode) { if case .followWithHeading = mode { setCurrentLocation(latDelta: 0.01, longDelta: 0.01) } Answers.logCustomEvent(withName: "TrackingMode", customAttributes: ["TrackingMode" : "\(mode)"]) mapView.setUserTrackingMode(mode, animated: mode == .followWithHeading) locationArrowView.setImage(mapView.userTrackingMode.arrowImage, for: .normal) } } extension MapViewController { @objc(mapView:didChangeUserTrackingMode:animated:) func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) { locationArrowView.setImage(mapView.userTrackingMode.arrowImage, for: .normal) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let current = locations.last else { return } currentUserLocation = current } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { locationManager.requestLocation() } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error) } } extension MKUserTrackingMode: CustomStringConvertible { var arrowImage: UIImage { switch self { case .none: return #imageLiteral(resourceName: "locationArrowNone") case .follow: return #imageLiteral(resourceName: "locationArrow") case .followWithHeading: return #imageLiteral(resourceName: "locationArrowFollewWithHeading") } } public var description: String { switch self { case .none: return "None" case .follow: return "Follow" case .followWithHeading: return "Heading" } } public var nextMode: MKUserTrackingMode { return MKUserTrackingMode(rawValue: (rawValue + 1) % 3)! } }
mit
af51d1e853a689124c7e6a1534ecc074
36.613861
143
0.648329
5.031788
false
false
false
false
brentdax/SQLKit
Sources/CorePostgreSQL/PGValue.swift
1
8680
// // PGValue.swift // LittlinkRouterPerfect // // Created by Brent Royal-Gordon on 11/30/16. // // import Foundation import libpq /// Conforming types can be converted to and from a `PGRawValue`. /// /// `PGValue` is the primary way you should get data in and out of PostgreSQL. /// It leverages `CorePostgreSQL`'s detailed knowledge of how PostgreSQL formats /// values to ensure that all data sent to PostgreSQL is in a format it will /// understand and all data received from PostgreSQL will be parsed with knowledge /// of any edge cases or obscure syntax. /// /// Conforming to `PGValue` alone only guarantees that the value can understand /// raw values received in `textual` format. Types which know how to parse `binary` /// format should conform to `PGBinaryValue`. /// /// Conforming types must be able to convert all values of `Self` into a /// `PGRawValue`. Conversion back may in some circumstances cause an error. public protocol PGValue { /// The PostgreSQL type which most closely corresponds to this type. /// /// The `preferredPGType` should be able to express all values of `Self` as /// accurately as possible. For instance, you would not give `Double` a /// `preferredPGType` of `numeric`, because `numeric` is an exact decimal /// number whereas `Double` is an approximate binary number. static var preferredPGType: PGType { get } /// Creates an instance of `Self` from the contents of a textual raw value. /// /// - Throws: If `text` is ill-formed or conversion otherwise fails. /// - Note: Conforming type should implement this initializer, but you will /// usually want to call the `init(rawPGValue:)` initializer instead of /// this one. init(textualRawPGValue text: String) throws /// Creates a `PGRawValue` from `Self`. /// /// - Note: Conforming types may return a `binary` raw value from this /// property even if they don't conform to `PGBinaryValue`. var rawPGValue: PGRawValue { get } // Implemented by extension; do not override. /// Creates an instance of `Self` from the `rawValue`. /// /// - Precondition: `rawValue` is not in binary format unless `Self` also /// conforms to `PGBinaryValue`. /// /// - Note: Conforming types should implement `init(textualRawPGValue:)` /// instead of this initializer, but you should usually call this one. init(rawPGValue: PGRawValue) throws } extension PGValue { /// Creates an instance of `Self` from the `rawValue`. /// /// - Precondition: `rawValue` is not in binary format unless `Self` also /// conforms to `PGBinaryValue`. /// /// - Note: Conforming types should implement `init(textualRawPGValue:)` /// instead of this initializer, but you should usually call this one. public init(rawPGValue: PGRawValue) throws { switch rawPGValue { case .textual(let text): try self.init(textualRawPGValue: text) case .binary(_): fatalError("Type does not support binary values.") } } } /// Conforming types can be converted to and from a `PGRawValue`, and support /// `PGRawValue`s in both textual and binary formats. /// /// Conforming types must be able to convert all values of `Self` into a /// `PGRawValue`. Conversion back may in some circumstances cause an error. public protocol PGBinaryValue: PGValue { /// Creates an instance of `Self` from the contents of a binary raw value. /// /// - Throws: If `bytes` are ill-formed or conversion otherwise fails. /// - Note: Conforming type should implement this initializer, but you will /// usually want to call the `init(rawPGValue:)` initializer instead of /// this one. init(binaryRawPGValue bytes: Data) throws } extension PGBinaryValue { /// Creates an instance of `Self` from the `rawValue`. /// /// - Note: Conforming types should implement `init(textualRawPGValue:)` and /// init(binaryRawPGValue:)` instead of this initializer, but you should /// usually call this one. public init(rawPGValue: PGRawValue) throws { switch rawPGValue { case .textual(let text): try self.init(textualRawPGValue: text) case .binary(let bytes): try self.init(binaryRawPGValue: bytes) } } } extension String: PGValue { public static let preferredPGType = PGType.text public init(textualRawPGValue text: String) { self = text } public var rawPGValue: PGRawValue { return .textual(self) } } extension Data: PGBinaryValue { public static let preferredPGType = PGType.byteA public init(textualRawPGValue text: String) { var count: Int = 0 let bytes = PQunescapeBytea(text, &count)! self.init(bytes: bytes, count: count) } public init(binaryRawPGValue bytes: Data) { self = bytes } public var rawPGValue: PGRawValue { return .binary(self) } } extension Bool: PGValue { public static let preferredPGType = PGType.boolean public init(textualRawPGValue text: String) throws { switch text { case "t", "true", "y", "yes", "on", "1": self = true case "f", "false", "n", "no", "off", "0": self = false default: throw PGError.invalidBoolean(text) } } public var rawPGValue: PGRawValue { return .textual(self ? "t" : "f") } } extension Int: PGValue { public static let preferredPGType = PGType.int8 public init(textualRawPGValue text: String) throws { guard let value = Int(text) else { throw PGError.invalidNumber(text) } self = value } public var rawPGValue: PGRawValue { return .textual(String(self)) } } extension Double: PGValue { public static let preferredPGType = PGType.float8 public init(textualRawPGValue text: String) throws { guard let value = Double(text) else { throw PGError.invalidNumber(text) } self = value } public var rawPGValue: PGRawValue { return .textual(String(self)) } } extension Decimal: PGValue { public static let preferredPGType = PGType.numeric public init(textualRawPGValue text: String) throws { guard let value = Decimal(string: text, locale: .posix) else { throw PGError.invalidNumber(text) } self = value } public var rawPGValue: PGRawValue { return .textual(String(describing: self)) } } extension PGTimestamp: PGValue { public static let preferredPGType = PGType.timestampTZ private static let formatter = PGTimestampFormatter(style: .timestamp) public init(textualRawPGValue text: String) throws { self = try PGTimestamp.formatter.timestamp(from: text) } public var rawPGValue: PGRawValue { return .textual(PGTimestamp.formatter.string(from: self)!) } } extension PGDate: PGValue { public static let preferredPGType = PGType.timestampTZ private static let formatter = PGTimestampFormatter(style: .date) public init(textualRawPGValue text: String) throws { let timestamp = try PGDate.formatter.timestamp(from: text) self = timestamp.date } public var rawPGValue: PGRawValue { let timestamp = PGTimestamp(date: self) return .textual(PGDate.formatter.string(from: timestamp)!) } } extension PGTime: PGValue { public static let preferredPGType = PGType.timestampTZ private static let formatter = PGTimestampFormatter(style: .time) public init(textualRawPGValue text: String) throws { let timestamp = try PGTime.formatter.timestamp(from: text) self = timestamp.time } public var rawPGValue: PGRawValue { let timestamp = PGTimestamp(time: self) return .textual(PGTime.formatter.string(from: timestamp)!) } } extension PGInterval: PGValue { public static let preferredPGType = PGType.interval private static let formatter = PGIntervalFormatter() public init(textualRawPGValue text: String) throws { self.init() // XXX compiler crash self = try PGInterval.formatter.interval(from: text) } public var rawPGValue: PGRawValue { return .textual(PGInterval.formatter.string(from: self)) } }
mit
59e66700fccbfa25866673b6491a99b6
31.878788
86
0.642166
4.179104
false
false
false
false
Longhanks/qlift
Sources/Qlift/QAction.swift
1
1406
import CQlift open class QAction: QObject { var triggeredCallback: ((Bool) -> Void)? public var text: String = "" { didSet { QAction_setText(self.ptr, text) } } // Icon not supported at the moment public init(text: String = "", parent: QObject? = nil) { self.text = text super.init(ptr: QAction_new(nil, text, parent?.ptr), parent: parent) } override init(ptr: UnsafeMutableRawPointer, parent: QObject? = nil) { super.init(ptr: ptr, parent: parent) } deinit { if self.ptr != nil { if QObject_parent(self.ptr) == nil { QAction_delete(self.ptr) } self.ptr = nil } } open func connectTriggered(receiver: QObject? = nil, to slot: @escaping ((Bool) -> Void)) { var object: QObject = self if receiver != nil { object = receiver! } self.triggeredCallback = slot let functor: @convention(c) (UnsafeMutableRawPointer?, Bool) -> Void = { raw, checked in if raw != nil { let _self = Unmanaged<QAction>.fromOpaque(raw!).takeUnretainedValue() _self.triggeredCallback!(checked) } } let rawSelf = Unmanaged.passUnretained(self).toOpaque() QAction_triggered_connect(self.ptr, object.ptr, rawSelf, functor) } }
mit
2c7053b398e931218529681279c0acd6
26.038462
96
0.555477
4.147493
false
false
false
false
spritekitbook/flappybird-swift
Chapter 6 /Start/FloppyBird/FloppyBird/GameScene.swift
2
3091
// // GameScene.swift // FloppyBird // // Created by Jeremy Novak on 9/24/16. // Copyright © 2016 SpriteKit Book. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { // MARK: - Private class constants private let cloudController = CloudController() private let hills = Hills() private let ground = Ground() private let tutorial = Tutorial() private let floppy = Floppy() private let logController = LogController() // MARK: - Private class variables private var lastUpdateTime:TimeInterval = 0.0 // MARK: - Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(size: CGSize) { super.init(size: size) } override func didMove(to view: SKView) { setup() } // MARK: - Setup private func setup() { self.backgroundColor = Colors.colorFrom(rgb: Colors.sky) self.addChild(cloudController) self.addChild(hills) self.addChild(ground) self.addChild(tutorial) self.addChild(floppy) self.addChild(logController) self.physicsWorld.contactDelegate = self self.physicsWorld.gravity = CGVector(dx: 0, dy: -10) self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame) self.physicsBody?.affectedByGravity = false self.physicsBody?.categoryBitMask = Contact.scene self.physicsBody?.collisionBitMask = 0x0 self.physicsBody?.contactTestBitMask = 0x0 } // MARK: - Update override func update(_ currentTime: TimeInterval) { let delta = currentTime - lastUpdateTime lastUpdateTime = currentTime cloudController.update(delta: delta) floppy.update() logController.update(delta: delta) } // MARK: - Touch Events override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch:UITouch = touches.first! as UITouch let touchLocation = touch.location(in: self) // if tutorial.contains(touchLocation) { // loadScene() // } floppy.fly() } // MARK: - Contact func didBegin(_ contact: SKPhysicsContact) { // Which body is not Floppy? let other = contact.bodyA.categoryBitMask == Contact.floppy ? contact.bodyB : contact.bodyA if other.categoryBitMask == Contact.scene { print("Game Over: Player Crashed!") } if other.categoryBitMask == Contact.log { print("Game Over: Player hit a log!") } if other.categoryBitMask == Contact.score { print("Score: Player passed through logs!") } } // MARK: - Load Scene private func loadScene() { let scene = GameOverScene(size: kViewSize) let transition = SKTransition.fade(with: SKColor.black, duration: 0.5) self.view?.presentScene(scene, transition: transition) } }
apache-2.0
28b4c724a33f431a182cc89492506ecf
28.428571
99
0.606796
4.775889
false
false
false
false
mxclove/compass
毕业设计_指南针最新3.1/毕业设计_指南针/DrawerViewController.swift
1
8681
// // DrawerViewController.swift // 毕业设计_指南针 // // Created by 马超 on 15/10/18. // Copyright © 2015年 马超. All rights reserved. // import UIKit let leftViewWidth: CGFloat = deviceWidth let leftViewController = CompassViewController() let mainViewController = MapViewController() class DrawerViewController: UIViewController , UIGestureRecognizerDelegate{ var leftView = UIView() var mainView = UIView() var isOpen = true var startX: CGFloat = 0.0 let panGesture = UIPanGestureRecognizer() let pageControl = UIPageControl () override func viewDidLoad() { super.viewDidLoad() // UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Fade) pageControl.frame = CGRect(x: deviceWidth * 0.5 - 20, y: deviceHeight * 0.92, width: 40, height: 37) pageControl.numberOfPages = 2 pageControl.currentPage = 0 self.view.addSubview(pageControl) leftView.frame = self.view.frame leftView.backgroundColor = UIColor.redColor() leftViewController.view.frame = leftView.frame leftView = leftViewController.view self.view.addSubview(leftView) mainView.frame = self.view.frame mainView.backgroundColor = UIColor.greenColor() mainViewController.view.frame = CGRect(x: leftViewWidth, y: 0, width: deviceWidth, height: deviceHeight) mainView = mainViewController.view self.view.addSubview(mainView) mainViewController.delegate = leftViewController panGesture.addTarget(self, action: "panBegan:") panGesture.delegate = self self.view.addGestureRecognizer(panGesture) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func figerOutNetworkOfType() { let statusType = IJReachability.isConnectedToNetworkOfType() switch statusType { case .WWAN: // print("Connection Type: Mobile") let alert = UIAlertController(title: "您正在使用流量上网,注意", message: "您可以进入设置,开启流量保护", preferredStyle: UIAlertControllerStyle.Alert) let Action = UIAlertAction(title: "好", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(Action) presentViewController(alert, animated: true, completion: nil) case .WiFi: // print("Connection Type: WiFi") break case .NotConnected: let alert = UIAlertController(title: "无法连接到网络,请检查您的网络", message: nil, preferredStyle: UIAlertControllerStyle.Alert) let Action = UIAlertAction(title: "好", style: UIAlertActionStyle.Default, handler: { (_) -> Void in }) alert.addAction(Action) presentViewController(alert, animated: true, completion: nil) } } func panBegan(recongnizer: UIPanGestureRecognizer) { // let location = recongnizer.translationInView(self.view) let location = recongnizer.locationInView(self.view) // print(location.x) if recongnizer.state == UIGestureRecognizerState.Began { startX = location.x } var differX = location.x - startX // print("differX = \(differX)") if differX > leftViewWidth { differX = leftViewWidth } if differX < -leftViewWidth { differX = -leftViewWidth } // if !isOpen { if borderAnimationEnable { if differX > 0 { self.leftView.x(differX - leftViewWidth) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } else { self.leftView.x(differX * 0.3 - leftViewWidth) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } } else { if differX > 0 { self.leftView.x(differX - leftViewWidth) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } } } else { if borderAnimationEnable { if differX < 0 { self.leftView.x(differX) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } else { self.leftView.x(differX * 0.3) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } } else { if differX < 0 { self.leftView.x(differX) self.mainView.x(leftView.frame.origin.x + leftView.frame.width) } } } if mainView.frame.origin.x < leftViewWidth * 0.5 { self.pageControl.currentPage = 1 } else { self.pageControl.currentPage = 0 } // if (differX + leftView.frame.origin.x) <= 0 && (differX + leftView.frame.origin.x) >= -leftView.frame.width { // self.leftView.x(differX - leftViewWidth) // self.mainView.x(leftView.frame.origin.x + leftView.frame.width) // } if recongnizer.state == UIGestureRecognizerState.Ended { if isOpen { if mainView.frame.origin.x < leftViewWidth * 0.8 { UIView.animateWithDuration(0.5, delay: 0.01, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in self.leftView.x(-leftViewWidth) self.mainView.x(0) self.pageControl.currentPage = 1 self.mainView.userInteractionEnabled = true self.isOpen = false }, completion: nil) } else { UIView.animateWithDuration(0.5, delay: 0.01, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.leftView.x(0) self.mainView.x(leftViewWidth) self.pageControl.currentPage = 0 self.mainView.userInteractionEnabled = false self.isOpen = true }, completion: nil) } } else { if mainView.frame.origin.x > leftViewWidth * 0.2 { UIView.animateWithDuration(0.5, delay: 0.01, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in self.leftView.x(0) self.mainView.x(leftViewWidth) self.pageControl.currentPage = 0 self.mainView.userInteractionEnabled = false self.isOpen = true }, completion: nil) } else { UIView.animateWithDuration(0.5, delay: 0.01, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.leftView.x(-leftViewWidth) self.mainView.x(0) self.pageControl.currentPage = 1 self.mainView.userInteractionEnabled = true self.isOpen = false }, completion: nil) } } } } } //extension DrawerViewController: MenuViewControllerDelegate { // func MenuSelectedControllerChanged(selectedNum: Int) { // mainViewController.view.frame = mainView.frame // mainView = mainViewController.view // mainView.userInteractionEnabled = false // self.view.addSubview(mainView) // // UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in // self.leftView.x(-leftViewWidth) // self.mainView.x(0) // }) { (finish) -> Void in // self.isOpen = false // self.mainView.userInteractionEnabled = true // } // //// self.leftView.x(-leftViewWidth) //// self.mainView.x(0) //// self.isOpen = false //// self.mainView.userInteractionEnabled = true // // print("self.view.subviews.count = === \(self.view.subviews.count)") // } //}
apache-2.0
8b73b0e7829d12fb7313a9084ea8bfe3
37.097778
147
0.55098
4.98662
false
false
false
false
liuchuo/Swift-practice
20150608-6.playground/Contents.swift
1
468
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let a: UInt8 = 0b10110010 let b: UInt8 = 0b01011110 println("a | b = \(a | b)") println("a & b = \(a & b)") println("a ^ b = \(a ^ b)") println("~a = \(~a)") println("a >> 2 = \(a >> 2)") println("a << 2 = \(a << 2)") let c: Int8 = -0b1100 println("c >> 2 = \(c >> 2)") println("c << 2 = \(c << 2)") var airports = ["TYO":"Tokyo","DUB":"Dublin"] println(airports)
gpl-2.0
66339ca40dee2356bcbe65ab8d2e3af8
18.5
52
0.536325
2.644068
false
false
false
false
davidhariri/done
DoneTests/DoneBaseMethodsTests.swift
1
798
// // DoneBaseMethodsTests.swift // Done // // Created by David Hariri on 2017-03-14. // Copyright © 2017 David Hariri. All rights reserved. // import XCTest @testable import Done class DoneBaseMethodsTests: XCTestCase { var doneBase: DoneBase! override func setUp() { super.setUp() doneBase = DoneBase() } override func tearDown() { super.tearDown() doneBase = nil } func testThatMarkUpdatedChangesUpdatedDate() { doneBase.markUpdated() let currentDate = Date() XCTAssert(doneBase.updated != nil, ".updated was nil") XCTAssert(round((doneBase.updated?.timeIntervalSince1970)!) == round(currentDate.timeIntervalSince1970), ".updated was not the same as now") } }
apache-2.0
c263809c9e373d6ce6ff5ed17b05e023
23.151515
89
0.628607
4.284946
false
true
false
false
vlas-voloshin/SubviewAttachingTextView
Example.playground/Sources/AttributedStringExtensions.swift
1
2231
/** Available under the MIT License Copyright (c) 2017 Vlas Voloshin */ import UIKit public extension NSTextAttachment { convenience init(image: UIImage, size: CGSize? = nil) { self.init(data: nil, ofType: nil) self.image = image if let size = size { self.bounds = CGRect(origin: .zero, size: size) } } } public extension NSAttributedString { func insertingAttachment(_ attachment: NSTextAttachment, at index: Int, with paragraphStyle: NSParagraphStyle? = nil) -> NSAttributedString { let copy = self.mutableCopy() as! NSMutableAttributedString copy.insertAttachment(attachment, at: index, with: paragraphStyle) return copy.copy() as! NSAttributedString } func addingAttributes(_ attributes: [NSAttributedString.Key : Any]) -> NSAttributedString { let copy = self.mutableCopy() as! NSMutableAttributedString copy.addAttributes(attributes) return copy.copy() as! NSAttributedString } } public extension NSMutableAttributedString { func insertAttachment(_ attachment: NSTextAttachment, at index: Int, with paragraphStyle: NSParagraphStyle? = nil) { let plainAttachmentString = NSAttributedString(attachment: attachment) if let paragraphStyle = paragraphStyle { let attachmentString = plainAttachmentString .addingAttributes([ .paragraphStyle : paragraphStyle ]) let separatorString = NSAttributedString(string: .paragraphSeparator) // Surround the attachment string with paragraph separators, so that the paragraph style is only applied to it let insertion = NSMutableAttributedString() insertion.append(separatorString) insertion.append(attachmentString) insertion.append(separatorString) self.insert(insertion, at: index) } else { self.insert(plainAttachmentString, at: index) } } func addAttributes(_ attributes: [NSAttributedString.Key : Any]) { self.addAttributes(attributes, range: NSRange(location: 0, length: self.length)) } } public extension String { static let paragraphSeparator = "\u{2029}" }
mit
18779afa6ff14d7e053b004a8b84b463
30.422535
145
0.678171
5.140553
false
false
false
false
remobjects/ElementsSamples
Silver/Delphi Compatibility/Basic WebAssembly GUI App/Program.swift
1
2176
import RemObjects.Elements.RTL.Delphi import RemObjects.Elements.RTL.Delphi.VCL @Export public class Program { public func HelloWorld() { // Create form var lForm = TForm(nil) lForm.Width = 800 // we can display the form in an existing div element. If Show parameter is nil, a new div is created lForm.Show(nil) var lTopLabel = TLabel(lForm) lTopLabel.Left = 1 lTopLabel.Parent = lForm lTopLabel.Caption = "Write the item caption on the edit and press Add New button to add to ListBox:" var lButton = TButton(lForm) lButton.Left = 50 lButton.Top = 50 lButton.Caption = "Add New" lButton.Parent = lForm var lEdit = TEdit(lForm) lEdit.Left = 150 lEdit.Top = 50 lEdit.Parent = lForm var lListBox = TListBox(lForm) lListBox.Left = 350 lListBox.Top = 50 lListBox.Parent = lForm lListBox.Width = 250 lListBox.MultiSelect = true lButton.OnClick = { (sender) in lListBox.Items.Add(lEdit.Text) } var lChangeLabel = TLabel(lForm) lChangeLabel.Top = 165 lChangeLabel.Parent = lForm lChangeLabel.Caption = "Press button to change label font:" var lChangeButton = TButton(lForm) lChangeButton.Left = 50 lChangeButton.Top = 200 lChangeButton.Caption = "Change font" lChangeButton.Parent = lForm var lLabel = TLabel(lForm) lLabel.Left = 150 lLabel.Top = 200 lLabel.Caption = "Sample text!" lLabel.Parent = lForm lChangeButton.OnClick = { (sender) in lLabel.Font.Name = "Verdana"; lLabel.Font.Size = 24 } var lMemo = TMemo(lForm) lMemo.Left = 50 lMemo.Top = 300 lMemo.Width = 250 lMemo.Height = 150 lMemo.Parent = lForm var lMemoButton = TButton(lForm) lMemoButton.Left = 350 lMemoButton.Top = 325 lMemoButton.Caption = "Add text" lMemoButton.Parent = lForm var lList = TStringList.Create() lList.Add("one line") lList.Add("another one") lMemoButton.OnClick = { (sender) in lMemo.Lines.AddStrings(lList) } var lDisplayButton = TButton(lForm) lDisplayButton.Top = lMemoButton.Top lDisplayButton.Left = 450 lDisplayButton.Caption = "Show memo text" lDisplayButton.Parent = lForm lDisplayButton.OnClick = { (sender) in ShowMessage(lMemo.Lines.Text) } } }
mit
859c99cba8e2018e9bca989e59579765
25.52439
103
0.713431
2.87947
false
false
false
false
practicalswift/swift
test/refactoring/LongNumber/basic.swift
40
811
func foo() { _ = 1234567 _ = 1234567.12345 _ = +1234567 _ = -1234567 } // RUN: %empty-directory(%t.result) // RUN: %refactor -simplify-long-number -source-filename %s -pos=2:9 > %t.result/Integer.swift // RUN: diff -u %S/Outputs/Integer.expected %t.result/Integer.swift // RUN: %refactor -simplify-long-number -source-filename %s -pos=3:9 > %t.result/Float.swift // RUN: diff -u %S/Outputs/Float.expected %t.result/Float.swift // RUN: %refactor -simplify-long-number -source-filename %s -pos=4:11 > %t.result/PositiveInteger.swift // RUN: diff -u %S/Outputs/PositiveInteger.expected %t.result/PositiveInteger.swift // RUN: %refactor -simplify-long-number -source-filename %s -pos=5:7 > %t.result/NegativeInteger.swift // RUN: diff -u %S/Outputs/NegativeInteger.expected %t.result/NegativeInteger.swift
apache-2.0
62c95e9dfcceaa23dc36183dca983155
49.6875
103
0.713933
2.970696
false
false
false
false
NSDengChen/Uber
Uber/Define/DCDefine.swift
1
553
// // DCDefine.swift // Uber // // Created by dengchen on 15/12/10. // Copyright © 2015年 name. All rights reserved. // import UIKit let loadingTip = "加载中..." let ScreenWidth = UIScreen.mainScreen().bounds.width let ScreenHeight = UIScreen.mainScreen().bounds.height let Screenbounds = UIScreen.mainScreen().bounds let IOS8:Float = 8.0 let isIphone5 = (ScreenHeight == 568) func DCLog(message:String,fucName:String = __FUNCTION__) { #if DEBUG print("\(fucName) logInfo:\n\(message)") #else #endif }
mit
1a9ecf1e0b0738980e4a3d6637b3e86e
17.133333
58
0.658088
3.443038
false
false
false
false
ingresse/ios-sdk
IngresseSDK/Model/CheckinStatus.swift
1
1062
// // CheckinStatus.swift // IngresseSDK // // Created by Mobile Developer on 7/6/18. // Copyright © 2018 Ingresse. All rights reserved. // public class CheckinStatus: NSObject, Decodable { public var id: Int public var timestamp: Int public var operation: String public var operatorUser: User? public var holder: User? enum CodingKeys: String, CodingKey { case id case timestamp case operation case operatorUser = "operator" case holder } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decodeIfPresent(Int.self, forKey: .id) ?? -1 timestamp = try container.decodeIfPresent(Int.self, forKey: .timestamp) ?? -1 operation = try container.decodeIfPresent(String.self, forKey: .operation) ?? "" operatorUser = try container.decodeIfPresent(User.self, forKey: .operatorUser) holder = try container.decodeIfPresent(User.self, forKey: .holder) } }
mit
f27f75a731e5c139115e9065bdcaa907
32.15625
88
0.672008
4.313008
false
false
false
false
huonw/swift
test/decl/func/operator.swift
1
14604
// RUN: %target-typecheck-verify-swift infix operator %%% infix operator %%%% func %%%() {} // expected-error {{operators must have one or two arguments}} func %%%%(a: Int, b: Int, c: Int) {} // expected-error {{operators must have one or two arguments}} struct X {} struct Y {} func +(lhs: X, rhs: X) -> X {} // okay func +++(lhs: X, rhs: X) -> X {} // expected-error {{operator implementation without matching operator declaration}} infix operator ++++ : ReallyHighPrecedence precedencegroup ReallyHighPrecedence { higherThan: BitwiseShiftPrecedence associativity: left } infix func fn_binary(_ lhs: Int, rhs: Int) {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} func ++++(lhs: X, rhs: X) -> X {} func ++++(lhs: Y, rhs: Y) -> Y {} // okay func useInt(_ x: Int) {} func test() { var x : Int let y : Int = 42 // Produce a diagnostic for using the result of an assignment as a value. // rdar://12961094 useInt(x = y) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} _ = x } prefix operator ~~ postfix operator ~~ infix operator ~~ postfix func foo(_ x: Int) {} // expected-error {{'postfix' requires a function with an operator identifier}} postfix func ~~(x: Int) -> Float { return Float(x) } postfix func ~~(x: Int, y: Int) {} // expected-error {{'postfix' requires a function with one argument}} prefix func ~~(x: Float) {} func test_postfix(_ x: Int) { ~~x~~ } prefix operator ~~~ // expected-note 2{{prefix operator found here}} // Unary operators require a prefix or postfix attribute func ~~~(x: Float) {} // expected-error{{prefix unary operator missing 'prefix' modifier}}{{1-1=prefix }} protocol P { static func ~~~(x: Self) // expected-error{{prefix unary operator missing 'prefix' modifier}}{{10-10=prefix }} } prefix func +// this should be a comment, not an operator (arg: Int) -> Int { return arg } prefix func -/* this also should be a comment, not an operator */ (arg: Int) -> Int { return arg } func +*/ () {} // expected-error {{expected identifier in function declaration}} expected-error {{unexpected end of block comment}} expected-error {{closure expression is unused}} expected-error{{top-level statement cannot begin with a closure expression}} expected-note{{did you mean to use a 'do' statement?}} {{13-13=do }} func errors() { */ // expected-error {{unexpected end of block comment}} // rdar://12962712 - reject */ in an operator as it should end a block comment. */+ // expected-error {{unexpected end of block comment}} } prefix operator ... prefix func ... (arg: Int) -> Int { return arg } func resyncParser() {} // Operator decl refs (<op>) infix operator +-+ prefix operator +-+ prefix operator -+- postfix operator -+- infix operator +-+= infix func +-+ (x: Int, y: Int) -> Int {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} prefix func +-+ (x: Int) -> Int {} prefix func -+- (y: inout Int) -> Int {} // expected-note 2{{found this candidate}} postfix func -+- (x: inout Int) -> Int {} // expected-note 2{{found this candidate}} infix func +-+= (x: inout Int, y: Int) -> Int {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} var n = 0 // Infix by context _ = (+-+)(1, 2) // Prefix by context _ = (+-+)(1) // Ambiguous -- could be prefix or postfix (-+-)(&n) // expected-error{{ambiguous use of operator '-+-'}} // Assignment operator refs become inout functions _ = (+-+=)(&n, 12) (+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{8-8=&}} var f1 : (Int, Int) -> Int = (+-+) var f2 : (Int) -> Int = (+-+) var f3 : (inout Int) -> Int = (-+-) // expected-error{{ambiguous use of operator '-+-'}} var f4 : (inout Int, Int) -> Int = (+-+=) var r5 : (a : (Int, Int) -> Int, b : (Int, Int) -> Int) = (+, -) var r6 : (a : (Int, Int) -> Int, b : (Int, Int) -> Int) = (b : +, a : -) struct f6_S { subscript(op : (Int, Int) -> Int) -> Int { return 42 } } var f6_s : f6_S var junk = f6_s[+] // Unicode operator names infix operator ☃ infix operator ☃⃠ // Operators can contain (but not start with) combining characters func ☃(x: Int, y: Int) -> Bool { return x == y } func ☃⃠(x: Int, y: Int) -> Bool { return x != y } var x, y : Int _ = x☃y _ = x☃⃠y // rdar://14705150 - crash on invalid func test_14705150() { let a = 4 var b! = a // expected-error {{type annotation missing in pattern}} // expected-error @-1 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error @-2 {{expected expression}} } prefix postfix func ++(x: Int) {} // expected-error {{'postfix' contradicts previous modifier 'prefix'}} {{8-16=}} postfix prefix func ++(x: Float) {} // expected-error {{'prefix' contradicts previous modifier 'postfix'}} {{9-16=}} postfix prefix infix func ++(x: Double) {} // expected-error {{'prefix' contradicts previous modifier 'postfix'}} {{9-16=}} expected-error {{'infix' contradicts previous modifier 'postfix'}} {{16-22=}} infix prefix func +-+(x: Int, y: Int) {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} expected-error{{'prefix' contradicts previous modifier 'infix'}} {{7-14=}} // Don't allow one to define a postfix '!'; it's built into the // language. Also illegal to have any postfix operator starting with '!'. postfix operator ! // expected-error {{cannot declare a custom postfix '!' operator}} expected-error {{expected operator name in operator declaration}} prefix operator & // expected-error {{cannot declare a custom prefix '&' operator}} // <rdar://problem/14607026> Restrict use of '<' and '>' as prefix/postfix operator names postfix operator > // expected-error {{cannot declare a custom postfix '>' operator}} prefix operator < // expected-error {{cannot declare a custom prefix '<' operator}} postfix func !(x: Int) { } // expected-error{{cannot declare a custom postfix '!' operator}} postfix func!(x: Int8) { } // expected-error{{cannot declare a custom postfix '!' operator}} prefix func & (x: Int) {} // expected-error {{cannot declare a custom prefix '&' operator}} // Only allow operators at global scope: func operator_in_func_bad () { prefix func + (input: String) -> String { return "+" + input } // expected-error {{operator functions can only be declared at global or in type scope}} } infix operator ? // expected-error {{expected operator name in operator declaration}} infix operator ??= func ??= <T>(result : inout T?, rhs : Int) { // ok } // <rdar://problem/14296004> [QoI] Poor diagnostic/recovery when two operators (e.g., == and -) are adjacted without spaces. _ = n*-4 // expected-error {{missing whitespace between '*' and '-' operators}} {{6-6= }} {{7-7= }} if n==-1 {} // expected-error {{missing whitespace between '==' and '-' operators}} {{5-5= }} {{7-7= }} prefix operator ☃⃠ prefix func☃⃠(a : Int) -> Int { return a } postfix operator ☃⃠ postfix func☃⃠(a : Int) -> Int { return a } _ = n☃⃠ ☃⃠ n // Ok. _ = n ☃⃠ ☃⃠n // Ok. _ = n ☃⃠☃⃠ n // expected-error {{use of unresolved operator '☃⃠☃⃠'}} _ = n☃⃠☃⃠n // expected-error {{ambiguous missing whitespace between unary and binary operators}} // expected-note @-1 {{could be binary '☃⃠' and prefix '☃⃠'}} {{12-12= }} {{18-18= }} // expected-note @-2 {{could be postfix '☃⃠' and binary '☃⃠'}} {{6-6= }} {{12-12= }} _ = n☃⃠☃⃠ // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = ~!n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = -+n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = -++n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} // <rdar://problem/16230507> Cannot use a negative constant as the second operator of ... operator _ = 3...-5 // expected-error {{ambiguous missing whitespace between unary and binary operators}} expected-note {{could be postfix '...' and binary '-'}} expected-note {{could be binary '...' and prefix '-'}} protocol P0 { static func %%%(lhs: Self, rhs: Self) -> Self } protocol P1 { func %%%(lhs: Self, rhs: Self) -> Self // expected-warning{{operator '%%%' declared in protocol must be 'static'}}{{3-3=static }} } struct S0 { static func %%%(lhs: S0, rhs: S0) -> S0 { return lhs } } extension S0 { static func %%%%(lhs: S0, rhs: S0) -> S0 { return lhs } } struct S1 { func %%%(lhs: S1, rhs: S1) -> S1 { return lhs } // expected-error{{operator '%%%' declared in type 'S1' must be 'static'}}{{3-3=static }} } extension S1 { func %%%%(lhs: S1, rhs: S1) -> S1 { return lhs } // expected-error{{operator '%%%%' declared in type 'S1' must be 'static'}}{{3-3=static }} } class C0 { static func %%%(lhs: C0, rhs: C0) -> C0 { return lhs } } class C1 { final func %%%(lhs: C1, rhs: C1) -> C1 { return lhs } // expected-error{{operator '%%%' declared in type 'C1' must be 'static'}}{{3-3=static }} } final class C2 { class func %%%(lhs: C2, rhs: C2) -> C2 { return lhs } } class C3 { class func %%%(lhs: C3, rhs: C3) -> C3 { return lhs } // expected-error{{operator '%%%' declared in non-final class 'C3' must be 'final'}}{{3-3=final }} } class C4 { func %%%(lhs: C4, rhs: C4) -> C4 { return lhs } // expected-error{{operator '%%%' declared in type 'C4' must be 'static'}}{{3-3=static }} } struct Unrelated { } struct S2 { static func %%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> S2 { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> S2.Type { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} // Okay: refers to S2 static func %%%(lhs: S2, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: inout S2, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: inout S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: S2) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: inout S2) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: S2.Type) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: inout S2.Type) -> Unrelated { } } extension S2 { static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> S2 { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> S2.Type { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} // Okay: refers to S2 static func %%%%(lhs: S2, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout S2, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: S2) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout S2) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: S2.Type) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout S2.Type) -> Unrelated { } } protocol P2 { static func %%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> Self // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> Self.Type // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} // Okay: refers to Self static func %%%(lhs: Self, rhs: Unrelated) -> Unrelated static func %%%(lhs: inout Self, rhs: Unrelated) -> Unrelated static func %%%(lhs: Self.Type, rhs: Unrelated) -> Unrelated static func %%%(lhs: inout Self.Type, rhs: Unrelated) -> Unrelated static func %%%(lhs: Unrelated, rhs: Self) -> Unrelated static func %%%(lhs: Unrelated, rhs: inout Self) -> Unrelated static func %%%(lhs: Unrelated, rhs: Self.Type) -> Unrelated static func %%%(lhs: Unrelated, rhs: inout Self.Type) -> Unrelated } extension P2 { static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Self { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Self.Type { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} // Okay: refers to Self static func %%%%(lhs: Self, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout Self, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Self.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout Self.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: Self) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout Self) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: Self.Type) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout Self.Type) -> Unrelated { } } protocol P3 { // Okay: refers to P3 static func %%%(lhs: P3, rhs: Unrelated) -> Unrelated } extension P3 { // Okay: refers to P3 static func %%%%(lhs: P3, rhs: Unrelated) -> Unrelated { } } // rdar://problem/27940842 - recovery with a non-static '=='. class C5 { func == (lhs: C5, rhs: C5) -> Bool { return false } // expected-error{{operator '==' declared in type 'C5' must be 'static'}} func test1(x: C5) { _ = x == x } } class C6 { static func == (lhs: C6, rhs: C6) -> Bool { return false } func test1(x: C6) { if x == x && x = x { } // expected-error{{expression is not assignable: '&&' returns immutable value}} } }
apache-2.0
3d4c85d933ef58cc40a08b33779113c0
39.633053
327
0.633945
3.558008
false
false
false
false
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/Model/GuessModel.swift
1
632
// // GuessModel.swift // XMLYDemo // // Created by xiudou on 2016/12/22. // Copyright © 2016年 CoderST. All rights reserved. // import UIKit class GuessModel: BaseModel { var title : String = "" var list : [GuessItem] = [GuessItem]() override func setValue(_ value: Any?, forKey key: String) { if key == "list"{ if let listArray = value as? [[String : AnyObject]]{ for listDict in listArray { list.append(GuessItem(dict: listDict)) } } }else{ super.setValue(value, forKey: key) } } }
mit
ca7cfbc79d59457a355ca5c66a0d6413
21.464286
64
0.527822
4.032051
false
false
false
false
ishaq/SimplePDF
Example/Tests/Tests.swift
1
1164
// https://github.com/Quick/Quick import Quick import Nimble import SimplePDFSwift class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
9a43f05d51fe486394663811c3b2cbe9
22.16
60
0.360104
5.514286
false
false
false
false
tache/SwifterSwift
Sources/Extensions/CoreGraphics/CGPointExtensions.swift
1
4739
// // CGPointExtensions.swift // SwifterSwift // // Created by Omar Albeik on 07/12/2016. // Copyright © 2016 SwifterSwift // #if os(macOS) import Cocoa #else import UIKit #endif // MARK: - Methods public extension CGPoint { /// SwifterSwift: Distance from another CGPoint. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// let distance = point1.distance(from: point2) /// //distance = 28.28 /// /// - Parameter point: CGPoint to get distance from. /// - Returns: Distance between self and given CGPoint. public func distance(from point: CGPoint) -> CGFloat { return CGPoint.distance(from: self, to: point) } /// SwifterSwift: Distance between two CGPoints. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// let distance = CGPoint.distance(from: point2, to: point1) /// //Distance = 28.28 /// /// - Parameters: /// - point1: first CGPoint. /// - point2: second CGPoint. /// - Returns: distance between the two given CGPoints. public static func distance(from point1: CGPoint, to point2: CGPoint) -> CGFloat { // http://stackoverflow.com/questions/6416101/calculate-the-distance-between-two-cgpoints return sqrt(pow(point2.x - point1.x, 2) + pow(point2.y - point1.y, 2)) } } // MARK: - Operators public extension CGPoint { /// SwifterSwift: Add two CGPoints. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// let point = point1 + point2 /// //point = CGPoint(x: 40, y: 40) /// /// - Parameters: /// - lhs: CGPoint to add to. /// - rhs: CGPoint to add. /// - Returns: result of addition of the two given CGPoints. public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } /// SwifterSwift: Add a CGPoints to self. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// point1 += point2 /// //point1 = CGPoint(x: 40, y: 40) /// /// - Parameters: /// - lhs: self /// - rhs: CGPoint to add. public static func += (lhs: inout CGPoint, rhs: CGPoint) { lhs = lhs + rhs } /// SwifterSwift: Subtract two CGPoints. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// let point = point1 - point2 /// //point = CGPoint(x: -20, y: -20) /// /// - Parameters: /// - lhs: CGPoint to subtract from. /// - rhs: CGPoint to subtract. /// - Returns: result of subtract of the two given CGPoints. public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } /// SwifterSwift: Subtract a CGPoints from self. /// /// let point1 = CGPoint(x: 10, y: 10) /// let point2 = CGPoint(x: 30, y: 30) /// point1 -= point2 /// //point1 = CGPoint(x: -20, y: -20) /// /// - Parameters: /// - lhs: self /// - rhs: CGPoint to subtract. public static func -= (lhs: inout CGPoint, rhs: CGPoint) { lhs = lhs - rhs } /// SwifterSwift: Multiply a CGPoint with a scalar /// /// let point1 = CGPoint(x: 10, y: 10) /// let scalar = point1 * 5 /// //scalar = CGPoint(x: 50, y: 50) /// /// - Parameters: /// - point: CGPoint to multiply. /// - scalar: scalar value. /// - Returns: result of multiplication of the given CGPoint with the scalar. public static func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } /// SwifterSwift: Multiply self with a scalar /// /// let point1 = CGPoint(x: 10, y: 10) /// point *= 5 /// //point1 = CGPoint(x: 50, y: 50) /// /// - Parameters: /// - point: self. /// - scalar: scalar value. /// - Returns: result of multiplication of the given CGPoint with the scalar. public static func *= (point: inout CGPoint, scalar: CGFloat) { point = point * scalar } /// SwifterSwift: Multiply a CGPoint with a scalar /// /// let point1 = CGPoint(x: 10, y: 10) /// let scalar = 5 * point1 /// //scalar = CGPoint(x: 50, y: 50) /// /// - Parameters: /// - scalar: scalar value. /// - point: CGPoint to multiply. /// - Returns: result of multiplication of the given CGPoint with the scalar. public static func * (scalar: CGFloat, point: CGPoint) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } }
mit
5bc32c104674d76950e31021975dc52d
30.171053
91
0.559308
3.41847
false
false
false
false
thoughtbot/Swish
Tests/SwishTests/MockClientSpec.swift
1
4971
import Foundation import Nimble import Quick import Swish import Swoosh class MockClientSpec: QuickSpec { override func spec() { describe("MockClient") { context("empty client") { it("shouldn't give a result") { let client = MockClient() client.perform(FakeRequest()) { _ in fail() } } } context("when() with a metatype") { it("succeeds when given a successful response") { let client = MockClient() .when(FakeRequest.self, "Yay") self.expectResponse(client, FakeRequest(), "Yay") } it("fails when given a failure") { let client = MockClient().when(FakeRequest.self, .serverError(code: 404, data: nil)) self.expectResponse(client, FakeRequest()) { result in switch result { case .success: fail() default: break } } } } context("when() with a request instance") { it("succeeds when given a successful response") { let client = MockClient() .when(FakeRequest(), "Yay") self.expectResponse(client, FakeRequest(), "Yay") } it("fails when given a failure") { let client = MockClient().when(FakeRequest(), .serverError(code: 404, data: nil)) self.expectResponse(client, FakeRequest()) { result in switch result { case .success: fail() default: break } } } } context("when() given a matching function") { it("succeeds when the fn returns a response object") { let client = MockClient() .when { (_: FakeRequest) in "Yay" } self.expectResponse(client, FakeRequest(), "Yay") } it("fails when the fn returns an error") { let client = MockClient() .when { (_: FakeRequest) in .serverError(code: 404, data: nil) } self.expectResponse(client, FakeRequest()) { result in switch result { case .success: fail() default: break } } } } context("when using an any matcher") { it("returns the single given response") { let client = MockClient() .when(FakeRequest.self, "hello world") self.expectResponse(client, FakeRequest(), "hello world") } } context("when using an mutliple any matchers") { it("returns the appropriate given response") { let client = MockClient() .when(FakeRequest.self, "hello world") .when(FakeRequestWithArguments.self, true) self.expectResponse(client, FakeRequest(), "hello world") self.expectResponse(client, FakeRequestWithArguments(arg: "xyz"), true) } } context("when using an equality matcher") { it("gives a different repsonse according to the specific request") { let client = MockClient() .when(FakeRequestWithArguments(arg: "xyz"), true) .when(FakeRequestWithArguments(arg: "abc"), false) self.expectResponse(client, FakeRequestWithArguments(arg: "xyz"), true) self.expectResponse(client, FakeRequestWithArguments(arg: "abc"), false) } } context("when using a predicate matcher") { it("it returns the appropriate response") { let client = MockClient() .when(FakeRequestWithArguments(arg: "xyz"), true) .when { (req: FakeRequestWithArguments) -> Bool? in if req.arg.count > 5 { return .some(true) } else { return .some(false) } } self.expectResponse(client, FakeRequestWithArguments(arg: "xyz"), true) self.expectResponse(client, FakeRequestWithArguments(arg: "abc"), false) self.expectResponse(client, FakeRequestWithArguments(arg: "def"), false) self.expectResponse(client, FakeRequestWithArguments(arg: "abcdef"), true) } } } } private func expectResponse<T>(_ client: Client, _ request: T, _ expectedResponse: T.ResponseObject) where T: Request, T.ResponseObject: Equatable { waitUntil(timeout: 1) { done in client.perform(request) { response in if case let .success(response) = response { expect(response).to(equal(expectedResponse)) done() } } } } private func expectResponse<T>(_ client: Client, _ request: T, responseExpectation: @escaping (Result<T.ResponseObject, SwishError>) -> Void) where T: Request { waitUntil(timeout: 1) { done in client.perform(request) { response in responseExpectation(response) done() } } } }
mit
21fbdea40ae6e7ed78c1af84cd702357
29.685185
162
0.554416
4.615599
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/BottomRightMiddle.Individual.swift
1
1305
// // BottomRightMiddle.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct BottomRightMiddle { let bottomRight: LayoutElement.Point let middle: LayoutElement.Vertical } } // MARK: - Make Frame extension IndividualProperty.BottomRightMiddle { private func makeFrame(bottomRight: Point, middle: Float, width: Float) -> Rect { let height = (bottomRight.y - middle).double let x = bottomRight.x - width let y = middle - height.half let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Width extension IndividualProperty.BottomRightMiddle: LayoutPropertyCanStoreWidthToEvaluateFrameType { public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let bottomRight = self.bottomRight.evaluated(from: parameters) let middle = self.middle.evaluated(from: parameters) let height = (bottomRight.y - middle).double let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height)) return self.makeFrame(bottomRight: bottomRight, middle: middle, width: width) } }
apache-2.0
b4de789747da792fd7d989474093ab75
22.888889
115
0.728682
3.944954
false
false
false
false
jilouc/kuromoji-swift
kuromoji-swift/util/StringUtils.swift
1
1727
// // StringUtils.swift // kuromoji-swift // // Created by Jean-Luc Dagon on 17/11/2016. // Copyright © 2016 Cocoapps. All rights reserved. // import Foundation extension String { func replace(_ pattern: String, with replacement: String) -> String { let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive) return regex.stringByReplacingMatches(in: self, options:[], range: NSMakeRange(0, self.characters.count), withTemplate: replacement) } func separatedBySpaces() -> [String] { return self.components(separatedBy: .whitespaces).filter { return $0.characters.count != 0 } } func scanHexInt32() -> UInt32? { return Scanner(string: self).scanHexInt32() } } extension Scanner { func scanHexInt32() -> UInt32? { var value: UInt32 = 0 if scanHexInt32(&value) { return value } return nil } func scanCharacters(from set: CharacterSet) -> String? { var value: NSString? = "" if scanCharacters(from: set, into: &value), let value = value as? String { return value } return nil } func scanUpToCharacters(from set: CharacterSet) -> String? { var value: NSString? = "" if scanUpToCharacters(from: set, into: &value), let value = value as? String { return value } return nil } func scanUpToString(_ string: String) -> String? { var value: NSString? = "" if scanUpTo(string, into: &value), let value = value as? String { return value } return nil } }
apache-2.0
160d3e5f72d3a5baf76d84bbb8b0afde
25.553846
140
0.573581
4.459948
false
false
false
false
vmachiel/swift
LearningSwift.playground/Pages/Protocols.xcplaygroundpage/Contents.swift
1
4818
// Protocols specify requirements (abc like) that need to be implmented. Think of a // board game where players and computers take turns. You can have a default Player class // that is subclassed into HumanPlayer and ComputerPlayer. Player needs to specify that // and instance can take a turn. But, humans and AI don't share behavior, and both over- // ride the basic method. So you make Player into a protocol, which specifies that a // takeTurn method MUST be implemented, and the different subclasses can implement them // in different ways. // Protocols can inherit other protocols. Think classes without data. import UIKit class Board { var typeOfGame: String var numberOfPlayers: Int init(typeOfGame: String, numberOfPlayers: Int) { self.typeOfGame = typeOfGame self.numberOfPlayers = numberOfPlayers } } protocol Player { func takeTurn(on board: Board) } // So now you declare a human and AI player class, which must implement the takeTurn // method. To this by "inheriting" the protocol. You don't write override, since you're // implementing instead. You can make them both classes or structures. // These are structs since you don't need multiple references to the same players struct HumanPlayer: Player { var name: String var score: Int func takeTurn(on board: Board) { print("Take a turn on the board)") } } struct ComputerPlayer: Player { func takeTurn(on board: Board) { print("Bleep Bloop, I've taken my turn") } } // EXTRA: You can extend objects by implemeting protocols as well: // Do this to ORGANIZE YOUR CODE extension HumanPlayer: CustomStringConvertible { var description: String { return "This player is named \(name) and has a score of \(score)" } } // Protocols are types. Vars can be of that type, which can be assigned something that // conforms to that protocol protocol Moveable { mutating func move(to point: CGPoint) } class Car: Moveable { var name: String init(name: String) { self.name = name } func move(to point: CGPoint) { print("I've moved to \(point)") } } let prius = Car(name: "Car 1") var somethingElse: Moveable //Protocols are types somethingElse = prius //TYPE IS Moveable // somethingElse.name = "Car2" Can't be done, it's not Car, its Moveable prius.name = "Car 2" print(prius.name) // You can organize different types that do confirm to same protocol, into an array of // the protocol type struct Shape: Moveable { mutating func move(to point: CGPoint) { print("Moved to \(point)") } } let square = Shape() var protocolArray = [Moveable]() protocolArray = [square, prius] // THEY CAN ONLY USE THE MOVEABLE funcs/vars: they are Moveable // USES OF PROTOCOLS!! // 1: Delegates. Views can send messages to a controller that implements a protocol // Look up delegation!! // 2: Dict keys need to be unique and hashable. Dictionary KEYS therefore implement the // Hashable protocol, which implements the Equatable protocol. Equatale enforces that an // item can be tested if it's equal to another item using == resulting in true or false // Types of the two arguments are Self: if an Int implements this for example, type of // the arguments are Int. protocol Equatable { static func ==(lhs: Self, rhs: Self) -> Bool } // Hashable inherists that, plus enforces that an interger hash value can be derived from // the object protocol Hashable: Equatable { var hashValue: Int { get } } // So you get: //Dictionary<Key: Hashable, Value> // Protocol extentions! // Thus you GAIN something if you confirm to that protocol let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"] let beatles = Set(["John", "Paul", "George", "Ringo"]) // These are of type Array and Set, both confirm to protocol Collection extension Collection { func summarize() { print("There are \(self.count) of us.") for name in self { print(name) } } } pythons.summarize() beatles.summarize() // Protocolos can define a default implemtation by using an Extention protocol Movable2 { func move(by: Int) var hasMoved: Bool {get} var distanceFromStart: Int {get set} } // Default implementation extension Movable2 { var hasMoved: Bool { return distanceFromStart != 0 } } // Now you can implement only the other two requirements class Car2: Movable2 { var distanceFromStart = 0 func move(by amount: Int) { distanceFromStart += amount } } // So now you can make an instance, without have to implement the distanceFromStart var car2 = Car2() car2.hasMoved // False car2.move(by: -8) car2.distanceFromStart // -8 car2.hasMoved //True // You CAN override the default implemtation
mit
e1a239e3a00e728b8ec86e119923f98c
27.508876
89
0.697385
3.945946
false
false
false
false
argent-os/argent-ios
app-ios/SearchViewController.swift
1
20160
// // SearchViewController.swift // CustomSearchBar // // Created by Gabriel Theodoropoulos on 8/9/15. // Copyright (c) 2015 Appcoda. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import TransitionTreasury import TransitionAnimation import CellAnimator import DZNEmptyDataSet import Crashlytics class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate { var tblSearchResults:UITableView = UITableView() let userImageView: UIImageView = UIImageView(frame: CGRectMake(10, 15, 30, 30)) private var dataArray = [User]() private var filteredArray = [User]() private var shouldShowSearchResults = false private var searchController: UISearchController! private var searchedText:String = "" private var dateFormatter = NSDateFormatter() private var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray) private var searchOverlayMaskView = UIView() private var refreshControlView = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() configureView() loadUserAccounts() configureSearchController() } override func viewDidAppear(animated: Bool) { self.searchController.searchBar.hidden = false if let text = searchController.searchBar.text { if text.characters.count > 0 { searchController.searchBar.becomeFirstResponder() } } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func configureView() { let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height let placeholderMaskImageView = UIImageView() placeholderMaskImageView.image = UIImage(named: "IconEmptyTableSearch") placeholderMaskImageView.contentMode = .ScaleAspectFit placeholderMaskImageView.frame = CGRect(x: searchOverlayMaskView.layer.frame.width/2-160, y: searchOverlayMaskView.layer.frame.height/2+170, width: 320, height: 320) placeholderMaskImageView.center = CGPointMake(self.view.layer.frame.width/2, self.view.layer.frame.height/2-120) searchOverlayMaskView.addSubview(placeholderMaskImageView) searchOverlayMaskView.backgroundColor = UIColor.whiteColor() searchOverlayMaskView.frame = CGRect(x: 0, y: 100, width: screenWidth, height: screenHeight-60) refreshControlView.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControlView.addTarget(self, action: #selector(SearchViewController.refresh(_:) as (SearchViewController) -> (UIRefreshControl) -> ()), forControlEvents: UIControlEvents.ValueChanged) self.tblSearchResults.addSubview(refreshControlView) // not required when using UITableViewController // definespresentationcontext screen self.definesPresentationContext = true self.view.backgroundColor = UIColor.whiteColor() let app: UIApplication = UIApplication.sharedApplication() let statusBarHeight: CGFloat = app.statusBarFrame.size.height let statusBarView: UIView = UIView(frame: CGRectMake(0, -statusBarHeight, UIScreen.mainScreen().bounds.size.width, statusBarHeight)) statusBarView.backgroundColor = UIColor.pastelBlue() self.navigationController?.navigationBar.addSubview(statusBarView) // THIS SETS STATUS BAR COLOR self.navigationController?.navigationBar.barStyle = .Black self.setNeedsStatusBarAppearanceUpdate() self.navigationController?.navigationBarHidden = false // self.navigationItem.title = "Search and Pay" self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor() self.navigationController?.navigationBar.backgroundColor = UIColor.pastelBlue() self.navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : UIFont(name: "SFUIText-Regular", size: 17)! ] activityIndicator.center = view.center activityIndicator.startAnimating() activityIndicator.hidesWhenStopped = true self.view.addSubview(activityIndicator) tblSearchResults.reloadData() tblSearchResults.showsVerticalScrollIndicator = false tblSearchResults.delegate = self tblSearchResults.dataSource = self tblSearchResults.emptyDataSetSource = self tblSearchResults.emptyDataSetDelegate = self // A little trick for removing the cell separators tblSearchResults.tableFooterView = UIView() tblSearchResults.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight-40) self.view.addSubview(tblSearchResults) } // MARK: UITableView Delegate and Datasource functions func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if shouldShowSearchResults { return filteredArray.count } else { return dataArray.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { self.tblSearchResults.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") let CellIdentifier: String = "Cell" let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: CellIdentifier) CellAnimator.animateCell(cell, withTransform: CellAnimator.TransformTilt, andDuration: 0.3) cell.imageView?.image = nil cell.indentationWidth = 2 // The amount each indentation will move the text cell.indentationLevel = 1 // The number of times you indent the text cell.textLabel?.textColor = UIColor.darkGrayColor() cell.textLabel?.font = UIFont(name: "SFUIText-Regular", size: 14) cell.selectionStyle = UITableViewCellSelectionStyle.Default cell.detailTextLabel?.font = UIFont(name: "SFUIText-Regular", size: 14) cell.detailTextLabel?.textColor = UIColor.lightBlue() cell.imageView!.frame = CGRectMake(10, 15, 30, 30) cell.imageView!.backgroundColor = UIColor.clearColor() cell.imageView!.layer.cornerRadius = 15 cell.imageView!.layer.masksToBounds = true //cell.imageView!.image = UIImage(named: "IconCheckFilled") if shouldShowSearchResults { // After filtering let pic = filteredArray[indexPath.row].picture cell.textLabel?.text = "@" + String(filteredArray[indexPath.row].username) //String(filteredArray[indexPath.row].business_name) ?? if pic != "" { let imageView: UIImageView = UIImageView(frame: CGRectMake(10, 15, 30, 30)) imageView.backgroundColor = UIColor.clearColor() imageView.layer.cornerRadius = 15 imageView.layer.masksToBounds = true //let priority = DISPATCH_QUEUE_PRIORITY_HIGH } let business_name = filteredArray[indexPath.row].business_name let first_name = filteredArray[indexPath.row].first_name let last_name = String(filteredArray[indexPath.row].last_name) let username = String(filteredArray[indexPath.row].username) if business_name != "" { cell.detailTextLabel?.text = business_name cell.textLabel?.text = "@" + username } else if first_name != "" { cell.detailTextLabel?.text = first_name + " " + last_name cell.textLabel?.text = "@" + username } else { cell.detailTextLabel?.text = "@" + username } } else { // Default loaded array let pic = dataArray[indexPath.row].picture if pic != "" { let imageView: UIImageView = UIImageView(frame: CGRectMake(10, 15, 30, 30)) imageView.backgroundColor = UIColor.clearColor() imageView.layer.cornerRadius = 15 imageView.layer.masksToBounds = true //let priority = DISPATCH_QUEUE_PRIORITY_HIGH } // let business_name = dataArray[indexPath.row].business_name // let first_name = dataArray[indexPath.row].first_name // let last_name = String(dataArray[indexPath.row].last_name) // if business_name != "" { // cell.detailTextLabel?.text = business_name // } else if first_name != "" || last_name != "" { // cell.detailTextLabel?.text = first_name + " " + last_name // } else { // cell.detailTextLabel?.text = String(dataArray[indexPath.row].username) // } } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) self.shouldShowSearchResults = false self.searchController.searchBar.hidden = true self.searchController.searchBar.tintColor = UIColor.whiteColor() self.searchController.searchBar.resignFirstResponder() self.searchController.searchBar.placeholder = "" let user: User if searchController.active && searchController.searchBar.text != "" { user = filteredArray[indexPath.row] } else { user = dataArray[indexPath.row] } let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SearchDetailViewController") as! SearchDetailViewController self.navigationController?.pushViewController(vc, animated: true) vc.detailUser = user } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60.0 } // MARK: Custom functions func loadUserAccounts() { activityIndicator.center = view.center activityIndicator.startAnimating() activityIndicator.hidesWhenStopped = true self.view.addSubview(activityIndicator) User.getUserAccounts({ (items, error) in if error != nil { let alert = UIAlertController(title: "Error", message: "Could not load user accounts \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } self.dataArray = items! self.activityIndicator.stopAnimating() //self.tblSearchResults.reloadData() }) } func configureSearchController() { let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width //let screenHeight = screen.size.height // Initialize and perform a minimum configuration to the search controller. searchController = UISearchController(searchResultsController: nil) // searchController.searchBar.scopeButtonTitles = ["Merchants", "Users"] searchController.searchBar.layer.frame.origin.x = 5 searchController.searchBar.layer.frame.size.width = screenWidth-20 searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.placeholder = "" searchController.searchBar.sizeToFit() searchController.searchBar.translucent = true searchController.searchBar.backgroundColor = UIColor.clearColor() searchController.searchBar.searchBarStyle = .Minimal searchController.searchBar.tintColor = UIColor.mediumBlue() searchController.searchBar.barStyle = .Black searchController.searchBar.showsScopeBar = true searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.autocorrectionType = .No searchController.searchBar.autocapitalizationType = .None searchController.searchBar.setImage(UIImage(named: "ic_search"), forSearchBarIcon: .Search, state: .Normal) searchController.searchBar.tintColor = UIColor.whiteColor() // White placeholder UILabel.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.whiteColor().colorWithAlphaComponent(0.5) UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.classForCoder()]).tintColor = UIColor.whiteColor() UIButton.appearanceWhenContainedInInstancesOfClasses([UISearchBar.classForCoder()]).tintColor = UIColor.whiteColor() UIButton.appearanceWhenContainedInInstancesOfClasses([UISearchBar.classForCoder()]).setTitleColor(UIColor.whiteColor(), forState: .Normal) UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.classForCoder()]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(),NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 14)!] self.navigationController?.navigationBar.addSubview(self.searchController.searchBar) } // MARK: UISearchBarDelegate functions func searchBarTextDidBeginEditing(searchBar: UISearchBar) { // Setup the Scope Bar let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width searchController.searchBar.layer.frame.size.width = screenWidth-10 searchController.searchBar.layer.frame.origin.x = 0 searchBar.setShowsCancelButton(true, animated: true) // Set cancel button color for ob: UIView in ((searchBar.subviews[0] )).subviews { if let z = ob as? UIButton { let btn: UIButton = z btn.setTitleColor(UIColor.whiteColor(), forState: .Normal) } } shouldShowSearchResults = true tblSearchResults.reloadData() searchOverlayMaskView.removeFromSuperview() self.view.addSubview(tblSearchResults) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width searchController.searchBar.layer.frame.size.width = screenWidth-10 searchController.searchBar.layer.frame.origin.x = 5 shouldShowSearchResults = false searchController.searchBar.placeholder = "" loadUserAccounts() addSubviewWithFade(searchOverlayMaskView, parentView: self, duration: 0.3) tblSearchResults.removeFromSuperview() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { if !shouldShowSearchResults { shouldShowSearchResults = true //tblSearchResults.reloadData() } self.view.endEditing(true) searchController.searchBar.resignFirstResponder() self.view.addSubview(tblSearchResults) } // MARK: UISearchResultsUpdating delegate function func updateSearchResultsForSearchController(searchController: UISearchController) { guard let searchString = searchController.searchBar.text else { return } Answers.logSearchWithQuery(searchString, customAttributes: nil) // Filter the data array and get only those users that match the search text. filteredArray = dataArray.filter({ (user) -> Bool in let fullName = user.first_name + " " + user.last_name return (user.username.lowercaseString.containsString(searchString.lowercaseString)) || (user.business_name.lowercaseString.containsString(searchString.lowercaseString) || (fullName.lowercaseString.containsString(searchString.lowercaseString))) }) // Reload the tableview. tblSearchResults.reloadData() } // Refresh private func refresh(sender:AnyObject) { self.loadUserAccounts() } // Search here private func didChangeSearchText(searchText: String) { // Filter the data array and get only those users that match the search text. filteredArray = dataArray.filter({ (user) -> Bool in var userStr: NSString if user.business_name != "" { userStr = user.business_name } else { userStr = user.username } Answers.logSearchWithQuery(searchText, customAttributes: nil) return (userStr.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound }) // Reload the tableview. tblSearchResults.reloadData() } private func filterContentForSearchText(searchText: String, scope: String) { filteredArray = filteredArray.filter({( user : User ) -> Bool in let fullName = user.first_name + " " + user.last_name return (user.username.lowercaseString.containsString(searchText.lowercaseString)) || (user.business_name.lowercaseString.containsString(searchText.lowercaseString) || (fullName.lowercaseString.containsString(searchText.lowercaseString))) }) tblSearchResults.reloadData() } // MARK: - UISearchBar Delegate func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope]) } // MARK: DZNEmptyDataSet delegate func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let str = adjustAttributedStringNoLineSpacing("\nARGENT", spacing: 4, fontName: "SFUIText-Regular", fontSize: 17, fontColor: UIColor.lightBlue()) return str } func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let str = adjustAttributedStringNoLineSpacing("SEARCH AND PAY", spacing: 4, fontName: "SFUIText-Regular", fontSize: 13, fontColor: UIColor.lightBlue()) return str } func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! { return UIImage(named: "IconEmptySearchPay") } func buttonTitleForEmptyDataSet(scrollView: UIScrollView!, forState state: UIControlState) -> NSAttributedString! { let str = "" //let attrs = [NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleCallout)] return NSAttributedString(string: str, attributes: calloutAttrs) } func emptyDataSetDidTapButton(scrollView: UIScrollView!) { let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("RecurringBillingViewController") as! RecurringBillingViewController self.presentViewController(viewController, animated: true, completion: nil) } } extension SearchViewController { func refresh(sender: UIRefreshControl) { refreshControlView.endRefreshing() self.loadUserAccounts() } }
mit
70526c1d1e355a4926db1cf6ae397bb2
42.828261
256
0.671131
5.704584
false
false
false
false
zach-freeman/swift-localview
localview/PhotoFullScreenViewController.swift
1
7567
// // PhotoFullScreenViewController.swift // localview // // Created by Zach Freeman on 8/14/15. // Copyright (c) 2021 sparkwing. All rights reserved. // import UIKit class PhotoFullScreenViewController: UIViewController, UIScrollViewDelegate { var containerScrollView: UIScrollView! @IBOutlet var fullImageView: UIImageView! @IBOutlet weak var commentTextView: UITextView! @IBOutlet weak var imageDownloadProgressView: UIProgressView! @IBOutlet weak var doneButton: UIButton! var fullImage: UIImage? var flickrPhoto: FlickrPhoto? var photoFetchState: FlickrApiUtils.PhotoFetchState? override func viewDidLoad() { super.viewDidLoad() self.photoFetchState = .photosNotFetched if Utils.isPhone() { UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver( self, selector: #selector(PhotoFullScreenViewController.orientationChanged(_:)), name: UIDevice.orientationDidChangeNotification, object: UIDevice.current) self.createViews() } // Do any additional setup after loading the view. } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } @objc func orientationChanged(_ note: Notification) { // we have to remove the image and scroll views and re-add them because the // navigation bar size changes when the orientation changes self.fullImageView.removeFromSuperview() self.containerScrollView.removeFromSuperview() self.createViews() self.setupImageInScrollView() } func createViews() { let viewBounds: CGRect = self.viewBounds() self.createScrollView(viewBounds) self.createImageView(viewBounds) self.view.bringSubviewToFront(doneButton) } func viewBounds() -> CGRect { var viewFrame: CGRect = CGRect.zero viewFrame = self.view.bounds return viewFrame } func createScrollView(_ viewBounds: CGRect) { // Create the scroll view self.containerScrollView = UIScrollView(frame: viewBounds) self.containerScrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.containerScrollView.showsHorizontalScrollIndicator = false self.containerScrollView.showsVerticalScrollIndicator = false self.containerScrollView.delegate = self let maxScale: CGFloat = 1.5 self.containerScrollView.maximumZoomScale = maxScale self.view.addSubview(self.containerScrollView) } func createImageView(_ viewBounds: CGRect) { self.fullImageView = UIImageView(frame: viewBounds) self.fullImageView.contentMode = UIView.ContentMode.scaleAspectFill self.fullImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.fullImageView.clipsToBounds = true self.containerScrollView.addSubview(self.fullImageView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.photoFetchState == .photosNotFetched { self.showPhotoAfterDownload() } } @IBAction func doneButtonTapped(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.imageDownloadProgressView.isHidden = true self.doneButton.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Scroll View Delegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.fullImageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { self.centerScrollViewContent() } func showPhotoAfterDownload() { let sdWebImageManager: SDWebImageManager = SDWebImageManager.shared() let progress: SDWebImageDownloaderProgressBlock = { [weak self] (receivedSize, expectedSize, _) in guard self != nil else { return } DispatchQueue.main.async { self?.imageDownloadProgressView.isHidden = false let receivedSizeFloat: Float = NSNumber(value: receivedSize as Int).floatValue let expectedSizeFloat: Float = NSNumber(value: expectedSize as Int).floatValue let progress: Float = receivedSizeFloat/expectedSizeFloat self?.imageDownloadProgressView.setProgress(progress, animated: true) } } let completion: SDInternalCompletionBlock = { [weak self] (image, _, _, _, _, _) in guard self != nil else { return } DispatchQueue.main.async { self?.photoFetchState = .photosFetched if Utils.isPad() { self?.fullImageView.image = image } else if Utils.isPhone() { self?.fullImage = UIImage() self?.fullImage = image self?.setupImageInScrollView() } self?.imageDownloadProgressView.isHidden = true self?.doneButton.isHidden = false } } sdWebImageManager.loadImage(with: self.flickrPhoto?.bigImageUrl as URL?, options: [], progress: progress, completed: completion) var photoTitle: String = self.flickrPhoto!.title! if photoTitle.isEmpty { photoTitle = FlickrConstants.kTitleNotAvailable } self.commentTextView.text = photoTitle self.commentTextView.textAlignment = .center } func setupImageInScrollView() { self.containerScrollView.minimumZoomScale = 1 self.containerScrollView.zoomScale = 1 self.fullImageView.frame = CGRect(x: 0, y: 0, width: self.fullImage!.size.width, height: self.fullImage!.size.height) self.fullImageView.image = self.fullImage self.containerScrollView.contentSize = self.fullImage!.size // Calculate Min let viewSize: CGSize = self.containerScrollView.bounds.size let xScale: CGFloat = viewSize.width / self.fullImage!.size.width let yScale: CGFloat = viewSize.height / self.fullImage!.size.height let minScale: CGFloat = min(xScale, yScale) self.containerScrollView.minimumZoomScale = min(minScale, 1) self.containerScrollView.zoomScale = self.containerScrollView.minimumZoomScale self.centerScrollViewContent() } func centerScrollViewContent() { let scrollViewSize = self.containerScrollView.bounds.size var imageFrame = self.fullImageView.frame if imageFrame.size.width < scrollViewSize.width { imageFrame.origin.x = (scrollViewSize.width - imageFrame.size.width) / 2.0 } else { imageFrame.origin.x = 0.0 } if imageFrame.size.height < scrollViewSize.height { imageFrame.origin.y = (scrollViewSize.height - imageFrame.size.height) / 2.0 } else { imageFrame.origin.y = 0.0 } self.fullImageView.frame = imageFrame } }
mit
bdcfa7910c08f2f7e1a542dc6bb988ac
41.751412
106
0.638826
5.405
false
false
false
false
brave/browser-ios
Client/Frontend/Browser/ContextMenuHelper.swift
2
3621
/* 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 WebKit import Shared protocol ContextMenuHelperDelegate: class { func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) } class ContextMenuHelper: NSObject, BrowserHelper, UIGestureRecognizerDelegate { fileprivate weak var browser: Browser? weak var delegate: ContextMenuHelperDelegate? fileprivate let gestureRecognizer = UILongPressGestureRecognizer() struct Elements { let link: URL? let image: URL? let folder: [Int]? } /// Clicking an element with VoiceOver fires touchstart, but not touchend, causing the context /// menu to appear when it shouldn't (filed as rdar://22256909). As a workaround, disable the custom /// context menu for VoiceOver users. fileprivate var showCustomContextMenu: Bool { return !UIAccessibilityIsVoiceOverRunning() } required init(browser: Browser) { super.init() self.browser = browser } class func scriptMessageHandlerName() -> String? { return "contextMenuMessageHandler" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if !showCustomContextMenu { return } guard let data = message.body as? [String: AnyObject] else { return } // On sites where <a> elements have child text elements, the text selection delegate can be triggered // when we show a context menu. To prevent this, cancel the text selection delegate if we know the // user is long-pressing a link. if let handled = data["handled"] as? Bool, handled { func blockOtherGestures(_ views: [UIView]) { for view in views { if let gestures = view.gestureRecognizers as [UIGestureRecognizer]! { for gesture in gestures { if gesture is UILongPressGestureRecognizer && gesture != gestureRecognizer { // toggling gets the gesture to ignore this long press gesture.isEnabled = false gesture.isEnabled = true } } } } } blockOtherGestures((browser?.webView?.scrollView.subviews)!) } var linkURL: URL? if let urlString = data["link"] as? String { linkURL = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.URLAllowedCharacterSet())!) } var imageURL: URL? if let urlString = data["image"] as? String { imageURL = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.URLAllowedCharacterSet())!) } if linkURL != nil || imageURL != nil { let elements = Elements(link: linkURL, image: imageURL, folder: nil) delegate?.contextMenuHelper(self, didLongPressElements: elements, gestureRecognizer: gestureRecognizer) } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return showCustomContextMenu } }
mpl-2.0
a75a4dd4dad735d8e518aefe40b275eb
38.791209
174
0.667219
5.702362
false
false
false
false
ChristianKienle/highway
Sources/POSIX/abscwd.swift
1
1805
import Foundation import Darwin import Url public func abscwd() -> Absolute { #if Xcode if let result = _getabsxcodecwd(file: #file) { return Absolute(result) } #endif func error() -> Never { fputs("error: no current directory\n", stderr) exit(EXIT_FAILURE) } let cwd = Darwin.getcwd(nil, Int(PATH_MAX)) if cwd == nil { error() } defer { free(cwd) } guard let path = String(validatingUTF8: cwd!) else { error() } return Absolute(path) } private func _getabsxcodecwd(file: String) -> URL? { // Special case: // Xcode modifies the current working directory. If the user // opens his highway project in Xcode and launches it // he expects the cwd to be the directory that contains // _highway/. // In order to determine the cwd we get #file and move up the // directory tree until we find '_highway/.build' // or more generally, until we find: // HWBundle.directoryName/HWBundle.buildDirectoryName // The cwd then becomes the parent of HWBundle.directoryName. let xcodeCWD = URL(fileURLWithPath: file) let components = xcodeCWD.pathComponents guard let buildDirIndex = components.index(of: ".build") else { return nil } // Check if index before buildDirIndex exists and value is correct let previousIndex = buildDirIndex - 1 guard components.indices.contains(previousIndex) else { return nil } let prevValue = components[previousIndex] let foundDirSequence = prevValue == "_highway" guard foundDirSequence else { return nil } let subComps = components[0..<previousIndex] var result = URL(string: "file://")! subComps.forEach { result = result.appendingPathComponent($0) } return result }
mit
291449c2c93a9e288505caae7db2a72a
32.425926
70
0.657618
4.237089
false
false
false
false
smartystreets/smartystreets-ios-sdk
Sources/SmartyStreets/SmartyErrors.swift
1
720
import Foundation class SmartyErrors { let SSErrorDomain = "SmartyErrorDomain" enum SSErrors: Int { case BatchFullError case FieldNotSetError case ObjectNilError case ObjectInvalidTypeError case NotPositiveIntergerError case JSONSerializationError case MaxRetriesExceededError case BadRequestError = 400 case BadCredentialsError = 401 case PaymentRequiredError = 402 case RequestEntityTooLargeError = 413 case UnprocessableEntityError = 422 case TooManyRequestsError = 429 case InternalServerError = 500 case ServiceUnavailableError = 503 case GatewayTimeoutError = 504 } }
apache-2.0
5a70d4c99ad083854bfeea5871391e68
29
45
0.683333
5.76
false
false
false
false
cburrows/swift-protobuf
Sources/SwiftProtobuf/BinaryEncoder.swift
1
4810
// Sources/SwiftProtobuf/BinaryEncoder.swift - Binary encoding support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Core support for protobuf binary encoding. Note that this is built /// on the general traversal machinery. /// // ----------------------------------------------------------------------------- import Foundation /// Encoder for Binary Protocol Buffer format internal struct BinaryEncoder { private var pointer: UnsafeMutableRawPointer init(forWritingInto pointer: UnsafeMutableRawPointer) { self.pointer = pointer } private mutating func append(_ byte: UInt8) { pointer.storeBytes(of: byte, as: UInt8.self) pointer = pointer.advanced(by: 1) } private mutating func append(contentsOf data: Data) { data.withUnsafeBytes { dataPointer in if let baseAddress = dataPointer.baseAddress, dataPointer.count > 0 { pointer.copyMemory(from: baseAddress, byteCount: dataPointer.count) pointer = pointer.advanced(by: dataPointer.count) } } } @discardableResult private mutating func append(contentsOf bufferPointer: UnsafeRawBufferPointer) -> Int { let count = bufferPointer.count if let baseAddress = bufferPointer.baseAddress, count > 0 { memcpy(pointer, baseAddress, count) } pointer = pointer.advanced(by: count) return count } func distance(pointer: UnsafeMutableRawPointer) -> Int { return pointer.distance(to: self.pointer) } mutating func appendUnknown(data: Data) { append(contentsOf: data) } mutating func startField(fieldNumber: Int, wireFormat: WireFormat) { startField(tag: FieldTag(fieldNumber: fieldNumber, wireFormat: wireFormat)) } mutating func startField(tag: FieldTag) { putVarInt(value: UInt64(tag.rawValue)) } mutating func putVarInt(value: UInt64) { var v = value while v > 127 { append(UInt8(v & 0x7f | 0x80)) v >>= 7 } append(UInt8(v)) } mutating func putVarInt(value: Int64) { putVarInt(value: UInt64(bitPattern: value)) } mutating func putVarInt(value: Int) { putVarInt(value: Int64(value)) } mutating func putZigZagVarInt(value: Int64) { let coded = ZigZag.encoded(value) putVarInt(value: coded) } mutating func putBoolValue(value: Bool) { append(value ? 1 : 0) } mutating func putFixedUInt64(value: UInt64) { var v = value.littleEndian let n = MemoryLayout<UInt64>.size memcpy(pointer, &v, n) pointer = pointer.advanced(by: n) } mutating func putFixedUInt32(value: UInt32) { var v = value.littleEndian let n = MemoryLayout<UInt32>.size memcpy(pointer, &v, n) pointer = pointer.advanced(by: n) } mutating func putFloatValue(value: Float) { let n = MemoryLayout<Float>.size var v = value var nativeBytes: UInt32 = 0 memcpy(&nativeBytes, &v, n) var littleEndianBytes = nativeBytes.littleEndian memcpy(pointer, &littleEndianBytes, n) pointer = pointer.advanced(by: n) } mutating func putDoubleValue(value: Double) { let n = MemoryLayout<Double>.size var v = value var nativeBytes: UInt64 = 0 memcpy(&nativeBytes, &v, n) var littleEndianBytes = nativeBytes.littleEndian memcpy(pointer, &littleEndianBytes, n) pointer = pointer.advanced(by: n) } // Write a string field, including the leading index/tag value. mutating func putStringValue(value: String) { let utf8 = value.utf8 // If the String does not support an internal representation in a form // of contiguous storage, body is not called and nil is returned. let isAvailable = utf8.withContiguousStorageIfAvailable { (body: UnsafeBufferPointer<UInt8>) -> Int in putVarInt(value: body.count) return append(contentsOf: UnsafeRawBufferPointer(body)) } if isAvailable == nil { let count = utf8.count putVarInt(value: count) for b in utf8 { pointer.storeBytes(of: b, as: UInt8.self) pointer = pointer.advanced(by: 1) } } } mutating func putBytesValue(value: Data) { putVarInt(value: value.count) append(contentsOf: value) } }
apache-2.0
b3bbca8d14c21d3f51f3ab217c4127a0
31.281879
110
0.610811
4.559242
false
false
false
false
debugsquad/nubecero
nubecero/View/AdminServer/VAdminServerCellFroob.swift
1
3509
import UIKit class VAdminServerCellFroob:VAdminServerCell, UITextFieldDelegate { private weak var textField:UITextField! private weak var modelFroob:MAdminServerItemFroob? override init(frame:CGRect) { super.init(frame:frame) let label:UILabel = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.isUserInteractionEnabled = false label.font = UIFont.bold(size:13) label.textColor = UIColor(white:0.75, alpha:1) label.text = NSLocalizedString("VAdminServerCellFroob_labelTitle", comment:"") let textField:UITextField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.clipsToBounds = true textField.backgroundColor = UIColor.clear textField.borderStyle = UITextBorderStyle.none textField.font = UIFont.medium(size:19) textField.textColor = UIColor.black textField.tintColor = UIColor.black textField.delegate = self textField.returnKeyType = UIReturnKeyType.done textField.keyboardAppearance = UIKeyboardAppearance.light textField.autocorrectionType = UITextAutocorrectionType.no textField.spellCheckingType = UITextSpellCheckingType.no textField.autocapitalizationType = UITextAutocapitalizationType.none textField.clearButtonMode = UITextFieldViewMode.never textField.keyboardType = UIKeyboardType.numbersAndPunctuation textField.placeholder = NSLocalizedString("VAdminServerCellFroob_placeholder", comment:"") self.textField = textField addSubview(label) addSubview(textField) let views:[String:UIView] = [ "label":label, "textField":textField] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-10-[label(90)]-0-[textField]-5-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[textField]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[label]-0-|", options:[], metrics:metrics, views:views)) } required init?(coder:NSCoder) { fatalError() } override func config(model:MAdminServerItem) { modelFroob = model as? MAdminServerItemFroob print() } //MARK: private private func print() { guard let space:Int = modelFroob?.space else { return } textField.text = "\(space)" } //MARK: textField delegate func textFieldDidEndEditing(_ textField:UITextField) { guard let editedText:String = textField.text, let amountInt:Int = Int(editedText) else { print() return } modelFroob?.newSpace(space:amountInt) print() } func textFieldShouldReturn(_ textField:UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
b7897d2b68c2ff124926c03009763ac5
28.737288
98
0.601881
5.705691
false
false
false
false
1457792186/JWSwift
熊猫TV2/XMTV/Classes/Main/Controller/BaseAllLivingVC.swift
2
3049
// // BaseAllLivingVC.swift // XMTV // // Created by Mac on 2017/1/18. // Copyright © 2017年 Mac. All rights reserved. // import UIKit class BaseAllLivingVC: BaseVC { var baseVM: BaseVM! lazy var collectionView : UICollectionView = {[unowned self] in let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin, bottom: 0, right: kItemMargin) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: NormalCellID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // MARK: - extension BaseAllLivingVC { override func setupUI() { contentView = collectionView view.addSubview(collectionView) super.setupUI() } } // MARK: - loadData extension BaseAllLivingVC { func loadData() {} } // MARK: - UICollectionView代理数据源方法 extension BaseAllLivingVC : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if baseVM.anchorGroups.count > 0 { return baseVM.anchorGroups[section].anchors.count } else { return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NormalCellID, for: indexPath) as! CollectionNormalCell cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] return cell } } extension BaseAllLivingVC : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] // anchor.isVertical == 0 ? pushNormalRoomVc(anchor) : presentShowRoomVc(anchor) } // private func presentShowRoomVc(_ anchor : AnchorModel) { // let showVc = ShowRoomVC() // showVc.anchor = anchor // present(showVc, animated: true, completion: nil) // } // // private func pushNormalRoomVc(_ anchor : AnchorModel) { // let normalVc = NormalRoomVC() // normalVc.anchor = anchor // navigationController?.pushViewController(normalVc, animated: true) // } }
apache-2.0
ce96a154881942654f68c259e8a6638b
32.688889
129
0.666227
5.130288
false
false
false
false
tardieu/swift
benchmark/single-source/Fibonacci.swift
10
1219
//===--- Fibonacci.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils func fibonacci(_ n: Int) -> Int { if (n < 2) { return 1 } return fibonacci(n - 2) + fibonacci(n - 1) } @inline(never) func Fibonacci(_ n: Int) -> Int { // This if prevents optimizer from computing return value of Fibonacci(32) // at compile time. if False() { return 0 } if (n < 2) { return 1 } return fibonacci(n - 2) + fibonacci(n - 1) } @inline(never) public func run_Fibonacci(_ N: Int) { let n = 32 let ref_result = 3524578 var result = 0 for _ in 1...N { result = Fibonacci(n) if result != ref_result { break } } CheckResults(result == ref_result, "Incorrect results in Fibonacci: \(result) != \(ref_result)") }
apache-2.0
6e9813d69cc1e88d60332093a1bbdb30
27.348837
80
0.5726
3.944984
false
false
false
false
tardieu/swift
test/Parse/switch.swift
1
9154
// RUN: %target-typecheck-verify-swift // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int), y: (Int,Int)) -> Bool { return true } func parseError1(x: Int) { switch func {} // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} expected-error {{expected identifier in function declaration}} expected-error {{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{15-15=do }} } func parseError2(x: Int) { switch x // expected-error {{expected '{' after 'switch' subject expression}} } func parseError3(x: Int) { switch x { case // expected-error {{expected pattern}} expected-error {{expected ':' after 'case'}} } } func parseError4(x: Int) { switch x { case var z where // expected-error {{expected expression for 'where' guard of 'case'}} expected-error {{expected ':' after 'case'}} } } func parseError5(x: Int) { switch x { case let z // expected-error {{expected ':' after 'case'}} expected-warning {{immutable value 'z' was never used}} {{12-13=_}} } } func parseError6(x: Int) { switch x { default // expected-error {{expected ':' after 'default'}} } } var x: Int switch x {} // expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} switch x { case 0: x = 0 // Multiple patterns per case case 1, 2, 3: x = 0 // 'where' guard case _ where x % 2 == 0: x = 1 x = 2 x = 3 case _ where x % 2 == 0, _ where x % 3 == 0: x = 1 case 10, _ where x % 3 == 0: x = 1 case _ where x % 2 == 0, 20: x = 1 case var y where y % 2 == 0: x = y + 1 case _ where 0: // expected-error {{'Int' is not convertible to 'Bool'}} x = 0 default: x = 1 } // Multiple cases per case block switch x { case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} default: x = 0 } switch x { case 0: x = 0 case 1: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: x = 0 default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} } switch x { case 0: ; // expected-error {{';' statements are not allowed}} {{3-5=}} case 1: x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} default: x = 0 case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case 1: x = 0 } switch x { default: x = 0 default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} x = 2 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}} x = 0 } switch x { case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: x = 0 case 1: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} var y = 0 default: // expected-error{{'default' label can only appear inside a 'switch' statement}} var z = 1 fallthrough // expected-error{{'fallthrough' is only allowed inside a switch}} switch x { case 0: fallthrough case 1: fallthrough default: fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}} } // Fallthrough can transfer control anywhere within a case and can appear // multiple times in the same case. switch x { case 0: if true { fallthrough } if false { fallthrough } x += 1 default: x += 1 } // Cases cannot contain 'var' bindings if there are multiple matching patterns // attached to a block. They may however contain other non-binding patterns. var t = (1, 2) switch t { case (var a, 2), (1, _): // expected-error {{'a' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (_, 2), (var a, _): // expected-error {{'a' must be bound in every pattern}} () case (var a, 2), (1, var b): // expected-error {{'a' must be bound in every pattern}} expected-error {{'b' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} case (1, _): () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} case (1, var b): // expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} () case (1, let b): // let bindings expected-warning {{immutable value 'b' was never used; consider replacing with '_' or removing it}} () case (_, 2), (let a, _): // expected-error {{'a' must be bound in every pattern}} () // OK case (_, 2), (1, _): () case (_, var a), (_, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, var b), (var b, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, _): () } func patternVarUsedInAnotherPattern(x: Int) { switch x { case let a, // expected-error {{'a' must be bound in every pattern}} a: break } } // Fallthroughs can't transfer control into a case label with bindings. switch t { case (1, 2): fallthrough // expected-error {{'fallthrough' cannot transfer control to a case label that declares variables}} case (var a, var b): // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} t = (b, a) } func test_label(x : Int) { Gronk: switch x { case 42: return } } func enumElementSyntaxOnTuple() { switch (1, 1) { case .Bar: // expected-error {{enum case 'Bar' not found in type '(Int, Int)'}} break default: break } } // sr-176 enum Whatever { case Thing } func f0(values: [Whatever]) { // expected-note {{did you mean 'values'?}} switch value { // expected-error {{use of unresolved identifier 'value'}} case .Thing: // Ok. Don't emit diagnostics about enum case not found in type <<error type>>. break } } // sr-720 enum Whichever { case Thing static let title = "title" static let alias: Whichever = .Thing } func f1(x: String, y: Whichever) { switch x { case Whichever.title: // Ok. Don't emit diagnostics for static member of enum. break case Whichever.buzz: // expected-error {{type 'Whichever' has no member 'buzz'}} break case Whichever.alias: // expected-error {{expression pattern of type 'Whichever' cannot match values of type 'String'}} break default: break } switch y { case Whichever.Thing: // Ok. break case Whichever.alias: // Ok. Don't emit diagnostics for static member of enum. break case Whichever.title: // expected-error {{expression pattern of type 'String' cannot match values of type 'Whichever'}} break } }
apache-2.0
0304706492b792ffc6fa9385d84353c7
28.720779
326
0.654905
3.526194
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/BusinessLayer/Core/Services/Mnemonic/Keys/Base58.swift
1
1311
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import Foundation struct Base58 { static let alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" static func encode(_ bytes: Data) -> String { var bytes = bytes var zerosCount = 0 var length = 0 for b in bytes { if b != 0 { break } zerosCount += 1 } bytes.removeFirst(zerosCount) let size = bytes.count * 138 / 100 + 1 var base58: [UInt8] = Array(repeating: 0, count: size) for b in bytes { var carry = Int(b) var i = 0 for j in 0...base58.count - 1 where carry != 0 || i < length { carry += 256 * Int(base58[base58.count - j - 1]) base58[base58.count - j - 1] = UInt8(carry % 58) carry /= 58 i += 1 } assert(carry == 0) length = i } // skip leading zeros var zerosToRemove = 0 var str = "" for b in base58 { if b != 0 { break } zerosToRemove += 1 } base58.removeFirst(zerosToRemove) while 0 < zerosCount { str = "\(str)1" zerosCount -= 1 } for b in base58 { str = "\(str)\(alphabet[String.Index(encodedOffset: Int(b))])" } return str } }
gpl-3.0
84a0eba1c29da18141f560c0c838dee2
20.47541
84
0.540458
3.797101
false
false
false
false
dn-m/Collections
CollectionsPerformanceTests/StackPerformanceTests.swift
1
1385
// // StackPerformanceTests.swift // Collections // // Created by James Bean on 7/11/17. // // import XCTest import Collections class StackPerformanceTests: XCTestCase { func randomStack(count: Int) -> Stack<Int> { assert(count > 0) return Stack((0..<count).map { _ in .random }) } // Expected complexity: O(1) func testStartIndexPerformanceMillionInts() { let stack = randomStack(count: 1_000_000) measure { let _ = stack.startIndex } } // Expected complexity: O(1) func testEndIndexPerformanceMillionInts() { let stack = randomStack(count: 1_000_000) measure { let _ = stack.endIndex } } // Expected complexity: O(1) func testCountPerformanceMillionInts() { let stack = randomStack(count: 1_000_000) measure { let _ = stack.count } } // Expected complexity: O(1) func testPushPerformanceMillionInts() { var stack = randomStack(count: 1_000_000) measure { stack.push(.random) } } // Expected complexity: O(1) func testPopPerformanceMillionInts() { var stack = randomStack(count: 1_000_000) measure { _ = stack.pop() } } // Expected complexity: O(1) func testSubscriptGetterPerformanceMillionInts() { let stack = randomStack(count: 1_000_000) measure { let _ = stack[12_345] } } }
mit
4ca36c688c5721763cee514251a40ab5
24.648148
54
0.616606
3.857939
false
true
false
false
xuech/OMS-WH
OMS-WH/Classes/OrderDetail/Model/EventLists.swift
1
1556
// // OMSEventLists.swift // OMSOwner // // Created by gwy on 2017/5/3. // Copyright © 2017年 medlog. All rights reserved. // import UIKit class EventLists: CommonPaseModel { var eventCode:String? var eventReasonDesc:String? var externalRemark1:String? // var sOEventID: NSNumber = 0 var eventOpDate:String?{ didSet{ if let date = eventOpDate { eventOperationDate = date.replacingOccurrences(of: ".0", with: "") } } } var eventOperationDate : String? var attachmentList:[[String:AnyObject]]?{ didSet{ if attachmentList?.count == 0 { return } for dict in attachmentList! { if let urlString = dict["attachmentDir"] as? String { if let url = URL(string: urlString) { if urlString.hasSuffix(".mp3"){ storedMp3URLs = url } if urlString.hasSuffix(".jpg") || urlString.hasSuffix(".png") || urlString.hasSuffix(".JPG") || urlString.hasSuffix(".PNG"){ storedPictureURLs.append(url) } } if let des = dict["attachmentDesc"] as? String { storedURLsDes.append(des) } } } } } var storedPictureURLs = [URL]() var storedMp3URLs : URL? var storedURLsDes = [String]() }
mit
8a0ea793d833832b005a97da661706a6
24.459016
148
0.488088
4.734756
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0113.xcplaygroundpage/Contents.swift
2
5046
/*: # Add integral rounding functions to FloatingPoint * Proposal: [SE-0113](0113-rounding-functions-on-floatingpoint.md) * Author: [Karl Wagner](https://github.com/karwa) * Review Manager: [Chris Lattner](http://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-July/000217.html) * Bug: [SR-2010](https://bugs.swift.org/browse/SR-2010) ## Introduction, Motivation The standard library lacks equivalents to the `floor()` and `ceil()` functions found in the standard libraries of most other languages. Currently, we need to import `Darwin` or `Glibc` in order to access the C standard library versions. In general, rounding of floating-point numbers for predictable conversion in to integers is something we should provide natively. Swift-evolution initial discussion thread: [\[Proposal\] Add floor() and ceiling() functions to FloatingPoint ](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160620/022146.html) ## Proposed Solution The proposed rounding API consists of a `FloatingPointRoundingRule` enum and new `round` and `rounded` methods on `FloatingPoint` ```swift /// Describes a rule for rounding a floating-point number. public enum FloatingPointRoundingRule { /// The result is the closest allowed value; if two values are equally close, /// the one with greater magnitude is chosen. Also known as "schoolbook /// rounding". case toNearestOrAwayFromZero /// The result is the closest allowed value; if two values are equally close, /// the even one is chosen. Also known as "bankers rounding". case toNearestOrEven /// The result is the closest allowed value that is greater than or equal /// to the source. case up /// The result is the closest allowed value that is less than or equal to /// the source. case down /// The result is the closest allowed value whose magnitude is less than or /// equal to that of the source. case towardZero /// The result is the closest allowed value whose magnitude is greater than /// or equal to that of the source. case awayFromZero } protocol FloatingPoint { ... /// Returns a rounded representation of `self`, according to the specified rounding rule. func rounded(_ rule: FloatingPointRoundingRule) -> Self /// Mutating form of `rounded` mutating func round(_ rule: FloatingPointRoundingRule) } extension FloatingPoint { ... /// Returns `self` rounded to the closest integral value. If `self` is /// exactly halfway between two integers (e.g. 1.5), the integral value /// with greater magnitude (2.0 in this example) is returned. public func rounded() -> Self { return rounded(.toNearestOrAwayFromZero) } /// Rounds `self` to the closest integral value. If `self` is exactly /// halfway between two integers (e.g. 1.5), the integral value with /// greater magnitude is selected. public mutating func round() { round(.toNearestOrAwayFromZero) } } ``` Calls such as `rounded(.up)` or `rounded(.down)` are equivalent to C standard library `ceil()` and `floor()` functions. - `(4.4).rounded() == 4.0` - `(4.5).rounded() == 5.0` - `(4.0).rounded(.up) == 4.0` - `(4.0).rounded(.down) == 4.0` Note: the rounding rules in the `FloatingPointRoundingRule` enum correspond to those in IEEE 754, with the exception of `.awayFromZero`. ## Impact on existing code This change is additive, although we may consider suppressing the imported, global-level C functions, or perhaps automatically migrating them to the new instance-method calls. ## Alternatives considered * `floor()` and `ceiling()`. The mailing list discussion indicated more nuanced forms of rounding were desired, and that it would be nice to abandon these technical names for what is a pretty common operation. * `floor()` and `ceil()` or `ceiling()` are [mathematical terms of art](http://mathworld.wolfram.com/CeilingFunction.html). But most people who want to round a floating point are not mathematicians. * `nextIntegralUp()` and `nextIntegralDown()` are more descriptive, and perhaps a better fit with the rest of the `FloatingPoint` API, but possibly misleading as `(4.0).nextIntegralUp() == 4.0` ## Changes introduced in implementation * `RoundingRule` was renamed `FloatingPointRoundingRule`, based on a suggestion from the standard library team. We may want to introduce rounding operations that operate on other types in the future, and they may not want the same set of rules. Also, this type name will be very rarely used, so a long precise typename doesn't add burden. * Added `.awayFromZero`, which is trivial to implement and was requested by several people during the review period. * Removed default rounding direction from protocol requirements (the language doesn't support that). The default rounding-direction operations were moved to an extension instead. ---------- [Previous](@previous) | [Next](@next) */
mit
b4fb04a2714155fa497ef38d264c1c37
44.459459
340
0.729092
4.298126
false
false
false
false
cocoaheadsru/server
Sources/App/Models/Client/Client.swift
1
1094
import Vapor import FluentProvider import HTTP // sourcery: AutoModelGeneratable // sourcery: fromJSON, toJSON, Preparation, Updateable, ResponseRepresentable, Timestampable final class Client: Model { let storage = Storage() var userId: Identifier? var pushToken: String init(pushToken: String, userId: Identifier?) { self.pushToken = pushToken self.userId = userId } // sourcery:inline:auto:Client.AutoModelGeneratable init(row: Row) throws { userId = try? row.get(Keys.userId) pushToken = try row.get(Keys.pushToken) } func makeRow() throws -> Row { var row = Row() try? row.set(Keys.userId, userId) try row.set(Keys.pushToken, pushToken) return row } // sourcery:end } extension Client { convenience init(request: Request) throws { self.init( pushToken: try request.json!.get(Keys.pushToken), userId: try request.user().id ) } static func returnIfExists(request: Request) throws -> Client? { return try Client.makeQuery() .filter(Keys.userId, try request.user().id) .first() } }
mit
2aa38b0716708d96d828d2a2d1e8ca13
21.791667
92
0.680987
3.879433
false
false
false
false
DrabWeb/Komikan
Komikan/Komikan/KMMangaListController.swift
1
15265
// // KMMangaListController.swift // Komikan // // Created by Seth on 2016-02-29. // import Cocoa /// Controls the manga list. Not nearly as powerful as KMMangaGridController, as it only controls filling in the table view from the grid controller class KMMangaListController: NSObject { /// A reference to the manga grid controller @IBOutlet weak var mangaGridController: KMMangaGridController! /// The main view controller @IBOutlet weak var viewController: ViewController! /// The table view this list controller is filling in @IBOutlet weak var mangaListTableView: KMMangaListTableView! /// When we click on mangaListTableView... @IBAction func mangaListTableViewClicked(_ sender: AnyObject) { // If we double clicked... if(NSApplication.shared().currentEvent?.clickCount == 2) { // Open the selected manga openManga(); } } /// The opened manga of the list var openedManga : [KMManga] = []; /// A little bool to stop the manga list from resorting at launch, otherwise it messes stuff up var firstSortChange : Bool = true; // The view controller we will load for the edit/open manga popover var editMangaViewController: KMEditMangaViewController? /// Returns the list of selected manga from the table view func selectedMangaList() -> [KMManga] { /// The list of selected manga we will return at the end var manga : [KMManga] = []; // For every selected row... for(_, currentIndex) in self.mangaListTableView.selectedRowIndexes.enumerated() { // Add the manga at the current index to the manga list manga.append(((self.mangaGridController.arrayController.arrangedObjects as? [KMMangaGridItem])![currentIndex].manga)); } // Return the manga list return manga; } /// Returns the single selected manga from the table view func selectedManga() -> KMManga { // Get the manga at the selected row in the array controller return ((self.mangaGridController.arrayController.arrangedObjects as? [KMMangaGridItem])![mangaListTableView.selectedRow].manga); } /// Have we already subscribed to the popover and readers notifications? var alreadySubscribed : Bool = false; /// Is the edit popover open? var editPopoverOpen : Bool = false; func openPopover(_ hidden : Bool, manga : KMManga) { // Hide the thumbnail window viewController.thumbnailImageHoverController.hide(); // Get the main storyboard let storyboard = NSStoryboard(name: "Main", bundle: nil); // Instanstiate the view controller for the edit/open manga view controller editMangaViewController = storyboard.instantiateController(withIdentifier: "editMangaViewController") as? KMEditMangaViewController; // If we said to hide the popover... if(hidden) { // Only load the view, but not display editMangaViewController?.loadView(); } else { // Show the popover editMangaViewController!.presentViewController(editMangaViewController!, asPopoverRelativeTo: viewController.backgroundVisualEffectView.bounds, of: viewController.backgroundVisualEffectView, preferredEdge: NSRectEdge.maxY, behavior: NSPopoverBehavior.semitransient); // Set editPopoverOpen to true editPopoverOpen = true; } // Add the selected manga to the list of opened manga openedManga.append(manga); // Say that we want to edit or open this manga NotificationCenter.default.post(name: Notification.Name(rawValue: "KMMangaGridCollectionItem.Editing"), object: manga); // If we havent already subscribed to the notifications... if(!alreadySubscribed) { // Subscribe to the popovers saved function NotificationCenter.default.addObserver(self, selector: #selector(KMMangaListController.saveMangaFromPopover(_:)), name:NSNotification.Name(rawValue: "KMEditMangaViewController.Saving"), object: nil); // Subscribe to the readers update percent finished function NotificationCenter.default.addObserver(self, selector: #selector(KMMangaListController.updatePercentFinished(_:)), name:NSNotification.Name(rawValue: "KMMangaGridCollectionItem.UpdatePercentFinished"), object: nil); // Say we subscribed alreadySubscribed = true; } } /// Opens all the selected manga func openManga() { // For every selected manga... for(_, currentSelectedManga) in selectedMangaList().enumerated() { print("KMMangaListController: Opening \"" + currentSelectedManga.title + "\""); // Open the popover openPopover(true, manga: currentSelectedManga); // Open the current manga (NSApplication.shared().delegate as! AppDelegate).openManga(currentSelectedManga, page: currentSelectedManga.currentPage); } } func saveMangaFromPopover(_ notification : Notification) { // For every manga in the opened manga... for(_, currentManga) in openedManga.enumerated() { // If the UUID matches... if(currentManga.uuid == (notification.object as? KMManga)!.uuid) { print("KMMangaListController: UUID matched for \"" + currentManga.title + "\""); // Print to the log the manga we received print("KMMangaListController: Saving manga \"" + currentManga.title + "\""); // For every manga inside the opened manga... for(_, _) in openedManga.enumerated() { // For every item in the array controller... for(_, currentMangaGridItem) in (self.mangaGridController.arrayController.arrangedObjects as? [KMMangaGridItem])!.enumerated() { // If the current grid item's manga's UUID is the same as the notification's manga's UUID... if(currentMangaGridItem.manga.uuid == (notification.object as? KMManga)!.uuid) { // Set the current manga to the notifications manga currentMangaGridItem.changeManga((notification.object as? KMManga)!); } } } // Store the current scroll position and selection mangaGridController.storeCurrentSelection(); // Reload the view to match its contents NotificationCenter.default.post(name: Notification.Name(rawValue: "ViewController.UpdateMangaGrid"), object: nil); // Resort the grid mangaGridController.resort(); // Redo the search, if there was one mangaGridController.redoSearch(); // Restore the scroll position and selection mangaGridController.restoreSelection(); } } } func updatePercentFinished(_ notification : Notification) { print("KMMangaListController: Updating percent..."); // For every manga in the opened manga... for(_, currentManga) in openedManga.enumerated() { // If the UUID matches... if(currentManga.uuid == (notification.object as? KMManga)!.uuid) { print("KMMangaListController: UUID matched for \"" + currentManga.title + "\""); // Update the passed mangas percent finished (notification.object as? KMManga)!.updatePercent(); // Set the current manga's percent done to the passed mangas percent done currentManga.percentFinished = ((notification.object as? KMManga)!.percentFinished); mangaListTableView.reloadData(); } } } /// Sets editPopoverOpen to false func sayEditPopoverIsClosed() { // Set editPopoverOpen to false editPopoverOpen = false; } override func awakeFromNib() { // Set the manga list controller's table view reference mangaListTableView.mangaListController = self; // Subscribe to the edit popover's closing notification NotificationCenter.default.addObserver(self, selector: #selector(KMMangaListController.sayEditPopoverIsClosed), name: NSNotification.Name(rawValue: "KMEditMangaViewController.Closing"), object: nil); } } extension KMMangaListController : NSTableViewDataSource { func tableViewSelectionIsChanging(_ notification: Notification) { // If the selected row isnt blank and the edit popover is open... if(self.mangaListTableView.selectedRowIndexes.first != -1 && self.editPopoverOpen) { // Dismiss the edit popover self.editMangaViewController?.dismiss(self); // Show the edit popover with the newly selected manga self.openPopover(false, manga: self.selectedManga()); } } func tableView(_ tableView: NSTableView, sizeToFitWidthOfColumn column: Int) -> CGFloat { /// The width we will set the cell to at the end var width : CGFloat = 0; // For every item in the table view's rows... for i in 0...(tableView.numberOfRows - 1) { /// The cell view at the current column let view = tableView.view(atColumn: column, row: i, makeIfNecessary: true) as! NSTableCellView; /// The size of this cell's text let size = view.textField!.attributedStringValue.size(); // Set width to the to the greatest number in between width and the label's width width = max(width, size.width); } // Return the width with 20px of padding return width + 20; } func numberOfRows(in aTableView: NSTableView) -> Int { // Return the number of items in the manga grid array controller return (self.mangaGridController.arrayController.arrangedObjects as? [AnyObject])!.count; } func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { // If this isnt the first time this was called... if(!firstSortChange) { // Set the sort descriptors of the manga array controller to the sort descriptors to use self.mangaGridController.arrayController.sortDescriptors = tableView.sortDescriptors; // Rearrange the array controller self.mangaGridController.arrayController.rearrangeObjects(); } // Say any more times after this this is called are not the first firstSortChange = false; } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { /// The cell view it is asking us about for the data let cellView : NSTableCellView = tableView.make(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView; // If the row we are trying to get an item from is in range of the array controller... if(row < (self.mangaGridController.arrayController.arrangedObjects as? [KMMangaGridItem])!.count) { /// This manga list items data let searchListItemData = (self.mangaGridController.arrayController.arrangedObjects as? [KMMangaGridItem])![row]; // If the column is the Title Column... if(tableColumn!.identifier == "Title Column") { // Set the text of this cell to be the title of this manga cellView.textField!.stringValue = searchListItemData.manga.title; // Set the cells thumbnail image (cellView as! KMMangaListTableCellView).thumbnailImage = searchListItemData.manga.coverImage; // Set the cells thumbnail hover controller (cellView as! KMMangaListTableCellView).thumbnailImageHoverController = viewController.thumbnailImageHoverController; // Set the cells manga list controller (cellView as! KMMangaListTableCellView).mangaListController = self; // Return the modified cell view return cellView; } // If the column is the Series Column... else if(tableColumn!.identifier == "Series Column") { // Set the text of this cell to be the series of this manga cellView.textField!.stringValue = searchListItemData.manga.series; // Return the modified cell view return cellView; } // If the column is the Author Column... else if(tableColumn!.identifier == "Writer Column") { // Set the text of this cell to be the author of this manga cellView.textField!.stringValue = searchListItemData.manga.writer; // Return the modified cell view return cellView; } // If the column is the Artist Column... else if(tableColumn!.identifier == "Artist Column") { // Set the text of this cell to be the artist of this manga cellView.textField!.stringValue = searchListItemData.manga.artist; // Return the modified cell view return cellView; } // If the column is the Percent Column... else if(tableColumn!.identifier == "Percent Column") { // Set the text of this cell to be the percent finished of this manga with a % on the end cellView.textField!.stringValue = String(searchListItemData.manga.percentFinished) + "%"; // Return the modified cell view return cellView; } // If the column is the Favourite Column... else if(tableColumn!.identifier == "Favourite Column") { // If this item is favourite... if(searchListItemData.manga.favourite) { // Set the text of this cell to be a filled star cellView.textField!.stringValue = "★"; } else { // Set the text of this cell to be an empty star cellView.textField!.stringValue = "☆"; } // Return the modified cell view return cellView; } } // Return the unmodified cell view, we didnt need to do anything to this one return cellView; } } extension KMMangaListController : NSTableViewDelegate { }
gpl-3.0
6ef5bc504017ef2b8ff8aa02d2ae483d
44.966867
278
0.605661
5.159229
false
false
false
false
zenghaojim33/BeautifulShop
BeautifulShop/BeautifulShop/Siren/BWMSirenManager.swift
1
2583
// // SirenManager.swift // SwiftJSONTest // // Created by 伟明 毕 on 15/5/10. // Copyright (c) 2015年 Bi Weiming. All rights reserved. // import Foundation /*** 版本检测器 */ @objc class BWMSirenManager : NSObject { // 需要检测的Apple Store APP ID private static let AppID:String = "914430432" // 对应的BundleID,如果BundleID不一致,不会调用版本检测器 private static let BundleID:String = "com.AppStore.BeautifulShop.BeautifulShop" private class func p_defaultSiren() -> Siren? { var bundleID:NSString = NSBundle.mainBundle().bundleIdentifier! if (bundleID.isEqualToString(BundleID)) { let theSiren:Siren! = Siren.sharedInstance theSiren.appID = self.AppID theSiren.alertType = SirenAlertType.Option; return theSiren } else { return nil } } /** 调用版本检测 :param: checkType 检测频率类型 :param: delegate 事件回调delegate */ class func run(versionCheckType checkType:SirenVersionCheckType, withDelegate delegate:SirenDelegate?) { if(self.p_defaultSiren() != nil) { let theSiren:Siren = self.p_defaultSiren()! theSiren.checkVersion(checkType) theSiren.delegate = delegate } } /** 获取当前版本 :returns: 返回当前版本字符串 */ class func currentVersion() -> NSString? { var infoDict:NSDictionary = NSBundle.mainBundle().infoDictionary as NSDictionary! let version:NSString? = infoDict.objectForKey("CFBundleShortVersionString") as? NSString return version } /** 获取最新版本 :returns: 返回最新版本字符串 */ class func newVersion() -> NSString? { let url:NSURL = NSURL(string: "http://itunes.apple.com/lookup?id=\(self.AppID)")! if let data:NSData? = NSData(contentsOfURL: url) { let dict:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary if (dict["results"]?.count > 0) { let version:NSString? = dict["results"]?[0]?["version"] as? NSString if (version == nil) { return "1.0.0" } else { return version } } else { return nil } } else { return nil } } private override init() {} }
apache-2.0
c0df2447aaed492b776d08e28fa09c49
28.938272
159
0.58433
4.425182
false
false
false
false
stephentyrone/swift
test/IRGen/sanitize_coverage.swift
1
2327
// REQUIRES: asan_runtime // RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=func %s | %FileCheck %s -check-prefix=SANCOV // RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=bb %s | %FileCheck %s -check-prefix=SANCOV // RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge %s | %FileCheck %s -check-prefix=SANCOV // RUN: %target-swift-frontend -emit-ir -sanitize=fuzzer %s | %FileCheck %s -check-prefix=SANCOV // RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge,trace-cmp %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_TRACE_CMP // RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge,trace-bb %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_TRACE_BB // RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge,indirect-calls %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_INDIRECT_CALLS // RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge,8bit-counters %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_8BIT_COUNTERS // RUN: %target-swift-frontend -emit-ir -sanitize=fuzzer %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_TRACE_CMP #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) import Glibc #elseif os(Windows) import MSVCRT #else #error("Unsupported platform") #endif // FIXME: We should have a reliable way of triggering an indirect call in the // LLVM IR generated from this code. func test() { // Use random numbers so the compiler can't constant fold #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) let x = arc4random() let y = arc4random() #else let x = rand() let y = rand() #endif // Comparison is to trigger insertion of __sanitizer_cov_trace_cmp let z = x == y print("\(z)") } test() // FIXME: We need a way to distinguish the different types of coverage instrumentation // that isn't really fragile. For now just check there's at least one call to the function // used to increment coverage count at a particular PC. // SANCOV_TRACE_CMP: call void @__sanitizer_cov_trace_cmp // SANCOV: call void @__sanitizer_cov
apache-2.0
ae1f70c573973a4a27b3d84258b931fb
50.711111
172
0.72153
3.144595
false
false
false
false
wfleming/pico-block
pblockLib/Async.swift
1
10035
// // Async.swift // https://github.com/duemunk/Async // // Created by Tobias DM on 15/07/14. // // OS X 10.10+ and iOS 8.0+ // Only use with ARC // // The MIT License (MIT) // Copyright (c) 2014 Tobias Due Munk // // 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 // MARK: - DSL for GCD queues private class GCD { /* dispatch_get_queue() */ class func mainQueue() -> dispatch_queue_t { return dispatch_get_main_queue() // Don't ever use dispatch_get_global_queue(qos_class_main(), 0) re https://gist.github.com/duemunk/34babc7ca8150ff81844 } class func userInteractiveQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0) } class func userInitiatedQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) } class func utilityQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) } class func backgroundQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) } } // MARK: - Async – Struct public struct Async { private let block: dispatch_block_t private init(_ block: dispatch_block_t) { self.block = block } } // MARK: - Async – Static methods extension Async { /* async */ public static func main(after after: Double? = nil, block: dispatch_block_t) -> Async { return Async.async(after, block: block, queue: GCD.mainQueue()) } public static func userInteractive(after after: Double? = nil, block: dispatch_block_t) -> Async { return Async.async(after, block: block, queue: GCD.userInteractiveQueue()) } public static func userInitiated(after after: Double? = nil, block: dispatch_block_t) -> Async { return Async.async(after, block: block, queue: GCD.userInitiatedQueue()) } public static func utility(after after: Double? = nil, block: dispatch_block_t) -> Async { return Async.async(after, block: block, queue: GCD.utilityQueue()) } public static func background(after after: Double? = nil, block: dispatch_block_t) -> Async { return Async.async(after, block: block, queue: GCD.backgroundQueue()) } public static func customQueue(queue: dispatch_queue_t, after: Double? = nil, block: dispatch_block_t) -> Async { return Async.async(after, block: block, queue: queue) } /* Convenience */ private static func async(seconds: Double? = nil, block chainingBlock: dispatch_block_t, queue: dispatch_queue_t) -> Async { if let seconds = seconds { return asyncAfter(seconds, block: chainingBlock, queue: queue) } return asyncNow(chainingBlock, queue: queue) } /* dispatch_async() */ private static func asyncNow(block: dispatch_block_t, queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see matching regular Async methods) // Create block with the "inherit" type let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) // Add block to queue dispatch_async(queue, _block) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_block) } /* dispatch_after() */ private static func asyncAfter(seconds: Double, block: dispatch_block_t, queue: dispatch_queue_t) -> Async { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) return at(time, block: block, queue: queue) } private static func at(time: dispatch_time_t, block: dispatch_block_t, queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) dispatch_after(time, queue, _block) return Async(_block) } } // MARK: - Async – Regualar methods matching static ones extension Async { /* chain */ public func main(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async { return chain(after, block: chainingBlock, queue: GCD.mainQueue()) } public func userInteractive(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async { return chain(after, block: chainingBlock, queue: GCD.userInteractiveQueue()) } public func userInitiated(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async { return chain(after, block: chainingBlock, queue: GCD.userInitiatedQueue()) } public func utility(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async { return chain(after, block: chainingBlock, queue: GCD.utilityQueue()) } public func background(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async { return chain(after, block: chainingBlock, queue: GCD.backgroundQueue()) } public func customQueue(queue: dispatch_queue_t, after: Double? = nil, chainingBlock: dispatch_block_t) -> Async { return chain(after, block: chainingBlock, queue: queue) } /* cancel */ public func cancel() { dispatch_block_cancel(block) } /* wait */ /// If optional parameter forSeconds is not provided, it uses DISPATCH_TIME_FOREVER public func wait(seconds seconds: Double = 0.0) { if seconds != 0.0 { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_block_wait(block, time) } else { dispatch_block_wait(block, DISPATCH_TIME_FOREVER) } } /* Convenience */ private func chain(seconds: Double? = nil, block chainingBlock: dispatch_block_t, queue: dispatch_queue_t) -> Async { if let seconds = seconds { return chainAfter(seconds, block: chainingBlock, queue: queue) } return chainNow(block: chainingBlock, queue: queue) } /* dispatch_async() */ private func chainNow(block chainingBlock: dispatch_block_t, queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) dispatch_block_notify(block, queue, _chainingBlock) return Async(_chainingBlock) } /* dispatch_after() */ private func chainAfter(seconds: Double, block chainingBlock: dispatch_block_t, queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) // Wrap block to be called when previous block is finished let chainingWrapperBlock: dispatch_block_t = { // Calculate time from now let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_after(time, queue, _chainingBlock) } // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingWrapperBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingWrapperBlock) // Add block to queue *after* previous block is finished dispatch_block_notify(self.block, queue, _chainingWrapperBlock) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_chainingBlock) } } // MARK: - Apply public struct Apply { // DSL for GCD dispatch_apply() // // Apply runs a block multiple times, before returning. // If you want run the block asynchronously from the current thread, // wrap it in an Async block, // e.g. Async.main { Apply.background(3) { ... } } public static func userInteractive(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInteractiveQueue(), block) } public static func userInitiated(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInitiatedQueue(), block) } public static func utility(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.utilityQueue(), block) } public static func background(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.backgroundQueue(), block) } public static func customQueue(iterations: Int, queue: dispatch_queue_t, block: Int -> ()) { dispatch_apply(iterations, queue, block) } } // MARK: - qos_class_t public extension qos_class_t { // Convenience description of qos_class_t // Calculated property var description: String { get { switch self { case qos_class_main(): return "Main" case QOS_CLASS_USER_INTERACTIVE: return "User Interactive" case QOS_CLASS_USER_INITIATED: return "User Initiated" case QOS_CLASS_DEFAULT: return "Default" case QOS_CLASS_UTILITY: return "Utility" case QOS_CLASS_BACKGROUND: return "Background" case QOS_CLASS_UNSPECIFIED: return "Unspecified" default: return "Unknown" } } } } // Make qos_class_t equatable extension qos_class_t: Equatable {}
mit
442666a3bda1edfeb5f69ca512e02e35
34.69395
128
0.700768
3.903854
false
false
false
false
mentalfaculty/impeller
Playgrounds/Brocolli with Enum.playground/Contents.swift
1
2279
//: Playground - noun: a place where people can play import Cocoa typealias UniqueIdentifier = String protocol Keyed { var key: String { get } } protocol Storable { associatedtype StorableProperty: Keyed var storage: Storage<StorableProperty> { get set } mutating func store(_ value: StorableProperty) } extension Storable { mutating func store(_ value: StorableProperty) { storage.propertiesByKey[value.key] = value } } struct Storage<PropertyType> { var version: UInt64 = 0 var timestamp = Date.timeIntervalSinceReferenceDate var uniqueIdentifier = UUID().uuidString var propertiesByKey = [String: PropertyType]() init() {} } struct Person : Storable { var storage = Storage<StorableProperty>() enum Property : Keyed { case name(String) case age(Int) var key: String { return "" } } typealias StorableProperty = Property } var person = Person() person.store(.name("Tom")) /* class Store { func saveValue<T:Storable>(value:T, resolvingConflictWith handler:((T, T) -> T)? ) { let storeValue:T = fetchValue(identifiedBy: value.metadata.uniqueIdentifier) var resolvedValue:T! if value.metadata.version == storeValue.metadata.version { // Store unchanged, so just save the new value directly resolvedValue = value } else { // Conflict. There have been saves since we fetched this value. let values = [storeValue, value] let sortedValues = values.sorted { $0.metadata.timestamp < $1.metadata.timestamp } if let handler = handler { resolvedValue = handler(sortedValues[0], sortedValues[1]) } else { resolvedValue = sortedValues[1] // Take most recent } } // Update metadata resolvedValue.metadata.timestamp = Date.timeIntervalSinceReferenceDate resolvedValue.metadata.version = storeValue.metadata.version + 1 // TODO: Save resolved value to disk } func fetchValue<T:Storable>(identifiedBy uniqueIdentifier:UniqueIdentifier) -> T { return Person() as! T } } */
mit
97af2ee6a46baa5a6308dd0c169840fe
26.130952
94
0.620886
4.698969
false
false
false
false
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Playgrounds to Production.xcplaygroundpage/Contents.swift
1
1965
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: ## Playgrounds to Production //: //: The intention of most of the AudioKit Playgrounds is to highlight a particular //: concept. To keep things clear, we have kept the amount of code to a minimum. //: But the flipside of that decision is that code from playgrounds will look a little //: different from production. In general, to see best practices, you can check out //: the AudioKit examples project, but here in this playground we'll highlight some //: important ways playground code differs from production code. //: //: In production, you would only import AudioKit, not AudioKitPlaygrounds import AudioKitPlaygrounds import AudioKit //: ### Memory management //: //: In a playground, you don't have to worry about whether a node is retained, so you can //: just write: let oscillator = AKOscillator() AudioKit.output = oscillator AudioKit.start() //: But if you did the same type of thing in a project: class BadAudioEngine { init() { let oscillator = AKOscillator() AudioKit.output = oscillator AudioKit.start() } } //: It wouldn't work because the oscillator node would be lost right after the init //: method completed. Instead, make sure it is declared as an instance variable: class AudioEngine { var oscillator: AKOscillator init() { oscillator = AKOscillator() AudioKit.output = oscillator AudioKit.start() } } //: ### Error Handling //: //: In AudioKit playgrounds, failable initializers are just one line: let file = try AKAudioFile() var player = try AKAudioPlayer(file: file) //: In production code, this would need to be wrapped in a do-catch block do { let file = try AKAudioFile(readFileName: "drumloop.wav") player = try AKAudioPlayer(file: file) } catch { AKLog("File Not Found") } //: --- //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
4f98e054e8ac9e96a6a286c9a0e4e79c
31.213115
89
0.698219
4.290393
false
false
false
false
editfmah/AeonAPI
Sources/TaskResult.swift
1
1989
// // TaskResult.swift // AeonAPI // // Created by Adrian Herridge on 24/06/2017. // // import Foundation import SWSQLite enum TaskStatus : Int { case TaskStatusNotExecuted = 0 case TaskStatusCompleted = 1 case TaskStatusErroredProcessing = 3 } enum TaskType : Int { case TaskTypeAeonSimpleWalletBalanceUpdate = 1 case TaskTypeAeonSimpleWalletRefresh = 2 case TaskTypeAeonSimpleWalletReadTransactions = 3 case TaskTypeCoinMarketUSD = 4 case TaskTypeCoinMarketGBP = 5 case TaskTypeCoinMarketEUR = 6 case TaskTypeCoinMarketBCN = 7 case TaskTypeAeonSimpleWalletReadSeed = 8 case TaskTypeAeonSimpleWalletRestore = 9 } class TaskResult : DataObject { // _id_ && _timestamp_ in base class. var user_id: String? var wallet_id: String? var opdate: String? var type: Int? var result: String? var status: Int? override func populateFromRecord(_ record: Record) { self.user_id = record["user_id"]?.asString() self.wallet_id = record["wallet_id"]?.asString() self.opdate = record["opdate"]?.asString() self.type = record["type"]?.asInt() self.result = record["result"]?.asString() self.status = record["status"]?.asInt() } override class func GetTables() -> [Action] { let actions = [ Action(createTable: "TaskResult"), Action(addColumn: "user_id", type: .String, table: "TaskResult"), Action(addColumn: "wallet_id", type: .String, table: "TaskResult"), Action(addColumn: "opdate", type: .String, table: "TaskResult"), Action(addColumn: "type", type: .Int, table: "TaskResult"), Action(addColumn: "result", type: .String, table: "TaskResult"), Action(addColumn: "status", type: .Int, table: "TaskResult"), Action(createIndexOnTable: "TaskResult", keyColumnName: "user_name", ascending: true) ] return actions } }
mit
0bc3a47cb6fb812dbe8c182f9e94c17f
30.078125
97
0.636501
3.93083
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/GoldenQuranSwift/SideMenuViewController.swift
1
5305
// // SideMenuViewController.swift // GoldenQuranSwift // // Created by Omar Fraiwan on 3/11/17. // Copyright © 2017 Omar Fraiwan. All rights reserved. // import UIKit import SideMenu class SideMenuViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupSideMenu() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showFeaturesSideMenu(){ if UIApplication.isAr() { self.performSegue(withIdentifier: "toFeaturesRight", sender: nil) } else { self.performSegue(withIdentifier: "toFeaturesLeft", sender: nil) } // self.performSegue(withIdentifier: "toFeatures", sender: nil) } fileprivate func setupSideMenu() { // Define the menus let featuresLeftVC = storyboard!.instantiateViewController(withIdentifier: "MushafFeaturesLeftNavigationViewController") as? UISideMenuNavigationController let featuresRightVC = storyboard!.instantiateViewController(withIdentifier: "MushafFeaturesRightNavigationViewController") as? UISideMenuNavigationController SideMenuManager.menuRightNavigationController = featuresRightVC SideMenuManager.menuLeftNavigationController = featuresLeftVC // Enable gestures. The left and/or right menus must be set up above for these to work. // Note that these continue to work on the Navigation Controller independent of the View Controller it displays! // SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar) // SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view) setMenuDefaults() // Set up a cool background image for demo purposes // SideMenuManager.menuAnimationBackgroundColor = UIColor(patternImage: UIImage(named: "GoldenIcon")!) } override var prefersStatusBarHidden: Bool { return true } fileprivate func setMenuDefaults(){ SideMenuManager.menuPresentMode = .menuSlideIn SideMenuManager.menuAnimationFadeStrength = 0.4 SideMenuManager.menuWidth = 300//min(UIScreen.main.bounds.width * 0.7, 520.0) SideMenuManager.menuAnimationTransformScaleFactor = 0.95 SideMenuManager.menuPushStyle = .subMenu } // fileprivate func setDefaults() { // let modes:[SideMenuManager.MenuPresentMode] = [.menuSlideIn, .viewSlideOut, .menuDissolveIn] // presentModeSegmentedControl.selectedSegmentIndex = modes.index(of: SideMenuManager.menuPresentMode)! // // let styles:[UIBlurEffectStyle] = [.dark, .light, .extraLight] // if let menuBlurEffectStyle = SideMenuManager.menuBlurEffectStyle { // blurSegmentControl.selectedSegmentIndex = styles.index(of: menuBlurEffectStyle) ?? 0 // } else { // blurSegmentControl.selectedSegmentIndex = 0 // } // // darknessSlider.value = Float(SideMenuManager.menuAnimationFadeStrength) // shadowOpacitySlider.value = Float(SideMenuManager.menuShadowOpacity) // shrinkFactorSlider.value = Float(SideMenuManager.menuAnimationTransformScaleFactor) // screenWidthSlider.value = Float(SideMenuManager.menuWidth / view.frame.width) // blackOutStatusBar.isOn = SideMenuManager.menuFadeStatusBar // } // // @IBAction fileprivate func changeSegment(_ segmentControl: UISegmentedControl) { // switch segmentControl { // case presentModeSegmentedControl: // let modes:[SideMenuManager.MenuPresentMode] = [.menuSlideIn, .viewSlideOut, .viewSlideInOut, .menuDissolveIn] // SideMenuManager.menuPresentMode = modes[segmentControl.selectedSegmentIndex] // case blurSegmentControl: // if segmentControl.selectedSegmentIndex == 0 { // SideMenuManager.menuBlurEffectStyle = nil // } else { // let styles:[UIBlurEffectStyle] = [.dark, .light, .extraLight] // SideMenuManager.menuBlurEffectStyle = styles[segmentControl.selectedSegmentIndex - 1] // } // default: break; // } // } // // @IBAction fileprivate func changeSlider(_ slider: UISlider) { // switch slider { // case darknessSlider: // SideMenuManager.menuAnimationFadeStrength = CGFloat(slider.value) // case shadowOpacitySlider: // SideMenuManager.menuShadowOpacity = slider.value // case shrinkFactorSlider: // SideMenuManager.menuAnimationTransformScaleFactor = CGFloat(slider.value) // case screenWidthSlider: // SideMenuManager.menuWidth = view.frame.width * CGFloat(slider.value) // default: break; // } // } // // @IBAction fileprivate func changeSwitch(_ switchControl: UISwitch) { // SideMenuManager.menuFadeStatusBar = switchControl.isOn // } }
mit
68cbc57cb38e1bb21307546da6ee4ed7
39.48855
165
0.673077
5.179688
false
false
false
false
AlexRamey/mbird-iOS
iOS Client/ArticlesController/RecentArticleTableViewCell.swift
1
2044
// // RecentArticleTableViewCell.swift // iOS Client // // Created by Alex Ramey on 4/7/18. // Copyright © 2018 Mockingbird. All rights reserved. // import UIKit class RecentArticleTableViewCell: UITableViewCell, ThumbnailImageCell { @IBOutlet weak var thumbnailImage: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code self.thumbnailImage.contentMode = .scaleAspectFill self.thumbnailImage.clipsToBounds = true self.categoryLabel.textColor = UIColor.MBOrange self.categoryLabel.font = UIFont(name: "AvenirNext-Bold", size: 13.0) self.timeLabel.textColor = UIColor.MBOrange self.timeLabel.font = UIFont(name: "AvenirNext-Bold", size: 13.0) let bgColorView = UIView() bgColorView.backgroundColor = UIColor.MBSelectedCell self.selectedBackgroundView = bgColorView } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setCategory(_ cat: String?) { self.categoryLabel.text = (cat ?? "mockingbird").uppercased() } func setTitle(_ title: NSAttributedString?) { self.titleLabel.attributedText = title self.titleLabel.textColor = UIColor.black self.titleLabel.font = UIFont(name: "IowanOldStyle-Roman", size: 22.0) self.titleLabel.sizeToFit() } func setDate(date: Date?) { if let date = date { // show the date var longDate = DateFormatter.localizedString(from: date, dateStyle: .long, timeStyle: .none) if let idx = longDate.index(of: ",") { longDate = String(longDate.prefix(upTo: idx)) } self.timeLabel.text = longDate } else { self.timeLabel.text = "recent" } } }
mit
e84fa3b08da2facbd96eebce46a6c12d
32.491803
104
0.63583
4.622172
false
false
false
false
srxboys/RXSwiftExtention
RXSwiftExtention/Home/Model/RXIndexTVModel.swift
1
2589
// // RXIndexTV.swift // RXSwiftExtention // // Created by srx on 2017/4/3. // Copyright © 2017年 https://github.com/srxboys. All rights reserved. // import UIKit class RXIndexTVModel: RXModel { var tv_id : String = "" var sku : String = "" var name : String = "" var goods_id : String = "" var price : Int = 0 var marketprice : Int = 0 var price_flag : String = "" var image : String = "" var starttime : Int = 0 var endtime : Int = 0 var currenttime : Int = 0 //为什么不写 set get 一般set get 不是本身(why:自己循环了) //只重写了get方法,没重写set方法,所以外界不能赋值,只能是只读属性 //var _currenttime : Int{ // get { // print(hashValue) // if(self.currenttime > 0) { return self.currenttime } // return Int(Date().timeIntervalSince1970) // } // // set { // if(newValue > 0) { // self.currenttime = newValue // } // } // } var channel_name : String = "" var live_stream_uris : String = "" var is_multiple : Int = 0 var descriptionStr : String = "" var isLiveType : Int = 0 override init() { super.init() } convenience init(dict:[String:Any]) { self.init() tv_id = dictForKeyString(dict, key: "tv_id") sku = dictForKeyString(dict, key: "sku") goods_id = dictForKeyString(dict, key: "goods_id") price = dictForKeyInt(dict, key: "price") marketprice = dictForKeyInt(dict, key: "marketprice") price_flag = dictForKeyString(dict, key: "price_flag") image = dictForKeyString(dict, key: "image") starttime = dictForKeyInt(dict, key: "starttime") endtime = dictForKeyInt(dict, key: "endtime") currenttime = dictForKeyInt(dict, key: "currenttime") channel_name = dictForKeyString(dict, key: "channel_name") live_stream_uris = dictForKeyString(dict, key: "live_stream_uris") is_multiple = dictForKeyInt(dict, key: "is_multiple") descriptionStr = dictForKeyString(dict, key: "description") //没有用重写get set if(currenttime <= 0) { currenttime = Int(Date().timeIntervalSince1970) } //也可以用计算属性 if(endtime < currenttime) { isLiveType = 0; } else if(starttime > currenttime) { isLiveType = 2; } else { isLiveType = 1; } } }
mit
fb442657de4e51575514a99e6a90177f
28.759036
74
0.551822
3.600583
false
false
false
false