repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
anirudh24seven/wikipedia-ios | Wikipedia/Code/SavedPageSpotlightManager.swift | 1 | 3499 | import UIKit
import MobileCoreServices
import CoreSpotlight
public extension NSURL {
@available(iOS 9.0, *)
func searchableItemAttributes() -> CSSearchableItemAttributeSet? {
guard wmf_isWikiResource else {
return nil
}
guard let title = wmf_title else {
return nil
}
let components = title.componentsSeparatedByString(" ")
let searchableItem = CSSearchableItemAttributeSet(itemContentType: kUTTypeInternetLocation as String)
searchableItem.keywords = ["Wikipedia","Wikimedia","Wiki"] + components
searchableItem.title = wmf_title
searchableItem.displayName = wmf_title
searchableItem.identifier = NSURL.wmf_desktopURLForURL(self)?.absoluteString
searchableItem.relatedUniqueIdentifier = NSURL.wmf_desktopURLForURL(self)?.absoluteString
return searchableItem
}
}
public extension MWKArticle {
@available(iOS 9.0, *)
func searchableItemAttributes() -> CSSearchableItemAttributeSet {
let searchableItem = url.searchableItemAttributes() ??
CSSearchableItemAttributeSet(itemContentType: kUTTypeInternetLocation as String)
searchableItem.subject = entityDescription
searchableItem.contentDescription = summary
if let string = imageURL {
if let url = NSURL(string: string) {
searchableItem.thumbnailData = WMFImageController.sharedInstance().diskDataForImageWithURL(url);
}
}
return searchableItem
}
}
@available(iOS 9.0, *)
public class WMFSavedPageSpotlightManager: NSObject {
let dataStore: MWKDataStore
var savedPageList: MWKSavedPageList {
return dataStore.savedPageList
}
public required init(dataStore: MWKDataStore) {
self.dataStore = dataStore
super.init()
}
public func reindexSavedPages() {
self.savedPageList.enumerateItemsWithBlock { (item, stop) in
self.addToIndex(item.url)
}
}
public func addToIndex(url: NSURL) {
guard let article = dataStore.existingArticleWithURL(url), let identifier = NSURL.wmf_desktopURLForURL(url)?.absoluteString else {
return
}
let searchableItemAttributes = article.searchableItemAttributes()
searchableItemAttributes.keywords?.append("Saved")
let item = CSSearchableItem(uniqueIdentifier: identifier, domainIdentifier: "org.wikimedia.wikipedia", attributeSet: searchableItemAttributes)
item.expirationDate = NSDate.distantFuture()
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item]) { (error: NSError?) -> Void in
if let error = error {
DDLogError("Indexing error: \(error.localizedDescription)")
} else {
DDLogVerbose("Search item successfully indexed!")
}
}
}
public func removeFromIndex(url: NSURL) {
guard let identifier = NSURL.wmf_desktopURLForURL(url)?.absoluteString else {
return
}
CSSearchableIndex.defaultSearchableIndex().deleteSearchableItemsWithIdentifiers([identifier]) { (error: NSError?) -> Void in
if let error = error {
DDLogError("Deindexing error: \(error.localizedDescription)")
} else {
DDLogVerbose("Search item successfully removed!")
}
}
}
}
| mit | 8d0ddac64e35cec6a918cc0faeb4bd94 | 34.704082 | 150 | 0.653044 | 5.43323 | false | false | false | false |
LYM-mg/DemoTest | indexView/indexView/Two/XibViewController.swift | 1 | 2363 | //
// XibViewController.swift
// indexView
//
// Created by i-Techsys.com on 2017/7/17.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
class XibViewController: UIViewController {
fileprivate lazy var titleLabel: UILabel = UILabel()
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.randomColor()
let view: XJLView = XJLView.loadViewFromXib1()
self.view.addSubview(view)
let view1: MGXibView = MGXibView.loadViewFromXib1()
view1.mg_y = view.frame.maxY + 10
self.view.addSubview(view1)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "SB", style: .done, target: self, action: #selector(LoadSB))
titleLabel.frame = CGRect(x: 120, y: 380, width: 200, height: 100)
// timer = Timer.scheduledTimer(with: 1.0, block: {
// print("打印定时器")
// }, repeats: true)
// timer = Timer.scheduledTimer(with: 1.0, action: {
// print("打印定时器")
// })
}
@objc func LoadSB() {
self.show(SBTools.loadControllerFromSB("Main"), sender: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let att = NSMutableAttributedString(string: "释放查看,的撒会单据号塞到好似符号ID师父hi第三方his地方很多看撒娇的接口", attributes: [NSAttributedString.Key.verticalGlyphForm: 1, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 9), NSAttributedString.Key.foregroundColor: UIColor.red])
titleLabel.attributedText = att
titleLabel.transform = CGAffineTransform(rotationAngle: .pi/2)
}
deinit {
timer?.invalidate()
print("XibViewController--deinit")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 6e8c2ca71637fa2d6489e9039099ebec | 32.970149 | 265 | 0.655975 | 4.168498 | false | false | false | false |
cristianames92/PortalView | Sources/Components/Collection.swift | 1 | 4774 | //
// CollectionView.swift
// PortalView
//
// Created by Argentino Ducret on 4/4/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import Foundation
import UIKit
public class SectionInset {
public static let zero = SectionInset(top: 0, left: 0, bottom: 0, right: 0)
public var bottom: UInt
public var top: UInt
public var left: UInt
public var right: UInt
public init(top: UInt, left: UInt, bottom: UInt, right: UInt) {
self.bottom = bottom
self.top = top
self.left = left
self.right = right
}
}
public enum CollectionScrollDirection {
case horizontal
case vertical
}
public struct CollectionProperties<MessageType> {
public var items: [CollectionItemProperties<MessageType>]
public var showsVerticalScrollIndicator: Bool
public var showsHorizontalScrollIndicator: Bool
public var isSnapToCellEnabled: Bool
// Layout properties
public var itemsWidth: UInt
public var itemsHeight: UInt
public var minimumInteritemSpacing: UInt
public var minimumLineSpacing: UInt
public var scrollDirection: CollectionScrollDirection
public var sectionInset: SectionInset
fileprivate init(
items: [CollectionItemProperties<MessageType>] = [],
showsVerticalScrollIndicator: Bool = false,
showsHorizontalScrollIndicator: Bool = false,
isSnapToCellEnabled: Bool = false,
itemsWidth: UInt,
itemsHeight: UInt,
minimumInteritemSpacing: UInt = 0,
minimumLineSpacing: UInt = 0,
scrollDirection: CollectionScrollDirection = .vertical,
sectionInset: SectionInset = .zero) {
self.items = items
self.showsVerticalScrollIndicator = showsVerticalScrollIndicator
self.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator
self.isSnapToCellEnabled = isSnapToCellEnabled
self.itemsWidth = itemsWidth
self.itemsHeight = itemsHeight
self.minimumLineSpacing = minimumLineSpacing
self.minimumInteritemSpacing = minimumInteritemSpacing
self.sectionInset = sectionInset
self.scrollDirection = scrollDirection
}
public func map<NewMessageType>(_ transform: @escaping (MessageType) -> NewMessageType) -> CollectionProperties<NewMessageType> {
return CollectionProperties<NewMessageType>(
items: self.items.map { $0.map(transform) },
showsVerticalScrollIndicator: self.showsVerticalScrollIndicator,
showsHorizontalScrollIndicator: self.showsHorizontalScrollIndicator,
isSnapToCellEnabled: self.isSnapToCellEnabled,
itemsWidth: self.itemsWidth,
itemsHeight: self.itemsHeight,
minimumInteritemSpacing: self.minimumInteritemSpacing,
minimumLineSpacing: self.minimumLineSpacing,
scrollDirection: self.scrollDirection,
sectionInset: self.sectionInset)
}
}
public struct CollectionItemProperties<MessageType> {
public typealias Renderer = () -> Component<MessageType>
public let onTap: MessageType?
public let renderer: Renderer
public let identifier: String
fileprivate init(
onTap: MessageType?,
identifier: String,
renderer: @escaping Renderer) {
self.onTap = onTap
self.renderer = renderer
self.identifier = identifier
}
}
extension CollectionItemProperties {
public func map<NewMessageType>(_ transform: @escaping (MessageType) -> NewMessageType) -> CollectionItemProperties<NewMessageType> {
return CollectionItemProperties<NewMessageType>(
onTap: self.onTap.map(transform),
identifier: self.identifier,
renderer: { self.renderer().map(transform) }
)
}
}
public func collection<MessageType>(
properties: CollectionProperties<MessageType>,
style: StyleSheet<EmptyStyleSheet> = EmptyStyleSheet.default,
layout: Layout = layout()) -> Component<MessageType> {
return .collection(properties, style, layout)
}
public func collectionItem<MessageType>(
onTap: MessageType? = .none,
identifier: String,
renderer: @escaping CollectionItemProperties<MessageType>.Renderer) -> CollectionItemProperties<MessageType> {
return CollectionItemProperties(onTap: onTap, identifier: identifier, renderer: renderer)
}
public func properties<MessageType>(itemsWidth: UInt, itemsHeight: UInt, configure: (inout CollectionProperties<MessageType>) -> ()) -> CollectionProperties<MessageType> {
var properties = CollectionProperties<MessageType>(itemsWidth: itemsWidth, itemsHeight: itemsHeight)
configure(&properties)
return properties
}
| mit | 0635df70996a4f778617d17f10acf1f6 | 33.839416 | 171 | 0.701865 | 5.285714 | false | false | false | false |
natecook1000/swift | test/DebugInfo/uninitialized.swift | 3 | 1104 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend %s -O -emit-ir -g -o - | %FileCheck %s --check-prefix=OPT
class MyClass {}
// CHECK-LABEL: define {{.*}} @"$S13uninitialized1fyyF"
// OPT-LABEL: define {{.*}} @"$S13uninitialized1fyyF"
public func f() {
var object: MyClass
// CHECK: %[[OBJ:.*]] = alloca %[[T1:.*]]*, align
// CHECK: call void @llvm.dbg.declare(metadata %[[T1]]** %[[OBJ]],
// CHECK: %[[BC1:.*]] = bitcast %[[T1]]** %[[OBJ]] to %swift.opaque**
// CHECK: store %swift.opaque* null, %swift.opaque** %[[BC1]], align {{.*}}
// OPT-NOT: store
// OPT: ret
}
// CHECK-LABEL: define {{.*}} @"$S13uninitialized1gyyF"
// OPT-LABEL: define {{.*}} @"$S13uninitialized1gyyF"
public func g() {
var dict: Dictionary<Int64, Int64>
// CHECK: %[[DICT:.*]] = alloca %[[T2:.*]], align
// CHECK: call void @llvm.dbg.declare(metadata %[[T2]]* %[[DICT]],
// CHECK: %[[BC2:.*]] = bitcast %[[T2]]* %[[DICT]] to %swift.opaque**
// CHECK: store %swift.opaque* null, %swift.opaque** %[[BC2]], align {{.*}}
// OPT-NOT: store
// OPT: ret
}
| apache-2.0 | 38abdb4b648acc9c1384c733531b3576 | 39.888889 | 88 | 0.571558 | 3.163324 | false | false | false | false |
pixio/PXImageView | Example/PXImageView/AppDelegate.swift | 1 | 1158 | //
// PXSwiftAppDelegate.swift
// PXImageView
//
// Created by Dave Heyborne on 2.17.16.
// Copyright © 2016 Dave Heyborne. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
window?.makeKeyAndVisible()
window?.backgroundColor = UIColor.white
let controller: ViewController = ViewController()
let navController: UINavigationController = UINavigationController(rootViewController: controller)
window?.rootViewController = navController
return true
}
func applicationWillResignActive(_ application: UIApplication) {}
func applicationDidEnterBackground(_ application: UIApplication) {}
func applicationWillEnterForeground(_ application: UIApplication) {}
func applicationDidBecomeActive(_ application: UIApplication) {}
func applicationWillTerminate(_ application: UIApplication) {}
}
| mit | 0b8697029214d05fad1fbfd896ce6917 | 30.27027 | 144 | 0.722558 | 6.187166 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/NewThemeController.swift | 1 | 6434 | //
// NewThemeController.swift
// Telegram
//
// Created by Mikhail Filimonov on 28/08/2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import ColorPalette
import ThemeSettings
import Postbox
private let _id_input_name = InputDataIdentifier("_id_input_name")
private struct NewThemeState : Equatable {
let name: String
let error: InputDataValueError?
init(name: String, error: InputDataValueError?) {
self.name = name
self.error = error
}
func withUpdatedCode(_ name: String) -> NewThemeState {
return NewThemeState(name: name, error: self.error)
}
func withUpdatedError(_ error: InputDataValueError?) -> NewThemeState {
return NewThemeState(name: self.name, error: error)
}
}
private func newThemeEntries(state: NewThemeState) -> [InputDataEntry] {
var entries: [InputDataEntry] = []
var sectionId: Int32 = 0
var index:Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.input(sectionId: sectionId, index: index, value: .string(state.name), error: state.error, identifier: _id_input_name, mode: .plain, data: InputDataRowData(), placeholder: nil, inputPlaceholder: strings().newThemePlaceholder, filter: { $0 }, limit: 100))
index += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().newThemeDesc), data: InputDataGeneralTextData()))
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func NewThemeController(context: AccountContext, palette: ColorPalette) -> InputDataModalController {
var palette = palette
let initialState = NewThemeState(name: findBestNameForPalette(palette), error: nil)
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((NewThemeState) -> NewThemeState) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
let disposable = MetaDisposable()
var close: (() -> Void)? = nil
let signal = statePromise.get() |> map { state in
return InputDataSignalValue(entries: newThemeEntries(state: state))
}
func create() -> InputDataValidation {
return .fail(.doSomething(next: { f in
let name = stateValue.with { $0.name }
if name.isEmpty {
f(.fail(.fields([_id_input_name : .shake])))
return
}
let temp = NSTemporaryDirectory() + "\(arc4random()).palette"
try? palette.toString.write(to: URL(fileURLWithPath: temp), atomically: true, encoding: .utf8)
let resource = LocalFileReferenceMediaResource(localFilePath: temp, randomId: arc4random64(), isUniquelyReferencedTemporaryFile: true, size: fileSize(temp))
var thumbnailData: Data? = nil
let preview = generateThemePreview(for: palette, wallpaper: theme.wallpaper.wallpaper, backgroundMode: theme.backgroundMode)
if let mutableData = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData(mutableData, "public.png" as CFString, 1, nil) {
CGImageDestinationAddImage(destination, preview, nil)
if CGImageDestinationFinalize(destination) {
let data = mutableData as Data
thumbnailData = data
}
}
disposable.set(showModalProgress(signal: createTheme(account: context.account, title: name, resource: resource, thumbnailData: thumbnailData, settings: nil)
|> filter { value in
switch value {
case .result:
return true
default:
return false
}
} |> take(1), for: context.window).start(next: { result in
switch result {
case let .result(theme):
_ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: {
$0.withUpdatedCloudTheme(theme)
}).start()
default:
break
}
exportPalette(palette: palette.withUpdatedName(name), completion: { result in
if let result = result {
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: result)])
}
})
f(.success(.custom {
delay(0.2, closure: {
close?()
})
}))
}, error: { _ in
alert(for: context.window, info: strings().unknownError)
}))
}))
}
let controller = InputDataController(dataSignal: signal, title: strings().newThemeTitle, validateData: { data in
let name = stateValue.with { $0.name }
if name.isEmpty {
updateState { current in
return current.withUpdatedError(.init(description: strings().newThemeEmptyTextError, target: .data))
}
return .fail(.fields([_id_input_name: .shake]))
} else {
return create()
}
}, updateDatas: { data in
updateState { current in
return current.withUpdatedCode(data[_id_input_name]?.stringValue ?? current.name).withUpdatedError(nil)
}
return .none
}, afterDisappear: {
disposable.dispose()
}, getBackgroundColor: {
theme.colors.background
})
let modalInteractions = ModalInteractions(acceptTitle: strings().newThemeCreate, accept: { [weak controller] in
_ = controller?.returnKeyAction()
}, drawBorder: true, height: 50, singleButton: true)
let modalController = InputDataModalController(controller, modalInteractions: modalInteractions)
controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in
modalController?.close()
})
close = { [weak modalController] in
modalController?.modal?.close()
}
return modalController
}
| gpl-2.0 | a034532eca48a5bc9dfaa67aee91e9a0 | 37.291667 | 273 | 0.602052 | 5.05739 | false | false | false | false |
dusanIntellex/backend-operation-layer | BackendServiceAdapter/Classes/Adapter/Executor/BackendFirebaseExecutor.swift | 1 | 10385 | //
// BackendFirebaseExecutor.swift
// AuthorizationApp
//
// Created by Vladimir Djokanovic on 8/16/17.
// Copyright © 2017 Intellex. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
class BackendFirebaseExecutor: NSObject, BackendExecutorProtocol {
var ref: DatabaseReference?
var storage = Storage.storage()
var uploadTask : StorageUploadTask?
var downloadTask : StorageDownloadTask?
/// Execute backend REST request with firebase wrapper
///
/// - Parameters:
/// - backendRequest: Request with all params
/// - successCallback: Return data and status code
/// - failureCallback: Return error and status code
func executeBackendRequest(backendRequest: BackendRequest, successCallback: @escaping BackendRequestSuccessCallback, failureCallback: @escaping BackendRequestFailureCallback){
if ref == nil{
ref = Database.database().reference()
}
backendRequestWithFirebase(backendRequest: backendRequest) { (data, error) in
if error == nil{
successCallback(data, 200)
}
else{
failureCallback(error, 0)
}
}
}
/// Upload file with unique file id, data to be uplaoded, headers and completion block. Upload progress and status is tracked on file which containe all data about upload progress
///
/// - Parameters:
/// - fileId: Id of file
/// - data: File data
/// - headers: Header for upload
/// - successCallback: Return data and status code
/// - failureCallback: Return error and stts code
func uploadFile(backendRequest: BackendRequest, successCallback: @escaping BackendRequestSuccessCallback, failureCallback: @escaping BackendRequestFailureCallback) {
guard let fileId = backendRequest.paramteres()?[BRFileIdConst] else {
failureCallback(nil, 1001)
return
}
// File located on disk
let file = FileLoad.getFile(fileId: fileId as! String, data: nil)
// Create a reference to the file you want to upload
guard let riversRef = getFilePath(request: backendRequest) else {
failureCallback(nil, 1001)
return
}
// Upload the file to the path "images/rivers.jpg"
uploadTask = riversRef.putFile(from: file.path!, metadata: nil) { metadata, error in
if let error = error {
print(error.localizedDescription)
failureCallback(error, 400)
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata!.downloadURL()
print("Download URL: \(downloadURL?.path ?? "No url")")
successCallback(metadata, 200)
}
}
observerLoad(task: uploadTask, file: file, successCallback: successCallback, failureCallback: failureCallback)
}
/// Download file
///
/// - Parameters:
/// - backendRequest: <#backendRequest description#>
/// - successCallback: <#successCallback description#>
/// - failureCallback: <#failureCallback description#>
func downloadFile(backendRequest: BackendRequest, successCallback: @escaping BackendRequestSuccessCallback, failureCallback: @escaping BackendRequestFailureCallback) {
guard let fileId = backendRequest.paramteres()?[BRFileIdConst] else {
failureCallback(nil, 1001)
return
}
// File located on disk
let file = FileLoad.getFile(fileId: fileId as! String, data: NSData())
// Create a reference to the file you want to upload
guard let riversRef = getFilePath(request: backendRequest) else {
failureCallback(nil, 1001)
return
}
// Download to the local filesystem
downloadTask = riversRef.write(toFile: file.path!) { url, error in
if let error = error {
print(error.localizedDescription)
failureCallback(error, 400)
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
print("Local URL: \(String(describing: url))")
successCallback(url, 200)
}
}
// Observer changes
observerLoad(task: downloadTask, file: file, successCallback: successCallback, failureCallback: failureCallback)
}
// MARK: - Task manage
func cancel(){
ref?.cancelDisconnectOperations()
if uploadTask != nil{
uploadTask!.cancel()
}
else if downloadTask != nil{
downloadTask?.cancel()
}
}
func pause(){
if uploadTask != nil{
uploadTask!.pause()
}
else if downloadTask != nil{
downloadTask?.pause()
}
}
func resume(){
if uploadTask != nil{
uploadTask!.resume()
}
else if downloadTask != nil{
downloadTask?.resume()
}
}
//MARK:- Private
private func observerLoad(task: StorageObservableTask?, file: FileLoad, successCallback: @escaping BackendRequestSuccessCallback, failureCallback: @escaping BackendRequestFailureCallback){
// Listen for state changes, errors, and completion of the upload.
task?.observe(.resume) { snapshot in
// Upload resumed, also fires when the upload starts
file.status = .progress
}
task?.observe(.pause) { snapshot in
// Upload paused
file.status = .pause
}
task?.observe(.progress) { snapshot in
// Upload reported progress
let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
/ Double(snapshot.progress!.totalUnitCount)
file.status = .progress
file.progress = CGFloat(percentComplete)
}
task?.observe(.success) { snapshot in
// Upload completed successfully
file.status = .success
}
task?.observe(.failure) { snapshot in
if let error = snapshot.error as NSError? {
switch (StorageErrorCode(rawValue: error.code)!) {
case .objectNotFound:
file.status = .fail
// File doesn't exist
break
case .unauthorized:
// User doesn't have permission to access file
file.status = .fail
break
case .cancelled:
file.status = .cancel
// User canceled the upload
break
/* ... */
case .unknown:
file.status = .fail
// Unknown error occurred, inspect the server response
break
default:
// A separate error occurred. This is a good place to retry the upload.
file.status = .fail
break
}
print(error.localizedDescription)
failureCallback(error, error.code)
}
}
}
private func getFilePath(request: BackendRequest) -> StorageReference?{
let storageRef = storage.reference()
guard let name = request.paramteres()?[BRFileNameConst] as? String, let ext = request.paramteres()?[BRFileExtensionConst] as? String, let path = request.paramteres()?[BRFilePathConst] as? String else { return nil }
return storageRef.child("\(path)/\(name).\(ext)")
}
private func backendRequestWithFirebase(backendRequest: BackendRequest, completion:@escaping (_ result : DataSnapshot?,_ error: Error?) -> Void){
switch backendRequest.method() {
case .get:
// If you have need for getting whole database use ""
if backendRequest.endpoint() == ""{
// If we want to listen changes on current model
if let observ = backendRequest.firebaseObserver(){
if observ{
ref!.observe(.value, with: { (snapshot) in
completion(snapshot, nil)
})
return
}
}
ref!.observeSingleEvent(of: .value, with: { (snapshot) in
completion(snapshot, nil)
})
}
else{
// If we want to listen changes on current model
if let observ = backendRequest.firebaseObserver(){
if observ{
ref!.child(backendRequest.endpoint()).observe( .value) { (snapshot) in
completion(snapshot, nil)
}
}
return
}
ref!.child(backendRequest.endpoint()).observeSingleEvent(of: .value, with: { (snapshot) in
completion(snapshot, nil)
})
}
break
case .post:
ref!.child(backendRequest.endpoint()).updateChildValues(backendRequest.paramteres()!, withCompletionBlock: { (error, reference) in
completion(nil, error)
})
break
default:
break
}
}
}
| mit | ed218f66edef48a7b58474d965d64b13 | 33.384106 | 222 | 0.521283 | 5.77852 | false | false | false | false |
zclongjie/ZCDouYu | ZCDouYu/ZCDouYu/Classes/Main/View/PageTitleView.swift | 1 | 6249 | //
// PageTitleView.swift
// ZCDouYu
//
// Created by 赵隆杰 on 16/9/18.
// Copyright © 2016年 赵隆杰. All rights reserved.
//
import UIKit
//定义协议
protocol PageTitleViewDelegate : class {
func pageTitleView(titleView : PageTitleView, selectIndex index : Int)
}
//定义常量
private let kScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) //灰黑色
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) //橘色
//定义类
class PageTitleView: UIView {
//定义属性
private var currentIndex : Int = 0
private var titles : [String]
weak var delegate : PageTitleViewDelegate?
//懒加载属性
private lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
private lazy var titleLabels : [UILabel] = [UILabel]()
private lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orangeColor()
return scrollLine
}()
//自定义构造函数
init(frame: CGRect, titles : [String]) {
self.titles = titles
super.init(frame: frame)
//设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
private func setupUI() {
//1.添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
//2.添加title对应的Label
setupTitleLabel()
//3.设置底线和滚动的滑块
setupBottomLineAndScrollLine()
}
private func setupTitleLabel() {
//0.确定label动一些frame值
let labelY : CGFloat = 0
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - kScrollLineH
for (index, title) in titles.enumerate() {
//1.创建UILabel
let label = UILabel()
//2.设置label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFontOfSize(16.0)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .Center
//3.设置label的frame
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
//4.将label添加到scrollView中
scrollView.addSubview(label)
titleLabels.append(label)
//5.给Label添加手势
label.userInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(_:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottomLineAndScrollLine() {
//1.添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGrayColor()
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
//2.添加scrollLine
//2.1获取第一个label
guard let firstLabel = titleLabels.first else { return }
firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
//2.2设置scrollLine的属性
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH)
}
}
//监听Label的点击
extension PageTitleView {
@objc private func titleLabelClick(tapGes : UITapGestureRecognizer) {
//1.获取当前label的下标值
guard let currentLabel = tapGes.view as? UILabel else { return }
//2.获取之前的label
let oldLabel = titleLabels[currentIndex]
//3.却换文字的颜色
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
//4.保存最新label的下标值
currentIndex = currentLabel.tag
//5.混动条位置发生改变
let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width
UIView.animateWithDuration(0.15, animations: {
self.scrollLine.frame.origin.x = scrollLineX
})
//6.通知代理
delegate?.pageTitleView(self, selectIndex: currentIndex)
}
}
//对外暴露的方法
extension PageTitleView {
func setTitleWithProgress(progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
//1.取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
//2.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
//3.颜色的渐变
//3.1.取出颜色变化的范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
//3.2.变化sourceLabel/targetLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
//4.记录最新的index
currentIndex = targetIndex
}
}
| mit | 8d109075ef1f8292156d5cb0749f9e6e | 27.396135 | 174 | 0.611432 | 4.64297 | false | false | false | false |
rbeeger/WebStats | WebStatsCommons/DateUtil.swift | 1 | 3704 | // Copyright (c) 2015 Robert F. Beeger
//
// 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 class DateUtil {
private let dateFormatter: NSDateFormatter
public init() {
dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .NoStyle
}
public func now() -> NSDate {
return NSDate()
}
public func stringFromDate(date:NSDate) -> String {
return dateFormatter.stringFromDate(date)
}
public func lastMondayFrom(date: NSDate) -> NSDate {
var result:NSDate? = nil
let calendar = NSCalendar.currentCalendar()
if let sixDaysAgo = calendar.dateByAddingUnit(.CalendarUnitDay, value: -6,
toDate: date, options: .allZeros) {
if let lastMonday = calendar.nextDateAfterDate(
sixDaysAgo,
matchingUnit: .CalendarUnitWeekday,
value: 2,
options: .MatchNextTime) {
result = lastMonday
}
}
assert(result != nil, "should have found the last Monday")
return result!
}
public func intervalsWithLastIntervalStartingOn(
startDate: NSDate, intervalLength: Int, intervalCount:Int) -> [Interval] {
return (0..<intervalCount).map({
NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay,
value: -(intervalLength * $0),
toDate: startDate, options: .allZeros)
}).filter({$0 != nil}).map({
self.intervalStartingOn($0!, withNumberOfDays: intervalLength)}).reverse()
}
public func dayStart(date:NSDate) -> NSDate {
return NSCalendar.currentCalendar().dateBySettingHour(
0, minute: 0, second: 0, ofDate: date, options: .allZeros)!
}
public func dayEnd(date:NSDate) -> NSDate {
return NSCalendar.currentCalendar().dateBySettingHour(
23, minute: 59, second: 59, ofDate: date, options: .allZeros)!
}
public func intervalStartingOn(startDate: NSDate, withNumberOfDays days:Int) -> Interval {
let calendar = NSCalendar.currentCalendar()
let startDateNormalized = dayStart(startDate)
let endDate = NSCalendar.currentCalendar().dateByAddingUnit(
.CalendarUnitDay, value: days - 1, toDate: startDateNormalized,
options: .allZeros)!
let endDateNormalized = dayEnd(endDate)
return Interval(startDate: startDateNormalized, endDate: endDateNormalized ?? startDate)
}
}
| mit | e38b7cd4b802ac0b7c47fc8d6ead0337 | 40.155556 | 96 | 0.650918 | 5.02578 | false | false | false | false |
atrick/swift | test/stdlib/StringIndex.swift | 1 | 31067 | // RUN: %target-run-stdlib-swift %S/Inputs/
// REQUIRES: executable_test
// UNSUPPORTED: freestanding
import StdlibUnittest
#if _runtime(_ObjC)
import Foundation
import StdlibUnicodeUnittest
#endif
var suite = TestSuite("StringIndexTests")
defer { runAllTests() }
enum SimpleString: String {
case smallASCII = "abcdefg"
case smallUnicode = "abéÏ𓀀"
case largeASCII = "012345678901234567890"
case largeUnicode = "abéÏ012345678901234567890𓀀"
case emoji = "😀😃🤢🤮👩🏿🎤🧛🏻♂️🧛🏻♂️👩👩👦👦"
}
let simpleStrings: [String] = [
SimpleString.smallASCII.rawValue,
SimpleString.smallUnicode.rawValue,
SimpleString.largeASCII.rawValue,
SimpleString.largeUnicode.rawValue,
SimpleString.emoji.rawValue,
"",
]
suite.test("basic sanity checks")
.forEach(in: simpleStrings) { s in
let utf8 = Array(s.utf8)
let subUTF8 = Array(s[...].utf8)
let utf16 = Array(s.utf16)
let subUTF16 = Array(s[...].utf16)
let utf32 = Array(s.unicodeScalars.map { $0.value })
let subUTF32 = Array(s[...].unicodeScalars.map { $0.value })
expectEqual(s, String(decoding: utf8, as: UTF8.self))
expectEqual(s, String(decoding: subUTF8, as: UTF8.self))
expectEqual(s, String(decoding: utf16, as: UTF16.self))
expectEqual(s, String(decoding: subUTF16, as: UTF16.self))
expectEqual(s, String(decoding: utf32, as: UTF32.self))
expectEqual(s, String(decoding: subUTF32, as: UTF32.self))
}
suite.test("view counts")
.forEach(in: simpleStrings) { s in
func validateViewCount<View: BidirectionalCollection>(
_ view: View, for string: String,
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) where View.Element: Equatable, View.Index == String.Index {
let stackTrace = stackTrace.pushIf(showFrame, file: file, line: line)
let count = view.count
func expect(_ i: Int,
file: String = #file, line: UInt = #line
) {
expectEqual(count, i, "for String: \(string)",
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line),
showFrame: false)
}
let reversedView = view.reversed()
expect(Array(view).count)
expect(view.indices.count)
expect(view.indices.reversed().count)
expect(reversedView.indices.count)
expect(view.distance(from: view.startIndex, to: view.endIndex))
expect(reversedView.distance(
from: reversedView.startIndex, to: reversedView.endIndex))
// Access the elements from the indices
expectEqual(Array(view), view.indices.map { view[$0] })
expectEqual(
Array(reversedView), reversedView.indices.map { reversedView[$0] })
let indicesArray = Array<String.Index>(view.indices)
for i in 0..<indicesArray.count {
var idx = view.startIndex
idx = view.index(idx, offsetBy: i)
expectEqual(indicesArray[i], idx)
}
}
validateViewCount(s, for: s)
validateViewCount(s.utf8, for: s)
validateViewCount(s.utf16, for: s)
validateViewCount(s.unicodeScalars, for: s)
validateViewCount(s[...], for: s)
validateViewCount(s[...].utf8, for: s)
validateViewCount(s[...].utf16, for: s)
validateViewCount(s[...].unicodeScalars, for: s)
}
suite.test("interchange")
.forEach(in: simpleStrings) { s in
// Basic index alignment
for idx in s.utf8.indices {
let char = s.utf8[idx]
// ASCII or leading code unit in the scalar
if char <= 0x7F || char >= 0b1100_0000 {
expectEqual(idx, idx.samePosition(in: s.unicodeScalars))
expectEqual(idx, idx.samePosition(in: s.utf16))
// ASCII
if char <= 0x7F {
expectEqual(UInt16(char), s.utf16[idx])
expectEqual(UInt32(char), s.unicodeScalars[idx].value)
}
} else {
// Continuation code unit
assert(char & 0b1100_0000 == 0b1000_0000)
expectNil(idx.samePosition(in: s))
expectNil(idx.samePosition(in: s.utf16))
expectNil(idx.samePosition(in: s.unicodeScalars))
}
}
}
suite.test("UTF-16 Offsets")
.forEach(in: simpleStrings) { s in
let end = s.endIndex
let utf16Count = s.utf16.count
expectEqual(end, String.Index(utf16Offset: utf16Count, in: s))
expectEqual(end, String.Index(utf16Offset: utf16Count, in: s[...]))
let pastEnd = String.Index(utf16Offset: utf16Count+1, in: s)
expectNotEqual(end, pastEnd)
expectEqual(pastEnd, String.Index(utf16Offset: utf16Count+1, in: s[...]))
expectEqual(pastEnd, String.Index(utf16Offset: utf16Count+2, in: s))
expectEqual(pastEnd, String.Index(utf16Offset: -1, in: s))
expectEqual(
pastEnd, String.Index(utf16Offset: Swift.max(1, utf16Count), in: s.dropFirst()))
let utf16Indices = Array(s.utf16.indices)
expectEqual(utf16Count, utf16Indices.count)
for i in 0..<utf16Indices.count {
let idx = String.Index(utf16Offset: i, in: s)
expectEqual(utf16Indices[i], idx)
expectEqual(i, idx.utf16Offset(in: s))
expectEqual(i, idx.utf16Offset(in: s[...]))
if i < s.dropLast().utf16.count {
expectEqual(
utf16Indices[i], String.Index(utf16Offset: i, in: s.dropLast()))
expectEqual(i, idx.utf16Offset(in: s.dropLast()))
} else if i == s.dropLast().utf16.count {
expectEqual(
utf16Indices[i], String.Index(utf16Offset: i, in: s.dropLast()))
} else {
expectNotEqual(
utf16Indices[i], String.Index(utf16Offset: i, in: s.dropLast()))
}
}
}
func swift5ScalarAlign(_ idx: String.Index, in str: String) -> String.Index {
var idx = idx
while str.utf8[idx] & 0xC0 == 0x80 { str.utf8.formIndex(before: &idx) }
return idx
}
suite.test("Scalar Align UTF-8 indices") {
// TODO: Test a new aligning API when we add it. For now, we
// test scalar-aligning UTF-8 indices
let str = "a😇"
let subScalarIdx = str.utf8.index(str.utf8.startIndex, offsetBy: 2)
let roundedIdx = swift5ScalarAlign(subScalarIdx, in: str)
expectEqual(1, roundedIdx.utf16Offset(in: str))
let roundedIdx2 = str.utf8[...subScalarIdx].lastIndex { $0 & 0xC0 != 0x80 }
expectEqual(roundedIdx, roundedIdx2)
var roundedIdx3 = subScalarIdx
while roundedIdx3.samePosition(in: str.unicodeScalars) == nil {
str.utf8.formIndex(before: &roundedIdx3)
}
expectEqual(roundedIdx, roundedIdx3)
}
#if _runtime(_ObjC)
suite.test("String.Index(_:within) / Range<String.Index>(_:in:)") {
guard #available(SwiftStdlib 5.1, *) else {
return
}
let str = simpleStrings.joined()
let substr = str[...]
for idx in str.utf8.indices {
expectEqual(
String.Index(idx, within: str), String.Index(idx, within: substr))
}
expectNil(String.Index(str.startIndex, within: str.dropFirst()))
expectNil(String.Index(str.endIndex, within: str.dropLast()))
expectNotNil(String.Index(str.startIndex, within: str))
expectNotNil(String.Index(str.endIndex, within: str))
let utf16Count = str.utf16.count
let utf16Indices = Array(str.utf16.indices) + [str.utf16.endIndex]
for location in 0..<utf16Count {
for length in 0...(utf16Count - location) {
let strLB = String.Index(utf16Indices[location], within: str)
let substrLB = String.Index(utf16Indices[location], within: substr)
let strUB = String.Index(utf16Indices[location+length], within: str)
let substrUB = String.Index(utf16Indices[location+length], within: substr)
expectEqual(strLB, substrLB)
expectEqual(strUB, substrUB)
let nsRange = NSRange(location: location, length: length)
let strRange = Range<String.Index>(nsRange, in: str)
let substrRange = Range<String.Index>(nsRange, in: substr)
expectEqual(strRange, substrRange)
guard strLB != nil && strUB != nil else {
expectNil(strRange)
continue
}
expectEqual(strRange, Range(uncheckedBounds: (strLB!, strUB!)))
}
}
}
#endif
#if _runtime(_ObjC)
suite.test("Misaligned") {
// Misaligned indices were fixed in 5.1
guard _hasSwift_5_1() else { return }
func doIt(_ str: String) {
let characterIndices = Array(str.indices)
let scalarIndices = Array(str.unicodeScalars.indices) + [str.endIndex]
let utf8Indices = Array(str.utf8.indices)
var lastScalarI = 0
for i in 1..<utf8Indices.count {
let idx = utf8Indices[i]
// Skip aligned indices
guard idx < scalarIndices[lastScalarI + 1] else {
assert(idx == scalarIndices[lastScalarI + 1])
lastScalarI += 1
continue
}
expectTrue(UTF8.isContinuation(str.utf8[idx]))
let lastScalarIdx = scalarIndices[lastScalarI]
// Check aligning-down
expectEqual(str[lastScalarIdx], str[idx])
expectEqual(str.utf16[lastScalarIdx], str.utf16[idx])
expectEqual(str.unicodeScalars[lastScalarIdx], str.unicodeScalars[idx])
// Check distance
let (start, end) = (str.startIndex, str.endIndex)
if characterIndices.contains(lastScalarIdx) {
expectEqual(0, str.distance(from: lastScalarIdx, to: idx))
expectEqual(str[..<idx].count, str.distance(from: start, to: idx))
expectEqual(str[idx...].count, str.distance(from: idx, to: end))
}
expectEqual(
0, str.unicodeScalars.distance(from: lastScalarIdx, to: idx))
expectEqual(
str.unicodeScalars[..<idx].count,
str.unicodeScalars.distance(from: start, to: idx))
expectEqual(
str.unicodeScalars[idx...].count,
str.unicodeScalars.distance(from: idx, to: end))
expectEqual(0, str.utf16.distance(from: lastScalarIdx, to: idx))
expectEqual(
str.utf16[..<idx].count, str.utf16.distance(from: start, to: idx))
expectEqual(
str.utf16[idx...].count, str.utf16.distance(from: idx, to: end))
}
}
let nsstring: NSString = "aодиde\u{301}日🧟♀️"
doIt(nsstring as String)
let string = "aодиde\u{301}日🧟♀️"
doIt(string)
}
#endif
let _examples: [StaticString] = [
"abc\r\ndefg",
"ab\r\ncдe\u{301}日🧟♀️x🧟x🏳️🌈🇺🇸🇨🇦",
]
let examples: [String] = _examples.flatMap { s in
let str = "\(s)"
#if _runtime(_ObjC)
let unichars = Array(str.utf16)
let nsstr = NSString(characters: unichars, length: unichars.count)
return [str, nsstr as String]
#else
return [str]
#endif
}
suite.test("Trivial index conversion cases/characters")
.forEach(in: examples) { s in
for i in s.indices {
let j = String.Index(i, within: s)
expectNotNil(j, "i: \(i)")
expectEqual(j, i)
}
}
suite.test("Trivial index conversion cases/scalars")
.forEach(in: examples) { s in
for i in s.unicodeScalars.indices {
let j = String.Index(i, within: s.unicodeScalars)
expectNotNil(j, "i: \(i)")
expectEqual(j, i)
}
}
suite.test("Trivial index conversion cases/UTF-8")
.forEach(in: examples) { s in
for i in s.utf8.indices {
let j = String.Index(i, within: s.utf8)
expectNotNil(j, "i: \(i)")
expectEqual(j, i)
}
}
suite.test("Trivial index conversion cases/UTF-16")
.forEach(in: examples) { s in
guard #available(SwiftStdlib 5.7, *) else {
// Prior to 5.7, String.Index.init(_:within:) used to incorrectly reject
// indices pointing to trailing surrogates.
return
}
for i in s.utf16.indices {
let j = String.Index(i, within: s.utf16)
expectNotNil(j, "i: \(i)")
expectEqual(j, i)
}
}
#if _runtime(_ObjC)
suite.test("Exhaustive Index Interchange")
.forEach(in: examples) { str in
guard #available(SwiftStdlib 5.1, *) else {
return
}
//str.dumpIndices()
var curCharIdx = str.startIndex
var curScalarIdx = str.startIndex
var curUTF8Idx = str.startIndex
var curUTF16Idx = str.startIndex
while curCharIdx < str.endIndex {
let curChar = str[curCharIdx]
expectEqual(curChar, str[curScalarIdx])
expectEqual(curChar, str[curUTF8Idx])
expectEqual(curChar, str[curUTF16Idx])
// Advance the character index once and have the scalar index catch up
str.formIndex(after: &curCharIdx)
let scalarStartIdx = curScalarIdx
defer {
let sub = str[scalarStartIdx..<curScalarIdx]
expectEqual(sub.count, 1)
expectEqual(sub.first, curChar)
expectEqual(str.distance(from: scalarStartIdx, to: curScalarIdx), 1)
}
while curScalarIdx < curCharIdx {
let scalarStartIdx = curScalarIdx
let curScalar = str.unicodeScalars[curScalarIdx]
let curSubChar = str[curScalarIdx]
// If there is a Character prior to this scalar, remember it and check
// that misaligned code unit indices also produce it.
let scalarPriorCharacter: Character?
if scalarStartIdx == str.startIndex {
scalarPriorCharacter = nil
} else {
scalarPriorCharacter = str[str.index(before: scalarStartIdx)]
}
// Advance the scalar index once and have the code unit indices catch up
str.unicodeScalars.formIndex(after: &curScalarIdx)
let utf8StartIdx = curUTF8Idx
defer {
let sub = str.unicodeScalars[utf8StartIdx..<curUTF8Idx]
expectEqual(sub.count, 1)
expectEqual(sub.first, curScalar)
expectEqual(
str.unicodeScalars.distance(from: utf8StartIdx, to: curUTF8Idx),
1)
expectEqual(
str.utf8.distance(from: utf8StartIdx, to: curUTF8Idx),
curScalar.utf8.count)
}
while curUTF8Idx < curScalarIdx {
expectEqual(curScalar, str.unicodeScalars[curUTF8Idx])
expectEqual(curSubChar, str[curUTF8Idx])
expectFalse(UTF16.isTrailSurrogate(str.utf16[curUTF8Idx]))
expectEqual(utf8StartIdx, str[curUTF8Idx...].startIndex)
expectTrue(str[utf8StartIdx..<curUTF8Idx].isEmpty)
expectEqual(str.utf16.distance(from: utf8StartIdx, to: curUTF8Idx), 0)
if let scalarPrior = scalarPriorCharacter {
expectEqual(scalarPrior, str[str.index(before: curUTF8Idx)])
}
str.utf8.formIndex(after: &curUTF8Idx)
}
expectEqual(curUTF8Idx, curScalarIdx)
var utf8RevIdx = curUTF8Idx
while utf8RevIdx > utf8StartIdx {
str.utf8.formIndex(before: &utf8RevIdx)
expectEqual(curScalar, str.unicodeScalars[utf8RevIdx])
expectEqual(curSubChar, str[utf8RevIdx])
expectFalse(UTF16.isTrailSurrogate(str.utf16[utf8RevIdx]))
expectEqual(utf8StartIdx, str[utf8RevIdx...].startIndex)
expectTrue(str[utf8StartIdx..<utf8RevIdx].isEmpty)
expectEqual(str.utf16.distance(from: utf8StartIdx, to: utf8RevIdx), 0)
}
expectEqual(utf8RevIdx, utf8StartIdx)
let utf16StartIdx = curUTF16Idx
defer {
let sub = str.unicodeScalars[utf16StartIdx..<curUTF16Idx]
expectEqual(sub.count, 1)
expectEqual(sub.first, curScalar)
expectEqual(
str.unicodeScalars.distance(from: utf16StartIdx, to: curUTF16Idx),
1)
expectEqual(
str.utf16.distance(from: utf16StartIdx, to: curUTF16Idx),
curScalar.utf16.count)
}
while curUTF16Idx < curScalarIdx {
expectEqual(curScalar, str.unicodeScalars[curUTF16Idx])
expectEqual(curSubChar, str[curUTF16Idx])
expectFalse(UTF8.isContinuation(str.utf8[curUTF16Idx]))
expectEqual(utf16StartIdx, str[curUTF16Idx...].startIndex)
expectTrue(str[utf16StartIdx..<curUTF16Idx].isEmpty)
expectEqual(str.utf8.distance(from: utf16StartIdx, to: curUTF16Idx), 0)
if let scalarPrior = scalarPriorCharacter {
expectEqual(scalarPrior, str[str.index(before: curUTF16Idx)])
}
str.utf16.formIndex(after: &curUTF16Idx)
}
expectEqual(curUTF16Idx, curScalarIdx)
var utf16RevIdx = curUTF16Idx
while utf16RevIdx > utf16StartIdx {
str.utf16.formIndex(before: &utf16RevIdx)
expectEqual(curScalar, str.unicodeScalars[utf16RevIdx])
expectEqual(curSubChar, str[utf16RevIdx])
expectFalse(UTF8.isContinuation(str.utf8[utf16RevIdx]))
expectEqual(utf16StartIdx, str[utf16RevIdx...].startIndex)
expectTrue(str[utf16StartIdx..<utf16RevIdx].isEmpty)
expectEqual(str.utf8.distance(from: utf16StartIdx, to: utf16RevIdx), 0)
}
expectEqual(utf16RevIdx, utf16StartIdx)
}
}
}
#endif
func fullyExhaustiveIndexInterchange(_ string: String) {
guard #available(SwiftStdlib 5.7, *) else {
// Index navigation in 5.7 always rounds input indices down to the nearest
// Character, so that we always have a well-defined distance between
// indices, even if they aren't valid.
//
// 5.6 and below did not behave consistently in this case.
return
}
//string.dumpIndices()
let scalarMap = string.scalarMap()
let characterMap = string.characterMap()
let allIndices = string.allIndices()
func referenceCharacterDistance(
from i: String.Index, to j: String.Index
) -> Int {
let ci = characterMap[i]!
let cj = characterMap[j]!
return cj.offset - ci.offset
}
func referenceScalarDistance(
from i: String.Index, to j: String.Index
) -> Int {
let si = scalarMap[i]!
let sj = scalarMap[j]!
return sj.offset - si.offset
}
for i in allIndices {
for j in allIndices {
let characterDistance = referenceCharacterDistance(from: i, to: j)
let scalarDistance = referenceScalarDistance(from: i, to: j)
// Check distance calculations.
expectEqual(
string.distance(from: i, to: j),
characterDistance,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
""")
expectEqual(
string.unicodeScalars.distance(from: i, to: j),
scalarDistance,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
""")
if i <= j {
// The substring `string[i..<j]` does not round its bounds to
// `Character` boundaries, so it may have a different count than what
// the base string reports.
let si = scalarMap[i]!.index
let sj = scalarMap[j]!.index
let s = String.UnicodeScalarView(string.unicodeScalars[si ..< sj])
let substringDistance = String(s).count
let substring = string[i ..< j]
let subscalars = string.unicodeScalars[i ..< j]
expectEqual(substring.count, substringDistance,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
""")
// The `Character` alignment consideration above doesn't apply to
// Unicode scalars in a substring.
expectEqual(subscalars.count, scalarDistance,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
""")
// Check reachability of substring bounds.
var i = substring.startIndex
for _ in 0 ..< substringDistance {
substring.formIndex(after: &i)
}
expectEqual(i, substring.endIndex)
expectEqual(
substring.index(substring.startIndex, offsetBy: substringDistance),
substring.endIndex,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
distance: \(characterDistance)
""")
expectEqual(
substring.index(substring.endIndex, offsetBy: -substringDistance),
substring.startIndex,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
distance: \(-characterDistance)
""")
expectEqual(
subscalars.index(subscalars.startIndex, offsetBy: scalarDistance),
subscalars.endIndex,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
distance: \(scalarDistance)
""")
expectEqual(
subscalars.index(subscalars.endIndex, offsetBy: -scalarDistance),
subscalars.startIndex,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
distance: \(-scalarDistance)
""")
}
// Check `String.index(_:offsetBy:limitedBy:)`.
for limit in allIndices {
let dest = characterMap[j]!.index
let expectHit = (
characterDistance > 0 && i <= limit && dest > limit ? true
: characterDistance < 0 && i >= limit && dest < limit ? true
: false)
expectEqual(
string.index(i, offsetBy: characterDistance, limitedBy: limit),
expectHit ? nil : dest,
"""
string: \(string.debugDescription)
i: \(i)
j: \(j) (distance: \(characterDistance))
limit: \(limit)
""")
}
}
}
}
suite.test("Fully exhaustive index interchange")
.forEach(in: examples) { string in
fullyExhaustiveIndexInterchange(string)
}
#if _runtime(_ObjC)
suite.test("Fully exhaustive index interchange/GraphemeBreakTests") {
for string in graphemeBreakTests.map { $0.0 } {
fullyExhaustiveIndexInterchange(string)
}
}
#endif
suite.test("Global vs local grapheme cluster boundaries") {
guard #available(SwiftStdlib 5.7, *) else {
// Index navigation in 5.7 always rounds input indices down to the nearest
// Character, so that we always have a well-defined distance between
// indices, even if they aren't valid.
//
// 5.6 and below did not behave consistently in this case.
return
}
let str = "a🇺🇸🇨🇦b"
// U+0061 LATIN SMALL LETTER A
// U+1F1FA REGIONAL INDICATOR SYMBOL LETTER U
// U+1F1F8 REGIONAL INDICATOR SYMBOL LETTER S
// U+1F1E8 REGIONAL INDICATOR SYMBOL LETTER C
// U+1F1E6 REGIONAL INDICATOR SYMBOL LETTER A
// U+0062 LATIN SMALL LETTER B
let c = Array(str.indices) + [str.endIndex]
let s = Array(str.unicodeScalars.indices) + [str.unicodeScalars.endIndex]
let u8 = Array(str.utf8.indices) + [str.utf8.endIndex]
let u16 = Array(str.utf16.indices) + [str.utf16.endIndex]
// Index navigation must always round the input index down to the nearest
// Character.
expectEqual(str.count, 4)
expectEqual(str.index(after: c[0]), c[1])
expectEqual(str.index(after: c[1]), c[2])
expectEqual(str.index(after: c[2]), c[3])
expectEqual(str.index(after: c[3]), c[4])
expectEqual(str.index(before: c[4]), c[3])
expectEqual(str.index(before: c[3]), c[2])
expectEqual(str.index(before: c[2]), c[1])
expectEqual(str.index(before: c[1]), c[0])
// Scalars
expectEqual(str.unicodeScalars.count, 6)
expectEqual(str.index(after: s[0]), s[1])
expectEqual(str.index(after: s[1]), s[3])
expectEqual(str.index(after: s[2]), s[3]) // s[2] ≅ s[1]
expectEqual(str.index(after: s[3]), s[5])
expectEqual(str.index(after: s[4]), s[5]) // s[4] ≅ s[3]
expectEqual(str.index(after: s[5]), s[6])
expectEqual(str.index(before: s[6]), s[5])
expectEqual(str.index(before: s[5]), s[3])
expectEqual(str.index(before: s[4]), s[1]) // s[4] ≅ s[3]
expectEqual(str.index(before: s[3]), s[1])
expectEqual(str.index(before: s[2]), s[0]) // s[2] ≅ s[1]
expectEqual(str.index(before: s[1]), s[0])
// UTF-8
expectEqual(str.utf8.count, 18)
expectEqual(str.index(after: u8[0]), u8[1])
for i in 1 ..< 9 { // s[i] ≅ s[1]
expectEqual(str.index(after: u8[i]), u8[9])
}
for i in 9 ..< 17 { // s[i] ≅ s[9]
expectEqual(str.index(after: u8[i]), u8[17])
}
expectEqual(str.index(after: u8[17]), u8[18])
// UTF-16
expectEqual(str.utf16.count, 10)
expectEqual(str.index(after: u16[0]), u16[1])
expectEqual(str.index(after: u16[1]), u16[5])
expectEqual(str.index(after: u16[2]), u16[5]) // s[2] ≅ s[1]
expectEqual(str.index(after: u16[3]), u16[5]) // s[3] ≅ s[1]
expectEqual(str.index(after: u16[4]), u16[5]) // s[4] ≅ s[1]
expectEqual(str.index(after: u16[5]), u16[9])
expectEqual(str.index(after: u16[6]), u16[9]) // s[6] ≅ s[5]
expectEqual(str.index(after: u16[7]), u16[9]) // s[7] ≅ s[5]
expectEqual(str.index(after: u16[8]), u16[9]) // s[8] ≅ s[5]
expectEqual(str.index(after: u16[9]), u16[10])
let i = s[2] // second scalar of US flag
let j = s[4] // second scalar of CA flag
// However, subscripting should only round down to the nearest scalar.
// Per SE-0180, `s[i..<j]` should be the Seychelles flag (country code SC)
let slice = str[i ..< j]
expectEqual(slice, "\u{1F1F8}\u{1F1E8}")
expectEqual(slice.first, "\u{1F1F8}\u{1F1E8}" as Character)
expectEqual(slice.count, 1)
// Index navigation within the substring must work as if we were in a string
// containing exactly the same scalars. Substring bounds must be reachable,
// even if they aren't reachable in the base string.
expectEqual(slice.startIndex, i)
expectEqual(slice.endIndex, j)
expectEqual(slice.index(after: slice.startIndex), j)
expectEqual(slice.index(before: slice.endIndex), i)
expectEqual(slice.unicodeScalars.count, 2)
expectEqual(slice.utf8.count, 8)
expectEqual(slice.utf16.count, 4)
}
#if _runtime(_ObjC)
suite.test("Index encoding correction/subscripts") {
guard #available(SwiftStdlib 5.7, *) else {
// String indices did not track their encoding until 5.7.
return
}
// This tests a special case in String's index validation where we allow
// UTF-16-encoded indices to be applied to UTF-8 strings, by transcoding the
// offset of the index. Applying such indices is always an error, but it
// happens relatively often when someone is erroneously holding on to an index
// of a UTF-16-encoded bridged NSString value through a mutation. Mutating a
// bridged string converts it to a UTF-8 native string, changing the meaning
// of the offset value. (Even if the mutation wouldn't otherwise affect the
// original index.)
//
// Before 5.7, the stdlib did not track the offset encoding of String indices,
// so they simply used the UTF-16 offset to access UTF-8 storage. This
// generally produces nonsensical results, but if the string happens to be
// ASCII, then this actually did work "fine".
//
// To avoid breaking binaries that rely on this behavior, the 5.7 stdlib
// automatically converts UTF-16-encoded indices to UTF-8 when needed.
// This can be quite slow, but it always produces the "right" results.
//
// This conversion is one way only (see StringTraps.swift for the other
// direction), and it does not account for the effect of the actual mutation.
// If the mutation's effect included the data addressed by the original index,
// then we may still get nonsensical results.
var s = ("🫱🏼🫲🏽 a 🧑🏽🌾 b" as NSString) as String
//s.dumpIndices()
let originals = s.allIndices(includingEnd: false).map {
($0, s[$0], s.unicodeScalars[$0], s.utf8[$0], s.utf16[$0])
}
s.makeContiguousUTF8()
//s.dumpIndices()
for (i, char, scalar, u8, u16) in originals {
expectEqual(s[i], char, "i: \(i)")
expectEqual(s.unicodeScalars[i], scalar, "i: \(i)")
expectEqual(s.utf8[i], u8, "i: \(i)")
expectEqual(s.utf16[i], u16, "i: \(i)")
}
}
#endif
#if _runtime(_ObjC)
suite.test("Index encoding correction/conversions/characters") {
guard #available(SwiftStdlib 5.7, *) else {
// String indices did not track their encoding until 5.7.
return
}
var s = ("🫱🏼🫲🏽 a 🧑🏽🌾 b" as NSString) as String
let chars = s.indices.map { ($0, s[$0]) }
s.makeContiguousUTF8()
for (i, char) in chars {
let j = String.Index(i, within: s)
expectNotNil(j, "i: \(i)")
expectEqual(j.map { s[$0] }, char, "i: \(i)")
}
}
#endif
#if _runtime(_ObjC)
suite.test("Index encoding correction/conversions/scalars") {
guard #available(SwiftStdlib 5.7, *) else {
// String indices did not track their encoding until 5.7.
return
}
var s = ("🫱🏼🫲🏽 a 🧑🏽🌾 b" as NSString) as String
let scalars = s.unicodeScalars.indices.map { ($0, s.unicodeScalars[$0]) }
s.makeContiguousUTF8()
for (i, scalar) in scalars {
let j = String.Index(i, within: s.unicodeScalars)
expectNotNil(j, "i: \(i)")
expectEqual(j.map { s.unicodeScalars[$0] }, scalar, "i: \(i)")
}
}
#endif
#if _runtime(_ObjC)
suite.test("Index encoding correction/conversions/UTF-8") {
guard #available(SwiftStdlib 5.7, *) else {
// String indices did not track their encoding until 5.7.
return
}
var s = ("🫱🏼🫲🏽 a 🧑🏽🌾 b" as NSString) as String
let utf8Units = s.utf8.indices.map { ($0, s.utf8[$0]) }
s.makeContiguousUTF8()
for (i, u8) in utf8Units {
let j = String.Index(i, within: s.utf8)
expectNotNil(j, "i: \(i)")
expectEqual(j.map { s.utf8[$0] }, u8, "i: \(i)")
}
}
#endif
#if _runtime(_ObjC)
suite.test("Index encoding correction/conversions/UTF-16") {
guard #available(SwiftStdlib 5.7, *) else {
// String indices did not track their encoding until 5.7.
return
}
var s = ("🫱🏼🫲🏽 a 🧑🏽🌾 b" as NSString) as String
let utf16Units = s.utf16.indices.map { ($0, s.utf16[$0]) }
s.makeContiguousUTF8()
for (i, u16) in utf16Units {
let j = String.Index(i, within: s.utf16)
expectNotNil(j, "i: \(i)")
expectEqual(j.map { s.utf16[$0] }, u16, "i: \(i)")
}
}
#endif
suite.test("String.replaceSubrange index validation")
.forEach(in: examples) { string in
guard #available(SwiftStdlib 5.7, *) else {
// Index navigation in 5.7 always rounds input indices down to the nearest
// Character, so that we always have a well-defined distance between
// indices, even if they aren't valid.
//
// 5.6 and below did not behave consistently in this case.
return
}
//string.dumpIndices()
let scalarMap = string.scalarMap()
let allIndices = string.allIndices()
for i in allIndices {
for j in allIndices {
guard i <= j else { continue }
let si = scalarMap[i]!.index
let sj = scalarMap[j]!.index
// Check String.replaceSubrange(_:with:)
do {
let replacement = "x"
var expected = "".unicodeScalars
expected += string.unicodeScalars[..<si]
expected += replacement.unicodeScalars
expected += string.unicodeScalars[sj...]
var actual = string
actual.replaceSubrange(i ..< j, with: replacement)
expectEqual(actual, String(expected),
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
""")
}
// Check String.unicodeScalars.replaceSubrange(_:with:)
do {
let replacement = "x".unicodeScalars
var expected = "".unicodeScalars
expected += string.unicodeScalars[..<si]
expected += replacement
expected += string.unicodeScalars[sj...]
var actual = string
actual.unicodeScalars.replaceSubrange(i ..< j, with: replacement)
expectEqual(actual, String(expected),
"""
string: \(string.debugDescription)
i: \(i)
j: \(j)
""")
}
}
}
}
| apache-2.0 | 230260cbb56618d3aa6480b205a92224 | 31.484688 | 84 | 0.64376 | 3.527867 | false | false | false | false |
jpush/jchat-swift | JChat/Src/ChatModule/Input/InputView/Emoticon/JCEmoticonGroup.swift | 1 | 614 | //
// JCEmoticonGroup.swift
// JChat
//
// Created by JIGUANG on 2017/3/9.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
public enum JCEmoticonType: Int {
case small = 0
case large = 1
public var isSmall: Bool {
return self == .small
}
public var isLarge: Bool {
return self == .large
}
}
open class JCEmoticonGroup: NSObject {
open lazy var id: String = UUID().uuidString
open var title: String?
open var thumbnail: UIImage?
open var type: JCEmoticonType = .small
open var emoticons: [JCEmoticon] = []
}
| mit | 2056e2c2bc8bdb97d9f1ab0802e13f8d | 17.515152 | 48 | 0.612111 | 3.771605 | false | false | false | false |
peaks-cc/iOS11_samplecode | chapter_02/02_PlaneDetection/PlaneDetection/ViewController.swift | 1 | 3240 | //
// ViewController.swift
// PlaneDetection
//
// Created by Shuichi Tsutsumi on 2017/07/17.
// Copyright © 2017 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.session.delegate = self
// シーンを生成してARSCNViewにセット
sceneView.scene = SCNScene()
// セッションのコンフィギュレーションを生成
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
// セッション開始
sceneView.session.run(configuration)
}
// MARK: - ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()}
print("anchor:\(anchor), node: \(node), node geometry: \(String(describing: node.geometry))")
// 平面ジオメトリを作成
let geometry = SCNPlane(width: CGFloat(planeAnchor.extent.x),
height: CGFloat(planeAnchor.extent.z))
geometry.materials.first?.diffuse.contents = UIColor.yellow.withAlphaComponent(0.5)
// 平面ジオメトリを持つノードを作成
let planeNode = SCNNode(geometry: geometry)
planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1, 0, 0)
DispatchQueue.main.async(execute: {
// 検出したアンカーに対応するノードに子ノードとして持たせる
node.addChildNode(planeNode)
})
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()}
DispatchQueue.main.async(execute: {
// 平面ジオメトリのサイズを更新
for childNode in node.childNodes {
guard let plane = childNode.geometry as? SCNPlane else {continue}
plane.width = CGFloat(planeAnchor.extent.x)
plane.height = CGFloat(planeAnchor.extent.z)
break
}
})
}
func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
print("\(self.classForCoder)/" + #function)
}
// MARK: - ARSessionDelegate
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
print("\(self.classForCoder)/" + #function)
// 平面検出時はARPlaneAnchor型のアンカーが得られる
// guard let planeAnchors = anchors as? [ARPlaneAnchor] else {return}
// print("平面を検出: \(planeAnchors)")
}
func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {
print("\(self.classForCoder)/" + #function)
}
func session(_ session: ARSession, didRemove anchors: [ARAnchor]) {
print("\(self.classForCoder)/" + #function)
}
}
| mit | 7187f27d032b968f52f1402c9db788ea | 32.494382 | 101 | 0.621268 | 4.503021 | false | false | false | false |
austinzheng/swift | test/decl/class/classes.swift | 42 | 2499 | // RUN: %target-typecheck-verify-swift -parse-as-library
class B : A {
override init() { super.init() }
override func f() {}
func g() -> (B, B) { return (B(), B()) } // expected-error {{declaration 'g()' cannot override more than one superclass declaration}}
override func h() -> (A, B) { return (B(), B()) } // expected-note {{'h()' previously overridden here}}
override func h() -> (B, A) { return (B(), B()) } // expected-error {{'h()' has already been overridden}}
func i() {} // expected-error {{overri}}
override func j() -> Int { return 0 }
func j() -> Float { return 0.0 }
func k() -> Float { return 0.0 }
override func l(_ l: Int) {}
override func l(_ l: Float) {}
override func m(_ x: Int) {}
func m(_ x: Float) {} // not an override of anything
func n(_ x: Float) {}
override subscript(i : Int) -> Int {
get {}
set {}
}
}
class A {
init() { }
func f() {}
func g() -> (B, A) { return (B(), B()) } // expected-note{{overridden declaration is here}}
func g() -> (A, B) { return (B(), B()) } // expected-note{{overridden declaration is here}}
func h() -> (A, A) { return (B(), B()) }
func j() -> Int { return 0 }
func k() -> Int { return 0 }
func l(_ l: Int) {}
func l(_ l: Float) {}
func m(_ x: Int) {}
func m(y: Int) {}
func n(_ x: Int) {}
subscript(i : Int) -> Int {
get {}
set {}
}
}
extension A {
func i() {} // expected-note{{overri}}
}
func f() {
let x = B()
_ = x.f() as ()
_ = x[10] as Int
}
class C<T> {
init() { }
func f(_ v: T) -> T { return v }
}
class D : C<Int> {
override init() { super.init() }
override func f(_ v: Int) -> Int { return v+1 }
}
func f2() {
let x = D()
_ = x.f(10)
}
class E<T> {
func f(_ v: T) -> T { return v }
}
class F : E<Int> {}
class G : F {
override func f(_ v: Int) -> Int { return v+1 }
}
// Explicit downcasting
func test_explicit_downcasting(_ f: F, ei: E<Int>) {
var g = f as! G
g = ei as! G
_ = g
}
// Type and instance functions with the same name
class H {
func f(_ x: Int) { }
class func f(_ x: Int) { }
}
class HDerived : H {
override func f(_ x: Int) { }
override class func f(_ x: Int) { }
}
// Subclass existentials in inheritance clause
protocol P {}
protocol Q {}
protocol R {}
class Base : Q & R {}
class Derived : P & Base {}
func f(_: P) {}
func g(_: Base) {}
func h(_: Q) {}
func i(_: R) {}
func testSubclassExistentialsInInheritanceClause() {
f(Derived())
g(Derived())
h(Derived())
i(Derived())
}
| apache-2.0 | 7c9503c7d28819e165c310f94cc3af2b | 22.35514 | 135 | 0.540616 | 2.953901 | false | false | false | false |
Avtolic/ACAlertController | ACAlertController/ACAlertControllerCore.swift | 1 | 20847 | //
// ACAlertControllerCore.swift
// ACAlertControllerDemo
//
// Created by Yury on 21/09/16.
// Copyright © 2016 Avtolic. All rights reserved.
//
import Foundation
import UIKit
public var alertLinesColor = UIColor(red:220/256, green:220/256, blue:224/256, alpha:1.0)
public protocol ACAlertListViewProtocol {
var contentHeight: CGFloat { get }
var view: UIView { get }
}
public protocol ACAlertListViewProvider {
func set(alertView: UIView, itemsView: UIView?, actionsView: UIView?, callBlock: @escaping (ACAlertActionProtocolBase) -> Void) -> Void
func alertView(items : [ACAlertItemProtocol], width: CGFloat) -> ACAlertListViewProtocol
func alertView(actions : [ACAlertActionProtocolBase], width: CGFloat) -> ACAlertListViewProtocol
}
open class StackViewProvider: NSObject, ACAlertListViewProvider, UIGestureRecognizerDelegate {
open func alertView(items: [ACAlertItemProtocol], width: CGFloat) -> ACAlertListViewProtocol {
let views = items.map { $0.alertItemView }
return ACStackAlertListView(views: views, width: width)
}
open func alertView(actions: [ACAlertActionProtocolBase], width: CGFloat) -> ACAlertListViewProtocol {
buttonsAndActions = actions.map { (buttonView(action: $0), $0) }
let views = buttonsAndActions.map { $0.0 }
if views.count == 2 {
let button1 = views[0]
let button2 = views[1]
button1.layoutIfNeeded()
button2.layoutIfNeeded()
let maxReducedWidth = (width - 1) / 2
if button1.bounds.width < maxReducedWidth && button2.bounds.width < maxReducedWidth
{
Layout.set(width: maxReducedWidth, view: button1)
Layout.set(width: maxReducedWidth, view: button2)
return ACStackAlertListView3(views: [button1, separatorView2(), button2], width: width)
}
}
let views2 = views.flatMap { [$0, separatorView()] }.dropLast()
return ACStackAlertListView2(views: Array(views2), width: width)
}
open var actionsView: UIView!
open var callBlock:((ACAlertActionProtocolBase) -> Void)!
open func set(alertView: UIView, itemsView: UIView?, actionsView: UIView?, callBlock:@escaping (ACAlertActionProtocolBase) -> Void) -> Void {
self.actionsView = actionsView
self.callBlock = callBlock
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleRecognizer))
recognizer.minimumPressDuration = 0.0
recognizer.allowableMovement = CGFloat.greatestFiniteMagnitude
recognizer.cancelsTouchesInView = false
recognizer.delegate = self
if let superRecognizers = actionsView?.gestureRecognizers {
for r in superRecognizers {
recognizer.require(toFail: r)
}
}
if let superRecognizers = itemsView?.gestureRecognizers {
for r in superRecognizers {
recognizer.require(toFail: r)
}
}
alertView.addGestureRecognizer(recognizer)
}
open var buttonsAndActions: [(UIView, ACAlertActionProtocolBase)] = []
open var buttonHighlightColor = UIColor(white: 0.9, alpha: 1)
// MARK: Touch recogniser
@objc open func handleRecognizer(_ recognizer: UILongPressGestureRecognizer) {
let point = recognizer.location(in: actionsView)
for (button, action) in buttonsAndActions
{
let isActive = button.frame.contains(point) && action.enabled
let isHighlighted = isActive && (recognizer.state == .began || recognizer.state == .changed)
button.backgroundColor = isHighlighted ? buttonHighlightColor : UIColor.clear
action.highlight(isHighlighted)
if isActive && recognizer.state == .ended {
callBlock(action)
}
}
}
open var buttonsMargins = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) // Applied to buttons
open var defaultButtonHeight: CGFloat = 45
open func buttonView(action: ACAlertActionProtocolBase) -> UIView {
let actionView = action.alertView
actionView.translatesAutoresizingMaskIntoConstraints = false
actionView.isUserInteractionEnabled = false
let button = UIView()
button.layoutMargins = buttonsMargins
button.addSubview(actionView)
button.translatesAutoresizingMaskIntoConstraints = false
Layout.setInCenter(view: button, subview: actionView, margins: true)
Layout.setOptional(height: defaultButtonHeight, view: button)
return button
}
open func separatorView() -> UIView {
let view = UIView()
view.backgroundColor = alertLinesColor
view.translatesAutoresizingMaskIntoConstraints = false
Layout.set(height: 0.5, view: view)
return view
}
open func separatorView2() -> UIView {
let view = UIView()
view.backgroundColor = alertLinesColor
view.translatesAutoresizingMaskIntoConstraints = false
Layout.set(width: 0.5, view: view)
return view
}
}
open class ACStackAlertListView: ACAlertListViewProtocol {
public var view: UIView { return scrollView }
public var contentHeight: CGFloat
open let stackView: UIStackView
open let scrollView = UIScrollView()
open var margins = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
public init(views: [UIView], width: CGFloat) {
stackView = UIStackView(arrangedSubviews: views )
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .equalSpacing
stackView.spacing = 0
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
Layout.setEqual(view:scrollView, subview: stackView, margins: false)
Layout.set(width: width, view: stackView)
stackView.layoutMargins = margins
stackView.isLayoutMarginsRelativeArrangement = true
contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}
}
open class ACStackAlertListView2: ACAlertListViewProtocol {
open var view: UIView { return scrollView }
open var contentHeight: CGFloat
open let stackView: UIStackView
open let scrollView = UIScrollView()
open var margins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public init(views: [UIView], width: CGFloat) {
stackView = UIStackView(arrangedSubviews: views )
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .equalSpacing
stackView.spacing = 0
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
Layout.setEqual(view:scrollView, subview: stackView, margins: false)
Layout.set(width: width, view: stackView)
stackView.layoutMargins = margins
stackView.isLayoutMarginsRelativeArrangement = true
contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}
}
open class ACStackAlertListView3: ACAlertListViewProtocol {
open var view: UIView { return scrollView }
open var contentHeight: CGFloat
open let stackView: UIStackView
open let scrollView = UIScrollView()
open var margins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public init(views: [UIView], width: CGFloat) {
stackView = UIStackView(arrangedSubviews: views )
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .equalSpacing
stackView.spacing = 0
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
Layout.setEqual(view:scrollView, subview: stackView, margins: false)
Layout.set(width: width, view: stackView)
stackView.layoutMargins = margins
stackView.isLayoutMarginsRelativeArrangement = true
contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}
}
open class ACAlertController : UIViewController{
fileprivate(set) open var items: [ACAlertItemProtocol] = []
fileprivate(set) open var actions: [ACAlertActionProtocolBase] = []
// open var items: [ACAlertItemProtocol] { return items.map{ $0.0 } }
// fileprivate(set) open var actions: [ACAlertActionProtocol] = []
open var backgroundColor = UIColor(white: 250/256, alpha: 1)
open var viewMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)//UIEdgeInsets(top: 15, bottom: 15)
// open var defaultItemsMargins = UIEdgeInsets(top: 2, left: 0, bottom: 2, right: 0) // Applied to items
// open var itemsMargins = UIEdgeInsets(top: 4, bottom: 4)
// open var actionsMargins = UIEdgeInsets(top: 4, bottom: 4)
open var alertWidth: CGFloat = 270
open var cornerRadius: CGFloat = 16
open var separatorHeight: CGFloat = 0.5
open var alertListsProvider: ACAlertListViewProvider = StackViewProvider()
open var itemsAlertList: ACAlertListViewProtocol?
open var actionsAlertList: ACAlertListViewProtocol?
open var separatorView: UIView = {
let view = UIView()
view.backgroundColor = alertLinesColor
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// MARK: Public methods
public init() {
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .overFullScreen
transitioningDelegate = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func addItem(_ item: ACAlertItemProtocol) {
guard isBeingPresented == false else {
print("ACAlertController could not be modified if it is already presented")
return
}
items.append(item)
}
open func addAction(_ action: ACAlertActionProtocolBase) {
guard isBeingPresented == false else {
print("ACAlertController could not be modified if it is already presented")
return
}
actions.append(action)
}
override open func loadView() {
view = UIView()
view.backgroundColor = backgroundColor
view.layer.cornerRadius = cornerRadius
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.masksToBounds = true
Layout.set(width: alertWidth, view: view)
// Is needed because of layoutMargins http://stackoverflow.com/questions/27421469/setting-layoutmargins-of-uiview-doesnt-work
let contentView = UIView()
view.addSubview(contentView)
contentView.layoutMargins = viewMargins
contentView.translatesAutoresizingMaskIntoConstraints = false
Layout.setEqual(view: view, subview: contentView, margins: false)
setContentView(view: contentView)
}
open func setContentView(view: UIView) {
if hasItems {
itemsAlertList = alertListsProvider.alertView(items: items, width: alertWidth - viewMargins.leftPlusRight)
}
if hasActions {
actionsAlertList = alertListsProvider.alertView(actions: actions, width: alertWidth - viewMargins.leftPlusRight)
}
let (height1, height2) = elementsHeights()
if let h = height1, let v = itemsAlertList?.view {
Layout.set(height: h, view: v)
}
if let h = height2, let v = actionsAlertList?.view {
Layout.set(height: h, view: v)
}
if let topSubview = itemsAlertList?.view ?? actionsAlertList?.view {
view.addSubview(topSubview)
Layout.setEqualTop(view: view, subview: topSubview, margins: true)
Layout.setEqualLeftAndRight(view: view, subview: topSubview, margins: true)
if let bottomSubview = actionsAlertList?.view, bottomSubview !== topSubview {
view.addSubview(separatorView)
Layout.setBottomToTop(topView: topSubview, bottomView: separatorView)
Layout.setEqualLeftAndRight(view: view, subview: separatorView, margins: true)
Layout.set(height: separatorHeight, view: separatorView)
view.addSubview(bottomSubview)
Layout.setBottomToTop(topView: separatorView, bottomView: bottomSubview)
Layout.setEqualLeftAndRight(view: view, subview: bottomSubview, margins: true)
Layout.setEqualBottom(view: view, subview: bottomSubview, margins: true)
} else {
Layout.setEqualBottom(view: view, subview: topSubview, margins: true)
}
}
alertListsProvider.set(alertView: view, itemsView: itemsAlertList?.view, actionsView: actionsAlertList?.view) { (action) in
self.presentingViewController?.dismiss(animated: true, completion: {
DispatchQueue.main.async(execute: {
action.call()
})
})
}
}
open var hasItems: Bool { return items.count > 0 }
open var hasActions: Bool { return actions.count > 0 }
open var maxViewHeight: CGFloat { return UIScreen.main.bounds.height - 80 }
open func elementsHeights() -> (itemsHeight: CGFloat?, actionsHeight: CGFloat?) {
let max = maxViewHeight - viewMargins.topPlusBottom
switch (itemsAlertList?.contentHeight, actionsAlertList?.contentHeight) {
case (nil, nil):
return (nil, nil)
case (.some(let height1), nil):
return (min(height1, max), nil)
case (nil, .some(let height2)):
return (nil, min(height2, max))
case (.some(let height1), .some(let height2)):
let max2 = max - separatorHeight
if max2 >= height1 + height2 {
return (height1, height2)
} else if height1 < max2 * 0.75 {
return (height1, max2 - height1)
} else if height2 < max2 * 0.75 {
return (max2 - height2, height2)
}
return (max2 / 2, max2 / 2)
}
}
}
extension ACAlertController: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ACAlertControllerAnimatedTransitioningBase(appearing: true)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ACAlertControllerAnimatedTransitioningBase(appearing: false)
}
}
open class Layout {
open static var nonMandatoryConstraintPriority: UILayoutPriority = 700 // Item's and action's constraints that could conflict with ACAlertController constraints should have priorities in [nonMandatoryConstraintPriority ..< 1000] range.
open class func set(width: CGFloat, view: UIView) {
NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width).isActive = true
}
open class func set(height: CGFloat, view: UIView) {
NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height).isActive = true
}
open class func setOptional(height: CGFloat, view: UIView) {
let constraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
constraint.priority = nonMandatoryConstraintPriority
constraint.isActive = true
}
open class func setOptional(width: CGFloat, view: UIView) {
let constraint = NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)
constraint.priority = nonMandatoryConstraintPriority
constraint.isActive = true
}
open class func setInCenter(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .leadingMargin : .leading, relatedBy: .lessThanOrEqual, toItem: subview, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .trailingMargin : .trailing, relatedBy: .greaterThanOrEqual, toItem: subview, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .lessThanOrEqual, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin : .bottom, relatedBy: .greaterThanOrEqual, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
let centerX = NSLayoutConstraint(item: view, attribute: margins ? .centerXWithinMargins : .centerX, relatedBy: .equal, toItem: subview, attribute: .centerX, multiplier: 1, constant: 0)
centerX.priority = nonMandatoryConstraintPriority
centerX.isActive = true
let centerY = NSLayoutConstraint(item: view, attribute: margins ? .centerYWithinMargins : .centerY, relatedBy: .equal, toItem: subview, attribute: .centerY, multiplier: 1, constant: 0)
centerY.priority = nonMandatoryConstraintPriority
centerY.isActive = true
}
open class func setEqual(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .leftMargin : .left, relatedBy: .equal, toItem: subview, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .rightMargin : .right, relatedBy: .equal, toItem: subview, attribute: .right, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .equal, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin: .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
}
open class func setEqualLeftAndRight(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .leftMargin : .left, relatedBy: .equal, toItem: subview, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .rightMargin : .right, relatedBy: .equal, toItem: subview, attribute: .right, multiplier: 1, constant: 0).isActive = true
}
open class func setEqualTop(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .equal, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true
}
open class func setEqualBottom(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin : .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
}
open class func setBottomToTop(topView: UIView, bottomView: UIView) {
NSLayoutConstraint(item: topView, attribute: .bottom, relatedBy: .equal, toItem: bottomView, attribute: .top, multiplier: 1, constant: 0).isActive = true
}
}
public extension UIEdgeInsets {
public var topPlusBottom: CGFloat { return top + bottom }
public var leftPlusRight: CGFloat { return left + right }
public init(top: CGFloat, bottom: CGFloat) {
self.init(top: top, left: 0, bottom: bottom, right: 0)
}
}
| mit | b862ddb198a9d421db50b7d5a0223eaf | 41.456212 | 239 | 0.659359 | 4.93981 | false | false | false | false |
caodong1991/SwiftStudyNote | Swift.playground/Pages/27 - AdvancedOperators.xcplaygroundpage/Contents.swift | 1 | 8803 | import Foundation
// 高级运算符
// 位运算符
/*
位运算符可以操作数据结构中每个独立的比特位。
*/
// 按位取反运算符
/*
~: 按位取反运算符,对一个数值的全部比特位进行取反。
按位取反运算符是一个前缀运算符,直接放在运算数之前,并且它们之间不能添加任何空格。
*/
let initialBits: UInt8 = 0b0000_1111
let invertedBits = ~initialBits // 等于 0b1111_0000
// 按位与运算符
/*
&: 按位与运算符,对两个数的比特位进行合并。
返回一个新的数,只有两个数的对应位都为1的时候,新数对应位才为1。
*/
let firstSixBits: UInt8 = 0b1111_1100
let lastSixBits: UInt8 = 0b0011_1111
let middleFourBits = firstSixBits & lastSixBits // 等于0b0011_1100
// 按位或运算符
/*
|: 按位或运算符,可以对两个数的比特位进行比较。
返回一个新的数,只要两个数的对应位中有任意一个为1时,新数的对应位就为1。
*/
let someBits: UInt8 = 0b1011_0010
let moreBits: UInt8 = 0b0101_1110
let combinedBits = someBits | moreBits // 等于 0b1111_1110
// 按位异或运算符
/*
^: 按位异或运算符,可以对两个数的比特位进行比较。
返回一个新的数,当两个数的对应位不相同时,新数的对应位就为1,并且对应位相同时则为0。
*/
let firstBits: UInt8 = 0b0001_0100
let otherBits: UInt8 = 0b0000_0101
let outputBits = firstBits ^ otherBits // 0b0001_0001
// 按位左移、按位右移运算符
/*
<<: 按位左移运算符 >>: 按位右移运算符
可以对一个数的所有位进行指定位数的左移和右移。
对一个数进行按位左移或按位右移,相当于对这个数进行乘以2或除以2的运算。
将一个整数左移一位,等价于将这个数乘以2。
将一个整数右移一位,等价于将这个数除以2。
*/
// 无符号整数的移位运算
/*
规则:
1. 已存在的为按指定的位数进行左移和右移。
2. 任何因移动而超出整型存储范围的位都会被丢弃。
3. 用0来填充移位后产生的空白位。
这种方法称为逻辑移位。
*/
let shiftBits: UInt8 = 4 // 即二进制的 0b0000_0100
shiftBits << 1 // 0b0000_1000
shiftBits << 2 // 0b0001_0000
shiftBits << 5 // 0b1000_0000
shiftBits << 6 // 0b0000_0000
shiftBits >> 2 // 0b0000_0010
/*
可以使用移位运算符对其他的数据类型进行编码和解码
*/
let pink: UInt32 = 0xCC6699 // 粉色的颜色值:#CC6699
let redComponent = (pink & 0xFF0000) >> 16 // 0xCC, 即204
let greenComponent = (pink & 0x00FF00) >> 8 // 0x66, 即102
let blueComponent = pink & 0x0000FF // 0x99, 即153
// 有符号整数的移位运算
/*
有符号整数使用第1个比特位,通常被称为符号位,来表示这个数的正负。
符号位为0代表正数,为1代表负数。
其余的比特位,通常称为数值位,存储了实际的值。
有符号正整数和无符号数的存储方式是一样的,都是从0开始算起。
负数的存储方式略有不同。它存储2的n次方减去其实际值的绝对值,这里的n是数值位的位数。
负数的表示通常被称为二进制补码,用这种方法来表示负数乍看起来有点奇怪,但它有几个优点。
1. 如果想对-1和-4进行加法预算,我们只需要对这两个数的全部8个比特位执行标准的二进制相加,包括符号位,
并且将计算结果中超出8位的数值丢弃:
0 1111_1100 = -4
+ 0 1111_1111 = -1
= 1 1111_1011 = -5
2. 使用二进制补码可以使负数的按位左移和右移运算得到跟正数相同的效果,
即每向左移一位将自身的数值乘以2,每向右一位就将自身的数值除以2。
规则:对有符号整数进行按位右移运算时,遵循与无符号整数相同的规则,但是对于移位产生的空白位使用符号位进行填充,而不是0。
这个行为可以确保有符号整数的符号位不会因为右移运算而改变,这通常称为算术移位。
由于正数和负数的特殊存储方式,在对它们进行右移的时候,会使它们越来越接近0。
在移位的过程中保持符号位不变,意味着负整数在接近0的过程中一直保持为负。
*/
// 溢出运算符
/*
当向一个整数类型的常量或变量赋予超过它容量的值时,Swift默认会报错,而不是允许生成一个无效的数。
*/
var potenttialOverflow = Int16.max
//potenttialOverflow += 1 // 这里会报错
/*
数值溢出时采取截断处理,而非报错。
swift提供了三个溢出运算符来让系统支持整数溢出运算:
溢出加法 &+
溢出减法 &-
溢出乘法 &*
*/
// 数值溢出
/*
数值有可能出现上溢或者下溢。
*/
var unsignedOverflow = UInt8.max // 255 1111_1111
unsignedOverflow = unsignedOverflow &+ 1 // 0 1_0000_0000 只能保留8位:0000_0000
unsignedOverflow = UInt8.min // 0 0000_0000
unsignedOverflow = unsignedOverflow &- 1 // 255 0000_0000 - 0000_0001 = 1111_1111
var signedOverflow = Int8.min // -128 1000_0000
signedOverflow = signedOverflow &- 1 // 127 1000_0000 - 0000_0001 = 0111_1111
// 优先级和结合性
// 运算符函数
/*
类和结构体可以为现有的运算符提供自定义的实现,这通常被称为运算符重载。
*/
/*
二元中缀运算符。
*/
struct Vector2D {
var x = 0.0, y = 0.0
}
extension Vector2D {
static func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.y, y: left.y + right.y)
}
}
let vector = Vector2D(x: 3.0, y: 1.0)
let anothetVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anothetVector
// 前缀和后缀运算符
/*
要实现前缀或后缀运算符,需要在声明运算符函数的时候func关键字之前指定prefix或者postfix修饰符
*/
extension Vector2D {
static prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
}
let positive = Vector2D(x: 3.0, y: 4.0)
let negative = -positive
let alsoPositive = -negative
// 复合赋值运算符
/*
复合赋值运算符将赋值运算符 = 与其他运算符进行结合。
在实现的时候,需要把运算符的左参数设置成 inout类型,因为这个参数的值在运算符函数内直接被修改。
*/
extension Vector2D {
static func += (left: inout Vector2D, right: Vector2D) {
left = left + right
}
}
var original = Vector2D(x: 1.0, y: 2.0)
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
original += vectorToAdd
/*
不能对赋值运算符重载
不能对三元条件运算符重载
*/
// 等价运算符
/*
通常情况下,自定义的类和结构体没有对等价运算符进行默认实现。
等价运算符通常被称为相等运算符 == 与不等运算符 !=。
为了使用等价运算符对自定义的类型进行判等运算,需要为相等运算符提供自定义实现,实现方法与其他中缀运算符一样,并且增加对标准库Equatable协议的遵循。
*/
extension Vector2D: Equatable {
static func == (left: Vector2D, right: Vector2D) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
}
let twothree = Vector2D(x: 2.0, y: 3.0)
let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
if twothree == anotherTwoThree {
print("these two vectors are equivalent")
}
/*
多数情况下,可以使用swift提供的等价运算默认实现:
只拥有存储属性,并且它们全都遵循Equatable协议的结构体
只拥有关联类型,并且它们全都遵循Equatable协议的结构体
没有关联类型的枚举
*/
struct Vector3D: Equatable {
var x = 0.0, y = 0.0, z = 0.0
}
let twoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0)
let anotherTwoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0)
if twoThreeFour == anotherTwoThreeFour {
print("Threse two vectors are also equivalent")
}
// 自定义运算符
/*
新的运算符要是用operator关键字在全局作用域内进行定义,同时还要指定prefix、infix或者postfix修饰符。
*/
prefix operator +++
extension Vector2D {
static prefix func +++ (vector: inout Vector2D) -> Vector2D {
vector += vector
return vector
}
}
var toBeDoubled = Vector2D(x: 2.0, y: 4.0)
let afterDoubling = +++toBeDoubled
// 自定义中缀运算符的优先级
infix operator +-: AdditionPrecedence
extension Vector2D {
static func +- (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
}
let firstVector = Vector2D(x: 1.0, y: 2.0)
let secondVector = Vector2D(x: 3.0, y: 4.0)
let plusMinusVector = firstVector +- secondVector
| mit | 092e8bc1dd4f62cd3db0b53f4f0286ab | 21.771429 | 82 | 0.698154 | 2.172508 | false | false | false | false |
jmgc/swift | test/Driver/Dependencies/independent-parseable-fine.swift | 1 | 4124 | // RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/independent-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: {{^{$}}
// CHECK-FIRST-DAG: "kind"{{ ?}}: "began"
// CHECK-FIRST-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-DAG: "{{(.\\/)?}}main.swift"
// CHECK-FIRST: {{^}$}}
// CHECK-FIRST: {{^{$}}
// CHECK-FIRST: "kind"{{ ?}}: "finished"
// CHECK-FIRST: "name"{{ ?}}: "compile"
// CHECK-FIRST: "output"{{ ?}}: "Handled main.swift{{(\\r)?}}\n"
// CHECK-FIRST: {{^}$}}
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND: {{^{$}}
// CHECK-SECOND-DAG: "kind"{{ ?}}: "skipped"
// CHECK-SECOND-DAG: "name"{{ ?}}: "compile"
// CHECK-SECOND-DAG: "{{(.\\/)?}}main.swift"
// CHECK-SECOND: {{^}$}}
// RUN: touch -t 201401240006 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/independent-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST-MULTI %s
// CHECK-FIRST-MULTI: {{^{$}}
// CHECK-FIRST-MULTI-DAG: "kind"{{ ?}}: "began"
// CHECK-FIRST-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-MULTI-DAG: "{{(.\\/)?}}main.swift"
// CHECK-FIRST-MULTI: {{^}$}}
// CHECK-FIRST-MULTI: {{^{$}}
// CHECK-FIRST-MULTI-DAG: "kind"{{ ?}}: "finished"
// CHECK-FIRST-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-MULTI-DAG: "output"{{ ?}}: "Handled main.swift{{(\\r)?}}\n"
// CHECK-FIRST-MULTI: {{^}$}}
// CHECK-FIRST-MULTI: {{^{$}}
// CHECK-FIRST-MULTI-DAG: "kind"{{ ?}}: "began"
// CHECK-FIRST-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-MULTI-DAG: "{{(.\\/)?}}other.swift"
// CHECK-FIRST-MULTI: {{^}$}}
// CHECK-FIRST-MULTI: {{^{$}}
// CHECK-FIRST-MULTI-DAG: "kind"{{ ?}}: "finished"
// CHECK-FIRST-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-MULTI-DAG: "output"{{ ?}}: "Handled other.swift{{(\\r)?}}\n"
// CHECK-FIRST-MULTI: {{^}$}}
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-SECOND-MULTI %s
// CHECK-SECOND-MULTI: {{^{$}}
// CHECK-SECOND-MULTI-DAG: "kind"{{ ?}}: "skipped"
// CHECK-SECOND-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-SECOND-MULTI-DAG: "{{(.\\/)?}}main.swift"
// CHECK-SECOND-MULTI: {{^}$}}
// CHECK-SECOND-MULTI: {{^{$}}
// CHECK-SECOND-MULTI-DAG: "kind"{{ ?}}: "skipped"
// CHECK-SECOND-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-SECOND-MULTI-DAG: "{{(.\\/)?}}other.swift"
// CHECK-SECOND-MULTI: {{^}$}}
// RUN: touch -t 201401240006 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST-MULTI %s
| apache-2.0 | 53b08a980d552f4e5fb9133b0aa3acd9 | 51.871795 | 337 | 0.640155 | 3.114804 | false | false | true | false |
artkirillov/DesignPatterns | Singleton.playground/Contents.swift | 1 | 578 | final class Singleton {
static let shared = Singleton()
private init() {
}
var value: Int = 0
func doSomething() {
print("Doing something with value \(value)")
}
}
var object = Singleton.shared
object.value = 1000
var secondObject = Singleton.shared
secondObject.value = 2000
object.doSomething()
secondObject.doSomething()
print(object === secondObject)
//var thirdObject = Singleton()
//thirdObject.value = 9999
//thirdObject.doSomething()
//print(object === thirdObject)
//print(secondObject === thirdObject)
| mit | 9f4bc33635124eaad9875db1a3627185 | 17.645161 | 52 | 0.6609 | 4.158273 | false | false | false | false |
firebase/SwiftLint | Source/SwiftLintFramework/Rules/NumberSeparatorRuleExamples.swift | 2 | 2563 | //
// NumberSeparatorRuleExamples.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/29/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
internal struct NumberSeparatorRuleExamples {
static let nonTriggeringExamples: [String] = {
return ["-", "+", ""].flatMap { (sign: String) -> [String] in
[
"let foo = \(sign)100",
"let foo = \(sign)1_000",
"let foo = \(sign)1_000_000",
"let foo = \(sign)1.000_1",
"let foo = \(sign)1_000_000.000_000_1",
"let binary = \(sign)0b10000",
"let binary = \(sign)0b1000_0001",
"let hex = \(sign)0xA",
"let hex = \(sign)0xAA_BB",
"let octal = \(sign)0o21",
"let octal = \(sign)0o21_1",
"let exp = \(sign)1_000_000.000_000e2"
]
}
}()
static let triggeringExamples = makeTriggeringExamples(signs: ["↓-", "+↓", "↓"])
static let corrections = makeCorrections(signs: [("↓-", "-"), ("+↓", "+"), ("↓", "")])
private static func makeTriggeringExamples(signs: [String]) -> [String] {
return signs.flatMap { (sign: String) -> [String] in
[
"let foo = \(sign)10_0",
"let foo = \(sign)1000",
"let foo = \(sign)1000e2",
"let foo = \(sign)1000E2",
"let foo = \(sign)1__000",
"let foo = \(sign)1.0001",
"let foo = \(sign)1_000_000.000000_1",
"let foo = \(sign)1000000.000000_1"
]
}
}
private static func makeCorrections(signs: [(String, String)]) -> [String: String] {
var result = [String: String]()
for (violation, sign) in signs {
result["let foo = \(violation)10_0"] = "let foo = \(sign)100"
result["let foo = \(violation)1000"] = "let foo = \(sign)1_000"
result["let foo = \(violation)1000e2"] = "let foo = \(sign)1_000e2"
result["let foo = \(violation)1000E2"] = "let foo = \(sign)1_000E2"
result["let foo = \(violation)1__000"] = "let foo = \(sign)1_000"
result["let foo = \(violation)1.0001"] = "let foo = \(sign)1.000_1"
result["let foo = \(violation)1_000_000.000000_1"] = "let foo = \(sign)1_000_000.000_000_1"
result["let foo = \(violation)1000000.000000_1"] = "let foo = \(sign)1_000_000.000_000_1"
}
return result
}
}
| mit | e51a6b895b485969344c3f61792bc988 | 36.5 | 103 | 0.486667 | 3.517241 | false | false | false | false |
tao6/TaoAutoLayout | TaoAutoLayout/UIView+AutoLayout.swift | 1 | 14313 | //
// UIView+Extension.swift
// TaoAutoLayout
//
// Created by 刘涛 on 16/7/6.
// Copyright © 2016年 tao6. All rights reserved.
//
import UIKit
/// 对齐类型枚举,设置控件相对于父视图的位置
///
/// - TopLeft: 左上
/// - TopRight: 右上
/// - TopCenter: 中上
/// - BottomLeft: 左下
/// - BottomRight: 右下
/// - BottomCenter: 中下
/// - CenterLeft: 左中
/// - CenterRight: 右中
/// - CenterCenter: 中中
public enum tao_AlignType {
case TopLeft
case TopRight
case TopCenter
case BottomLeft
case BottomRight
case BottomCenter
case CenterLeft
case CenterRight
case CenterCenter
private func layoutAttributes(isInner: Bool, isVertical: Bool) -> tao_LayoutAttributes {
let attributes = tao_LayoutAttributes()
switch self {
case .TopLeft:
attributes.horizontals(.Left, to: .Left).verticals(.Top, to: .Top)
if isInner {
return attributes
} else if isVertical {
return attributes.verticals(.Bottom, to: .Top)
} else {
return attributes.horizontals(.Right, to: .Left)
}
case .TopRight:
attributes.horizontals(.Right, to: .Right).verticals(.Top, to: .Top)
if isInner {
return attributes
} else if isVertical {
return attributes.verticals(.Bottom, to: .Top)
} else {
return attributes.horizontals(.Left, to: .Right)
}
case .TopCenter: // 仅内部 & 垂直参照需要
attributes.horizontals(.CenterX, to: .CenterX).verticals(.Top, to: .Top)
return isInner ? attributes : attributes.verticals(.Bottom, to: .Top)
case .BottomLeft:
attributes.horizontals(.Left, to: .Left).verticals(.Bottom, to: .Bottom)
if isInner {
return attributes
} else if isVertical {
return attributes.verticals(.Top, to: .Bottom)
} else {
return attributes.horizontals(.Right, to: .Left)
}
case .BottomRight:
attributes.horizontals(.Right, to: .Right).verticals(.Bottom, to: .Bottom)
if isInner {
return attributes
} else if isVertical {
return attributes.verticals(.Top, to: .Bottom)
} else {
return attributes.horizontals(.Left, to: .Right)
}
case .BottomCenter: // 仅内部 & 垂直参照需要
attributes.horizontals(.CenterX, to: .CenterX).verticals(.Bottom, to: .Bottom)
return isInner ? attributes : attributes.verticals(.Top, to: .Bottom)
case .CenterLeft: // 仅内部 & 水平参照需要
attributes.horizontals(.Left, to: .Left).verticals(.CenterY, to: .CenterY)
return isInner ? attributes : attributes.horizontals(.Right, to: .Left)
case .CenterRight: // 仅内部 & 水平参照需要
attributes.horizontals(.Right, to: .Right).verticals(.CenterY, to: .CenterY)
return isInner ? attributes : attributes.horizontals(.Left, to: .Right)
case .CenterCenter: // 仅内部参照需要
return tao_LayoutAttributes(horizontal: .CenterX, referHorizontal: .CenterX, vertical: .CenterY, referVertical: .CenterY)
}
}
}
extension UIView {
/// 填充子视图
///
/// - parameter referView: 参考视图
/// - parameter insets: 间距
public func tao_Fill(referView: UIView, insets: UIEdgeInsets = UIEdgeInsetsZero) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var cons = [NSLayoutConstraint]()
cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-\(insets.left)-[subView]-\(insets.right)-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : self])
cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(insets.top)-[subView]-\(insets.bottom)-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : self])
superview?.addConstraints(cons)
return cons
}
/// 参照参考视图内部对齐
///
/// - parameter type: 对齐方式
/// - Parameter referView: 参考视图
/// - Parameter size: 视图大小,如果是 nil 则不设置大小
/// - Parameter offset: 偏移量,默认是 CGPoint(x: 0, y: 0)
///
/// - returns: 约束数组
public func tao_AlignInner(type type: tao_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] {
return tao_AlignLayout(referView, attributes: type.layoutAttributes(true, isVertical: true), size: size, offset: offset)
}
/// 参照参考视图垂直对齐
///
/// - parameter type: 对齐方式
/// - parameter referView: 参考视图
/// - parameter size: 视图大小,如果是 nil 则不设置大小
/// - parameter offset: 偏移量,默认是 CGPoint(x: 0, y: 0)
///
/// - returns: 约束数组
public func tao_AlignVertical(type type: tao_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] {
return tao_AlignLayout(referView, attributes: type.layoutAttributes(false, isVertical: true), size: size, offset: offset)
}
/// 参照参考视图水平对齐
///
/// - parameter type: 对齐方式
/// - parameter referView: 参考视图
/// - parameter size: 视图大小,如果是 nil 则不设置大小
/// - parameter offset: 偏移量,默认是 CGPoint(x: 0, y: 0)
///
/// - returns: 约束数组
public func tao_AlignHorizontal(type type: tao_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] {
return tao_AlignLayout(referView, attributes: type.layoutAttributes(false, isVertical: false), size: size, offset: offset)
}
/// 在当前视图内部水平平铺控件
///
/// - parameter views: 子视图数组
/// - parameter insets: 间距
///
/// - returns: 约束数组
public func tao_HorizontalTile(views: [UIView], insets: UIEdgeInsets) -> [NSLayoutConstraint] {
assert(!views.isEmpty, "views should not be empty")
var cons = [NSLayoutConstraint]()
let firstView = views[0]
firstView.tao_AlignInner(type: tao_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: insets.left, y: insets.top))
cons.append(NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -insets.bottom))
// 添加后续视图的约束
var preView = firstView
for i in 1..<views.count {
let subView = views[i]
cons += subView.tao_sizeConstraints(firstView)
subView.tao_AlignHorizontal(type: tao_AlignType.TopRight, referView: preView, size: nil, offset: CGPoint(x: insets.right, y: 0))
preView = subView
}
let lastView = views.last!
cons.append(NSLayoutConstraint(item: lastView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -insets.right))
addConstraints(cons)
return cons
}
/// 在当前视图内部垂直平铺控件
///
/// - parameter views: 子视图数组
/// - parameter insets: 间距
///
/// - returns: 约束数组
public func tao_VerticalTile(views: [UIView], insets: UIEdgeInsets) -> [NSLayoutConstraint] {
assert(!views.isEmpty, "views should not be empty")
var cons = [NSLayoutConstraint]()
let firstView = views[0]
firstView.tao_AlignInner(type: tao_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: insets.left, y: insets.top))
cons.append(NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -insets.right))
// 添加后续视图的约束
var preView = firstView
for i in 1..<views.count {
let subView = views[i]
cons += subView.tao_sizeConstraints(firstView)
subView.tao_AlignVertical(type: tao_AlignType.BottomLeft, referView: preView, size: nil, offset: CGPoint(x: 0, y: insets.bottom))
preView = subView
}
let lastView = views.last!
cons.append(NSLayoutConstraint(item: lastView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -insets.bottom))
addConstraints(cons)
return cons
}
/// 从约束数组中查找指定 attribute 的约束
///
/// - parameter constraintsList: 约束数组
/// - parameter attribute: 约束属性
///
/// - returns: attribute 对应的约束
public func tao_Constraint(constraintsList: [NSLayoutConstraint], attribute: NSLayoutAttribute) -> NSLayoutConstraint? {
for constraint in constraintsList {
if constraint.firstItem as! NSObject == self && constraint.firstAttribute == attribute {
return constraint
}
}
return nil
}
// MARK: - 私有函数
/// 参照参考视图对齐布局
///
/// - parameter referView: 参考视图
/// - parameter attributes: 参照属性
/// - parameter size: 视图大小,如果是 nil 则不设置大小
/// - parameter offset: 偏移量,默认是 CGPoint(x: 0, y: 0)
///
/// - returns: 约束数组
private func tao_AlignLayout(referView: UIView, attributes: tao_LayoutAttributes, size: CGSize?, offset: CGPoint) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var cons = [NSLayoutConstraint]()
cons += tao_positionConstraints(referView, attributes: attributes, offset: offset)
if size != nil {
cons += tao_sizeConstraints(size!)
}
superview?.addConstraints(cons)
return cons
}
/// 尺寸约束数组
///
/// - parameter size: 视图大小
///
/// - returns: 约束数组
private func tao_sizeConstraints(size: CGSize) -> [NSLayoutConstraint] {
var cons = [NSLayoutConstraint]()
cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: size.width))
cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: size.height))
return cons
}
/// 尺寸约束数组
///
/// - parameter referView: 参考视图,与参考视图大小一致
///
/// - returns: 约束数组
private func tao_sizeConstraints(referView: UIView) -> [NSLayoutConstraint] {
var cons = [NSLayoutConstraint]()
cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 0))
return cons
}
/// 位置约束数组
///
/// - parameter referView: 参考视图
/// - parameter attributes: 参照属性
/// - parameter offset: 偏移量
///
/// - returns: 约束数组
private func tao_positionConstraints(referView: UIView, attributes: tao_LayoutAttributes, offset: CGPoint) -> [NSLayoutConstraint] {
var cons = [NSLayoutConstraint]()
cons.append(NSLayoutConstraint(item: self, attribute: attributes.horizontal, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: attributes.referHorizontal, multiplier: 1.0, constant: offset.x))
cons.append(NSLayoutConstraint(item: self, attribute: attributes.vertical, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: attributes.referVertical, multiplier: 1.0, constant: offset.y))
return cons
}
}
/// 布局属性
private final class tao_LayoutAttributes {
var horizontal: NSLayoutAttribute
var referHorizontal: NSLayoutAttribute
var vertical: NSLayoutAttribute
var referVertical: NSLayoutAttribute
init() {
horizontal = NSLayoutAttribute.Left
referHorizontal = NSLayoutAttribute.Left
vertical = NSLayoutAttribute.Top
referVertical = NSLayoutAttribute.Top
}
init(horizontal: NSLayoutAttribute, referHorizontal: NSLayoutAttribute, vertical: NSLayoutAttribute, referVertical: NSLayoutAttribute) {
self.horizontal = horizontal
self.referHorizontal = referHorizontal
self.vertical = vertical
self.referVertical = referVertical
}
private func horizontals(from: NSLayoutAttribute, to: NSLayoutAttribute) -> Self {
horizontal = from
referHorizontal = to
return self
}
private func verticals(from: NSLayoutAttribute, to: NSLayoutAttribute) -> Self {
vertical = from
referVertical = to
return self
}
}
| mit | 669017dfb656c0375c9e6daa3c109529 | 38.241983 | 222 | 0.61575 | 4.427632 | false | false | false | false |
pauljohanneskraft/Math | Example/CoreMath/Cocoa/NSMenu.swift | 1 | 2155 | //
// NSMenu.swift
// Math
//
// Created by Paul Kraft on 09.12.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
import Cocoa
extension NSMenu {
static func makeAppMenuItem(for app: NSApplication, name: String) -> NSMenuItem {
let hideOthers = NSMenuItem(title: "Hide Others",
action: #selector(app.hideOtherApplications(_:)), keyEquivalent: "h")
hideOthers.keyEquivalentModifierMask = [.command, .option]
let appMenu = NSMenu(with:
[
.new(title: "About \(name)", action: nil, keyEquivalent: ""),
.separator,
.new(title: "Preferences...", action: nil, keyEquivalent: ","),
.separator,
.new(title: "Hide \(name)", action: #selector(app.hide(_:)), keyEquivalent: "h"),
.item(hideOthers),
.new(title: "Show All", action: #selector(app.unhideAllApplications(_:)), keyEquivalent: ""),
.separator,
.new(title: "Quit \(name)", action: #selector(app.terminate(_:)), keyEquivalent: "q")
]
)
let mainAppMenuItem = NSMenuItem(title: "Application", action: nil, keyEquivalent: "")
mainAppMenuItem.submenu = appMenu
return mainAppMenuItem
}
}
extension NSMenu {
convenience init(title: String = "", with items: [NSMenu.Item]) {
self.init(title: title)
addItems(items)
}
func addItems(_ items: [NSMenu.Item]) {
items.forEach { self.addItem($0.menuItem) }
}
}
extension NSMenu {
enum Item {
case separator
case new(title: String, action: Selector?, keyEquivalent: String)
case item(NSMenuItem)
var menuItem: NSMenuItem {
switch self {
case .separator:
return NSMenuItem.separator()
case let .new(title, action, keyEquivalent):
return NSMenuItem(title: title, action: action, keyEquivalent: keyEquivalent)
case let .item(item):
return item
}
}
}
}
| mit | 5a68c04d72333c3b71036b570c4c56b6 | 32.138462 | 109 | 0.553853 | 4.632258 | false | false | false | false |
FranDepascuali/ProyectoAlimentar | ProyectoAlimentar/Resources/Resource.swift | 1 | 1654 | //
// Resource.swift
// ProyectoAlimentar
//
// Created by Francisco Depascuali on 9/21/16.
// Copyright © 2016 Alimentar. All rights reserved.
//
import UIKit
public protocol Resource {
var identifier: String { get }
}
public enum ImageAssetIdentifier: String {
case OrderPin = "order_pin"
case SelectedOrderPin = "selected_order_pin"
case LoginBackgroundImage = "bg_login_ios"
case LoginLogo = "img_login_logo_pa"
case TimeOpenedIcon = "img_donation_time"
case LocationIcon = "img_donation_location"
case Chronometer = "img_chronometer"
case BigChronometer = "big_img_chronometer"
}
public enum CellIdentifier: String {
case DonationRecordCell
case ActiveDonationCell
case DonationDetailCell
}
public extension UICollectionView {
public func registerCell(_ identifier: CellIdentifier) {
register(UINib(nibName: identifier.rawValue, bundle: nil), forCellWithReuseIdentifier: identifier.rawValue)
}
public func dequeCellWithIdentifier<CellType: UICollectionViewCell>(_ identifier: CellIdentifier, forIndexPath indexPath: IndexPath) -> CellType {
return dequeueReusableCell(withReuseIdentifier: identifier.rawValue, for: indexPath) as! CellType
}
public func dequeCellWithIdentifier<CellType: UICollectionViewCell>(_ identifier: CellIdentifier, forIndexPath index: Int) -> CellType {
return dequeCellWithIdentifier(identifier, forIndexPath: IndexPath(item: index, section: 0))
}
}
public extension UIImage {
convenience init(identifier: ImageAssetIdentifier) {
self.init(named:identifier.rawValue)!
}
}
| apache-2.0 | df381f0302f144b58975f86536c9051c | 28 | 150 | 0.727768 | 4.504087 | false | false | false | false |
Yogayu/EmotionNote | EmotionNote/EmotionNote/EmotionTableViewController.swift | 1 | 7173 | //
// EmotionTableViewController.swift
// EmotionNote
//
// Created by youxinyu on 15/12/1.
// Copyright © 2015年 yogayu.github.io. All rights reserved.
//
import UIKit
class EmotionTableViewController: UITableViewController {
var notes = [Note]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = editButtonItem()
tableView.estimatedRowHeight = 90
tableView.rowHeight = UITableViewAutomaticDimension
navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: UIControlState.Normal)
navigationController?.navigationBar.titleTextAttributes = ([NSForegroundColorAttributeName : UIColor.whiteColor()])
preferredStatusBarStyle()
if let savedNotes = loadNotes() {
notes += savedNotes
} else {
loadSampleNotes()
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
func loadSampleNotes() {
let photo3 = UIImage(named: "face3")!
let note3 = Note(content: "Where's is my mom? I couldn't find her anywhere. Why life is so annoying? Oh...",emotion: "It seems that you are angry.\nAnd you feel a little neutral.", emotionPhoto: photo3, time: "15-12-05")!
let photo4 = UIImage(named: "face4")!
let note4 = Note(content: "Love me? Change me then we can be together forever.", emotion: "I know you are in a happy mood.\nAnd you feel a bit of netural.", emotionPhoto: photo4, time: "15-12-05")!
let photo5 = UIImage(named: "face5")!
let note5 = Note(content: "What are you doing here? I am going to sleep. This my sweet dream.", emotion: "Do you enjoy your surprise emotion?\nAnd you feel a little fear.", emotionPhoto: photo5, time: "15-12-04")!
let photo6 = UIImage(named: "face6")!
let note6 = Note(content: "Why? Why? Tell me why? Am I not so good? Am I saying too much? I don't want to break with you. I can't image the life without you.", emotion:"How sad you are now!\nAnd it mix with some neutral emotion.",emotionPhoto: photo6, time: "15-12-02")!
let photo7 = UIImage(named: "face7")!
let note7 = Note(content: "Life is full of adventures. Find your dream and achieve it.",emotion: "You must feel very happy.\nAnd you may also somehow in a digust mood.", emotionPhoto: photo7, time: "15-12-04")!
let photo8 = UIImage(named: "face8")!
let note8 = Note(content: "Power is everything.", emotion: "I know you are in a neutral mood.\nAnd you feel a little sad.", emotionPhoto: photo8, time: "15-12-03")!
let photo2 = UIImage(named: "face9")!
let note2 = Note(content: "My dragon,why you take me there? I am the queen. I belong to somewehere else.", emotion:"I know you are in a neutral mood.\nAnd you feel a little sad. Drasgon's mother~",emotionPhoto: photo2, time: "15-12-02")!
let photo1 = UIImage(named: "face10")!
let note1 = Note(content: "See you at the star~",emotion: "You must feel very happy.\n", emotionPhoto: photo1, time: "15-12-01")!
notes += [note3,note4,note5,note6,note7,note8,note1,note2]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Unwind
@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? EmotionViewController, note = sourceViewController.note {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing note
notes[selectedIndexPath.row] = note
tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
} else {
// Add a new note
let newIndexPath = NSIndexPath(forRow: notes.count, inSection: 0)
notes.append(note)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
// Save the note
saveNotes()
}
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail" {
let noteDetailViewController = segue.destinationViewController as! EmotionViewController
// Get the cell that generated this segue.
if let selectedNoteCell = sender as? EmotionTableViewCell {
let indexPath = tableView.indexPathForCell(selectedNoteCell)!
let selectedNote = notes[indexPath.row]
noteDetailViewController.note = selectedNote
}
}
else if segue.identifier == "AddItem" {
print("Adding new note.")
}
}
// MARK: NSCoding
func saveNotes() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(notes, toFile: Note.ArchiveURL.path!)
if !isSuccessfulSave {
print("Failed to save notes...")
}
}
func loadNotes() -> [Note]? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(Note.ArchiveURL.path!) as? [Note]
}
}
extension EmotionTableViewController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notes.count
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "EmotionTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! EmotionTableViewCell
// Fetches the appropriate meal for the data source layout.
let note = notes[indexPath.row]
cell.contentLabel.text = note.content
cell.emotionView.image = note.emotionPhoto
cell.timeLabel.text = note.time
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
notes.removeAtIndex(indexPath.row)
saveNotes()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
| mit | 0db7a9dc2e23724ea584e3900df0acf8 | 43.521739 | 278 | 0.64495 | 4.906229 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-ios | Pod/Classes/Common/Components/UserAgent.swift | 1 | 1196 | //
// WebAgent.swift
// SuperAwesome
//
// Created by Gunhan Sancar on 01/04/2020.
//
import WebKit
/**
* Class that returns the current User Agent using WKWebView object.
*/
@objc(SAUserAgentType)
public protocol UserAgentType {
@objc(name) var name: String { get }
}
@objc(SAUserAgent)
public class UserAgent: NSObject, UserAgentType {
public var name: String
private var webView: WKWebView?
private var dataRepository: DataRepositoryType
init(device: DeviceTypeObjc, dataRepository: DataRepositoryType) {
self.dataRepository = dataRepository
self.name = dataRepository.userAgent ?? device.userAgent
super.init()
evaluateUserAgent()
}
private func evaluateUserAgent() {
webView = WKWebView()
webView?.evaluateJavaScript("navigator.userAgent", completionHandler: { (result, error) in
if error != nil {
print("UserAgent.evaluateUserAgent.error:", String(describing: error))
} else if let result = result as? String {
self.name = result
self.dataRepository.userAgent = result
}
self.webView = nil
})
}
}
| lgpl-3.0 | dd30d4587f22136126e72151452803aa | 26.181818 | 98 | 0.643813 | 4.582375 | false | false | false | false |
apple/swift | test/expr/primary/literal/collection_upcast_opt.swift | 30 | 1227 | // RUN: %target-typecheck-verify-swift -dump-ast > %t.ast
// RUN: %FileCheck %s < %t.ast
// Verify that upcasts of array literals upcast the individual elements in place
// rather than introducing a collection_upcast_expr.
protocol P { }
struct X : P { }
struct TakesArray<T> {
init(_: [(T) -> Void]) { }
}
// CHECK-LABEL: func_decl{{.*}}"arrayUpcast(_:_:)"
// CHECK: assign_expr
// CHECK-NOT: collection_upcast_expr
// CHECK: array_expr type='[(X) -> Void]'
// CHECK: function_conversion_expr implicit type='(X) -> Void'
// CHECK-NEXT: {{declref_expr.*x1}}
// CHECK-NEXT: function_conversion_expr implicit type='(X) -> Void'
// CHECK-NEXT: {{declref_expr.*x2}}
func arrayUpcast(_ x1: @escaping (P) -> Void, _ x2: @escaping (P) -> Void) {
_ = TakesArray<X>([x1, x2])
}
struct TakesDictionary<T> {
init(_: [Int : (T) -> Void]) { }
}
// CHECK-LABEL: func_decl{{.*}}"dictionaryUpcast(_:_:)"
// CHECK: assign_expr
// CHECK-NOT: collection_upcast_expr
// CHECK: paren_expr type='([Int : (X) -> Void])'
// CHECK-NOT: collection_upcast_expr
// CHECK: (dictionary_expr type='[Int : (X) -> Void]'
func dictionaryUpcast(_ x1: @escaping (P) -> Void, _ x2: @escaping (P) -> Void) {
_ = TakesDictionary<X>(([1: x1, 2: x2]))
}
| apache-2.0 | 52437ce165e403e63acba86ac481147d | 31.289474 | 81 | 0.625102 | 3 | false | false | false | false |
pksprojects/ElasticSwift | Tests/ElasticSwiftQueryDSLTests/CompoundQueriesTests.swift | 1 | 9375 | //
// CompoundQuriesTests.swift
// ElasticSwiftQueryDSLTests
//
// Created by Prafull Kumar Soni on 9/2/19.
//
import Logging
import UnitTestSettings
import XCTest
@testable import ElasticSwiftCodableUtils
@testable import ElasticSwiftQueryDSL
class CompoundQueriesTest: XCTestCase {
let logger = Logger(label: "org.pksprojects.ElasticSwiftQueryDSLTests.CompoundQuriesTest", factory: logFactory)
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
super.setUp()
XCTAssert(isLoggingConfigured)
logger.info("====================TEST=START===============================")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
logger.info("====================TEST=END===============================")
}
func test_01_constantScoreQuery_encode() throws {
let query = ConstantScoreQuery(MatchAllQuery(), boost: 1.1)
let data = try! JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"constant_score\":{\"filter\":{\"match_all\":{}},\"boost\":1.1}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_02_constantScoreQuery_decode() throws {
let query = ConstantScoreQuery(MatchAllQuery(boost: 1.1), boost: 1.1)
let jsonStr = "{\"constant_score\":{\"filter\":{\"match_all\":{\"boost\":1.1}},\"boost\":1.1}}"
let decoded = try! JSONDecoder().decode(ConstantScoreQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_03_boolQuery_encode() throws {
let query = try BoolQueryBuilder()
.filter(query: MatchAllQuery())
.filter(query: MatchNoneQuery())
.must(query: MatchAllQuery())
.mustNot(query: MatchNoneQuery())
.build()
let data = try! JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"bool\":{\"filter\":[{\"match_all\":{}},{\"match_none\":{}}],\"must\":[{\"match_all\":{}}],\"must_not\":[{\"match_none\":{}}]}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_04_boolQuery_decode() throws {
let query = try BoolQueryBuilder()
.filter(query: MatchAllQuery())
.filter(query: MatchNoneQuery())
.must(query: MatchAllQuery())
.mustNot(query: MatchNoneQuery())
.build()
let jsonStr = "{\"bool\":{\"filter\":[{\"match_all\":{}},{\"match_none\":{}}],\"must\":[{\"match_all\":{}}],\"must_not\":[{\"match_none\":{}}]}}"
let decoded = try! JSONDecoder().decode(BoolQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_05_functionScoreQuery_encode() throws {
let scoreFunction = try LinearDecayFunctionBuilder()
.set(field: "date")
.set(origin: "2013-09-17")
.set(scale: "10d")
.set(offset: "5d")
.set(decay: 0.5)
.build()
let query = try FunctionScoreQueryBuilder()
.set(query: MatchAllQuery())
.add(function: scoreFunction)
.build()
let data = try! JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"function_score\":{\"query\":{\"match_all\":{}},\"functions\":[{\"linear\":{\"date\":{\"decay\":0.5,\"offset\":\"5d\",\"origin\":\"2013-09-17\",\"scale\":\"10d\"}}}]}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_06_functionScoreQuery_decode() throws {
let gaussFunction = try GaussDecayFunctionBuilder()
.set(field: "price")
.set(origin: "0")
.set(scale: "20")
.build()
let gaussFunction2 = try GaussDecayFunctionBuilder()
.set(field: "location")
.set(origin: "11, 12")
.set(scale: "2km")
.build()
let query = FunctionScoreQuery(query: MatchQuery(field: "properties", value: "balcony"), scoreMode: .multiply, functions: gaussFunction, gaussFunction2)
let jsonStr = """
{
"function_score": {
"functions": [
{
"gauss": {
"price": {
"origin": "0",
"scale": "20"
}
}
},
{
"gauss": {
"location": {
"origin": "11, 12",
"scale": "2km"
}
}
}
],
"query": {
"match": {
"properties": "balcony"
}
},
"score_mode": "multiply"
}
}
"""
let decoded = try JSONDecoder().decode(FunctionScoreQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_07_disMaxQuery_encode() throws {
let query = DisMaxQuery([TermQuery(field: "title", value: "Quick pets"), TermQuery(field: "body", value: "Quick pets")], tieBreaker: 0.7, boost: 1.0)
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"dis_max" : {
"queries" : [
{ "term" : { "title" : "Quick pets" }},
{ "term" : { "body" : "Quick pets" }}
],
"tie_breaker" : 0.7,
"boost": 1.0
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_08_disMaxQuery_decode() throws {
let query = DisMaxQuery([TermQuery(field: "title", value: "Quick pets"), TermQuery(field: "body", value: "Quick pets")], tieBreaker: 0.7)
let jsonStr = """
{
"dis_max" : {
"queries" : [
{ "term" : { "title" : "Quick pets" }},
{ "term" : { "body" : "Quick pets" }}
],
"tie_breaker" : 0.7
}
}
"""
let decoded = try JSONDecoder().decode(DisMaxQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
func test_09_boostingQuery_encode() throws {
let query = BoostingQuery(positive: TermQuery(field: "text", value: "apple"), negative: TermQuery(field: "text", value: "pie tart fruit crumble tree"), negativeBoost: 0.5)
let data = try JSONEncoder().encode(query)
let encodedStr = String(data: data, encoding: .utf8)!
logger.debug("Script Encode test: \(encodedStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: """
{
"boosting" : {
"positive" : {
"term" : {
"text" : "apple"
}
},
"negative" : {
"term" : {
"text" : "pie tart fruit crumble tree"
}
},
"negative_boost" : 0.5
}
}
""".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func test_10_boostingQuery_decode() throws {
let query = BoostingQuery(positive: TermQuery(field: "text", value: "apple"), negative: TermQuery(field: "text", value: "pie tart fruit crumble tree"), negativeBoost: 0.5)
let jsonStr = """
{
"boosting" : {
"positive" : {
"term" : {
"text" : "apple"
}
},
"negative" : {
"term" : {
"text" : "pie tart fruit crumble tree"
}
},
"negative_boost" : 0.5
}
}
"""
let decoded = try JSONDecoder().decode(BoostingQuery.self, from: jsonStr.data(using: .utf8)!)
XCTAssertEqual(query, decoded)
}
}
| mit | 772aca3e0def3e1304b5faf92fc077a6 | 33.981343 | 278 | 0.51328 | 4.294549 | false | true | false | false |
skyfe79/SwiftImageProcessing | 06_SplitRGBColorSpace_2.playground/Sources/ByteImage.swift | 1 | 4410 | import UIKit
/**
* 1byte크기의 화소 배열로 이뤄진 이미지
*/
public struct BytePixel {
private var value: UInt8
public init(value : UInt8) {
self.value = value
}
//red
public var C: UInt8 {
get { return value }
set { value = newValue }
}
public var Cf: Double {
get { return Double(self.C) / 255.0 }
set { self.C = UInt8(newValue * 255.0) }
}
}
public struct ByteImage {
public var pixels: UnsafeMutableBufferPointer<BytePixel>
public var width: Int
public var height: Int
public init?(image: UIImage) {
// CGImage로 변환이 가능해야 한다.
guard let cgImage = image.cgImage else {
return nil
}
// 주소 계산을 위해서 Float을 Int로 저장한다.
width = Int(image.size.width)
height = Int(image.size.height)
// 1 * width * height 크기의 버퍼를 생성한다.
let bytesPerRow = width * 1
let imageData = UnsafeMutablePointer<BytePixel>.allocate(capacity: width * height)
// 색상공간은 Device의 것을 따른다
let colorSpace = CGColorSpaceCreateDeviceGray()
// BGRA로 비트맵을 만든다
let bitmapInfo: UInt32 = CGBitmapInfo().rawValue
// 비트맵 생성
guard let imageContext = CGContext(data: imageData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
return nil
}
// cgImage를 imageData에 채운다.
imageContext.draw(cgImage, in: CGRect(origin: .zero, size: image.size))
// 이미지 화소의 배열 주소를 pixels에 담는다
pixels = UnsafeMutableBufferPointer<BytePixel>(start: imageData, count: width * height)
}
public init(width: Int, height: Int) {
let image = ByteImage.newUIImage(width: width, height: height)
self.init(image: image)!
}
public func clone() -> ByteImage {
let cloneImage = ByteImage(width: self.width, height: self.height)
for y in 0..<height {
for x in 0..<width {
let index = y * width + x
cloneImage.pixels[index] = self.pixels[index]
}
}
return cloneImage
}
public func toUIImage() -> UIImage? {
let colorSpace = CGColorSpaceCreateDeviceGray()
let bitmapInfo: UInt32 = CGBitmapInfo().rawValue
let bytesPerRow = width * 1
guard let imageContext = CGContext(data: pixels.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) else {
return nil
}
guard let cgImage = imageContext.makeImage() else {
return nil
}
let image = UIImage(cgImage: cgImage)
return image
}
public func pixel(x : Int, _ y : Int) -> BytePixel? {
guard x >= 0 && x < width && y >= 0 && y < height else {
return nil
}
let address = y * width + x
return pixels[address]
}
public mutating func pixel(x : Int, _ y : Int, _ pixel: BytePixel) {
guard x >= 0 && x < width && y >= 0 && y < height else {
return
}
let address = y * width + x
pixels[address] = pixel
}
public mutating func process( functor : ((BytePixel) -> BytePixel) ) {
for y in 0..<height {
for x in 0..<width {
let index = y * width + x
pixels[index] = functor(pixels[index])
}
}
}
private static func newUIImage(width: Int, height: Int) -> UIImage {
let size = CGSize(width: CGFloat(width), height: CGFloat(height));
UIGraphicsBeginImageContextWithOptions(size, true, 0);
UIColor.black.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
}
extension UInt8 {
public func toBytePixel() -> BytePixel {
return BytePixel(value: self)
}
}
| mit | cbebf9a071595b22396251be37164e75 | 29.402878 | 235 | 0.564363 | 4.196624 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/TimelineCells/Styles/Bubble/BubbleRoomCellLayoutConstants.swift | 1 | 2410 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Bubble style room cell layout constants
@objcMembers
final class BubbleRoomCellLayoutConstants: NSObject {
/// Inner content view margins
static let innerContentViewMargins: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 5.0, right: 0)
// Sender name margins
static let senderNameLabelMargins: UIEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 0.0, right: 0)
// Text message bubbles margins from cell content view
static let outgoingBubbleBackgroundMargins: UIEdgeInsets = UIEdgeInsets(top: 0, left: 80, bottom: 0, right: 34)
static let incomingBubbleBackgroundMargins: UIEdgeInsets = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 80)
static let bubbleTextViewInsets: UIEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 12, right: 5)
static let bubbleCornerRadius: CGFloat = 12.0
// Voice message
static let voiceMessagePlaybackViewRightMargin: CGFloat = 40
// Polls
static let pollBubbleBackgroundInsets: UIEdgeInsets = UIEdgeInsets(top: 2, left: 10, bottom: 0, right: 10)
// Decoration margins
// Timestamp margins
/// Timestamp margins for sticker cell, margin is relative to the image view
static let stickerTimestampViewMargins = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: -27) // Right margin is not reliable there, if the text size change this one is not working anymore
/// Timestamp margins inside bubble
static let bubbleTimestampViewMargins = UIEdgeInsets(top: 0, left: 0, bottom: 4.0, right: 8.0)
static let reactionsViewMargins = UIEdgeInsets(top: 4, left: 0, bottom: 0, right: 0)
static let threadSummaryViewMargins: UIEdgeInsets = UIEdgeInsets(top: 8.0, left: 0, bottom: 5, right: 0)
}
| apache-2.0 | 82c311633eae487a96220ed49949eac1 | 37.870968 | 193 | 0.711203 | 4.381818 | false | false | false | false |
halonsoluis/MiniRev | MiniRev/MiniRev/Social/MenuHandlers.swift | 1 | 3158 | //
// MenuHandlers.swift
// MiniRev
//
// Created by Hugo on 11/24/15.
// Copyright © 2015 Hugo Alonso. All rights reserved.
//
import Foundation
import Social
enum SubjectOptions : String {
case WhatIlove = "WhatIlove", Suggestions = "Suggestions", BugReport = "BugReport", Other = "Other", WhatIDontLike = "WhatIDontlove"
static let allValues = [WhatIlove, Suggestions, BugReport, Other]
func description() -> String{
return NSLocalizedString(self.rawValue, comment: "Subject")
}
}
enum MenuSocialHandlers {
case Review, FAQ, PrivacyPolice, TwitterPage, FacebookPage
func goTo() {
switch self {
case .FacebookPage: NetworkLinker.Facebook.openPage()
case .TwitterPage: NetworkLinker.Twitter.openPage()
case .Review: RatingHandler().rate()
case .FAQ: NetworkLinker.FAQPage.openPage()
case .PrivacyPolice: NetworkLinker.PrivacyPolicePage.openPage()
}
}
static func shareInFacebookAboutMiniRev(parentViewController:UIViewController) {
let vc = shareTheLove(SLServiceTypeFacebook)
parentViewController.presentViewController(vc, animated: true, completion: nil)
}
static func sendATwiitAboutMiniRev(parentViewController:UIViewController) {
let vc = shareTheLove(SLServiceTypeTwitter)
parentViewController.presentViewController(vc, animated: true, completion: nil)
}
private static func shareTheLove(socialNetwork: String) -> SLComposeViewController {
let vc = SLComposeViewController(forServiceType: socialNetwork)
vc.setInitialText(NSLocalizedString("check-out-beatune", comment: "Check out MiniRev"))
//vc.addImage(detailImageView.image!)
vc.addURL(NSURL(string: "https://itunes.apple.com/app/id\(RateDataManager.getAppID())"))
return vc
}
static func sendMail(parentViewController: UIViewController) {
let receipt = SocialAccounts.getEmailReceipt()
let receipts = [receipt]
requestMailSubject(parentViewController) { subject in
let mail = MailHandler(receipts: receipts, subject: subject, messageBody: "")
mail.sendMail(parentViewController)
}
}
static private func requestMailSubject(parentViewController: UIViewController, callBack: (String)->Void) {
let sendUsEmail = NSLocalizedString("sendUsEmail", comment: "Subject")
let alert = UIAlertController(title: "", message: sendUsEmail, preferredStyle: UIAlertControllerStyle.ActionSheet)
for subject in SubjectOptions.allValues{
//Do something
let bt_action = UIAlertAction(title: subject.description(), style: UIAlertActionStyle.Default) { (action) -> Void in
callBack(subject.description())
}
alert.addAction(bt_action)
}
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(cancel)
parentViewController.presentViewController(alert, animated: true, completion: nil)
}
}
| mit | 8ef883dd52de986d0aca0b9337cafc74 | 36.141176 | 136 | 0.677225 | 4.783333 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/BackerDashboardViewModelTests.swift | 1 | 10368 | @testable import KsApi
@testable import Library
import Prelude
import ReactiveExtensions_TestHelpers
import ReactiveSwift
import XCTest
internal final class BackerDashboardViewModelTests: TestCase {
private let vm: BackerDashboardViewModelType = BackerDashboardViewModel()
private let avatarURL = TestObserver<String, Never>()
private let backedButtonTitleText = TestObserver<String, Never>()
private let backerNameText = TestObserver<String, Never>()
private let configurePagesDataSourceTab = TestObserver<BackerDashboardTab, Never>()
private let configurePagesDataSourceSort = TestObserver<DiscoveryParams.Sort, Never>()
private let embeddedViewTopConstraintConstant = TestObserver<CGFloat, Never>()
private let goToMessages = TestObserver<(), Never>()
private let goToProject = TestObserver<Project, Never>()
private let goToSettings = TestObserver<(), Never>()
private let navigateToTab = TestObserver<BackerDashboardTab, Never>()
private let pinSelectedIndicatorToTab = TestObserver<BackerDashboardTab, Never>()
private let pinSelectedIndicatorToTabAnimated = TestObserver<Bool, Never>()
private let postNotification = TestObserver<Notification, Never>()
private let savedButtonTitleText = TestObserver<String, Never>()
private let setSelectedButton = TestObserver<BackerDashboardTab, Never>()
private let sortBarIsHidden = TestObserver<Bool, Never>()
private let updateCurrentUserInEnvironment = TestObserver<User, Never>()
override func setUp() {
super.setUp()
self.vm.outputs.avatarURL.map { $0?.absoluteString ?? "" }.observe(self.avatarURL.observer)
self.vm.outputs.backedButtonTitleText.observe(self.backedButtonTitleText.observer)
self.vm.outputs.backerNameText.observe(self.backerNameText.observer)
self.vm.outputs.configurePagesDataSource.map(first).observe(self.configurePagesDataSourceTab.observer)
self.vm.outputs.configurePagesDataSource.map(second).observe(self.configurePagesDataSourceSort.observer)
self.vm.outputs.embeddedViewTopConstraintConstant.observe(self.embeddedViewTopConstraintConstant.observer)
self.vm.outputs.goToMessages.observe(self.goToMessages.observer)
self.vm.outputs.goToSettings.observe(self.goToSettings.observer)
self.vm.outputs.navigateToTab.observe(self.navigateToTab.observer)
self.vm.outputs.pinSelectedIndicatorToTab.map(first).observe(self.pinSelectedIndicatorToTab.observer)
self.vm.outputs.pinSelectedIndicatorToTab.map(second)
.observe(self.pinSelectedIndicatorToTabAnimated.observer)
self.vm.outputs.savedButtonTitleText.observe(self.savedButtonTitleText.observer)
self.vm.outputs.setSelectedButton.observe(self.setSelectedButton.observer)
self.vm.outputs.sortBarIsHidden.observe(self.sortBarIsHidden.observer)
self.vm.outputs.updateCurrentUserInEnvironment.observe(self.updateCurrentUserInEnvironment.observer)
self.vm.outputs.postNotification.observe(self.postNotification.observer)
}
func testUserAndHeaderDisplayData() {
let location = Location.template
|> Location.lens.displayableName .~ "Siberia"
let user = User.template
|> \.name .~ "Princess Vespa"
|> \.location .~ location
|> \.stats.backedProjectsCount .~ 45
|> \.stats.starredProjectsCount .~ 58
|> \.avatar.large .~ "http://cats.com/furball.jpg"
withEnvironment(apiService: MockService(fetchUserSelfResponse: user)) {
AppEnvironment.login(AccessTokenEnvelope(accessToken: "deadbeef", user: user))
self.avatarURL.assertValueCount(0)
self.backedButtonTitleText.assertValueCount(0)
self.backerNameText.assertValueCount(0)
self.pinSelectedIndicatorToTab.assertValueCount(0)
self.pinSelectedIndicatorToTabAnimated.assertValueCount(0)
self.savedButtonTitleText.assertValueCount(0)
self.setSelectedButton.assertValueCount(0)
self.sortBarIsHidden.assertValueCount(0)
self.postNotification.assertValueCount(0)
self.updateCurrentUserInEnvironment.assertValueCount(0)
self.vm.inputs.viewDidLoad()
self.vm.inputs.viewWillAppear(false)
self.scheduler.advance()
// Signals emit twice as they are prefixed with the current user data.
self.avatarURL.assertValues(["http://cats.com/furball.jpg", "http://cats.com/furball.jpg"])
self.backedButtonTitleText.assertValues(["45\nbacked", "45\nbacked"])
self.backerNameText.assertValues(["Princess Vespa", "Princess Vespa"])
self.savedButtonTitleText.assertValues(["58\nsaved", "58\nsaved"])
self.setSelectedButton.assertValues([.backed])
self.sortBarIsHidden.assertValues([true])
self.embeddedViewTopConstraintConstant.assertValues([0.0])
self.postNotification.assertValueCount(0)
self.updateCurrentUserInEnvironment.assertValues([user])
self.vm.inputs.currentUserUpdatedInEnvironment()
self.postNotification.assertValueCount(1)
// Signals that emit just once because they rely on the datasource tab index to exist first.
self.pinSelectedIndicatorToTab.assertValues([.backed])
self.pinSelectedIndicatorToTabAnimated.assertValues([false])
}
}
func testUserUpdatesInEnvironment_AfterSavingProject() {
let user = User.template
|> \.name .~ "user"
|> \.stats.starredProjectsCount .~ 60
withEnvironment(apiService: MockService(fetchUserSelfResponse: user)) {
AppEnvironment.login(AccessTokenEnvelope(accessToken: "deadbeef", user: user))
self.vm.inputs.viewWillAppear(false)
self.scheduler.advance()
self.updateCurrentUserInEnvironment.assertValues([user])
let user2 = user
|> \.name .~ "Updated user"
withEnvironment(apiService: MockService(fetchUserSelfResponse: user2)) {
self.vm.inputs.projectSaved()
self.scheduler.advance()
self.updateCurrentUserInEnvironment.assertValues([user, user, user2])
}
}
}
func testConfigurePagesData() {
self.configurePagesDataSourceTab.assertValueCount(0)
self.configurePagesDataSourceSort.assertValueCount(0)
self.vm.inputs.viewDidLoad()
self.configurePagesDataSourceTab.assertValues([.backed])
self.configurePagesDataSourceSort.assertValues([.endingSoon])
}
func testTabNavigation() {
withEnvironment(apiService: MockService(fetchUserSelfResponse: .template)) {
AppEnvironment.login(AccessTokenEnvelope(accessToken: "deadbeef", user: .template))
self.vm.inputs.viewDidLoad()
self.vm.inputs.viewWillAppear(false)
self.setSelectedButton.assertValueCount(0)
self.pinSelectedIndicatorToTab.assertValueCount(0)
self.pinSelectedIndicatorToTabAnimated.assertValueCount(0)
XCTAssertEqual(.backed, self.vm.outputs.currentSelectedTab)
self.scheduler.advance()
self.navigateToTab.assertValueCount(0)
self.setSelectedButton.assertValues([.backed])
self.pinSelectedIndicatorToTab.assertValues([.backed])
self.pinSelectedIndicatorToTabAnimated.assertValues([false])
XCTAssertEqual(.backed, self.vm.outputs.currentSelectedTab)
self.vm.inputs.savedProjectsButtonTapped()
self.navigateToTab.assertValues([.saved])
self.setSelectedButton.assertValues([.backed, .saved])
self.pinSelectedIndicatorToTab.assertValues([.backed, .saved])
self.pinSelectedIndicatorToTabAnimated.assertValues([false, true])
XCTAssertEqual(.saved, self.vm.outputs.currentSelectedTab)
XCTAssertEqual("discover", self.segmentTrackingClient.properties.last?["context_page"] as? String)
XCTAssertEqual("watched", self.segmentTrackingClient.properties.last?["context_type"] as? String)
XCTAssertEqual(
"account_menu",
self.segmentTrackingClient.properties.last?["context_location"] as? String
)
self.vm.inputs.backedProjectsButtonTapped()
self.navigateToTab.assertValues([.saved, .backed])
self.setSelectedButton.assertValues([.backed, .saved, .backed])
self.pinSelectedIndicatorToTab.assertValues([.backed, .saved, .backed])
self.pinSelectedIndicatorToTabAnimated.assertValues([false, true, true])
XCTAssertEqual(.backed, self.vm.outputs.currentSelectedTab)
// Swiping.
self.vm.inputs.willTransition(toPage: 1)
self.vm.inputs.pageTransition(completed: false)
self.navigateToTab.assertValues([.saved, .backed], "Tab switch does not complete.")
self.setSelectedButton.assertValues([.backed, .saved, .backed], "Selection does not emit.")
self.pinSelectedIndicatorToTab.assertValues([.backed, .saved, .backed], "Selection does not emit.")
XCTAssertEqual(.backed, self.vm.outputs.currentSelectedTab)
self.vm.inputs.willTransition(toPage: 1)
self.vm.inputs.pageTransition(completed: true)
self.navigateToTab.assertValues([.saved, .backed, .saved])
self.setSelectedButton.assertValues([.backed, .saved, .backed, .saved])
self.pinSelectedIndicatorToTab.assertValues([.backed, .saved, .backed, .saved])
self.pinSelectedIndicatorToTabAnimated.assertValues([false, true, true, true])
XCTAssertEqual(.saved, self.vm.outputs.currentSelectedTab)
XCTAssertEqual("discover", self.segmentTrackingClient.properties.last?["context_page"] as? String)
XCTAssertEqual("watched", self.segmentTrackingClient.properties.last?["context_type"] as? String)
XCTAssertEqual(
"account_menu",
self.segmentTrackingClient.properties.last?["context_location"] as? String
)
}
}
func testGoPlaces() {
self.vm.inputs.viewDidLoad()
self.vm.inputs.viewWillAppear(false)
self.goToSettings.assertValueCount(0)
self.vm.inputs.settingsButtonTapped()
self.goToSettings.assertValueCount(1)
self.goToMessages.assertValueCount(0)
self.vm.inputs.messagesButtonTapped()
self.goToMessages.assertValueCount(1)
}
func testHeaderPanning() {
self.vm.inputs.viewDidLoad()
self.vm.inputs.viewWillAppear(false)
// Panning on the header view.
self.vm.inputs.beganPanGestureWith(headerTopConstant: -101.0, scrollViewYOffset: 0.0)
XCTAssertEqual(-101.0, self.vm.outputs.initialTopConstant)
// Panning on the projects table view.
self.vm.inputs.beganPanGestureWith(headerTopConstant: -101.0, scrollViewYOffset: 500.0)
XCTAssertEqual(-500, self.vm.outputs.initialTopConstant)
}
}
| apache-2.0 | 8da2cbb6983c89340e5eab25b319cc42 | 42.563025 | 110 | 0.753376 | 4.470893 | false | true | false | false |
lorentey/GlueKit | Sources/SetSortingByMappingToComparable.swift | 1 | 4064 | //
// SetSortingByMappingToComparable.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-08-15.
// Copyright © 2015–2017 Károly Lőrentey.
//
import BTree
extension ObservableSetType {
/// Given a transformation into a comparable type, return an observable array containing transformed
/// versions of elements in this set, in increasing order.
public func sortedMap<Result: Comparable>(by transform: @escaping (Element) -> Result) -> AnyObservableArray<Result> {
return SetSortingByMappingToComparable(parent: self, transform: transform).anyObservableArray
}
}
extension ObservableSetType where Element: Comparable {
/// Return an observable array containing the members of this set, in increasing order.
public func sorted() -> AnyObservableArray<Element> {
return self.sortedMap { $0 }
}
}
private final class SetSortingByMappingToComparable<Parent: ObservableSetType, Element: Comparable>: _BaseObservableArray<Element> {
typealias Change = ArrayChange<Element>
private struct SortingSink: UniqueOwnedSink {
typealias Owner = SetSortingByMappingToComparable
unowned(unsafe) let owner: Owner
func receive(_ update: SetUpdate<Parent.Element>) {
owner.applyParentUpdate(update)
}
}
private let parent: Parent
private let transform: (Parent.Element) -> Element
private var contents: Map<Element, Int> = [:]
init(parent: Parent, transform: @escaping (Parent.Element) -> Element) {
self.parent = parent
self.transform = transform
super.init()
for element in parent.value {
let transformed = transform(element)
contents[transformed] = (contents[transformed] ?? 0) + 1
}
parent.add(SortingSink(owner: self))
}
deinit {
parent.remove(SortingSink(owner: self))
}
func applyParentUpdate(_ update: SetUpdate<Parent.Element>) {
switch update {
case .beginTransaction:
beginTransaction()
case .change(let change):
var arrayChange = ArrayChange<Element>(initialCount: contents.count)
for element in change.removed {
let transformed = transform(element)
guard let index = contents.index(forKey: transformed) else { fatalError("Removed element '\(transformed)' not found in sorted set") }
let count = contents[index].1
if count == 1 {
let offset = contents.offset(of: index)
let old = contents.remove(at: index)
if isConnected {
arrayChange.add(.remove(old.key, at: offset))
}
}
else {
contents[transformed] = count - 1
}
}
for element in change.inserted {
let transformed = transform(element)
if let count = contents[transformed] {
precondition(count > 0)
contents[transformed] = count + 1
}
else {
contents[transformed] = 1
if isConnected {
let offset = contents.offset(of: transformed)!
arrayChange.add(.insert(transformed, at: offset))
}
}
}
if isConnected, !arrayChange.isEmpty {
sendChange(arrayChange)
}
case .endTransaction:
endTransaction()
}
}
override var isBuffered: Bool { return false }
override subscript(index: Int) -> Element { return contents.element(atOffset: index).0 }
override subscript(bounds: Range<Int>) -> ArraySlice<Element> { return ArraySlice(contents.submap(withOffsets: bounds).lazy.map { $0.0 }) }
override var value: Array<Element> { return Array(contents.lazy.map { $0.0 }) }
override var count: Int { return contents.count }
}
| mit | 1917e1e8eb70bbcff331c90fa524056f | 36.564815 | 149 | 0.595514 | 4.971814 | false | false | false | false |
Onetaway/iOS8-day-by-day | 19-core-image-kernels/FilterBuilder/FilterBuilder/ChromaKeyFilter.swift | 3 | 1806 | //
// Copyright 2014 Scott Logic
//
// 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 CoreImage
class ChromaKeyFilter: CIFilter {
// MARK: - Properties
var kernel: CIColorKernel?
var inputImage: CIImage?
var activeColor = CIColor(red: 0.0, green: 1.0, blue: 0.0)
var threshold: CGFloat = 0.7
// MARK: - Initialization
override init() {
super.init()
kernel = createKernel()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
kernel = createKernel()
}
// MARK: - API
func outputImage() -> CIImage? {
if let inputImage = inputImage {
let dod = inputImage.extent()
if let kernel = kernel {
var args = [inputImage as AnyObject, activeColor as AnyObject, threshold as AnyObject]
return kernel.applyWithExtent(dod, arguments: args)
}
}
return nil
}
// MARK: - Utility methods
private func createKernel() -> CIColorKernel {
let kernelString =
"kernel vec4 chromaKey( __sample s, __color c, float threshold ) { \n" +
" vec4 diff = s.rgba - c;\n" +
" float distance = length( diff );\n" +
" float alpha = compare( distance - threshold, 0.0, 1.0 );\n" +
" return vec4( s.rgb, alpha ); \n" +
"}"
return CIColorKernel(string: kernelString)
}
}
| apache-2.0 | 37b8c26ad3ed45781319565491f80240 | 29.1 | 94 | 0.660576 | 3.883871 | false | false | false | false |
apple/swift-corelibs-foundation | Tests/Foundation/FixtureValues.swift | 1 | 18356 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// Please keep this import statement as-is; this file is also used by the GenerateTestFixtures project, which doesn't have TestImports.swift.
#if canImport(SwiftFoundation)
import SwiftFoundation
#else
import Foundation
#endif
// -----
extension Calendar {
static var neutral: Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
calendar.locale = NSLocale.system
return calendar
}
}
enum Fixtures {
static let mutableAttributedString = TypedFixture<NSMutableAttributedString>("NSMutableAttributedString") {
let string = NSMutableAttributedString(string: "0123456789")
// Should have: .xyyzzxyx.
let attrs1: [NSAttributedString.Key: Any] = [.init("Font"): "Helvetica", .init("Size"): 123]
let attrs2: [NSAttributedString.Key: Any] = [.init("Font"): "Times", .init("Size"): 456]
let attrs3NS = attrs2 as NSDictionary
let attrs3Maybe: [NSAttributedString.Key: Any]?
if let attrs3Swift = attrs3NS as? [String: Any] {
attrs3Maybe = Dictionary(attrs3Swift.map { (NSAttributedString.Key($0.key), $0.value) }, uniquingKeysWith: { $1 })
} else {
attrs3Maybe = nil
}
let attrs3 = try XCTUnwrap(attrs3Maybe)
string.setAttributes(attrs1, range: NSMakeRange(1, string.length - 2))
string.setAttributes(attrs2, range: NSMakeRange(2, 2))
string.setAttributes(attrs3, range: NSMakeRange(4, 2))
string.setAttributes(attrs2, range: NSMakeRange(8, 1))
return string
}
static let attributedString = TypedFixture<NSAttributedString>("NSAttributedString") {
return NSAttributedString(attributedString: try Fixtures.mutableAttributedString.make())
}
// ===== ByteCountFormatter =====
static let byteCountFormatterDefault = TypedFixture<ByteCountFormatter>("ByteCountFormatter-Default") {
return ByteCountFormatter()
}
static let byteCountFormatterAllFieldsSet = TypedFixture<ByteCountFormatter>("ByteCountFormatter-AllFieldsSet") {
let f = ByteCountFormatter()
f.allowedUnits = [.useBytes, .useKB]
f.countStyle = .decimal
f.formattingContext = .beginningOfSentence
f.zeroPadsFractionDigits = true
f.includesCount = true
f.allowsNonnumericFormatting = false
f.includesUnit = false
f.includesCount = false
f.isAdaptive = false
return f
}
// ===== DateIntervalFormatter =====
static let dateIntervalFormatterDefault = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-Default") {
let dif = DateIntervalFormatter()
let calendar = Calendar.neutral
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
return dif
}
static let dateIntervalFormatterValuesSetWithoutTemplate = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-ValuesSetWithoutTemplate") {
let dif = DateIntervalFormatter()
var calendar = Calendar.neutral
calendar.locale = Locale(identifier: "ja-JP")
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
dif.dateStyle = .long
dif.timeStyle = .none
dif.timeZone = TimeZone(secondsFromGMT: 60 * 60)
return dif
}
static let dateIntervalFormatterValuesSetWithTemplate = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-ValuesSetWithTemplate") {
let dif = DateIntervalFormatter()
var calendar = Calendar.neutral
calendar.locale = Locale(identifier: "ja-JP")
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
dif.dateTemplate = "dd mm yyyy HH:MM"
dif.timeZone = TimeZone(secondsFromGMT: 60 * 60)
return dif
}
// ===== ISO8601DateFormatter =====
static let iso8601FormatterDefault = TypedFixture<ISO8601DateFormatter>("ISO8601DateFormatter-Default") {
let idf = ISO8601DateFormatter()
idf.timeZone = Calendar.neutral.timeZone
return idf
}
static let iso8601FormatterOptionsSet = TypedFixture<ISO8601DateFormatter>("ISO8601DateFormatter-OptionsSet") {
let idf = ISO8601DateFormatter()
idf.timeZone = Calendar.neutral.timeZone
idf.formatOptions = [ .withDay, .withWeekOfYear, .withMonth, .withTimeZone, .withColonSeparatorInTimeZone, .withDashSeparatorInDate ]
return idf
}
// ===== NSTextCheckingResult =====
static let textCheckingResultSimpleRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-SimpleRegex") {
let string = "aaa"
let regexp = try NSRegularExpression(pattern: "aaa", options: [])
let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first)
return result
}
static let textCheckingResultExtendedRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-ExtendedRegex") {
let string = "aaaaaa"
let regexp = try NSRegularExpression(pattern: "a(a(a(a(a(a)))))", options: [])
let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first)
return result
}
static let textCheckingResultComplexRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-ComplexRegex") {
let string = "aaaaaaaaa"
let regexp = try NSRegularExpression(pattern: "a(a(a(a(a(a(a(a(a))))))))", options: [])
let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first)
return result
}
// ===== NSIndexSet =====
static let indexSetEmpty = TypedFixture<NSIndexSet>("NSIndexSet-Empty") {
return NSIndexSet(indexesIn: NSMakeRange(0, 0))
}
static let indexSetOneRange = TypedFixture<NSIndexSet>("NSIndexSet-OneRange") {
return NSIndexSet(indexesIn: NSMakeRange(0, 50))
}
static let indexSetManyRanges = TypedFixture<NSIndexSet>("NSIndexSet-ManyRanges") {
let indexSet = NSMutableIndexSet()
indexSet.add(in: NSMakeRange(0, 50))
indexSet.add(in: NSMakeRange(100, 50))
indexSet.add(in: NSMakeRange(1000, 50))
indexSet.add(in: NSMakeRange(Int.max - 50, 50))
return indexSet.copy() as! NSIndexSet
}
static let mutableIndexSetEmpty = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-Empty") {
return (try Fixtures.indexSetEmpty.make()).mutableCopy() as! NSMutableIndexSet
}
static let mutableIndexSetOneRange = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-OneRange") {
return (try Fixtures.indexSetOneRange.make()).mutableCopy() as! NSMutableIndexSet
}
static let mutableIndexSetManyRanges = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-ManyRanges") {
return (try Fixtures.indexSetManyRanges.make()).mutableCopy() as! NSMutableIndexSet
}
// ===== NSIndexPath =====
static let indexPathEmpty = TypedFixture<NSIndexPath>("NSIndexPath-Empty") {
return NSIndexPath()
}
static let indexPathOneIndex = TypedFixture<NSIndexPath>("NSIndexPath-OneIndex") {
return NSIndexPath(index: 52)
}
static let indexPathManyIndices = TypedFixture<NSIndexPath>("NSIndexPath-ManyIndices") {
var indexPath = IndexPath()
indexPath.append([4, 8, 15, 16, 23, 42])
return indexPath as NSIndexPath
}
// ===== NSSet, NSMutableSet =====
static let setOfNumbers = TypedFixture<NSSet>("NSSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSSet(array: numbers)
}
static let setEmpty = TypedFixture<NSSet>("NSSet-Empty") {
return NSSet()
}
static let mutableSetOfNumbers = TypedFixture<NSMutableSet>("NSMutableSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSMutableSet(array: numbers)
}
static let mutableSetEmpty = TypedFixture<NSMutableSet>("NSMutableSet-Empty") {
return NSMutableSet()
}
// ===== NSCountedSet =====
static let countedSetOfNumbersAppearingOnce = TypedFixture<NSCountedSet>("NSCountedSet-NumbersAppearingOnce") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSCountedSet(array: numbers)
}
static let countedSetOfNumbersAppearingSeveralTimes = TypedFixture<NSCountedSet>("NSCountedSet-NumbersAppearingSeveralTimes") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
let set = NSCountedSet()
for _ in 0 ..< 5 {
for number in numbers {
set.add(number)
}
}
return set
}
static let countedSetEmpty = TypedFixture<NSCountedSet>("NSCountedSet-Empty") {
return NSCountedSet()
}
// ===== NSCharacterSet, NSMutableCharacterSet =====
static let characterSetEmpty = TypedFixture<NSCharacterSet>("NSCharacterSet-Empty") {
return NSCharacterSet()
}
static let characterSetRange = TypedFixture<NSCharacterSet>("NSCharacterSet-Range") {
return NSCharacterSet(range: NSMakeRange(0, 255))
}
static let characterSetString = TypedFixture<NSCharacterSet>("NSCharacterSet-String") {
return NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz")
}
static let characterSetBitmap = TypedFixture<NSCharacterSet>("NSCharacterSet-Bitmap") {
let someSet = NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz")
return NSCharacterSet(bitmapRepresentation: someSet.bitmapRepresentation)
}
static let characterSetBuiltin = TypedFixture<NSCharacterSet>("NSCharacterSet-Builtin") {
return NSCharacterSet.alphanumerics as NSCharacterSet
}
// ===== NSOrderedSet, NSMutableOrderedSet =====
static let orderedSetOfNumbers = TypedFixture<NSOrderedSet>("NSOrderedSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSOrderedSet(array: numbers)
}
static let orderedSetEmpty = TypedFixture<NSOrderedSet>("NSOrderedSet-Empty") {
return NSOrderedSet()
}
static let mutableOrderedSetOfNumbers = TypedFixture<NSMutableOrderedSet>("NSMutableOrderedSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSMutableOrderedSet(array: numbers)
}
static let mutableOrderedSetEmpty = TypedFixture<NSMutableOrderedSet>("NSMutableOrderedSet-Empty") {
return NSMutableOrderedSet()
}
// ===== NSMeasurement =====
static let zeroMeasurement = TypedFixture<NSMeasurement>("NSMeasurement-Zero") {
let noUnit = Unit(symbol: "")
return NSMeasurement(doubleValue: 0, unit: noUnit)
}
static let lengthMeasurement = TypedFixture<NSMeasurement>("NSMeasurement-Length") {
return NSMeasurement(doubleValue: 45, unit: UnitLength.miles)
}
static let frequencyMeasurement = TypedFixture<NSMeasurement>("NSMeasurement-Frequency") {
return NSMeasurement(doubleValue: 1400, unit: UnitFrequency.megahertz)
}
static let angleMeasurement = TypedFixture<NSMeasurement>("NSMeasurement-Angle") {
return NSMeasurement(doubleValue: 90, unit: UnitAngle.degrees)
}
// ===== Fixture list =====
static let _listOfAllFixtures: [AnyFixture] = [
AnyFixture(Fixtures.mutableAttributedString),
AnyFixture(Fixtures.attributedString),
AnyFixture(Fixtures.byteCountFormatterDefault),
AnyFixture(Fixtures.byteCountFormatterAllFieldsSet),
AnyFixture(Fixtures.dateIntervalFormatterDefault),
AnyFixture(Fixtures.dateIntervalFormatterValuesSetWithTemplate),
AnyFixture(Fixtures.dateIntervalFormatterValuesSetWithoutTemplate),
AnyFixture(Fixtures.iso8601FormatterDefault),
AnyFixture(Fixtures.iso8601FormatterOptionsSet),
AnyFixture(Fixtures.textCheckingResultSimpleRegex),
AnyFixture(Fixtures.textCheckingResultExtendedRegex),
AnyFixture(Fixtures.textCheckingResultComplexRegex),
AnyFixture(Fixtures.indexSetEmpty),
AnyFixture(Fixtures.indexSetOneRange),
AnyFixture(Fixtures.indexSetManyRanges),
AnyFixture(Fixtures.mutableIndexSetEmpty),
AnyFixture(Fixtures.mutableIndexSetOneRange),
AnyFixture(Fixtures.mutableIndexSetManyRanges),
AnyFixture(Fixtures.indexPathEmpty),
AnyFixture(Fixtures.indexPathOneIndex),
AnyFixture(Fixtures.indexPathManyIndices),
AnyFixture(Fixtures.setOfNumbers),
AnyFixture(Fixtures.setEmpty),
AnyFixture(Fixtures.mutableSetOfNumbers),
AnyFixture(Fixtures.mutableSetEmpty),
AnyFixture(Fixtures.countedSetOfNumbersAppearingOnce),
AnyFixture(Fixtures.countedSetOfNumbersAppearingSeveralTimes),
AnyFixture(Fixtures.countedSetEmpty),
AnyFixture(Fixtures.characterSetEmpty),
AnyFixture(Fixtures.characterSetRange),
AnyFixture(Fixtures.characterSetString),
AnyFixture(Fixtures.characterSetBitmap),
AnyFixture(Fixtures.characterSetBuiltin),
AnyFixture(Fixtures.orderedSetOfNumbers),
AnyFixture(Fixtures.orderedSetEmpty),
AnyFixture(Fixtures.mutableOrderedSetOfNumbers),
AnyFixture(Fixtures.mutableOrderedSetEmpty),
AnyFixture(Fixtures.zeroMeasurement),
AnyFixture(Fixtures.lengthMeasurement),
AnyFixture(Fixtures.frequencyMeasurement),
AnyFixture(Fixtures.angleMeasurement),
]
// This ensures that we do not have fixtures with duplicate identifiers:
static var all: [AnyFixture] {
return Array(Fixtures.allFixturesByIdentifier.values)
}
static var allFixturesByIdentifier: [String: AnyFixture] = {
let keysAndValues = Fixtures._listOfAllFixtures.map { ($0.identifier, $0) }
return Dictionary(keysAndValues, uniquingKeysWith: { _, _ in fatalError("No two keys should be the same in fixtures. Double-check keys in FixtureValues.swift to make sure they're all unique.") })
}()
}
// -----
// Support for the above:
enum FixtureVariant: String, CaseIterable {
case macOS10_14 = "macOS-10.14"
func url(fixtureRepository: URL) -> URL {
return URL(fileURLWithPath: self.rawValue, relativeTo: fixtureRepository)
}
}
protocol Fixture {
associatedtype ValueType
var identifier: String { get }
func make() throws -> ValueType
var supportsSecureCoding: Bool { get }
}
struct TypedFixture<ValueType: NSObject & NSCoding>: Fixture {
var identifier: String
private var creationHandler: () throws -> ValueType
init(_ identifier: String, creationHandler: @escaping () throws -> ValueType) {
self.identifier = identifier
self.creationHandler = creationHandler
}
func make() throws -> ValueType {
return try creationHandler()
}
var supportsSecureCoding: Bool {
let kind: Any.Type
if let made = try? make() {
kind = type(of: made)
} else {
kind = ValueType.self
}
return (kind as? NSSecureCoding.Type)?.supportsSecureCoding == true
}
}
struct AnyFixture: Fixture {
var identifier: String
private var creationHandler: () throws -> NSObject & NSCoding
let supportsSecureCoding: Bool
init<T: Fixture>(_ fixture: T) {
self.identifier = fixture.identifier
self.creationHandler = { return try fixture.make() as! (NSObject & NSCoding) }
self.supportsSecureCoding = fixture.supportsSecureCoding
}
func make() throws -> NSObject & NSCoding {
return try creationHandler()
}
}
enum FixtureError: Error {
case noneFound
}
extension Fixture where ValueType: NSObject & NSCoding {
func load(fixtureRepository: URL, variant: FixtureVariant) throws -> ValueType? {
let data = try Data(contentsOf: url(inFixtureRepository: fixtureRepository, variant: variant))
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
unarchiver.requiresSecureCoding = self.supportsSecureCoding
unarchiver.decodingFailurePolicy = .setErrorAndReturn
let value = unarchiver.decodeObject(of: ValueType.self, forKey: NSKeyedArchiveRootObjectKey)
if let error = unarchiver.error {
throw error
}
return value
}
func url(inFixtureRepository fixtureRepository: URL, variant: FixtureVariant) -> URL {
return variant.url(fixtureRepository: fixtureRepository)
.appendingPathComponent(identifier)
.appendingPathExtension("archive")
}
func loadEach(fixtureRepository: URL, handler: (ValueType, FixtureVariant) throws -> Void) throws {
var foundAny = false
for variant in FixtureVariant.allCases {
let fileURL = url(inFixtureRepository: fixtureRepository, variant: variant)
guard (try? fileURL.checkResourceIsReachable()) == true else { continue }
foundAny = true
if let value = try load(fixtureRepository: fixtureRepository, variant: variant) {
try handler(value, variant)
}
}
guard foundAny else { throw FixtureError.noneFound }
}
}
| apache-2.0 | b28b53c71ec4011b77221bd25ef71207 | 37.162162 | 203 | 0.665504 | 5.055357 | false | false | false | false |
LuckyResistor/FontToBytes | FontToBytes/MainViewController.swift | 1 | 16167 | //
// Lucky Resistor's Font to Byte
// ---------------------------------------------------------------------------
// (c)2015 by Lucky Resistor. See LICENSE for details.
//
// 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 2 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
import Cocoa
let UD_SelectedModeIndex = "selectedModeIndex"
let UD_SelectedOutputIndex = "selectedOutputIndex"
let UD_InvertBitsChecked = "invertBitsChecked"
let UD_ReverseBitsChecked = "reverseBitsChecked"
/// The view controller for the main window
///
class MainViewController: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate {
/// All visible mode items.
private var modeItems = [
ModeItem(title: "8×8 Fixed Top-Down", converter: Converter8x8Fixed(direction: .TopDown)),
ModeItem(title: "8×8 Fixed Left-Right", converter: Converter8x8Fixed(direction: .LeftRight))
]
private var sourceCodeGenerators: [SourceCodeGeneratorItem] = [
SourceCodeGeneratorItemImpl<ArduinoSourceGenerator>(title: "Arduino Format"),
SourceCodeGeneratorItemImpl<CommonCppSourceGenerator>(title: "C++ Common Format")
]
/// The mode section.
private let modeSectionItem = ModeItem(title: "MODES")
/// The navigation outline view on the left side.
@IBOutlet weak var navigation: NSOutlineView!
/// The main view.
@IBOutlet weak var mainView: NSView!
/// Invert bits checkbox
@IBOutlet weak var invertBitsCheckbox: NSButton!
/// Reverse bits checkbox
@IBOutlet weak var reverseBitsCheckbox: NSButton!
/// The selection for the output format.
@IBOutlet weak var outputFormatSelection: NSPopUpButton!
/// The currently displayed view controller in the main view
var mainViewController: NSViewController? = nil
/// The currently displayed view
enum DisplayedView {
case Welcome
case Error
case Result
}
/// The currently displayed view
var displayedView = DisplayedView.Welcome
/// The current code which is displayed
var code = ""
/// The least used input image for a later print operation
var inputImage: InputImage? = nil
/// Initialize the view after load.
///
override func viewDidLoad() {
super.viewDidLoad()
// expand all items.
navigation.expandItem(nil, expandChildren: true)
// The user defaults
let ud = NSUserDefaults.standardUserDefaults()
// Select the item
let selectedModeIndex = ud.integerForKey(UD_SelectedModeIndex)
dispatch_async(dispatch_get_main_queue()) {
self.navigation.selectRowIndexes(NSIndexSet(index: selectedModeIndex+1), byExtendingSelection: false)
}
// Check the invert bits checkbox.
let invertBitsChecked = ud.boolForKey(UD_InvertBitsChecked)
self.invertBitsCheckbox.state = (invertBitsChecked ? NSOnState : NSOffState)
// Check the flip bits checkbox.
let reverseBitsChecked = ud.boolForKey(UD_ReverseBitsChecked)
self.reverseBitsCheckbox.state = (reverseBitsChecked ? NSOnState : NSOffState)
// Prepare the popup button with the outputs
self.outputFormatSelection.removeAllItems()
for item in sourceCodeGenerators {
self.outputFormatSelection.addItemWithTitle(item.title)
}
let selectedOutputIndex = ud.integerForKey(UD_SelectedOutputIndex)
self.outputFormatSelection.selectItemAtIndex(selectedOutputIndex)
// Show the welcome view
displayWelcomeView()
}
override func viewWillDisappear() {
super.viewWillDisappear()
// Store the user defaults
let ud = NSUserDefaults.standardUserDefaults()
ud.setInteger(self.navigation.selectedRow-1, forKey: UD_SelectedModeIndex)
ud.setBool(self.invertBitsCheckbox.state == NSOnState, forKey: UD_InvertBitsChecked)
ud.setBool(self.reverseBitsCheckbox.state == NSOnState, forKey: UD_ReverseBitsChecked)
ud.setInteger(self.outputFormatSelection.indexOfSelectedItem, forKey: UD_SelectedOutputIndex)
}
/// Go back to the welcome view
///
@IBAction func goBack(sender: AnyObject) {
dispatch_async(dispatch_get_main_queue(), {
self.displayWelcomeView()
})
}
/// Save the current result into a file.
///
@IBAction func saveDocumentAs(sender: AnyObject) {
guard displayedView == .Result else {
return
}
let savePanel = NSSavePanel()
savePanel.allowedFileTypes = ["cpp", "h", "c", "txt"]
savePanel.beginSheetModalForWindow(NSApp.mainWindow!, completionHandler: {(result: Int) in
if result == NSFileHandlingPanelOKButton {
do {
try self.code.writeToURL(savePanel.URL!, atomically: true, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
dispatch_async(dispatch_get_main_queue(), {
NSApp.mainWindow!.presentError(error)
})
} catch {
print("Unknown error.")
}
}
})
}
/// Open a document.
///
@IBAction func openDocument(sender: AnyObject) {
guard displayedView == .Welcome else {
return
}
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true
openPanel.canChooseDirectories = false
openPanel.allowsMultipleSelection = false
openPanel.allowedFileTypes = ["png"]
openPanel.beginSheetModalForWindow(NSApp.mainWindow!, completionHandler: {(result: Int) in
if result == NSFileHandlingPanelOKButton {
let welcomeViewController = self.mainViewController as! WelcomeViewController
welcomeViewController.goIntoDroppedState()
self.convertImage(openPanel.URLs[0])
}
})
}
/// Enable all valid menu items.
///
override func validateMenuItem(menuItem: NSMenuItem) -> Bool {
if menuItem.action == Selector("saveDocumentAs:") {
return displayedView == .Result
} else if menuItem.action == Selector("openDocument:") {
return displayedView == .Welcome
} else if menuItem.action == Selector("printDocument:") {
return displayedView == .Result
} else {
return true
}
}
/// Displays the welcome view
///
func displayWelcomeView() {
let newController = storyboard!.instantiateControllerWithIdentifier("welcomeView") as! WelcomeViewController
newController.representedObject = self
newController.onURLDropped = {(url: NSURL) in
self.convertImage(url)
}
displayViewInMain(newController)
displayedView = .Welcome
}
/// Displays the result view
///
func displayResultView(result: String) {
let newController = storyboard!.instantiateControllerWithIdentifier("resultView") as! NSViewController
newController.representedObject = result
displayViewInMain(newController)
displayedView = .Result
}
/// Displays the error view
///
func displayErrorView(error: ConverterError) {
let newController = storyboard!.instantiateControllerWithIdentifier("errorView") as! NSViewController
newController.representedObject = error
displayViewInMain(newController)
displayedView = .Error
}
/// Displays a new view using a given view controller.
///
func displayViewInMain(newController: NSViewController) {
if mainViewController != nil {
for view in mainView.subviews {
view.removeFromSuperviewWithoutNeedingDisplay();
}
}
let newView = newController.view;
newView.translatesAutoresizingMaskIntoConstraints = false
mainView.addSubview(newView)
mainView.addConstraint(NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: mainView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0));
mainView.addConstraint(NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: mainView, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0));
mainView.addConstraint(NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: mainView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0));
mainView.addConstraint(NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: mainView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0));
self.mainViewController = newController
}
/// Convert the given image into code
///
func convertImage(url: NSURL) {
// Run this things in another thread.
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), {
// Try to open the file as NSImage.
if let image = NSImage(contentsOfURL: url) {
do {
// Get the image object for the converter.
let inputImage = try InputImageFromNSImage(image: image)
// Store a copy for later print of a character map
self.inputImage = inputImage
// Get the byte writer for the output.
let selectedOutputIndex = self.outputFormatSelection.indexOfSelectedItem
let sourceCodeGeneratorItem = self.sourceCodeGenerators[selectedOutputIndex]
let sourceCodeOptions = SourceCodeOptions(
inversion: self.invertBitsCheckbox.state == NSOnState ? .Invert : .None,
bitOrder: self.reverseBitsCheckbox.state == NSOnState ? .Reverse : .Normal)
let sourceCodeGenerator = sourceCodeGeneratorItem.createGenerator(sourceCodeOptions)
// Get the selected mode item.
if let modeItem = self.navigation.itemAtRow(self.navigation.selectedRow) as? ModeItem {
// Start the selected converter
let converter = modeItem.converter!
try converter.convertImage(inputImage, byteWriter: sourceCodeGenerator)
// Get the produced code and display it in the result view
let sourceCode = sourceCodeGenerator.sourceCode
self.code = sourceCode
dispatch_async(dispatch_get_main_queue(), {
self.displayResultView(sourceCode)
})
} else {
dispatch_async(dispatch_get_main_queue(), {
let error = ConverterError(summary: "No Mode Selected",
details: "There is no mode selected. Select your desired mode in the navigation at the left side in this window.")
self.displayErrorView(error)
})
}
} catch let error as ConverterError {
dispatch_async(dispatch_get_main_queue(), {
self.displayErrorView(error)
})
} catch {
dispatch_async(dispatch_get_main_queue(), {
let error = ConverterError(summary: "Unknown Error",
details: "There was a unknown problem. Try again and if the problem persists contact the author of the software.")
self.displayErrorView(error)
})
}
} else {
dispatch_async(dispatch_get_main_queue(), {
let error = ConverterError(summary: "Problem Loading the Image File",
details: "There was a problem while loading the image file. Check if the file is a valid PNG file in RGB or RGBA format.")
self.displayErrorView(error)
})
}
})
}
/// Create a character map to print or as PDF
///
@IBAction func printDocument(sender: AnyObject) {
// Run this things in another thread.
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), {
do {
guard let modeItem = self.navigation.itemAtRow(self.navigation.selectedRow) as? ModeItem else {
return
}
// Start the selected converter
let converter = modeItem.converter!
let characterMap = try converter.createCharacterImages(self.inputImage!)
// Start the print from the main queue
dispatch_async(dispatch_get_main_queue(), {
let printView = PrintView(characterMap: characterMap)
let printOperation = NSPrintOperation(view: printView)
printOperation.runOperation()
})
} catch {
// ignore any problems.
}
})
}
// Implement NSOutlineViewDataSource and NSOutlineViewDelegate
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
if item == nil {
return 1
} else {
return modeItems.count
}
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
if item is ModeItem {
let modeItem = item as! ModeItem
return modeItem.isSection
} else {
return false
}
}
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
if item == nil {
return modeSectionItem
} else {
if item === self.modeSectionItem {
return modeItems[index]
}
return ModeItem(title: "Unknown")
}
}
func outlineView(outlineView: NSOutlineView, shouldShowOutlineCellForItem item: AnyObject) -> Bool {
return false
}
func outlineView(outlineView: NSOutlineView, shouldSelectItem item: AnyObject) -> Bool {
guard let modeItem = item as? ModeItem else {
return false
}
return !modeItem.isSection
}
func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? {
guard let modeItem = item as? ModeItem else {
return nil
}
if modeItem.isSection {
let view = outlineView.makeViewWithIdentifier("HeaderCell", owner: self) as! NSTableCellView
view.textField?.stringValue = modeItem.title
return view
} else {
let view = outlineView.makeViewWithIdentifier("DataCell", owner: self) as! NSTableCellView
view.textField?.stringValue = modeItem.title
return view
}
}
}
| gpl-2.0 | c8f3401c84b0dde245853434615f76ab | 39.211443 | 229 | 0.614538 | 5.402741 | false | false | false | false |
silt-lang/silt | Sources/InnerCore/IRGenerator.swift | 1 | 4895 | /// IRGenerator.swift
///
/// Copyright 2019, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import LLVM
import OuterCore
import Seismography
public enum IRGen {
public static func emit(_ module: GIRModule) -> Module {
let igm = IRGenModule(module: module)
igm.emit()
igm.emitMain()
return igm.module
}
}
extension IRBuilder {
func getOrCreateIntrinsic(
_ name: String, _ signature: LLVM.FunctionType
) -> Function {
if let intrinsic = self.module.function(named: name) {
return intrinsic
}
return self.addFunction(name, type: signature)
}
@discardableResult
func createLifetimeStart(
_ buf: Address, _ size: Size = Size(bits: UInt64.max)
) -> Call {
let argTys: [IRType] = [IntType.int64, PointerType.toVoid]
let sig = LLVM.FunctionType(argTys, VoidType())
let fn = self.getOrCreateIntrinsic("llvm.lifetime.start.p0i8", sig)
let addr: Address
if buf.address.type.asLLVM() == PointerType.toVoid.asLLVM() {
addr = buf
} else {
addr = self.createPointerBitCast(of: buf, to: PointerType.toVoid)
}
return self.buildCall(fn, args: [
IntType.int64.constant(size.rawValue),
addr.address,
])
}
@discardableResult
func createLifetimeEnd(
_ buf: Address, _ size: Size = Size(bits: UInt64.max)
) -> Call {
let argTys: [IRType] = [IntType.int64, PointerType.toVoid]
let sig = LLVM.FunctionType(argTys, VoidType())
let fn = self.getOrCreateIntrinsic("llvm.lifetime.end.p0i8", sig)
let addr: Address
if buf.address.type.asLLVM() == PointerType.toVoid.asLLVM() {
addr = buf
} else {
addr = self.createPointerBitCast(of: buf, to: PointerType.toVoid)
}
return self.buildCall(fn, args: [
IntType.int64.constant(size.rawValue),
addr.address
])
}
}
extension IRBuilder {
func createLoad(
_ ptr: Address, ordering: AtomicOrdering = .notAtomic,
volatile: Bool = false, alignment: Alignment = .zero,
name: String = ""
) -> IRValue {
return self.buildLoad(ptr.address, type: ptr.pointeeType,
ordering: ordering, volatile: volatile,
alignment: alignment, name: name)
}
func createAlloca(
_ type: IRType, count: IRValue? = nil,
alignment: Alignment, name: String = ""
) -> Address {
let alloca = self.buildAlloca(type: type, count: count,
alignment: alignment, name: name)
return Address(alloca, alignment, type)
}
func createPointerBitCast(
of address: Address, to type: PointerType
) -> Address {
let addr = self.buildBitCast(address.address, type: type)
return Address(addr, address.alignment, address.pointeeType)
}
func createElementBitCast(
_ address: Address, _ type: IRType, name: String
) -> Address {
guard let origPtrType = address.address.type as? PointerType else {
fatalError()
}
if origPtrType.pointee.asLLVM() == type.asLLVM() {
return address
}
let ptrType = PointerType(pointee: type)
return self.createPointerBitCast(of: address, to: ptrType)
}
func createStructGEP(_ address: Address, _ index: Int,
_ layout: LLVM.StructLayout, _ name: String) -> Address {
guard let str = address.pointeeType as? StructType else {
fatalError()
}
let offset = layout.memberOffsets[index]
let addr = self.buildStructGEP(address.address, type: address.pointeeType,
index: index,
name: address.address.name + name)
return Address(addr, address.alignment.alignment(at: offset),
str.elementTypes[index])
}
func createStructGEP(_ address: Address, _ index: Int,
_ offset: Size, _ name: String) -> Address {
guard let str = address.pointeeType as? StructType else {
fatalError()
}
let addr = self.buildStructGEP(address.address, type: address.pointeeType,
index: index,
name: address.address.name + name)
return Address(addr, address.alignment.alignment(at: offset),
str.elementTypes[index])
}
func createBitOrPointerCast(_ value: IRValue, to destTy: IRType,
_ name: String = "") -> IRValue {
if value.type.asLLVM() == destTy.asLLVM() {
return value
}
if value.type is PointerType, let destIntTy = destTy as? IntType {
return self.buildPtrToInt(value, type: destIntTy, name: name)
}
if value.type is IntType, let destPtrTy = destTy as? PointerType {
return self.buildIntToPtr(value, type: destPtrTy, name: name)
}
return self.buildBitCast(value, type: destTy, name: name)
}
}
| mit | e8284f675e485d9e357fc70decc65b79 | 31.417219 | 80 | 0.628192 | 3.91287 | false | false | false | false |
oacastefanita/PollsFramework | Example/PollsFramework-mac/ViewObjectsViewController.swift | 1 | 5698 | //
// ViewObjectsViewController.swift
// PollsFramework
//
// Created by Stefanita Oaca on 29/08/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Cocoa
import PollsFramework
class ViewObjectsListViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
var objects = [Any]()
var selectedObject: Any!
@IBOutlet weak var tableView: NSTableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func numberOfRows(in tableView: NSTableView) -> Int {
return objects.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "textViewCell"), owner: self) as! TextViewTableViewCell
for (name, type) in NSObject.getTypesOfProperties(in: NSObject.classFromString((objects[row] as! NSObject).className).self as! NSObject.Type)!{
if let prop = (objects[row] as! NSObject).value(forKey: name){
cell.textView.string = cell.textView.string + name + ":" + "\(prop)\n"
}
}
return cell
}
func tableViewSelectionDidChange(_ notification: Notification) {
let row = tableView.selectedRowIndexes.first!
selectedObject = objects[row]
if selectedObject is Poll{
if (selectedObject as! Poll).pollTypeId == PollTypes.singleText.rawValue{
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "showSingleTextPoll"), sender: self)
return
}
if (selectedObject as! Poll).pollTypeId == PollTypes.bestText.rawValue{
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "showBestTextPoll"), sender: self)
return
}
if (selectedObject as! Poll).pollTypeId == PollTypes.singleImage.rawValue{
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "showSingleImagePoll"), sender: self)
return
}
if (selectedObject as! Poll).pollTypeId == PollTypes.bestImage.rawValue{
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "showBestImagePoll"), sender: self)
return
}
} else if selectedObject is Country{
PollsFrameworkController.sharedInstance.getStateByCountry(country: selectedObject as! Country){ (success, response) in
if !success {
}
else {
let secondViewController = self.storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "viewObjectsListViewController")) as! ViewObjectsListViewController
secondViewController.objects = response
self.presentViewControllerAsModalWindow(secondViewController)
}
}
return
} else if selectedObject is State{
PollsFrameworkController.sharedInstance.getCitiesByState(state: selectedObject as! State){ (success, response) in
if !success {
}
else {
let secondViewController = self.storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "viewObjectsListViewController")) as! ViewObjectsListViewController
secondViewController.objects = response
self.presentViewControllerAsModalWindow(secondViewController)
}
}
return
}
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "showObjectDetailsFromObjectsList"), sender: self)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if segue.identifier!.rawValue == "showObjectDetailsFromObjectsList"{
(segue.destinationController as! ViewObjectViewController).object = self.selectedObject
} else if segue.identifier!.rawValue == "showSingleTextPoll"{
(segue.destinationController as! SingleTextPollViewController).screenType = (self.selectedObject as! Poll).isPublished == false ? .draft : .edit
(segue.destinationController as! SingleTextPollViewController).poll = self.selectedObject as! Poll
} else if segue.identifier!.rawValue == "showBestTextPoll"{
(segue.destinationController as! BestTextPollViewController).screenType = (self.selectedObject as! Poll).isPublished == false ? .draft : .edit
(segue.destinationController as! BestTextPollViewController).poll = self.selectedObject as! Poll
} else if segue.identifier!.rawValue == "showSingleImagePoll"{
(segue.destinationController as! SingleImagePollViewController).screenType = (self.selectedObject as! Poll).isPublished == false ? .draft : .edit
(segue.destinationController as! SingleImagePollViewController).poll = self.selectedObject as! Poll
} else if segue.identifier!.rawValue == "showBestImagePoll"{
(segue.destinationController as! BestImagePollViewController).screenType = (self.selectedObject as! Poll).isPublished == false ? .draft : .edit
(segue.destinationController as! BestImagePollViewController).poll = self.selectedObject as! Poll
}
}
@IBAction func onDone(_ sender: Any) {
self.view.window?.close()
}
}
| mit | 08a528fca2ad35aa60940591b868e812 | 49.866071 | 208 | 0.657364 | 5.314366 | false | false | false | false |
uber/rides-ios-sdk | source/UberRides/Model/RideRequestLocation.swift | 1 | 3866 | //
// RideRequestLocation.swift
// UberRides
//
// Copyright © 2016 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 UberCore
// MARK: RideRequestLocation
/**
* Location of a pickup or destination in a ride request.
*/
@objc(UBSDKRideRequestLocation) public class RideRequestLocation: NSObject, Codable {
/**
The alias from an Uber user’s profile mapped to the pickup address (if available).
Can be either work or home. Only exposed with a valid access token for places scope.
*/
@objc public private(set) var alias: String?
/// The name of the pickup place (if available). Not exposed in sandbox.
@objc public private(set) var name: String?
/// The current bearing in degrees for a moving location.
@nonobjc public private(set) var bearing: Int?
/// The current bearing in degrees for a moving location.
@objc(bearing) public var objc_bearing: NSNumber? {
if let bearing = bearing {
return NSNumber(value: bearing)
} else {
return nil
}
}
/// ETA is only available when the trips is accepted or arriving.
@nonobjc public private(set) var eta: Int?
/// ETA is only available when the trips is accepted or arriving.
@objc(eta) public var objc_eta: NSNumber? {
if let eta = eta {
return NSNumber(value: eta)
} else {
return nil
}
}
/// The latitude of the location.
@nonobjc public private(set) var latitude: Double?
/// The latitude of the location.
@objc(latitude) public var objc_latitude: NSNumber? {
if let latitude = latitude {
return NSNumber(value: latitude)
} else {
return nil
}
}
/// The longitude of the location.
@nonobjc public private(set) var longitude: Double?
/// The longitude of the location.
@objc(longitude) public var objc_longitude: NSNumber? {
if let longitude = longitude {
return NSNumber(value: longitude)
} else {
return nil
}
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
alias = try container.decodeIfPresent(String.self, forKey: .alias)
name = try container.decodeIfPresent(String.self, forKey: .name)
bearing = try container.decodeIfPresent(Int.self, forKey: .bearing)
eta = try container.decodeIfPresent(Int.self, forKey: .eta)
eta = eta != -1 ? eta : nil // Since the API returns -1, converting to an optional.
latitude = try container.decodeIfPresent(Double.self, forKey: .latitude)
longitude = try container.decodeIfPresent(Double.self, forKey: .longitude)
}
}
| mit | ea6c9bff4fdc5770463392055960e33d | 37.63 | 92 | 0.674087 | 4.414857 | false | false | false | false |
SomaticLabs/SwiftMomentSDK | SwiftyZorb/Public/SwiftyZorb.swift | 1 | 10419 | //
// SwiftyZorb.swift
// SwiftyZorb
//
// Created by Jacob Rockland on 2/22/17.
// Copyright © 2017 Somatic Technologies, Inc. All rights reserved.
//
import SwiftyBluetooth
import Alamofire
import SwiftyJSON
// MARK: Bluetooth Management Methods
/**
Scans for and retrieves a collection of available Zorb devices with a given hardware version (either V1 or V2) as enumerated in `ZorbDevice.Version`.
Usage Example:
```swift
// Retrieves a list all available devices as an array of `ZorbDevice` objects.
SwiftyZorb.retrieveAvailableDevices(withVersion: .V2) { result in
switch result {
case .success(let devices):
// Retrieval succeeded
for device in devices {
// Do something with devices
}
case .failure(let error):
// An error occurred during retrieval
}
}
```
*/
public func retrieveAvailableDevices(withVersion version: ZorbDevice.Version, completion: @escaping (SwiftyBluetooth.Result<[ZorbDevice]>) -> Void) {
bluetoothManager.retrieveAvailableDevices(withVersion: version) { result in completion(result) }
}
/**
Maintaining backwares compatibility, scans for and retrieves a collection of available Zorb devices with V1 hardware.
Usage Example:
```swift
// Retrieves a list all available devices as an array of `ZorbDevice` objects.
SwiftyZorb.retrieveAvailableDevices(withVersion: .V2) { result in
switch result {
case .success(let devices):
// Retrieval succeeded
for device in devices {
// Do something with devices
}
case .failure(let error):
// An error occurred during retrieval
}
}
```
*/
@available(*, deprecated, message: "Please specify hardware version with `withVersion` parameter.")
public func retrieveAvailableDevices(completion: @escaping (SwiftyBluetooth.Result<[ZorbDevice]>) -> Void) {
bluetoothManager.retrieveAvailableDevices(withVersion: .V1) { result in completion(result) }
}
/**
Initiates a connection to an advertising Zorb device with a given hardware version (either V1 or V2) as enumerated in` ZorbDevice.Version`.
Usage Example:
```swift
// Attempts connection to an advertising device
SwiftyZorb.connect(withVersion: .V2) { result in
switch result {
case .success:
// Connect succeeded
case .failure(let error):
// An error occurred during connection
}
}
```
*/
public func connect(withVersion version: ZorbDevice.Version, completion: @escaping ConnectPeripheralCallback) {
bluetoothManager.connect(withVersion: version) { result in completion(result) }
}
/**
Maintaining backwares compatibility, initiates a connection to an advertising Zorb device with V1 hardware.
Usage Example:
```swift
// Attempts connection to an advertising device
SwiftyZorb.connect { result in
switch result {
case .success:
// Connect succeeded
case .failure(let error):
// An error occurred during connection
}
}
```
*/
@available(*, deprecated, message: "Please specify hardware version with `withVersion` parameter.")
public func connect(completion: @escaping ConnectPeripheralCallback) {
bluetoothManager.connect(withVersion: .V1) { result in completion(result) }
}
/**
Ends connection to a connected Zorb device.
Usage Example:
```swift
// After calling this method, device disconnection will be guaranteed
SwiftyZorb.disconnect()
```
*/
public func disconnect() {
bluetoothManager.device?.disconnect()
}
/**
Forgets previously stored device connection.
Usage Example:
```swift
// After calling this method, a new device connection can be created
SwiftyZorb.forget()
```
*/
public func forget() {
Settings.resetZorbPeripheral()
}
// MARK: Bluetooth Javascript Methods
/**
Writes the appropriate command to reset connected Zorb device's Javascript virtual machine.
Usage Example:
```swift
SwiftyZorb.reset { result in
switch result {
case .success:
// Reset succeeded
case .failure(let error):
// An error occurred during reset
}
}
```
*/
public func reset(completion: @escaping WriteRequestCallback) {
bluetoothManager.device?.reset { result in completion(result) }
}
/**
Reads version `String` from Zorb device.
Usage Example:
```swift
SwiftyZorb.readVersion { result in
switch result {
case .success(let version):
// Reading version string succeeded
case .failure(let error):
// An error occurred during read
}
}
```
*/
public func readVersion(completion: @escaping (SwiftyBluetooth.Result<String>) -> Void) {
bluetoothManager.device?.readVersion { result in completion(result) }
}
/**
Reads serial `String` from Zorb device.
Usage Example:
```swift
SwiftyZorb.readSerial { result in
switch result {
case .success(let serial):
// Reading serial string succeeded
case .failure(let error):
// An error occurred during read
}
}
```
*/
public func readSerial(completion: @escaping (SwiftyBluetooth.Result<String>) -> Void) {
bluetoothManager.device?.readSerial { result in completion(result) }
}
/**
Writes desired actuator data to Zorb device.
Usage Example:
```swift
SwiftyZorb.writeActuators(duration: 100, topLeft: 0, topRight: 0, bottomLeft: 25, bottomRight: 25) { result in
switch result {
case .success:
// Write succeeded
case .failure(let error):
// An error occurred during write
}
}
```
- Parameter duration: The total duration, in milliseconds for the given set of vibrations to last.
- Parameter topLeft: Intensity, in a range from 0 to 100, for the top left actuator to be set at.
- Parameter topRight: Intensity, in a range from 0 to 100, for the top right actuator to be set at.
- Parameter bottomLeft: Intensity, in a range from 0 to 100, for the bottom left actuator to be set at.
- Parameter bottomRight: Intensity, in a range from 0 to 100, for the bottom right actuator to be set at.
*/
public func writeActuators(duration: UInt16, topLeft: UInt8, topRight: UInt8, bottomLeft: UInt8, bottomRight: UInt8, completion: @escaping WriteRequestCallback) {
bluetoothManager.device?.writeActuators(duration: duration, topLeft: topLeft, topRight: topRight, bottomLeft: bottomLeft, bottomRight: bottomRight) { result in completion(result) }
}
/**
Writes a given string of Javascript to the connected Zorb device.
Using this method requires internet connection, which is used to compile the Javascript to bytecode before transmission.
Usage Example:
```swift
let javascript = "new Zorb.Vibration(" +
"0," +
"new Zorb.Effect(0,100,11,250)," +
"213" +
").start();"
SwiftyZorb.writeJavascript(javascript) { result in
switch result {
case .success:
// Write succeeded
case .failure(let error):
// An error occurred during write
}
}
```
- Parameter javascript: The Javascript code to be written
*/
public func writeJavascript(_ javascript: String, completion: @escaping WriteRequestCallback) {
bluetoothManager.device?.writeJavascript(javascript) { result in completion(result) }
}
/**
Writes the Javascript code at a given URL to the connected Zorb device.
Usage Example:
```swift
let url = URL(string: "https://gist.githubusercontent.com/jakerockland/17cb9cbfda0e09fa8251fc7666e2c4dc/raw")!
SwiftyZorb.writeJavascript(at url) { result in
switch result {
case .success:
// Write succeeded
case .failure(let error):
// An error occurred during write
}
}
```
- Parameter url: A URL to the hosted Javascript script to be written
*/
public func writeJavascript(at url: URL, completion: @escaping WriteRequestCallback) {
bluetoothManager.device?.writeJavascript(at: url) { result in completion(result) }
}
/**
Writes a Zorb_Timeline object (as specified by zorb.pb.swift) to the UART RX characteristic.
Usage Example:
```swift
// Create Zorb_Timeline and Zorb_Vibration objects using the generated types provided by zorb.pb.swift.
var timeline = Zorb_Timeline()
var vibration = Zorb_Vibration()
// Populate data in the Zorb_Vibration object.
vibration.channels = 0x01
vibration.delay = 1000
vibration.duration = 2000
vibration.position = 0
vibration.start = 0
vibration.end = 100
vibration.easing = 2
// Append the Zorb_Vibration to the Zorb_Timeline.
timeline.vibrations.append(vibration)
// Write the bytecode to the UART RX characteristic.
SwiftyZorb.writeTimeline(timeline) { result in
switch result {
case .success:
// Write succeeded
case .failure(let error):
// An error occurred during write
}
}
```
- Parameter timeline: A Zorb_Timeline object (from zorb-protocol)
*/
public func writeTimeline(_ timeline: Zorb_Timeline, completion: @escaping WriteRequestCallback) {
bluetoothManager.device?.writeTimeline(timeline) { result in completion(result) }
}
/**
Writes a given string of base64 encoded bytecode to the connected Zorb device.
Usage Example:
```swift
let bytecode = "BgAAAFAAAAAsAAAAAQAAAAQAAQABAAUAAAEDBAYAAQACAAYAOwABKQIDxEYBAAAABAABACEAAwABAgMDAAAGAAgAOwECt8gARgAAAAAAAAAFAAAAAAAAAAIAb24JAHRpbWVydGljawABAHQABgBNb21lbnQGAHVwdGltZQ=="
SwiftyZorb.writeBytecode(bytecode) { result in
switch result {
case .success:
// Write succeeded
case .failure(let error):
// An error occurred during write
}
}
```
- Parameter bytecode: The base64 encoded representation of pre-compiled Javascript bytecode to be written
*/
public func writeBytecodeString(_ bytecode: String, completion: @escaping WriteRequestCallback) {
bluetoothManager.device?.writeBytecodeString(bytecode) { result in completion(result) }
}
/**
Triggers a given pre-loaded pattern on the connected Zorb device.
Usage Example:
```swift
SwiftyZorb.triggerPattern(.🎊) { result in
switch result {
case .success:
// Pattern triggered successfully
case .failure(let error):
// An error occurred in triggering pattern
}
}
```
- Parameter pattern: The `Trigger` enumeration option of the given preloaded pattern to trigger
*/
public func triggerPattern(_ pattern: Trigger, completion: @escaping WriteRequestCallback) {
bluetoothManager.device?.triggerPattern(pattern) { result in completion(result) }
}
| mit | 259ff72a3a51e7faf89bd702b62cdc6d | 27.930556 | 186 | 0.71109 | 4.149402 | false | false | false | false |
TOWNTHON/Antonym | iOS/Antonym/Networking/NetworkEngine.swift | 1 | 2756 | //
// HttpMethod.swift
// Antonym
//
// Created by 広瀬緑 on 2016/10/29.
// Copyright © 2016年 midori hirose. All rights reserved.
//
import UIKit
import AVFoundation
final class NetworkEngine {
var antonym = ""
private let talker = AVSpeechSynthesizer()
func getAsync(text: String) {
let urlString = "http://antonym.herokuapp.com/api/antonyms/?phrase=" + uriEncode(text: text)
guard let url = URL(string: urlString) else {
return
}
var request = NSMutableURLRequest(url: url) as URLRequest
request.httpMethod = "GET"
// use NSURLSessionDataTask
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
if (error == nil) {
let json = try! JSONSerialization.jsonObject(with: data!, options: []) as? [String:[[String:AnyObject]]]
guard let phrases = json?["phrases"] else {
return
}
for phrase in phrases {
guard let antonyma = phrase["antonym"] as? String else {
return
}
self.antonym = antonyma
self.speech(text: self.antonym)
print(self.antonym)
}
} else {
print(error)
}
})
task.resume()
}
// func fetchData(text: String) -> String {
// //Construct url object via string
// let urlString = "http://antonym.herokuapp.com/api/antonyms/?phrase=" + uriEncode(text: text)
// var url = NSURL(string: urlString)
// let task = URLSession.shared.dataTask(with: url!) { data, response, error in
// guard error == nil else {
// print(error)
// return
// }
// guard let data = data else {
// print("Data is empty")
// return
// }
//
// let json = try! JSONSerialization.jsonObject(with: data, options: [])
// print(json)
// }
// task.resume()
// return text
// }
func uriEncode(text: String) -> String {
return text.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.alphanumerics)!
}
private func speech(text: String) {
let utterance = AVSpeechUtterance(string: text)
setOptionsForSpeech(utterance: utterance)
self.talker.speak(utterance)
}
private func setOptionsForSpeech(utterance: AVSpeechUtterance) {
utterance.voice = AVSpeechSynthesisVoice(language: "ja-JP")
utterance.pitchMultiplier = 0.8
utterance.rate = 0.1
}
}
| mit | 5cf95efaef99467d30dfdca7f40093ce | 32.5 | 120 | 0.544594 | 4.42351 | false | false | false | false |
dobnezmi/EmotionNote | EmotionNote/WeeklyViewCell.swift | 1 | 4426 | //
// WeeklyViewCell.swift
// EmotionNote
//
// Created by Shingo Suzuki on 2016/09/29.
// Copyright © 2016年 dobnezmi. All rights reserved.
//
import UIKit
import RxSwift
class WeeklyViewCell: ChartViewCell {
@IBOutlet weak var scrollView: UIScrollView!
let disposeBag = DisposeBag()
// Cell ID
static let WeeklyChartCellID = "WeeklyCell"
// Presenter
let weeklyPresenter: WeeklyChartPresenter = Injector.container.resolve(WeeklyChartPresenter.self)!
// キャプションラベル
var captionLabels: [UILabel] = []
// 感情統計
var pieChartViews: [PieChartView] = []
let leftMargin: CGFloat = 10
let rightMargin: CGFloat = 20
let dataStore: EmotionDataStore = Injector.container.resolve(EmotionDataStore.self)!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
class func nib() -> UINib {
return UINib(nibName: NSStringFromClass(self).components(separatedBy: ".").last!,
bundle: Bundle(for: self))
}
func clearViews() {
for subview in scrollView.subviews {
subview.removeFromSuperview()
}
captionLabels.removeAll()
}
func showWeeklyEmotionChart() {
if captionLabels.count > 0 {
return
}
weeklyPresenter.rx_weeklyEmotion.asObservable().subscribe(onNext: { [weak self] emotionCount in
self?.createCharts(emotionCount: emotionCount)
}).addDisposableTo(disposeBag)
}
func createPiechart(pieChart: PieChartView?, emotionCount: EmotionCount) {
guard emotionCount.sumAllEmotions() > 0 else {
if let pieChart = pieChart {
emptyLabel(baseView: scrollView, rect: pieChart.frame)
}
return
}
let happyEntry = PieChartDataEntry(value: Double(emotionCount.happyCount), label: Emotion.Happy.toString())
let enjoyEntry = PieChartDataEntry(value: Double(emotionCount.enjoyCount), label: Emotion.Enjoy.toString())
let sadEntry = PieChartDataEntry(value: Double(emotionCount.sadCount), label: Emotion.Sad.toString())
let frustEntry = PieChartDataEntry(value: Double(emotionCount.frustCount), label: Emotion.Frustrated.toString())
let values = datasetValues(entries: [happyEntry, enjoyEntry, sadEntry, frustEntry])
let dataSet = PieChartDataSet(values: values, label: nil)
dataSet.sliceSpace = 2.0
dataSet.colors = ChartColorTemplates.material()
let chartData = PieChartData(dataSet: dataSet)
let formatter = NumberFormatter()
formatter.numberStyle = .none
chartData.setValueFormatter(DefaultValueFormatter(formatter: formatter))
if let pieChart = pieChart {
pieChart.data = chartData
pieChart.drawHoleEnabled = false
pieChart.legend.horizontalAlignment = .center
scrollView.addSubview(pieChart)
}
}
private func createCharts(emotionCount: [EmotionCount]) {
var posY: CGFloat = 44.0
for i in 0 ..< SSWeekday.weekdayCount() {
captionLabels.append(UILabel())
createCaptionLabel(baseView: scrollView,
targetLabel: captionLabels[i],
caption: "\(SSWeekday(rawValue: i)!.toString())の感情",
offsetY: posY)
posY = captionLabels[i].frame.origin.y + captionLabels[i].frame.height + 8
pieChartViews.append(PieChartView(frame:
CGRect(x: leftMargin, y: posY, width: self.frame.width-rightMargin, height: 250)))
pieChartViews[i].descriptionText = ""
createPiechart(pieChart: pieChartViews[i], emotionCount: emotionCount[i])
posY = pieChartViews[i].frame.origin.y + pieChartViews[i].frame.height + 16
}
scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: posY + 250 + 16 + 100)
}
private func datasetValues(entries: [PieChartDataEntry]) -> [PieChartDataEntry] {
var values: [PieChartDataEntry] = []
for entry in entries {
if entry.value > 0 {
values.append(entry)
}
}
return values
}
}
| apache-2.0 | 7539be692f3a499d8cb90621336fd089 | 34.991803 | 120 | 0.618766 | 4.804158 | false | false | false | false |
dhf/SwiftForms | SwiftForms/cells/FormSegmentedControlCell.swift | 1 | 3276 | //
// FormSegmentedControlCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 21/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormSegmentedControlCell: FormBaseCell {
/// MARK: Cell views
public let titleLabel = UILabel()
public let segmentedControl = UISegmentedControl()
public required init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
titleLabel.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
titleLabel.setContentCompressionResistancePriority(500, forAxis: .Horizontal)
segmentedControl.setContentCompressionResistancePriority(500, forAxis: .Horizontal)
titleLabel.font = (self as? FormFontDefaults).map {
$0.titleLabelFont
} ?? UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
contentView.addSubview(titleLabel)
contentView.addSubview(segmentedControl)
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
segmentedControl.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)
}
public override func update() {
super.update()
titleLabel.text = rowDescriptor.title
updateSegmentedControl()
if let value = rowDescriptor.value,
let options = rowDescriptor.configuration.options,
let idx = options.indexOf(value) {
segmentedControl.selectedSegmentIndex = idx
}
}
public override func constraintsViews() -> [String : UIView] {
return ["titleLabel" : titleLabel, "segmentedControl" : segmentedControl]
}
public override func defaultVisualConstraints() -> [String] {
if let text = titleLabel.text where !text.isEmpty {
return ["H:|-16-[titleLabel]-16-[segmentedControl]-16-|"]
}
else {
return ["H:|-16-[segmentedControl]-16-|"]
}
}
/// MARK: Actions
internal func valueChanged(sender: UISegmentedControl) {
let options = rowDescriptor.configuration.options
let optionValue = options?[sender.selectedSegmentIndex]
rowDescriptor.value = optionValue
}
/// MARK: Private
private func updateSegmentedControl() {
segmentedControl.removeAllSegments()
if let options = rowDescriptor.configuration.options {
for (idx, optionValue) in options.enumerate() {
segmentedControl.insertSegmentWithTitle(rowDescriptor.titleForOptionValue(optionValue), atIndex: idx, animated: false)
}
}
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 08d4b58bf2f2007f0dda8ff9b29dcdda | 34.989011 | 191 | 0.663511 | 5.560272 | false | false | false | false |
ps2/rileylink_ios | MinimedKitUI/Setup/MinimedPumpSetupCompleteViewController.swift | 1 | 884 | //
// MinimedPumpSetupCompleteViewController.swift
// Loop
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import UIKit
import LoopKitUI
class MinimedPumpSetupCompleteViewController: SetupTableViewController {
@IBOutlet private var pumpImageView: UIImageView!
var pumpImage: UIImage? {
didSet {
if isViewLoaded {
pumpImageView.image = pumpImage
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
pumpImageView.image = pumpImage
self.navigationItem.hidesBackButton = true
self.navigationItem.rightBarButtonItem = nil
}
override func continueButtonPressed(_ sender: Any) {
if let setupViewController = navigationController as? MinimedPumpManagerSetupViewController {
setupViewController.finishedSetup()
}
}
}
| mit | eb84f812207e35073014159cfc5174fe | 22.864865 | 101 | 0.669309 | 5.417178 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/Others/AVPageViewController.swift | 1 | 3702 | //
// AVPageViewController.swift
// AVLighterPageViewController
//
// Created by Angel Vasa on 13/01/16.
// Copyright © 2016 Angel Vasa. All rights reserved.
//
import UIKit
class AVPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var contentViews: Array<UIViewController>?
var presentingIndex: Int = 0
override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
super.init(transitionStyle: UIPageViewController.TransitionStyle.scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
self.delegate = self
self.dataSource = self
}
func setupControllers(_ contentViews: Array<UIViewController>, viewControllerFrameRect: CGRect, withPresentingViewControllerIndex index:Int) {
self.contentViews = contentViews
self.presentingIndex = index
self.setupViewControllerIndex(contentViews)
self.view.frame = viewControllerFrameRect
let viewController = NSArray(object: self.viewController(atIndex: self.presentingIndex))
self.setViewControllers(
viewController as? [UIViewController],
direction: UIPageViewController.NavigationDirection.forward,
animated: true,
completion: { [weak self] (finished: Bool) in
if finished {
DispatchQueue.main.async(execute: {
self!.setViewControllers(
viewController as? [UIViewController],
direction: UIPageViewController.NavigationDirection.forward,
animated: false,
completion: nil
)
})
}
})
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func viewController(atIndex index:Int) -> UIViewController {
let vc = self.contentViews![index] as! AVPageContentViewController
vc.viewControllerIndex = index
return vc
}
func setupViewControllerIndex(_ viewControllers: Array<UIViewController>) {
for i in 0 ..< viewControllers.count - 1 {
let vc = self.contentViews![i] as! AVPageContentViewController
vc.viewControllerIndex = i
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let viewController = viewController as! AVPageContentViewController
var index = viewController.viewControllerIndex as Int
if(index == 0 || index == NSNotFound) {
return nil
}
index -= 1
return self.viewController(atIndex: index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let viewController = viewController as! AVPageContentViewController
var index = viewController.viewControllerIndex as Int
if(index == NSNotFound || index == self.contentViews!.count - 1) {
return nil
}
index += 1
return self.viewController(atIndex: index)
}
func gotoNextViewController(_ index: Int) {
setupControllers(self.contentViews!, viewControllerFrameRect: self.view.frame, withPresentingViewControllerIndex: index)
}
}
| mpl-2.0 | 29fcde4f3ca39e375a98c54021110b51 | 40.58427 | 204 | 0.65739 | 6.047386 | false | false | false | false |
Josscii/iOS-Demos | ScrollTableViewDemo/ScrollTableViewDemo/ViewController4.swift | 1 | 2535 | //
// ViewController4.swift
// ScrollTableViewDemo
//
// Created by Josscii on 2017/11/26.
// Copyright © 2017年 Josscii. All rights reserved.
//
import UIKit
class CollaborativeScrollView: UIScrollView, UIGestureRecognizerDelegate {
var lastContentOffset: CGPoint = CGPoint(x: 0, y: 0)
// func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// return otherGestureRecognizer.view is CollaborativeScrollView
// }
}
class YourViewController: UIViewController, UIScrollViewDelegate {
private var mLockOuterScrollView = false
var mOuterScrollView: CollaborativeScrollView!
var mInnerScrollView: CollaborativeScrollView!
enum Direction {
case none, left, right, up, down
}
override func viewDidLoad() {
mOuterScrollView = CollaborativeScrollView(frame: view.bounds)
mOuterScrollView.contentSize = CGSize(width: view.bounds.width, height: view.bounds.height+300)
mOuterScrollView.backgroundColor = .green
view.addSubview(mOuterScrollView)
mInnerScrollView = CollaborativeScrollView(frame: CGRect(x: 0, y: 300, width: view.bounds.width, height: view.bounds.height))
mInnerScrollView.contentSize = CGSize(width: view.bounds.width, height: 2000)
mInnerScrollView.backgroundColor = .red
mOuterScrollView.addSubview(mInnerScrollView)
mOuterScrollView.delegate = self
mInnerScrollView.delegate = self
// mInnerScrollView.bounces = false
// mOuterScrollView.showsVerticalScrollIndicator = false
// mInnerScrollView.panGestureRecognizer.require(toFail: mOuterScrollView.panGestureRecognizer)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == mOuterScrollView {
} else {
let direction: Direction
if mInnerScrollView.lastContentOffset.y > scrollView.contentOffset.y {
direction = .down
} else {
direction = .up
}
if direction == .up && mOuterScrollView.contentOffset.y < 300 {
mInnerScrollView.isScrollEnabled = false
} else {
mInnerScrollView.isScrollEnabled = true
}
mInnerScrollView.lastContentOffset = scrollView.contentOffset;
}
}
}
| mit | 2f4cafa7fba7f2bb40574957e47b8e5c | 33.684932 | 159 | 0.657188 | 5.125506 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Dripping Sounds.xcplaygroundpage/Contents.swift | 1 | 2356 | //: ## Dripping Sounds
//: ### Physical model of a water drop letting hitting a pool.
//: ### What's this good for? We don't know, but hey it's cool. :)
import AudioKit
import XCPlayground
var playRate = 2.0
let drip = AKDrip(intensity: 1)
drip.intensity = 100
let reverb = AKReverb(drip)
AudioKit.output = reverb
AudioKit.start()
AKPlaygroundLoop(frequency: playRate) {
drip.trigger()
}
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Dripping Sounds")
addSubview(AKPropertySlider(
property: "Intensity",
value: drip.intensity, maximum: 300,
color: AKColor.redColor()
) { sliderValue in
drip.intensity = sliderValue
})
addSubview(AKPropertySlider(
property: "Damping Factor",
value: drip.dampingFactor, maximum: 2,
color: AKColor.greenColor()
) { sliderValue in
drip.dampingFactor = sliderValue
})
addSubview(AKPropertySlider(
property: "Energy Return",
value: drip.energyReturn, maximum: 5,
color: AKColor.yellowColor()
) { sliderValue in
drip.energyReturn = sliderValue
})
addSubview(AKPropertySlider(
property: "Main Resonant Frequency",
format: "%0.1f Hz",
value: drip.mainResonantFrequency, maximum: 800,
color: AKColor.cyanColor()
) { sliderValue in
drip.mainResonantFrequency = sliderValue
})
addSubview(AKPropertySlider(
property: "1st Resonant Frequency",
format: "%0.1f Hz",
value: drip.firstResonantFrequency, maximum: 800,
color: AKColor.cyanColor()
) { sliderValue in
drip.firstResonantFrequency = sliderValue
})
addSubview(AKPropertySlider(
property: "2nd Resonant Frequency",
format: "%0.1f Hz",
value: drip.secondResonantFrequency, maximum: 800,
color: AKColor.cyanColor()
) { sliderValue in
drip.secondResonantFrequency = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView() | mit | 8dcea60f9baeb7724b148c198add5c31 | 29.217949 | 67 | 0.592105 | 5.034188 | false | false | false | false |
lilongcnc/Swift-weibo2015 | ILWEIBO04/ILWEIBO04/Classes/UI/Main/TabBar.swift | 1 | 2397 | //
// TabBar.swift
// ILWEIBO04
//
// Created by 李龙 on 15/3/6.
// Copyright (c) 2015年 Lauren. All rights reserved.
//
import UIKit
class TabBar: UITabBar {
//MARK: 创建回调到视图控制器中的闭包
var composedButtonClicked: (() -> ())?
override func awakeFromNib() {
self.addSubview(Composebutton!)
}
override func layoutSubviews() {
super.layoutSubviews()
var index = 0
let num = self.subviews.count
let h = self.bounds.size.height
let w = self.bounds.size.width / CGFloat(count)
for view in self.subviews as! [UIView]{
//判断只是基础控件: view is UIControl
if view is UIControl && !(view is UIButton){
//设置控件的frame
let x = CGFloat(index) * w
view.frame = CGRectMake(x, 0, w, h)
self.addSubview(view)
index++
if index == 2 {
index++ //给加号空出一个位置
}
}
}
//设置中间按钮的frame
Composebutton!.frame = CGRectMake(2 * w, 0, w, h)
}
let count = 5
//懒加载中间的 加号图片
lazy var Composebutton : UIButton? = {
let btn = UIButton()
btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
//我们在懒加载中self.addSubview 这个方法不智能提示,是swift要求我们创建 在awakeFromNib中添加,各个方法更加的职责明确
//添加监听
btn.addTarget(self, action: "clickCompose", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
//点击方法
func clickCompose() {
//判断闭包是否设置了数值
if composedButtonClicked != nil{
composedButtonClicked!()
}
}
}
| mit | f733aa08debf633fc6bcccc0449a68fe | 25.402439 | 121 | 0.549654 | 4.436475 | false | false | false | false |
whiteath/ReadFoundationSource | Foundation/Decimal.swift | 2 | 71162 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public var NSDecimalMaxSize: Int32 { return 8 }
// Give a precision of at least 38 decimal digits, 128 binary positions.
public var NSDecimalNoScale: Int32 { return Int32(Int16.max) }
public struct Decimal {
fileprivate static let maxSize: UInt32 = UInt32(NSDecimalMaxSize)
fileprivate var __exponent: Int8
fileprivate var __lengthAndFlags: UInt8
fileprivate var __reserved: UInt16
public var _exponent: Int32 {
get {
return Int32(__exponent)
}
set {
__exponent = Int8(truncatingIfNeeded: newValue)
}
}
// length == 0 && isNegative -> NaN
public var _length: UInt32 {
get {
return UInt32((__lengthAndFlags & 0b0000_1111))
}
set {
guard newValue <= maxMantissaLength else {
fatalError("Attempt to set a length greater than capacity \(newValue) > \(maxMantissaLength)")
}
__lengthAndFlags =
(__lengthAndFlags & 0b1111_0000) |
UInt8(newValue & 0b0000_1111)
}
}
public var _isNegative: UInt32 {
get {
return UInt32(((__lengthAndFlags) & 0b0001_0000) >> 4)
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b1110_1111) |
(UInt8(newValue & 0b0000_0001 ) << 4)
}
}
public var _isCompact: UInt32 {
get {
return UInt32(((__lengthAndFlags) & 0b0010_0000) >> 5)
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b1101_1111) |
(UInt8(newValue & 0b0000_00001 ) << 5)
}
}
public var _reserved: UInt32 {
get {
return UInt32(UInt32(__lengthAndFlags & 0b1100_0000) << 10 | UInt32(__reserved))
}
set {
__lengthAndFlags =
(__lengthAndFlags & 0b0011_1111) |
UInt8(UInt32(newValue & (0b11 << 16)) >> 10)
__reserved = UInt16(newValue & 0b1111_1111_1111_1111)
}
}
public var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)
public init() {
self._mantissa = (0,0,0,0,0,0,0,0)
self.__exponent = 0
self.__lengthAndFlags = 0
self.__reserved = 0
}
fileprivate init(length: UInt32, mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)) {
self._mantissa = mantissa
self.__exponent = 0
self.__lengthAndFlags = 0
self.__reserved = 0
self._length = length
}
public init(_exponent: Int32, _length: UInt32, _isNegative: UInt32, _isCompact: UInt32, _reserved: UInt32, _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)){
self._mantissa = _mantissa
self.__exponent = Int8(truncatingIfNeeded: _exponent)
self.__lengthAndFlags = UInt8(_length & 0b1111)
self.__reserved = 0
self._isNegative = _isNegative
self._isCompact = _isCompact
self._reserved = _reserved
}
}
extension Decimal {
public static let leastFiniteMagnitude = Decimal(
_exponent: 127,
_length: 8,
_isNegative: 1,
_isCompact: 1,
_reserved: 0,
_mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)
)
public static let greatestFiniteMagnitude = Decimal(
_exponent: 127,
_length: 8,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)
)
public static let leastNormalMagnitude = Decimal(
_exponent: -127,
_length: 1,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)
)
public static let leastNonzeroMagnitude = Decimal(
_exponent: -127,
_length: 1,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)
)
public static let pi = Decimal(
_exponent: -38,
_length: 8,
_isNegative: 0,
_isCompact: 1,
_reserved: 0,
_mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58)
)
public var exponent: Int {
get {
return Int(self.__exponent)
}
}
public var significand: Decimal {
get {
return Decimal(_exponent: 0, _length: _length, _isNegative: _isNegative, _isCompact: _isCompact, _reserved: 0, _mantissa: _mantissa)
}
}
public init(sign: FloatingPointSign, exponent: Int, significand: Decimal) {
self.init(_exponent: Int32(exponent) + significand._exponent, _length: significand._length, _isNegative: sign == .plus ? 0 : 1, _isCompact: significand._isCompact, _reserved: 0, _mantissa: significand._mantissa)
}
public init(signOf: Decimal, magnitudeOf magnitude: Decimal) {
self.init(_exponent: magnitude._exponent, _length: magnitude._length, _isNegative: signOf._isNegative, _isCompact: magnitude._isCompact, _reserved: 0, _mantissa: magnitude._mantissa)
}
public var sign: FloatingPointSign {
return _isNegative == 0 ? FloatingPointSign.plus : FloatingPointSign.minus
}
public static var radix: Int {
return 10
}
public var ulp: Decimal {
if !self.isFinite { return Decimal.nan }
return Decimal(_exponent: _exponent, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
public func isEqual(to other: Decimal) -> Bool {
return self.compare(to: other) == .orderedSame
}
public func isLess(than other: Decimal) -> Bool {
return self.compare(to: other) == .orderedAscending
}
public func isLessThanOrEqualTo(_ other: Decimal) -> Bool {
let comparison = self.compare(to: other)
return comparison == .orderedAscending || comparison == .orderedSame
}
public func isTotallyOrdered(belowOrEqualTo other: Decimal) -> Bool {
// Notes: Decimal does not have -0 or infinities to worry about
if self.isNaN {
return false
} else if self < other {
return true
} else if other < self {
return false
}
// fall through to == behavior
return true
}
public var isCanonical: Bool {
return true
}
public var nextUp: Decimal {
return self + Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
public var nextDown: Decimal {
return self - Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000))
}
}
extension Decimal : Hashable, Comparable {
internal var doubleValue: Double {
var d = 0.0
if _length == 0 && _isNegative == 1 {
return Double.nan
}
d = d * 65536 + Double(_mantissa.7)
d = d * 65536 + Double(_mantissa.6)
d = d * 65536 + Double(_mantissa.5)
d = d * 65536 + Double(_mantissa.4)
d = d * 65536 + Double(_mantissa.3)
d = d * 65536 + Double(_mantissa.2)
d = d * 65536 + Double(_mantissa.1)
d = d * 65536 + Double(_mantissa.0)
if _exponent < 0 {
for _ in _exponent..<0 {
d /= 10.0
}
} else {
for _ in 0..<_exponent {
d *= 10.0
}
}
return _isNegative != 0 ? -d : d
}
public var hashValue: Int {
return Int(bitPattern: __CFHashDouble(doubleValue))
}
public static func ==(lhs: Decimal, rhs: Decimal) -> Bool {
if lhs.isNaN {
return rhs.isNaN
}
if lhs.__exponent == rhs.__exponent && lhs.__lengthAndFlags == rhs.__lengthAndFlags && lhs.__reserved == rhs.__reserved {
if lhs._mantissa.0 == rhs._mantissa.0 &&
lhs._mantissa.1 == rhs._mantissa.1 &&
lhs._mantissa.2 == rhs._mantissa.2 &&
lhs._mantissa.3 == rhs._mantissa.3 &&
lhs._mantissa.4 == rhs._mantissa.4 &&
lhs._mantissa.5 == rhs._mantissa.5 &&
lhs._mantissa.6 == rhs._mantissa.6 &&
lhs._mantissa.7 == rhs._mantissa.7 {
return true
}
}
var lhsVal = lhs
var rhsVal = rhs
return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedSame
}
public static func <(lhs: Decimal, rhs: Decimal) -> Bool {
var lhsVal = lhs
var rhsVal = rhs
return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedAscending
}
}
extension Decimal : ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self.init(value)
}
}
extension Decimal : ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.init(value)
}
}
extension Decimal : SignedNumeric {
public var magnitude: Decimal {
return Decimal(_exponent: _exponent, _length: _length, _isNegative: 0, _isCompact: _isCompact, _reserved: 0, _mantissa: _mantissa)
}
// FIXME(integers): implement properly
public init?<T : BinaryInteger>(exactly source: T) {
fatalError()
}
public static func +=(_ lhs: inout Decimal, _ rhs: Decimal) {
var leftOp = lhs
var rightOp = rhs
_ = NSDecimalAdd(&lhs, &leftOp, &rightOp, .plain)
}
public static func -=(_ lhs: inout Decimal, _ rhs: Decimal) {
var leftOp = lhs
var rightOp = rhs
_ = NSDecimalSubtract(&lhs, &leftOp, &rightOp, .plain)
}
public static func *=(_ lhs: inout Decimal, _ rhs: Decimal) {
var leftOp = lhs
var rightOp = rhs
_ = NSDecimalMultiply(&lhs, &leftOp, &rightOp, .plain)
}
public static func /=(_ lhs: inout Decimal, _ rhs: Decimal) {
var leftOp = lhs
var rightOp = rhs
_ = NSDecimalDivide(&lhs, &leftOp, &rightOp, .plain)
}
public static func +(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer += rhs
return answer;
}
public static func -(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer -= rhs
return answer;
}
public static func /(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer /= rhs
return answer;
}
public static func *(lhs: Decimal, rhs: Decimal) -> Decimal {
var answer = lhs
answer *= rhs
return answer;
}
public mutating func negate() {
_isNegative = _isNegative == 0 ? 1 : 0
}
}
extension Decimal {
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func add(_ other: Decimal) {
self += other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func subtract(_ other: Decimal) {
self -= other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func multiply(by other: Decimal) {
self *= other
}
@available(swift, obsoleted: 4, message: "Please use arithmetic operators instead")
@_transparent
public mutating func divide(by other: Decimal) {
self /= other
}
}
extension Decimal : Strideable {
public func distance(to other: Decimal) -> Decimal {
return self - other
}
public func advanced(by n: Decimal) -> Decimal {
return self + n
}
}
extension Decimal {
public typealias RoundingMode = NSDecimalNumber.RoundingMode
public typealias CalculationError = NSDecimalNumber.CalculationError
public init(_ value: UInt8) {
self.init(UInt64(value))
}
public init(_ value: Int8) {
self.init(Int64(value))
}
public init(_ value: UInt16) {
self.init(UInt64(value))
}
public init(_ value: Int16) {
self.init(Int64(value))
}
public init(_ value: UInt32) {
self.init(UInt64(value))
}
public init(_ value: Int32) {
self.init(Int64(value))
}
public init(_ value: Double) {
if value.isNaN {
self = Decimal.nan
} else if value == 0.0 {
self = Decimal()
} else {
self = Decimal()
let negative = value < 0
var val = negative ? -1 * value : value
var exponent = 0
while val < Double(UInt64.max - 1) {
val *= 10.0
exponent -= 1
}
while Double(UInt64.max - 1) < val {
val /= 10.0
exponent += 1
}
var mantissa = UInt64(val)
var i = Int32(0)
// this is a bit ugly but it is the closest approximation of the C initializer that can be expressed here.
while mantissa != 0 && i < NSDecimalMaxSize {
switch i {
case 0:
_mantissa.0 = UInt16(truncatingIfNeeded:mantissa)
case 1:
_mantissa.1 = UInt16(truncatingIfNeeded:mantissa)
case 2:
_mantissa.2 = UInt16(truncatingIfNeeded:mantissa)
case 3:
_mantissa.3 = UInt16(truncatingIfNeeded:mantissa)
case 4:
_mantissa.4 = UInt16(truncatingIfNeeded:mantissa)
case 5:
_mantissa.5 = UInt16(truncatingIfNeeded:mantissa)
case 6:
_mantissa.6 = UInt16(truncatingIfNeeded:mantissa)
case 7:
_mantissa.7 = UInt16(truncatingIfNeeded:mantissa)
default:
fatalError("initialization overflow")
}
mantissa = mantissa >> 16
i += 1
}
_length = UInt32(i)
_isNegative = negative ? 1 : 0
_isCompact = 0
_exponent = Int32(exponent)
self.compact()
}
}
public init(_ value: UInt64) {
self.init(Double(value))
}
public init(_ value: Int64) {
self.init(Double(value))
}
public init(_ value: UInt) {
self.init(UInt64(value))
}
public init(_ value: Int) {
self.init(Int64(value))
}
public var isSignalingNaN: Bool {
return false
}
public static var nan: Decimal {
return quietNaN
}
public static var quietNaN: Decimal {
var quiet = Decimal()
quiet._isNegative = 1
return quiet
}
public var floatingPointClass: FloatingPointClassification {
if _length == 0 && _isNegative == 1 {
return .quietNaN
} else if _length == 0 {
return .positiveZero
}
if _isNegative == 1 {
return .negativeNormal
} else {
return .positiveNormal
}
}
public var isSignMinus: Bool {
return _isNegative != 0
}
public var isNormal: Bool {
return !isZero && !isInfinite && !isNaN
}
public var isFinite: Bool {
return !isNaN
}
public var isZero: Bool {
return _length == 0 && _isNegative == 0
}
public var isSubnormal: Bool {
return false
}
public var isInfinite: Bool {
return false
}
public var isNaN: Bool {
return _length == 0 && _isNegative == 1
}
public var isSignaling: Bool {
return false
}
}
extension Decimal : CustomStringConvertible {
public init?(string: String, locale: Locale? = nil) {
let scan = Scanner(string: string)
var theDecimal = Decimal()
if !scan.scanDecimal(&theDecimal) {
return nil
}
self = theDecimal
}
public var description: String {
if self.isNaN {
return "NaN"
}
if _length == 0 {
return "0"
}
var copy = self
let ZERO : CChar = 0x30 // ASCII '0' == 0x30
let decimalChar : CChar = 0x2e // ASCII '.' == 0x2e
let MINUS : CChar = 0x2d // ASCII '-' == 0x2d
let bufferSize = 200 // max value : 39+128+sign+decimalpoint
var buffer = Array<CChar>(repeating: 0, count: bufferSize)
var i = bufferSize - 1
while copy._exponent > 0 {
i -= 1
buffer[i] = ZERO
copy._exponent -= 1
}
if copy._exponent == 0 {
copy._exponent = 1
}
while copy._length != 0 {
var remainder: UInt16 = 0
if copy._exponent == 0 {
i -= 1
buffer[i] = decimalChar
}
copy._exponent += 1
(remainder,_) = divideByShort(©, 10)
i -= 1
buffer[i] = Int8(remainder) + ZERO
}
if copy._exponent <= 0 {
while copy._exponent != 0 {
i -= 1
buffer[i] = ZERO
copy._exponent += 1
}
i -= 1
buffer[i] = decimalChar
i -= 1
buffer[i] = ZERO
}
if copy._isNegative != 0 {
i -= 1
buffer[i] = MINUS
}
return String(cString: Array(buffer.suffix(from:i)))
}
}
fileprivate func divideByShort<T:VariableLengthNumber>(_ d: inout T, _ divisor:UInt16) -> (UInt16,NSDecimalNumber.CalculationError) {
if divisor == 0 {
d._length = 0
return (0,.divideByZero)
}
// note the below is not the same as from length to 0 by -1
var carry: UInt32 = 0
for i in (0..<d._length).reversed() {
let accumulator = UInt32(d[i]) + carry * (1<<16)
d[i] = UInt16(accumulator / UInt32(divisor))
carry = accumulator % UInt32(divisor)
}
d.trimTrailingZeros()
return (UInt16(carry),.noError)
}
fileprivate func multiplyByShort<T:VariableLengthNumber>(_ d: inout T, _ mul:UInt16) -> NSDecimalNumber.CalculationError {
if mul == 0 {
d._length = 0
return .noError
}
var carry: UInt32 = 0
// FIXME handle NSCalculationOverflow here?
for i in 0..<d._length {
let accumulator: UInt32 = UInt32(d[i]) * UInt32(mul) + carry
carry = accumulator >> 16
d[i] = UInt16(truncatingIfNeeded: accumulator)
}
if carry != 0 {
if d._length >= Decimal.maxSize {
return .overflow
}
d[d._length] = UInt16(truncatingIfNeeded: carry)
d._length += 1
}
return .noError
}
fileprivate func addShort<T:VariableLengthNumber>(_ d: inout T, _ add:UInt16) -> NSDecimalNumber.CalculationError {
var carry:UInt32 = UInt32(add)
for i in 0..<d._length {
let accumulator: UInt32 = UInt32(d[i]) + carry
carry = accumulator >> 16
d[i] = UInt16(truncatingIfNeeded: accumulator)
}
if carry != 0 {
if d._length >= Decimal.maxSize {
return .overflow
}
d[d._length] = UInt16(truncatingIfNeeded: carry)
d._length += 1
}
return .noError
}
public func NSDecimalIsNotANumber(_ dcm: UnsafePointer<Decimal>) -> Bool {
return dcm.pointee.isNaN
}
/*************** Operations ***********/
public func NSDecimalCopy(_ destination: UnsafeMutablePointer<Decimal>, _ source: UnsafePointer<Decimal>) {
destination.pointee.__lengthAndFlags = source.pointee.__lengthAndFlags
destination.pointee.__exponent = source.pointee.__exponent
destination.pointee.__reserved = source.pointee.__reserved
destination.pointee._mantissa = source.pointee._mantissa
}
public func NSDecimalCompact(_ number: UnsafeMutablePointer<Decimal>) {
number.pointee.compact()
}
// NSDecimalCompare:Compares leftOperand and rightOperand.
public func NSDecimalCompare(_ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>) -> ComparisonResult {
let left = leftOperand.pointee
let right = rightOperand.pointee
return left.compare(to: right)
}
fileprivate extension UInt16 {
func compareTo(_ other: UInt16) -> ComparisonResult {
if self < other {
return .orderedAscending
} else if self > other {
return .orderedDescending
} else {
return .orderedSame
}
}
}
fileprivate func mantissaCompare<T:VariableLengthNumber>(
_ left: T,
_ right: T) -> ComparisonResult {
if left._length > right._length {
return .orderedDescending
}
if left._length < right._length {
return .orderedAscending
}
let length = left._length // == right._length
for i in (0..<length).reversed() {
let comparison = left[i].compareTo(right[i])
if comparison != .orderedSame {
return comparison
}
}
return .orderedSame
}
fileprivate func fitMantissa(_ big: inout WideDecimal, _ exponent: inout Int32, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if big._length <= Decimal.maxSize {
return .noError
}
var remainder: UInt16 = 0
var previousRemainder: Bool = false
// Divide by 10 as much as possible
while big._length > Decimal.maxSize + 1 {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&big,10000)
exponent += 4
}
while big._length > Decimal.maxSize {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&big,10)
exponent += 1
}
// If we are on a tie, adjust with previous remainder.
// .50001 is equivalent to .6
if previousRemainder && (remainder == 0 || remainder == 5) {
remainder += 1
}
if remainder == 0 {
return .noError
}
// Round the result
switch roundingMode {
case .down:
break
case .bankers:
if remainder == 5 && (big[0] & 1) == 0 {
break
}
fallthrough
case .plain:
if remainder < 5 {
break
}
fallthrough
case .up:
let originalLength = big._length
// big._length += 1 ??
_ = addShort(&big,1)
if originalLength > big._length {
// the last digit is == 0. Remove it.
_ = divideByShort(&big, 10)
exponent += 1
}
}
return .lossOfPrecision;
}
fileprivate func integerMultiply<T:VariableLengthNumber>(_ big: inout T,
_ left: T,
_ right: Decimal) -> NSDecimalNumber.CalculationError {
if left._length == 0 || right._length == 0 {
big._length = 0
return .noError
}
if big._length == 0 || big._length > left._length + right._length {
big._length = min(big.maxMantissaLength,left._length + right._length)
}
big.zeroMantissa()
var carry: UInt16 = 0
for j in 0..<right._length {
var accumulator: UInt32 = 0
carry = 0
for i in 0..<left._length {
if i + j < big._length {
let bigij = UInt32(big[i+j])
accumulator = UInt32(carry) + bigij + UInt32(right[j]) * UInt32(left[i])
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
big[i+j] = UInt16(truncatingIfNeeded:accumulator)
} else if carry != 0 || (right[j] == 0 && left[j] == 0) {
return .overflow
}
}
if carry != 0 {
if left._length + j < big._length {
big[left._length + j] = carry
} else {
return .overflow
}
}
}
big.trimTrailingZeros()
return .noError
}
fileprivate func integerDivide<T:VariableLengthNumber>(_ r: inout T,
_ cu: T,
_ cv: Decimal) -> NSDecimalNumber.CalculationError {
// Calculate result = a / b.
// Result could NOT be a pointer to same space as a or b.
// resultLen must be >= aLen - bLen.
//
// Based on algorithm in The Art of Computer Programming, Volume 2,
// Seminumerical Algorithms by Donald E. Knuth, 2nd Edition. In addition
// you need to consult the erratas for the book available at:
//
// http://www-cs-faculty.stanford.edu/~uno/taocp.html
var u = WideDecimal(true)
var v = WideDecimal(true) // divisor
// Simple case
if cv.isZero {
return .divideByZero;
}
// If u < v, the result is approximately 0...
if cu._length < cv._length {
for i in 0..<cv._length {
if cu[i] < cv[i] {
r._length = 0
return .noError;
}
}
}
// Fast algorithm
if cv._length == 1 {
r = cu
let (_,error) = divideByShort(&r, cv[0])
return error
}
u.copyMantissa(from: cu)
v.copyMantissa(from: cv)
u._length = cu._length + 1
v._length = cv._length + 1
// D1: Normalize
// Calculate d such that d*highest_digit of v >= b/2 (0x8000)
//
// I could probably use something smarter to get d to be a power of 2.
// In this case the multiply below became only a shift.
let d: UInt32 = UInt32((1 << 16) / Int(cv[cv._length - 1] + 1))
// This is to make the whole algorithm work and u*d/v*d == u/v
_ = multiplyByShort(&u, UInt16(d))
_ = multiplyByShort(&v, UInt16(d))
u.trimTrailingZeros()
v.trimTrailingZeros()
// Set a zero at the leftmost u position if the multiplication
// does not have a carry.
if u._length == cu._length {
u[u._length] = 0
u._length += 1
}
v[v._length] = 0; // Set a zero at the leftmost v position.
// the algorithm will use it during the
// multiplication/subtraction phase.
// Determine the size of the quotient.
// It's an approximate value.
let ql:UInt16 = UInt16(u._length - v._length)
// Some useful constants for the loop
// It's used to determine the quotient digit as fast as possible
// The test vl > 1 is probably useless, since optimizations
// up there are taking over this case. I'll keep it, just in case.
let v1:UInt16 = v[v._length-1]
let v2:UInt16 = v._length > 1 ? v[v._length-2] : 0
// D2: initialize j
// On each pass, build a single value for the quotient.
for j in 0..<ql {
// D3: calculate q^
// This formula and test for q gives at most q+1; See Knuth for proof.
let ul = u._length
let tmp:UInt32 = UInt32(u[ul - UInt32(j) - UInt32(1)]) << 16 + UInt32(u[ul - UInt32(j) - UInt32(2)])
var q:UInt32 = tmp / UInt32(v1) // Quotient digit. could be a short.
var rtmp:UInt32 = tmp % UInt32(v1)
// This test catches all cases where q is really q+2 and
// most where it is q+1
if q == (1 << 16) || UInt32(v2) * q > (rtmp<<16) + UInt32(u[ul - UInt32(j) - UInt32(3)]) {
q -= 1
rtmp += UInt32(v1)
if (rtmp < (1 << 16)) && ( (q == (1 << 16) ) || ( UInt32(v2) * q > (rtmp<<16) + UInt32(u[ul - UInt32(j) - UInt32(3)])) ) {
q -= 1
rtmp += UInt32(v1)
}
}
// D4: multiply and subtract.
var mk:UInt32 = 0 // multiply carry
var sk:UInt32 = 1 // subtraction carry
var acc:UInt32
// We perform a multiplication and a subtraction
// during the same pass...
for i in 0...v._length {
let ul = u._length
let vl = v._length
acc = q * UInt32(v[i]) + mk // multiply
mk = acc >> 16 // multiplication carry
acc = acc & 0xffff;
acc = 0xffff + UInt32(u[ul - vl + i - UInt32(j) - UInt32(1)]) - acc + sk; // subtract
sk = acc >> 16;
u[ul - vl + i - UInt32(j) - UInt32(1)] = UInt16(truncatingIfNeeded:acc)
}
// D5: test remainder
// This test catches cases where q is still q + 1
if sk == 0 {
// D6: add back.
var k:UInt32 = 0 // Addition carry
// subtract one from the quotient digit
q -= 1
for i in 0...v._length {
let ul = u._length
let vl = v._length
acc = UInt32(v[i]) + UInt32(u[UInt32(ul) - UInt32(vl) + UInt32(i) - UInt32(j) - UInt32(1)]) + k
k = acc >> 16;
u[UInt32(ul) - UInt32(vl) + UInt32(i) - UInt32(j) - UInt32(1)] = UInt16(truncatingIfNeeded:acc)
}
// k must be == 1 here
}
r[UInt32(ql - j - UInt16(1))] = UInt16(q)
// D7: loop on j
}
r._length = UInt32(ql);
r.trimTrailingZeros()
return .noError;
}
fileprivate func integerMultiplyByPowerOf10<T:VariableLengthNumber>(_ result: inout T, _ left: T, _ p: Int) -> NSDecimalNumber.CalculationError {
var power = p
if power == 0 {
result = left
return .noError
}
let isNegative = power < 0
if isNegative {
power = -power
}
result = left
let maxpow10 = pow10.count - 1
var error:NSDecimalNumber.CalculationError = .noError
while power > maxpow10 {
var big = T()
power -= maxpow10
let p10 = pow10[maxpow10]
if !isNegative {
error = integerMultiply(&big,result,p10)
} else {
error = integerDivide(&big,result,p10)
}
if error != .noError && error != .lossOfPrecision {
return error;
}
for i in 0..<big._length {
result[i] = big[i]
}
result._length = big._length
}
var big = T()
// Handle the rest of the power (<= maxpow10)
let p10 = pow10[Int(power)]
if !isNegative {
error = integerMultiply(&big, result, p10)
} else {
error = integerDivide(&big, result, p10)
}
for i in 0..<big._length {
result[i] = big[i]
}
result._length = big._length
return error;
}
public func NSDecimalRound(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) {
NSDecimalCopy(result,number) // this is unnecessary if they are the same address, but we can't test that here
result.pointee.round(scale: scale,roundingMode: roundingMode)
}
// Rounds num to the given scale using the given mode.
// result may be a pointer to same space as num.
// scale indicates number of significant digits after the decimal point
public func NSDecimalNormalize(_ a: UnsafeMutablePointer<Decimal>, _ b: UnsafeMutablePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
var diffexp = a.pointee.__exponent - b.pointee.__exponent
var result = Decimal()
//
// If the two numbers share the same exponents,
// the normalisation is already done
//
if diffexp == 0 {
return .noError
}
//
// Put the smallest of the two in aa
//
var aa: UnsafeMutablePointer<Decimal>
var bb: UnsafeMutablePointer<Decimal>
if diffexp < 0 {
aa = b
bb = a
diffexp = -diffexp
} else {
aa = a
bb = b
}
//
// Build a backup for aa
//
var backup = Decimal()
NSDecimalCopy(&backup,aa)
//
// Try to multiply aa to reach the same exponent level than bb
//
if integerMultiplyByPowerOf10(&result, aa.pointee, Int(diffexp)) == .noError {
// Succeed. Adjust the length/exponent info
// and return no errorNSDecimalNormalize
aa.pointee.copyMantissa(from: result)
aa.pointee._exponent = bb.pointee._exponent
return .noError;
}
//
// Failed, restart from scratch
//
NSDecimalCopy(aa, &backup);
//
// What is the maximum pow10 we can apply to aa ?
//
let logBase10of2to16 = 4.81647993
let aaLength = aa.pointee._length
let maxpow10 = Int8(floor(Double(Decimal.maxSize - aaLength) * logBase10of2to16))
//
// Divide bb by this value
//
_ = integerMultiplyByPowerOf10(&result, bb.pointee, Int(maxpow10 - diffexp))
bb.pointee.copyMantissa(from: result)
bb.pointee._exponent -= Int32(maxpow10 - diffexp);
//
// If bb > 0 multiply aa by the same value
//
if !bb.pointee.isZero {
_ = integerMultiplyByPowerOf10(&result, aa.pointee, Int(maxpow10))
aa.pointee.copyMantissa(from: result)
aa.pointee._exponent -= Int32(maxpow10)
} else {
bb.pointee._exponent = aa.pointee._exponent;
}
//
// the two exponents are now identical, but we've lost some digits in the operation.
//
return .lossOfPrecision;
}
public func NSDecimalAdd(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN {
result.pointee.setNaN()
return .overflow
}
if leftOperand.pointee.isZero {
NSDecimalCopy(result, rightOperand)
return .noError
} else if rightOperand.pointee.isZero {
NSDecimalCopy(result, leftOperand)
return .noError
} else {
var a = Decimal()
var b = Decimal()
var error:NSDecimalNumber.CalculationError = .noError
NSDecimalCopy(&a,leftOperand)
NSDecimalCopy(&b,rightOperand)
let normalizeError = NSDecimalNormalize(&a, &b,roundingMode)
if a.isZero {
NSDecimalCopy(result,&b)
return normalizeError
}
if b.isZero {
NSDecimalCopy(result,&a)
return normalizeError
}
result.pointee._exponent = a._exponent
if a.isNegative == b.isNegative {
var big = WideDecimal()
result.pointee.isNegative = a.isNegative
// No possible error here.
_ = integerAdd(&big,&a,&b)
if big._length > Decimal.maxSize {
var exponent:Int32 = 0
error = fitMantissa(&big, &exponent, roundingMode)
let newExponent = result.pointee._exponent + exponent
// Just to be sure!
if newExponent > Int32(Int8.max) {
result.pointee.setNaN()
return .overflow
}
result.pointee._exponent = newExponent
}
let length = min(Decimal.maxSize,big._length)
for i in 0..<length {
result.pointee[i] = big[i]
}
result.pointee._length = length
} else { // not the same sign
let comparison = mantissaCompare(a,b)
switch comparison {
case .orderedSame:
result.pointee.setZero()
case .orderedAscending:
_ = integerSubtract(&result.pointee,&b,&a)
result.pointee.isNegative = b.isNegative
case .orderedDescending:
_ = integerSubtract(&result.pointee,&a,&b)
result.pointee.isNegative = a.isNegative
}
}
result.pointee._isCompact = 0
NSDecimalCompact(result)
return error == .noError ? normalizeError : error
}
}
fileprivate func integerAdd(_ result: inout WideDecimal, _ left: inout Decimal, _ right: inout Decimal) -> NSDecimalNumber.CalculationError {
var i:UInt32 = 0
var carry:UInt16 = 0
var accumulator:UInt32 = 0
let c:UInt32 = min(left._length, right._length)
while i < c {
let li = UInt32(left[i])
let ri = UInt32(right[i])
accumulator = li + ri + UInt32(carry)
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
result[i] = UInt16(truncatingIfNeeded:accumulator)
i += 1
}
while i < left._length {
if carry != 0 {
let li = UInt32(left[i])
accumulator = li + UInt32(carry)
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
result[i] = UInt16(truncatingIfNeeded:accumulator)
i += 1
} else {
while i < left._length {
result[i] = left[i]
i += 1
}
break
}
}
while i < right._length {
if carry != 0 {
let ri = UInt32(right[i])
accumulator = ri + UInt32(carry)
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
result[i] = UInt16(truncatingIfNeeded:accumulator)
i += 1
} else {
while i < right._length {
result[i] = right[i]
i += 1
}
break
}
}
if carry != 0 {
if result._length < i {
result._length = i
return .overflow
} else {
result[i] = carry
i += 1
}
}
result._length = i;
return .noError;
}
// integerSubtract: Subtract b from a, put the result in result, and
// modify resultLen to match the length of the result.
// Result may be a pointer to same space as a or b.
// resultLen must be >= Max(aLen,bLen).
// Could return NSCalculationOverflow if b > a. In this case 0 - result
// give b-a...
//
fileprivate func integerSubtract(_ result: inout Decimal, _ left: inout Decimal, _ right: inout Decimal) -> NSDecimalNumber.CalculationError {
var i:UInt32 = 0
var carry:UInt16 = 1
var accumulator:UInt32 = 0
let c:UInt32 = min(left._length, right._length)
while i < c {
let li = UInt32(left[i])
let ri = UInt32(right[i])
accumulator = 0xffff + li - ri + UInt32(carry)
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
result[i] = UInt16(truncatingIfNeeded:accumulator)
i += 1
}
while i < left._length {
if carry != 0 {
let li = UInt32(left[i])
accumulator = 0xffff + li // + no carry
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
result[i] = UInt16(truncatingIfNeeded:accumulator)
i += 1
} else {
while i < left._length {
result[i] = left[i]
i += 1
}
break
}
}
while i < right._length {
let ri = UInt32(right[i])
accumulator = 0xffff - ri + UInt32(carry)
carry = UInt16(truncatingIfNeeded:accumulator >> 16)
result[i] = UInt16(truncatingIfNeeded:accumulator)
i += 1
}
if carry != 0 {
return .overflow
}
result._length = i;
result.trimTrailingZeros()
return .noError;
}
// Exact operations. result may be a pointer to same space as leftOperand or rightOperand
public func NSDecimalSubtract(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
var r = rightOperand.pointee
if r._length != 0 {
r.negate()
}
return NSDecimalAdd(result, leftOperand, &r, roundingMode)
}
// Exact operations. result may be a pointer to same space as leftOperand or rightOperand
public func NSDecimalMultiply(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN {
result.pointee.setNaN()
return .overflow
}
if leftOperand.pointee.isZero || rightOperand.pointee.isZero {
result.pointee.setZero()
return .noError
}
var big = WideDecimal()
var calculationError:NSDecimalNumber.CalculationError = .noError
calculationError = integerMultiply(&big,WideDecimal(leftOperand.pointee),rightOperand.pointee)
result.pointee._isNegative = (leftOperand.pointee._isNegative + rightOperand.pointee._isNegative) % 2
var newExponent = leftOperand.pointee._exponent + rightOperand.pointee._exponent
if big._length > Decimal.maxSize {
var exponent:Int32 = 0
calculationError = fitMantissa(&big, &exponent, roundingMode)
newExponent += exponent
}
for i in 0..<big._length {
result.pointee[i] = big[i]
}
result.pointee._length = big._length
result.pointee._isCompact = 0
if newExponent > Int32(Int8.max) {
result.pointee.setNaN()
return .overflow
}
result.pointee._exponent = newExponent
NSDecimalCompact(result)
return calculationError
}
// Exact operations. result may be a pointer to same space as leftOperand or rightOperand
public func NSDecimalDivide(_ result: UnsafeMutablePointer<Decimal>, _ leftOperand: UnsafePointer<Decimal>, _ rightOperand: UnsafePointer<Decimal>, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if leftOperand.pointee.isNaN || rightOperand.pointee.isNaN {
result.pointee.setNaN()
return .overflow
}
if rightOperand.pointee.isZero {
result.pointee.setNaN()
return .divideByZero
}
if leftOperand.pointee.isZero {
result.pointee.setZero()
return .noError
}
var a = Decimal()
var b = Decimal()
var big = WideDecimal()
var exponent:Int32 = 0
NSDecimalCopy(&a, leftOperand)
NSDecimalCopy(&b, rightOperand)
/* If the precision of the left operand is much smaller
* than that of the right operand (for example,
* 20 and 0.112314123094856724234234572), then the
* difference in their exponents is large and a lot of
* precision will be lost below. This is particularly
* true as the difference approaches 38 or larger.
* Normalizing here looses some precision on the
* individual operands, but often produces a more
* accurate result later. I chose 19 arbitrarily
* as half of the magic 38, so that normalization
* doesn't always occur. */
if (19 <= Int(a._exponent - b._exponent)) {
_ = NSDecimalNormalize(&a, &b, roundingMode);
/* We ignore the small loss of precision this may
* induce in the individual operands. */
/* Sometimes the normalization done previously is inappropriate and
* forces one of the operands to 0. If this happens, restore both. */
if a.isZero || b.isZero {
NSDecimalCopy(&a, leftOperand);
NSDecimalCopy(&b, rightOperand);
}
}
_ = integerMultiplyByPowerOf10(&big, WideDecimal(a), 38) // Trust me, it's 38 !
_ = integerDivide(&big, big, b)
_ = fitMantissa(&big, &exponent, .down)
let length = min(big._length,Decimal.maxSize)
for i in 0..<length {
result.pointee[i] = big[i]
}
result.pointee._length = length
result.pointee.isNegative = a._isNegative != b._isNegative
exponent = a._exponent - b._exponent - 38 + exponent
if exponent < Int32(Int8.min) {
result.pointee.setNaN()
return .underflow
}
if exponent > Int32(Int8.max) {
result.pointee.setNaN()
return .overflow;
}
result.pointee._exponent = Int32(exponent)
result.pointee._isCompact = 0
NSDecimalCompact(result)
return .noError
}
// Division could be silently inexact;
// Exact operations. result may be a pointer to same space as leftOperand or rightOperand
public func NSDecimalPower(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ power: Int, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
if number.pointee.isNaN {
result.pointee.setNaN()
return .overflow
}
NSDecimalCopy(result,number)
return result.pointee.power(UInt(power), roundingMode:roundingMode)
}
public func NSDecimalMultiplyByPowerOf10(_ result: UnsafeMutablePointer<Decimal>, _ number: UnsafePointer<Decimal>, _ power: Int16, _ roundingMode: NSDecimalNumber.RoundingMode) -> NSDecimalNumber.CalculationError {
NSDecimalCopy(result,number)
return result.pointee.multiply(byPowerOf10: power)
}
public func NSDecimalString(_ dcm: UnsafePointer<Decimal>, _ locale: Any?) -> String {
guard locale == nil else {
fatalError("Locale not supported: \(locale!)")
}
return dcm.pointee.description
}
private func multiplyBy10(_ dcm: inout Decimal, andAdd extra:Int) -> NSDecimalNumber.CalculationError {
let backup = dcm
if multiplyByShort(&dcm, 10) == .noError && addShort(&dcm, UInt16(extra)) == .noError {
return .noError
} else {
dcm = backup // restore the old values
return .overflow // this is the only possible error
}
}
fileprivate protocol VariableLengthNumber {
var _length: UInt32 { get set }
init()
subscript(index:UInt32) -> UInt16 { get set }
var isZero:Bool { get }
mutating func copyMantissa<T:VariableLengthNumber>(from other:T)
mutating func zeroMantissa()
mutating func trimTrailingZeros()
var maxMantissaLength: UInt32 { get }
}
extension Decimal: VariableLengthNumber {
var maxMantissaLength:UInt32 {
return Decimal.maxSize
}
fileprivate mutating func zeroMantissa() {
for i in 0..<Decimal.maxSize {
self[i] = 0
}
}
internal mutating func trimTrailingZeros() {
if _length > Decimal.maxSize {
_length = Decimal.maxSize
}
while _length != 0 && self[_length - 1] == 0 {
_length -= 1
}
}
fileprivate mutating func copyMantissa<T : VariableLengthNumber>(from other: T) {
if other._length > maxMantissaLength {
for i in maxMantissaLength..<other._length {
guard other[i] == 0 else {
fatalError("Loss of precision during copy other[\(i)] \(other[i]) != 0")
}
}
}
let length = min(other._length, maxMantissaLength)
for i in 0..<length {
self[i] = other[i]
}
self._length = length
self._isCompact = 0
}
}
// Provides a way with dealing with extra-length decimals, used for calculations
fileprivate struct WideDecimal : VariableLengthNumber {
var maxMantissaLength:UInt32 {
return _extraWide ? 17 : 16
}
fileprivate mutating func zeroMantissa() {
for i in 0..<maxMantissaLength {
self[i] = 0
}
}
fileprivate mutating func trimTrailingZeros() {
while _length != 0 && self[_length - 1] == 0 {
_length -= 1
}
}
init() {
self.init(false)
}
fileprivate mutating func copyMantissa<T : VariableLengthNumber>(from other: T) {
let length = other is Decimal ? min(other._length,Decimal.maxSize) : other._length
for i in 0..<length {
self[i] = other[i]
}
self._length = length
}
var isZero: Bool {
return _length == 0
}
var __length: UInt16
var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16,
UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)
// Most uses of this class use 16 shorts, but integer division uses 17 shorts
var _extraWide: Bool
var _length: UInt32 {
get {
return UInt32(__length)
}
set {
guard newValue <= maxMantissaLength else {
fatalError("Attempt to set a length greater than capacity \(newValue) > \(maxMantissaLength)")
}
__length = UInt16(newValue)
}
}
init(_ extraWide:Bool = false) {
__length = 0
_mantissa = (UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0))
_extraWide = extraWide
}
init(_ decimal:Decimal) {
self.__length = UInt16(decimal._length)
self._extraWide = false
self._mantissa = (decimal[0],decimal[1],decimal[2],decimal[3],decimal[4],decimal[5],decimal[6],decimal[7],UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0),UInt16(0))
}
subscript(index:UInt32) -> UInt16 {
get {
switch index {
case 0: return _mantissa.0
case 1: return _mantissa.1
case 2: return _mantissa.2
case 3: return _mantissa.3
case 4: return _mantissa.4
case 5: return _mantissa.5
case 6: return _mantissa.6
case 7: return _mantissa.7
case 8: return _mantissa.8
case 9: return _mantissa.9
case 10: return _mantissa.10
case 11: return _mantissa.11
case 12: return _mantissa.12
case 13: return _mantissa.13
case 14: return _mantissa.14
case 15: return _mantissa.15
case 16 where _extraWide: return _mantissa.16 // used in integerDivide
default: fatalError("Invalid index \(index) for _mantissa")
}
}
set {
switch index {
case 0: _mantissa.0 = newValue
case 1: _mantissa.1 = newValue
case 2: _mantissa.2 = newValue
case 3: _mantissa.3 = newValue
case 4: _mantissa.4 = newValue
case 5: _mantissa.5 = newValue
case 6: _mantissa.6 = newValue
case 7: _mantissa.7 = newValue
case 8: _mantissa.8 = newValue
case 9: _mantissa.9 = newValue
case 10: _mantissa.10 = newValue
case 11: _mantissa.11 = newValue
case 12: _mantissa.12 = newValue
case 13: _mantissa.13 = newValue
case 14: _mantissa.14 = newValue
case 15: _mantissa.15 = newValue
case 16 where _extraWide: _mantissa.16 = newValue
default: fatalError("Invalid index \(index) for _mantissa")
}
}
}
func toDecimal() -> Decimal {
var result = Decimal()
result._length = self._length
for i in 0..<_length {
result[i] = self[i]
}
return result
}
}
// == Internal (Swifty) functions ==
extension Decimal {
fileprivate var isCompact: Bool {
get {
return _isCompact != 0
}
set {
_isCompact = newValue ? 1 : 0
}
}
fileprivate var isNegative: Bool {
get {
return _isNegative != 0
}
set {
_isNegative = newValue ? 1 : 0
}
}
fileprivate mutating func compact() {
if isCompact || isNaN || _length == 0 {
return
}
var newExponent = self._exponent
var remainder: UInt16 = 0
// Divide by 10 as much as possible
repeat {
(remainder,_) = divideByShort(&self,10)
newExponent += 1
} while remainder == 0
// Put the non-empty remainder in place
_ = multiplyByShort(&self,10)
_ = addShort(&self,remainder)
newExponent -= 1
// Set the new exponent
while newExponent > Int32(Int8.max) {
_ = multiplyByShort(&self,10)
newExponent -= 1
}
_exponent = newExponent
isCompact = true
}
fileprivate mutating func round(scale:Int, roundingMode:RoundingMode) {
// scale is the number of digits after the decimal point
var s = Int32(scale) + _exponent
if s == NSDecimalNoScale || s >= 0 {
return
}
s = -s
var remainder: UInt16 = 0
var previousRemainder = false
let negative = _isNegative != 0
var newExponent = _exponent + s
while s > 4 {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&self, 10000)
s -= 4
}
while s > 0 {
if remainder != 0 {
previousRemainder = true
}
(remainder,_) = divideByShort(&self, 10)
s -= 1
}
// If we are on a tie, adjust with premdr. .50001 is equivalent to .6
if previousRemainder && (remainder == 0 || remainder == 5) {
remainder += 1;
}
if remainder != 0 {
if negative {
switch roundingMode {
case .up:
break
case .bankers:
if remainder == 5 && (self[0] & 1) == 0 {
remainder += 1
}
fallthrough
case .plain:
if remainder < 5 {
break
}
fallthrough
case .down:
_ = addShort(&self, 1)
}
if _length == 0 {
_isNegative = 0;
}
} else {
switch roundingMode {
case .down:
break
case .bankers:
if remainder == 5 && (self[0] & 1) == 0 {
remainder -= 1
}
fallthrough
case .plain:
if remainder < 5 {
break
}
fallthrough
case .up:
_ = addShort(&self, 1)
}
}
}
_isCompact = 0;
while newExponent > Int32(Int8.max) {
newExponent -= 1;
_ = multiplyByShort(&self, 10);
}
_exponent = newExponent;
self.compact();
}
internal func compare(to other:Decimal) -> ComparisonResult {
// NaN is a special case and is arbitrary ordered before everything else
// Conceptually comparing with NaN is bogus anyway but raising or
// always returning the same answer will confuse the sorting algorithms
if self.isNaN {
return other.isNaN ? .orderedSame : .orderedAscending
}
if other.isNaN {
return .orderedDescending
}
// Check the sign
if self._isNegative > other._isNegative {
return .orderedAscending
}
if self._isNegative < other._isNegative {
return .orderedDescending
}
// If one of the two is == 0, the other is bigger
// because 0 implies isNegative = 0...
if self.isZero && other.isZero {
return .orderedSame
}
if self.isZero {
return .orderedAscending
}
if other.isZero {
return .orderedDescending
}
var selfNormal = self
var otherNormal = other
_ = NSDecimalNormalize(&selfNormal, &otherNormal, .down)
let comparison = mantissaCompare(selfNormal,otherNormal)
if selfNormal._isNegative == 1 {
if comparison == .orderedDescending {
return .orderedAscending
} else if comparison == .orderedAscending {
return .orderedDescending
} else {
return .orderedSame
}
}
return comparison
}
fileprivate subscript(index:UInt32) -> UInt16 {
get {
switch index {
case 0: return _mantissa.0
case 1: return _mantissa.1
case 2: return _mantissa.2
case 3: return _mantissa.3
case 4: return _mantissa.4
case 5: return _mantissa.5
case 6: return _mantissa.6
case 7: return _mantissa.7
default: fatalError("Invalid index \(index) for _mantissa")
}
}
set {
switch index {
case 0: _mantissa.0 = newValue
case 1: _mantissa.1 = newValue
case 2: _mantissa.2 = newValue
case 3: _mantissa.3 = newValue
case 4: _mantissa.4 = newValue
case 5: _mantissa.5 = newValue
case 6: _mantissa.6 = newValue
case 7: _mantissa.7 = newValue
default: fatalError("Invalid index \(index) for _mantissa")
}
}
}
fileprivate mutating func setNaN() {
_length = 0
_isNegative = 1
}
fileprivate mutating func setZero() {
_length = 0
_isNegative = 0
}
fileprivate mutating func multiply(byPowerOf10 power:Int16) -> CalculationError {
if isNaN {
return .overflow
}
if isZero {
return .noError
}
let newExponent = _exponent + Int32(power)
if newExponent < Int32(Int8.min) {
setNaN()
return .underflow
}
if newExponent > Int32(Int8.max) {
setNaN()
return .overflow
}
_exponent = newExponent
return .noError
}
fileprivate mutating func power(_ p:UInt, roundingMode:RoundingMode) -> CalculationError {
if isNaN {
return .overflow
}
var power = p
if power == 0 {
_exponent = 0
_length = 1
_isNegative = 0
self[0] = 1
_isCompact = 1
return .noError
} else if power == 1 {
return .noError
}
var temporary = Decimal(1)
var error:CalculationError = .noError
while power > 1 {
if power % 2 == 1 {
let previousError = error
var leftOp = temporary
error = NSDecimalMultiply(&temporary, &leftOp, &self, roundingMode)
if previousError != .noError { // FIXME is this the intent?
error = previousError
}
if error == .overflow || error == .underflow {
setNaN()
return error
}
power -= 1
}
if power != 0 {
let previousError = error
var leftOp = self
var rightOp = self
error = NSDecimalMultiply(&self, &leftOp, &rightOp, roundingMode)
if previousError != .noError { // FIXME is this the intent?
error = previousError
}
if error == .overflow || error == .underflow {
setNaN()
return error
}
power /= 2
}
}
let previousError = error
var rightOp = self
error = NSDecimalMultiply(&self, &temporary, &rightOp, roundingMode)
if previousError != .noError { // FIXME is this the intent?
error = previousError
}
if error == .overflow || error == .underflow {
setNaN()
return error
}
return error
}
}
fileprivate let pow10 = [
/*^00*/ Decimal(length: 1, mantissa:( 0x0001,0,0,0,0,0,0,0)),
/*^01*/ Decimal(length: 1, mantissa:( 0x000a,0,0,0,0,0,0,0)),
/*^02*/ Decimal(length: 1, mantissa:( 0x0064,0,0,0,0,0,0,0)),
/*^03*/ Decimal(length: 1, mantissa:( 0x03e8,0,0,0,0,0,0,0)),
/*^04*/ Decimal(length: 1, mantissa:( 0x2710,0,0,0,0,0,0,0)),
/*^05*/ Decimal(length: 2, mantissa:( 0x86a0, 0x0001,0,0,0,0,0,0)),
/*^06*/ Decimal(length: 2, mantissa:( 0x4240, 0x000f,0,0,0,0,0,0)),
/*^07*/ Decimal(length: 2, mantissa:( 0x9680, 0x0098,0,0,0,0,0,0)),
/*^08*/ Decimal(length: 2, mantissa:( 0xe100, 0x05f5,0,0,0,0,0,0)),
/*^09*/ Decimal(length: 2, mantissa:( 0xca00, 0x3b9a,0,0,0,0,0,0)),
/*^10*/ Decimal(length: 3, mantissa:( 0xe400, 0x540b, 0x0002,0,0,0,0,0)),
/*^11*/ Decimal(length: 3, mantissa:( 0xe800, 0x4876, 0x0017,0,0,0,0,0)),
/*^12*/ Decimal(length: 3, mantissa:( 0x1000, 0xd4a5, 0x00e8,0,0,0,0,0)),
/*^13*/ Decimal(length: 3, mantissa:( 0xa000, 0x4e72, 0x0918,0,0,0,0,0)),
/*^14*/ Decimal(length: 3, mantissa:( 0x4000, 0x107a, 0x5af3,0,0,0,0,0)),
/*^15*/ Decimal(length: 4, mantissa:( 0x8000, 0xa4c6, 0x8d7e, 0x0003,0,0,0,0)),
/*^16*/ Decimal(length: 4, mantissa:( 0x0000, 0x6fc1, 0x86f2, 0x0023,0,0,0,0)),
/*^17*/ Decimal(length: 4, mantissa:( 0x0000, 0x5d8a, 0x4578, 0x0163,0,0,0,0)),
/*^18*/ Decimal(length: 4, mantissa:( 0x0000, 0xa764, 0xb6b3, 0x0de0,0,0,0,0)),
/*^19*/ Decimal(length: 4, mantissa:( 0x0000, 0x89e8, 0x2304, 0x8ac7,0,0,0,0)),
/*^20*/ Decimal(length: 5, mantissa:( 0x0000, 0x6310, 0x5e2d, 0x6bc7, 0x0005,0,0,0)),
/*^21*/ Decimal(length: 5, mantissa:( 0x0000, 0xdea0, 0xadc5, 0x35c9, 0x0036,0,0,0)),
/*^22*/ Decimal(length: 5, mantissa:( 0x0000, 0xb240, 0xc9ba, 0x19e0, 0x021e,0,0,0)),
/*^23*/ Decimal(length: 5, mantissa:( 0x0000, 0xf680, 0xe14a, 0x02c7, 0x152d,0,0,0)),
/*^24*/ Decimal(length: 5, mantissa:( 0x0000, 0xa100, 0xcced, 0x1bce, 0xd3c2,0,0,0)),
/*^25*/ Decimal(length: 6, mantissa:( 0x0000, 0x4a00, 0x0148, 0x1614, 0x4595, 0x0008,0,0)),
/*^26*/ Decimal(length: 6, mantissa:( 0x0000, 0xe400, 0x0cd2, 0xdcc8, 0xb7d2, 0x0052,0,0)),
/*^27*/ Decimal(length: 6, mantissa:( 0x0000, 0xe800, 0x803c, 0x9fd0, 0x2e3c, 0x033b,0,0)),
/*^28*/ Decimal(length: 6, mantissa:( 0x0000, 0x1000, 0x0261, 0x3e25, 0xce5e, 0x204f,0,0)),
/*^29*/ Decimal(length: 7, mantissa:( 0x0000, 0xa000, 0x17ca, 0x6d72, 0x0fae, 0x431e, 0x0001,0)),
/*^30*/ Decimal(length: 7, mantissa:( 0x0000, 0x4000, 0xedea, 0x4674, 0x9cd0, 0x9f2c, 0x000c,0)),
/*^31*/ Decimal(length: 7, mantissa:( 0x0000, 0x8000, 0x4b26, 0xc091, 0x2022, 0x37be, 0x007e,0)),
/*^32*/ Decimal(length: 7, mantissa:( 0x0000, 0x0000, 0xef81, 0x85ac, 0x415b, 0x2d6d, 0x04ee,0)),
/*^33*/ Decimal(length: 7, mantissa:( 0x0000, 0x0000, 0x5b0a, 0x38c1, 0x8d93, 0xc644, 0x314d,0)),
/*^34*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x8e64, 0x378d, 0x87c0, 0xbead, 0xed09, 0x0001)),
/*^35*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x8fe8, 0x2b87, 0x4d82, 0x72c7, 0x4261, 0x0013)),
/*^36*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x9f10, 0xb34b, 0x0715, 0x7bc9, 0x97ce, 0x00c0)),
/*^37*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x36a0, 0x00f4, 0x46d9, 0xd5da, 0xee10, 0x0785)),
/*^38*/ Decimal(length: 8, mantissa:( 0x0000, 0x0000, 0x2240, 0x098a, 0xc47a, 0x5a86, 0x4ca8, 0x4b3b))
/*^39 is on 9 shorts. */
]
// Copied from Scanner.swift
private func decimalSep(_ locale: Locale?) -> String {
if let loc = locale {
if let sep = loc._bridgeToObjectiveC().object(forKey: .decimalSeparator) as? NSString {
return sep._swiftObject
}
return "."
} else {
return decimalSep(Locale.current)
}
}
// Copied from Scanner.swift
private func isADigit(_ ch: unichar) -> Bool {
struct Local {
static let set = CharacterSet.decimalDigits
}
return Local.set.contains(UnicodeScalar(ch)!)
}
// Copied from Scanner.swift
private func numericValue(_ ch: unichar) -> Int {
if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) {
return Int(ch) - Int(unichar(unicodeScalarLiteral: "0"))
} else {
return __CFCharDigitValue(UniChar(ch))
}
}
// Could be silently inexact for float and double.
extension Scanner {
public func scanDecimal(_ dcm: inout Decimal) -> Bool {
if let result = scanDecimal() {
dcm = result
return true
} else {
return false
}
}
public func scanDecimal() -> Decimal? {
var result = Decimal()
let string = self._scanString
let length = string.length
var buf = _NSStringBuffer(string: string, start: self._scanLocation, end: length)
let ds_chars = decimalSep(locale).utf16
let ds = ds_chars[ds_chars.startIndex]
buf.skip(_skipSet)
var neg = false
if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") {
neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-")
buf.advance()
buf.skip(_skipSet)
}
guard isADigit(buf.currentCharacter) else {
return nil
}
var tooBig = false
// build the mantissa
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
if tooBig || multiplyBy10(&result,andAdd:numeral) != .noError {
tooBig = true
if result._exponent == Int32(Int8.max) {
repeat {
buf.advance()
} while isADigit(buf.currentCharacter)
return Decimal.nan
}
result._exponent += 1
}
buf.advance()
} while isADigit(buf.currentCharacter)
// get the decimal point
if buf.currentCharacter == ds {
buf.advance()
// continue to build the mantissa
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
if tooBig || multiplyBy10(&result,andAdd:numeral) != .noError {
tooBig = true
} else {
if result._exponent == Int32(Int8.min) {
repeat {
buf.advance()
} while isADigit(buf.currentCharacter)
return Decimal.nan
}
result._exponent -= 1
}
buf.advance()
} while isADigit(buf.currentCharacter)
}
if buf.currentCharacter == unichar(unicodeScalarLiteral: "e") || buf.currentCharacter == unichar(unicodeScalarLiteral: "E") {
var exponentIsNegative = false
var exponent: Int32 = 0
buf.advance()
if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") {
exponentIsNegative = true
buf.advance()
} else if buf.currentCharacter == unichar(unicodeScalarLiteral: "+") {
buf.advance()
}
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
exponent = 10 * exponent + Int32(numeral)
guard exponent <= 2*Int32(Int8.max) else {
return Decimal.nan
}
buf.advance()
} while isADigit(buf.currentCharacter)
if exponentIsNegative {
exponent = -exponent
}
exponent += result._exponent
guard exponent >= Int32(Int8.min) && exponent <= Int32(Int8.max) else {
return Decimal.nan
}
result._exponent = exponent
}
result.isNegative = neg
// if we get to this point, and have NaN, then the input string was probably "-0"
// or some variation on that, and normalize that to zero.
if result.isNaN {
result = Decimal(0)
}
result.compact()
self._scanLocation = buf.location
return result
}
}
extension Decimal : Codable {
private enum CodingKeys : Int, CodingKey {
case exponent
case length
case isNegative
case isCompact
case mantissa
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let exponent = try container.decode(CInt.self, forKey: .exponent)
let length = try container.decode(CUnsignedInt.self, forKey: .length)
let isNegative = try container.decode(Bool.self, forKey: .isNegative)
let isCompact = try container.decode(Bool.self, forKey: .isCompact)
var mantissaContainer = try container.nestedUnkeyedContainer(forKey: .mantissa)
var mantissa: (CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort,
CUnsignedShort, CUnsignedShort, CUnsignedShort, CUnsignedShort) = (0,0,0,0,0,0,0,0)
mantissa.0 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.1 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.2 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.3 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.4 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.5 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.6 = try mantissaContainer.decode(CUnsignedShort.self)
mantissa.7 = try mantissaContainer.decode(CUnsignedShort.self)
self.init(_exponent: exponent,
_length: length,
_isNegative: CUnsignedInt(isNegative ? 1 : 0),
_isCompact: CUnsignedInt(isCompact ? 1 : 0),
_reserved: 0,
_mantissa: mantissa)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(_exponent, forKey: .exponent)
try container.encode(_length, forKey: .length)
try container.encode(_isNegative == 0 ? false : true, forKey: .isNegative)
try container.encode(_isCompact == 0 ? false : true, forKey: .isCompact)
var mantissaContainer = container.nestedUnkeyedContainer(forKey: .mantissa)
try mantissaContainer.encode(_mantissa.0)
try mantissaContainer.encode(_mantissa.1)
try mantissaContainer.encode(_mantissa.2)
try mantissaContainer.encode(_mantissa.3)
try mantissaContainer.encode(_mantissa.4)
try mantissaContainer.encode(_mantissa.5)
try mantissaContainer.encode(_mantissa.6)
try mantissaContainer.encode(_mantissa.7)
}
}
| apache-2.0 | 42449945433f93ba8f6f7285ab8fcd09 | 32.191231 | 233 | 0.562027 | 4.12366 | false | false | false | false |
exponent/exponent | packages/expo-dev-launcher/ios/EXDevLauncherURLHelper.swift | 2 | 903 | // Copyright 2015-present 650 Industries. All rights reserved.
import Foundation
@objc
public class EXDevLauncherURLHelper: NSObject {
@objc
public static func isDevLauncherURL(_ url: URL?) -> Bool {
return url?.host == "expo-development-client"
}
@objc
public static func replaceEXPScheme(_ url: URL, to scheme: String) -> URL {
var components = URLComponents.init(url: url, resolvingAgainstBaseURL: false)!
if (components.scheme == "exp") {
components.scheme = scheme
}
return components.url!
}
@objc
public static func getAppURLFromDevLauncherURL(_ url: URL) -> URL? {
let components = URLComponents.init(url: url, resolvingAgainstBaseURL: false)
for parameter in components?.queryItems ?? [] {
if parameter.name == "url" {
return URL.init(string: parameter.value?.removingPercentEncoding ?? "")
}
}
return nil
}
}
| bsd-3-clause | 59c2b340c6b91e74f4c92c8816061ed5 | 27.21875 | 82 | 0.678848 | 4.180556 | false | false | false | false |
JJMoon/MySwiftCheatSheet | UI_Extension/HtAudioPlayer.swift | 1 | 4708 | //
// HtAudioPlayer.swift
// Trainer
//
// Created by Jongwoo Moon on 2016. 1. 27..
// Copyright © 2016년 IMLab. All rights reserved.
//
import Foundation
import AVFoundation
class HtAudioPlayer: NSObject {
var log = HtLog(cName: "HtAudioPlayer")
var counter = 0, pausing = false, repeatLmt = 1 // 기본은 한번만..
var aURL : NSURL?
var cntTimer: NSTimer?, interval = 60.0 / 100.0
private var player: AVAudioPlayer?
private var players = [AVAudioPlayer](), arrNum = 7, sequenceIdx = 0
private var isMuteOn = false
var playing: Bool { get { return (player?.playing)! } }
//var isPlaying: Bool { get { return (player?.isPlaying)! } }
convenience init(repeatLimit: Int, url: NSURL, initMuteOn: Bool) {
self.init()
aURL = url
isMuteOn = initMuteOn
repeatLmt = repeatLimit
do {
try player = AVAudioPlayer(contentsOfURL: url)
} catch {
print(" AV Player Creation Error !!!!! \(url) ")
}
applyMute()
}
deinit {
cntTimer?.invalidate()
}
////////////////////////////////////////////////////////////////////// [ UI Sub ]
// Interval Variation
func initTimer(intervalOfTimer: Double) {
//log.printThisFunc("initTimer(intervalOfTimer: Double)", lnum: 1)
if 1 < intervalOfTimer {
interval = intervalOfTimer
} else {
interval = 5
}
playerArraySet()
resetTimer()
player?.stop()
cntTimer = NSTimer.scheduledTimerWithTimeInterval(60.0 / interval, // second
target:self, selector: #selector(HtAudioPlayer.update), userInfo: nil, repeats: true)
applyMute()
}
private func playerArraySet() {
//print(" playerArraySet()")
// for pler in players { pler.stop() }
players = [AVAudioPlayer]()
for _ in 0..<arrNum {
do {
try players.append(AVAudioPlayer(contentsOfURL: aURL!))
} catch {
print(" AV Player Creation Error !!!!! \(aURL) ")
}
}
applyMute()
}
func update() {
//log.printAlways("audio update .>>>> \(aURL) sequenceIdx : \(sequenceIdx) ***** >>>>>> ", lnum: 1)
if pausing { return }
if (sequenceIdx == arrNum) { sequenceIdx = 0 }
players[sequenceIdx].play()
sequenceIdx += 1
}
func pauseTimer() {
print("\n audio Timer .>>>> \(aURL) ***** >>>>>> pauseTimer \n")
if pausing { return } // 현재 정지 중...
pausing = true
applyMute()
}
func unpuaseTimer() {
print("\n audio Timer .>>>> \(aURL) ***** >>>>>> unpauseTimer \n")
pausing = false
applyMute()
}
private func resetTimer() {
print("\n audio Timer .>>>> \(aURL) ***** >>>>>> resetTimer() \n")
if cntTimer != nil {
cntTimer?.invalidate()
cntTimer = nil
}
applyMute()
}
/// 멈춤. 타이머도 동시에..
func stop() {
print(" HtAudioPlayer :: stop \(cntTimer)")
//print("\n audio Timer .>>>> \(aURL) ***** >>>>>> stop \n")
player?.stop()
cntTimer?.invalidate()
resetTimer()
}
/// 뮤트 관련...
func muteOnOff(isOn: Bool) {
isMuteOn = isOn
applyMute()
}
/// 오디오 컨트롤 할 때마다 볼륨 조절..
private func applyMute() {
if (isMuteOn) {
setVolume(0)
} else {
setVolume(1.0)
}
}
private func setVolume(vol : Float) {
player?.volume = vol
for av in players {
av.volume = vol
}
}
/// Not use Timer...
func reset() {
resetCount()
player?.stop()
player = nil
pausing = false
}
func resetCount() {
counter = 0
}
func pause() {
if pausing { return } // 현재 정지 중...
if player?.playing == true { // 재생을 다 한 상태면 pause 가 아니라 play를 해야 함..
player?.pause()
pausing = true
}
}
func unpause() {
if pausing {
if 0 == players.count {
player?.play() // 재 시작..
}
pausing = false
}
//print(" un puase ")
}
func play() -> Bool {
pausing = false
var rval = false
if counter <= repeatLmt || repeatLmt == -1 { rval = player!.play() }
counter += 1
return rval // 플레이가 안되면 false 리턴.
}
} | apache-2.0 | 5d156075fc66db42782434b96615f344 | 24.785311 | 112 | 0.489371 | 3.933621 | false | false | false | false |
GetZero/Give-Me-One | MyOne/问题/ViewController/QuestionViewController.swift | 1 | 3463 | //
// ArticleViewController.swift
// MyOne
//
// Created by 韦曲凌 on 16/8/24.
// Copyright © 2016年 Wake GetZero. All rights reserved.
//
import UIKit
class QuestionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
// MARK: Life circle and property
var questionModels: QuestionModel = QuestionModel()
var day: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
initWithUserInterface()
addObservers()
startNetwork()
}
deinit {
questionModels.removeObserver(self, forKeyPath: questionModels.resultKeyPath())
}
func initWithUserInterface() {
view.addSubview(questionCollectionView)
view.addSubview(juhuaActivity)
view.addSubview(networkWarningLabel)
}
// MARK: Observer and network
func addObservers() {
questionModels.addObserver(self, forKeyPath: questionModels.resultKeyPath(), options: .New, context: nil)
}
func startNetwork() {
juhuaActivity.startAnimating()
questionModels.startNetwork(day)
day -= 1
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if object!.isKindOfClass(QuestionModel) && keyPath! == questionModels.resultKeyPath() {
dispatch_async(dispatch_get_main_queue(), {
if change!["new"]! as! String == "Success" {
self.questionCollectionView.reloadData()
self.networkWarningLabel.hidden = true
} else {
let _: UIAlertController = UIAlertController.networkErrorAlert(self)
self.networkWarningLabel.hidden = false
self.juhuaActivity.stopAnimating()
}
})
}
}
// MARK: Delegate and datasource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
questionModels.questionDatas.count == 0 ? juhuaActivity.startAnimating() : juhuaActivity.stopAnimating()
return questionModels.questionDatas.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: QuestionCell = collectionView.dequeueReusableCellWithReuseIdentifier("QuestionCell", forIndexPath: indexPath) as! QuestionCell
cell.setModel(questionModels.questionDatas[indexPath.item])
return cell
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if indexPath.item == questionModels.questionDatas.count - 1 {
startNetwork()
}
}
// MARK: Lazy load
private lazy var questionCollectionView: UICollectionView = {
let view: UICollectionView = UICollectionView.standardCollectionView("QuestionCell")
view.delegate = self
view.dataSource = self
return view
}()
private lazy var juhuaActivity: UIActivityIndicatorView = UIActivityIndicatorView.juhuaActivityView(self.view)
private lazy var networkWarningLabel: UILabel = UILabel.networkErrorWarning(self.view)
}
| apache-2.0 | 40299ce9cea600ef3924ec32b8e7e5e8 | 35.357895 | 157 | 0.665605 | 5.491256 | false | false | false | false |
jkolb/Swiftish | Sources/Swiftish/Plane.swift | 1 | 1861 | /*
The MIT License (MIT)
Copyright (c) 2015-2017 Justin Kolb
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.
*/
public struct Plane<T: Vectorable> : Hashable, CustomStringConvertible {
public let normal: Vector3<T>
public let distance: T
public init(normal: Vector3<T>, distance: T) {
self.normal = normal
self.distance = distance
}
public var description: String {
return "{\(normal), \(distance)}"
}
public func transform(_ t: Transform3<T>) -> Plane<T> {
let pointOnPlane = normal * distance
let transformedNormal = normal * t.rotation
let transformedPoint = pointOnPlane.transform(t)
let transformedDistance = Vector3<T>.dot(transformedNormal, transformedPoint)
return Plane(normal: transformedNormal, distance: transformedDistance)
}
}
| mit | 9d5e552636fc19d2161bf936eb39b6ea | 39.456522 | 85 | 0.727566 | 4.747449 | false | false | false | false |
esttorhe/SlackTeamExplorer | SlackTeamExplorer/SlackTeamCoreDataProxy/ViewModels/MembersViewModel.swift | 1 | 8417 | //
// MembersViewModel.swift
// SlackTeamCoreDataProxy
//
// Created by Esteban Torres on 29/6/15.
// Copyright (c) 2015 Esteban Torres. All rights reserved.
//
// Native Frameworks
import CoreData
// Pods
import ReactiveViewModel
import ReactiveCocoa
import ReachabilitySwift
public class MembersViewModel: RVMViewModel {
private var members = [Member]()
private let coreDataProxy = SlackTeamCoreDataProxy()
public let beginLoadingSignal: RACSignal = RACSubject()
public let endLoadingSignal: RACSignal = RACSubject()
public let updateContentSignal: RACSignal = RACSubject()
public let reachability = Reachability.reachabilityForInternetConnection()
public var loadFromDBOnly: Bool = false
public var numberOfSections: Int {
get { return 1 }
}
public func numberOfItemsInSection(section: Int) -> Int {
return self.members.count
}
public func memberAtIndexPath(indexPath: NSIndexPath) -> Member {
let member = self.members[indexPath.item]
return self.members[indexPath.item]
}
public init(useGroupContext:Bool = true) {
coreDataProxy.useMemoryStorage = !useGroupContext
super.init()
reachability.startNotifier()
self.didBecomeActiveSignal.subscribeNext { [unowned self] active in
self.active = false
// Notify caller that network request is about to begin
if let beginSignal = self.beginLoadingSignal as? RACSubject { beginSignal.sendNext(nil) }
// Check if we have connectivity or not and retrieve the data depending
// on this.
if self.reachability.isReachable() && !self.loadFromDBOnly {
self.loadDataFromWeb()
} else {
self.loadDataFromDB()
}
}
}
// MARK: - Internal Helpers
/**
Executes a REST request to Slack's API retrieving all the members of the team associated to the
provided auth token.
Once successfully retrieved the data checks for existing members in the DB and only inserts the
new ones.
Assigns a union of both lists as `self.members` for later usage.
*/
internal func loadDataFromWeb() {
SlackProvider.request(.TeamUsersList) { (data, status, response, error) -> () in
// Notify caller that network request ended
if let endSignal = self.endLoadingSignal as? RACSubject { endSignal.sendNext(nil) }
// Check if there was a network error, and if so notify back and cancel processing
// data.
if let err = error where err.code != 0 {
if let updateSignal = self.updateContentSignal as? RACSubject {
updateSignal.sendError(err)
}
return
}
// Parse data
if let data = data {
var localError: NSError?
if let json: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &localError) {
if let members = json["members"] as? Array<Dictionary<NSObject, AnyObject>> {
// Map the array of dictionaries into Member models removing possible `nil`s.
self.findOrCreate(members: members)
// Report back the new data.
if let updateSignal = self.updateContentSignal as? RACSubject {
updateSignal.sendNext(self.members)
}
}
} else {
if let updateSignal = self.updateContentSignal as? RACSubject {
updateSignal.sendError(localError)
}
}
}
}
}
/**
Retrieves the list of members from the team associated to the auth token previously retrieved
from the Web.
If no local data is found (meaning we never ran the app connected to the internet before) we
would have an empty set of data.
*/
internal func loadDataFromDB() {
if let context = coreDataProxy.managedObjectContext {
let fetch = NSFetchRequest(entityName: "Member")
fetch.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
var innerError: NSError?
if let currentMembers = context.executeFetchRequest(fetch, error: &innerError) as? Array<Member> {
// Notify caller that network request ended
if let endSignal = self.endLoadingSignal as? RACSubject { endSignal.sendNext(nil) }
// Check if there was a network error, and if so notify back and cancel processing
// data.
if let err = innerError where err.code != 0 {
if let updateSignal = self.updateContentSignal as? RACSubject {
updateSignal.sendError(err)
}
return
}
self.members = currentMembers
// Report back the new data.
if let updateSignal = self.updateContentSignal as? RACSubject {
updateSignal.sendNext(self.members)
}
} else {
if let updateSignal = self.updateContentSignal as? RACSubject {
let err = NSError(domain: "es.estebantorr.SlackTeamExplorer.MembersViewModel",
code: -667,
userInfo: [NSLocalizedDescriptionKey: "Unable to retrieve `Member` models from the database"])
updateSignal.sendError(err)
}
}
}
}
/**
Following Apple's suggestions ( https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html )
we try to match existing members in one single fetch and then only insert missing records from the DB.
For the sake's of this demo we are not updating matching data and only fetching to insert missing records.
*/
internal func findOrCreate(#members: Array<Dictionary<NSObject, AnyObject>>) {
if let context = coreDataProxy.managedObjectContext {
var membersArray = Array<Member>()
// Extract & sort the ids of the JSON members
let sortedMembers = members.map{ $0["id"] as! String }.sorted{ $0 < $1 }
// Fetch all the existing members that match the ids provided
var error: NSError?
let fetchRequest = NSFetchRequest(entityName: "Member")
fetchRequest.predicate = NSPredicate(format: "(membersIdentifier IN %@)", sortedMembers)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "membersIdentifier", ascending: true)]
if let matchingMembers = context.executeFetchRequest(fetchRequest, error: &error) as? Array<Member> {
membersArray += matchingMembers
let fetchedIds = matchingMembers.map { $0.membersIdentifier }.sorted{ $0 < $1 }.map{ $0! }
// We have all the matching IDs, now filter the data that should be inserted
let predicate = NSPredicate(format: "NOT (SELF[\"id\"] IN %@)", fetchedIds)
if let memberIDsToInsert = (members as NSArray).filteredArrayUsingPredicate(predicate) as? Array<Dictionary<String, AnyObject>> {
// Map the data not present in the DB into `Member` objects
let membersToInsert = memberIDsToInsert.map { Member.memberInContext(context, json: $0) }.filter{ $0 != nil }.map{ $0! }
membersArray += membersToInsert
}
} else {
let newMembers = members.map { Member.memberInContext(context, json: $0) }.filter{ $0 != nil }.map{ $0! }
membersArray += newMembers
}
self.members = membersArray.sorted{ $0.name < $1.name }
dispatch_async(dispatch_get_main_queue()) {
self.coreDataProxy.saveContext()
}
}
}
}
| mit | bef4b755a98f87d746c068306eac263e | 42.611399 | 145 | 0.58168 | 5.317119 | false | false | false | false |
cavalcantedosanjos/ND-OnTheMap | OnTheMap/OnTheMap/ViewControllers/SearchLocationViewController.swift | 1 | 4899 | //
// SearchLocationViewController.swift
// OnTheMap
//
// Created by Joao Anjos on 14/02/17.
// Copyright © 2017 Joao Anjos. All rights reserved.
//
import UIKit
import CoreLocation
protocol SearchLocationViewControllerDelegate {
func didFinishedPostLocation()
}
class SearchLocationViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var findButton: CustomButton!
let kShowLocationSegue = "showLocationSegue"
var delegate: SearchLocationViewControllerDelegate?
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
findButton.isEnabled = false
enableActivityIndicator(enable: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == kShowLocationSegue){
let vc = segue.destination as! ShowLocationViewController
vc.placemark = sender as? CLPlacemark
vc.delegate = self
}
}
// MARK: - Actions
@IBAction func cancelButton_Clicked(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func findButton_Clicked(_ sender: Any) {
guard let location = locationTextField.text, !location.isEmpty else {
showMessage(message: "Required location.", title: "Invalid Field!")
return
}
enableActivityIndicator(enable: true)
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(locationTextField.text!) { (places, error) in
self.enableActivityIndicator(enable: false)
guard (error == nil) else {
self.showMessage(message: "Location Not Found.", title: "Error")
return
}
if let place = places?.first {
self.performSegue(withIdentifier: self.kShowLocationSegue, sender: place)
}
}
}
// MARK: - Helpers
func enableActivityIndicator(enable: Bool){
if enable {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
activityIndicator.isHidden = !enable
}
func showMessage(message: String, title: String) {
let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
// MARK: - Keyboard
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(_ notification:Notification) {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
let heightKeyboard = keyboardSize.cgRectValue.height - 60
self.view.frame.origin.y = heightKeyboard * (-1)
}
func keyboardWillHide(notification: Notification) {
self.view.frame.origin.y = 0
}
}
// MARK: - UITextFieldDelegate
extension SearchLocationViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.text == "Enter Your Location Here" {
textField.text = ""
findButton.isEnabled = true
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension SearchLocationViewController: ShowLocationViewControllerDelegate {
func didFinishedPostLocation() {
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
self.delegate?.didFinishedPostLocation()
}
}
}
| mit | 47b67bb24d0baccc0bbaba7c3fdefe7f | 31.872483 | 146 | 0.644753 | 5.347162 | false | false | false | false |
ryanbooker/Swiftz | Tests/SwiftzTests/ReaderSpec.swift | 1 | 2810 | //
// ReaderSpec.swift
// Swiftz
//
// Created by Matthew Purland on 11/25/15.
// Copyright © 2015-2016 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
import SwiftCheck
class ReaderSpec : XCTestCase {
func testReader() {
func addOne() -> Reader<Int, Int> {
return asks { $0 + 1 }
}
func hello() -> Reader<String, String> {
return asks { "Hello \($0)" }
}
func bye() -> Reader<String, String> {
return asks { "Goodbye \($0)!" }
}
func helloAndGoodbye() -> Reader<String, String> {
return asks { hello().runReader($0) + " and " + bye().runReader($0) }
}
XCTAssert(addOne().runReader(1) == 2)
let input = "Matthew"
let helloReader = hello()
let modifiedHelloReader = helloReader.local({ "\($0) - Local"})
XCTAssert(helloReader.runReader(input) == "Hello \(input)")
XCTAssert(modifiedHelloReader.runReader(input) == "Hello \(input) - Local")
let byeReader = bye()
let modifiedByeReader = byeReader.local({ $0 + " - Local" })
XCTAssert(byeReader.runReader(input) == "Goodbye \(input)!")
XCTAssert(modifiedByeReader.runReader(input) == "Goodbye \(input) - Local!")
let result = hello() >>- { $0.runReader(input) }
XCTAssert(result == "Hello \(input)")
let result2 = bye().runReader(input)
XCTAssert(result2 == "Goodbye \(input)!")
let helloAndGoodbyeReader = helloAndGoodbye()
XCTAssert(helloAndGoodbyeReader.runReader(input) == "Hello \(input) and Goodbye \(input)!")
let lengthResult = runReader(reader { (environment: String) -> Int in
return environment.lengthOfBytes(using: String.Encoding.utf8)
})("Banana")
XCTAssert(lengthResult == 6)
let length : (String) -> Int = { $0.lengthOfBytes(using: String.Encoding.utf8) }
let lengthResult2 = runReader(reader(length))("Banana")
XCTAssert(lengthResult2 == 6)
// Ask
let lengthResult3 = (reader { 1234 } >>- runReader)?()
XCTAssert(lengthResult3 == 1234)
let lengthResult4 = hello() >>- runReader
XCTAssert(lengthResult4?("Matthew") == "Hello Matthew")
// Asks
let lengthResult5 = runReader(asks(length))("Banana")
XCTAssert(lengthResult5 == 6)
let lengthReader = runReader(reader(asks))(length)
let lengthResult6 = lengthReader.runReader("Banana")
XCTAssert(lengthResult6 == 6)
// >>-
let lengthResult7 = (asks(length) >>- runReader)?("abc")
XCTAssert(lengthResult7 == .some(3))
}
}
| bsd-3-clause | e6a53413e683ee12528548ad6a66fc73 | 33.256098 | 99 | 0.56141 | 4.430599 | false | false | false | false |
Jackysonglanlan/Scripts | swift/xunyou_accelerator/Tests/xunyou_acceleratorTests/helpers/AwaitExtension.swift | 1 | 1490 |
import Quick
import Nimble
// see https://www.swiftbysundell.com/posts/asyncawait-in-swift-unit-tests
class AwaitError : Error {}
extension QuickSpec {
/**
* Usage:
* let reValue = try await{ (callback: (String) -> Void) -> Void in
* // async op ...
* callback("result value")
* }
*
* expect(reValue) == "result value"
*/
func await<T>(_ function: (@escaping (T) -> Void) -> Void) throws -> T {
let expectation = self.expectation(description: "Async call")
var result: T?
function() { value in
result = value
expectation.fulfill()
}
waitForExpectations(timeout: 10)
guard let unwrappedResult = result else {
throw AwaitError()
}
return unwrappedResult
}
typealias Function<T> = (T) -> Void
/**
* Usage:
* let reValue = try await(asyncOp, arg1)
*
*/
func await<A, R>(_ function: @escaping Function<(A, Function<R>)>, _ argument: A) throws -> R {
return try await { handler in
function((argument, handler))
}
}
/**
* Usage:
* let reValue = try await(asyncOp, arg1, arg2)
*
*/
func await<A1, A2, R>(_ function: @escaping Function<(A1, A2, Function<R>)>,
_ arg1: A1, _ arg2: A2) throws -> R {
return try await { handler in
function((arg1, arg2, handler))
}
}
}
| unlicense | 7e890d45c780a40aff8075587b23a574 | 22.650794 | 99 | 0.521477 | 3.860104 | false | false | false | false |
kildevaeld/FASlideView | Example/Pods/Nimble/Nimble/Matchers/RaisesException.swift | 1 | 10050 | import Foundation
internal struct RaiseExceptionMatchResult {
var success: Bool
var nameFailureMessage: FailureMessage?
var reasonFailureMessage: FailureMessage?
var userInfoFailureMessage: FailureMessage?
}
internal func raiseExceptionMatcher(matches: (NSException?, SourceLocation) -> RaiseExceptionMatchResult) -> MatcherFunc<Any> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.actualValue = nil
var exception: NSException?
let capture = NMBExceptionCapture(handler: ({ e in
exception = e
}), finally: nil)
capture.tryBlock {
actualExpression.evaluate()
return
}
let result = matches(exception, actualExpression.location)
failureMessage.postfixMessage = "raise exception"
if let nameFailureMessage = result.nameFailureMessage {
failureMessage.postfixMessage += " with name \(nameFailureMessage.postfixMessage)"
}
if let reasonFailureMessage = result.reasonFailureMessage {
failureMessage.postfixMessage += " with reason \(reasonFailureMessage.postfixMessage)"
}
if let userInfoFailureMessage = result.userInfoFailureMessage {
failureMessage.postfixMessage += " with userInfo \(userInfoFailureMessage.postfixMessage)"
}
if result.nameFailureMessage == nil && result.reasonFailureMessage == nil
&& result.userInfoFailureMessage == nil {
failureMessage.postfixMessage = "raise any exception"
}
return result.success
}
}
// A Nimble matcher that succeeds when the actual expression raises an exception, which name,
// reason and userInfo match successfully with the provided matchers
public func raiseException(
named: NonNilMatcherFunc<String>? = nil,
reason: NonNilMatcherFunc<String>? = nil,
userInfo: NonNilMatcherFunc<NSDictionary>? = nil) -> MatcherFunc<Any> {
return raiseExceptionMatcher() { exception, location in
var matches = exception != nil
var nameFailureMessage: FailureMessage?
if let nameMatcher = named {
let wrapper = NonNilMatcherWrapper(NonNilBasicMatcherWrapper(nameMatcher))
nameFailureMessage = FailureMessage()
matches = wrapper.matches(
Expression(expression: { exception?.name },
location: location,
isClosure: false),
failureMessage: nameFailureMessage!) && matches
}
var reasonFailureMessage: FailureMessage?
if let reasonMatcher = reason {
let wrapper = NonNilMatcherWrapper(NonNilBasicMatcherWrapper(reasonMatcher))
reasonFailureMessage = FailureMessage()
matches = wrapper.matches(
Expression(expression: { exception?.reason },
location: location,
isClosure: false),
failureMessage: reasonFailureMessage!) && matches
}
var userInfoFailureMessage: FailureMessage?
if let userInfoMatcher = userInfo {
let wrapper = NonNilMatcherWrapper(NonNilBasicMatcherWrapper(userInfoMatcher))
userInfoFailureMessage = FailureMessage()
matches = wrapper.matches(
Expression(expression: { exception?.userInfo },
location: location,
isClosure: false),
failureMessage: userInfoFailureMessage!) && matches
}
return RaiseExceptionMatchResult(
success: matches,
nameFailureMessage: nameFailureMessage,
reasonFailureMessage: reasonFailureMessage,
userInfoFailureMessage: userInfoFailureMessage)
}
}
/// A Nimble matcher that succeeds when the actual expression raises an exception with
/// the specified name, reason, and userInfo.
public func raiseException(named named: String, reason: String, userInfo: NSDictionary) -> MatcherFunc<Any> {
return raiseException(equal(named), reason: equal(reason), userInfo: equal(userInfo))
}
/// A Nimble matcher that succeeds when the actual expression raises an exception with
/// the specified name and reason.
public func raiseException(named named: String, reason: String) -> MatcherFunc<Any> {
return raiseException(named: equal(named), reason: equal(reason))
}
/// A Nimble matcher that succeeds when the actual expression raises an exception with
/// the specified name.
public func raiseException(named named: String) -> MatcherFunc<Any> {
return raiseException(named: equal(named))
}
public class NMBObjCRaiseExceptionMatcher : NMBMatcher {
var _name: String?
var _reason: String?
var _userInfo: NSDictionary?
var _nameMatcher: NMBMatcher?
var _reasonMatcher: NMBMatcher?
var _userInfoMatcher: NMBMatcher?
init(name: String?, reason: String?, userInfo: NSDictionary?) {
_name = name
_reason = reason
_userInfo = userInfo
}
init(nameMatcher: NMBMatcher?, reasonMatcher: NMBMatcher?, userInfoMatcher: NMBMatcher?) {
_nameMatcher = nameMatcher
_reasonMatcher = reasonMatcher
_userInfoMatcher = userInfoMatcher
}
public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let block: () -> Any? = ({ actualBlock(); return nil })
let expr = Expression(expression: block, location: location)
if _nameMatcher != nil || _reasonMatcher != nil || _userInfoMatcher != nil {
return raiseExceptionMatcher() {
exception, location in
var matches = exception != nil
var nameFailureMessage: FailureMessage?
if let nameMatcher = self._nameMatcher {
nameFailureMessage = FailureMessage()
matches = nameMatcher.matches({ exception?.name },
failureMessage: nameFailureMessage!,
location: location) && matches
}
var reasonFailureMessage: FailureMessage?
if let reasonMatcher = self._reasonMatcher {
reasonFailureMessage = FailureMessage()
matches = reasonMatcher.matches({ exception?.reason },
failureMessage: reasonFailureMessage!,
location: location) && matches
}
var userInfoFailureMessage: FailureMessage?
if let userInfoMatcher = self._userInfoMatcher {
userInfoFailureMessage = FailureMessage()
matches = userInfoMatcher.matches({ exception?.userInfo },
failureMessage: userInfoFailureMessage!,
location: location) && matches
}
return RaiseExceptionMatchResult(
success: matches,
nameFailureMessage: nameFailureMessage,
reasonFailureMessage: reasonFailureMessage,
userInfoFailureMessage: userInfoFailureMessage)
}.matches(expr, failureMessage: failureMessage)
} else if let name = _name, reason = _reason, userInfo = _userInfo {
return raiseException(named: name, reason: reason, userInfo: userInfo).matches(expr, failureMessage: failureMessage)
} else if let name = _name, reason = _reason {
return raiseException(named: name, reason: reason).matches(expr, failureMessage: failureMessage)
} else if let name = _name {
return raiseException(named: name).matches(expr, failureMessage: failureMessage)
} else {
return raiseException().matches(expr, failureMessage: failureMessage)
}
}
public func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
return !matches(actualBlock, failureMessage: failureMessage, location: location)
}
public var named: (name: String) -> NMBObjCRaiseExceptionMatcher {
return ({ name in
return NMBObjCRaiseExceptionMatcher(name: name, reason: self._reason, userInfo: self._userInfo)
})
}
public var reason: (reason: String?) -> NMBObjCRaiseExceptionMatcher {
return ({ reason in
return NMBObjCRaiseExceptionMatcher(name: self._name, reason: reason, userInfo: self._userInfo)
})
}
public var userInfo: (userInfo: NSDictionary?) -> NMBObjCRaiseExceptionMatcher {
return ({ userInfo in
return NMBObjCRaiseExceptionMatcher(name: self._name, reason: self._reason, userInfo: userInfo)
})
}
public var withName: (nameMatcher: NMBMatcher) -> NMBObjCRaiseExceptionMatcher {
return ({ nameMatcher in
return NMBObjCRaiseExceptionMatcher(nameMatcher: nameMatcher,
reasonMatcher: self._reasonMatcher, userInfoMatcher: self._userInfoMatcher)
})
}
public var withReason: (reasonMatcher: NMBMatcher) -> NMBObjCRaiseExceptionMatcher {
return ({ reasonMatcher in
return NMBObjCRaiseExceptionMatcher(nameMatcher: self._nameMatcher,
reasonMatcher: reasonMatcher, userInfoMatcher: self._userInfoMatcher)
})
}
public var withUserInfo: (userInfoMatcher: NMBMatcher) -> NMBObjCRaiseExceptionMatcher {
return ({ userInfoMatcher in
return NMBObjCRaiseExceptionMatcher(nameMatcher: self._nameMatcher,
reasonMatcher: self._reasonMatcher, userInfoMatcher: userInfoMatcher)
})
}
}
extension NMBObjCMatcher {
public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher {
return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil, userInfo: nil)
}
}
| mit | 7b70a43872f9b5eed54b5fd7c0d1a1eb | 41.584746 | 128 | 0.639801 | 5.911765 | false | false | false | false |
Mclarenyang/medicine_aid | medicine aid/VisitingRecordTableViewController.swift | 1 | 5535 | //
// VisitingRecordTableViewController.swift
// medicine aid
//
// Created by nexuslink mac 2 on 2017/7/16.
// Copyright © 2017年 NMID. All rights reserved.
//
import UIKit
import RealmSwift
class VisitingRecordTableViewController: UITableViewController {
// 显示列表参数
var list :[(String,String)] = [("","")]
//刷新
let rc = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
/// 设置导航栏
self.navigationItem.title = "就诊记录"
self.navigationController?.navigationBar.barTintColor = UIColor(red:255/255,green:60/255,blue:40/255 ,alpha:1)
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
//设置刷新UIRefreshControl
rc.attributedTitle = NSAttributedString(string: "正在拼命刷新")
rc.addTarget(self, action: #selector(InquiryRecordTableViewController.refreshTableView), for: UIControlEvents.valueChanged)
rc.tintColor = UIColor(red:255/255,green:60/255,blue:40/255 ,alpha: 1)
self.tableView.refreshControl = rc
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(_ animated: Bool) {
refreshTableView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return list.count
}
// tableview 加载cell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
/// 定义cell
let cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cellId")
// 读取数据
let time = list[indexPath.row].1
cell.textLabel?.text = time
//cell.detailTextLabel?.text = time
return cell
}
//刷新表格
func refreshTableView(){
getRecord()
rc.endRefreshing()
}
//读取记录
func getRecord() {
self.list.removeAll()
//读取储存信息
//ID
let defaults = UserDefaults.standard
let UserID = String(describing: defaults.value(forKey: "UserID")!)
//读取所有条目
let realm = try! Realm()
let mylist = realm.objects(DPRList.self).filter("PatientID = '\(UserID)'").filter("MedicalList == nil")
guard mylist.count != 0 else {
let newlistsub = ("","暂无数据")
list.append(newlistsub)
self.tableView.reloadData()
return
}
for i in 0...mylist.count-1{
var newlistsub:(String,String) = ("","")
newlistsub.0 = mylist[i].DoctorID
newlistsub.1 = mylist[i].Time
list.append(newlistsub)
}
self.tableView.reloadData()
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | ae2a27ccad0c7c13970ef9b2cf17b8a3 | 29.761364 | 136 | 0.621167 | 5.088346 | false | false | false | false |
sourcebitsllc/Asset-Generator-Mac | XCAssetGenerator/StatusCrafter.swift | 1 | 1494 | //
// StatusViewModel.swift
// XCAssetGenerator
//
// Created by Bader on 5/26/15.
// Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved.
//
import Foundation
typealias Status = String
struct StatusCrafter {
static func postGeneration(catalog: Path, amount: Int) -> Status {
let s = pluralize(amount, singular: "asset was", plural: "assets were")
return "\(s) added to \(catalog)"
}
static func status(#assets: [Asset]?, target: AssetCatalog?) -> Status {
switch (assets, target) {
case (.None, _):
return "Drop a folder with slices you'd like to add to your Xcode project"
case (.Some(let a), .None):
let end = (a.count > 0) ? pluralize(a.count, singular: "asset", plural: "assets") : "assets"
return "Choose an Xcode project to add " + end
case (.Some(let a), .Some(let catalog)) where a.count == 0:
return "Add slices to the folder in order to build assets"
case (.Some(let a), .Some(let catalog)):
return newAssetsStatus(a, catalog: catalog)
default:
return ""
}
}
private static func newAssetsStatus(assets: [Asset], catalog: AssetCatalog) -> Status {
let total = AssetDiff.diffWithOperation(assets, catalog: catalog)(operation: .NewAssets)
let n = pluralize(total, singular: "new asset", plural: "new assets")
return "Hit Build to add \(n) to your project"
}
}
| mit | 44e80574aa780d6b7b10f31041fb164f | 32.954545 | 104 | 0.608434 | 3.931579 | false | false | false | false |
rambler-ios/RamblerConferences | Carthage/Checkouts/rides-ios-sdk/examples/Swift SDK/Swift SDK/DeeplinkExampleViewController.swift | 1 | 4113 | //
// DeeplinkExampleViewController.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 UberRides
import CoreLocation
/// This class provides an example for using the RideRequestButton to initiate a deeplink
/// into the Uber app
public class DeeplinkExampleViewController: ButtonExampleViewController {
let blackRequestButton = RideRequestButton()
let whiteRequestButton = RideRequestButton()
override public func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Deeplink Buttons"
topView.addSubview(blackRequestButton)
bottomView.addSubview(whiteRequestButton)
initialSetup()
addBlackRequestButtonConstraints()
addWhiteRequestButtonConstraints()
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
whiteRequestButton.loadRideInformation()
}
// Mark: Private Interface
private func initialSetup() {
let deeplinkBehavior = DeeplinkRequestingBehavior()
whiteRequestButton.requestBehavior = deeplinkBehavior
whiteRequestButton.colorStyle = .White
let parameterBuilder = RideParametersBuilder()
parameterBuilder.setProductID("a1111c8c-c720-46c3-8534-2fcdd730040d")
let pickupLocation = CLLocation(latitude: 37.770, longitude: -122.466)
parameterBuilder.setPickupLocation(pickupLocation, nickname: "California Academy of Sciences")
let dropoffLocation = CLLocation(latitude: 37.791, longitude: -122.405)
parameterBuilder.setDropoffLocation(dropoffLocation, nickname: "Pier 39")
whiteRequestButton.rideParameters = parameterBuilder.build()
}
private func addBlackRequestButtonConstraints() {
blackRequestButton.translatesAutoresizingMaskIntoConstraints = false
let centerYConstraint = NSLayoutConstraint(item: blackRequestButton, attribute: .CenterY, relatedBy: .Equal, toItem: topView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
let centerXConstraint = NSLayoutConstraint(item: blackRequestButton, attribute: .CenterX, relatedBy: .Equal, toItem: topView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
topView.addConstraints([centerYConstraint, centerXConstraint])
}
private func addWhiteRequestButtonConstraints() {
whiteRequestButton.translatesAutoresizingMaskIntoConstraints = false
let centerYConstraint = NSLayoutConstraint(item: whiteRequestButton, attribute: .CenterY, relatedBy: .Equal, toItem: bottomView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
let centerXConstraint = NSLayoutConstraint(item: whiteRequestButton, attribute: .CenterX, relatedBy: .Equal, toItem: bottomView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
bottomView.addConstraints([centerYConstraint, centerXConstraint])
}
}
| mit | 9e175fd6f74c58e2d3e6da052e7babcf | 45.202247 | 189 | 0.730788 | 5.165829 | false | false | false | false |
craaron/ioscreator | SpriteKitSwiftAccelerometerTutorial/SpriteKitSwiftAccelerometerTutorial/GameScene.swift | 40 | 1356 | //
// GameScene.swift
// SpriteKitSwiftAccelerometerTutorial
//
// Created by Arthur Knopper on 10/12/14.
// Copyright (c) 2014 Arthur Knopper. All rights reserved.
//
import SpriteKit
import CoreMotion
class GameScene: SKScene {
var airplane = SKSpriteNode()
var motionManager = CMMotionManager()
var destX:CGFloat = 0.0
override func didMoveToView(view: SKView) {
/* Setup your scene here */
// 1
airplane = SKSpriteNode(imageNamed: "Airplane")
airplane.position = CGPointMake(frame.size.width/2, frame.size.height/2)
self.addChild(airplane)
if motionManager.accelerometerAvailable == true {
// 2
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{
data, error in
var currentX = self.airplane.position.x
// 3
if data.acceleration.x < 0 {
self.destX = currentX + CGFloat(data.acceleration.x * 100)
}
else if data.acceleration.x > 0 {
self.destX = currentX + CGFloat(data.acceleration.x * 100)
}
})
}
}
// 4
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
var action = SKAction.moveToX(destX, duration: 1)
self.airplane.runAction(action)
}
}
| mit | 61fcc224991421beb1ebf5dbb5fc20d4 | 24.584906 | 99 | 0.632743 | 4.374194 | false | false | false | false |
stakes/Frameless | Frameless/HistoryManager.swift | 2 | 6161 | //
// HistoryManager.swift
// Frameless
//
// Created by Jay Stakelon on 8/6/15.
// Copyright (c) 2015 Jay Stakelon. All rights reserved.
//
import WebKit
class HistoryManager: NSObject {
static let manager = HistoryManager()
let _maxHistoryItems = 50
var _fullHistory: Array<HistoryEntry>?
var totalEntries: Int {
get {
return _fullHistory!.count
}
}
var studio: HistoryEntry?
var matches: Array<HistoryEntry> = Array<HistoryEntry>()
var history: Array<HistoryEntry> = Array<HistoryEntry>()
override init() {
super.init()
_fullHistory = readHistory()
}
func getHistoryDataFor(originalString: String) {
let stringToFind = originalString.lowercaseString
studio = nil
history.removeAll(keepCapacity: false)
matches.removeAll(keepCapacity: false)
var framerMatches = Array<HistoryEntry>()
var domainMatches = Array<HistoryEntry>()
var titleMatches = Array<HistoryEntry>()
for entry:HistoryEntry in _fullHistory! {
let entryUrl = entry.urlString.lowercaseString
let entryTitle = entry.title?.lowercaseString
if entryTitle?.rangeOfString("framer studio projects") != nil {
// Put Framer Studio home in the top matches
studio = entry
} else if entryUrl.rangeOfString(stringToFind) != nil {
if entryUrl.lowercaseString.rangeOfString(".framer") != nil {
// is it a framer project URL? these go first
framerMatches.insert(entry, atIndex: 0)
} else {
if entryUrl.hasPrefix(stringToFind) && entryUrl.lowercaseString.rangeOfString(".framer") == nil {
// is it a domain match? if it's a letter-for-letter match put in top matches
// unless it's a local Framer Studio URL because that list will get long
matches.append(entry)
} else {
// otherwise add to history
domainMatches.insert(entry, atIndex: 0)
}
}
} else if entryTitle?.rangeOfString(stringToFind) != nil {
// is it a title match? cause these go last
titleMatches.insert(entry, atIndex: 0)
}
history = framerMatches + domainMatches + titleMatches
}
NSNotificationCenter.defaultCenter().postNotificationName(HISTORY_UPDATED_NOTIFICATION, object: nil)
}
func addToHistory(webView: WKWebView) {
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.KeepHistory.rawValue) as! Bool == true {
if let urlStr = webView.URL?.absoluteString as String! {
if verifyUniquenessOfURL(urlStr) {
checkForFramerStudio(webView)
var title = webView.title
if title == nil || title == "" {
title = " "
}
let historyEntry = HistoryEntry(url: webView.URL!, urlString: createDisplayURLString(webView.URL!), title: title)
_fullHistory?.append(historyEntry)
trimHistory()
saveHistory()
NSNotificationCenter.defaultCenter().postNotificationName(HISTORY_UPDATED_NOTIFICATION, object: nil)
}
}
}
}
func trimHistory() {
if let arr = _fullHistory {
if arr.count > _maxHistoryItems {
let count = arr.count as Int
let extraCount = count - _maxHistoryItems
let newarr = arr[extraCount...(arr.endIndex-1)]
_fullHistory = Array<HistoryEntry>(newarr)
}
}
}
func createDisplayURLString(url: NSURL) -> String {
var str = url.resourceSpecifier
if str.hasPrefix("//") {
str = str.substringFromIndex(str.startIndex.advancedBy(2))
}
if str.hasPrefix("www.") {
str = str.substringFromIndex(str.startIndex.advancedBy(4))
}
if str.hasSuffix("/") {
str = str.substringToIndex(str.endIndex.predecessor())
}
return str
}
func verifyUniquenessOfURL(urlStr: String) -> Bool {
for entry:HistoryEntry in _fullHistory! {
let fullURLString = entry.url.absoluteString as String!
if fullURLString == urlStr {
return false
}
}
return true
}
func checkForFramerStudio(webView:WKWebView) {
// if this is a Framer Studio URL
if webView.title?.lowercaseString.rangeOfString("framer studio projects") != nil {
// remove old framer studios
let filteredHistory = _fullHistory!.filter({
return $0.title?.lowercaseString.rangeOfString("framer studio projects") == nil
})
_fullHistory = filteredHistory
saveHistory()
}
}
func clearHistory() {
history.removeAll(keepCapacity: false)
matches.removeAll(keepCapacity: false)
_fullHistory?.removeAll(keepCapacity: false)
saveHistory()
NSNotificationCenter.defaultCenter().postNotificationName(HISTORY_UPDATED_NOTIFICATION, object: nil)
}
func saveHistory() {
let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(_fullHistory as Array<HistoryEntry>!)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(archivedObject, forKey: AppDefaultKeys.History.rawValue)
defaults.synchronize()
}
func readHistory() -> Array<HistoryEntry>? {
if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.History.rawValue) as? NSData {
return (NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as? [HistoryEntry])!
} else {
return Array<HistoryEntry>()
}
}
}
| mit | 80ffeb2cd1910c7f6ef94551405599d6 | 37.748428 | 133 | 0.585132 | 5.100166 | false | false | false | false |
nostramap/nostra-sdk-sample-ios | IdentifySample/Swift/IdentifySample/IdentifyViewController.swift | 1 | 5490 | //
// ViewController.swift
// IdentifySample
//
// Copyright © 2559 Globtech. All rights reserved.
//
import UIKit
import NOSTRASDK
import ArcGIS
class IdentifyViewController: UIViewController, AGSMapViewLayerDelegate, AGSMapViewTouchDelegate, AGSLayerDelegate, AGSCalloutDelegate {
@IBOutlet weak var mapView: AGSMapView!
let referrer = ""
let graphicLayer = AGSGraphicsLayer();
var idenResult: NTIdentifyResult?;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initializeMap();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailSegue" {
let detailViewController = segue.destination as! DetailViewController;
detailViewController.idenResult = idenResult;
}
}
func initializeMap() {
mapView.layerDelegate = self;
mapView.touchDelegate = self;
mapView.callout.delegate = self;
do {
// Get map permisson.
let resultSet = try NTMapPermissionService.execute();
// Get Street map HD (service id: 2)
if resultSet.results != nil && resultSet.results.count > 0 {
let filtered = resultSet.results.filter({ (mp) -> Bool in
return mp.serviceId == 2;
})
if filtered.count > 0 {
let mapPermisson = filtered.first;
let url = URL(string: mapPermisson!.serviceUrl_L);
let cred = AGSCredential(token: mapPermisson?.serviceToken_L, referer: referrer);
let tiledLayer = AGSTiledMapServiceLayer(url: url, credential: cred)
tiledLayer?.renderNativeResolution = true;
tiledLayer?.delegate = self;
mapView.addMapLayer(tiledLayer, withName: mapPermisson!.serviceName);
}
}
}
catch let error as NSError {
print("error: \(error)");
}
}
@IBAction func btnCurrentLocation_Clicked(_ btn: UIButton) {
btn.isSelected = !btn.isSelected;
mapView.locationDisplay.autoPanMode = btn.isSelected ? .default : .off;
}
//MARK: Touch Delegate
func mapView(_ mapView: AGSMapView!, didTapAndHoldAt screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [AnyHashable: Any]!) {
if graphicLayer.graphicsCount > 0 {
graphicLayer.removeAllGraphics();
}
let symbol = AGSSimpleMarkerSymbol(color: UIColor.red);
symbol?.style = .X;
symbol?.size = CGSize(width: 15, height: 15);
let graphic = AGSGraphic(geometry: mappoint, symbol: symbol, attributes: nil);
graphicLayer.addGraphic(graphic);
}
//MARK: Callout delegate
func callout(_ callout: AGSCallout!, willShowFor feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool {
var show = false;
do {
let point = AGSPoint(fromDecimalDegreesString: mapPoint.decimalDegreesString(withNumDigits: 7),
with: AGSSpatialReference.wgs84());
let idenParam = NTIdentifyParameter(lat: (point?.y)!, lon: (point?.x)!);
idenResult = try NTIdentifyService.execute(idenParam);
callout.title = idenResult!.name_L;
callout.detail = "\(idenResult!.adminLevel3_L), \(idenResult!.adminLevel2_L), \(idenResult!.adminLevel1_L)"
if idenResult?.nostraId != nil && idenResult?.nostraId != "" {
callout.accessoryButtonType = .detailDisclosure
callout.isAccessoryButtonHidden = false;
}
else {
callout.isAccessoryButtonHidden = true;
}
show = true;
}
catch let error as NSError {
print("error: \(error.description)")
}
return show;
}
func didClickAccessoryButton(for callout: AGSCallout!) {
self.performSegue(withIdentifier: "detailSegue", sender: nil);
}
//MARK: Map view and Layer delegate
func mapViewDidLoad(_ mapView: AGSMapView!) {
mapView.locationDisplay.startDataSource()
let env = AGSEnvelope(xmin: 10458701.000000, ymin: 542977.875000,
xmax: 11986879.000000, ymax: 2498290.000000,
spatialReference: AGSSpatialReference.webMercator());
mapView.zoom(to: env, animated: true);
mapView.addMapLayer(graphicLayer, withName: "GraphicLyaer");
}
func layerDidLoad(_ layer: AGSLayer!) {
print("\(layer.name) was loaded");
}
func layer(_ layer: AGSLayer!, didFailToLoadWithError error: Error!) {
print("\(layer.name) failed to load by reason: \(error.localizedDescription)");
}
}
| apache-2.0 | 7c976d604aca0b84b364397c0fba4678 | 31.47929 | 136 | 0.559665 | 5.227619 | false | false | false | false |
benzhipeng/DFImageManager | DFImageManager.playground/section-1.swift | 1 | 827 | // Playground - noun: a place where people can play
import UIKit
import DFImageManagerKit
import XCPlayground
// WARNING: DFImageManager Swift interfaces are automatically generated by Xcode.
let manager = DFImageManager.sharedManager()
let imageURL = NSURL(string: "http://farm8.staticflickr.com/7315/16455839655_7d6deb1ebf_z_d.jpg")!
// Request fullsize image
manager.requestImageForResource(imageURL) { (image: UIImage!, [NSObject : AnyObject]!) -> Void in
var fetchedImage = image
}
// Request scaled image
let request = DFImageRequest(resource: imageURL, targetSize: CGSize(width: 100, height: 100), contentMode: .AspectFill, options: nil)
manager.requestImageForRequest(request) { (image: UIImage!, [NSObject : AnyObject]!) -> Void in
var fetchedImage = image
}
XCPSetExecutionShouldContinueIndefinitely()
| mit | d5e1aecd344e080a6e81a8704774c5ea | 33.458333 | 133 | 0.771463 | 4.094059 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/DelaySubscription.swift | 11 | 1458 | //
// DelaySubscription.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DelaySubscriptionSink<O: ObserverType>
: Sink<O>, ObserverType {
typealias E = O.E
typealias Parent = DelaySubscription<E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
}
class DelaySubscription<Element>: Producer<Element> {
private let _source: Observable<Element>
private let _dueTime: RxTimeInterval
private let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DelaySubscriptionSink(parent: self, observer: observer, cancel: cancel)
let subscription = _scheduler.scheduleRelative((), dueTime: _dueTime) { _ in
return self._source.subscribe(sink)
}
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | f2505bbaf8d5bfe35088da7fae9a5ee9 | 27.568627 | 145 | 0.641043 | 4.442073 | false | false | false | false |
icerockdev/IRPDFKit | IRPDFKit/Classes/IRPDFDocumentViewController.swift | 1 | 5499 | //
// Created by Aleksey Mikhailov on 10/10/16.
// Copyright © 2016 IceRock Development. All rights reserved.
//
import UIKit
import CoreGraphics
import JASON
public class IRPDFDocumentViewController: UIViewController {
@IBOutlet weak var pdfPagesScrollView: UIScrollView!
public var pdfDocumentUrl: NSURL? {
didSet {
if let url = pdfDocumentUrl {
pdfDocument = CGPDFDocumentCreateWithURL(url)
searchEngine = IRPDFSearchEngine(documentUrl: url)
} else {
pdfDocument = nil
searchEngine = nil
}
}
}
var pdfDocument: CGPDFDocument? {
didSet {
reloadData()
}
}
var pdfView: IRPDFDocumentView!
var searchEngine: IRPDFSearchEngine?
var lastSearchQuery: String?
public override func viewDidLoad() {
super.viewDidLoad()
if pdfPagesScrollView == nil {
let scrollView = UIScrollView(frame: view.bounds)
view.addSubview(scrollView)
pdfPagesScrollView = scrollView
pdfPagesScrollView.scrollEnabled = true
pdfPagesScrollView.bounces = true
pdfPagesScrollView.alwaysBounceVertical = true
pdfPagesScrollView.backgroundColor = UIColor.groupTableViewBackgroundColor()
pdfPagesScrollView.showsVerticalScrollIndicator = true
pdfPagesScrollView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
pdfPagesScrollView.maximumZoomScale = 8
pdfPagesScrollView.minimumZoomScale = 1
}
pdfPagesScrollView.delegate = self
var doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTapGesture))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
pdfPagesScrollView.addGestureRecognizer(doubleTapGestureRecognizer)
}
public func reloadData() {
guard let _ = pdfPagesScrollView else {
return
}
for view in pdfPagesScrollView.subviews {
view.removeFromSuperview()
}
guard let pdfDocument = pdfDocument else {
return
}
pdfView = IRPDFDocumentView(frame: pdfPagesScrollView.bounds)
pdfView.pdfDocument = pdfDocument
pdfView.translatesAutoresizingMaskIntoConstraints = false
pdfPagesScrollView.addSubview(pdfView)
pdfPagesScrollView.addConstraint(NSLayoutConstraint(item: pdfPagesScrollView,
attribute: .Top, relatedBy: .Equal, toItem: pdfView,
attribute: .Top, multiplier: 1, constant: 0))
pdfPagesScrollView.addConstraint(NSLayoutConstraint(item: pdfPagesScrollView,
attribute: .Bottom, relatedBy: .Equal, toItem: pdfView,
attribute: .Bottom, multiplier: 1, constant: 0))
pdfPagesScrollView.addConstraint(NSLayoutConstraint(item: pdfPagesScrollView,
attribute: .CenterX, relatedBy: .Equal, toItem: pdfView,
attribute: .CenterX, multiplier: 1, constant: 0))
pdfPagesScrollView.addConstraint(NSLayoutConstraint(item: pdfPagesScrollView,
attribute: .Leading, relatedBy: .Equal, toItem: pdfView,
attribute: .Leading, multiplier: 1, constant: 0))
pdfPagesScrollView.addConstraint(NSLayoutConstraint(item: pdfPagesScrollView,
attribute: .Trailing, relatedBy: .Equal, toItem: pdfView,
attribute: .Trailing, multiplier: 1, constant: 0))
}
public func search(_ query: String) {
searchEngine?.search(query) {
[weak self] (_, searchResults) in
self?.pdfView.highlightedSearchResults = searchResults
}
}
public func presentSearchViewController(anchor: UIBarButtonItem) {
guard let _ = searchEngine else {
return
}
let searchViewController = IRPDFSearchResultsViewController()
searchViewController.searchDelegate = self
searchViewController.searchEngine = searchEngine
searchViewController.searchQuery = lastSearchQuery
searchViewController.modalPresentationStyle = .Popover
searchViewController.popoverPresentationController?.barButtonItem = anchor
presentViewController(searchViewController, animated: true, completion: nil)
}
}
extension IRPDFDocumentViewController {
func doubleTapGesture(gestureRecognizer: UITapGestureRecognizer) {
let zoomScale: CGFloat
if pdfPagesScrollView.zoomScale > pdfPagesScrollView.minimumZoomScale {
zoomScale = pdfPagesScrollView.minimumZoomScale
} else {
zoomScale = pdfPagesScrollView.maximumZoomScale
}
pdfPagesScrollView.setZoomScale(zoomScale, animated: true)
}
}
extension IRPDFDocumentViewController: UIScrollViewDelegate {
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return scrollView.subviews[0]
}
}
extension IRPDFDocumentViewController: IRPDFSearchResultsDelegate {
func searchResultsViewController(viewController: IRPDFSearchResultsViewController,
receiveResults results: [IRPDFSearchResult]?) {
pdfView.highlightedSearchResults = results
}
func searchResultsViewController(viewController: IRPDFSearchResultsViewController,
didSelectResult result: IRPDFSearchResult) {
pdfView.highlightedSearchResults = [result]
if let frame = pdfView.pageFrames?[result.page - 1] {
pdfPagesScrollView.zoomScale = 1.0
pdfPagesScrollView.contentOffset = frame.origin
}
}
func searchResultsViewController(viewController: IRPDFSearchResultsViewController,
queryChanged query: String?) {
lastSearchQuery = query
}
}
| mit | a5960ce5a8d7ab077bc94dc110f0249c | 32.321212 | 110 | 0.721353 | 5.369141 | false | false | false | false |
Parallels-MIPT/Coconut-Kit | CoconutKit/CoconutKit/ICloudDirectoryManager.swift | 1 | 6794 | //
// ICloudDirectoryManager.swift
// ICDocumentsSync-IOS
//
// Created by Malyshev Alexander on 31.07.15.
// Copyright (c) 2015 SecurityQQ. All rights reserved.
//
import Foundation
struct Const {
static let documents = "Documents"
static let directoryOperationQueueName = "directoryOperationQueue"
static let storedUbiquityIdentityToken = "com.triangle.storedUbituityIdentityToken"
}
struct QueueManager {
static let directoryQueue : NSOperationQueue = {
var queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1
queue.name = Const.directoryOperationQueueName
return queue
}()
}
@objc public class ICloudDirectoryManager: NSObject {
public let coordinator : NSFileCoordinator
public lazy var isUsingICloud : Bool = { return ICloudDirectoryManager.ubiquityContainerIdentityToken() != nil }()
public unowned var directoryPresenter : NSFilePresenter
public let directoryURL : NSURL
public var iCloudURL : NSURL?
public let directoryOperationQueue = QueueManager.directoryQueue
public init(directoryURL : NSURL) {
self.directoryPresenter = DirectoryFilePresenter(directoryURL: directoryURL, conflictManager: ConflictSolutionManager.defaultManager)
self.directoryURL = directoryURL
self.coordinator = NSFileCoordinator(filePresenter: directoryPresenter)
super.init()
NSFileCoordinator.addFilePresenter(directoryPresenter)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("ubiquityIdentityTokenDidChange:"), name: NSUbiquityIdentityDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
NSFileCoordinator.removeFilePresenter(directoryPresenter)
}
//MARK - storing iCloud token
private static var storedUbiquityIdentityToken : protocol<NSCoding, NSCopying, NSObjectProtocol>? {
if let ubiquityIdentityTokenArchive = NSUserDefaults.standardUserDefaults().objectForKey(Const.storedUbiquityIdentityToken) as? NSData,
storedToken = NSKeyedUnarchiver.unarchiveObjectWithData(ubiquityIdentityTokenArchive) as? protocol<NSCoding, NSCopying, NSObjectProtocol> {
return storedToken
}
return nil
}
private static func ubiquityContainerIdentityToken() -> protocol<NSCoding, NSCopying, NSObjectProtocol>? {
if let token = NSFileManager.defaultManager().ubiquityIdentityToken {
let archivedToken = NSKeyedArchiver.archivedDataWithRootObject(token)
NSUserDefaults.standardUserDefaults().setObject(archivedToken, forKey: Const.storedUbiquityIdentityToken)
return token
}
return nil
}
func ubiquityIdentityTokenDidChange(notification: NSNotification) {
if (NSFileManager.defaultManager().ubiquityIdentityToken == nil) {
directoryOperationQueue.cancelAllOperations()
} else {
moveDirectoryToiCloud()
}
}
//MARK - ICloudDirectory
public func getICloudDirectoryURLAndPerformHandler(handler : (NSURL -> Void)) {
if (iCloudURL == nil) {
let ubiqContainerURLOperation = UbiquitousContainerURLOperation { self.iCloudURL = $0 }
directoryOperationQueue.addOperation(ubiqContainerURLOperation)
directoryOperationQueue.addOperationWithBlock { [unowned self] in
let documentsDirectory = self.iCloudURL?.URLByAppendingPathComponent(Const.documents, isDirectory: true)
self.iCloudURL = documentsDirectory
handler(self.iCloudURL!)
}
} else {
directoryOperationQueue.addOperationWithBlock { [unowned self] in
handler(self.iCloudURL!)
}
}
}
//MARK - Moving to iCloud
public func moveDirectoryToiCloud() {
changeDirectoryUbiquitous(true)
}
public func removeDirectoryFromICloud() {
changeDirectoryUbiquitous(false)
}
public func moveSubitemToICloud(filename : String, typeOfFile : String) {
changeSubitemUbiquitous(true, filename: filename, typeOfFile: typeOfFile)
}
public func removeSubitemFromICloud(filename: String, typeOfFile : String) {
changeSubitemUbiquitous(false, filename: filename, typeOfFile: typeOfFile)
}
private func changeDirectoryUbiquitous(isUbiquitous: Bool) {
if isUsingICloud {
let urlHandler : [NSURL] -> Void = { [unowned self](urls) in
for url: NSURL in urls {
if let filename = url.URLByDeletingLastPathComponent?.lastPathComponent, typeOfFile = url.pathExtension {
self.changeSubitemUbiquitous(isUbiquitous, filename: filename, typeOfFile: typeOfFile)
}
}
}
if isUbiquitous {
let readDirOp = ReadDirectoryOperation(filePresenter: directoryPresenter, directoryURL: directoryURL, errorHandler: defaultFileOperationErrorHandler, urlHandler: urlHandler)
directoryOperationQueue.addOperation(readDirOp)
} else {
let handler : NSURL -> Void = { [unowned self](iCloudURL) in
let readDirOp = ReadDirectoryOperation(filePresenter: self.directoryPresenter, directoryURL: iCloudURL, errorHandler: defaultFileOperationErrorHandler, urlHandler: urlHandler)
self.directoryOperationQueue.addOperation(readDirOp)
}
getICloudDirectoryURLAndPerformHandler(handler)
}
}
}
private func changeSubitemUbiquitous(isUbiquitous: Bool, filename: String, typeOfFile: String) {
let movingHandler : NSURL -> Void = { [unowned self](iCloudURL) in
let newURL : NSURL
let oldURL : NSURL
if isUbiquitous {
newURL = iCloudURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(typeOfFile)
oldURL = self.directoryURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(typeOfFile)
} else {
newURL = self.directoryURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(typeOfFile)
oldURL = iCloudURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(typeOfFile)
}
let movingOperation = WriteFileForMovingOperation(newURL: newURL, filePresenter: self.directoryPresenter, fileURL: oldURL)
self.directoryOperationQueue.addOperation(movingOperation)
}
getICloudDirectoryURLAndPerformHandler(movingHandler)
}
} | apache-2.0 | f624662685ac9d310cd55e6fedee073b | 43.411765 | 195 | 0.687077 | 5.555192 | false | false | false | false |
codeforgreenville/trolley-tracker-ios-client | TrolleyTracker/Dependencies/ConcurrentOperation.swift | 1 | 2103 | //
// GetETAOperation.swift
//
//
// Created by Austin Younts on 8/23/15.
//
//
import Foundation
class ConcurrentOperation: Operation {
override var isAsynchronous: Bool {
return true
}
override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> {
let keys = ["isReady", "isExecuting", "isFinished", "isCancelled"]
if keys.contains(key) {
return ["state"]
}
return []
}
private enum State: Int {
/// The initial state of an `Operation`.
case initialized
/// The `Operation` is executing.
case executing
/// The `Operation` has finished executing.
case finished
/// The `Operation` has been cancelled.
case cancelled
}
private var _state = State.initialized
private var state: State {
get {
return _state
}
set(newState) {
// Manually fire the KVO notifications for state change, since this is "private".
willChangeValue(forKey: "state")
switch (_state, newState) {
case (.finished, _):
break // cannot leave the finished state
default:
_state = newState
}
didChangeValue(forKey: "state")
}
}
override var isExecuting: Bool {
return state == .executing
}
override var isFinished: Bool {
return state == .finished
}
override var isCancelled: Bool {
return state == .cancelled
}
override final func start() {
if !(state == .cancelled) {
state = .executing
}
execute()
}
func execute() {
print("\(type(of: self)) must override `execute()`.", terminator: "")
finish()
}
override func cancel() {
state = .cancelled
}
final func finish() {
state = .finished
}
}
| mit | 581c2ca2adda44647236110233e8bbcf | 20.90625 | 93 | 0.504042 | 5.231343 | false | false | false | false |
ben-ng/swift | benchmark/single-source/Hanoi.swift | 1 | 1378 | //===--- Hanoi.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks performance of Swift hanoi tower.
// <rdar://problem/22151932>
import Foundation
import TestsUtils
struct Move {
var from: String
var to: String
init(from:String, to:String) {
self.from = from
self.to = to
}
}
class TowersOfHanoi {
// Record all moves made.
var moves : [Move] = [Move]()
func solve(_ n: Int, start: String, auxiliary: String, end: String) {
if (n == 1) {
moves.append(Move(from:start, to:end))
} else {
solve(n - 1, start: start, auxiliary: end, end: auxiliary)
moves.append(Move(from:start, to:end))
solve(n - 1, start: auxiliary, auxiliary: start, end: end)
}
}
}
@inline(never)
public func run_Hanoi(_ N: Int) {
for _ in 1...100*N {
let hanoi: TowersOfHanoi = TowersOfHanoi()
hanoi.solve(10, start: "A", auxiliary: "B", end: "C")
}
}
| apache-2.0 | 2d42bf33f2b03e48cf21ea68453c9dd9 | 27.708333 | 80 | 0.582003 | 3.714286 | false | false | false | false |
adrfer/swift | test/SILGen/availability_query.swift | 1 | 2429 | // RUN: %target-swift-frontend -emit-silgen %s -target x86_64-apple-macosx10.50 | FileCheck %s
// REQUIRES: OS=macosx
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8
// CHECK: [[FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.53.8, iOS 7.1, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 50
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// Since we are compiling for an unmentioned platform (OS X), we check against the minimum
// deployment target, which is 10.50
if #available(iOS 7.1, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.52, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10, *) {
}
| apache-2.0 | 6c7875e6d23354bf9525b34f3d7e66c9 | 62.921053 | 170 | 0.650062 | 3.331962 | false | false | false | false |
hectoregm/ios_apprentice | Checklists/Checklists/DataModel.swift | 1 | 2890 | //
// DataModel.swift
// Checklists
//
// Created by Hector Enrique Gomez Morales on 12/30/14.
// Copyright (c) 2014 Hector Enrique Gomez Morales. All rights reserved.
//
import Foundation
class DataModel {
var lists = [Checklist]()
var indexOfSelectedChecklist: Int {
get {
return NSUserDefaults.standardUserDefaults().integerForKey("ChecklistIndex")
}
set {
NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: "ChecklistIndex")
}
}
init() {
loadChecklists()
registerDefaults()
handleFirstTime()
}
class func nextChecklistItemID() -> Int {
let userDefaults = NSUserDefaults.standardUserDefaults()
let itemID = userDefaults.integerForKey("ChecklistItemID")
userDefaults.setInteger(itemID + 1, forKey: "ChecklistItemID")
userDefaults.synchronize()
return itemID
}
func documentsDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
return paths[0]
}
func dataFilePath() -> String {
return documentsDirectory().stringByAppendingPathComponent("Checklists.plist")
}
func saveChecklists() {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
archiver.encodeObject(lists, forKey: "Checklists")
archiver.finishEncoding()
data.writeToFile(dataFilePath(), atomically: true)
}
func loadChecklists() {
let path = dataFilePath()
if NSFileManager.defaultManager().fileExistsAtPath(path) {
if let data = NSData(contentsOfFile: path) {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
lists = unarchiver.decodeObjectForKey("Checklists") as [Checklist]
unarchiver.finishDecoding()
sortChecklists()
}
}
}
func sortChecklists() {
lists.sort {
checklist1, checklist2 in
return checklist1.name.localizedStandardCompare(checklist2.name) == NSComparisonResult.OrderedAscending
}
}
func registerDefaults() {
let dictionary = [ "ChecklistIndex": -1,
"FirstTime": true,
"ChecklistItemID": 0]
NSUserDefaults.standardUserDefaults().registerDefaults(dictionary)
}
func handleFirstTime() {
let userDefaults = NSUserDefaults.standardUserDefaults()
let firstTime = userDefaults.boolForKey("FirstTime")
if firstTime {
let checklist = Checklist(name: "List")
lists.append(checklist)
indexOfSelectedChecklist = 0
userDefaults.setBool(false, forKey: "FirstTime")
}
}
} | mit | fcbd85659094d40590aed86c757dc094 | 31.483146 | 115 | 0.621799 | 5.633528 | false | false | false | false |
codelynx/silvershadow | Silvershadow/Sequence+Z.swift | 1 | 1944 | //
// Sequence+Z.swift
// ZKit [swift 3]
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Electricwoods LLC, Kaz Yoshikawa.
//
// 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.
//
//
// Description:
// pair() invokes closure with a paired items accoding to the sequence.
// It is usuful to build another sequence of item[N-1], item[N] based from
// the current sequence.
//
// Usage:
// let array = [1, 3, 4, 7, 8, 9]
// let items = array.pair { "\($0.0)-\($0.1)" } // ["1-3", "3-4", "4-7", "7-8", "8-9"]
//
extension Sequence {
@discardableResult
func pair<T>(_ closure: (Self.Iterator.Element, Self.Iterator.Element) -> T ) -> [T] {
var results = [T]()
var previous: Self.Iterator.Element? = nil
var iterator = self.makeIterator()
while let item = iterator.next() {
if let previous = previous {
results.append(closure(previous, item))
}
previous = item
}
return results
}
}
| mit | cca1bf52c70e0f524e67c9a1fbe586f5 | 32.517241 | 87 | 0.699074 | 3.521739 | false | false | false | false |
PatrickChow/Swift-Awsome | News/Modules/Channel..Listing/ViewController/ChannelListingsViewController.swift | 1 | 3501 | //
// Created by Patrick Chow on 2017/6/27.
// Copyright (c) 2017 JIEMIAN. All rights reserved.
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ChannelListingsViewController: ViewController, UITableViewDelegate {
// typealias _SectionModelType = SectionModel<String, ChannelModel>
public var tableView: UITableView!
public let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, ChannelModel>>()
override func viewDidLoad() {
super.viewDidLoad()
tableView = configureTableView()
if #available(iOS 9.0, *) {
tableView.cellLayoutMarginsFollowReadableWidth = false
}
view.addSubview(tableView)
configureDataSource()
tableView.rx
.setDelegate(self)
.disposed(by: disposeBag)
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .none
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNonzeroMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 15
}
public func configureTableView() -> UITableView {
let tableView = UITableView(frame: view.bounds, style: .grouped)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.backgroundColor = .clear
tableView.decelerationRate = 0.1
tableView.separatorInset = .zero
tableView.layoutMargins = .zero
return tableView
}
public func configureDataSource() {
tableView.register(ChannelListingsCell.self, forCellReuseIdentifier: "Cell")
tableView.register(ChannelListingsAccessoryCell.self, forCellReuseIdentifier: "ClassicCell")
let viewModel = TableViewChannelsSubscriptionCommandsModel(ChannelModel.selectingAllChannelsFromDBAndCovertToModel())
dataSource.configureCell = { [weak self] (_, tv, indexPath, element) in
if !element.isEditable {
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")
if let cell = cell as? ChannelListingsCell {
cell.setViewModel(element)
return cell
}
return cell!
}
let cell = tv.dequeueReusableCell(withIdentifier: "ClassicCell")
guard let listingCell = cell as? ChannelListingsAccessoryCell else {
return cell!
}
if let strongSelf = self {
let accessoryButtonTapped = listingCell.accessoryButtonTapped.takeUntil(listingCell.preparingForReuse)
accessoryButtonTapped
.map {
indexPath
}
.bind(to: viewModel.subscribing())
.disposed(by: strongSelf.disposeBag)
// TODO: 绑定顶部显示那个频道订阅
}
listingCell.setViewModel(element)
return listingCell
}
viewModel.items
.map {
$0.map {
SectionModel(model: "", items: $0)
}
}
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
}
| mit | 5a9fb163ba246aa5aa1b1b2245d62bdc | 33.77 | 125 | 0.606845 | 5.71875 | false | false | false | false |
Duraiamuthan/HybridWebRTC_iOS | WebRTCSupport/Pods/XWebView/XWebView/XWVMetaObject.swift | 1 | 9445 | /*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import ObjectiveC
class XWVMetaObject: CollectionType {
enum Member {
case Method(selector: Selector, arity: Int32)
case Property(getter: Selector, setter: Selector)
case Initializer(selector: Selector, arity: Int32)
var isMethod: Bool {
if case .Method = self { return true }
return false
}
var isProperty: Bool {
if case .Property = self { return true }
return false
}
var isInitializer: Bool {
if case .Initializer = self { return true }
return false
}
var selector: Selector? {
switch self {
case let .Method(selector, _):
assert(selector != Selector())
return selector
case let .Initializer(selector, _):
assert(selector != Selector())
return selector
default:
return nil
}
}
var getter: Selector? {
if case .Property(let getter, _) = self {
assert(getter != Selector())
return getter
}
return nil
}
var setter: Selector? {
if case .Property(let getter, let setter) = self {
assert(getter != Selector())
return setter
}
return nil
}
var type: String {
let promise: Bool
let arity: Int32
switch self {
case let .Method(selector, a):
promise = selector.description.hasSuffix(":promiseObject:") ||
selector.description.hasSuffix("PromiseObject:")
arity = a
case let .Initializer(_, a):
promise = true
arity = a < 0 ? a: a + 1
default:
promise = false
arity = -1
}
if !promise && arity < 0 {
return ""
}
return "#" + (arity >= 0 ? "\(arity)" : "") + (promise ? "p" : "a")
}
}
let plugin: AnyClass
private var members = [String: Member]()
private static let exclusion: Set<Selector> = {
var methods = instanceMethods(forProtocol: XWVScripting.self)
methods.remove(#selector(XWVScripting.invokeDefaultMethodWithArguments(_:)))
return methods.union([
#selector(_SpecialSelectors.dealloc),
#selector(NSObject.copy as ()->AnyObject)
])
}()
init(plugin: AnyClass) {
self.plugin = plugin
enumerateExcluding(self.dynamicType.exclusion) {
(name, member) -> Bool in
var name = name
var member = member
switch member {
case let .Method(selector, _):
if let cls = plugin as? XWVScripting.Type {
if cls.isSelectorExcludedFromScript?(selector) ?? false {
return true
}
if selector == #selector(XWVScripting.invokeDefaultMethodWithArguments(_:)) {
member = .Method(selector: selector, arity: -1)
name = ""
} else {
name = cls.scriptNameForSelector?(selector) ?? name
}
} else if name.characters.first == "_" {
return true
}
case .Property(_, _):
if let cls = plugin as? XWVScripting.Type {
if let isExcluded = cls.isKeyExcludedFromScript where name.withCString(isExcluded) {
return true
}
if let scriptNameForKey = cls.scriptNameForKey {
name = name.withCString(scriptNameForKey) ?? name
}
} else if name.characters.first == "_" {
return true
}
case let .Initializer(selector, _):
if selector == #selector(_InitSelector.init(byScriptWithArguments:)) {
member = .Initializer(selector: selector, arity: -1)
name = ""
} else if let cls = plugin as? XWVScripting.Type {
name = cls.scriptNameForSelector?(selector) ?? name
}
if !name.isEmpty {
return true
}
}
assert(members.indexForKey(name) == nil, "Plugin class \(plugin) has a conflict in member name '\(name)'")
members[name] = member
return true
}
}
private func enumerateExcluding(selectors: Set<Selector>, @noescape callback: ((String, Member)->Bool)) -> Bool {
var known = selectors
// enumerate properties
let propertyList = class_copyPropertyList(plugin, nil)
if propertyList != nil, var prop = Optional(propertyList) {
defer { free(propertyList) }
while prop.memory != nil {
let name = String(UTF8String: property_getName(prop.memory))!
// get getter
var attr = property_copyAttributeValue(prop.memory, "G")
let getter = Selector(attr == nil ? name : String(UTF8String: attr)!)
free(attr)
if known.contains(getter) {
prop = prop.successor()
continue
}
known.insert(getter)
// get setter if readwrite
var setter = Selector()
attr = property_copyAttributeValue(prop.memory, "R")
if attr == nil {
attr = property_copyAttributeValue(prop.memory, "S")
if attr == nil {
setter = Selector("set\(String(name.characters.first!).uppercaseString)\(String(name.characters.dropFirst())):")
} else {
setter = Selector(String(UTF8String: attr)!)
}
if known.contains(setter) {
setter = Selector()
} else {
known.insert(setter)
}
}
free(attr)
let info = Member.Property(getter: getter, setter: setter)
if !callback(name, info) {
return false
}
prop = prop.successor()
}
}
// enumerate methods
let methodList = class_copyMethodList(plugin, nil)
if methodList != nil, var method = Optional(methodList) {
defer { free(methodList) }
while method.memory != nil {
let sel = method_getName(method.memory)
if !known.contains(sel) && !sel.description.hasPrefix(".") {
let arity = Int32(method_getNumberOfArguments(method.memory) - 2)
let member: Member
if sel.description.hasPrefix("init") {
member = Member.Initializer(selector: sel, arity: arity)
} else {
member = Member.Method(selector: sel, arity: arity)
}
var name = sel.description
if let end = name.characters.indexOf(":") {
name = name[name.startIndex ..< end]
}
if !callback(name, member) {
return false
}
}
method = method.successor()
}
}
return true
}
}
extension XWVMetaObject {
// SequenceType
typealias Generator = DictionaryGenerator<String, Member>
func generate() -> Generator {
return members.generate()
}
// CollectionType
typealias Index = DictionaryIndex<String, Member>
var startIndex: Index {
return members.startIndex
}
var endIndex: Index {
return members.endIndex
}
subscript (position: Index) -> (String, Member) {
return members[position]
}
subscript (name: String) -> Member? {
return members[name]
}
}
private func instanceMethods(forProtocol aProtocol: Protocol) -> Set<Selector> {
var selectors = Set<Selector>()
for (req, inst) in [(true, true), (false, true)] {
let methodList = protocol_copyMethodDescriptionList(aProtocol.self, req, inst, nil)
if methodList != nil, var desc = Optional(methodList) {
while desc.memory.name != nil {
selectors.insert(desc.memory.name)
desc = desc.successor()
}
free(methodList)
}
}
return selectors
}
| gpl-3.0 | d151f9e788411a9785e66724558bf1fe | 35.608527 | 136 | 0.505558 | 5.30618 | false | false | false | false |
efremidze/Cluster | Sources/Annotation.swift | 1 | 4619 | //
// Annotation.swift
// Cluster
//
// Created by Lasha Efremidze on 4/15/17.
// Copyright © 2017 efremidze. All rights reserved.
//
import MapKit
open class Annotation: MKPointAnnotation {
// @available(swift, obsoleted: 6.0, message: "Please migrate to StyledClusterAnnotationView.")
open var style: ClusterAnnotationStyle?
public convenience init(coordinate: CLLocationCoordinate2D) {
self.init()
self.coordinate = coordinate
}
}
open class ClusterAnnotation: Annotation {
open var annotations = [MKAnnotation]()
open override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? ClusterAnnotation else { return false }
if self === object {
return true
}
if coordinate != object.coordinate {
return false
}
if annotations.count != object.annotations.count {
return false
}
return annotations.map { $0.coordinate } == object.annotations.map { $0.coordinate }
}
}
/**
The view associated with your cluster annotations.
*/
open class ClusterAnnotationView: MKAnnotationView {
open lazy var countLabel: UILabel = {
let label = UILabel()
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.backgroundColor = .clear
label.font = .boldSystemFont(ofSize: 13)
label.textColor = .white
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.baselineAdjustment = .alignCenters
self.addSubview(label)
return label
}()
open override var annotation: MKAnnotation? {
didSet {
configure()
}
}
open func configure() {
guard let annotation = annotation as? ClusterAnnotation else { return }
let count = annotation.annotations.count
countLabel.text = "\(count)"
}
}
/**
The style of the cluster annotation view.
*/
public enum ClusterAnnotationStyle {
/**
Displays the annotations as a circle.
- `color`: The color of the annotation circle
- `radius`: The radius of the annotation circle
*/
case color(UIColor, radius: CGFloat)
/**
Displays the annotation as an image.
*/
case image(UIImage?)
}
/**
A cluster annotation view that supports styles.
*/
open class StyledClusterAnnotationView: ClusterAnnotationView {
/**
The style of the cluster annotation view.
*/
public var style: ClusterAnnotationStyle
/**
Initializes and returns a new cluster annotation view.
- Parameters:
- annotation: The annotation object to associate with the new view.
- reuseIdentifier: If you plan to reuse the annotation view for similar types of annotations, pass a string to identify it. Although you can pass nil if you do not intend to reuse the view, reusing annotation views is generally recommended.
- style: The cluster annotation style to associate with the new view.
- Returns: The initialized cluster annotation view.
*/
public init(annotation: MKAnnotation?, reuseIdentifier: String?, style: ClusterAnnotationStyle) {
self.style = style
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
configure()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func configure() {
guard let annotation = annotation as? ClusterAnnotation else { return }
switch style {
case let .image(image):
backgroundColor = .clear
self.image = image
case let .color(color, radius):
let count = annotation.annotations.count
backgroundColor = color
var diameter = radius * 2
switch count {
case _ where count < 8:
diameter *= 0.6
case _ where count < 16:
diameter *= 0.8
default: break
}
frame = CGRect(origin: frame.origin, size: CGSize(width: diameter, height: diameter))
countLabel.text = "\(count)"
}
}
override open func layoutSubviews() {
super.layoutSubviews()
if case .color = style {
layer.masksToBounds = true
layer.cornerRadius = image == nil ? bounds.width / 2 : 0
countLabel.frame = bounds
}
}
}
| mit | 848af0d268f769df97634c8a69783b23 | 28.793548 | 245 | 0.614335 | 5.09151 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/ToolKit/JSToolKit/JSUI/TableViewCell/JSCellModelFactory.swift | 1 | 2592 | //
// JSCellModelFactory.swift
// BeeFun
//
// Created by WengHengcong on 25/06/2017.
// Copyright © 2017 JungleSong. All rights reserved.
//
import UIKit
/// Model工厂
class JSCellModelFactory {
// MARK: - Label
static func labelInit(type: String, id: String, key: String?, value: String?, discosure: Bool?) -> JSCellModel {
let cellM = JSCellModel.init(type: type, id: id, key: key, value: value, discosure: false)
return cellM
}
static func labelInit(type: String, id: String, key: String?, value: String?, discosure: Bool?, keySize: CGFloat?, valueSize: CGFloat?) -> JSCellModel {
let cellM = JSCellModel.init(type: type, id: id, key: key, value: value, discosure: discosure, keySize: keySize, valueSize: valueSize)
return cellM
}
// MARK: - Image
static func imageInit(type: String, id: String, key: String?, value: String?, icon: String?, discosure: Bool?) -> JSCellModel {
let cellM = JSCellModel.init(type: type, id: id, key: key, value: value, icon: icon, discosure: discosure)
return cellM
}
static func imageInit(type: String, id: String, key: String?, value: String?, icon: String?, discosure: Bool?, keySize: CGFloat?, valueSize: CGFloat?) -> JSCellModel {
let cellM = JSCellModel.init(type: type, id: id, key: key, value: value, icon: icon, discosure: discosure, keySize: keySize, valueSize: valueSize)
return cellM
}
// MARK: - Edit
static func eidtInit(type: String, id: String, key: String?, value: String?, placeholder: String?) -> JSCellModel {
let cellM = JSCellModel.init(type: type, id: id, key: key, value: value, placeholder: placeholder)
return cellM
}
static func eidtInit(type: String, id: String, key: String?, value: String?, placeholder: String?, keySize: CGFloat?, valueSize: CGFloat?) -> JSCellModel {
let cellM = JSCellModel.init(type: type, id: id, key: key, value: value, placeholder: placeholder, keySize: keySize, valueSize: valueSize)
return cellM
}
// MARK: - Switch
static func switchInit(type: String, id: String, key: String?, switched: Bool?) -> JSCellModel {
let cellM = JSCellModel.init(type: type, id: id, key: key, switched: switched)
return cellM
}
static func switchInit(type: String, id: String, key: String?, switched: Bool?, keySize: CGFloat?) -> JSCellModel {
let cellM = JSCellModel.init(type: type, id: id, key: key, switched: switched, keySize: keySize)
return cellM
}
}
| mit | 7508442439c2b54ad1471aac5802a91b | 41.409836 | 171 | 0.649014 | 3.716954 | false | false | false | false |
mottx/XCGLogger | Sources/XCGLogger/Destinations/FileDestination.swift | 1 | 8860 | //
// FileDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2014-06-06.
// Copyright © 2014 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Foundation
import Dispatch
// MARK: - FileDestination
/// A standard destination that outputs log details to a file
open class FileDestination: BaseQueuedDestination {
// MARK: - Properties
/// Logger that owns the destination object
open override var owner: XCGLogger? {
didSet {
if owner != nil {
openFile()
}
else {
closeFile()
}
}
}
/// FileURL of the file to log to
open var writeToFileURL: URL? = nil {
didSet {
openFile()
}
}
/// File handle for the log file
internal var logFileHandle: FileHandle? = nil
/// Option: whether or not to append to the log file if it already exists
internal var shouldAppend: Bool
/// Option: if appending to the log file, the string to output at the start to mark where the append took place
internal var appendMarker: String?
/// Option: Attributes to use when creating a new file
internal var fileAttributes: [FileAttributeKey: Any]? = nil
// MARK: - Life Cycle
public init(owner: XCGLogger? = nil, writeToFile: Any, identifier: String = "", shouldAppend: Bool = false, appendMarker: String? = "-- ** ** ** --", attributes: [String: Any]? = nil) {
self.shouldAppend = shouldAppend
self.appendMarker = appendMarker
if let attrKeys = attributes?.keys {
fileAttributes = [FileAttributeKey: Any]()
for key in attrKeys {
if let val = attributes![key]{
let newKey = FileAttributeKey(key)
fileAttributes?.updateValue(val, forKey: newKey)
}
}
}
if writeToFile is NSString {
writeToFileURL = URL(fileURLWithPath: writeToFile as! String)
}
else if let writeToFile = writeToFile as? URL, writeToFile.isFileURL {
writeToFileURL = writeToFile
}
else {
writeToFileURL = nil
}
super.init(owner: owner, identifier: identifier)
if owner != nil {
openFile()
}
}
deinit {
// close file stream if open
closeFile()
}
// MARK: - File Handling Methods
/// Open the log file for writing.
///
/// - Parameters: None
///
/// - Returns: Nothing
///
private func openFile() {
guard let owner = owner else { return }
if logFileHandle != nil {
closeFile()
}
guard let writeToFileURL = writeToFileURL else { return }
let fileManager: FileManager = FileManager.default
let fileExists: Bool = fileManager.fileExists(atPath: writeToFileURL.path)
if !shouldAppend || !fileExists {
fileManager.createFile(atPath: writeToFileURL.path, contents: nil, attributes: self.fileAttributes)
}
do {
logFileHandle = try FileHandle(forWritingTo: writeToFileURL)
if fileExists && shouldAppend {
logFileHandle?.seekToEndOfFile()
if let appendMarker = appendMarker,
let encodedData = "\(appendMarker)\n".data(using: String.Encoding.utf8) {
_try({
self.logFileHandle?.write(encodedData)
},
catch: { (exception: NSException) in
print("Objective-C Exception occurred: \(exception)")
})
}
}
}
catch let error as NSError {
owner._logln("Attempt to open log file for \(fileExists && shouldAppend ? "appending" : "writing") failed: \(error.localizedDescription)", level: .error, source: self)
logFileHandle = nil
return
}
owner.logAppDetails(selectedDestination: self)
let logDetails = LogDetails(level: .info, date: Date(), message: "XCGLogger " + (fileExists && shouldAppend ? "appending" : "writing") + " log to: " + writeToFileURL.absoluteString, functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo)
owner._logln(logDetails.message, level: logDetails.level, source: self)
if owner.destination(withIdentifier: identifier) == nil {
processInternal(logDetails: logDetails)
}
}
/// Close the log file.
///
/// - Parameters: None
///
/// - Returns: Nothing
///
private func closeFile() {
logFileHandle?.synchronizeFile()
logFileHandle?.closeFile()
logFileHandle = nil
}
/// Force any buffered data to be written to the file.
///
/// - Parameters:
/// - closure: An optional closure to execute after the file has been rotated.
///
/// - Returns: Nothing.
///
open func flush(closure: (() -> Void)? = nil) {
if let logQueue = logQueue {
logQueue.async {
self.logFileHandle?.synchronizeFile()
closure?()
}
}
else {
logFileHandle?.synchronizeFile()
closure?()
}
}
/// Rotate the log file, storing the existing log file in the specified location.
///
/// - Parameters:
/// - archiveToFile: FileURL or path (as String) to where the existing log file should be rotated to.
/// - closure: An optional closure to execute after the file has been rotated.
///
/// - Returns:
/// - true: Log file rotated successfully.
/// - false: Error rotating the log file.
///
@discardableResult open func rotateFile(to archiveToFile: Any, closure: ((_ success: Bool) -> Void)? = nil) -> Bool {
var archiveToFileURL: URL? = nil
if archiveToFile is NSString {
archiveToFileURL = URL(fileURLWithPath: archiveToFile as! String)
}
else if let archiveToFile = archiveToFile as? URL, archiveToFile.isFileURL {
archiveToFileURL = archiveToFile
}
else {
closure?(false)
return false
}
if let archiveToFileURL = archiveToFileURL,
let writeToFileURL = writeToFileURL {
let fileManager: FileManager = FileManager.default
guard !fileManager.fileExists(atPath: archiveToFileURL.path) else { closure?(false); return false }
closeFile()
haveLoggedAppDetails = false
do {
try fileManager.moveItem(atPath: writeToFileURL.path, toPath: archiveToFileURL.path)
}
catch let error as NSError {
openFile()
owner?._logln("Unable to rotate file \(writeToFileURL.path) to \(archiveToFileURL.path): \(error.localizedDescription)", level: .error, source: self)
closure?(false)
return false
}
do {
if let identifierData: Data = identifier.data(using: .utf8) {
try archiveToFileURL.setExtendedAttribute(data: identifierData, forName: XCGLogger.Constants.extendedAttributeArchivedLogIdentifierKey)
}
if let timestampData: Data = "\(Date().timeIntervalSince1970)".data(using: .utf8) {
try archiveToFileURL.setExtendedAttribute(data: timestampData, forName: XCGLogger.Constants.extendedAttributeArchivedLogTimestampKey)
}
}
catch let error as NSError {
owner?._logln("Unable to set extended file attributes on file \(archiveToFileURL.path): \(error.localizedDescription)", level: .error, source: self)
}
owner?._logln("Rotated file \(writeToFileURL.path) to \(archiveToFileURL.path)", level: .info, source: self)
openFile()
closure?(true)
return true
}
closure?(false)
return false
}
// MARK: - Overridden Methods
/// Write the log to the log file.
///
/// - Parameters:
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open override func write(message: String) {
if let encodedData = "\(message)\n".data(using: String.Encoding.utf8) {
_try({
self.logFileHandle?.write(encodedData)
},
catch: { (exception: NSException) in
print("Objective-C Exception occurred: \(exception)")
})
}
}
}
| mit | a0bc8d3bad628741b54c6dc03e234f7d | 33.877953 | 284 | 0.57388 | 5.192849 | false | false | false | false |
khoren93/SwiftHub | SwiftHub/Application/AppDelegate.swift | 1 | 3746 | //
// AppDelegate.swift
// SwiftHub
//
// Created by Khoren Markosyan on 1/4/17.
// Copyright © 2017 Khoren Markosyan. All rights reserved.
//
import UIKit
import Toast_Swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
static var shared: AppDelegate? {
return UIApplication.shared.delegate as? AppDelegate
}
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let libsManager = LibsManager.shared
libsManager.setupLibs(with: window)
if Configs.Network.useStaging == true {
// Logout
User.removeCurrentUser()
AuthManager.removeToken()
// Use Green Dark theme
var theme = ThemeType.currentTheme()
if theme.isDark != true {
theme = theme.toggled()
}
theme = theme.withColor(color: .green)
themeService.switch(theme)
// Disable banners
libsManager.bannersEnabled.accept(false)
} else {
connectedToInternet().skip(1).subscribe(onNext: { [weak self] (connected) in
var style = ToastManager.shared.style
style.backgroundColor = connected ? UIColor.Material.green: UIColor.Material.red
let message = connected ? R.string.localizable.toastConnectionBackMessage.key.localized(): R.string.localizable.toastConnectionLostMessage.key.localized()
let image = connected ? R.image.icon_toast_success(): R.image.icon_toast_warning()
if let view = self?.window?.rootViewController?.view {
view.makeToast(message, position: .bottom, image: image, style: style)
}
}).disposed(by: rx.disposeBag)
}
// Show initial screen
Application.shared.presentInitialScreen(in: window!)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 164138ce4dcbe3fbffb15bbc4e475fb8 | 45.234568 | 285 | 0.68972 | 5.319602 | false | false | false | false |
spr/littleswiftsnippets | June-2014/SwappingValues.playground/section-1.swift | 1 | 226 | // Swapping in Swift
// Old way
func mySwap<T>(inout x: T, inout y: T) {
var hold = x
x = y
y = hold
}
var one = 1
var two = 2
mySwap(&one, &two)
one
two
// Swap with tuples
(two, one) = (one, two)
one
two
| unlicense | fb2cdafc9b6546cc1f1ccccba772f8a8 | 8.416667 | 40 | 0.553097 | 2.404255 | false | false | false | false |
AlexeyTyurenkov/NBUStats | NBUStatProject/FinstatLib/FinstatLib/Models/Sttring+Time.swift | 1 | 648 | //
// Sttring+Time.swift
// FinStat Ukraine
//
// Created by Aleksey Tyurenkov on 3/2/18.
// Copyright © 2018 Oleksii Tiurenkov. All rights reserved.
//
import Foundation
extension String
{
func UTCToLocal() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
guard let dt = dateFormatter.date(from: self) else { return self }
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
return dateFormatter.string(from: dt)
}
}
| mit | fc0f726f836c342f7a55fcd6ed97e125 | 25.958333 | 74 | 0.647604 | 3.85119 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Generators/Oscillators/PWM Oscillator/AKPWMOscillator.swift | 1 | 6469 | //
// AKPWMOscillator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// Pulse-Width Modulating Oscillator
///
open class AKPWMOscillator: AKNode, AKToggleable, AKComponent {
public typealias AKAudioUnitType = AKPWMOscillatorAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(generator: "pwmo")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var frequencyParameter: AUParameter?
fileprivate var amplitudeParameter: AUParameter?
fileprivate var pulseWidthParameter: AUParameter?
fileprivate var detuningOffsetParameter: AUParameter?
fileprivate var detuningMultiplierParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// In cycles per second, or Hz.
@objc open dynamic var frequency: Double = 440 {
willSet {
if frequency != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
frequencyParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.frequency = Float(newValue)
}
}
}
}
/// Output amplitude
@objc open dynamic var amplitude: Double = 1.0 {
willSet {
if amplitude != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
amplitudeParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.amplitude = Float(newValue)
}
}
}
}
/// Frequency offset in Hz.
@objc open dynamic var detuningOffset: Double = 0 {
willSet {
if detuningOffset != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
detuningOffsetParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.detuningOffset = Float(newValue)
}
}
}
}
/// Frequency detuning multiplier
@objc open dynamic var detuningMultiplier: Double = 1 {
willSet {
if detuningMultiplier != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
detuningMultiplierParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.detuningMultiplier = Float(newValue)
}
}
}
}
/// Duty cycle width (range 0-1).
@objc open dynamic var pulseWidth: Double = 0.5 {
willSet {
if pulseWidth != newValue {
if internalAU?.isSetUp() ?? false {
if let existingToken = token {
pulseWidthParameter?.setValue(Float(newValue), originator: existingToken)
}
} else {
internalAU?.pulseWidth = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize the oscillator with defaults
///
public convenience override init() {
self.init(frequency: 440)
}
/// Initialize this oscillator node
///
/// - Parameters:
/// - frequency: In cycles per second, or Hz.
/// - amplitude: Output amplitude
/// - pulseWidth: Duty cycle width (range 0-1).
/// - detuningOffset: Frequency offset in Hz.
/// - detuningMultiplier: Frequency detuning multiplier
///
@objc public init(
frequency: Double,
amplitude: Double = 1.0,
pulseWidth: Double = 0.5,
detuningOffset: Double = 0,
detuningMultiplier: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
self.pulseWidth = pulseWidth
self.detuningOffset = detuningOffset
self.detuningMultiplier = detuningMultiplier
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
frequencyParameter = tree["frequency"]
amplitudeParameter = tree["amplitude"]
pulseWidthParameter = tree["pulseWidth"]
detuningOffsetParameter = tree["detuningOffset"]
detuningMultiplierParameter = tree["detuningMultiplier"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
internalAU?.pulseWidth = Float(pulseWidth)
internalAU?.detuningOffset = Float(detuningOffset)
internalAU?.detuningMultiplier = Float(detuningMultiplier)
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| mit | 71fc7014b4a5be9cc6d30f4954575957 | 32.863874 | 105 | 0.576685 | 5.769848 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/File Upload Object/HATFileUploadStatus.swift | 1 | 2204 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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 SwiftyJSON
// MARK: Struct
public struct HATFileUploadStatus {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `status` in JSON is `status`
* `size` in JSON is `size`
*/
private enum CodingKeys: String, CodingKey {
case status
case size
}
// MARK: - Variables
/// The status of the uploaded file. Can be either `new` or `completed` when the upload file has been marked as completed
public var status: String = ""
/// The size of the uploaded file. Optional
public var size: Int?
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
status = ""
size = nil
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received
*/
public init(from dict: Dictionary<String, JSON>) {
self.init()
if let tempStatus: String = dict["status"]?.stringValue {
status = tempStatus
}
if let tempSize: Int = dict["size"]?.intValue {
size = tempSize
}
}
// MARK: - JSON Mapper
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
if size != nil {
return [
"status": self.status,
"size": self.size!,
"unixTimeStamp": Int(HATFormatterHelper.formatDateToEpoch(date: Date())!)!
]
}
return [
"status": self.status,
"unixTimeStamp": Int(HATFormatterHelper.formatDateToEpoch(date: Date())!)!
]
}
}
| mpl-2.0 | 2de87ec2ca87cc1b56f76a5cd99025ee | 21.958333 | 125 | 0.564882 | 4.434608 | false | false | false | false |
S2dentik/Taylor | TaylorFramework/Modules/caprices/ProccessingMessage/InformationalOptionsFactory.swift | 4 | 1851 | //
// InformationalOptionsFactory.swift
// Caprices
//
// Created by Alex Culeva on 11/2/15.
// Copyright © 2015 yopeso.dmitriicelpan. All rights reserved.
//
import Cocoa
import Foundation
typealias OutputReporter = [String: String]
typealias CustomizationRule = [String: Int]
struct InformationalOptionsFactory {
var infoOptions: [InformationalOption]
var reporterTypes = [OutputReporter]()
var customizationRules = CustomizationRule()
var verbosityLevel = VerbosityLevel.error
init() {
self.init(infoOptions: [])
}
init(infoOptions: [InformationalOption]) {
self.infoOptions = infoOptions
reporterTypes = getReporters()
customizationRules = getRuleCustomizations()
verbosityLevel = getVerbosityLevel()
}
func filterClassesOfType(_ name: String) -> [InformationalOption] {
return infoOptions.filter { $0.name == name }
}
func getReporters() -> [OutputReporter] {
let reporterOptions = filterClassesOfType(ReporterOption().name).map {
$0 as! ReporterOption
}
return reporterOptions.reduce([]) { $0 + [$1.dictionaryFromArgument()] }
}
func getRuleCustomizations() -> CustomizationRule {
let ruleCustomizationOptions = filterClassesOfType(RuleCustomizationOption().name).map {
$0 as! RuleCustomizationOption
}
return ruleCustomizationOptions.reduce(CustomizationRule()) { $1.setRuleToDictionary($0) }
}
func getVerbosityLevel() -> VerbosityLevel {
let verbosityOptions = filterClassesOfType(VerbosityOption().name).map {
$0 as! VerbosityOption
}
guard verbosityOptions.count == 1 else {
return .error
}
return verbosityOptions[0].verbosityLevelFromOption()
}
}
| mit | 3ba95e46fffa97828fc61fac424c5077 | 29.833333 | 98 | 0.659459 | 4.534314 | false | false | false | false |
glessard/swift-channels | ChannelsTests/SimpleChannel.swift | 1 | 1934 | //
// SimpleChannel.swift
// concurrency
//
// Created by Guillaume Lessard on 2014-12-08.
// Copyright (c) 2014 Guillaume Lessard. All rights reserved.
//
import Darwin
import Dispatch
@testable import Channels
/**
The simplest single-element buffered channel that can
fulfill the contract of ChannelType.
*/
open class SimpleChannel: ChannelType, SelectableChannelType
{
fileprivate var element: Int = 0
fileprivate var head = 0
fileprivate var tail = 0
fileprivate let filled = DispatchSemaphore(value: 0)
fileprivate let empty = DispatchSemaphore(value: 1)
fileprivate var closed = false
deinit
{
if head < tail
{
empty.signal()
}
}
open var isClosed: Bool { return closed }
open var isEmpty: Bool { return tail &- head <= 0 }
open var isFull: Bool { return tail &- head >= 1 }
open func close()
{
if closed { return }
closed = true
empty.signal()
filled.signal()
}
open func put(_ newElement: Int) -> Bool
{
if closed { return false }
_ = empty.wait(timeout: DispatchTime.distantFuture)
if closed
{
empty.signal()
return false
}
element = newElement
tail = tail &+ 1
filled.signal()
return true
}
open func get() -> Int?
{
if closed && tail &- head <= 0 { return nil }
_ = filled.wait(timeout: DispatchTime.distantFuture)
if tail &- head > 0
{
let e = element
head = head &+ 1
empty.signal()
return e
}
else
{
assert(closed, #function)
filled.signal()
return nil
}
}
open func selectGet(_ select: ChannelSemaphore, selection: Selection)
{
}
open func extract(_ selection: Selection) -> Int?
{
return nil
}
open func selectPut(_ select: ChannelSemaphore, selection: Selection)
{
}
open func insert(_ selection: Selection, newElement: Int) -> Bool
{
return false
}
}
| mit | 05b7a747665ca7e5583bb986e224cdf6 | 16.423423 | 71 | 0.624095 | 4.114894 | false | false | false | false |
DouglasHennrich/TextFieldEffects | TextFieldEffects/TextFieldEffects/KaedeTextField.swift | 3 | 4003 | //
// KaedeTextField.swift
// Swish
//
// Created by Raúl Riera on 20/01/2015.
// Copyright (c) 2015 com.raulriera.swishapp. All rights reserved.
//
import UIKit
@IBDesignable public class KaedeTextField: TextFieldEffects {
@IBInspectable public var placeholderColor: UIColor? {
didSet {
updatePlaceholder()
}
}
@IBInspectable public var foregroundColor: UIColor? {
didSet {
updateForegroundColor()
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
drawViewsForRect(bounds)
}
}
private let foregroundView = UIView()
private let placeholderInsets = CGPoint(x: 10, y: 5)
private let textFieldInsets = CGPoint(x: 10, y: 0)
// MARK: - TextFieldsEffectsProtocol
override func drawViewsForRect(rect: CGRect) {
let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height))
foregroundView.frame = frame
foregroundView.userInteractionEnabled = false
placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
updateForegroundColor()
updatePlaceholder()
if text!.isNotEmpty || isFirstResponder() {
animateViewsForTextEntry()
}
addSubview(foregroundView)
addSubview(placeholderLabel)
}
// MARK: -
private func updateForegroundColor() {
foregroundView.backgroundColor = foregroundColor
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.8)
return smallerFont
}
override func animateViewsForTextEntry() {
UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .BeginFromCurrentState, animations: ({
self.placeholderLabel.frame.origin = CGPoint(x: self.frame.size.width * 0.65, y: self.placeholderInsets.y)
}), completion: nil)
UIView.animateWithDuration(0.45, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.5, options: .BeginFromCurrentState, animations: ({
self.foregroundView.frame.origin = CGPoint(x: self.frame.size.width * 0.6, y: 0)
}), completion: nil)
}
override func animateViewsForTextDisplay() {
if text!.isEmpty {
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: .BeginFromCurrentState, animations: ({
self.placeholderLabel.frame.origin = self.placeholderInsets
}), completion: nil)
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 2.0, options: .BeginFromCurrentState, animations: ({
self.foregroundView.frame.origin = CGPointZero
}), completion: nil)
}
}
// MARK: - Overrides
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
let frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width * 0.6, height: bounds.size.height))
return CGRectInset(frame, textFieldInsets.x, textFieldInsets.y)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
let frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width * 0.6, height: bounds.size.height))
return CGRectInset(frame, textFieldInsets.x, textFieldInsets.y)
}
} | mit | 0744a39bd98e7289114a762ade1d8024 | 34.114035 | 160 | 0.638681 | 5.008761 | false | false | false | false |
txstate-etc/mobile-tracs-ios | mobile-tracs-ios/Data/Settings.swift | 1 | 2059 | //
// Settings.swift
// mobile-tracs-ios
//
// Created by Nick Wing on 3/26/17.
// Copyright © 2017 Texas State University. All rights reserved.
//
import Foundation
class Settings : JSONRepresentable {
var global_disable = false
var disabled_filters:[SettingsEntry] = []
init() {
}
init(dict: [String:Any]?) {
if let dict = dict {
global_disable = dict["global_disable"] as? Bool ?? false
for entrydict in dict["blacklist"] as? [[String:[String:String]]] ?? [] {
let entry = SettingsEntry(dict: entrydict)
if entry.valid() { disabled_filters.append(entry) }
}
}
}
func entryIsDisabled(_ targetentry: SettingsEntry)->Bool {
return disabled_filters.contains(targetentry)
}
func disableEntry(_ targetentry: SettingsEntry) {
if !entryIsDisabled(targetentry) {
disabled_filters.append(targetentry)
}
}
func enableEntry(_ targetentry: SettingsEntry) {
disabled_filters = disabled_filters.filter { (entry) -> Bool in
return entry != targetentry
}
}
func disableSite(site:Site) {
disableEntry(SettingsEntry(disabled_site: site))
}
func enableSite(site:Site) {
enableEntry(SettingsEntry(disabled_site: site))
}
func siteIsDisabled(site:Site)->Bool {
return entryIsDisabled(SettingsEntry(disabled_site:site))
}
func disableObjectType(type:String) {
if !objectTypeIsDisabled(type: type) {
disabled_filters.append(SettingsEntry(disabled_type: type))
}
}
func enableObjectType(type:String) {
enableEntry(SettingsEntry(disabled_type: type))
}
func objectTypeIsDisabled(type:String)->Bool {
return entryIsDisabled(SettingsEntry(disabled_type: type))
}
func toJSONObject() -> Any {
return [
"global_disable": global_disable,
"blacklist": disabled_filters.toJSONObject()
]
}
}
| mit | 7188b9b47decb295ceda9c24a9b341d1 | 27.985915 | 85 | 0.607386 | 4.278586 | false | false | false | false |
apptut/PhotoPicker | PhotoPicker/ViewController.swift | 1 | 11320 | //
// ViewController.swift
// PhotoPicker
//
// Created by liangqi on 16/3/4.
// Copyright © 2016年 dailyios. All rights reserved.
//
import UIKit
import Photos
import MobileCoreServices
class ViewController: UIViewController,PhotoPickerControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var selectModel = [PhotoImageModel]()
var containerView = UIView()
var triggerRefresh = false
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.containerView)
self.checkNeedAddButton()
self.renderView()
}
private func checkNeedAddButton(){
if self.selectModel.count < PhotoPickerController.imageMaxSelectedNum && !hasButton() {
selectModel.append(PhotoImageModel(type: ModelType.Button, data: nil))
}
}
private func hasButton() -> Bool{
for item in self.selectModel {
if item.type == ModelType.Button {
return true
}
}
return false
}
/**
* 删除已选择图片数据 Model
*/
func removeElement(element: PhotoImageModel?){
if let current = element {
self.selectModel = self.selectModel.filter({$0 != current})
self.triggerRefresh = true // 删除数据事出发重绘界面逻辑
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.statusBarStyle = .default
self.navigationController?.navigationBar.barStyle = .default
if self.triggerRefresh { // 检测是否需要重绘界面
self.triggerRefresh = false
self.updateView()
}
}
private func updateView(){
self.clearAll()
self.checkNeedAddButton()
self.renderView()
}
private func renderView(){
if selectModel.count <= 0 {return;}
let totalWidth = UIScreen.main.bounds.width
let space:CGFloat = 10
let lineImageTotal = 4
let line = self.selectModel.count / lineImageTotal
let lastItems = self.selectModel.count % lineImageTotal
let lessItemWidth = (totalWidth - (CGFloat(lineImageTotal) + 1) * space)
let itemWidth = lessItemWidth / CGFloat(lineImageTotal)
for i in 0 ..< line {
let itemY = CGFloat(i+1) * space + CGFloat(i) * itemWidth
for j in 0 ..< lineImageTotal {
let itemX = CGFloat(j+1) * space + CGFloat(j) * itemWidth
let index = i * lineImageTotal + j
self.renderItemView(itemX: itemX, itemY: itemY, itemWidth: itemWidth, index: index)
}
}
// last line
for i in 0..<lastItems{
let itemX = CGFloat(i+1) * space + CGFloat(i) * itemWidth
let itemY = CGFloat(line+1) * space + CGFloat(line) * itemWidth
let index = line * lineImageTotal + i
self.renderItemView(itemX: itemX, itemY: itemY, itemWidth: itemWidth, index: index)
}
let totalLine = ceil(Double(self.selectModel.count) / Double(lineImageTotal))
let containerHeight = CGFloat(totalLine) * itemWidth + (CGFloat(totalLine) + 1) * space
self.containerView.frame = CGRect(x:0, y:0, width:totalWidth, height:containerHeight)
}
private func renderItemView(itemX:CGFloat,itemY:CGFloat,itemWidth:CGFloat,index:Int){
let itemModel = self.selectModel[index]
let button = UIButton(frame: CGRect(x:itemX, y:itemY, width:itemWidth, height: itemWidth))
button.backgroundColor = UIColor.red
button.tag = index
if itemModel.type == ModelType.Button {
button.backgroundColor = UIColor.clear
button.addTarget(self, action: #selector(ViewController.eventAddImage), for: .touchUpInside)
button.contentMode = .scaleAspectFill
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.init(red: 200/255, green: 200/255, blue: 200/255, alpha: 1).cgColor
button.setImage(UIImage(named: "image_select"), for: UIControlState.normal)
} else {
button.addTarget(self, action: #selector(ViewController.eventPreview), for: .touchUpInside)
if let asset = itemModel.data {
let pixSize = UIScreen.main.scale * itemWidth
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: pixSize, height: pixSize), contentMode: PHImageContentMode.aspectFill, options: nil, resultHandler: { (image, info) -> Void in
if image != nil {
button.setImage(image, for: UIControlState.normal)
button.contentMode = .scaleAspectFill
button.clipsToBounds = true
}
})
}
}
self.containerView.addSubview(button)
}
private func clearAll(){
for subview in self.containerView.subviews {
if let view = subview as? UIButton {
view.removeFromSuperview()
}
}
}
// MARK: - 按钮事件
func eventPreview(button:UIButton){
let preview = SinglePhotoPreviewViewController()
let data = self.getModelExceptButton()
preview.selectImages = data
preview.sourceDelegate = self
preview.currentPage = button.tag
self.show(preview, sender: nil)
}
// 页面底部 stylesheet
func eventAddImage() {
let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
// change the style sheet text color
alert.view.tintColor = UIColor.black
let actionCancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
let actionCamera = UIAlertAction.init(title: "拍照", style: .default) { (UIAlertAction) -> Void in
self.selectByCamera()
}
let actionPhoto = UIAlertAction.init(title: "从手机照片中选择", style: .default) { (UIAlertAction) -> Void in
self.selectFromPhoto()
}
alert.addAction(actionCancel)
alert.addAction(actionCamera)
alert.addAction(actionPhoto)
self.present(alert, animated: true, completion: nil)
}
// 拍照获取
private func selectByCamera(){
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .camera // 调用摄像头
imagePicker.cameraDevice = .rear // 后置摄像头拍照
imagePicker.cameraCaptureMode = .photo // 拍照
imagePicker.allowsEditing = true
imagePicker.delegate = self
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.modalPresentationStyle = .popover
self.show(imagePicker, sender: nil)
}
// MARK: - 拍照 delegate相关方法
// 退出拍照
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
// 完成拍照
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
let mediaType = info[UIImagePickerControllerMediaType] as! String;
if mediaType == kUTTypeImage as String { // 图片类型
var image: UIImage? = nil
var localId: String? = ""
if picker.isEditing { // 拍照图片运行编辑,则优先尝试从编辑后的类型中获取图片
image = info[UIImagePickerControllerEditedImage] as? UIImage
}else{
image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
// 存入相册
if image != nil {
PHPhotoLibrary.shared().performChanges({
let result = PHAssetChangeRequest.creationRequestForAsset(from: image!)
let assetPlaceholder = result.placeholderForCreatedAsset
localId = assetPlaceholder?.localIdentifier
}, completionHandler: { (success, error) in
if success && localId != nil {
let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [localId!], options: nil)
let asset = assetResult[0]
DispatchQueue.main.async {
self.renderSelectImages(images: [asset])
}
}
})
}
}
}
/**
* 从相册中选择图片
*/
private func selectFromPhoto(){
PHPhotoLibrary.requestAuthorization {[unowned self] (status) -> Void in
DispatchQueue.main.async {
switch status {
case .authorized:
self.showLocalPhotoGallery()
break
default:
self.showNoPermissionDailog()
break
}
}
}
}
/**
* 用户相册未授权,Dialog提示
*/
private func showNoPermissionDailog(){
let alert = UIAlertController.init(title: nil, message: "没有打开相册的权限", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "确定", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
/**
* 打开本地相册列表
*/
private func showLocalPhotoGallery(){
let picker = PhotoPickerController(type: PageType.RecentAlbum)
picker.imageSelectDelegate = self
picker.modalPresentationStyle = .popover
PhotoPickerController.imageMaxSelectedNum = 4 // 允许选择的最大图片张数
let realModel = self.getModelExceptButton() // 获取已经选择过的图片
PhotoPickerController.alreadySelectedImageNum = realModel.count
debugPrint(realModel.count)
self.show(picker, sender: nil)
}
func onImageSelectFinished(images: [PHAsset]) {
self.renderSelectImages(images: images)
}
private func renderSelectImages(images: [PHAsset]){
for item in images {
self.selectModel.insert(PhotoImageModel(type: ModelType.Image, data: item), at: 0)
}
let total = self.selectModel.count;
if total > PhotoPickerController.imageMaxSelectedNum {
for i in 0 ..< total {
let item = self.selectModel[i]
if item.type == .Button {
self.selectModel.remove(at: i)
}
}
}
self.renderView()
}
private func getModelExceptButton()->[PhotoImageModel]{
var newModels = [PhotoImageModel]()
for i in 0..<self.selectModel.count {
let item = self.selectModel[i]
if item.type != .Button {
newModels.append(item)
}
}
return newModels
}
}
| apache-2.0 | 81d42e8daf29089bf20b2b89d580597e | 35.069079 | 218 | 0.587232 | 4.914836 | false | false | false | false |
Mioke/PlanB | PlanB/PlanB/Base/Kits/ModuleLoader/ModuleLoader.swift | 1 | 2218 | //
// ModuleLoader.swift
// swiftArchitecture
//
// Created by jiangkelan on 5/12/16.
// Copyright © 2016 KleinMioke. All rights reserved.
//
import UIKit
class ModuleLoader: NSObject {
enum OperationLevel: Int {
case High; case Low; case Default
}
private static var defaultLoader: ModuleLoader? = ModuleLoader()
class func loader() -> ModuleLoader {
if ModuleLoader.defaultLoader == nil {
ModuleLoader.defaultLoader = ModuleLoader()
}
return ModuleLoader.defaultLoader!
}
let group: dispatch_group_t = dispatch_group_create()
var maxConcurrentNum: Int = 3
var currentNum: Int = 0
private var operations: [OperationLevel: [() -> ()]]
override init() {
operations = [.High: [], .Default: [], .Low: []]
super.init()
dispatch_group_notify(group, dispatch_get_main_queue()) {
self.currentNum = 0
self.run()
}
}
func addOperation(level: ModuleLoader.OperationLevel = .Default, operation: () -> ()) -> Void {
operations[level]! += [operation]
}
func run() -> Void {
while currentNum < maxConcurrentNum {
var op: (() -> ())? = nil
var priority: dispatch_queue_priority_t = DISPATCH_QUEUE_PRIORITY_DEFAULT
if operations[.High]!.count > 0 {
op = operations[.High]!.removeFirst()
priority = DISPATCH_QUEUE_PRIORITY_HIGH
} else if operations[.Default]!.count > 0 {
op = operations[.Default]!.removeFirst()
priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
} else if operations[.Low]!.count > 0 {
op = operations[.Low]!.removeFirst()
priority = DISPATCH_QUEUE_PRIORITY_BACKGROUND
}
guard op != nil else {
ModuleLoader.defaultLoader = nil
return
}
self.currentNum += 1
dispatch_group_async(group, dispatch_get_global_queue(priority, 0), {
op?()
})
}
}
}
| gpl-3.0 | 31add4da9af70c4023134e51b203d76d | 27.792208 | 99 | 0.529995 | 4.767742 | false | false | false | false |
Calvin-Huang/CHCarouselView | CHCarouselView/Views/CarouselView.swift | 1 | 9600 | //
// CarouselView.swift
// CHCarouselView
//
// Created by Calvin on 8/5/16.
// Copyright © 2016 CapsLock. All rights reserved.
//
import UIKit
open class CarouselView: UIScrollView {
@IBOutlet weak var pageControl: UIPageControl?
@IBOutlet open var views: [UIView] = [] {
willSet {
views.forEach { (view) in
view.removeFromSuperview()
}
pause()
}
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable open var isInfinite: Bool = false
@IBInspectable open var interval: Double = 0
@IBInspectable open var animationDuration: Double = 0.3
open var currentPage: Int {
set {
switch pageControl {
case .none:
self.currentPage = newValue
case .some(let pageControl):
pageControl.currentPage = newValue
}
}
get {
switch pageControl {
case .none:
return self.currentPage
case .some(let pageControl):
return pageControl.currentPage
}
}
}
open var selected: ((_ currentPage: Int) -> Void)?
open var isPaused: Bool {
return timer == nil
}
fileprivate var canInfinite: Bool {
return isInfinite && views.count > 1
}
fileprivate enum ScrollDirection {
case none
case top
case right
case down
case left
init(fromPoint: CGPoint, toPoint: CGPoint) {
if fromPoint.x - toPoint.x < 0 && fromPoint.y == toPoint.y {
self = .left
} else if fromPoint.x - toPoint.x > 0 && fromPoint.y == toPoint.y {
self = .right
} else if fromPoint.x == toPoint.x && fromPoint.y - toPoint.y < 0 {
self = .down
} else if fromPoint.x == toPoint.x && fromPoint.y - toPoint.y > 0 {
self = .top
} else {
self = .none
}
}
}
fileprivate var timer: Timer?
// MARK: Initializers
override public init(frame: CGRect) {
super.init(frame: frame)
self.configure()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.configure()
}
deinit {
self.removeObserver(self, forKeyPath: "contentOffset")
timer?.invalidate()
timer = nil
}
// MARK: Life Cycle
open override func removeFromSuperview() {
super.removeFromSuperview()
timer?.invalidate()
timer = nil
}
// MARK: UIView Delegate
open override func draw(_ rect: CGRect) {
resetInfiniteContentShift()
views
.forEach {
self.addSubview($0)
}
pageControl?.numberOfPages = views.count
let viewsCountWithInfiniteMock = (canInfinite ? 2 : 0) + views.count
self.contentSize = CGSize(width: CGFloat(viewsCountWithInfiniteMock) * self.bounds.width, height: self.bounds.height)
self.contentOffset = canInfinite ? CGPoint(x: self.bounds.width, y: 0) : CGPoint.zero
if canInfinite && interval > 0 {
start()
}
}
// MARK: - Override Methods
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
selected?(currentPage)
}
// MARK: - KVO Delegate
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// Check condition with tracking for only prepare view when still scrolling.
if keyPath == "contentOffset" && canInfinite {
guard let change = change, let oldOffset = (change[NSKeyValueChangeKey.oldKey] as AnyObject?)?.cgPointValue else {
return
}
if self.isTracking {
let newOffset = self.contentOffset
prepareViewForInfiniteInlusion(ScrollDirection(fromPoint: oldOffset, toPoint: newOffset))
pause()
} else {
start()
}
}
}
// MARK: - Selectors
internal func autoScrollToNextPage(_: AnyObject) {
UIView.animate(withDuration: animationDuration, animations: {
var nextPage = self.currentPage + 1
if self.canInfinite {
nextPage = nextPage + 1
} else if nextPage >= self.views.count {
nextPage = 0
}
self.contentOffset = CGPoint(x: CGFloat(nextPage) * self.bounds.width, y: 0)
})
}
// MARK: - Public Methods
open func pause() {
guard let _ = timer else { return }
timer?.invalidate()
timer = nil
}
open func start() {
if timer != nil || interval <= 0 { return }
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(autoScrollToNextPage(_:)), userInfo: nil, repeats: true)
}
// MARK: - Private Methods
fileprivate func configure() {
self.delegate = self
self.isPagingEnabled = true
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
self.scrollsToTop = false
self.addObserver(self, forKeyPath: "contentOffset", options: .old, context: nil)
}
fileprivate func prepareViewForInfiniteInlusion(_ direction: ScrollDirection) {
let viewsCount = CGFloat(views.count)
switch direction {
case .left:
if self.contentOffset.x <= self.bounds.size.width {
guard let lastView = views.last else {
return
}
lastView.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
} else if self.contentOffset.x >= viewsCount * self.bounds.size.width {
guard let firstView = views.first else {
return
}
firstView.frame = CGRect(x: (viewsCount + 1) * self.bounds.size.width, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
} else {
resetInfiniteContentShift()
}
case .right:
if self.contentOffset.x >= viewsCount * self.bounds.size.width {
guard let firstView = views.first else {
return
}
firstView.frame = CGRect(x: (viewsCount + 1) * self.bounds.size.width, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
} else if self.contentOffset.x <= self.bounds.size.width {
guard let lastView = views.last else {
return
}
lastView.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
} else {
resetInfiniteContentShift()
}
case .top:
break
case .down:
break
default:
break
}
}
fileprivate func resetInfiniteContentShift() {
views
.enumerated()
.forEach { (index: Int, view: UIView) in
let indexShiftted = isInfinite ? index + 1 : index
let viewOffset = CGPoint(x: CGFloat(indexShiftted) * self.bounds.width, y: 0)
view.frame = CGRect(origin: viewOffset, size: self.bounds.size)
}
}
fileprivate func shiftToRealViewPosition() {
let viewsCount = CGFloat(views.count)
if self.contentOffset.x <= 0 {
self.contentOffset = CGPoint(x: viewsCount * self.bounds.size.width, y: 0)
resetInfiniteContentShift()
} else if self.contentOffset.x >= (viewsCount + 1) * self.bounds.size.width {
self.contentOffset = CGPoint(x: self.bounds.size.width, y: 0)
resetInfiniteContentShift()
}
}
}
// MARK: - ScrollViewDelegate
extension CarouselView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX: Int = Int(scrollView.contentOffset.x)
let width: Int = Int(self.bounds.width)
let remainder: Int = offsetX % width
var page: Int = offsetX / width + ((remainder > width / 2) ? 1 : 0)
if canInfinite {
if page == 0 {
page = views.count - 1
} else if page == views.count + 1 {
page = 0
} else {
page = page - 1
}
shiftToRealViewPosition()
}
currentPage = page
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if canInfinite {
resetInfiniteContentShift()
}
}
}
| mit | ab93c0e00166e0d739ad0a4fb7fd6a3c | 29.667732 | 156 | 0.519012 | 5.119467 | false | false | false | false |
Bluthwort/Bluthwort | Sources/Classes/Core/Constants.swift | 1 | 1765 | //
// Constants.swift
//
// Copyright (c) 2018 Bluthwort
//
// 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.
//
public let kScreenWidth = UIScreen.main.bounds.width
public let kScreenHeight = UIScreen.main.bounds.height
public let kMargin8: CGFloat = 8.0
public let kMargin12: CGFloat = 12.0
public let kMargin20: CGFloat = 20.0
public let kSecondsOfAMinute = 60
public let kSecondsOfAnHour = 60 * kSecondsOfAMinute
public let kSecondsOfADay = 24 * kSecondsOfAnHour
public let kSecondsOfAWeek = 7 * kSecondsOfADay
public let kSecondsOfHalfAMonth = 15 * kSecondsOfADay
public let kSecondsOfAMonth = 30 * kSecondsOfADay
public let kSecondsOfHalfAYear = 182 * kSecondsOfADay
public let kSecondsOfAYear = 365 * kSecondsOfADay
| mit | fc0b16145de0fe83ae395f8a7aab4525 | 44.25641 | 81 | 0.769972 | 4.423559 | false | false | false | false |
matthewpurcell/firefox-ios | Providers/NSUserDefaultsPrefs.swift | 9 | 4927 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
public class NSUserDefaultsPrefs: Prefs {
private let prefixWithDot: String
private let userDefaults: NSUserDefaults
public func getBranchPrefix() -> String {
return self.prefixWithDot
}
init(prefix: String, userDefaults: NSUserDefaults) {
self.prefixWithDot = prefix + (prefix.endsWith(".") ? "" : ".")
self.userDefaults = userDefaults
}
init(prefix: String) {
self.prefixWithDot = prefix + (prefix.endsWith(".") ? "" : ".")
self.userDefaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
}
public func branch(branch: String) -> Prefs {
let prefix = self.prefixWithDot + branch + "."
return NSUserDefaultsPrefs(prefix: prefix, userDefaults: self.userDefaults)
}
// Preferences are qualified by the profile's local name.
// Connecting a profile to a Firefox Account, or changing to another, won't alter this.
private func qualifyKey(key: String) -> String {
return self.prefixWithDot + key
}
public func setInt(value: Int32, forKey defaultName: String) {
// Why aren't you using userDefaults.setInteger?
// Because userDefaults.getInteger returns a non-optional; it's impossible
// to tell whether there's a value set, and you thus can't distinguish
// between "not present" and zero.
// Yeah, NSUserDefaults is meant to be used for storing "defaults", not data.
setObject(NSNumber(int: value), forKey: defaultName)
}
public func setTimestamp(value: Timestamp, forKey defaultName: String) {
setLong(value, forKey: defaultName)
}
public func setLong(value: UInt64, forKey defaultName: String) {
setObject(NSNumber(unsignedLongLong: value), forKey: defaultName)
}
public func setLong(value: Int64, forKey defaultName: String) {
setObject(NSNumber(longLong: value), forKey: defaultName)
}
public func setString(value: String, forKey defaultName: String) {
setObject(value, forKey: defaultName)
}
public func setObject(value: AnyObject?, forKey defaultName: String) {
userDefaults.setObject(value, forKey: qualifyKey(defaultName))
}
public func stringForKey(defaultName: String) -> String? {
// stringForKey converts numbers to strings, which is almost always a bug.
return userDefaults.objectForKey(qualifyKey(defaultName)) as? String
}
public func setBool(value: Bool, forKey defaultName: String) {
setObject(NSNumber(bool: value), forKey: defaultName)
}
public func boolForKey(defaultName: String) -> Bool? {
// boolForKey just returns false if the key doesn't exist. We need to
// distinguish between false and non-existent keys, so use objectForKey
// and cast the result instead.
let number = userDefaults.objectForKey(qualifyKey(defaultName)) as? NSNumber
return number?.boolValue
}
private func nsNumberForKey(defaultName: String) -> NSNumber? {
return userDefaults.objectForKey(qualifyKey(defaultName)) as? NSNumber
}
public func unsignedLongForKey(defaultName: String) -> UInt64? {
return nsNumberForKey(defaultName)?.unsignedLongLongValue
}
public func timestampForKey(defaultName: String) -> Timestamp? {
return unsignedLongForKey(defaultName)
}
public func longForKey(defaultName: String) -> Int64? {
return nsNumberForKey(defaultName)?.longLongValue
}
public func intForKey(defaultName: String) -> Int32? {
return nsNumberForKey(defaultName)?.intValue
}
public func stringArrayForKey(defaultName: String) -> [String]? {
let objects = userDefaults.stringArrayForKey(qualifyKey(defaultName))
if let strings = objects {
return strings
}
return nil
}
public func arrayForKey(defaultName: String) -> [AnyObject]? {
return userDefaults.arrayForKey(qualifyKey(defaultName))
}
public func dictionaryForKey(defaultName: String) -> [String : AnyObject]? {
return userDefaults.dictionaryForKey(qualifyKey(defaultName))
}
public func removeObjectForKey(defaultName: String) {
userDefaults.removeObjectForKey(qualifyKey(defaultName))
}
public func clearAll() {
// TODO: userDefaults.removePersistentDomainForName() has no effect for app group suites.
// iOS Bug? Iterate and remove each manually for now.
for key in userDefaults.dictionaryRepresentation().keys {
if key.startsWith(prefixWithDot) {
userDefaults.removeObjectForKey(key)
}
}
}
}
| mpl-2.0 | 4771f8fee4ae47590ead42c5891276d7 | 36.325758 | 97 | 0.679724 | 4.971746 | false | false | false | false |
24/ios-o2o-c | gxc/Order/OrderDetailLeftViewController.swift | 1 | 12447 | //
// OrderDetailLeftViewController.swift
// gxc
//
// Created by gx on 14/12/8.
// Copyright (c) 2014年 zheng. All rights reserved.
//
import Foundation
class OrderDetailLeftViewController: UIViewController {
var leftView = UIView()
var lleftView = UIView()
var shopOrderDetail = GXViewState.OrderDetail
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor(fromHexString: "#008FD7")
var navigationBar = self.navigationController?.navigationBar
/*navigation 不遮住View*/
self.automaticallyAdjustsScrollViewInsets = false
self.edgesForExtendedLayout = UIRectEdge()
let superview: UIView = self.view
leftView = UIView()
self.view.addSubview(leftView)
leftView.snp_makeConstraints { make in
make.top.equalTo(superview.snp_top)
make.left.equalTo(10)
make.width.equalTo(superview)
make.height.equalTo(400)
}
leftView.addSubview(lleftView)
lleftView.layer.borderWidth = 1.0
lleftView.layer.borderColor = UIColor(fromHexString: "#008FD7").CGColor
lleftView.layer.cornerRadius = 6
lleftView.layer.masksToBounds = true
lleftView.snp_makeConstraints { make in
make.top.equalTo(self.leftView.snp_top)
make.left.equalTo(self.leftView.snp_left)
make.right.equalTo(self.leftView.snp_right).offset(-22)
make.height.equalTo(170)
}
initGUI()
}
func initGUI()
{
var orderDetail = shopOrderDetail.shopDetail!
let superview: UIView = self.view
var lleftOrderIdLable = UILabel()
var lleftOrderMoneyLabel = UILabel()
var lleftOrderUserAddressLabel = UILabel()
var lleftOrderUserPhoneLabel = UILabel()
var lleftOrderShopName = UILabel()
var lleftOrderShopPhone = UITextView()
lleftView.addSubview(lleftOrderIdLable)
if(orderDetail.IsPay! == false)
{
var lleftOderStatusLabel = UILabel()
lleftView.addSubview(lleftOderStatusLabel)
lleftOderStatusLabel.snp_makeConstraints { make in
make.top.equalTo(self.lleftView.snp_top).offset(10)
make.right.equalTo(self.lleftView.snp_right)
make.width.equalTo(80)
make.height.equalTo(25)
}
lleftOderStatusLabel.text = "未付款 "
lleftOderStatusLabel.textColor = UIColor.redColor()
lleftOderStatusLabel.font = UIFont(name:"Heiti SC",size:13)
}
lleftView.addSubview(lleftOrderMoneyLabel)
lleftView.addSubview(lleftOrderUserAddressLabel)
lleftView.addSubview(lleftOrderUserPhoneLabel)
lleftView.addSubview(lleftOrderShopName)
lleftView.addSubview(lleftOrderShopPhone)
lleftOrderIdLable.snp_makeConstraints { make in
make.top.equalTo(self.lleftView.snp_top).offset(10)
make.left.equalTo(self.lleftView.snp_left).offset(10)
make.width.equalTo(200)
make.height.equalTo(25)
}
lleftOrderMoneyLabel.snp_makeConstraints { make in
make.top.equalTo(lleftOrderIdLable.snp_bottom)
make.left.equalTo(self.lleftView.snp_left).offset(10)
make.width.equalTo(self.lleftView)
make.height.equalTo(25)
}
lleftOrderUserAddressLabel.snp_makeConstraints { make in
make.top.equalTo(lleftOrderMoneyLabel.snp_bottom)
make.left.equalTo(self.lleftView.snp_left).offset(10)
make.width.equalTo(self.lleftView)
make.height.equalTo(25)
}
lleftOrderUserPhoneLabel.snp_makeConstraints { make in
make.top.equalTo(lleftOrderUserAddressLabel.snp_bottom)
make.left.equalTo(self.lleftView.snp_left).offset(10)
make.width.equalTo(self.lleftView)
make.height.equalTo(25)
}
lleftOrderShopName.snp_makeConstraints { make in
make.top.equalTo(lleftOrderUserPhoneLabel.snp_bottom)
make.left.equalTo(self.lleftView.snp_left).offset(10)
make.width.equalTo(self.lleftView)
make.height.equalTo(25)
}
lleftOrderShopPhone.snp_makeConstraints { make in
make.top.equalTo(lleftOrderShopName.snp_bottom)
make.left.equalTo(self.lleftView.snp_left).offset(6)
make.width.equalTo(self.lleftView)
make.height.equalTo(25)
}
lleftOrderIdLable.text = "订单编号 : " + NSString(format: "%.0f", shopOrderDetail.shopDetail!.OrderId!)
lleftOrderIdLable.font = UIFont(name:"Heiti SC",size:13)
lleftOrderMoneyLabel.text = "付款信息 : "
lleftOrderMoneyLabel.font = UIFont(name:"Heiti SC",size:13)
lleftOrderUserAddressLabel.text = "客户地址 : \(String(shopOrderDetail.shopDetail!.UserCommunity!)) \(String(shopOrderDetail.shopDetail!.UserRoomNo!))"
lleftOrderUserAddressLabel.font = UIFont(name:"Heiti SC",size:13)
lleftOrderUserPhoneLabel.text = "客户电话 : \(String(shopOrderDetail.shopDetail!.UserPhone!))"
lleftOrderUserPhoneLabel.font = UIFont(name:"Heiti SC",size:13)
lleftOrderShopName.text = "下单饲料经销店 : \(String(shopOrderDetail.shopDetail!.ShopMini!.Name!))"
lleftOrderShopName.font = UIFont(name:"Heiti SC",size:13)
var phone = shopOrderDetail.shopDetail!.ShopMini!.Phone == nil ? "" : String(shopOrderDetail.shopDetail!.ShopMini!.Phone!)
lleftOrderShopPhone.font = UIFont(name:"Heiti SC",size:13)
lleftOrderShopPhone.text = "饲料经销店电话 : \(phone)"
lleftOrderShopPhone.editable = false
lleftOrderShopPhone.dataDetectorTypes = UIDataDetectorTypes.All
//six icon
var image = "order_status_\(shopOrderDetail.shopDetail!.Status!).png"
print(image)
var firstIcon = UIImageView(image: UIImage(named: image))
leftView.addSubview(firstIcon)
firstIcon.snp_makeConstraints { make in
make.top.equalTo(lleftOrderShopPhone.snp_bottom).offset(5)
make.left.equalTo(self.leftView.snp_left).offset(2)
make.right.equalTo(self.leftView.snp_right).offset(-2)
make.centerX.equalTo(self.leftView.snp_centerX)
make.height.equalTo(53)
make.width.equalTo(312)
}
//one red line
var lineView = UIView()
lineView.backgroundColor = UIColor.redColor()
leftView.addSubview(lineView)
lineView.snp_makeConstraints { make in
make.top.equalTo(firstIcon.snp_bottom)
make.left.equalTo(self.lleftView.snp_left)
make.width.equalTo(self.lleftView)
make.height.equalTo(3)
}
//预约状态 6
var last_left_bottom = lineView.snp_bottom
var count = 0
if (shopOrderDetail.shopDetail!.Status! == 2) { count = 2 } else { count = 6 }
//订单取消是2
var statusSuccessTxtArray = ["","预约","","饲料","已洗好","预约送衣","完成","收衣"]
var statusCancelTxtArray = ["","预约","订单取消"]
var statusTimes = [
shopOrderDetail.shopDetail!.ConfirmTime,
shopOrderDetail.shopDetail!.GetTime!,
shopOrderDetail.shopDetail!.WashingTime,
shopOrderDetail.shopDetail!.WashedTime,
shopOrderDetail.shopDetail!.SendTime,
shopOrderDetail.shopDetail!.FinishTime
]
var statusIntArray = [0 , 1, 2 ,7 ,3 ,4 ,5 ,6]
for index in 1...count
{
var headImage = UIImageView()
var statusDescription = UILabel()
statusDescription.font = UIFont(name:"Heiti SC",size:13)
if(count == 2)
{
if(index == 1)
{
headImage = UIImageView(image: UIImage(named: "order_status_end.png"))
}
else
{
headImage = UIImageView(image: UIImage(named: "order_status_ing.png"))
}
statusDescription.text = statusCancelTxtArray[index]
}
else
{
if(index == 2)
{
statusDescription.text = statusSuccessTxtArray[7]
}
else if (index == 7)
{
statusDescription.text = statusSuccessTxtArray[2]
}
else
{
statusDescription.text = statusSuccessTxtArray[index]
}
if(statusTimes[index - 1] == "" && index != 2 && index != 3 )
{
headImage = UIImageView(image: UIImage(named: "order_status_after.png"))
}
else
{
if(shopOrderDetail.shopDetail!.Status! == 1 && index == 1)
{
headImage = UIImageView(image: UIImage(named: "order_status_ing.png"))
statusDescription.text = statusDescription.text! + " [\(statusTimes[index-1]!)]"
}
else if(shopOrderDetail.shopDetail!.Status! == 1 )
{
headImage = UIImageView(image: UIImage(named: "order_status_after.png"))
}
else
{
if(shopOrderDetail.shopDetail!.Status! == 7 && index == 2)
{
headImage = UIImageView(image: UIImage(named: "order_status_ing.png"))
statusDescription.text = statusDescription.text! + " [\(shopOrderDetail.shopDetail!.ReceiveTime!)]"
}
else if(shopOrderDetail.shopDetail!.Status! == 3 && index == 3)
{
headImage = UIImageView(image: UIImage(named: "order_status_ing.png"))
statusDescription.text = statusDescription.text! + " [\(shopOrderDetail.shopDetail!.WashingTime!)]"
}
else if(shopOrderDetail.shopDetail!.Status! == index )
{
headImage = UIImageView(image: UIImage(named: "order_status_ing.png"))
statusDescription.text = statusDescription.text! + " [\(statusTimes[index-1]!)]"
}
else
{
headImage = UIImageView(image: UIImage(named: "order_status_end.png"))
statusDescription.text = statusDescription.text! + " [\(statusTimes[index-1]!)]"
}
}
}
}
leftView.addSubview(headImage)
leftView.addSubview(statusDescription)
headImage.snp_makeConstraints { make in
make.top.equalTo(last_left_bottom).offset(8)
make.left.equalTo(self.leftView.snp_left)
make.width.equalTo(3)
make.height.equalTo(15)
}
statusDescription.snp_makeConstraints { make in
make.left.equalTo(headImage.snp_right).offset(2)
make.centerY.equalTo(headImage.snp_centerY)
make.width.equalTo(240)
make.height.equalTo(25)
}
last_left_bottom = headImage.snp_bottom
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | f50303d1689da3fdb7f2b2dcc87439b6 | 36.654434 | 155 | 0.549501 | 4.601271 | false | false | false | false |
jhihguan/JSON2Realm | Pods/Gloss/Sources/Encoder.swift | 1 | 8371 | //
// Encoder.swift
// Gloss
//
// Copyright (c) 2015 Harlan Kellaway
//
// 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
/**
Set of functions used to encode values to JSON
*/
public struct Encoder {
// MARK: - Encoders
/**
Returns function to encode value to JSON
:parameter: key Key used to create JSON property
:returns: Function decoding value to optional JSON
*/
public static func encode<T>(key: String) -> T? -> JSON? {
return {
property in
if let property = property as? AnyObject {
return [key : property]
}
return nil
}
}
/**
Returns function to encode value to JSON
for objects the conform to the Encodable protocol
:parameter: key Key used to create JSON property
:returns: Function decoding value to optional JSON
*/
public static func encodeEncodable<T: Encodable>(key: String) -> T? -> JSON? {
return {
model in
if let model = model, json = model.toJSON() {
return [key : json]
}
return nil
}
}
/**
Returns function to encode date as JSON
:parameter: key Key used to create JSON property
:parameter: dateFormatter Formatter used to format date string
:returns: Function encoding date to optional JSON
*/
public static func encodeDate(key: String, dateFormatter: NSDateFormatter) -> NSDate? -> JSON? {
return {
date in
if let date = date {
return [key : dateFormatter.stringFromDate(date)]
}
return nil
}
}
/**
Returns function to encode ISO8601 date as JSON
:parameter: key Key used to create JSON property
:parameter: dateFormatter Formatter used to format date string
:returns: Function encoding ISO8601 date to optional JSON
*/
public static func encodeDateISO8601(key: String) -> NSDate? -> JSON? {
return Encoder.encodeDate(key, dateFormatter: GlossDateFormatterISO8601())
}
/**
Returns function to encode enum value as JSON
:parameter: key Key used to create JSON property
:returns: Function encoding enum value to optional JSON
*/
public static func encodeEnum<T: RawRepresentable>(key: String) -> T? -> JSON? {
return {
enumValue in
if let enumValue = enumValue {
return [key : enumValue.rawValue as! AnyObject]
}
return nil
}
}
/**
Returns function to encode URL as JSON
:parameter: key Key used to create JSON property
:returns: Function encoding URL to optional JSON
*/
public static func encodeURL(key: String) -> NSURL? -> JSON? {
return {
url in
if let url = url {
return [key : url.absoluteString]
}
return nil
}
}
/**
Returns function to encode array as JSON
:parameter: key Key used to create JSON property
:returns: Function encoding array to optional JSON
*/
public static func encodeArray<T>(key: String) -> [T]? -> JSON? {
return {
array in
if let array = array as? AnyObject {
return [key : array]
}
return nil
}
}
/**
Returns function to encode array as JSON
for objects the conform to the Encodable protocol
:parameter: key Key used to create JSON property
:returns: Function encoding array to optional JSON
*/
public static func encodeEncodableArray<T: Encodable>(key: String) -> [T]? -> JSON? {
return {
array in
if let array = array {
var encodedArray: [JSON] = []
for model in array {
if let json = model.toJSON() {
encodedArray.append(json)
}
}
return [key : encodedArray]
}
return nil
}
}
/**
Returns function to encode a [String : Encodable] into JSON
for objects the conform to the Encodable protocol
:parameter: key Key used to create JSON property
:returns: Function encoding dictionary to optional JSON
*/
public static func encodeEncodableDictionary<T: Encodable>(key: String) -> [String : T]? -> JSON? {
return {
dictionary in
guard let dictionary = dictionary else {
return nil
}
let encoded : [String:JSON] = dictionary.flatMap { (key, value) in
guard let json = value.toJSON() else {
return nil
}
return (key, json)
}
return [key : encoded]
}
}
/**
Returns function to encode array as JSON
of enum raw values
:parameter: key Key used to create JSON property
:returns: Function encoding array to optional JSON
*/
public static func encodeEnumArray<T: RawRepresentable>(key: String) -> [T]? -> JSON? {
return {
enumValues in
if let enumValues = enumValues {
var rawValues: [T.RawValue] = []
for enumValue in enumValues {
rawValues.append(enumValue.rawValue)
}
return [key : rawValues as! AnyObject]
}
return nil
}
}
/**
Returns function to encode date array as JSON
:parameter: key Key used to create JSON property
:parameter: dateFormatter Formatter used to format date string
:returns: Function encoding date array to optional JSON
*/
public static func encodeDateArray(key: String, dateFormatter: NSDateFormatter) -> [NSDate]? -> JSON? {
return {
dates in
if let dates = dates {
var dateStrings: [String] = []
for date in dates {
let dateString = dateFormatter.stringFromDate(date)
dateStrings.append(dateString)
}
return [key : dateStrings]
}
return nil
}
}
/**
Returns function to encode ISO8601 date array as JSON
:parameter: key Key used to create JSON property
:parameter: dateFormatter Formatter used to format date string
:returns: Function encoding ISO8601 date array to optional JSON
*/
public static func encodeDateISO8601Array(key: String) -> [NSDate]? -> JSON? {
return Encoder.encodeDateArray(key, dateFormatter: GlossDateFormatterISO8601())
}
}
| mit | e520b819d2c5766745a976b81676f2bd | 28.37193 | 107 | 0.551189 | 5.400645 | false | false | false | false |
jeffreality/iOS-Swift-Camera | iOS Swift Camera/RecordVideoViewController.swift | 1 | 7826 | //
// RecordVideoViewController.swift
// iOS Swift Camera
//
// Created by Jeffrey Berthiaume on 9/18/15.
// Copyright © 2015 Jeffrey Berthiaume. All rights reserved.
//
import UIKit
import AVFoundation
class RecordVideoViewController: UIViewController {
var movieFileOutput:AVCaptureMovieFileOutput? = nil
var isRecording = false
var elapsedTime = 0.0
var elapsedTimer:NSTimer? = nil
var fileName:String? = nil
@IBOutlet weak var videoPreviewView: UIView!
@IBOutlet weak var btnStartRecording: UIButton!
@IBOutlet weak var elapsedTimeLabel: UILabel!
var session: AVCaptureSession? = nil
var previewLayer: AVCaptureVideoPreviewLayer? = nil
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let maxSecondsForVideo = 15.0
let captureFramesPerSecond = 30.0
override func viewDidLoad() {
super.viewDidLoad()
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
if device != nil {
self.setupRecording()
}
}
func setupRecording () {
if session != nil {
session!.stopRunning()
session = nil
}
btnStartRecording.setImage(UIImage(named: "ButtonRecord"), forState: UIControlState.Normal)
isRecording = false
self.setupCaptureSession()
elapsedTime = -0.5
self.updateElapsedTime()
}
func setupCaptureSession () {
session = AVCaptureSession()
session?.sessionPreset = AVCaptureSessionPresetMedium
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
let input = try AVCaptureDeviceInput(device: device)
session?.addInput(input)
} catch {
print ("video initialization error")
}
AVAudioSession.sharedInstance().requestRecordPermission { (granted: Bool) -> Void in
if granted {
let audioCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
do {
let audioInput = try AVCaptureDeviceInput(device: audioCaptureDevice)
self.session?.addInput(audioInput)
} catch {
print ("audio initialization error")
}
}
}
let queue = dispatch_queue_create("videoCaptureQueue", nil)
let output = AVCaptureVideoDataOutput ()
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey : Int(kCVPixelFormatType_32BGRA)]
output.setSampleBufferDelegate(self, queue: queue)
session?.addOutput(output)
previewLayer = AVCaptureVideoPreviewLayer (session: session)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer?.frame = CGRectMake(0, 0, videoPreviewView.frame.size.width, videoPreviewView.frame.size.height)
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
let currentOrientation = UIDevice.currentDevice().orientation
UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications()
if currentOrientation == UIDeviceOrientation.LandscapeLeft {
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
} else {
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeLeft
}
videoPreviewView.layer.addSublayer(previewLayer!)
movieFileOutput = AVCaptureMovieFileOutput()
let maxDuration = CMTimeMakeWithSeconds(maxSecondsForVideo, Int32(captureFramesPerSecond))
movieFileOutput?.maxRecordedDuration = maxDuration
movieFileOutput?.minFreeDiskSpaceLimit = 1024 * 1024
if (session?.canAddOutput(movieFileOutput) != nil) {
session?.addOutput(movieFileOutput)
}
var videoConnection:AVCaptureConnection? = nil
for connection in (movieFileOutput?.connections)! {
for port in connection.inputPorts! {
if port.mediaType == AVMediaTypeVideo {
videoConnection = connection as? AVCaptureConnection
break
}
}
if videoConnection != nil {
break
}
}
videoConnection?.videoOrientation = AVCaptureVideoOrientation (ui: currentOrientation)
if (session?.canSetSessionPreset(AVCaptureSessionPreset640x480) != nil) {
session?.sessionPreset = AVCaptureSessionPreset640x480
}
session?.startRunning()
}
func updateElapsedTime () {
elapsedTime += 0.5
let elapsedFromMax = maxSecondsForVideo - elapsedTime
elapsedTimeLabel.text = "00:" + String(format: "%02d", Int(round(elapsedFromMax)))
if elapsedTime >= maxSecondsForVideo {
isRecording = true
self.recordVideo(self.btnStartRecording)
}
}
func generateThumbnailFromVideo () {
let videoURL = NSURL(fileURLWithPath: (documentsURL.path! + "/" + fileName! + ".mp4"))
let thumbnailPath = documentsURL.path! + "/" + fileName! + ".jpg"
let asset = AVAsset(URL: videoURL)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
let time = CMTimeMake(2, 1)
do {
let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: nil)
let videoThumb = UIImage(CGImage: imageRef)
let imgData = UIImageJPEGRepresentation(videoThumb, 0.8)
NSFileManager.defaultManager().createFileAtPath(thumbnailPath, contents: imgData, attributes: nil)
} catch let error as NSError {
print("Image generation failed with error \(error)")
}
}
@IBAction func recordVideo (btn : UIButton) {
if !isRecording {
isRecording = true
elapsedTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("updateElapsedTime"), userInfo: nil, repeats: true)
btn.setImage(UIImage (named: "ButtonStop"), forState: UIControlState.Normal)
fileName = NSUUID ().UUIDString
let path = documentsURL.path! + "/" + fileName! + ".mp4"
let outputURL = NSURL(fileURLWithPath: path)
movieFileOutput?.startRecordingToOutputFileURL(outputURL, recordingDelegate: self)
} else {
isRecording = false
elapsedTimer?.invalidate()
movieFileOutput?.stopRecording()
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
if fromInterfaceOrientation == UIInterfaceOrientation.LandscapeLeft {
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
} else {
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeLeft
}
}
}
extension AVCaptureVideoOrientation {
var uiInterfaceOrientation: UIDeviceOrientation {
get {
switch self {
case .LandscapeLeft: return .LandscapeLeft
case .LandscapeRight: return .LandscapeRight
case .Portrait: return .Portrait
case .PortraitUpsideDown: return .PortraitUpsideDown
}
}
}
init(ui:UIDeviceOrientation) {
switch ui {
case .LandscapeRight: self = .LandscapeRight
case .LandscapeLeft: self = .LandscapeLeft
case .Portrait: self = .Portrait
case .PortraitUpsideDown: self = .PortraitUpsideDown
default: self = .Portrait
}
}
}
extension RecordVideoViewController: AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureFileOutputRecordingDelegate {
func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
print (outputFileURL);
self.generateThumbnailFromVideo()
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| gpl-2.0 | f077266bf3b44449cfcaead96e246c36 | 31.069672 | 178 | 0.698019 | 5.593281 | false | false | false | false |
jmgc/swift | stdlib/public/Concurrency/Task.swift | 1 | 14346 | ////===----------------------------------------------------------------------===//
////
//// This source file is part of the Swift.org open source project
////
//// Copyright (c) 2020 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 Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== Task -------------------------------------------------------------------
/// An asynchronous task (just "Task" hereafter) is the analogue of a thread for
/// asynchronous functions. All asynchronous functions run as part of some task.
///
/// A task can only be interacted with by code running "in" the task,
/// by invoking the appropriate context sensitive static functions which operate
/// on the "current" task. Because all such functions are `async` they can only
/// be invoked as part of an existing task, and therefore are guaranteed to be
/// effective.
///
/// A task's execution can be seen as a series of periods where the task was
/// running. Each such period ends at a suspension point or -- finally -- the
/// completion of the task.
///
/// These partial periods towards the task's completion are `PartialAsyncTask`.
/// Partial tasks are generally not interacted with by end-users directly,
/// unless implementing a scheduler.
public enum Task {
}
// ==== Task Priority ----------------------------------------------------------
extension Task {
/// Returns the current task's priority.
///
/// ### Suspension
/// This function returns instantly and will never suspend.
/* @instantaneous */
public static func currentPriority() async -> Priority {
getJobFlags(Builtin.getCurrentAsyncTask()).priority
}
/// Task priority may inform decisions an `Executor` makes about how and when
/// to schedule tasks submitted to it.
///
/// ### Priority scheduling
/// An executor MAY utilize priority information to attempt running higher
/// priority tasks first, and then continuing to serve lower priority tasks.
///
/// The exact semantics of how priority is treated are left up to each
/// platform and `Executor` implementation.
///
/// ### Priority inheritance
/// Child tasks automatically inherit their parent task's priority.
///
/// Detached tasks (created by `Task.runDetached`) DO NOT inherit task priority,
/// as they are "detached" from their parent tasks after all.
///
/// ### Priority elevation
/// In some situations the priority of a task must be elevated (or "escalated", "raised"):
///
/// - if a `Task` running on behalf of an actor, and a new higher-priority
/// task is enqueued to the actor, its current task must be temporarily
/// elevated to the priority of the enqueued task, in order to allow the new
/// task to be processed at--effectively-- the priority it was enqueued with.
/// - this DOES NOT affect `Task.currentPriority()`.
/// - if a task is created with a `Task.Handle`, and a higher-priority task
/// calls the `await handle.get()` function the priority of this task must be
/// permanently increased until the task completes.
/// - this DOES affect `Task.currentPriority()`.
///
/// TODO: Define the details of task priority; It is likely to be a concept
/// similar to Darwin Dispatch's QoS; bearing in mind that priority is not as
/// much of a thing on other platforms (i.e. server side Linux systems).
public enum Priority: Int, Comparable {
// Values must be same as defined by the internal `JobPriority`.
case userInteractive = 0x21
case userInitiated = 0x19
case `default` = 0x15
case utility = 0x11
case background = 0x09
case unspecified = 0x00
public static func < (lhs: Priority, rhs: Priority) -> Bool {
lhs.rawValue < rhs.rawValue
}
}
}
// ==== Task Handle ------------------------------------------------------------
extension Task {
/// A task handle refers to an in-flight `Task`,
/// allowing for potentially awaiting for its result or canceling it.
///
/// It is not a programming error to drop a handle without awaiting or canceling it,
/// i.e. the task will run regardless of the handle still being present or not.
/// Dropping a handle however means losing the ability to await on the task's result
/// and losing the ability to cancel it.
public struct Handle<Success> {
let task: Builtin.NativeObject
/// Wait for the task to complete, returning (or throwing) its result.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// If the awaited on task gets cancelled externally the `get()` will throw
/// a cancellation error.
///
/// If the task gets cancelled internally, e.g. by checking for cancellation
/// and throwing a specific error or using `checkCancellation` the error
/// thrown out of the task will be re-thrown here.
public func get() async throws -> Success {
return await try _taskFutureGetThrowing(task)
}
/// Attempt to cancel the task.
///
/// Whether this function has any effect is task-dependent.
///
/// For a task to respect cancellation it must cooperatively check for it
/// while running. Many tasks will check for cancellation before beginning
/// their "actual work", however this is not a requirement nor is it guaranteed
/// how and when tasks check for cancellation in general.
public func cancel() {
Builtin.cancelAsyncTask(task)
}
}
}
// ==== Job Flags --------------------------------------------------------------
extension Task {
/// Flags for schedulable jobs.
///
/// This is a port of the C++ FlagSet.
struct JobFlags {
/// Kinds of schedulable jobs.
enum Kind: Int {
case task = 0
};
/// The actual bit representation of these flags.
var bits: Int = 0
/// The kind of job described by these flags.
var kind: Kind {
get {
Kind(rawValue: bits & 0xFF)!
}
set {
bits = (bits & ~0xFF) | newValue.rawValue
}
}
/// Whether this is an asynchronous task.
var isAsyncTask: Bool { kind == .task }
/// The priority given to the job.
var priority: Priority {
get {
Priority(rawValue: (bits & 0xFF00) >> 8)!
}
set {
bits = (bits & ~0xFF00) | (newValue.rawValue << 8)
}
}
/// Whether this is a child task.
var isChildTask: Bool {
get {
(bits & (1 << 24)) != 0
}
set {
if newValue {
bits = bits | 1 << 24
} else {
bits = (bits & ~(1 << 24))
}
}
}
/// Whether this is a future.
var isFuture: Bool {
get {
(bits & (1 << 25)) != 0
}
set {
if newValue {
bits = bits | 1 << 25
} else {
bits = (bits & ~(1 << 25))
}
}
}
/// Whether this is a channel.
var isTaskGroup: Bool {
get {
(bits & (1 << 26)) != 0
}
set {
if newValue {
bits = bits | 1 << 26
} else {
bits = (bits & ~(1 << 26))
}
}
}
}
}
// ==== Detached Tasks ---------------------------------------------------------
extension Task {
/// Run given throwing `operation` as part of a new top-level task.
///
/// Creating detached tasks should, generally, be avoided in favor of using
/// `async` functions, `async let` declarations and `await` expressions - as
/// those benefit from structured, bounded concurrency which is easier to reason
/// about, as well as automatically inheriting the parent tasks priority,
/// task-local storage, deadlines, as well as being cancelled automatically
/// when their parent task is cancelled. Detached tasks do not get any of those
/// benefits, and thus should only be used when an operation is impossible to
/// be modelled with child tasks.
///
/// ### Cancellation
/// A detached task always runs to completion unless it is explicitly cancelled.
/// Specifically, dropping a detached tasks `Task.Handle` does _not_ automatically
/// cancel given task.
///
/// Canceling a task must be performed explicitly via `handle.cancel()`.
///
/// - Note: it is generally preferable to use child tasks rather than detached
/// tasks. Child tasks automatically carry priorities, task-local state,
/// deadlines and have other benefits resulting from the structured
/// concurrency concepts that they model. Consider using detached tasks only
/// when strictly necessary and impossible to model operations otherwise.
///
/// - Parameters:
/// - priority: priority of the task
/// - operation: the operation to execute
/// - Returns: handle to the task, allowing to `await handle.get()` on the
/// tasks result or `cancel` it. If the operation fails the handle will
/// throw the error the operation has thrown when awaited on.
public static func runDetached<T>(
priority: Priority = .default,
operation: @escaping () async throws -> T
) -> Handle<T> {
// Set up the job flags for a new task.
var flags = JobFlags()
flags.kind = .task
flags.priority = priority
flags.isFuture = true
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTaskFuture(flags.bits, nil, operation)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(task))
return Handle<T>(task: task)
}
}
public func _runAsyncHandler(operation: @escaping () async -> ()) {
_ = Task.runDetached(operation: operation)
}
// ==== Voluntary Suspension -----------------------------------------------------
extension Task {
/// Suspend until a given point in time.
///
/// ### Cancellation
/// Does not check for cancellation and suspends the current context until the
/// given deadline.
///
/// - Parameter until: point in time until which to suspend.
public static func sleep(until: Deadline) async {
fatalError("\(#function) not implemented yet.")
}
/// Explicitly suspend the current task, potentially giving up execution actor
/// of current actor/task, allowing other tasks to execute.
///
/// This is not a perfect cure for starvation;
/// if the task is the highest-priority task in the system, it might go
/// immediately back to executing.
public static func yield() async {
fatalError("\(#function) not implemented yet.")
}
}
@_silgen_name("swift_task_getJobFlags")
func getJobFlags(_ task: Builtin.NativeObject) -> Task.JobFlags
@_silgen_name("swift_task_enqueueGlobal")
@usableFromInline
func _enqueueJobGlobal(_ task: Builtin.Job)
@_silgen_name("swift_task_isCancelled")
func isTaskCancelled(_ task: Builtin.NativeObject) -> Bool
@_silgen_name("swift_task_runAndBlockThread")
public func runAsyncAndBlock(_ asyncFun: @escaping () async -> ())
@_silgen_name("swift_task_future_wait")
func _taskFutureWait(
on task: Builtin.NativeObject
) async -> (hadErrorResult: Bool, storage: UnsafeRawPointer)
public func _taskFutureGet<T>(_ task: Builtin.NativeObject) async -> T {
let rawResult = await _taskFutureWait(on: task)
assert(!rawResult.hadErrorResult)
// Take the value.
let storagePtr = rawResult.storage.bindMemory(to: T.self, capacity: 1)
return UnsafeMutablePointer<T>(mutating: storagePtr).pointee
}
public func _taskFutureGetThrowing<T>(
_ task: Builtin.NativeObject
) async throws -> T {
let rawResult = await _taskFutureWait(on: task)
if rawResult.hadErrorResult {
// Throw the result on error.
throw unsafeBitCast(rawResult.storage, to: Error.self)
}
// Take the value on success
let storagePtr =
rawResult.storage.bindMemory(to: T.self, capacity: 1)
return UnsafeMutablePointer<T>(mutating: storagePtr).pointee
}
public func _runChildTask<T>(
operation: @escaping () async throws -> T
) async -> Builtin.NativeObject {
let currentTask = Builtin.getCurrentAsyncTask()
// Set up the job flags for a new task.
var flags = Task.JobFlags()
flags.kind = .task
flags.priority = getJobFlags(currentTask).priority
flags.isFuture = true
flags.isChildTask = true
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTaskFuture(
flags.bits, currentTask, operation)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(task))
return task
}
public func _runGroupChildTask<T>(
overridingPriority priorityOverride: Task.Priority? = nil,
operation: @escaping () async throws -> T
) async -> Builtin.NativeObject {
let currentTask = Builtin.getCurrentAsyncTask()
// Set up the job flags for a new task.
var flags = Task.JobFlags()
flags.kind = .task
flags.priority = priorityOverride ?? getJobFlags(currentTask).priority
flags.isFuture = true
flags.isChildTask = true
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTaskFuture(
flags.bits, currentTask, operation)
// Enqueue the resulting job.
_enqueueJobGlobal(Builtin.convertTaskToJob(task))
return task
}
@_silgen_name("swift_task_cancel")
func _taskCancel(_ task: Builtin.NativeObject)
@_silgen_name("swift_task_isCancelled")
func _taskIsCancelled(_ task: Builtin.NativeObject) -> Bool
#if _runtime(_ObjC)
/// Intrinsic used by SILGen to launch a task for bridging a Swift async method
/// which was called through its ObjC-exported completion-handler-based API.
@_alwaysEmitIntoClient
@usableFromInline
internal func _runTaskForBridgedAsyncMethod(_ body: @escaping () async -> Void) {
// TODO: We can probably do better than Task.runDetached
// if we're already running on behalf of a task,
// if the receiver of the method invocation is itself an Actor, or in other
// situations.
_ = Task.runDetached { await body() }
}
#endif
| apache-2.0 | ecd298a0b3a6d5706aca47b4a1a0a760 | 33.157143 | 92 | 0.646522 | 4.37378 | false | false | false | false |
chenzhe555/core-ios-swift | core-ios-swift/Framework_swift/CustomView/custom/AdScrollView/BaseImageScrollView_s.swift | 1 | 8255 | //
// BaseImageScrollView_s.swift
// MeicaiStore_swift
//
// Created by mc962 on 16/3/2.
// Copyright © 2016年 陈哲是个好孩子. All rights reserved.
//
import UIKit
@objc public protocol BaseImageScrollViewDelegate {
func dlScrollImageClickedAtIndex(index: NSInteger);
}
class BaseImageScrollView_s: UIView,UIScrollViewDelegate {
//MARK: *************** .h(Protocal Enum ...)
//MARK: *************** .h(Property Method ...)
var scrollDelegate: BaseImageScrollViewDelegate?;
//是本地已有图片数组还是服务器上图片
var isLocalImageArray = false;
/**
用本地已有的Image数组更新scrollview(如果无展示图一定要传入defaultImage)
- parameter imgArr: Image的数组
*/
func fillInImageArray(imgArr: NSArray?) -> Void {
if(imgArr == nil)
{
if(self.defaultImage != nil)
{
self.imageArray = [self.defaultImage!];
}
else
{
self.imageArray = [UIImage.transformToPureImageWithColor(UIColor.whiteColor())];
}
}
else
{
self.imageArray = imgArr!;
}
self.leftImageIndex = self.imageArray.count - 1;
self.centerImageIndex = 0;
self.rightImageIndex = 1;
//图片少于一张不滚动,没有PageController
if(self.imageArray.count == 1)
{
self.scrollView.scrollEnabled = false;
self.rightImageIndex = 0;
}
self.pageController.numberOfPages = self.imageArray.count;
self.pageController.currentPage = 0;
self.scrollView.contentOffset = CGPointMake(self.scrollView.width, 0);
self.updateImage();
}
//MARK: *************** .m(Category ...)
//滚动视图以及复用的三个ImageView
var scrollView: UIScrollView!;
let leftImageView = UIImageView();
var leftImageIndex = 0;
let centerImageView = UIImageView();
var centerImageIndex = 1;
let rightImageView = UIImageView();
var rightImageIndex = 2;
//PageController
let pageController = UIPageControl();
//是否自动滚动,默认自动滚动
var isAutoScroll = true;
//当前数据源数组
var imageArray = [];
//一张图片都没有时候的默认图片,无默认一片白
var defaultImage: UIImage?;
//图片正在下载时候的默认图
var placeHolderImage: UIImage?;
//MARK: *************** .m(Method ...)
override init(frame: CGRect) {
super.init(frame: frame);
//添加属性
self.scrollView = UIScrollView(frame: CGRectMake(0,0,frame.size.width,frame.size.height));
self.scrollView.bounces = false;
self.scrollView.showsVerticalScrollIndicator = false;
self.scrollView.showsHorizontalScrollIndicator = false;
self.scrollView.pagingEnabled = true;
self.scrollView.contentSize = CGSizeMake(frame.size.width*3, frame.size.height);
self.scrollView.delegate = self;
//添加子视图
self.leftImageView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
self.leftImageView.addTarget(self, action: Selector("test"));
self.leftImageView.userInteractionEnabled = true;
self.centerImageView.frame = CGRectMake(frame.size.width, 0, frame.size.width, frame.size.height);
self.centerImageView.addTarget(self, action: Selector("test"));
self.centerImageView.userInteractionEnabled = true;
self.rightImageView.frame = CGRectMake(frame.size.width*2, 0, frame.size.width, frame.size.height);
self.rightImageView.addTarget(self, action: Selector("test"));
self.rightImageView.userInteractionEnabled = true;
self.pageController.frame = CGRectMake((frame.size.width - 100)/2, (frame.size.height - 40), 100, 20);
self.pageController.pageIndicatorTintColor = UIColor.grayColor();
self.pageController.currentPageIndicatorTintColor = UIColor.redColor();
self.scrollView.addSubview(self.leftImageView);
self.scrollView.addSubview(self.centerImageView);
self.scrollView.addSubview(self.rightImageView);
self.addSubview(self.scrollView);
self.addSubview(self.pageController);
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
func test() -> Void {
print("xxxxxxxxxxxxxxx");
}
/**
更新当前Image数据源
*/
private func updateImage() -> Void {
if(self.isLocalImageArray)
{
self.leftImageView.image = self.imageArray[self.leftImageIndex] as? UIImage;
self.centerImageView.image = self.imageArray[self.centerImageIndex] as? UIImage;
self.rightImageView.image = self.imageArray[self.rightImageIndex] as? UIImage;
}
else
{
if(self.placeHolderImage != nil)
{
self.leftImageView.sd_setImageWithURL(NSURL(string: self.imageArray[self.leftImageIndex] as! String), placeholderImage: self.placeHolderImage!);
self.centerImageView.sd_setImageWithURL(NSURL(string: self.imageArray[self.centerImageIndex] as! String), placeholderImage: self.placeHolderImage!);
self.rightImageView.sd_setImageWithURL(NSURL(string: self.imageArray[self.rightImageIndex] as! String), placeholderImage: self.placeHolderImage!);
}
else
{
self.leftImageView.sd_setImageWithURL(NSURL(string: self.imageArray[self.leftImageIndex] as! String), placeholderImage: UIImage.transformToPureImageWithColor(UIColor.whiteColor()));
self.centerImageView.sd_setImageWithURL(NSURL(string: self.imageArray[self.centerImageIndex] as! String), placeholderImage: UIImage.transformToPureImageWithColor(UIColor.whiteColor()));
self.rightImageView.sd_setImageWithURL(NSURL(string: self.imageArray[self.rightImageIndex] as! String), placeholderImage: UIImage.transformToPureImageWithColor(UIColor.whiteColor()));
}
}
}
//MARK: UIScrollView滚动事件
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if(self.scrollView.contentOffset.x == 0)
{
self.leftImageIndex--;
self.centerImageIndex--;
self.rightImageIndex--;
self.leftImageIndex = (self.leftImageIndex == -1) ? (self.imageArray.count - 1) : self.leftImageIndex;
self.centerImageIndex = (self.centerImageIndex == -1) ? (self.imageArray.count - 1) : self.centerImageIndex;
self.rightImageIndex = (self.rightImageIndex == -1) ? (self.imageArray.count - 1) : self.rightImageIndex;
}
else if(self.scrollView.contentOffset.x == self.scrollView.width*2)
{
self.leftImageIndex++;
self.centerImageIndex++;
self.rightImageIndex++;
self.leftImageIndex = (self.leftImageIndex == self.imageArray.count) ? 0 : self.leftImageIndex;
self.centerImageIndex = (self.centerImageIndex == self.imageArray.count) ? 0 : self.centerImageIndex;
self.rightImageIndex = (self.rightImageIndex == self.imageArray.count) ? 0 : self.rightImageIndex;
}
else
{
return;
}
print(self.scrollView.contentOffset.x);
self.updateImage();
self.pageController.currentPage = self.centerImageIndex;
self.scrollView.contentOffset = CGPointMake(self.scrollView.width,0);
}
func imageViewClicked(obj: UIImageView) -> Void {
if(obj.isEqual(self.leftImageView))
{
self.scrollDelegate?.dlScrollImageClickedAtIndex(self.leftImageIndex);
}
else if(obj.isEqual(self.centerImageView))
{
self.scrollDelegate?.dlScrollImageClickedAtIndex(self.centerImageIndex);
}
else if(obj.isEqual(self.rightImageView))
{
self.scrollDelegate?.dlScrollImageClickedAtIndex(self.rightImageIndex);
}
}
}
| mit | 13290300ab3ca1750c36598b410e71b5 | 37.878049 | 201 | 0.632246 | 4.572576 | false | false | false | false |
fabioalmeida/FAAutoLayout | FAAutoLayout/Classes/UIView+Fill.swift | 1 | 5184 | //
// UIView+Fill.swift
// FAAutoLayout
//
// Created by Fábio Almeida on 27/06/2017.
// Copyright (c) 2017 Fábio Almeida. All rights reserved.
//
import UIKit
// MARK: - Fill
public extension UIView {
/// Constrains all the view margins to its container view (i.e. the view **superview**).
///
/// These contraint are added directly to the container view and are returned for future manipulation (if needed).
/// This method should be used for most of the cases you wish to define one equal space relation between a view
/// and the correspondent container view on all sides (e.g. the view should fill the container, or fill it with
/// some given padding at all sides).
///
/// The arguments should only be changed when the desired value is not the default value, to simplify the method readability.
/// All the **default values** for these contraint are the same as if the they were created on the Interface Builder.
///
/// - Parameters:
/// - constant: The constant added to the multiplied second attribute participating in the constraint. The default value is 0.
/// - relation: The relation between the two attributes in the constraint (e.g. =, >, >=, <, <=). The default relation is Equal.
/// - priority: The priority of the constraint. The default value is 1000 (required).
/// - multiplier: The multiplier applied to the second attribute participating in the constraint. The default value is 1.
/// - Returns: The added constraints between the two views in the following order: leading, trailing, top, bottom
@discardableResult
@objc(fillContainer:relation:priority:multiplier:)
func fillContainer(_ constant: CGFloat = Constants.spacing,
relation: NSLayoutConstraint.Relation = Constants.relation,
priority: UILayoutPriority = Constants.priority,
multiplier: CGFloat = Constants.multiplier) -> [NSLayoutConstraint] {
validateViewHierarchy()
return self.fill(view: superview!, constant: constant, relation: relation, priority: priority, multiplier: multiplier)
}
/// Constrains all the view margins to a container view (e.g. the view **superview** or another view higher in the hierarchy).
///
/// These contraint are added directly to the container view and are returned for future manipulation (if needed).
/// This method should be used when you wish to define one equal space relation to a view that is above the direct
/// container view hierarchy, for instance, `self.superview.superview`.
/// It will add constraints on all sides (e.g. the view should fill the container, or fill it with some given padding).
///
/// The arguments should only be changed when the desired value is not the default value, to simplify the method readability.
/// All the **default values** for these contraint are the same as if the they were created on the Interface Builder.
///
/// - Parameters:
/// - view: The container view for which we want to create the fill relation. For example, view.superview.superview.
/// - constant: The constant added to the multiplied second attribute participating in the constraint. The default value is 0.
/// - relation: The relation between the two attributes in the constraint (e.g. =, >, >=, <, <=). The default relation is Equal.
/// - priority: The priority of the constraint. The default value is 1000 (required).
/// - multiplier: The multiplier applied to the second attribute participating in the constraint. The default value is 1.
/// - Returns: The added constraints between the two views in the following order: leading, trailing, top, bottom
@discardableResult
@objc(fillView:constant:relation:priority:multiplier:)
func fill(view: UIView,
constant: CGFloat = Constants.spacing,
relation: NSLayoutConstraint.Relation = Constants.relation,
priority: UILayoutPriority = Constants.priority,
multiplier: CGFloat = Constants.multiplier) -> [NSLayoutConstraint] {
let leadingConstraint = NSLayoutConstraint.leadingSpaceConstraint(fromView: self, toView: view, relation: relation, multiplier: multiplier, constant: constant)
leadingConstraint.priority = priority
let trailingConstraint = NSLayoutConstraint.trailingSpaceConstraint(fromView: self, toView: view, relation: relation, multiplier: multiplier, constant: constant)
trailingConstraint.priority = priority
let topConstraint = NSLayoutConstraint.topSpaceConstraint(fromView: self, toView: view, relation: relation, multiplier: multiplier, constant: constant)
topConstraint.priority = priority
let bottomConstraint = NSLayoutConstraint.bottomSpaceConstraint(fromView: self, toView: view, relation: relation, multiplier: multiplier, constant: constant)
bottomConstraint.priority = priority
view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
return [leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]
}
}
| mit | b548e4cc3e01e4d080fa2535b115f181 | 64.594937 | 169 | 0.712852 | 5.05561 | false | false | false | false |
Chris-Perkins/Lifting-Buddy | Lifting Buddy/ExercisesTableViewCell.swift | 1 | 12765 | //
// ExercisesTableViewCell.swift
// Lifting Buddy
//
// Created by Christopher Perkins on 11/1/17.
// Copyright © 2017 Christopher Perkins. All rights reserved.
//
import UIKit
import SwiftCharts
class ExerciseTableViewCell: UITableViewCell {
// MARK: View properties
// The multiplier of how much the graph should take up
private static let chartWidthMultiplier: CGFloat = 0.85
// delegate we call to show the workout
public var mainViewCellDelegate: WorkoutSessionStarter?
// delegate to show a view for us
public var showViewDelegate: ShowViewDelegate?
// The title for every cell
private let cellTitle: UILabel
// The exercise associated with each cell
private var exercise: Exercise?
// An indicator on whether or not the cell is expanded
private let expandImage: UIImageView
// a button that absorbs touches to prevent view from collapsing
private let invisButton: UIButton
// The view which holds our chart and all associated views
private let chartFrame: UIView
// The view that actually stores the exercise chart
private var chartView: ExerciseChartViewWithToggles?
// The button that allows for exercise editing
private let editButton: PrettyButton
// A button to start the exercise
private let startExerciseButton: PrettyButton
// the height constraint for our chart frame
private var chartHeightConstraint: NSLayoutConstraint?
// MARK: Init functions
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
cellTitle = UILabel()
expandImage = UIImageView(image: #imageLiteral(resourceName: "DownArrow"))
invisButton = UIButton()
chartFrame = UIView()
editButton = PrettyButton()
startExerciseButton = PrettyButton()
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
editButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside)
startExerciseButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside)
addSubview(cellTitle)
addSubview(expandImage)
addSubview(chartFrame)
addSubview(editButton)
addSubview(startExerciseButton)
createAndActivateCellTitleConstraints()
createAndActivateExpandImageConstraints()
createAndActivateChartFrameConstraints()
createAndActivateEditButtonConstraints()
createAndActivateStartButtonConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View overrides
override func layoutSubviews() {
super.layoutSubviews()
chartFrame.layoutSubviews()
clipsToBounds = true
chartFrame.clipsToBounds = true
cellTitle.textColor = .niceBlue
cellTitle.textAlignment = .left
if (isSelected) {
editButton.setDefaultProperties()
editButton.setTitle(NSLocalizedString("Button.Edit", comment: ""), for: .normal)
startExerciseButton.setDefaultProperties()
startExerciseButton.backgroundColor = .niceBlue
startExerciseButton.setTitle(NSLocalizedString("Button.StartEX", comment: ""), for: .normal)
backgroundColor = .lightestBlackWhiteColor
} else {
backgroundColor = .primaryBlackWhiteColor
}
}
// MARK: Encapsulated methods
// Set the exercise for this cell
public func setExercise(exercise: Exercise) {
self.exercise = exercise
cellTitle.text = exercise.getName()
if exercise.getProgressionMethods().count > 0 {
let chartGraphView = ExerciseChartViewWithToggles(exercise: exercise,
chartWidth: frame.width *
ExerciseTableViewCell.chartWidthMultiplier)
chartFrame.addSubview(chartGraphView)
chartFrame.backgroundColor = .niceRed
chartHeightConstraint?.constant =
ExerciseChartViewWithToggles.getNecessaryHeightForExerciseGraph(exercise: exercise)
chartGraphView.translatesAutoresizingMaskIntoConstraints = false
chartView = chartGraphView
NSLayoutConstraint.clingViewToView(view: chartGraphView,
toView: chartFrame)
} else {
chartHeightConstraint?.constant = 0
}
layoutSubviews()
}
// Sets the expand button constraints
public func setExpandable(expandable: Bool) {
expandImage.alpha = expandable ? 1 : 0
}
// MARK: View functions
// Update selected status; v image becomes ^
public func updateSelectedStatus() {
if isSelected {
expandImage.transform = CGAffineTransform(scaleX: 1, y: -1)
chartView?.createChart()
} else {
expandImage.transform = CGAffineTransform(scaleX: 1, y: 1)
chartView?.destroyChart()
}
layoutSubviews()
}
// MARK: Event functions
@objc private func buttonPress(sender: UIButton) {
switch(sender) {
case startExerciseButton:
guard let mainViewController = viewContainingController() as? MainViewController else {
fatalError("view controller is now main view controller?")
}
mainViewController.startSession(workout: nil, exercise: exercise!)
case editButton:
guard let showViewDelegate = showViewDelegate else {
fatalError("ShowViewDelegate not set for CreateExerciseView")
}
let createExerciseView = CreateExerciseView(exercise: exercise, frame: .zero)
createExerciseView.showViewDelegate = showViewDelegate
showViewDelegate.showView(createExerciseView)
default:
fatalError("Button press not handled in exercisestableview!")
}
}
// MARK: Constraint functions
// Below view top ; indent to left by 10 ; do not overlap expandImage ; height of defaultHeight
private func createAndActivateCellTitleConstraints() {
cellTitle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitle,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitle,
withCopyView: self,
attribute: .left,
plusConstant: 10).isActive = true
NSLayoutConstraint(item: expandImage,
attribute: .left,
relatedBy: .equal,
toItem: cellTitle,
attribute: .right,
multiplier: 1,
constant: 5).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: cellTitle,
height: UITableViewCell.defaultHeight).isActive = true
}
// Indent from right ; Below self top ; Width 16 ; Height 8.46
private func createAndActivateExpandImageConstraints() {
expandImage.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: expandImage,
withCopyView: self,
attribute: .right,
plusConstant: -10).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: expandImage,
withCopyView: self,
attribute: .top,
plusConstant: 20.77).isActive = true
NSLayoutConstraint.createWidthConstraintForView(view: expandImage,
width: 16).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: expandImage,
height: 8.46).isActive = true
}
private func createAndActivateChartFrameConstraints() {
chartFrame.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: chartFrame,
withCopyView: self,
attribute: .centerX).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: chartFrame,
withCopyView: self,
attribute: .width,
multiplier: ExerciseTableViewCell.chartWidthMultiplier
).isActive = true
NSLayoutConstraint.createViewBelowViewConstraint(view: chartFrame,
belowView: cellTitle).isActive = true
// Start at 0. Is increased when exercise is set.
chartHeightConstraint = NSLayoutConstraint.createHeightConstraintForView(view: chartFrame,
height: 0)
chartHeightConstraint?.isActive = true
}
// Place at bottom of view, left of view ; width of this view * 0.5 ; Height of default
private func createAndActivateEditButtonConstraints() {
editButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewBelowViewConstraint(view: editButton,
belowView: chartFrame,
withPadding: 10).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: editButton,
height: PrettyButton.defaultHeight).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: editButton,
withCopyView: self,
attribute: .left).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: editButton,
withCopyView: self,
attribute: .width,
multiplier: 0.5).isActive = true
}
// Place at bottom of view, right of view ; width of this view * 0.5 ; Height of default
private func createAndActivateStartButtonConstraints() {
startExerciseButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewBelowViewConstraint(view: startExerciseButton,
belowView: chartFrame,
withPadding: 10).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: startExerciseButton,
height: PrettyButton.defaultHeight).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: startExerciseButton,
withCopyView: self,
attribute: .right).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: startExerciseButton,
withCopyView: self,
attribute: .width,
multiplier: 0.5).isActive = true
}
}
| mit | 5e87a164dfc2194143a12c5203f20c55 | 45.926471 | 115 | 0.556174 | 7.190986 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Basics.playground/Pages/Balancing Nodes.xcplaygroundpage/Contents.swift | 1 | 1409 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Balancing Nodes
//: Sometimes you want to ensure that an audio signal that you're processing
//: remains at a volume similar to where it started.
//: Such an application is perfect for the AKBalancer node.
import XCPlayground
import AudioKit
//: This section prepares the players
let bundle = NSBundle.mainBundle()
let file = try AKAudioFile(readFileName: "drumloop.wav", baseDir: .Resources)
var source = try AKAudioPlayer(file: file)
source.looping = true
let highPassFiltering = AKHighPassFilter(source, cutoffFrequency: 900)
let lowPassFiltering = AKLowPassFilter(highPassFiltering, cutoffFrequency: 300)
//: At this point you don't have much signal left, so you balance it against the original signal!
let rebalancedWithSource = AKBalancer(lowPassFiltering, comparator: source)
AudioKit.output = rebalancedWithSource
AudioKit.start()
source.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Balancing Nodes")
addLabel("Listen to the difference in volume:")
addSubview(AKBypassButton(node: rebalancedWithSource))
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | 0edbd8b29d5bc4adc9a92e6ce8098dde | 31.022727 | 97 | 0.748758 | 4.295732 | false | false | false | false |
nmdias/FeedKit | Tests/RSS2Tests.swift | 1 | 11275 | //
// RSS2Tests.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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 XCTest
import FeedKit
class RSS2Tests: BaseTestCase {
func testRSS2Feed() {
// Given
let URL = fileURL("RSS2", type: "xml")
let parser = FeedParser(URL: URL)
do {
// When
let feed = try parser.parse().get().rssFeed
// Then
XCTAssertNotNil(feed)
XCTAssertEqual(feed?.title, "Iris")
XCTAssertEqual(feed?.link, "http://www.iris.news/", "")
XCTAssertEqual(feed?.description, "The one place for you daily news.")
XCTAssertEqual(feed?.language, "en-us")
XCTAssertEqual(feed?.copyright, "Copyright 2015, Iris News")
XCTAssertEqual(feed?.managingEditor, "[email protected] (John Appleseed)")
XCTAssertEqual(feed?.webMaster, "[email protected] (John Appleseed)")
XCTAssertNotNil(feed?.pubDate)
XCTAssertNotNil(feed?.lastBuildDate)
XCTAssertNotNil(feed?.categories)
XCTAssertEqual(feed?.categories?.count, 2)
XCTAssertEqual(feed?.categories?.first?.value, "Media")
XCTAssertNil(feed?.categories?.first?.attributes)
XCTAssertEqual(feed?.categories?.first?.attributes?.domain, nil)
XCTAssertEqual(feed?.categories?.last?.value, "News/Media/Science")
XCTAssertNotNil(feed?.categories?.last?.attributes)
XCTAssertEqual(feed?.categories?.last?.attributes?.domain, "dmoz")
XCTAssertEqual(feed?.generator, "Iris Gen")
XCTAssertEqual(feed?.docs, "http://blogs.law.harvard.edu/tech/rss")
XCTAssertNotNil(feed?.cloud?.attributes)
XCTAssertEqual(feed?.cloud?.attributes?.domain, "server.iris.com")
XCTAssertEqual(feed?.cloud?.attributes?.path, "/rpc")
XCTAssertEqual(feed?.cloud?.attributes?.port, 80)
XCTAssertEqual(feed?.cloud?.attributes?.protocolSpecification, "xml-rpc")
XCTAssertEqual(feed?.cloud?.attributes?.registerProcedure, "cloud.notify")
XCTAssertEqual(feed?.rating, "(PICS-1.1 \"http://www.rsac.org/ratingsv01.html\" l by \"[email protected]\" on \"2007.01.29T10:09-0800\" r (n 0 s 0 v 0 l 0))")
XCTAssertEqual(feed?.ttl, 60)
XCTAssertNotNil(feed?.image)
XCTAssertEqual(feed?.image?.link, "http://www.iris.news/")
XCTAssertEqual(feed?.image?.url, "http://www.iris.news/image.jpg")
XCTAssertEqual(feed?.image?.title, "Iris")
XCTAssertEqual(feed?.image?.description, "Read the Iris news feed.")
XCTAssertEqual(feed?.image?.width, 64)
XCTAssertEqual(feed?.image?.height, 192)
XCTAssertNotNil(feed?.skipDays)
XCTAssertEqual(feed?.skipDays?.count, 2)
XCTAssertEqual(feed?.skipDays?.first, .saturday)
XCTAssertEqual(feed?.skipDays?.last, .sunday)
XCTAssertNotNil(feed?.skipHours)
XCTAssertEqual(feed?.skipHours?.count, 5)
XCTAssertEqual(feed?.skipHours?.first, 0)
XCTAssertEqual(feed?.skipHours?[1], 1)
XCTAssertEqual(feed?.skipHours?[2], 2)
XCTAssertEqual(feed?.skipHours?[3], 22)
XCTAssertEqual(feed?.skipHours?[4], 23)
XCTAssertNotNil(feed?.textInput)
XCTAssertEqual(feed?.textInput?.title, "TextInput Inquiry")
XCTAssertEqual(feed?.textInput?.description, "Your aggregator supports the textInput element. What software are you using?")
XCTAssertEqual(feed?.textInput?.name, "query")
XCTAssertEqual(feed?.textInput?.link, "http://www.iris.com/textinput.php")
} catch {
XCTFail(error.localizedDescription)
}
}
func testFeedItems() {
// Given
let URL = fileURL("RSS2", type: "xml")
let parser = FeedParser(URL: URL)
// When
do {
let feed = try parser.parse().get().rssFeed
// Then
XCTAssertNotNil(feed)
XCTAssertNotNil(feed?.items)
XCTAssertEqual(feed?.items?.count, 2)
XCTAssertEqual(feed?.items?.first?.title, "Seventh Heaven! Ryan Hurls Another No Hitter")
XCTAssertEqual(feed?.items?.first?.link, "http://dallas.example.com/1991/05/02/nolan.htm")
XCTAssertEqual(feed?.items?.first?.author, "[email protected] (Joe Bob Briggs)")
XCTAssertNotNil(feed?.items?.first?.categories)
XCTAssertEqual(feed?.items?.first?.categories?.count, 2)
XCTAssertEqual(feed?.items?.first?.categories?.first?.value, "movies")
XCTAssertNil(feed?.items?.first?.categories?.first?.attributes)
XCTAssertEqual(feed?.items?.first?.categories?.first?.attributes?.domain, nil)
XCTAssertEqual(feed?.items?.first?.categories?.last?.value, "1983/V")
XCTAssertNotNil(feed?.items?.first?.categories?.last?.attributes)
XCTAssertEqual(feed?.items?.first?.categories?.last?.attributes?.domain, "rec.arts.movies.reviews")
XCTAssertEqual(feed?.items?.first?.comments, "http://dallas.example.com/feedback/1983/06/joebob.htm")
XCTAssertEqual(feed?.items?.first?.description, "I'm headed for France. I wasn't gonna go this year, but then last week \"Valley Girl\" came out and I said to myself, Joe Bob, you gotta get out of the country for a while.")
XCTAssertNotNil(feed?.items?.first?.enclosure)
XCTAssertNotNil(feed?.items?.first?.enclosure?.attributes)
XCTAssertEqual(feed?.items?.first?.enclosure?.attributes?.length, 24986239)
XCTAssertEqual(feed?.items?.first?.enclosure?.attributes?.type, "audio/mpeg")
XCTAssertEqual(feed?.items?.first?.enclosure?.attributes?.url, "http://dallas.example.com/joebob_050689.mp3")
XCTAssertNotNil(feed?.items?.first?.guid)
XCTAssertEqual(feed?.items?.first?.guid?.value, "tag:dallas.example.com,4131:news")
XCTAssertEqual(feed?.items?.first?.guid?.attributes?.isPermaLink, false)
XCTAssertNotNil(feed?.items?.first?.pubDate)
XCTAssertNotNil(feed?.items?.first?.source)
XCTAssertEqual(feed?.items?.first?.source?.value, "Los Angeles Herald-Examiner")
XCTAssertNotNil(feed?.items?.first?.source?.attributes)
XCTAssertEqual(feed?.items?.first?.source?.attributes?.url, "http://la.example.com/rss.xml")
XCTAssertEqual(feed?.items?.last?.title, "Seventh Heaven! Ryan Hurls Another No Hitter")
XCTAssertEqual(feed?.items?.last?.link, "http://dallas.example.com/1991/05/02/nolan.htm")
XCTAssertEqual(feed?.items?.last?.author, "[email protected] (Joe Bob Briggs)")
XCTAssertNotNil(feed?.items?.last?.categories)
XCTAssertEqual(feed?.items?.last?.categories?.count, 2)
XCTAssertEqual(feed?.items?.last?.categories?.first?.value, "movies")
XCTAssertNil(feed?.items?.last?.categories?.first?.attributes)
XCTAssertEqual(feed?.items?.last?.categories?.first?.attributes?.domain, nil)
XCTAssertEqual(feed?.items?.last?.categories?.last?.value, "1983/V")
XCTAssertNotNil(feed?.items?.last?.categories?.last?.attributes)
XCTAssertEqual(feed?.items?.last?.categories?.last?.attributes?.domain, "rec.arts.movies.reviews")
XCTAssertEqual(feed?.items?.last?.comments, "http://dallas.example.com/feedback/1983/06/joebob.htm")
XCTAssertEqual(feed?.items?.last?.description, "I\'m headed for France. I wasn\'t gonna go this year, but then last week <a href=\"http://www.imdb.com/title/tt0086525/\">Valley Girl</a> came out and I said to myself, Joe Bob, you gotta get out of the country for a while.")
XCTAssertNotNil(feed?.items?.last?.enclosure)
XCTAssertNotNil(feed?.items?.last?.enclosure?.attributes)
XCTAssertEqual(feed?.items?.last?.enclosure?.attributes?.length, 24986239)
XCTAssertEqual(feed?.items?.last?.enclosure?.attributes?.type, "audio/mpeg")
XCTAssertEqual(feed?.items?.last?.enclosure?.attributes?.url, "http://dallas.example.com/joebob_050689.mp3")
XCTAssertNotNil(feed?.items?.last?.guid)
XCTAssertEqual(feed?.items?.last?.guid?.value, "http://dallas.example.com/item/1234")
XCTAssertNotNil(feed?.items?.last?.guid?.attributes)
XCTAssertEqual(feed?.items?.last?.guid?.attributes?.isPermaLink, true)
XCTAssertNotNil(feed?.items?.last?.pubDate)
XCTAssertNotNil(feed?.items?.last?.source)
XCTAssertEqual(feed?.items?.last?.source?.value, "Los Angeles Herald-Examiner")
XCTAssertNotNil(feed?.items?.last?.source?.attributes)
XCTAssertEqual(feed?.items?.last?.source?.attributes?.url, "http://la.example.com/rss.xml")
} catch {
XCTFail(error.localizedDescription)
}
}
func testRSS2FeedParsingPerformance() {
self.measure {
// Given
let expectation = self.expectation(description: "RSS2 Parsing Performance")
let URL = self.fileURL("RSS2", type: "xml")
let parser = FeedParser(URL: URL)
// When
parser.parseAsync { (result) in
// Then
expectation.fulfill()
}
self.waitForExpectations(timeout: self.timeout, handler: nil)
}
}
}
| mit | 21db7677b72ac919066015bffd1a3e9e | 48.451754 | 285 | 0.612062 | 4.602041 | false | false | false | false |
derekcoder/SwiftDevHints | SwiftDevHints/Classes/DateExtensions.swift | 2 | 12001 | //
// DateExtensions.swift
// SwiftDevHints
//
// Created by ZHOU DENGFENG on 17/12/17.
// Copyright © 2017 ZHOU DENGFENG DEREK. All rights reserved.
//
import Foundation
public extension Date {
func next(of component: Calendar.Component) -> Date? {
let calendar = Calendar.current
switch component {
case .year, .month, .day, .hour, .minute, .second:
return calendar.date(byAdding: component, value: 1, to: self)
case .weekOfYear, .weekOfMonth:
return calendar.date(byAdding: .day, value: 7, to: self)
default: return nil
}
}
func previous(of component: Calendar.Component) -> Date? {
let calendar = Calendar.current
switch component {
case .year, .month, .day, .hour, .minute, .second:
return calendar.date(byAdding: component, value: -1, to: self)
case .weekOfYear, .weekOfMonth:
return calendar.date(byAdding: .day, value: -7, to: self)
default: return nil
}
}
func beginning(of component: Calendar.Component) -> Date? {
let components: Set<Calendar.Component>
switch component {
case .year: components = [.year]
case .month: components = [.year, .month]
case .day: components = [.year, .month, .day]
case .weekOfYear, .weekOfMonth: components = [.yearForWeekOfYear, .weekOfYear]
case .hour: components = [.year, .month, .day, .hour]
case .minute: components = [.year, .month, .day, .hour, .minute]
case .second: components = [.year, .month, .day, .hour, .minute, .second]
default: components = []
}
guard !components.isEmpty else { return nil }
return Calendar.current.date(from: Calendar.current.dateComponents(components, from: self))
}
func end(of component: Calendar.Component) -> Date? {
switch component {
case .year, .month, .day, .weekOfYear, .weekOfMonth, .hour, .minute, .second:
let beginningOfNext = self.next(of: component)!.beginning(of: component)!
return beginningOfNext.previous(of: .second)
default: return nil
}
}
/// The start time of day for current date.
///
/// let today = Date() // December 17, 2017 at 5:54:46 PM GMT+8
/// let startOfToday = today.startOfDay // December 17, 2017 at 12:00:00 AM GMT+8
///
var startOfDay: Date {
return NSCalendar.current.startOfDay(for: self)
}
/// The end time of day for current date.
///
/// let today = Date() // December 17, 2017 at 5:54:46 PM GMT+8
/// let endOfToday = today.endOfDay // December 17, 2017 at 11:59:59 PM GMT+8
///
var endOfDay: Date {
return self.nextDay.startOfDay.addingTimeInterval(-1)
}
/// The next day for current date and the time is same.
///
/// let today = Date() // December 17, 2017 at 5:54:46 PM GMT+8
/// let startOfToday = today.startOfDay // December 18, 2017 at 5:54:46 PM GMT+8
///
var nextDay: Date {
return NSCalendar.current.date(byAdding: .day, value: 1, to: self)!
}
/// The previous day for current date and the time is same.
///
/// let today = Date() // December 17, 2017 at 5:54:46 PM GMT+8
/// let startOfToday = today.startOfDay // December 16, 2017 at 5:54:46 PM GMT+8
///
var previousDay: Date {
return NSCalendar.current.date(byAdding: .day, value: -1, to: self)!
}
/// The last days for current date and the time is same.
///
/// let today = Date() // December 17, 2017 at 5:54:46 PM GMT+8
/// // December 14, 2017 at 5:54:46 PM GMT+8
/// // December 15, 2017 at 5:54:46 PM GMT+8
/// // December 16, 2017 at 5:54:46 PM GMT+8
/// let last3Days = today.lastDays(withCount: 3, includingToday: false)
///
func lastDays(withCount count: Int, includingToday: Bool = true) -> [Date] {
let calendar = NSCalendar.current
var days = [Date]()
let start = includingToday ? 0 : 1
let end = includingToday ? count : count + 1
for i in start..<end {
let day = calendar.date(byAdding: .day, value: -i, to: self)!
days.append(day)
}
return days.reversed()
}
/// The next days for current date and the time is same.
///
/// let today = Date() // December 17, 2017 at 5:54:46 PM GMT+8
/// // December 17, 2017 at 5:54:46 PM GMT+8
/// // December 18, 2017 at 5:54:46 PM GMT+8
/// // December 19, 2017 at 5:54:46 PM GMT+8
/// let next3Days = today.nextDays(withCount: 3, includingToday: true)
///
func nextDays(withCount count: Int, includingToday: Bool = true) -> [Date] {
let calendar = NSCalendar.current
var days = [Date]()
let start = includingToday ? 0 : 1
let end = includingToday ? count : count + 1
for i in start..<end {
let day = calendar.date(byAdding: .day, value: i, to: self)!
days.append(day)
}
return days
}
func adding(_ comp: Calendar.Component, value: Int) -> Date {
return Calendar.current.date(byAdding: comp, value: value, to: self)!
}
mutating func add(_ comp: Calendar.Component, value: Int) {
self = adding(comp, value: value)
}
func isInSameYear(date: Date) -> Bool {
return Calendar.current.isDate(self, equalTo: date, toGranularity: .year)
}
func isInSameMonth(date: Date) -> Bool {
return Calendar.current.isDate(self, equalTo: date, toGranularity: .month)
}
func isInSameWeek(date: Date) -> Bool {
return Calendar.current.isDate(self, equalTo: date, toGranularity: .weekOfYear)
}
func isInSameDay(date: Date) -> Bool {
return Calendar.current.isDate(self, inSameDayAs: date)
}
var isToday: Bool {
return Calendar.current.isDateInToday(self)
}
var isTomorrow: Bool {
return Calendar.current.isDateInTomorrow(self)
}
var isYesterday: Bool {
return Calendar.current.isDateInYesterday(self)
}
var isWeekend: Bool {
return Calendar.current.isDateInWeekend(self)
}
var isWorkday: Bool {
return !self.isWeekend
}
var isThisWeek: Bool {
return self.isInSameWeek(date: Date())
}
var isThisMonth: Bool {
return self.isInSameMonth(date: Date())
}
var isThisYear: Bool {
return self.isInSameYear(date: Date())
}
var isFuture: Bool {
return Date() < self
}
var isPast: Bool {
return self < Date()
}
var era: Int {
return Calendar.current.component(.era, from: self)
}
var year: Int {
get { return Calendar.current.component(.year, from: self) }
set {
guard newValue > 0 else { return }
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: self)
guard let newDate = calendar.date(byAdding: .year, value: newValue - currentYear, to: self) else { return }
self = newDate
}
}
var weekOfYear: Int {
return Calendar.current.component(.weekOfYear, from: self)
}
var month: Int {
get { return Calendar.current.component(.month, from: self) }
set {
let calendar = Calendar.current
guard let rangeOfMonths = calendar.range(of: .month, in: .year, for: self) else { return }
guard rangeOfMonths.contains(newValue) else { return }
let currentMonth = calendar.component(.month, from: self)
guard let newDate = calendar.date(byAdding: .month, value: newValue - currentMonth, to: self) else { return }
self = newDate
}
}
var weekday: Int {
return Calendar.current.component(.weekday, from: self)
}
var weekOfMonth: Int {
return Calendar.current.component(.weekOfMonth, from: self)
}
var day: Int {
get { return Calendar.current.component(.day, from: self) }
set {
let calendar = Calendar.current
guard let rangeOfDays = calendar.range(of: .day, in: .month, for: self) else { return }
guard rangeOfDays.contains(newValue) else { return }
let currentDay = calendar.component(.day, from: self)
guard let newDate = calendar.date(byAdding: .day, value: newValue - currentDay, to: self) else { return }
self = newDate
}
}
var hour: Int {
get { return Calendar.current.component(.hour, from: self) }
set {
let calendar = Calendar.current
guard let rangeOfHours = calendar.range(of: .hour, in: .day, for: self) else { return }
guard rangeOfHours.contains(newValue) else { return }
let currentHour = calendar.component(.hour, from: self)
guard let newDate = calendar.date(byAdding: .hour, value: newValue - currentHour, to: self) else { return }
self = newDate
}
}
var minute: Int {
get { return Calendar.current.component(.minute, from: self) }
set {
let calendar = Calendar.current
guard let rangeOfMinutes = calendar.range(of: .minute, in: .hour, for: self) else { return }
guard rangeOfMinutes.contains(newValue) else { return }
let currentMinute = calendar.component(.minute, from: self)
guard let newDate = calendar.date(byAdding: .minute, value: newValue - currentMinute, to: self) else { return }
self = newDate
}
}
var second: Int {
get { return Calendar.current.component(.second, from: self) }
set {
let calendar = Calendar.current
guard let rangeOfSeconds = calendar.range(of: .second, in: .minute, for: self) else { return }
guard rangeOfSeconds.contains(newValue) else { return }
let currentSecond = calendar.component(.second, from: self)
guard let newDate = calendar.date(byAdding: .second, value: newValue - currentSecond, to: self) else { return }
self = newDate
}
}
var nanosecond: Int {
get { return Calendar.current.component(.nanosecond, from: self) }
set {
let calendar = Calendar.current
guard let rangeOfNanoseconds = calendar.range(of: .nanosecond, in: .second, for: self) else { return }
guard rangeOfNanoseconds.contains(newValue) else { return }
let currentNanosecond = calendar.component(.nanosecond, from: self)
guard let newDate = calendar.date(byAdding: .second, value: newValue - currentNanosecond, to: self) else { return }
self = newDate
}
}
init?(calendar: Calendar? = Calendar.current,
timeZone: TimeZone = TimeZone.current,
era: Int? = Date().era,
year: Int? = Date().year,
month: Int? = Date().month,
day: Int? = Date().day,
hour: Int? = Date().hour,
minute: Int? = Date().minute,
second: Int? = Date().second,
nanosecond: Int? = Date().nanosecond) {
var comps = DateComponents()
comps.calendar = calendar
comps.timeZone = timeZone
comps.era = era
comps.year = year
comps.month = month
comps.day = day
comps.hour = hour
comps.minute = minute
comps.second = second
comps.nanosecond = nanosecond
guard let date = calendar?.date(from: comps) else { return nil }
self = date
}
}
| mit | 326a832c27accb6c42b20e6a37e52b02 | 34.608309 | 127 | 0.576 | 4.210526 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/Theme/Theme+Configure.swift | 1 | 2206 | //
// Xcore
// Copyright © 2016 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
extension Theme {
/// A method to set system components default appearance using the given theme.
///
/// - Parameter theme: The theme to set.
public static func set(_ theme: Theme) {
self.default = theme
setSystemComponentsTheme(theme)
setComponentsTheme(theme)
}
private static func setSystemComponentsTheme(_ theme: Theme) {
UIApplication.sharedOrNil?.delegate?.window??.tintColor = theme.tintColor
UIBarButtonItem.appearance().setTitleTextAttributes(
UIViewController.defaultNavigationBarTextAttributes,
for: .normal
)
UINavigationBar.appearance().apply {
$0.titleTextAttributes = UIViewController.defaultNavigationBarTextAttributes
$0.tintColor = theme.tintColor
$0.barTintColor = theme.backgroundColor
$0.barStyle = .default
$0.isTranslucent = true
}
UIToolbar.appearance().apply {
$0.tintColor = theme.tintColor
$0.barTintColor = theme.backgroundColor
$0.barStyle = .default
$0.isTranslucent = true
}
UIPageControl.appearance().apply {
$0.pageIndicatorTintColor = .systemGray6
$0.currentPageIndicatorTintColor = theme.tintColor
$0.backgroundColor = .clear
}
UISwitch.appearance().apply {
$0.tintColor = theme.textColor.alpha(0.08)
$0.onTintColor = theme.toggleColor
}
UISlider.appearance().apply {
$0.maximumTrackTintColor = theme.textColor.alpha(0.16)
}
UITabBar.appearance().apply {
$0.tintColor = theme.tintColor
$0.borderColor = theme.separatorColor
$0.borderWidth = .onePixel
}
}
private static func setComponentsTheme(_ theme: Theme) {
BlurView.appearance().blurOpacity = 0.8
SeparatorView.appearance().tintColor = theme.separatorColor
UIViewController.defaultAppearance.apply {
$0.tintColor = theme.tintColor
}
}
}
| mit | a0b319a1291cd9a8146d91f36c1a7033 | 29.205479 | 88 | 0.61542 | 5.127907 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.