repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VikingDen/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Dialogs/DialogsSearchSource.swift
|
24
|
1245
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class DialogsSearchSource: SearchSource {
// MARK: -
// MARK: Private vars
private let DialogsListSearchCellIdentifier = "DialogsListSearchCellIdentifier"
// MARK: -
// MARK: UITableView
override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(DialogsListSearchCellIdentifier) as! DialogsSearchCell?
if cell == nil {
cell = DialogsSearchCell(reuseIdentifier: DialogsListSearchCellIdentifier)
}
return cell!;
}
override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
var searchEntity = item as! ACSearchEntity
let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section) - 1;
(cell as? DialogsSearchCell)?.bindSearchEntity(searchEntity, isLast: isLast)
}
override func buildDisplayList() -> ARBindedDisplayList {
return Actor.buildSearchDisplayList()
}
}
|
mit
|
d00048aca7754a406623d91aa0028b96
| 31.763158 | 139 | 0.681928 | 5.123457 | false | false | false | false |
Takanu/Pelican
|
Sources/Pelican/API/Request/Request+Admin.swift
|
1
|
8943
|
//
// Request+Admin.swift
// PelicanTests
//
// Created by Takanu Kyriako on 10/07/2017.
//
//
import Foundation
/**
Adds an extension that deals in creating requests for administrating a chat. The bot must be an administrator to use these requests.
*/
extension TelegramRequest {
/*
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to kick a user from a group or a supergroup. In the case of supergroups, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator
in the group for this to work. Returns True on success.
*/
public static func kickChatMember(chatID: String, userID: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
"user_id": Int(userID)
]
// Set the Request, Method and Content
request.method = "kickChatMember"
return request
}
/*
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work. Returns
True on success.
*/
public static func unbanChatMember(chatID: String, userID: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
"user_id": Int(userID)
]
// Set the Request, Method and Content
request.method = "unbanChatMember"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a
user. Returns True on success.
*/
public static func restrictChatMember(chatID: String,
userID: String,
restrictUntil: Int?,
restrictions: (msg: Bool, media: Bool, stickers: Bool, useWebPreview: Bool)?) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
"user_id": Int(userID),
"until_date": restrictUntil
]
if restrictUntil != nil { request.query["until_date"] = restrictUntil! }
if restrictions != nil {
request.query["can_send_messages"] = restrictions!.msg
request.query["can_send_media_messages"] = restrictions!.media
request.query["can_send_other_messages"] = restrictions!.stickers
request.query["can_add_web_page_previews"] = restrictions!.useWebPreview
}
// Set the Request, Method and Content
request.method = "restrictChatMember"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a
user. Returns True on success.
*/
public static func promoteChatMember(chatID: String,
userID: String,
rights: (info: Bool, msg: Bool, edit: Bool, delete: Bool, invite: Bool, restrict: Bool, pin: Bool, promote: Bool)?) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
"user_id": Int(userID),
]
if rights != nil {
request.query["can_change_info"] = rights!.info
request.query["can_post_messages"] = rights!.msg
request.query["can_edit_messages"] = rights!.edit
request.query["can_delete_messages"] = rights!.delete
request.query["can_invite_users"] = rights!.invite
request.query["can_restrict_members"] = rights!.restrict
request.query["can_pin_messages"] = rights!.pin
request.query["can_promote_members"] = rights!.promote
}
// Set the Request, Method and Content
request.method = "promoteChatMember"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns exported invite link as String on success.
*/
public static func exportChatInviteLink(chatID: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
]
// Set the Request, Method and Content
request.method = "exportChatInviteLink"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
- note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.
*/
public static func setChatPhoto(chatID: String, file: MessageFile) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
]
// Set the Request, Method and Content
request.method = "setChatPhoto"
request.file = file
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
- note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.
*/
public static func deleteChatPhoto(chatID: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
]
// Set the Request, Method and Content
request.method = "deleteChatPhoto"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*/
public static func setChatTitle(chatID: String, title: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
"title": title
]
// Set the Request, Method and Content
request.method = "setChatTitle"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*/
public static func setChatDescription(chatID: String, description: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
"description": description
]
// Set the Request, Method and Content
request.method = "setChatTitle"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*/
public static func pinChatMessage(chatID: String, messageID: Int, disableNotification: Bool = false) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
"message_id": messageID,
"disable_notification": disableNotification
]
// Set the Request, Method and Content
request.method = "pinChatMessage"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to unpin a message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*/
public static func unpinChatMessage(chatID: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": Int(chatID),
]
// Set the Request, Method and Content
request.method = "unpinChatMessage"
return request
}
}
|
mit
|
519b89cf859b8888cb3a80952b659d5e
| 31.97048 | 233 | 0.713598 | 3.995975 | false | false | false | false |
Rafaj-Design/DDDestroyer
|
DDDestroyer/AppDelegate.swift
|
1
|
3035
|
//
// AppDelegate.swift
// DDDestroyer
//
// Created by Rafaj Design on 22/03/2017.
// Copyright © 2017 Rafaj Design. All rights reserved.
//
import Cocoa
import AppKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var statusItem: NSStatusItem?
var menuItems: [NSMenuItem] = []
var subDirectories: [URL] = []
var derivedFolderUrl: URL {
let home: String = NSHomeDirectory()
var url: URL = URL.init(fileURLWithPath: home)
url.appendPathComponent("Library/Developer/Xcode/DerivedData")
return url
}
// MARK: Application delegate methods
func applicationDidFinishLaunching(_ aNotification: Notification) {
self.statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
self.statusItem?.image = NSImage(named: "icon")
self.statusItem?.image?.isTemplate = true
self.statusItem?.action = #selector(AppDelegate.didTapStatusBarIcon)
}
// MARK: Actions
func didTapStatusBarIcon() {
let menu: NSMenu = NSMenu.init()
var item: NSMenuItem = NSMenuItem.init(title: "Clear ALL", action: #selector(AppDelegate.deleteAll), keyEquivalent: "")
menu.addItem(item)
menu.addItem(NSMenuItem.separator())
self.subDirectories = self.derivedFolderUrl.subDirectories
self.menuItems = []
for url: URL in self.subDirectories {
var components: [String] = url.lastPathComponent.components(separatedBy: "-")
if components.count > 1 {
components.removeLast()
}
let title = components.joined(separator: "-")
item = NSMenuItem.init(title: title, action: #selector(AppDelegate.deleteOne), keyEquivalent: "")
menu.addItem(item)
self.menuItems.append(item)
}
menu.addItem(NSMenuItem.separator())
item = NSMenuItem.init(title: "Open folder ...", action: #selector(AppDelegate.openFolder), keyEquivalent: "")
menu.addItem(item)
self.statusItem?.popUpMenu(menu)
}
func deleteAll() {
self.deleteDerivedData()
}
func deleteOne(sender: NSMenuItem) {
let index: Int = self.menuItems.index(of: sender)!
let url: URL = self.subDirectories[index]
self.deleteDerivedData(url.lastPathComponent)
}
// MARK: Working with derived data
func openFolder() {
NSWorkspace.shared().selectFile(nil, inFileViewerRootedAtPath: self.derivedFolderUrl.path)
}
func deleteDerivedData(_ subfolder: String? = nil) {
do {
var url: URL = self.derivedFolderUrl
if subfolder != nil {
url.appendPathComponent(subfolder!)
}
try FileManager.default.removeItem(at: url)
}
catch {
print(error)
}
}
}
|
mit
|
8d8493e3ef4a641818fde8bd949d7150
| 29.34 | 127 | 0.612722 | 4.793049 | false | false | false | false |
padawan/smartphone-app
|
MT_iOS/MT_iOS/Classes/ViewController/EntryHTMLEditorViewController.swift
|
1
|
7114
|
//
// EntryHTMLEditorViewController.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/05.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
import ZSSRichTextEditor
class EntryHTMLEditorViewController: BaseViewController, UITextViewDelegate, AddAssetDelegate {
var sourceView: ZSSTextView!
var object: EntryTextAreaItem!
var blog: Blog!
var entry: BaseEntry!
override func viewDidLoad() {
super.viewDidLoad()
self.title = object.label
// Do any additional setup after loading the view.
self.sourceView = ZSSTextView(frame: self.view.bounds)
self.sourceView.autocapitalizationType = UITextAutocapitalizationType.None
self.sourceView.autocorrectionType = UITextAutocorrectionType.No
//self.sourceView.font = UIFont.systemFontOfSize(16.0)
self.sourceView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
self.sourceView.autoresizesSubviews = true
self.sourceView.delegate = self
self.view.addSubview(self.sourceView)
self.sourceView.text = object.text
self.sourceView.selectedRange = NSRange()
let toolBar = UIToolbar(frame: CGRectMake(0.0, 0.0, self.view.frame.size.width, 44.0))
let cameraButton = UIBarButtonItem(image: UIImage(named: "btn_camera"), left: true, target: self, action: "cameraButtonPushed:")
let flexibleButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var previewButton = UIBarButtonItem(image: UIImage(named: "btn_preview"), style: UIBarButtonItemStyle.Plain, target: self, action: "previewButtonPushed:")
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "doneButtonPushed:")
if object is BlockTextItem {
toolBar.items = [flexibleButton, previewButton, doneButton]
} else {
toolBar.items = [cameraButton, flexibleButton, previewButton, doneButton]
}
self.sourceView.inputAccessoryView = toolBar
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "saveButtonPushed:")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_arw"), left: true, target: self, action: "backButtonPushed:")
self.sourceView.becomeFirstResponder()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func keyboardWillShow(notification: NSNotification) {
var info = notification.userInfo!
var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
var insets = self.sourceView.contentInset
insets.bottom = keyboardFrame.size.height
UIView.animateWithDuration(duration, animations:
{_ in
self.sourceView.contentInset = insets;
}
)
}
func keyboardWillHide(notification: NSNotification) {
var info = notification.userInfo!
var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
var insets = self.sourceView.contentInset
insets.bottom = 0
UIView.animateWithDuration(duration, animations:
{_ in
self.sourceView.contentInset = insets;
}
)
}
@IBAction func saveButtonPushed(sender: UIBarButtonItem) {
object.text = sourceView.text
object.isDirty = true
self.navigationController?.popViewControllerAnimated(true)
}
@IBAction func doneButtonPushed(sender: UIBarButtonItem) {
self.sourceView.resignFirstResponder()
}
private func showAssetSelector() {
let storyboard: UIStoryboard = UIStoryboard(name: "ImageSelector", bundle: nil)
let nav = storyboard.instantiateInitialViewController() as! UINavigationController
let vc = nav.topViewController as! ImageSelectorTableViewController
vc.blog = blog
vc.delegate = self
vc.showAlign = true
vc.object = EntryImageItem()
vc.entry = entry
self.presentViewController(nav, animated: true, completion: nil)
}
@IBAction func cameraButtonPushed(sender: UIBarButtonItem) {
self.showAssetSelector()
}
func AddAssetDone(controller: AddAssetTableViewController, asset: Asset) {
self.dismissViewControllerAnimated(true, completion: nil)
let vc = controller as! ImageSelectorTableViewController
let item = vc.object
item.asset = asset
let align = controller.imageAlign
object.assets.append(asset)
self.sourceView.replaceRange(self.sourceView.selectedTextRange!, withText: asset.imageHTML(align))
}
@IBAction func backButtonPushed(sender: UIBarButtonItem) {
if self.sourceView.text == object.text {
self.navigationController?.popViewControllerAnimated(true)
return
}
Utils.confrimSave(self)
}
@IBAction func previewButtonPushed(sender: UIBarButtonItem) {
let vc = PreviewViewController()
let nav = UINavigationController(rootViewController: vc)
var html = "<!DOCTYPE html><html><head><title>Preview</title><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"></head><body>"
html += self.sourceView.text
html += "</body></html>"
vc.html = html
self.presentViewController(nav, animated: true, completion: nil)
}
}
|
mit
|
30adad99282aa3232baa6adf3cd73bf3
| 40.348837 | 162 | 0.686586 | 5.343351 | false | false | false | false |
apple/swift-corelibs-foundation
|
Sources/FoundationNetworking/URLProtectionSpace.swift
|
1
|
13918
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
/*!
@const NSURLProtectionSpaceHTTP
@abstract The protocol for HTTP
*/
public let NSURLProtectionSpaceHTTP: String = "NSURLProtectionSpaceHTTP"
/*!
@const NSURLProtectionSpaceHTTPS
@abstract The protocol for HTTPS
*/
public let NSURLProtectionSpaceHTTPS: String = "NSURLProtectionSpaceHTTPS"
/*!
@const NSURLProtectionSpaceFTP
@abstract The protocol for FTP
*/
public let NSURLProtectionSpaceFTP: String = "NSURLProtectionSpaceFTP"
/*!
@const NSURLProtectionSpaceHTTPProxy
@abstract The proxy type for http proxies
*/
public let NSURLProtectionSpaceHTTPProxy: String = "NSURLProtectionSpaceHTTPProxy"
/*!
@const NSURLProtectionSpaceHTTPSProxy
@abstract The proxy type for https proxies
*/
public let NSURLProtectionSpaceHTTPSProxy: String = "NSURLProtectionSpaceHTTPSProxy"
/*!
@const NSURLProtectionSpaceFTPProxy
@abstract The proxy type for ftp proxies
*/
public let NSURLProtectionSpaceFTPProxy: String = "NSURLProtectionSpaceFTPProxy"
/*!
@const NSURLProtectionSpaceSOCKSProxy
@abstract The proxy type for SOCKS proxies
*/
public let NSURLProtectionSpaceSOCKSProxy: String = "NSURLProtectionSpaceSOCKSProxy"
/*!
@const NSURLAuthenticationMethodDefault
@abstract The default authentication method for a protocol
*/
public let NSURLAuthenticationMethodDefault: String = "NSURLAuthenticationMethodDefault"
/*!
@const NSURLAuthenticationMethodHTTPBasic
@abstract HTTP basic authentication. Equivalent to
NSURLAuthenticationMethodDefault for http.
*/
public let NSURLAuthenticationMethodHTTPBasic: String = "NSURLAuthenticationMethodHTTPBasic"
/*!
@const NSURLAuthenticationMethodHTTPDigest
@abstract HTTP digest authentication.
*/
public let NSURLAuthenticationMethodHTTPDigest: String = "NSURLAuthenticationMethodHTTPDigest"
/*!
@const NSURLAuthenticationMethodHTMLForm
@abstract HTML form authentication. Applies to any protocol.
*/
public let NSURLAuthenticationMethodHTMLForm: String = "NSURLAuthenticationMethodHTMLForm"
/*!
@const NSURLAuthenticationMethodNTLM
@abstract NTLM authentication.
*/
public let NSURLAuthenticationMethodNTLM: String = "NSURLAuthenticationMethodNTLM"
/*!
@const NSURLAuthenticationMethodNegotiate
@abstract Negotiate authentication.
*/
public let NSURLAuthenticationMethodNegotiate: String = "NSURLAuthenticationMethodNegotiate"
/*!
@const NSURLAuthenticationMethodClientCertificate
@abstract SSL Client certificate. Applies to any protocol.
*/
@available(*, deprecated, message: "swift-corelibs-foundation does not currently support certificate authentication.")
public let NSURLAuthenticationMethodClientCertificate: String = "NSURLAuthenticationMethodClientCertificate"
/*!
@const NSURLAuthenticationMethodServerTrust
@abstract SecTrustRef validation required. Applies to any protocol.
*/
@available(*, deprecated, message: "swift-corelibs-foundation does not support methods of authentication that rely on the Darwin Security framework.")
public let NSURLAuthenticationMethodServerTrust: String = "NSURLAuthenticationMethodServerTrust"
/*!
@class URLProtectionSpace
@discussion This class represents a protection space requiring authentication.
*/
open class URLProtectionSpace : NSObject, NSCopying {
private let _host: String
private let _isProxy: Bool
private let _proxyType: String?
private let _port: Int
private let _protocol: String?
private let _realm: String?
private let _authenticationMethod: String
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self // These instances are immutable.
}
/*!
@method initWithHost:port:protocol:realm:authenticationMethod:
@abstract Initialize a protection space representing an origin server, or a realm on one
@param host The hostname of the server
@param port The port for the server
@param protocol The sprotocol for this server - e.g. "http", "ftp", "https"
@param realm A string indicating a protocol-specific subdivision
of a single host. For http and https, this maps to the realm
string in http authentication challenges. For many other protocols
it is unused.
@param authenticationMethod The authentication method to use to access this protection space -
valid values include nil (default method), @"digest" and @"form".
@result The initialized object.
*/
public init(host: String, port: Int, protocol: String?, realm: String?, authenticationMethod: String?) {
_host = host
_port = port
_protocol = `protocol`
_realm = realm
_authenticationMethod = authenticationMethod ?? NSURLAuthenticationMethodDefault
_proxyType = nil
_isProxy = false
}
/*!
@method initWithProxyHost:port:type:realm:authenticationMethod:
@abstract Initialize a protection space representing a proxy server, or a realm on one
@param host The hostname of the proxy server
@param port The port for the proxy server
@param type The type of proxy - e.g. "http", "ftp", "SOCKS"
@param realm A string indicating a protocol-specific subdivision
of a single host. For http and https, this maps to the realm
string in http authentication challenges. For many other protocols
it is unused.
@param authenticationMethod The authentication method to use to access this protection space -
valid values include nil (default method) and @"digest"
@result The initialized object.
*/
public init(proxyHost host: String, port: Int, type: String?, realm: String?, authenticationMethod: String?) {
_host = host
_port = port
_proxyType = type
_realm = realm
_authenticationMethod = authenticationMethod ?? NSURLAuthenticationMethodDefault
_isProxy = true
_protocol = nil
}
/*!
@method realm
@abstract Get the authentication realm for which the protection space that
needs authentication
@discussion This is generally only available for http
authentication, and may be nil otherwise.
@result The realm string
*/
open var realm: String? {
return _realm
}
/*!
@method receivesCredentialSecurely
@abstract Determine if the password for this protection space can be sent securely
@result YES if a secure authentication method or protocol will be used, NO otherwise
*/
open var receivesCredentialSecurely: Bool {
switch self.protocol {
// The documentation is ambiguous whether a protection space needs to use the NSURLProtectionSpace… constants, or URL schemes.
// Allow both.
case NSURLProtectionSpaceHTTPS: fallthrough
case "https": fallthrough
case "ftps":
return true
default:
switch authenticationMethod {
case NSURLAuthenticationMethodDefault: fallthrough
case NSURLAuthenticationMethodHTTPBasic: fallthrough
case NSURLAuthenticationMethodHTTPDigest: fallthrough
case NSURLAuthenticationMethodHTMLForm:
return false
case NSURLAuthenticationMethodNTLM: fallthrough
case NSURLAuthenticationMethodNegotiate: fallthrough
case NSURLAuthenticationMethodClientCertificate: fallthrough
case NSURLAuthenticationMethodServerTrust:
return true
default:
return false
}
}
}
/*!
@method host
@abstract Get the proxy host if this is a proxy authentication, or the host from the URL.
@result The host for this protection space.
*/
open var host: String {
return _host
}
/*!
@method port
@abstract Get the proxy port if this is a proxy authentication, or the port from the URL.
@result The port for this protection space, or 0 if not set.
*/
open var port: Int {
return _port
}
/*!
@method proxyType
@abstract Get the type of this protection space, if a proxy
@result The type string, or nil if not a proxy.
*/
open var proxyType: String? {
return _proxyType
}
/*!
@method protocol
@abstract Get the protocol of this protection space, if not a proxy
@result The type string, or nil if a proxy.
*/
open var `protocol`: String? {
return _protocol
}
/*!
@method authenticationMethod
@abstract Get the authentication method to be used for this protection space
@result The authentication method
*/
open var authenticationMethod: String {
return _authenticationMethod
}
/*!
@method isProxy
@abstract Determine if this authenticating protection space is a proxy server
@result YES if a proxy, NO otherwise
*/
open override func isProxy() -> Bool {
return _isProxy
}
/*!
A string that represents the contents of the URLProtectionSpace Object.
This property is intended to produce readable output.
*/
open override var description: String {
let authMethods: Set<String> = [
NSURLAuthenticationMethodDefault,
NSURLAuthenticationMethodHTTPBasic,
NSURLAuthenticationMethodHTTPDigest,
NSURLAuthenticationMethodHTMLForm,
NSURLAuthenticationMethodNTLM,
NSURLAuthenticationMethodNegotiate,
NSURLAuthenticationMethodClientCertificate,
NSURLAuthenticationMethodServerTrust
]
var result = "<\(type(of: self)) \(Unmanaged.passUnretained(self).toOpaque())>: "
result += "Host:\(host), "
if let prot = self.protocol {
result += "Server:\(prot), "
} else {
result += "Server:(null), "
}
if authMethods.contains(self.authenticationMethod) {
result += "Auth-Scheme:\(self.authenticationMethod), "
} else {
result += "Auth-Scheme:NSURLAuthenticationMethodDefault, "
}
if let realm = self.realm {
result += "Realm:\(realm), "
} else {
result += "Realm:(null), "
}
result += "Port:\(self.port), "
if _isProxy {
result += "Proxy:YES, "
} else {
result += "Proxy:NO, "
}
if let proxyType = self.proxyType {
result += "Proxy-Type:\(proxyType), "
} else {
result += "Proxy-Type:(null)"
}
return result
}
}
extension URLProtectionSpace {
//an internal helper to create a URLProtectionSpace from a HTTPURLResponse
static func create(with response: HTTPURLResponse) -> URLProtectionSpace? {
// Using first challenge, as we don't support multiple challenges yet
guard let challenge = _HTTPURLProtocol._HTTPMessage._Challenge.challenges(from: response).first else {
return nil
}
guard let url = response.url, let host = url.host, let proto = url.scheme, proto == "http" || proto == "https" else {
return nil
}
let port = url.port ?? (proto == "http" ? 80 : 443)
return URLProtectionSpace(host: host,
port: port,
protocol: proto,
realm: challenge.parameter(withName: "realm")?.value,
authenticationMethod: challenge.authenticationMethod)
}
}
extension _HTTPURLProtocol._HTTPMessage._Challenge {
var authenticationMethod: String? {
if authScheme.caseInsensitiveCompare(_HTTPURLProtocol._HTTPMessage._Challenge.AuthSchemeBasic) == .orderedSame {
return NSURLAuthenticationMethodHTTPBasic
} else if authScheme.caseInsensitiveCompare(_HTTPURLProtocol._HTTPMessage._Challenge.AuthSchemeDigest) == .orderedSame {
return NSURLAuthenticationMethodHTTPDigest
} else {
return nil
}
}
}
extension URLProtectionSpace {
/*!
@method distinguishedNames
@abstract Returns an array of acceptable certificate issuing authorities for client certification authentication. Issuers are identified by their distinguished name and returned as a DER encoded data.
@result An array of NSData objects. (Nil if the authenticationMethod is not NSURLAuthenticationMethodClientCertificate)
*/
@available(*, deprecated, message: "swift-corelibs-foundation does not currently support certificate authentication.")
public var distinguishedNames: [Data]? { return nil }
/*!
@method serverTrust
@abstract Returns a SecTrustRef which represents the state of the servers SSL transaction state
@result A SecTrustRef from Security.framework. (Nil if the authenticationMethod is not NSURLAuthenticationMethodServerTrust)
*/
@available(*, unavailable, message: "swift-corelibs-foundation does not support methods of authentication that rely on the Darwin Security framework.")
public var serverTrust: Any? { NSUnsupported() }
}
|
apache-2.0
|
0490cab297a755bb2f99835d823e1577
| 35.524934 | 208 | 0.675266 | 5.487382 | false | false | false | false |
nuclearace/Starscream
|
examples/SimpleTest/SimpleTest/ViewController.swift
|
2
|
1784
|
//
// ViewController.swift
// SimpleTest
//
// Created by Dalton Cherry on 8/12/14.
// Copyright (c) 2014 vluxe. All rights reserved.
//
import UIKit
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
var socket: WebSocket!
override func viewDidLoad() {
super.viewDidLoad()
var request = URLRequest(url: URL(string: "http://localhost:8080")!)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket.delegate = self
socket.connect()
}
// MARK: Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocketClient) {
print("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
if let e = error as? WSError {
print("websocket is disconnected: \(e.message)")
} else if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
print("Received text: \(text)")
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
print("Received data: \(data.count)")
}
// MARK: Write Text Action
@IBAction func writeText(_ sender: UIBarButtonItem) {
socket.write(string: "hello there!")
}
// MARK: Disconnect Action
@IBAction func disconnect(_ sender: UIBarButtonItem) {
if socket.isConnected {
sender.title = "Connect"
socket.disconnect()
} else {
sender.title = "Disconnect"
socket.connect()
}
}
}
|
apache-2.0
|
8bd89e422c892f5bda54044bacbc23f0
| 25.626866 | 76 | 0.600336 | 4.901099 | false | false | false | false |
alexanderedge/European-Sports
|
EurosportKit/Parsers/TokenParser.swift
|
1
|
1772
|
//
// TokenParser.swift
// EurosportPlayer
//
// Created by Alexander Edge on 14/05/2016.
import Foundation
internal struct TokenParser: JSONParsingType {
typealias T = Token
enum TokenError: Error {
case invalidToken
case invalidHdnts
case invalidExpiryTimeInSeconds
case invalidExpiryTimestamp
case invalidStartTimestamp
}
static func parse(_ json: [String : Any]) throws -> T {
let query: String = try json.extract("token")
var parsedToken: String?
var parsedHdnts: String?
var urlComponents = URLComponents()
urlComponents.query = query
if let queryItems = urlComponents.queryItems {
for queryItem in queryItems {
switch queryItem.name {
case "token":
parsedToken = queryItem.value
break
case "hdnts":
parsedHdnts = queryItem.value?.removingPercentEncoding
break
default:
break
}
}
}
let duration: TimeInterval = try json.extract("expiretimeinseconds")
let expiryTimestamp: TimeInterval = try json.extract("expiretimestamp")
let startTimestamp: TimeInterval = try json.extract("starttimestamp")
guard let token = parsedToken else {
throw TokenError.invalidToken
}
guard let hdnts = parsedHdnts else {
throw TokenError.invalidHdnts
}
return Token(token: token, hdnts: hdnts, startDate: Date(timeIntervalSince1970: startTimestamp), expiryDate: Date(timeIntervalSince1970: expiryTimestamp), duration: duration)
}
}
|
mit
|
e3c2619d718443039c4b64aaad912d5c
| 28.533333 | 182 | 0.590858 | 5.27381 | false | false | false | false |
xedin/swift
|
test/Driver/opt-remark.swift
|
13
|
1379
|
// RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -O %s -o %t/throwaway 2>&1 | %FileCheck -allow-empty -check-prefix=DEFAULT %s
// RUN: %target-swiftc_driver -O -Rpass=sil-inliner %s -o %t/throwaway 2>&1 | %FileCheck -check-prefix=REMARK_PASSED %s
// RUN: %target-swiftc_driver -O -Rpass-missed=sil-inliner %s -o %t/throwaway 2>&1 | %FileCheck -check-prefix=REMARK_MISSED %s
// DEFAULT-NOT: remark:
func big() {
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
}
func small() {
print("hello")
}
func foo() {
// REMARK_MISSED-NOT: remark: {{.*}} inlined
// REMARK_MISSED: opt-remark.swift:44:2: remark: Not profitable to inline function "throwaway.big()" (cost = {{.*}}, benefit = {{.*}})
// REMARK_MISSED-NOT: remark: {{.*}} inlined
big()
// REMARK_PASSED-NOT: remark: Not profitable
// REMARK_PASSED: opt-remark.swift:48:3: remark: "throwaway.small()" inlined into "throwaway.foo()" (cost = {{.*}}, benefit = {{.*}})
// REMARK_PASSED-NOT: remark: Not profitable
small()
}
|
apache-2.0
|
0ca56e2abf435242acf0de19cf8b6bf7
| 27.142857 | 136 | 0.628716 | 3.064444 | false | false | false | false |
ibm-cloud-security/appid-clientsdk-swift
|
Source/IBMCloudAppID/internal/tokens/IdentityTokenImpl.swift
|
1
|
868
|
import Foundation
internal class IdentityTokenImpl: AbstractToken, IdentityToken {
private static let NAME = "name"
private static let EMAIL = "email"
private static let GENDER = "gender"
private static let LOCALE = "locale"
private static let PICTURE = "picture"
private static let IDENTITIES = "identities"
var name: String? {
return payload[IdentityTokenImpl.NAME] as? String
}
var email: String? {
return payload[IdentityTokenImpl.EMAIL] as? String
}
var gender: String? {
return payload[IdentityTokenImpl.GENDER] as? String
}
var locale: String? {
return payload[IdentityTokenImpl.LOCALE] as? String
}
var picture: String? {
return payload[IdentityTokenImpl.PICTURE] as? String
}
var identities: Array<Dictionary<String, Any>>? {
return payload[IdentityTokenImpl.IDENTITIES] as? Array<Dictionary<String, Any>>
}
}
|
apache-2.0
|
165e514619cb2e2ea3e2262a7e5ec13e
| 23.8 | 87 | 0.735023 | 3.557377 | false | false | false | false |
KolitOffice/ITUtility
|
ITUtility/ITUtility.swift
|
1
|
3967
|
//
// ITUtility.swift
// AISCamp
//
// Created by Itsaraporn Chaichayanon on 3/9/2558 BE.
// Copyright (c) 2558 AIS (SAND-DLD). All rights reserved.
//
import UIKit
private var _callback: (() -> Void)?
class ITUtility: NSObject {
class func writeLogData (tag: String, data: NSData?, file:String, function:String, line:Int) {
#if DEBUG
var message: NSString = "Data nil"
if let dataValue = data {
message = NSString(data: dataValue, encoding: NSUTF8StringEncoding)!
}
print("")
print("+\(tag)+++++++++ : \(NSDate())")
print("File : \(file)")
print("Function : \(function)")
print("Line : \(line)")
print("Message : \(message)")
print("----------")
print("")
#endif
}
class func writeLogString (tag: String, message: NSString, file:String = __FILE__, fnc:String = __FUNCTION__, line:(Int)=__LINE__) {
#if DEBUG
print("")
print("+\(tag)+++++++++ : \(NSDate())")
print("File : \(file)")
print("Function : \(fnc)")
print("Line : \(line)")
print("Message : \(message)")
print("----------")
print("")
#endif
}
class func convertStringToDate(datestring: NSString, format: NSString, timezone: NSString, locale: NSString) -> NSDate{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format as String
dateFormatter.timeZone = NSTimeZone(name: timezone as String)
dateFormatter.locale = NSLocale(localeIdentifier: locale as String)
return dateFormatter.dateFromString(datestring as String)!
}
class func convertDateToString(date: NSDate, format: NSString, timezone: NSString, locale: NSString) -> NSString{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format as String
dateFormatter.timeZone = NSTimeZone(name: timezone as String)
dateFormatter.locale = NSLocale(localeIdentifier: locale as String)
return dateFormatter.stringFromDate(date)
}
class func downloadImage(urlstring: NSString, completion: ((data: NSData?) -> Void)) -> NSURLSessionDataTask? {
if(urlstring == "") {
completion(data: nil)
return nil
}
let url: NSURL = NSURL(string: urlstring as String)!
let sessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {
(data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
completion(data: NSData(data: data!))
}
})
sessionDataTask.resume()
return sessionDataTask
}
class func isValidEmail(testStr:String) -> Bool {
let regex = try? NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: .CaseInsensitive)
return regex?.firstMatchInString(testStr, options: [], range: NSMakeRange(0, testStr.characters.count)) != nil
}
class func getCurrentVersionNumber() -> NSString {
let mainBundle = NSBundle.mainBundle()
let buildNumber: NSString = mainBundle.objectForInfoDictionaryKey("CFBundleVersion") as! NSString
let versionNumber: NSString = mainBundle.objectForInfoDictionaryKey("CFBundleShortVersionString") as! NSString
return NSString(format: "v.%@ (%@)", versionNumber , buildNumber)
}
class func setDropShadowOnBottom (view onview: UIView?, color: UIColor, radius: CGFloat, opacity: Float) {
if let view = onview {
view.layer.shadowColor = color.CGColor
view.layer.shadowOffset = CGSizeMake(0, 1.0)
view.layer.shadowOpacity = opacity
view.layer.shadowRadius = radius
}
}
}
|
mit
|
0e21933391bef5e0253346af73450b06
| 37.514563 | 137 | 0.585833 | 4.873464 | false | false | false | false |
ncalexan/firefox-ios
|
ClientTests/MockProfile.swift
|
1
|
6971
|
/* 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/. */
@testable import Client
import Foundation
import Account
import ReadingList
import Shared
import Storage
import Sync
import XCTest
import Deferred
open class MockSyncManager: SyncManager {
open var isSyncing = false
open var lastSyncFinishTime: Timestamp?
open var syncDisplayState: SyncDisplayState?
open func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
private func completedWithStats(collection: String) -> Deferred<Maybe<SyncStatus>> {
return deferMaybe(SyncStatus.completed(SyncEngineStatsSession(collection: collection)))
}
open func syncClients() -> SyncResult { return completedWithStats(collection: "mock_clients") }
open func syncClientsThenTabs() -> SyncResult { return completedWithStats(collection: "mock_clientsandtabs") }
open func syncHistory() -> SyncResult { return completedWithStats(collection: "mock_history") }
open func syncLogins() -> SyncResult { return completedWithStats(collection: "mock_logins") }
open func syncEverything(why: SyncReason) -> Success {
return succeed()
}
open func syncNamedCollections(why: SyncReason, names: [String]) -> Success {
return succeed()
}
open func beginTimedSyncs() {}
open func endTimedSyncs() {}
open func applicationDidBecomeActive() {
self.beginTimedSyncs()
}
open func applicationDidEnterBackground() {
self.endTimedSyncs()
}
open func onNewProfile() {
}
open func onAddedAccount() -> Success {
return succeed()
}
open func onRemovedAccount(_ account: FirefoxAccount?) -> Success {
return succeed()
}
open func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
}
open class MockTabQueue: TabQueue {
open func addToQueue(_ tab: ShareItem) -> Success {
return succeed()
}
open func getQueuedTabs() -> Deferred<Maybe<Cursor<ShareItem>>> {
return deferMaybe(ArrayCursor<ShareItem>(data: []))
}
open func clearQueuedTabs() -> Success {
return succeed()
}
}
open class MockPanelDataObservers: PanelDataObservers {
override init(profile: Profile) {
super.init(profile: profile)
self.activityStream = MockActivityStreamDataObserver(profile: profile)
}
}
open class MockActivityStreamDataObserver: DataObserver {
public var profile: Profile
public weak var delegate: DataObserverDelegate?
init(profile: Profile) {
self.profile = profile
}
public func refreshIfNeeded(forceHighlights highlights: Bool, forceTopSites topsites: Bool) {
}
}
open class MockProfile: Profile {
// Read/Writeable properties for mocking
public var recommendations: HistoryRecommendations
public var places: BrowserHistory & Favicons & SyncableHistory & ResettableSyncStorage & HistoryRecommendations
public var files: FileAccessor
public var history: BrowserHistory & SyncableHistory & ResettableSyncStorage
public var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage
public var syncManager: SyncManager!
public lazy var panelDataObservers: PanelDataObservers = {
return MockPanelDataObservers(profile: self)
}()
var db: BrowserDB
fileprivate let name: String = "mockaccount"
init() {
files = MockFiles()
syncManager = MockSyncManager()
logins = MockLogins(files: files)
db = BrowserDB(filename: "mock.db", schema: BrowserSchema(), files: files)
places = SQLiteHistory(db: self.db, prefs: MockProfilePrefs())
recommendations = places
history = places
}
public func localName() -> String {
return name
}
public func reopen() {
}
public func shutdown() {
}
public var isShutdown: Bool = false
public var favicons: Favicons {
return self.places
}
lazy public var queue: TabQueue = {
return MockTabQueue()
}()
lazy public var metadata: Metadata = {
return SQLiteMetadata(db: self.db)
}()
lazy public var isChinaEdition: Bool = {
return Locale.current.identifier == "zh_CN"
}()
lazy public var certStore: CertStore = {
return CertStore()
}()
lazy public var bookmarks: BookmarksModelFactorySource & KeywordSearchSource & SyncableBookmarks & LocalItemSource & MirrorItemSource & ShareToDestination = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
let p = self.places
return MergedSQLiteBookmarks(db: self.db)
}()
lazy public var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs, files: self.files)
}()
lazy public var prefs: Prefs = {
return MockProfilePrefs()
}()
lazy public var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
lazy public var recentlyClosedTabs: ClosedTabsStore = {
return ClosedTabsStore(prefs: self.prefs)
}()
internal lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
fileprivate lazy var syncCommands: SyncCommands = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
public let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount?
public func hasAccount() -> Bool {
return account != nil
}
public func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.none
}
public func getAccount() -> FirefoxAccount? {
return account
}
public func setAccount(_ account: FirefoxAccount) {
self.account = account
self.syncManager.onAddedAccount()
}
public func flushAccount() {}
public func removeAccount() {
let old = self.account
self.account = nil
self.syncManager.onRemovedAccount(old)
}
public func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return deferMaybe([])
}
public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
public func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return deferMaybe(0)
}
public func sendItems(_ items: [ShareItem], toClients clients: [RemoteClient]) -> Deferred<Maybe<SyncStatus>> {
return deferMaybe(SyncStatus.notStarted(.offline))
}
}
|
mpl-2.0
|
3a3eb9938e7e86389200d9ecdabf8cf4
| 28.790598 | 162 | 0.675943 | 5.110704 | false | false | false | false |
hyperconnect/Bond
|
Bond/Bond+Foundation.swift
|
1
|
5076
|
//
// Bond+Foundation.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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
private var XXContext = 0
@objc private class DynamicKVOHelper: NSObject {
let listener: AnyObject -> Void
weak var object: NSObject?
let keyPath: String
init(keyPath: String, object: NSObject, listener: AnyObject -> Void) {
self.keyPath = keyPath
self.object = object
self.listener = listener
super.init()
self.object?.addObserver(self, forKeyPath: keyPath, options: .New, context: &XXContext)
}
deinit {
object?.removeObserver(self, forKeyPath: keyPath)
}
override dynamic func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == &XXContext {
if let newValue: AnyObject = change[NSKeyValueChangeNewKey] {
listener(newValue)
}
}
}
}
@objc private class DynamicNotificationCenterHelper: NSObject {
let listener: NSNotification -> Void
init(notificationName: String, object: AnyObject?, listener: NSNotification -> Void) {
self.listener = listener
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveNotification:", name: notificationName, object: object)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
dynamic func didReceiveNotification(notification: NSNotification) {
listener(notification)
}
}
public func dynamicObservableFor<T>(object: NSObject, #keyPath: String, #defaultValue: T) -> Dynamic<T> {
let keyPathValue: AnyObject? = object.valueForKeyPath(keyPath)
let value: T = (keyPathValue != nil) ? (keyPathValue as? T)! : defaultValue
let dynamic = InternalDynamic(value)
let helper = DynamicKVOHelper(keyPath: keyPath, object: object as NSObject) {
[unowned dynamic] (v: AnyObject) -> Void in
dynamic.updatingFromSelf = true
if v is NSNull {
dynamic.value = defaultValue
} else {
dynamic.value = (v as? T)!
}
dynamic.updatingFromSelf = false
}
dynamic.retain(helper)
return dynamic
}
public func dynamicObservableFor<T>(object: NSObject, #keyPath: String, #from: AnyObject? -> T, #to: T -> AnyObject?) -> Dynamic<T> {
let keyPathValue: AnyObject? = object.valueForKeyPath(keyPath)
let dynamic = InternalDynamic(from(keyPathValue))
let helper = DynamicKVOHelper(keyPath: keyPath, object: object as NSObject) {
[unowned dynamic] (v: AnyObject?) -> Void in
dynamic.updatingFromSelf = true
dynamic.value = from(v)
dynamic.updatingFromSelf = false
}
let feedbackBond = Bond<T>() { [weak object] value in
if let object = object {
object.setValue(to(value), forKey: keyPath)
}
}
dynamic.bindTo(feedbackBond, fire: false, strongly: false)
dynamic.retain(feedbackBond)
dynamic.retain(helper)
return dynamic
}
public func dynamicObservableFor<T>(notificationName: String, #object: AnyObject?, #parser: NSNotification -> T) -> InternalDynamic<T> {
let dynamic: InternalDynamic<T> = InternalDynamic()
let helper = DynamicNotificationCenterHelper(notificationName: notificationName, object: object) {
[unowned dynamic] notification in
dynamic.updatingFromSelf = true
dynamic.value = parser(notification)
dynamic.updatingFromSelf = false
}
dynamic.retain(helper)
return dynamic
}
public extension Dynamic {
public class func asObservableFor(object: NSObject, keyPath: String, defaultValue: T) -> Dynamic<T> {
let dynamic: Dynamic<T> = dynamicObservableFor(object, keyPath: keyPath, defaultValue: defaultValue)
return dynamic
}
public class func asObservableFor(notificationName: String, object: AnyObject?, parser: NSNotification -> T) -> Dynamic<T> {
let dynamic: InternalDynamic<T> = dynamicObservableFor(notificationName, object: object, parser: parser)
return dynamic
}
}
|
mit
|
783deeacf897db40578d5485aa48163f
| 33.530612 | 162 | 0.720449 | 4.379638 | false | false | false | false |
Maxim-38RUS-Zabelin/ios-charts
|
Charts/Classes/Renderers/LineChartRenderer.swift
|
1
|
25390
|
//
// LineChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
@objc
public protocol LineChartRendererDelegate
{
func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData!
func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter
func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter!
func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Double
func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Double
func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Double
func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Double
func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int
}
public class LineChartRenderer: ChartDataRendererBase
{
public weak var delegate: LineChartRendererDelegate?
public init(delegate: LineChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.delegate = delegate
}
public override func drawData(#context: CGContext)
{
var lineData = delegate!.lineChartRendererData(self)
if (lineData === nil)
{
return
}
for (var i = 0; i < lineData.dataSetCount; i++)
{
var set = lineData.getDataSetByIndex(i)
if (set !== nil && set!.isVisible)
{
drawDataSet(context: context, dataSet: set as! LineChartDataSet)
}
}
}
internal struct CGCPoint
{
internal var x: CGFloat = 0.0
internal var y: CGFloat = 0.0
/// x-axis distance
internal var dx: CGFloat = 0.0
/// y-axis distance
internal var dy: CGFloat = 0.0
internal init(x: CGFloat, y: CGFloat)
{
self.x = x
self.y = y
}
}
internal func drawDataSet(#context: CGContext, dataSet: LineChartDataSet)
{
var entries = dataSet.yVals
if (entries.count < 1)
{
return
}
CGContextSaveGState(context)
CGContextSetLineWidth(context, dataSet.lineWidth)
if (dataSet.lineDashLengths != nil)
{
CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths, dataSet.lineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
// if drawing cubic lines is enabled
if (dataSet.isDrawCubicEnabled)
{
drawCubic(context: context, dataSet: dataSet, entries: entries)
}
else
{ // draw normal (straight) lines
drawLinear(context: context, dataSet: dataSet, entries: entries)
}
CGContextRestoreGState(context)
}
internal func drawCubic(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry])
{
var trans = delegate?.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var entryFrom = dataSet.entryForXIndex(_minX)
var entryTo = dataSet.entryForXIndex(_maxX)
var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
var phaseX = _animator.phaseX
var phaseY = _animator.phaseY
// get the color that is specified for this position from the DataSet
var drawingColor = dataSet.colors.first!
var intensity = dataSet.cubicIntensity
// the path for the cubic-spline
var cubicPath = CGPathCreateMutable()
var valueToPixelMatrix = trans!.valueToPixelMatrix
var size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx)))
if (size - minx >= 2)
{
var prevDx: CGFloat = 0.0
var prevDy: CGFloat = 0.0
var curDx: CGFloat = 0.0
var curDy: CGFloat = 0.0
var prevPrev = entries[minx]
var prev = entries[minx]
var cur = entries[minx]
var next = entries[minx + 1]
// let the spline start
CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY)
prevDx = CGFloat(cur.xIndex - prev.xIndex) * intensity
prevDy = CGFloat(cur.value - prev.value) * intensity
curDx = CGFloat(next.xIndex - cur.xIndex) * intensity
curDy = CGFloat(next.value - cur.value) * intensity
// the first cubic
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix,
CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY,
CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY)
for (var j = minx + 1, count = min(size, entries.count - 1); j < count; j++)
{
prevPrev = entries[j == 1 ? 0 : j - 2]
prev = entries[j - 1]
cur = entries[j]
next = entries[j + 1]
prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity
prevDy = CGFloat(cur.value - prevPrev.value) * intensity
curDx = CGFloat(next.xIndex - prev.xIndex) * intensity
curDy = CGFloat(next.value - prev.value) * intensity
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx,
(CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY)
}
if (size > entries.count - 1)
{
prevPrev = entries[entries.count - (entries.count >= 3 ? 3 : 2)]
prev = entries[entries.count - 2]
cur = entries[entries.count - 1]
next = cur
prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity
prevDy = CGFloat(cur.value - prevPrev.value) * intensity
curDx = CGFloat(next.xIndex - prev.xIndex) * intensity
curDy = CGFloat(next.value - prev.value) * intensity
// the last cubic
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx,
(CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY)
}
}
CGContextSaveGState(context)
if (dataSet.isDrawFilledEnabled)
{
drawCubicFill(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix, from: minx, to: size)
}
CGContextBeginPath(context)
CGContextAddPath(context, cubicPath)
CGContextSetStrokeColorWithColor(context, drawingColor.CGColor)
CGContextStrokePath(context)
CGContextRestoreGState(context)
}
internal func drawCubicFill(#context: CGContext, dataSet: LineChartDataSet, spline: CGMutablePath, var matrix: CGAffineTransform, from: Int, to: Int)
{
CGContextSaveGState(context)
var fillMin = delegate!.lineChartRendererFillFormatter(self).getFillLinePosition(
dataSet: dataSet,
data: delegate!.lineChartRendererData(self),
chartMaxY: delegate!.lineChartRendererChartYMax(self),
chartMinY: delegate!.lineChartRendererChartYMin(self))
var pt1 = CGPoint(x: CGFloat(to - 1), y: fillMin)
var pt2 = CGPoint(x: CGFloat(from), y: fillMin)
pt1 = CGPointApplyAffineTransform(pt1, matrix)
pt2 = CGPointApplyAffineTransform(pt2, matrix)
CGContextBeginPath(context)
CGContextAddPath(context, spline)
CGContextAddLineToPoint(context, pt1.x, pt1.y)
CGContextAddLineToPoint(context, pt2.x, pt2.y)
CGContextClosePath(context)
CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor)
CGContextSetAlpha(context, dataSet.fillAlpha)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint())
internal func drawLinear(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry])
{
var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var valueToPixelMatrix = trans.valueToPixelMatrix
var phaseX = _animator.phaseX
var phaseY = _animator.phaseY
CGContextSaveGState(context)
var entryFrom = dataSet.entryForXIndex(_minX)
var entryTo = dataSet.entryForXIndex(_maxX)
var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
// more than 1 color
if (dataSet.colors.count > 1)
{
if (_lineSegments.count != 2)
{
_lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint())
}
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++)
{
if (count > 1 && j == count - 1)
{ // Last point, we have already drawn a line to this point
break
}
var e = entries[j]
_lineSegments[0].x = CGFloat(e.xIndex)
_lineSegments[0].y = CGFloat(e.value) * phaseY
_lineSegments[0] = CGPointApplyAffineTransform(_lineSegments[0], valueToPixelMatrix)
if (j + 1 < count)
{
e = entries[j + 1]
_lineSegments[1].x = CGFloat(e.xIndex)
_lineSegments[1].y = CGFloat(e.value) * phaseY
_lineSegments[1] = CGPointApplyAffineTransform(_lineSegments[1], valueToPixelMatrix)
}
else
{
_lineSegments[1] = _lineSegments[0]
}
if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x))
{
break
}
// make sure the lines don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x)
|| (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))
|| (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)))
{
continue
}
// get the color that is set for this line-segment
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor)
CGContextStrokeLineSegments(context, _lineSegments, 2)
}
}
else
{ // only one color per dataset
var e1: ChartDataEntry!
var e2: ChartDataEntry!
if (_lineSegments.count != max((entries.count - 1) * 2, 2))
{
_lineSegments = [CGPoint](count: max((entries.count - 1) * 2, 2), repeatedValue: CGPoint())
}
e1 = entries[minx]
var count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx)))
for (var x = count > 1 ? minx + 1 : minx, j = 0; x < count; x++)
{
e1 = entries[x == 0 ? 0 : (x - 1)]
e2 = entries[x]
_lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY), valueToPixelMatrix)
_lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY), valueToPixelMatrix)
}
var size = max((count - minx - 1) * 2, 2)
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor)
CGContextStrokeLineSegments(context, _lineSegments, size)
}
CGContextRestoreGState(context)
// if drawing filled is enabled
if (dataSet.isDrawFilledEnabled && entries.count > 0)
{
drawLinearFill(context: context, dataSet: dataSet, entries: entries, minx: minx, maxx: maxx, trans: trans)
}
}
internal func drawLinearFill(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry], minx: Int, maxx: Int, trans: ChartTransformer)
{
CGContextSaveGState(context)
CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor)
// filled is usually drawn with less alpha
CGContextSetAlpha(context, dataSet.fillAlpha)
var filled = generateFilledPath(
entries,
fillMin: delegate!.lineChartRendererFillFormatter(self).getFillLinePosition(
dataSet: dataSet,
data: delegate!.lineChartRendererData(self),
chartMaxY: delegate!.lineChartRendererChartYMax(self),
chartMinY: delegate!.lineChartRendererChartYMin(self)),
from: minx,
to: maxx,
matrix: trans.valueToPixelMatrix)
CGContextBeginPath(context)
CGContextAddPath(context, filled)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
/// Generates the path that is used for filled drawing.
private func generateFilledPath(entries: [ChartDataEntry], fillMin: CGFloat, from: Int, to: Int, var matrix: CGAffineTransform) -> CGPath
{
var phaseX = _animator.phaseX
var phaseY = _animator.phaseY
var filled = CGPathCreateMutable()
CGPathMoveToPoint(filled, &matrix, CGFloat(entries[from].xIndex), fillMin)
CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[from].xIndex), CGFloat(entries[from].value) * phaseY)
// create a new path
for (var x = from + 1, count = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))); x < count; x++)
{
var e = entries[x]
CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY)
}
// close up
CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, entries.count - 1), 0)].xIndex), fillMin)
CGPathCloseSubpath(filled)
return filled
}
public override func drawValues(#context: CGContext)
{
var lineData = delegate!.lineChartRendererData(self)
if (lineData === nil)
{
return
}
var defaultValueFormatter = delegate!.lineChartDefaultRendererValueFormatter(self)
if (CGFloat(lineData.yValCount) < CGFloat(delegate!.lineChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX)
{
var dataSets = lineData.dataSets
for (var i = 0; i < dataSets.count; i++)
{
var dataSet = dataSets[i] as! LineChartDataSet
if (!dataSet.isDrawValuesEnabled)
{
continue
}
var valueFont = dataSet.valueFont
var valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency)
// make sure the values do not interfear with the circles
var valOffset = Int(dataSet.circleRadius * 1.75)
if (!dataSet.isDrawCirclesEnabled)
{
valOffset = valOffset / 2
}
var entries = dataSet.yVals
var entryFrom = dataSet.entryForXIndex(_minX)
var entryTo = dataSet.entryForXIndex(_maxX)
var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
var positions = trans.generateTransformedValuesLine(
entries,
phaseX: _animator.phaseX,
phaseY: _animator.phaseY,
from: minx,
to: maxx)
for (var j = 0, count = positions.count; j < count; j++)
{
if (!viewPortHandler.isInBoundsRight(positions[j].x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y))
{
continue
}
var val = entries[j + minx].value
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: positions[j].x, y: positions[j].y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
}
}
}
public override func drawExtras(#context: CGContext)
{
drawCircles(context: context)
}
private func drawCircles(#context: CGContext)
{
var phaseX = _animator.phaseX
var phaseY = _animator.phaseY
var lineData = delegate!.lineChartRendererData(self)
var dataSets = lineData.dataSets
var pt = CGPoint()
var rect = CGRect()
CGContextSaveGState(context)
for (var i = 0, count = dataSets.count; i < count; i++)
{
var dataSet = lineData.getDataSetByIndex(i) as! LineChartDataSet!
if (!dataSet.isVisible || !dataSet.isDrawCirclesEnabled)
{
continue
}
var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var valueToPixelMatrix = trans.valueToPixelMatrix
var entries = dataSet.yVals
var circleRadius = dataSet.circleRadius
var circleDiameter = circleRadius * 2.0
var circleHoleDiameter = circleRadius
var circleHoleRadius = circleHoleDiameter / 2.0
var isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled
var entryFrom = dataSet.entryForXIndex(_minX)!
var entryTo = dataSet.entryForXIndex(_maxX)!
var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0)
var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count)
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++)
{
var e = entries[j]
pt.x = CGFloat(e.xIndex)
pt.y = CGFloat(e.value) * phaseY
pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the circles don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
if let circleColor = dataSet.getCircleColor(j)
{
CGContextSetFillColorWithColor(context, circleColor.CGColor)
rect.origin.x = pt.x - circleRadius
rect.origin.y = pt.y - circleRadius
rect.size.width = circleDiameter
rect.size.height = circleDiameter
CGContextFillEllipseInRect(context, rect)
if (isDrawCircleHoleEnabled)
{
CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor)
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
rect.size.width = circleHoleDiameter
rect.size.height = circleHoleDiameter
CGContextFillEllipseInRect(context, rect)
}
}
if let circleImage = dataSet.circleImage {
rect.origin.x = pt.x - circleImage.size.width / CGFloat(2.0)
rect.origin.y = pt.y - circleImage.size.height / CGFloat(2.0)
rect.size.width = circleImage.size.width
rect.size.height = circleImage.size.height
CGContextDrawImage(context, rect, circleImage.CGImage)
}
}
}
CGContextRestoreGState(context)
}
var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint())
public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight])
{
var lineData = delegate!.lineChartRendererData(self)
var chartXMax = delegate!.lineChartRendererChartXMax(self)
var chartYMax = delegate!.lineChartRendererChartYMax(self)
var chartYMin = delegate!.lineChartRendererChartYMin(self)
CGContextSaveGState(context)
for (var i = 0; i < indices.count; i++)
{
var set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as! LineChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
CGContextSetLineWidth(context, set.highlightLineWidth)
if (set.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
var xIndex = indices[i].xIndex; // get the x-position
if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX)
{
continue
}
let yValue = set.yValForXIndex(xIndex)
if (yValue.isNaN)
{
continue
}
var y = CGFloat(yValue) * _animator.phaseY; // get the y-position
_highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMax))
_highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMin))
_highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.lineChartRendererChartXMin(self)), y: y)
_highlightPtsBuffer[3] = CGPoint(x: CGFloat(chartXMax), y: y)
var trans = delegate!.lineChartRenderer(self, transformerForAxis: set.axisDependency)
trans.pointValuesToPixel(&_highlightPtsBuffer)
// draw the highlight lines
CGContextStrokeLineSegments(context, _highlightPtsBuffer, 4)
}
CGContextRestoreGState(context)
}
}
|
apache-2.0
|
dc44f82038a106bcfbb28665448fec60
| 38.673438 | 306 | 0.55451 | 5.553368 | false | false | false | false |
abdullahselek/SwiftyNotifications
|
SwiftyNotifications/SwiftyNotificationsDrawings.swift
|
1
|
7563
|
//
// SwiftyNotificationsDrawings.swift
// SwiftyNotifications
//
// Copyright © 2017 Abdullah Selek. 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
internal class SwiftyNotificationsDrawings {
internal static func drawCheckmark(color: UIColor) {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 8.0, y: 37.0))
bezierPath.addLine(to: CGPoint(x: 27.0, y: 56.0))
bezierPath.move(to: CGPoint(x: 27.0, y: 56.0))
bezierPath.addLine(to: CGPoint(x: 75.0, y: 8.0))
bezierPath.lineCapStyle = .round
color.setStroke()
bezierPath.lineWidth = 14
bezierPath.stroke()
}
internal static func checkMarkImage(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 85, height: 63), false, 0)
drawCheckmark(color: color)
let checkmark = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return checkmark!
}
internal static func drawCross(color: UIColor) {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 10.0, y: 10.0))
bezierPath.addLine(to: CGPoint(x: 53.0, y: 53.0))
bezierPath.move(to: CGPoint(x: 10.0, y: 53.0))
bezierPath.addLine(to: CGPoint(x: 53.0, y: 10.0))
bezierPath.lineCapStyle = .round
color.setStroke()
bezierPath.lineWidth = 10
bezierPath.stroke()
}
internal static func crossImage(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 63.0, height: 63.0), false, 0)
drawCross(color: color)
let cross = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return cross!
}
internal static func drawInfo(color: UIColor) {
let info = UIBezierPath()
info.move(to: CGPoint(x: 45.66, y: 15.96))
info.addCurve(to: CGPoint(x: 45.66, y: 5.22),
controlPoint1: CGPoint(x: 48.78, y: 12.99),
controlPoint2: CGPoint(x: 48.78, y: 8.19))
info.addCurve(to: CGPoint(x: 34.34, y: 5.22),
controlPoint1: CGPoint(x: 42.53, y: 2.26),
controlPoint2: CGPoint(x: 37.47, y: 2.26))
info.addCurve(to: CGPoint(x: 34.34, y: 15.96),
controlPoint1: CGPoint(x: 32.22, y: 8.19),
controlPoint2: CGPoint(x: 31.22, y: 12.99))
info.addCurve(to: CGPoint(x: 45.66, y: 15.96),
controlPoint1: CGPoint(x: 37.47, y: 18.92),
controlPoint2: CGPoint(x: 42.53, y: 18.92))
info.close()
info.move(to: CGPoint(x: 48.0, y: 69.41))
info.addCurve(to: CGPoint(x: 40.0, y: 77.0),
controlPoint1: CGPoint(x: 48.0, y: 73.58),
controlPoint2: CGPoint(x: 44.4, y: 77.0))
info.addLine(to: CGPoint(x: 40.0, y: 77.0))
info.addCurve(to: CGPoint(x: 32.0, y: 69.41),
controlPoint1: CGPoint(x: 35.6, y: 77.0),
controlPoint2: CGPoint(x: 32.0, y: 73.58))
info.addLine(to: CGPoint(x: 32.0, y: 35.26))
info.addCurve(to: CGPoint(x: 40.0, y: 27.67),
controlPoint1: CGPoint(x: 32.0, y: 31.08),
controlPoint2: CGPoint(x: 35.6, y: 27.67))
info.addLine(to: CGPoint(x: 40.0, y: 27.67))
info.addCurve(to: CGPoint(x: 48.0, y: 35.26),
controlPoint1: CGPoint(x: 44.4, y: 27.67),
controlPoint2: CGPoint(x: 48.0, y: 31.08))
info.addLine(to: CGPoint(x: 48.0, y: 69.41))
info.close()
color.setFill()
info.fill()
}
internal static func infoImage(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 80.0, height: 80.0), false, 0)
drawInfo(color: color)
let info = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return info!
}
internal static func drawWarning(backgroundColor: UIColor, foregroundColor: UIColor) {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 54.0, y: 10.0))
bezierPath.addLine(to: CGPoint(x: 11.0, y: 81.0))
bezierPath.addLine(to: CGPoint(x: 54.0, y: 81.0))
bezierPath.addLine(to: CGPoint(x: 97.0, y: 81.0))
bezierPath.addLine(to: CGPoint(x: 54.0, y: 10.0))
bezierPath.lineCapStyle = .round
bezierPath.lineJoinStyle = .round
backgroundColor.setFill()
bezierPath.fill()
backgroundColor.setStroke()
bezierPath.lineWidth = 14
bezierPath.stroke()
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 54.0, y: 48.0))
bezier2Path.addLine(to: CGPoint(x: 54.0, y: 71.0))
bezier2Path.lineCapStyle = .round
bezier2Path.lineJoinStyle = .round
foregroundColor.setFill()
bezier2Path.fill()
foregroundColor.setStroke()
bezier2Path.lineWidth = 14
bezier2Path.stroke()
let oval = UIBezierPath(ovalIn: CGRect(x: 47.0, y: 19.0, width: 14.0, height: 14.0))
foregroundColor.setFill()
oval.fill()
}
internal static func warningImage(backgroundColor: UIColor, foregroundColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 108.0, height: 92.0), false, 0)
drawWarning(backgroundColor: backgroundColor, foregroundColor: foregroundColor)
let warning = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return warning!
}
}
internal extension UIImage {
func scaleImageToSize(size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return self
}
return image
}
func scaleImageToFitSize(size: CGSize) -> UIImage {
let aspect = self.size.width / self.size.height
if size.width / aspect <= size.height {
return scaleImageToSize(size: CGSize(width: size.width, height: size.width / aspect))
} else {
return scaleImageToSize(size: CGSize(width: size.height * aspect, height: size.height))
}
}
}
|
mit
|
f177839a80cf592c02c28f73abae92d1
| 41.723164 | 102 | 0.62457 | 3.973726 | false | false | false | false |
loudnate/Loop
|
Learn/Lessons/ModalDayLesson.swift
|
1
|
7476
|
//
// ModalDayLesson.swift
// Learn
//
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import Foundation
import HealthKit
import LoopCore
import LoopKit
import os.log
final class ModalDayLesson: Lesson {
let title = NSLocalizedString("Modal Day", comment: "Lesson title")
let subtitle = NSLocalizedString("Visualizes the most frequent glucose values by time of day", comment: "Lesson subtitle")
let configurationSections: [LessonSectionProviding]
private let dataManager: DataManager
private let dateIntervalEntry: DateIntervalEntry
private let glucoseUnit: HKUnit
init(dataManager: DataManager) {
self.dataManager = dataManager
self.glucoseUnit = dataManager.glucoseStore.preferredUnit ?? .milligramsPerDeciliter
dateIntervalEntry = DateIntervalEntry(
end: Date(),
weeks: 2
)
self.configurationSections = [
dateIntervalEntry
]
}
func execute(completion: @escaping ([LessonSectionProviding]) -> Void) {
guard let dates = dateIntervalEntry.dateInterval else {
// TODO: Cleaner error presentation
completion([LessonSection(headerTitle: "Error: Please fill out all fields", footerTitle: nil, cells: [])])
return
}
let calendar = Calendar.current
let calculator = ModalDayCalculator(dataManager: dataManager, dates: dates, bucketSize: .minutes(60), unit: glucoseUnit, calendar: calendar)
calculator.execute { (result) in
switch result {
case .failure(let error):
completion([
LessonSection(cells: [TextCell(text: String(describing: error))])
])
case .success(let buckets):
guard buckets.count > 0 else {
completion([
LessonSection(cells: [TextCell(text: NSLocalizedString("No data available", comment: "Lesson result text for no data"))])
])
return
}
let dateFormatter = DateIntervalFormatter(timeStyle: .short)
let glucoseFormatter = QuantityFormatter()
glucoseFormatter.setPreferredNumberFormatter(for: self.glucoseUnit)
completion([
LessonSection(cells: buckets.compactMap({ (bucket) -> TextCell? in
guard let start = calendar.date(from: bucket.time.lowerBound.dateComponents),
let end = calendar.date(from: bucket.time.upperBound.dateComponents),
let time = dateFormatter.string(from: DateInterval(start: start, end: end)),
let median = bucket.median,
let medianString = glucoseFormatter.string(from: median, for: bucket.unit)
else {
return nil
}
return TextCell(text: time, detailText: medianString)
}))
])
}
}
}
}
fileprivate extension TextCell {
}
fileprivate struct ModalDayBucket {
let time: Range<TimeComponents>
let orderedValues: [Double]
let unit: HKUnit
init(time: Range<TimeComponents>, unorderedValues: [Double], unit: HKUnit) {
self.time = time
self.orderedValues = unorderedValues.sorted()
self.unit = unit
}
var median: HKQuantity? {
let count = orderedValues.count
guard count > 0 else {
return nil
}
if count % 2 == 1 {
return HKQuantity(unit: unit, doubleValue: orderedValues[count / 2])
} else {
let mid = count / 2
let lower = orderedValues[mid - 1]
let upper = orderedValues[mid]
return HKQuantity(unit: unit, doubleValue: (lower + upper) / 2)
}
}
}
fileprivate struct ModalDayBuilder {
let calendar: Calendar
let bucketSize: TimeInterval
let unit: HKUnit
private(set) var unorderedValuesByBucket: [Range<TimeComponents>: [Double]]
init(calendar: Calendar, bucketSize: TimeInterval, unit: HKUnit) {
self.calendar = calendar
self.bucketSize = bucketSize
self.unit = unit
self.unorderedValuesByBucket = [:]
}
mutating func add(_ value: Double, at time: TimeComponents) {
let bucket = time.bucket(withBucketSize: bucketSize)
var values = unorderedValuesByBucket[bucket] ?? []
values.append(value)
unorderedValuesByBucket[bucket] = values
}
mutating func add(_ value: Double, at date: DateComponents) {
guard let time = TimeComponents(dateComponents: date) else {
return
}
add(value, at: time)
}
mutating func add(_ value: Double, at date: Date) {
add(value, at: calendar.dateComponents([.hour, .minute], from: date))
}
mutating func add(_ quantity: HKQuantity, at date: Date) {
add(quantity.doubleValue(for: unit), at: date)
}
var allBuckets: [ModalDayBucket] {
return unorderedValuesByBucket.sorted(by: { $0.0.lowerBound < $1.0.lowerBound }).map { pair -> ModalDayBucket in
return ModalDayBucket(time: pair.key, unorderedValues: pair.value, unit: unit)
}
}
}
fileprivate class ModalDayCalculator {
typealias ResultType = ModalDayBuilder
let calculator: DayCalculator<ResultType>
let bucketSize: TimeInterval
let calendar: Calendar
private let log: OSLog
init(dataManager: DataManager, dates: DateInterval, bucketSize: TimeInterval, unit: HKUnit, calendar: Calendar) {
self.calculator = DayCalculator(dataManager: dataManager, dates: dates, initial: ModalDayBuilder(calendar: calendar, bucketSize: bucketSize, unit: unit))
self.bucketSize = bucketSize
self.calendar = calendar
log = OSLog(category: String(describing: type(of: self)))
}
func execute(completion: @escaping (_ result: Result<[ModalDayBucket]>) -> Void) {
os_log(.default, log: log, "Computing Modal day in %{public}@", String(describing: calculator.dates))
calculator.execute(calculator: { (dataManager, day, mutableResult, completion) in
os_log(.default, log: self.log, "Fetching samples in %{public}@", String(describing: day))
dataManager.glucoseStore.getGlucoseSamples(start: day.start, end: day.end, completion: { (result) in
switch result {
case .failure(let error):
os_log(.error, log: self.log, "Failed to fetch samples: %{public}@", String(describing: error))
completion(error)
case .success(let samples):
os_log(.error, log: self.log, "Found %d samples", samples.count)
for sample in samples {
_ = mutableResult.mutate({ (result) in
result.add(sample.quantity, at: sample.startDate)
})
}
completion(nil)
}
})
}, completion: { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let builder):
completion(.success(builder.allBuckets))
}
})
}
}
|
apache-2.0
|
8430a36bb972bd99e10ceb8bb3e822c9
| 34.259434 | 161 | 0.59398 | 4.895219 | false | false | false | false |
bvanzile/StarHero
|
StarHero/Useful/VectorMath.swift
|
1
|
6399
|
//
// VectorMath.swift
// StarHero
//
// Created by Bryan Van Zile on 5/17/19.
// Copyright © 2019 Bryan Van Zile. All rights reserved.
//
import Foundation
import SpriteKit
// Simple 2D vector
struct Vector: VectorMath {
// Properties used in a 2D vector
var x: CGFloat = 0
var y: CGFloat = 0
// Initialize a vector with 2 values
init(x: CGFloat, y: CGFloat) {
self.x = x
self.y = y
}
// Initialize a vector from a CGPoint
init(_ point: CGPoint) {
x = point.x
y = point.y
}
// Initialize based on degrees
init(degrees: CGFloat) {
x = cos(degreesToRads(degrees: degrees))
y = sin(degreesToRads(degrees: degrees))
}
// Initialize based on degrees
init(rads: CGFloat) {
x = cos(rads)
y = sin(rads)
}
// Default to 0, 0
init() { }
// The vector magnitude
func length() -> CGFloat {
return CGFloat((x * x) + (y * y)).squareRoot()
}
// Normalize vector to length of 1
func normalize() -> Vector {
let magnitude = self.length()
if magnitude == 0 {
// Return 0 vector, keep in mind to avoid divide by 0 later on
return self
}
else {
return Vector(x: self.x / magnitude, y: self.y / magnitude)
}
}
// Overload the * operator for multiplication
static func *(left: Vector, right: CGFloat) -> Vector {
return Vector(x: left.x * right, y: left.y * right)
}
// Overload the * operator for multiplication
static func /(left: Vector, right: CGFloat) -> Vector {
return Vector(x: left.x / right, y: left.y / right)
}
// Overload the + operator for vector addition
static func +(left: Vector, right: Vector) -> Vector {
return Vector(x: left.x + right.x, y: left.y + right.y)
}
// Overload the - operator for vector addition
static func -(left: Vector, right: Vector) -> Vector {
return Vector(x: left.x - right.x, y: left.y - right.y)
}
func dot(vector: Vector) -> CGFloat {
let thisVectorNormalized = self.normalize()
let otherVectorNormalized = vector.normalize()
return acos((thisVectorNormalized.x * otherVectorNormalized.x) + (thisVectorNormalized.y * otherVectorNormalized.y))
}
func dotDegrees(vector: Vector) -> CGFloat {
let thisVectorNormalized = self.normalize()
let otherVectorNormalized = vector.normalize()
return radsToDegrees(rads: acos((thisVectorNormalized.x * otherVectorNormalized.x) + (thisVectorNormalized.y * otherVectorNormalized.y)))
}
// Return the vector that is perpindicular and to the right (clockwise)
func right() -> Vector {
return Vector(x: y, y: -x)
}
// Return the vector that is perpindicular and to the right (clockwise)
func left() -> Vector {
return Vector(x: -y, y: x)
}
// Returns the reverse of this vector
func reverse() -> Vector {
return Vector(x: -x, y: -y)
}
// Adjusts the vector so that it does not exceed the input
func truncate(value: CGFloat) -> Vector {
// Check if the length of the vector is greater than the input
if(self.length() > value) {
// If so, normalize and change to desired length
return self.normalize() * value
}
return self
}
// Distance between this vetor and the one passed in argument
func distanceBetween(vector: Vector) -> CGFloat {
return (self - vector).length()
}
// Rotate vector by degrees
func rotate(degrees: CGFloat) -> Vector {
let rotation = degreesToRads(degrees: degrees)
return Vector(x: (x * cos(rotation)) - (y * sin(rotation)), y: (x * sin(rotation)) + (y * cos(rotation)))
}
// Convert vector to degrees
func toRads() -> CGFloat {
return atan2(y, x)
}
// Convert vector to degrees
func toDegrees() -> CGFloat {
return radsToDegrees(rads: atan2(y, x))
}
// Return this vector as a CGPoint
func toCGPoint() -> CGPoint {
return CGPoint(x: x, y: y)
}
// Check if this is a zero'd out vector
func isZero() -> Bool {
if x == 0 && y == 0 {
return true
}
return false
}
}
// Inheritable class that appends some useful math functions to any class that inherits it
protocol VectorMath { }
extension VectorMath {
// Reusable function for receving a normalized vector that represents an angle in degrees
func angleToVector(degrees: CGFloat) -> Vector {
return Vector(x: cos(degreesToRads(degrees: degrees)), y: sin(degreesToRads(degrees: degrees)))
}
// Reusable function for receving a normalized vector that represents an angle in degrees
func angleToVector(rads: CGFloat) -> Vector {
return Vector(x: cos(rads), y: sin(rads))
}
// Converts degrees to radians
func degreesToRads(degrees: CGFloat) -> CGFloat {
return degrees * (.pi / 180.0)
}
// Converts radians to degrees
func radsToDegrees(rads: CGFloat) -> CGFloat {
return rads * (180.0 / .pi)
}
// Reusable function for taking separated coordinates and returning a CGPoint object
func coordToCGPoint(x: CGFloat, y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
// Reusable function for taking separated coordinates and returning a CGPoint object
func vectorToCGPoint(vector: Vector) -> CGPoint {
return CGPoint(x: vector.x, y: vector.y)
}
// Convert the heading direction to the sprite's necessary rotation
func ConvertHeadingToSpriteRotation(heading: CGFloat) -> CGFloat {
return self.degreesToRads(degrees: heading + 90.0)
}
// Finds the angle between 2 points
func GetDirection(firstPoint: CGPoint, secondPoint: CGPoint) -> CGFloat {
return self.radsToDegrees(rads: atan2(secondPoint.y - firstPoint.y, secondPoint.x - firstPoint.x))
}
// Get a randomized vector
func randomVector() -> Vector {
let randomizedVector = Vector(x: CGFloat.random(in: -1...1), y: CGFloat.random(in: -1...1))
return randomizedVector.normalize()
}
}
|
mit
|
3a3d886038d0a52155ea187ccf120d71
| 30.209756 | 145 | 0.60347 | 4.149157 | false | false | false | false |
kuyazee/WarpSDK-iOS
|
WarpSDK/WarpObject.swift
|
1
|
7233
|
//
// WarpObject.swift
// Practice
//
// Created by Zonily Jame Pesquera on 28/10/2016.
//
//
import Foundation
import PromiseKit
public extension Warp {
public class Object: WarpObjectProtocol {
internal let objectClassName: String
internal var dictionary: [String: Any] = [:]
/// returns the id
public var id: Int {
return self.dictionary["id"] as? Int ?? 0
}
/// returns the createdAt
public var createdAt: String {
return self.dictionary["created_at"] as? String ?? ""
}
/// returns the updatedAt
public var updatedAt: String {
return self.dictionary["updated_at"] as? String ?? ""
}
/// Description
///
/// - Parameters:
/// - id: Database primary key
/// - className: Table name in the Database
/// - Returns: A new instance of the object
public class func createWithoutData(id: Int, className: String = "") -> Warp.Object {
let object = Warp.Object(className: className)
object.dictionary["id"] = id
return object
}
/// Description
///
/// - Parameter className: Table name in the Database
public required init(className: String) {
self.objectClassName = className
}
/// Description
///
/// - Parameters:
/// - className: Table name in the Database
/// - json: possible table rows
required public init(className: String, json: [String: Any]) {
self.objectClassName = className
self.dictionary = json
}
/// This function will be used to set a value to this object
///
/// - Parameters:
/// - value: value that will be set to a key
/// - forKey: The key name
/// - Returns: The same object but with updated properties
public func set(object value: Any, forKey: String) -> Self {
switch forKey {
case "created_at", "updated_at", "id":
fatalError("This action is not permitted")
default:
if value is Warp.Object {
self.dictionary[forKey] = WarpPointer.map(warpObject: value as! Warp.Object)
return self
}
if value is Warp.User {
self.dictionary[forKey] = WarpPointer.map(warpUser: value as! Warp.User)
return self
}
self.dictionary[forKey] = value
return self
}
}
/// This function will be used to take a value from this object
///
/// - Parameter forKey: the key name
/// - Returns: The value associated to the key
public func get(object forKey: String) -> Any? {
return self.dictionary[forKey]
}
public func save(_ completion: @escaping WarpResultBlock) -> WarpDataRequest {
guard let warp = Warp.shared else {
fatalError("[Warp] [Warp] WarpServer is not yet initialized")
}
let endPoint: String = {
if self.id > 0 {
return warp.generateEndpoint(.classes(className: self.objectClassName, id: self.id))
} else {
return warp.generateEndpoint(.classes(className: self.objectClassName, id: nil))
}
}()
let request: WarpDataRequest = {
if self.id > 0 {
return Warp.API.put(endPoint, parameters: self.dictionary, headers: warp.HEADER())
} else {
return Warp.API.post(endPoint, parameters: self.dictionary, headers: warp.HEADER())
}
}()
return request.warpResponse { (warpResult) in
switch warpResult {
case .success(let JSON):
let warpResponse = WarpResponse(json: JSON, result: [String: Any].self)
switch warpResponse.statusType {
case .success:
self.dictionary = warpResponse.result!
completion(true, nil)
default:
completion(true, WarpError(message: warpResponse.message, status: warpResponse.status))
}
break
case .failure(let error):
completion(false, error)
}
}
}
public func destroy(_ completion: @escaping WarpResultBlock) -> WarpDataRequest {
guard let warp = Warp.shared else {
fatalError("[Warp] WarpServer is not yet initialized")
}
let endPoint = warp.generateEndpoint(.classes(className: self.objectClassName, id: self.id))
let request = Warp.API.delete(endPoint, parameters: self.dictionary, headers: warp.HEADER())
guard self.id > 0 else {
completion(false, WarpError(code: .objectDoesNotExist))
return request
}
return request.warpResponse { (warpResult) in
switch warpResult {
case .success(let JSON):
let warpResponse = WarpResponse(json: JSON, result: [String: Any].self)
switch warpResponse.statusType {
case .success:
self.dictionary = warpResponse.result!
completion(true, nil)
default:
completion(true, WarpError(message: warpResponse.message, status: warpResponse.status))
}
case .failure(let error):
completion(false, error)
}
}
}
public func save() -> Promise<Warp.Object> {
return Promise { fulfill, reject in
_ = self.save({ (isSuccess, error) in
if let error = error {
reject(error)
} else {
fulfill(self)
}
})
}
}
public func destroy() -> Promise<Warp.Object> {
return Promise { fulfill, reject in
_ = self.destroy({ (isSuccess, error) in
if let error = error {
reject(error)
} else {
fulfill(self)
}
})
}
}
/// Creates a Warp.Query<Warp.Object> instance
///
/// - Parameter className: The Warp.Object's className
/// - Returns: a new Warp.Query<Warp.Object> instance
public static func Query(className: String) -> Warp.Query<Warp.Object> {
return Warp.Query(className: className)
}
}
}
|
mit
|
10d0bf4c1db7b8af397934c56c60d17c
| 35.530303 | 111 | 0.486658 | 5.279562 | false | false | false | false |
kumaw/AMRequestAPI
|
AMRequestAPI/Classes/AMRequestAPI.swift
|
1
|
3599
|
//
// RequestAPI.swift
// MiaoCai
//
// Created by imac on 2016/10/24.
// Copyright © 2016年 iMac. All rights reserved.
//
import Foundation
import PromiseKit
import Alamofire
import SwiftyJSON
public class AMRequestAPI: NSObject {
public static let share = AMRequestAPI()
private override init() {}
//默认参数
public let defaultParams:[String:Any] = [:]
func addDefaultParams(params: [String:Any]?) -> Dictionary<String,Any>?{
var tempParams:[String:Any] = params ?? [:]
for (k, v) in defaultParams {
tempParams.updateValue(v, forKey: k)
}
return tempParams
}
//promise的请求
//url: 请求地址
//body: 请求参数
//errorHandle: 是否自动处理错误
public func post(url:String,body:Dictionary<String, Any>?)->Promise<JSON>{
let params = addDefaultParams(params: body)
let purl = url
var tempRes:JSON?
NSLog("请求地址%@", purl)
NSLog("请求参数%@", params!.description)
//2种类型判断,带文件传输用upload
var hasData = false
var p:Promise<JSON>?
var nextp:Promise<JSON>?
if(body != nil){
for item in body!.enumerated(){
if(item.element.value is AMUploadFile){
hasData = true
}
}
if(hasData){
NSLog("含文件上传")
p = self.upload(url: purl, data: params!)
}
}
if(!hasData){
p = Alamofire.request(purl, method: HTTPMethod.post, parameters: params).responseJSON().then(execute: { (response) -> JSON in
tempRes = JSON(response);
return tempRes!
})
}
if(p != nil){
nextp = p?.then(execute: { (json) -> JSON in
return json
})
}
return nextp!
}
//上传文件promise封装
func upload(url:String,data:[String:Any])->Promise<JSON>{
return Promise{ fulfill, reject in
Alamofire.upload(multipartFormData: { (multipartFormData) in
for item in data.enumerated(){
if item.element.value is String {
//字符串类型
let str = item.element.value as! String
multipartFormData.append(str.data(using: String.Encoding.utf8)!, withName: item.element.key)
}else if(item.element.value is AMUploadFile){
//文件类型
let file = item.element.value as! AMUploadFile
multipartFormData.append(file.data, withName: item.element.key, fileName: "a", mimeType: file.mimeType)
}
}
}, to: url, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
_ = upload.responseJSON().then(execute: { (res) -> Void in
let temp = JSON(res)
print(temp)
fulfill(temp)
})
case .failure(let encodingError):
print(encodingError)
}
})
}
}
}
|
mit
|
9ac4f3e1b5435555527791ff81b6e092
| 26.983871 | 137 | 0.470605 | 4.908062 | false | false | false | false |
bizz84/ReviewTime
|
ReviewTime/ViewControllers/HomeViewController.swift
|
1
|
6565
|
//
// HomeViewController.swift
// ReviewTime
//
// Created by Nathan Hegedus on 18/06/15.
// Copyright (c) 2015 Nathan Hegedus. All rights reserved.
//
import UIKit
import TwitterKit
class HomeViewController: UIViewController {
var timer: NSTimer?
@IBOutlet weak var lastUpdateLabel: UILabel!
@IBOutlet weak var iosTypeLabel: UILabel!
@IBOutlet weak var iosDaysLabel: UILabel!
@IBOutlet weak var iosDescriptionLabel: UILabel!
@IBOutlet weak var macTypeLabel: UILabel!
@IBOutlet weak var macDaysLabel: UILabel!
@IBOutlet weak var macDescriptionLabel: UILabel!
@IBOutlet weak var errorButton: UIButton!
@IBOutlet weak var iosButton: NHButton!
@IBOutlet weak var macButton: NHButton!
@IBOutlet weak var extraInfoLabel: UILabel!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
var loginTwitterButton:TWTRLogInButton?
var reviewTimeResult: ReviewTime? {
didSet {
self.iosDaysLabel.hidden = false
self.iosDaysLabel.text = NSLocalizedString("\(reviewTimeResult!.iosAverageTime) days", comment: "Average Days")
self.iosDescriptionLabel.text = NSLocalizedString("Based on \(reviewTimeResult!.iosTotalTweets) reviews in the last 14 days", comment: "Description reviews iOS")
self.macDaysLabel.hidden = false
self.macDaysLabel.text = NSLocalizedString("\(reviewTimeResult!.macAverageTime) days", comment: "Average Days")
self.macDescriptionLabel.text = NSLocalizedString("Based on \(reviewTimeResult!.macTotalTweets) reviews in the last 30 days", comment: "Description reviews Mac")
self.lastUpdateLabel.text = NSLocalizedString("last updated: \(reviewTimeResult!.lastUpdate)", comment: "Last update Label")
self.activityIndicatorView.stopAnimating()
self.fadeInLabels()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.fetchData()
self.logAnalytics()
}
override func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetMac", name: "Mac", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetIOS", name: "iOS", object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.timer?.invalidate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Private Methods
private func logAnalytics() {
let tracker = GAI.sharedInstance().defaultTracker
tracker.set("HomeViewController", value: "Load_Home")
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
}
internal func fetchData() {
self.activityIndicatorView.startAnimating()
ReviewTimeWS.fetchReviewTimeData { (reviewTime, error) -> Void in
if error == nil {
self.reviewTimeResult = reviewTime
self.timer = NSTimer.scheduledTimerWithTimeInterval(30*60, target: self, selector: "fetchData", userInfo: nil, repeats: false)
}else{
self.activityIndicatorView.stopAnimating()
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.errorButton.alpha = 1.0
})
}
}
}
private func fadeInLabels() {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.iosDaysLabel.alpha = 1.0
self.iosTypeLabel.alpha = 1.0
self.iosDescriptionLabel.alpha = 1.0
self.macDaysLabel.alpha = 1.0
self.macTypeLabel.alpha = 1.0
self.macDescriptionLabel.alpha = 1.0
self.lastUpdateLabel.alpha = 1.0
})
}
private func tweetReviewTimeWithHashtag(hashtag: String) {
if Twitter.sharedInstance().session() == nil {
Twitter.sharedInstance().logInWithCompletion {
(session, error) -> Void in
if (session != nil) {
self.tweetReviewTimeWithHashtag(hashtag)
}
}
}else{
let composer = TWTRComposer()
composer.setText(hashtag)
composer.showFromViewController(self, completion: { (result) -> Void in
if (result == TWTRComposerResult.Done) {
let tracker = GAI.sharedInstance().defaultTracker
tracker.set("Tweeted", value: "Tweeted_\(hashtag)")
log.debug("Tweeted")
}
})
}
}
// MARK: - IBActions
@IBAction func tryAgain(sender: AnyObject) {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.errorButton.alpha = 0.0
}) { (bool) -> Void in
self.fetchData()
}
}
@IBAction func tweetIOS() {
let tracker = GAI.sharedInstance().defaultTracker
tracker.set("Start Twitter for iOS hashtag", value: "Tweet_iOS")
self.tweetReviewTimeWithHashtag("#iosreviewtime")
}
@IBAction func tweetMac( ) {
let tracker = GAI.sharedInstance().defaultTracker
tracker.set("Start Twitter for Mac hashtag", value: "Tweet_Mac")
self.tweetReviewTimeWithHashtag("#macreviewtime")
}
@IBAction func openInfo(sender: AnyObject) {
let title = NSLocalizedString("Where does this data come from?", comment: "Title alert about")
let message = NSLocalizedString("This is not official Apple data. It is based only on anecdotal data gathered from people posting their latest review times on Twitter and App.net using the #macreviewtime or #iosreviewtime hash tags.", comment: "Message alert about")
UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "Ok").show()
}
}
|
mit
|
cd8c698f64ead850181128fd46f74bf8
| 32.494898 | 274 | 0.605941 | 5.20206 | false | false | false | false |
hejunbinlan/Operations
|
examples/Permissions/Pods/TaylorSource/framework/TaylorSource/Base/Datasource.swift
|
1
|
16465
|
//
// Created by Daniel Thorpe on 16/04/2015.
//
import UIKit
/**
The core protocol of Datasource functionality.
It has an associated type, _FactoryType which in turn is responsible for
associates types for item model, cell class, supplementary view classes,
parent view class and index types.
The factory provides an API to register cells and views, and in
turn it can be used to vend cells and view.
Types which implement DatasourceType (this protocol) should use the
factory in conjuction with a storage medium for data items.
This protocol exists to allow for the definition of different kinds of
datasources. Coupled with DatasourceProviderType, datasources can be
composed and extended with ease. See SegmentedDatasource for example.
*/
public protocol DatasourceType {
typealias FactoryType: _FactoryType
/// Access the factory from the datasource, likely should be a stored property.
var factory: FactoryType { get }
/// An identifier which is primarily to ease debugging and logging.
var identifier: String { get }
/// Optional human readable title
var title: String? { get }
/// The number of sections in the data source
var numberOfSections: Int { get }
/**
The number of items in the section.
- parameter section: The section index
- returns: An Int, the number of items.
*/
func numberOfItemsInSection(sectionIndex: Int) -> Int
/**
Access the underlying data item at the indexPath.
- parameter indexPath: A NSIndexPath instance.
- returns: An optional Item
*/
func itemAtIndexPath(indexPath: NSIndexPath) -> FactoryType.ItemType?
/**
Vends a configured cell for the item.
- parameter view: the View which should dequeue the cell.
- parameter indexPath: the NSIndexPath of the item.
:return: a FactoryType.CellType instance, this should be dequeued and configured.
*/
func cellForItemInView(view: FactoryType.ViewType, atIndexPath indexPath: NSIndexPath) -> FactoryType.CellType
/**
Vends a configured supplementary view of kind.
- parameter view: the View which should dequeue the cell.
- parameter kind: the kind of the supplementary element. See SupplementaryElementKind
- parameter indexPath: the NSIndexPath of the item.
:return: a Factory.Type.SupplementaryViewType instance, this should be dequeued and configured.
*/
func viewForSupplementaryElementInView(view: FactoryType.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> FactoryType.SupplementaryViewType?
/**
Vends a optional text for the supplementary kind
- parameter view: the View which should dequeue the cell.
- parameter kind: the kind of the supplementary element. See SupplementaryElementKind
- parameter indexPath: the NSIndexPath of the item.
:return: a TextType?
*/
func textForSupplementaryElementInView(view: FactoryType.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> FactoryType.TextType?
}
/**
Suggested usage is not to use a DatasourceType directly, but instead to create
a bespoke type which implements this protocol, DatasourceProviderType, and vend
a configured datasource. This type could be considered to be like a view model
in MVVM paradigms. But in traditional MVC, such a type is just a model, which
the view controller initalizes and owns.
*/
public protocol DatasourceProviderType {
typealias Datasource: DatasourceType
/// The underlying Datasource.
var datasource: Datasource { get }
}
/**
Simple wrapper for a Datasource. TaylorSource is designed for composing Datasources
inside custom classes, referred to as *datasource providers*. There are Table View
and Collection View data source generators which accept datasource providers.
Therefore, if you absolutely don't want your own custom class to act as the datasource
provider, this structure is available to easily wrap any DatasourceType. e.g.
let datasource: UITableViewDataSourceProvider<BasicDatasourceProvider<StaticDatasource>>
tableView.dataSource = datasource.tableViewDataSource
*/
public struct BasicDatasourceProvider<Datasource: DatasourceType>: DatasourceProviderType {
/// The wrapped Datasource
public let datasource: Datasource
public init(_ d: Datasource) {
datasource = d
}
}
/**
A concrete implementation of DatasourceType for simple immutable arrays of objects.
The static datasource is initalized with the model items to display. They all
are in the same section.
The cell and supplementary index types are both NSIndexPath, which means using a
BasicFactory. This means that the configure block for cells and supplementary views
will receive an NSIndexPath as their index argument.
*/
public final class StaticDatasource<
Factory
where
Factory: _FactoryType,
Factory.CellIndexType == NSIndexPath,
Factory.SupplementaryIndexType == NSIndexPath>: DatasourceType, SequenceType, CollectionType {
typealias FactoryType = Factory
public let identifier: String
public let factory: Factory
public var title: String? = .None
private var items: [Factory.ItemType]
/**
The initializer.
- parameter id: a String identifier
:factory: a Factory whose CellIndexType and SupplementaryIndexType must be NSIndexPath, such as BasicFactory.
:items: an array of Factory.ItemType instances.
*/
public init(id: String, factory f: Factory, items i: [Factory.ItemType]) {
identifier = id
factory = f
items = i
}
/// The number of section, always 1 for a static datasource
public var numberOfSections: Int {
return 1
}
/// The number of items in a section, always the item count for a static datasource
public func numberOfItemsInSection(sectionIndex: Int) -> Int {
return items.count
}
/**
The item at an indexPath. Will ignore the section property of the NSIndexPath.
Will also return .None if the indexPath item index is out of bounds of the
array of items.
- parameter indexPath: an NSIndexPath
- returns: an optional Factory.ItemType
*/
public func itemAtIndexPath(indexPath: NSIndexPath) -> Factory.ItemType? {
if items.startIndex <= indexPath.item && indexPath.item < items.endIndex {
return items[indexPath.item]
}
return .None
}
/**
Will return a cell.
The cell is configured with the item at the index path first.
Note, that the itemAtIndexPath method will gracefully return a .None if the
indexPath is out of range. Here, we fatalError which will deliberately crash the
app.
- parameter view: the view instance.
- parameter indexPath: an NSIndexPath
- returns: an dequeued and configured Factory.CellType
*/
public func cellForItemInView(view: Factory.ViewType, atIndexPath indexPath: NSIndexPath) -> Factory.CellType {
if let item = itemAtIndexPath(indexPath) {
return factory.cellForItem(item, inView: view, atIndex: indexPath)
}
fatalError("No item available at index path: \(indexPath)")
}
/**
Will return a supplementary view.
This is the result of running any registered closure from the factory
for this supplementary element kind.
- parameter view: the view instance.
- parameter kind: the SupplementaryElementKind of the supplementary view.
- returns: an dequeued and configured Factory.SupplementaryViewType
*/
public func viewForSupplementaryElementInView(view: Factory.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> Factory.SupplementaryViewType? {
return factory.supplementaryViewForKind(kind, inView: view, atIndex: indexPath)
}
/**
Will return an optional text for the supplementary kind
- parameter view: the View which should dequeue the cell.
- parameter kind: the kind of the supplementary element. See SupplementaryElementKind
- parameter indexPath: the NSIndexPath of the item.
:return: a TextType?
*/
public func textForSupplementaryElementInView(view: Factory.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> Factory.TextType? {
return factory.supplementaryTextForKind(kind, atIndex: indexPath)
}
// SequenceType
public func generate() -> Array<Factory.ItemType>.Generator {
return items.generate()
}
// CollectionType
public var startIndex: Int {
return items.startIndex
}
public var endIndex: Int {
return items.endIndex
}
public subscript(i: Int) -> Factory.ItemType {
return items[i]
}
}
struct SegmentedDatasourceState {
var selectedIndex: Int = 0
}
/**
A Segmented Datasource.
Usage scenario is where a view (e.g. UITableView) displays the content relevant to
a selected UISegmentedControl tab, typically displayed above or below the table.
The SegmentedDatasource receives an array of DatasourceProviderType instances. This
means they must all be the same type, and therefore have the same underlying associated
types, e.g. model type. However, typical usage would involve using the tabs to
filter the same type of objects with some other metric. See the Example project.
*/
public final class SegmentedDatasource<DatasourceProvider: DatasourceProviderType>: DatasourceType {
public typealias UpdateBlock = () -> Void
private let state: Protector<SegmentedDatasourceState>
internal let update: UpdateBlock?
internal let datasources: [DatasourceProvider]
private var valueChangedHandler: TargetActionHandler? = .None
public let identifier: String
/// The index of the currently selected datasource provider
public var indexOfSelectedDatasource: Int {
return state.read { state in state.selectedIndex }
}
/// The currently selected datasource provider
public var selectedDatasourceProvider: DatasourceProvider {
return datasources[indexOfSelectedDatasource]
}
/// The currently selected datasource
public var selectedDatasource: DatasourceProvider.Datasource {
return selectedDatasourceProvider.datasource
}
/// The currently selected datasource's title
public var title: String? {
return selectedDatasource.title
}
/// The currently selected datasource's factory
public var factory: DatasourceProvider.Datasource.FactoryType {
return selectedDatasource.factory
}
init(id: String, datasources d: [DatasourceProvider], selectedIndex: Int = 0, didSelectDatasourceCompletion: UpdateBlock) {
identifier = id
datasources = d
state = Protector(SegmentedDatasourceState(selectedIndex: selectedIndex))
update = didSelectDatasourceCompletion
}
/**
Configures a segmented control with the datasource.
This will iterate through the datasources and insert a segment using the
datasource title for each one.
Additionally, it will add a handler for the .ValueChanged control event. The
action will select the appropriate datasource and call the
didSelectDatasourceCompletion completion block.
- parameter segmentedControl: the UISegmentedControl to configure.
*/
public func configureSegmentedControl(segmentedControl: UISegmentedControl) {
segmentedControl.removeAllSegments()
for (index, provider) in datasources.enumerate() {
let title = provider.datasource.title ?? "No title"
segmentedControl.insertSegmentWithTitle(title, atIndex: index, animated: false)
}
valueChangedHandler = TargetActionHandler { self.selectedSegmentedIndexDidChange($0) }
segmentedControl.addTarget(valueChangedHandler!, action: valueChangedHandler!.dynamicType.selector, forControlEvents: .ValueChanged)
segmentedControl.selectedSegmentIndex = indexOfSelectedDatasource
}
/**
Programatic interface to select a datasource at a given index.
- parameter index: an Int index.
*/
public func selectDatasourceAtIndex(index: Int) {
precondition(0 <= index, "Index must be greater than zero.")
precondition(index < datasources.count, "Index must be less than maximum number of datasources.")
state.write({ (inout state: SegmentedDatasourceState) in
state.selectedIndex = index
}, completion: update)
}
func selectedSegmentedIndexDidChange(sender: AnyObject?) {
if let segmentedControl = sender as? UISegmentedControl {
segmentedControl.userInteractionEnabled = false
selectDatasourceAtIndex(segmentedControl.selectedSegmentIndex)
segmentedControl.userInteractionEnabled = true
}
}
// DatasourceType
public var numberOfSections: Int {
return selectedDatasource.numberOfSections
}
public func numberOfItemsInSection(sectionIndex: Int) -> Int {
return selectedDatasource.numberOfItemsInSection(sectionIndex)
}
public func itemAtIndexPath(indexPath: NSIndexPath) -> DatasourceProvider.Datasource.FactoryType.ItemType? {
return selectedDatasource.itemAtIndexPath(indexPath)
}
public func cellForItemInView(view: DatasourceProvider.Datasource.FactoryType.ViewType, atIndexPath indexPath: NSIndexPath) -> DatasourceProvider.Datasource.FactoryType.CellType {
return selectedDatasource.cellForItemInView(view, atIndexPath: indexPath)
}
public func viewForSupplementaryElementInView(view: DatasourceProvider.Datasource.FactoryType.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> DatasourceProvider.Datasource.FactoryType.SupplementaryViewType? {
return selectedDatasource.viewForSupplementaryElementInView(view, kind: kind, atIndexPath: indexPath)
}
public func textForSupplementaryElementInView(view: DatasourceProvider.Datasource.FactoryType.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> DatasourceProvider.Datasource.FactoryType.TextType? {
return selectedDatasource.textForSupplementaryElementInView(view, kind: kind, atIndexPath: indexPath)
}
// SequenceType
public func generate() -> Array<DatasourceProvider>.Generator {
return datasources.generate()
}
// CollectionType
public var startIndex: Int {
return datasources.startIndex
}
public var endIndex: Int {
return datasources.endIndex
}
public subscript(i: Int) -> DatasourceProvider {
return datasources[i]
}
}
public struct SegmentedDatasourceProvider<DatasourceProvider: DatasourceProviderType>: DatasourceProviderType {
public typealias UpdateBlock = () -> Void
public let datasource: SegmentedDatasource<DatasourceProvider>
/// The index of the currently selected datasource provider
public var indexOfSelectedDatasource: Int {
return datasource.indexOfSelectedDatasource
}
/// The currently selected datasource provider
public var selectedDatasourceProvider: DatasourceProvider {
return datasource.selectedDatasourceProvider
}
/// The currently selected datasource
public var selectedDatasource: DatasourceProvider.Datasource {
return datasource.selectedDatasource
}
/**
The initializer.
- parameter id,: a String identifier for the datasource.
- parameter datasources,: an array of DatasourceProvider instances.
- parameter selectedIndex,: the index of the initial selection.
- parameter didSelectDatasourceCompletion,: a completion block which executes when selecting the datasource has completed. This block should reload the view.
*/
public init(id: String, datasources: [DatasourceProvider], selectedIndex: Int = 0, didSelectDatasourceCompletion: () -> Void) {
datasource = SegmentedDatasource(id: id, datasources: datasources, selectedIndex: selectedIndex, didSelectDatasourceCompletion: didSelectDatasourceCompletion)
}
/**
Call the equivalent function on SegmentedDatasource.
- parameter segmentedControl: the UISegmentedControl to configure.
*/
public func configureSegmentedControl(segmentedControl: UISegmentedControl) {
datasource.configureSegmentedControl(segmentedControl)
}
}
|
mit
|
e503e184757137571a7bf4370d982c63
| 35.588889 | 245 | 0.735742 | 5.285714 | false | false | false | false |
dinsight/AxiomKit
|
Sources/AXFactsLibrary.swift
|
1
|
1265
|
//
// StockFacts.swift
// AxiomKit
//
// Created by Alexandru Cotoman Jecu on 6/17/17.
// Copyright © 2017 Digital Insight, LLC. All rights reserved.
//
import Foundation
import PuppetMasterKit
public class AXFactsLibrary {
public class EntityFact : AXFact {
public private(set) weak var entity: PMEntity?
/**
Initialization
*/
public override init() {
super.init()
}
/**
Initialization
- Parameter agent: the agent to hunt
*/
public init(_ entity : PMEntity?) {
self.entity = entity
}
/**
Equality operator
*/
static open func ==(lhs: EntityFact, rhs: EntityFact) -> Bool {
return lhs.getTypeString() == rhs.getTypeString() && rhs.entity === lhs.entity
}
/**
Equality operator
*/
static open func !=(lhs: EntityFact, rhs: EntityFact) -> Bool {
return !(lhs == rhs)
}
}
public class Hunt : EntityFact { }
public class Hungry : EntityFact { }
public class Defend : EntityFact { }
}
|
mit
|
c18c2d5d35355dff298fa1d57b03acc3
| 20.423729 | 90 | 0.492089 | 4.75188 | false | false | false | false |
UIKonf/uikonf-app
|
UIKonfApp/UIKonfApp/TimeLineViewController.swift
|
1
|
8638
|
import UIKit
import Entitas
class TimeLineViewController: UITableViewController {
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).context
var groupOfEvents : Group!
let sectionNames = ["Before Conference", "Social Events Day", "First Conference Day", "Second Conference Day", "Hackathon Day", "The End"]
var events : [[Entity]] = [[], [], [], [], [], []]
private lazy var reload : dispatch_block_t = dispatch_debounce_block(0.1) {
self.navigationController?.popToRootViewControllerAnimated(true)
let events = sorted(self.groupOfEvents) {
e1 , e2 in
if !e1.has(StartTimeComponent) {
return true
}
if !e2.has(StartTimeComponent) {
return false
}
return e1.get(StartTimeComponent)!.date.timeIntervalSinceReferenceDate < e2.get(StartTimeComponent)!.date.timeIntervalSinceReferenceDate
}
for i in 0...5 {
self.events[i] = []
}
self.events[0].append(events.first!)
self.events[5].append(events.last!)
for event in events {
if !event.has(StartTimeComponent) || !event.has(EndTimeComponent){
continue
}
let day = calendar.component(NSCalendarUnit.CalendarUnitDay, fromDate: event.get(StartTimeComponent)!.date)
let index = day - 16
self.events[index].append(event)
}
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
groupOfEvents = context.entityGroup(Matcher.Any(StartTimeComponent, EndTimeComponent))
setNavigationTitleFont()
groupOfEvents.addObserver(self)
context.entityGroup(Matcher.All(RatingComponent)).addObserver(self)
readDataIntoContext(context)
syncData(context)
}
func setNavigationTitleFont(){
let font = UIFont(name: "AntennaExtraCond-Bold", size: 18)!
let fontKey : NSString = NSFontAttributeName
let attributes : [NSObject : AnyObject] = [fontKey : font]
self.navigationController?.navigationBar.titleTextAttributes = attributes
}
func updateSendButton(){
let button = UIBarButtonItem(title: "Send Ratings", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("sendRatings"))
self.navigationItem.leftBarButtonItem = button
}
@IBAction func scrollToNow(){
let now = NSDate()
let day = calendar.component(NSCalendarUnit.CalendarUnitDay, fromDate: now)
if groupOfEvents.count == 0 {
return
}
let nowSeconds = now.timeIntervalSince1970
if nowSeconds < events[1][0].get(StartTimeComponent)!.date.timeIntervalSince1970 {
self.tableView.selectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), animated: true, scrollPosition: UITableViewScrollPosition.Top)
} else if nowSeconds >= events[5][0].get(StartTimeComponent)!.date.timeIntervalSince1970 {
self.tableView.selectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 5), animated: true, scrollPosition: UITableViewScrollPosition.Top)
} else {
let section = day - 16
for (row, event) in enumerate(events[section]) {
let (startSeconds, endSeconds) = (event.get(StartTimeComponent)!.date.timeIntervalSince1970, event.get(EndTimeComponent)!.date.timeIntervalSince1970)
if nowSeconds >= startSeconds && now.timeIntervalSince1970 < endSeconds {
self.tableView.selectRowAtIndexPath(NSIndexPath(forRow: row, inSection: section), animated: true, scrollPosition: UITableViewScrollPosition.Top)
}
}
}
}
func sendRatings(){
let uuid = NSUserDefaults.standardUserDefaults().stringForKey("uuid")!
let serverEntity = context.entityGroup(Matcher.All(ServerComponent)).sortedEntities.first!
var url: NSURL = serverEntity.get(ServerComponent)!.url.URLByAppendingPathComponent(uuid)
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
let ratings = ratingsDict(context)
let numberOfTalks = context.entityGroup(Matcher.All(TitleComponent, SpeakerNameComponent)).count
let data = NSJSONSerialization.dataWithJSONObject(ratings, options: NSJSONWritingOptions(0), error: nil)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
let alertView : UIAlertView
if error == nil {
alertView = UIAlertView(title: "Thank you", message: "You just rated \(ratings.count) out of \(numberOfTalks) talks.", delegate: nil, cancelButtonTitle: "OK")
} else {
alertView = UIAlertView(title: "Ops, could not send", message: "Please try again later.", delegate: nil, cancelButtonTitle: "OK")
}
dispatch_async(dispatch_get_main_queue(), {
alertView.show()
})
})
}
}
extension TimeLineViewController {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return groupOfEvents.count == 0 ? 0 : sectionNames.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionNames[section]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier : String
switch indexPath.section {
case 0 : cellIdentifier = "beforeConference"
case 5 : cellIdentifier = "afterConference"
default : cellIdentifier = "timeSlot"
}
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! EntityCell
cell.updateWithEntity(events[indexPath.section][indexPath.row], context: context)
return cell as! UITableViewCell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
let event = events[indexPath.section][indexPath.row]
let height : CGFloat
if(!event.has(StartTimeComponent)){
height = 320
} else if (!event.has(EndTimeComponent)) {
height = 400
} else {
let duration = event.get(EndTimeComponent)!.date.timeIntervalSinceDate(event.get(StartTimeComponent)!.date)
height = CGFloat(100 * sqrt(duration / (60 * 30)))
}
return height
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let event = events[indexPath.section][indexPath.row]
if(!Matcher.All(StartTimeComponent, EndTimeComponent).isMatching(event)){
return
}
for selectedEntity in context.entityGroup(Matcher.All(StartTimeComponent, EndTimeComponent,SelectedComponent)){
selectedEntity.remove(SelectedComponent)
}
event.set(SelectedComponent())
return
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
if segue.identifier! == "showTimeSlotDetails" {
let vc = segue.destinationViewController as! TimeSlotViewController
vc.context = context
}
}
}
extension TimeLineViewController : GroupObserver {
func entityAdded(entity : Entity) {
if entity.has(RatingComponent){
updateSendButton()
} else {
reload()
}
}
func entityRemoved(entity : Entity, withRemovedComponent removedComponent : Component) {
if removedComponent is RatingComponent {
return
}
reload()
}
}
|
mit
|
45ef4bf4d886636257b085726b20e575
| 37.73991 | 174 | 0.629891 | 5.286414 | false | false | false | false |
Joachimdj/JobResume
|
Apps/Forum17/2017/Forum/Views/FavoritesListView.swift
|
1
|
9730
|
//
// FavoritesList.swift
// Forum
//
// Created by Joachim Dittman on 13/08/2017.
// Copyright © 2017 Joachim Dittman. All rights reserved.
//
import UIKit
class FavoritesListView: UIViewController,UITableViewDelegate,UITableViewDataSource {
var uc = UserController()
var tableView = UITableView()
var lectureContainer = [Lecture]()
var auctionContainer = [AuctionItem]()
let typeImagesArray = ["cirkel_workshop","cirkel_social","Cirkel_debat","cirkel_firehose","cirkel_3roundBurst","cirkel_talk"]
var dayNames = ["Fredag","Lørdag","Søndag"]
let items = ["Program","Auktion"]
var daySC = UISegmentedControl()
var type = 0
var line = UIView(frame:CGRect(x:5,y:55, width:UIScreen.main.bounds.width - 10,height:1))
var titleLabel = UILabel(frame:CGRect(x:10,y:27, width:UIScreen.main.bounds.width - 20,height:20))
var blurEffectView = UIVisualEffectView()
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = "Din oversigt".uppercased()
titleLabel.font = UIFont (name: "HelveticaNeue-Bold", size: 25)
titleLabel.textAlignment = .center
self.view.addSubview(titleLabel)
line.backgroundColor = .black
self.view.addSubview(line)
let bImage = UIButton()
bImage.frame = CGRect(x: -10,y: 2,width: 70,height: 70)
bImage.setImage(UIImage(named: "ic_exit_to_app")!.withRenderingMode(UIImageRenderingMode.alwaysTemplate), for: UIControlState())
bImage.tintColor = UIColor.black
bImage.addTarget(self, action: #selector(logOut(sender:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(bImage)
daySC = UISegmentedControl(items: items)
daySC.selectedSegmentIndex = 0
let frame = UIScreen.main.bounds
daySC.frame = CGRect(x:-2, y:55, width: frame.width + 4,height: 30)
daySC.addTarget(self, action: #selector(changeColor(sender:)), for: .valueChanged)
daySC.tintColor = .black
self.view.addSubview(daySC)
tableView.frame = CGRect(x:0,y:85, width:self.view.frame.width,height:self.view.frame.height - 132);
tableView.delegate = self
tableView.dataSource = self
tableView.register(LectureCell.self, forCellReuseIdentifier: "LectureCell")
tableView.register(AuctionListCell.self, forCellReuseIdentifier: "AuctionListCell")
tableView.backgroundColor = UIColor.clear
tableView.rowHeight = 75
tableView.separatorColor = .clear
self.view.addSubview(tableView)
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurEffectView.alpha = 0.0
self.tableView.addSubview(blurEffectView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
print("FavoriteListView")
if(type == 0)
{ tableView.rowHeight = 75
if(User.userContainer.count > 0)
{
reloadLectureFavorite()
}
}
else
{ tableView.rowHeight = 110
if(User.userContainer.count > 0)
{
reloadAuctionFavorite()
}
}
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.blurEffectView.alpha = 0.0
}, completion: nil)
}
func changeColor(sender: UISegmentedControl) {
type = sender.selectedSegmentIndex
if(type == 0)
{ tableView.rowHeight = 75
reloadLectureFavorite()
}
else
{ tableView.rowHeight = 110
reloadAuctionFavorite()
}
self.tableView.reloadData()
}
func reloadLectureFavorite()
{
lectureContainer.removeAll()
let con = uc.uc.favoriteLectures
var index = 0
while (index < 3) {
for i in con[index]!
{
i.day = index
lectureContainer.append(i)
}
index += 1
}
self.tableView.reloadData()
}
func reloadAuctionFavorite()
{
print("reload auction")
auctionContainer = uc.uc.favoriteAuctionItems
self.tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
if(type == 0)
{
return lectureContainer.count
}
else
{
return 1
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(type == 0){
let i = lectureContainer
var index = section
if(section - 1 < 0)
{
index = 0
}
if(index > 0)
{
if("\(dayNames[i[section].day])\(i[section].startTime!)\(i[section].endTime!)" != "\(dayNames[0])\(i[section - 1].startTime!)\(i[section - 1].endTime!)")
{
return"\(dayNames[i[section].day]) \(String(describing: i[section].startTime!)) - \(i[section].endTime!)"
}
else
{
return ""
}
}
else
{
return "\(dayNames[i[section].day]) \(String(describing:i[section].startTime!)) - \(i[section].endTime!)"
}
}
else
{
return ""
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(type == 1)
{
return auctionContainer.count
}
return 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(type == 0)
{
let cell:LectureCell = tableView.dequeueReusableCell(withIdentifier: "LectureCell", for: indexPath) as! LectureCell
cell.favorite.setImage(UIImage(named:"heartDark"), for: UIControlState())
cell.favorite.addTarget(self, action: #selector(updateFavorite(_:)), for: UIControlEvents.touchUpInside)
let item = lectureContainer[indexPath.section]
cell.typeImage.image = UIImage(named: typeImagesArray[Int(item.type!)!])
cell.titleLabel.text = item.name?.uppercased()
cell.placeLabel.text = item.place
cell.favorite.tag = indexPath.section
cell.selectionStyle = .none
return cell
}
else
{
let cell:AuctionListCell = tableView.dequeueReusableCell(withIdentifier: "AuctionListCell", for: indexPath) as! AuctionListCell
cell.favorite.setImage(UIImage(named:"heartDark"), for: UIControlState())
cell.favorite.addTarget(self, action: #selector(updateFavorite(_:)), for: UIControlEvents.touchUpInside)
let item = auctionContainer[indexPath.row]
if(item.image != nil)
{
if((URL(string:item.image!)) != nil)
{
cell.profileImageView.kf.setImage(with:URL(string:item.image!)!, placeholder: UIImage(named:"noPic"), options: nil, progressBlock: nil, completionHandler: { (image, error, CacheType, imageURL) in })
}
}
cell.titleLabel.text = item.name?.uppercased()
cell.startBid.text = "Startbud: \(item.startBid!) DKK"
cell.donator.text = "\(item.donator!)"
cell.favorite.tag = indexPath.row
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.blurEffectView.alpha = 1.0
}, completion: nil)
if(type == 0)
{
let vc = LectureItemView()
let item = lectureContainer[indexPath.section]
vc.lc = [item]
self.present(vc, animated: true, completion: nil)
}
else
{
let vc = AuctionItemView()
let item = auctionContainer[indexPath.section]
vc.ac = [item]
self.present(vc, animated: true, completion: nil)
}
}
func updateFavorite(_ sender:AnyObject)
{
if(type == 0)
{
let item = lectureContainer[sender.tag]
print("updateFavorite")
_ = uc.removeFromFavoritList(type: "lecture", lecture: item, auctionItem: nil)
reloadLectureFavorite()
}
else
{
let item = auctionContainer[sender.tag]
print("updateFavorite")
_ = uc.removeFromFavoritList(type: "auction", lecture: nil, auctionItem: item)
reloadAuctionFavorite()
}
}
func logOut(sender:AnyObject)
{
loadedFirst = false
loggedIn = false
self.tabBarController?.selectedIndex = 1
let vc = LoginView()
vc.logOut = true
self.present(vc,animated: true,completion: nil)
}
}
|
mit
|
98d51f5dfc4e7f02631b515632d5bdc0
| 32.657439 | 219 | 0.575923 | 4.63632 | false | false | false | false |
vulgur/Sources
|
CodeReader/View/FileListViewController.swift
|
1
|
4850
|
//
// FileListViewController.swift
// CodeReader
//
// Created by vulgur on 16/5/27.
// Copyright © 2016年 MAD. All rights reserved.
//
import UIKit
import Alamofire
import ObjectMapper
import EZLoadingActivity
class FileListViewController: UITableViewController {
var fileList = [RepoFile]()
var apiURLString: String?
var pathTitle: String!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib.init(nibName: "FileCell", bundle: nil), forCellReuseIdentifier: "FileCell")
configNavigationTitle()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let path = apiURLString {
fetchFileList(path)
}
}
// MARK: Private methods
func configNavigationTitle() {
let pathComponents = self.pathTitle.components(separatedBy: "/")
let currentPath = pathComponents[pathComponents.count-1]
let parentPath = pathComponents[pathComponents.count-2]
navigationItem.backBarButtonItem = UIBarButtonItem(title: currentPath == "" ? "/" : currentPath, style: UIBarButtonItemStyle.plain, target: nil, action: nil)
if pathTitle.characters.count > 30 {
navigationItem.title = ".../" + parentPath + "/" + currentPath
} else {
navigationItem.title = pathTitle
}
}
func fetchFileList(_ path: String) {
_ = EZLoadingActivity.show("loading files", disableUI: true)
Alamofire.request(path)
.responseArray(completionHandler: { (response: DataResponse<[RepoFile]>) in
if let items = response.result.value {
self.fileList = items
self.tableView.reloadData()
}
_ = EZLoadingActivity.hide()
})
// .responseJSON { (response) in
// switch response.result{
// case .success:
// if let items = Mapper<RepoFile>().mapArray(response.result.value) {
// self.fileList = items
// self.tableView.reloadData()
// }
// case .failure(let error):
// print(error)
// }
// EZLoadingActivity.hide()
// }
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fileList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FileCell", for: indexPath) as! FileCell
let file = fileList[(indexPath as NSIndexPath).row]
if file.type == "dir" {
cell.filenameLabel.textColor = UIColor(red: 51/255, green: 98/255, blue: 178/255, alpha: 1)
cell.fileIconImageView.image = UIImage(named: "dir")
} else {
cell.fileIconImageView.image = UIImage(named: "file")
}
cell.filenameLabel.text = file.name
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let file = fileList[(indexPath as NSIndexPath).row]
if file.type == "dir" {
let nextFileListVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FileListViewController") as! FileListViewController
nextFileListVC.apiURLString = file.apiURLString
if pathTitle == "/" {
nextFileListVC.pathTitle = self.pathTitle + file.name!
} else {
nextFileListVC.pathTitle = self.pathTitle + "/" + file.name!
}
navigationController?.pushViewController(nextFileListVC, animated: true)
} else if file.type == "file" {
performSegue(withIdentifier: "ShowCode", sender: file)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowCode" {
let codeVC = segue.destination as! CodeViewController
let file = sender as! RepoFile
RecentsManager.sharedManager.addRecentFile(file)
codeVC.file = file
}
}
@IBAction func backToRoot(_ sender: UIBarButtonItem) {
if let repoVC = navigationController?.viewControllers[1] {
_ = navigationController?.popToViewController(repoVC, animated: true)
} else {
_ = navigationController?.popToRootViewController(animated: true)
}
}
}
|
mit
|
654609863107228a1931d1824d14a231
| 36.867188 | 167 | 0.602022 | 5.064786 | false | false | false | false |
verticon/VerticonsToolbox
|
VerticonsToolbox/UI/View.swift
|
1
|
11887
|
//
// View.swift
// Toolbox
//
// Created by Robert Vaessen on 9/26/16.
// Copyright © 2016 Robert Vaessen. All rights reserved.
//
import UIKit
public extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
var viewController : UIViewController? {
func findViewController(forResponder responder: UIResponder) -> UIViewController? {
if let nextResponder = responder.next {
switch nextResponder {
case is UIViewController:
return nextResponder as? UIViewController
case is UIView:
return findViewController(forResponder: nextResponder)
default:
break
}
}
return nil
}
return findViewController(forResponder: self)
}
// Draw a circle with a line through it
func drawFailureIndication(lineWidth: CGFloat) {
let context = UIGraphicsGetCurrentContext()!;
context.saveGState()
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(lineWidth)
// First the circle
let minDimension = bounds.maxX < bounds.maxY ? bounds.maxX : bounds.maxY
let side = minDimension - lineWidth
context.addEllipse(in: CGRect(x: bounds.midX - (side / 2), y: bounds.midY - (side / 2), width: side, height: side))
context.strokePath()
// Then the line
let radius = Double(side / 2)
let startAngle = 135 * Double.pi / 180
let startX = radius * cos(startAngle)
let startY = -radius * sin(startAngle) // Positive Y is down instead of up, hence the negative sign to correct
let finishAngle = 315 * Double.pi / 180
let finishX = radius * cos(finishAngle)
let finishY = -radius * sin(finishAngle)
context.translateBy(x: bounds.midX, y: bounds.midY) // Place the origin in the middle
context.move(to: CGPoint(x: startX, y: startY)) // Move onto the circle at the start angle
context.addLine(to: CGPoint(x: finishX, y: finishY)) // Draw a line across the circle
context.strokePath()
context.translateBy(x: -bounds.midX, y: -bounds.midY) // Put the origin back to where it was
context.restoreGState()
}
}
@IBDesignable open class GradientView: UIView {
@IBInspectable @objc dynamic public var firstColor = UIColor.white
@IBInspectable @objc dynamic public var secondColor = UIColor.black
override open class var layerClass: AnyClass {
return CAGradientLayer.self
}
override open func layoutSubviews() {
(layer as? CAGradientLayer)?.colors = [firstColor.cgColor, secondColor.cgColor]
super.layoutSubviews()
}
}
public struct MarchingAntsRect {
private let rect: CAShapeLayer
private let rectAnimation: CABasicAnimation
private let rectAnimationKey = "marchingAntsBorder"
public init(bounds: CGRect, color: UIColor) {
rect = CAShapeLayer()
rect.bounds = bounds
rect.strokeColor = color.cgColor
rect.fillColor = nil
rect.lineWidth = 2
rect.lineDashPattern = [10,5,5,5]
rect.lineDashPhase = 0
let path = CGMutablePath()
let minX: CGFloat = rect.lineWidth
let maxX: CGFloat = rect.bounds.maxX - rect.lineWidth
let minY: CGFloat = rect.lineWidth
let maxY: CGFloat = rect.bounds.maxY - rect.lineWidth
path.addLines(between: [
CGPoint(x: minX, y: minY),
CGPoint(x: maxX, y: minY),
CGPoint(x: maxX, y: maxY),
CGPoint(x: minX, y: maxY),
CGPoint(x: minX, y: minY)
])
rect.path = path
rectAnimation = CABasicAnimation(keyPath: #keyPath(CAShapeLayer.lineDashPhase))
rectAnimation.fromValue = 0
rectAnimation.toValue = rect.lineDashPattern?.reduce(0) { $0 + $1.intValue }
rectAnimation.duration = 1
rectAnimation.repeatCount = Float.greatestFiniteMagnitude
}
public var bounds: CGRect { return rect.bounds }
public var installed: Bool { rect.superlayer != nil }
public enum Installation : Error {
case notInstalled
case alreadyInstalled
}
public func install(in: UIView) throws {
guard !installed else { throw Installation.alreadyInstalled }
rect.position = `in`.layer.position
`in`.layer.addSublayer(rect)
}
public func startMarching() throws {
guard installed else { throw Installation.notInstalled }
rect.add(rectAnimation, forKey: rectAnimationKey)
}
public var isMarching: Bool {
return installed && rect.animation(forKey: rectAnimationKey) != nil
}
public func stopMarching() throws {
guard installed else { throw Installation.notInstalled }
rect.removeAnimation(forKey: rectAnimationKey)
}
public func uninstall() throws {
guard installed else { throw Installation.notInstalled }
rect.removeFromSuperlayer()
}
}
/*
public extension UIView {
/*
let myCustomView = CustomView.fromNib() // NIB named "CustomView"
let myCustomView: CustomView? = CustomView.fromNib() // NIB named "CustomView" might not exist
let myCustomView = CustomView.fromNib("some other NIB name")
I encountered some difficulty with the connection of the NIB to the custom class' outlets.
I found that I needed to configure the NIB in a certain way:
1) For the Fileowner - In the Identity Inspector, leave the Custom Class blank
2) For the outermost View - In the Identity Inspector, set the Custom Class to the desired class
3) For the outermost View - In the Connection Inspector, make the connections to the subviews in the Document Outline.
*/
/* Throws an exception if the view specifies connections because no owner is provided to which to wire the outlets
Strangely, it seems to be okay for the nib to specify actions.
2017-03-18 17:04:24.122 Nibs[51960:29042640] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x61000000b7c0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key clickMe.'
*** First throw call stack:
(
0 CoreFoundation 0x000000010be96d4b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x00000001098d921e objc_exception_throw + 48
2 CoreFoundation 0x000000010be96c99 -[NSException raise] + 9
3 Foundation 0x00000001093e79df -[NSObject(NSKeyValueCoding) setValue:forKey:] + 291
4 UIKit 0x000000010a1b779e -[UIRuntimeOutletConnection connect] + 109
5 CoreFoundation 0x000000010be3b9e0 -[NSArray makeObjectsPerformSelector:] + 256
6 UIKit 0x000000010a1b6122 -[UINib instantiateWithOwner:options:] + 1867
7 UIKit 0x000000010a1b83bb -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 223
8 VerticonsToolbox 0x00000001093482f6 _TZFE16VerticonsToolboxCSo6UIView7fromNibuRxS0_rfTGSqSS_4typeMx_GSqx_ + 1158
9 VerticonsToolbox 0x0000000109347c83 _TZFE16VerticonsToolboxCSo6UIView7fromNibuRxS0_rfTGSqSS_4typeMx_x + 163
10 VerticonsToolbox 0x0000000109347bb1 _TZFE16VerticonsToolboxCSo6UIView7fromNibfGSqSS_DS0_ + 145
11 VerticonsToolbox 0x0000000109347e0c _TToZFE16VerticonsToolboxCSo6UIView7fromNibfGSqSS_DS0_ + 204
12 Nibs 0x0000000109299b47 _TFC4Nibs18NibsViewController11viewDidLoadfT_T_ + 711
13 Nibs 0x0000000109299d02 _TToFC4Nibs18NibsViewController11viewDidLoadfT_T_ + 34
14 UIKit 0x0000000109f4aa3d -[UIViewController loadViewIfRequired] + 1258
15 UIKit 0x0000000109f4ae70 -[UIViewController view] + 27
16 UIKit 0x0000000109e144b5 -[UIWindow addRootViewControllerViewIfPossible] + 71
17 UIKit 0x0000000109e14c06 -[UIWindow _setHidden:forced:] + 293
18 UIKit 0x0000000109e28519 -[UIWindow makeKeyAndVisible] + 42
19 UIKit 0x0000000109da0f8d -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4818
20 UIKit 0x0000000109da70ed -[UIApplication _runWithMainScene:transitionContext:completion:] + 1731
21 UIKit 0x0000000109da426d -[UIApplication workspaceDidEndTransaction:] + 188
22 FrontBoardServices 0x000000010f3516cb __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
23 FrontBoardServices 0x000000010f351544 -[FBSSerialQueue _performNext] + 189
24 FrontBoardServices 0x000000010f3518cd -[FBSSerialQueue _performNextFromRunLoopSource] + 45
25 CoreFoundation 0x000000010be3b761 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
26 CoreFoundation 0x000000010be2098c __CFRunLoopDoSources0 + 556
27 CoreFoundation 0x000000010be1fe76 __CFRunLoopRun + 918
28 CoreFoundation 0x000000010be1f884 CFRunLoopRunSpecific + 420
29 UIKit 0x0000000109da2aea -[UIApplication _run] + 434
30 UIKit 0x0000000109da8c68 UIApplicationMain + 159
31 Nibs 0x000000010929b66f main + 111
32 libdyld.dylib 0x000000010dcd468d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
*/
public class func fromNib(_ nibNameOrNil: String? = nil) -> Self {
return fromNib(nibNameOrNil, type: self)
}
public class func fromNib<T : UIView>(_ nibNameOrNil: String? = nil, type: T.Type) -> T {
let v: T? = fromNib(nibNameOrNil, type: T.self)
return v!
}
public class func fromNib<T : UIView>(_ nibNameOrNil: String? = nil, type: T.Type) -> T? {
let name = nibNameOrNil == nil ? nibName : nibNameOrNil!
if let views = Bundle(for: type).loadNibNamed(name, owner: nil) {
for view in views {
if let v = view as? T { return v }
}
}
return nil
}
public class var nibName: String {
let name = "\(self)".components(separatedBy: ".").first ?? ""
return name
}
public class var nib: UINib? {
if let _ = Bundle.main.path(forResource: nibName, ofType: "nib") {
return UINib(nibName: nibName, bundle: nil)
} else {
return nil
}
}
}
*/
|
mit
|
a6efddad812a7350f797fff570a692c6
| 41.298932 | 251 | 0.607017 | 4.590962 | false | false | false | false |
JGiola/swift
|
test/Sanitizers/tsan/mainactor.swift
|
5
|
2542
|
// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking %import-libdispatch -sanitize=thread) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// REQUIRES: tsan_runtime
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: threading_none
import Dispatch
/// @returns true iff the expected answer is actually the case, i.e., correct.
/// If the current queue does not match expectations, this function may return
/// false or just crash the program with non-zero exit code, depending on SDK.
func checkIfMainQueue(expectedAnswer expected: Bool) -> Bool {
if #available(macOS 10.12, iOS 10, tvOS 10, watchOS 3, *) {
dispatchPrecondition(condition: expected ? .onQueue(DispatchQueue.main)
: .notOnQueue(DispatchQueue.main))
}
return true
}
actor A {
func onCorrectQueue(_ count : Int) -> Int {
if checkIfMainQueue(expectedAnswer: false) {
print("on actor instance's queue")
return count + 1
}
print("ERROR: not on actor instance's queue")
return -10
}
}
@MainActor func checkAnotherFn(_ count : Int) -> Int {
if checkIfMainQueue(expectedAnswer: true) {
print("on main queue again!")
return count + 1
} else {
print("ERROR: left the main queue?")
return -10
}
}
@MainActor func enterMainActor(_ initialCount : Int) async -> Int {
if checkIfMainQueue(expectedAnswer: true) {
print("hello from main actor!")
} else {
print("ERROR: not on correct queue!")
}
// try calling a function on another actor.
let count = await A().onCorrectQueue(initialCount)
guard checkIfMainQueue(expectedAnswer: true) else {
print("ERROR: did not switch back to main actor!")
return -10
}
return checkAnotherFn(count) + 1
}
@Sendable func someFunc() async -> Int {
// NOTE: the "return" counter is just to make sure we're properly returning values.
// the expected number should be equal to the number of "plus-one" expressions.
// since there are no loops or duplicate function calls
return await enterMainActor(0) + 1
}
// CHECK: starting
// CHECK-NOT: ERROR
// CHECK: hello from main actor!
// CHECK-NOT: ERROR
// CHECK: on actor instance's queue
// CHECK-NOT: ERROR
// CHECK: on main queue again!
// CHECK-NOT: ERROR
// CHECK: finished with return counter = 4
@main struct RunIt {
static func main() async {
print("starting")
let result = await someFunc()
print("finished with return counter = \(result)")
}
}
|
apache-2.0
|
5706c40cde7812d9d54f0b2e84c9e1ee
| 28.55814 | 147 | 0.682927 | 3.978091 | false | false | false | false |
Augustyniak/RATreeView
|
Examples/RATreeViewBasicExampleSwift/TreeViewController.swift
|
2
|
6040
|
//
// TreeViewController.swift
// RATreeViewExamples
//
// Created by Rafal Augustyniak on 21/11/15.
// Copyright © 2015 com.Augustyniak. All rights reserved.
//
import UIKit
import RATreeView
class TreeViewController: UIViewController, RATreeViewDelegate, RATreeViewDataSource {
var treeView : RATreeView!
var data : [DataObject]
var editButton : UIBarButtonItem!
convenience init() {
self.init(nibName : nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
data = TreeViewController.commonInit()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
data = TreeViewController.commonInit()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "Things"
setupTreeView()
updateNavigationBarButtons()
}
func setupTreeView() -> Void {
treeView = RATreeView(frame: view.bounds)
treeView.register(UINib(nibName: String(describing: TreeTableViewCell.self), bundle: nil), forCellReuseIdentifier: String(describing: TreeTableViewCell.self))
treeView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
treeView.delegate = self;
treeView.dataSource = self;
treeView.treeFooterView = UIView()
treeView.backgroundColor = .clear
view.addSubview(treeView)
}
func updateNavigationBarButtons() -> Void {
let systemItem = treeView.isEditing ? UIBarButtonSystemItem.done : UIBarButtonSystemItem.edit;
self.editButton = UIBarButtonItem(barButtonSystemItem: systemItem, target: self, action: #selector(TreeViewController.editButtonTapped(_:)))
self.navigationItem.rightBarButtonItem = self.editButton;
}
func editButtonTapped(_ sender: AnyObject) -> Void {
treeView.setEditing(!treeView.isEditing, animated: true)
updateNavigationBarButtons()
}
//MARK: RATreeView data source
func treeView(_ treeView: RATreeView, numberOfChildrenOfItem item: Any?) -> Int {
if let item = item as? DataObject {
return item.children.count
} else {
return self.data.count
}
}
func treeView(_ treeView: RATreeView, child index: Int, ofItem item: Any?) -> Any {
if let item = item as? DataObject {
return item.children[index]
} else {
return data[index] as AnyObject
}
}
func treeView(_ treeView: RATreeView, cellForItem item: Any?) -> UITableViewCell {
let cell = treeView.dequeueReusableCell(withIdentifier: String(describing: TreeTableViewCell.self)) as! TreeTableViewCell
let item = item as! DataObject
let level = treeView.levelForCell(forItem: item)
let detailsText = "Number of children \(item.children.count)"
cell.selectionStyle = .none
cell.setup(withTitle: item.name, detailsText: detailsText, level: level, additionalButtonHidden: false)
cell.additionButtonActionBlock = { [weak treeView] cell in
guard let treeView = treeView else {
return;
}
let item = treeView.item(for: cell) as! DataObject
let newItem = DataObject(name: "Added value")
item.addChild(newItem)
treeView.insertItems(at: IndexSet(integer: item.children.count-1), inParent: item, with: RATreeViewRowAnimationNone);
treeView.reloadRows(forItems: [item], with: RATreeViewRowAnimationNone)
}
return cell
}
//MARK: RATreeView delegate
func treeView(_ treeView: RATreeView, commit editingStyle: UITableViewCellEditingStyle, forRowForItem item: Any) {
guard editingStyle == .delete else { return; }
let item = item as! DataObject
let parent = treeView.parent(forItem: item) as? DataObject
let index: Int
if let parent = parent {
index = parent.children.index(where: { dataObject in
return dataObject === item
})!
parent.removeChild(item)
} else {
index = self.data.index(where: { dataObject in
return dataObject === item;
})!
self.data.remove(at: index)
}
self.treeView.deleteItems(at: IndexSet(integer: index), inParent: parent, with: RATreeViewRowAnimationRight)
if let parent = parent {
self.treeView.reloadRows(forItems: [parent], with: RATreeViewRowAnimationNone)
}
}
}
private extension TreeViewController {
static func commonInit() -> [DataObject] {
let phone1 = DataObject(name: "Phone 1")
let phone2 = DataObject(name: "Phone 2")
let phone3 = DataObject(name: "Phone 3")
let phone4 = DataObject(name: "Phone 4")
let phones = DataObject(name: "Phones", children: [phone1, phone2, phone3, phone4])
let notebook1 = DataObject(name: "Notebook 1")
let notebook2 = DataObject(name: "Notebook 2")
let computer1 = DataObject(name: "Computer 1", children: [notebook1, notebook2])
let computer2 = DataObject(name: "Computer 2")
let computer3 = DataObject(name: "Computer 3")
let computers = DataObject(name: "Computers", children: [computer1, computer2, computer3])
let cars = DataObject(name: "Cars")
let bikes = DataObject(name: "Bikes")
let houses = DataObject(name: "Houses")
let flats = DataObject(name: "Flats")
let motorbikes = DataObject(name: "motorbikes")
let drinks = DataObject(name: "Drinks")
let food = DataObject(name: "Food")
let sweets = DataObject(name: "Sweets")
let watches = DataObject(name: "Watches")
let walls = DataObject(name: "Walls")
return [phones, computers, cars, bikes, houses, flats, motorbikes, drinks, food, sweets, watches, walls]
}
}
|
mit
|
71d3e199222d530dc8a03c96235ec29c
| 35.379518 | 166 | 0.64514 | 4.699611 | false | false | false | false |
m-nakada/RUG
|
Carthage/Checkouts/Himotoki/Himotoki/decode.swift
|
2
|
1666
|
//
// decode.swift
// Himotoki
//
// Created by Syo Ikeda on 5/19/15.
// Copyright (c) 2015 Syo Ikeda. All rights reserved.
//
/// - Throws: DecodeError
public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject) throws -> T {
let extractor = Extractor(object)
return try T.decode(extractor)
}
/// - Throws: DecodeError
public func decode<T: Decodable where T.DecodedType == T>(object: AnyObject, rootKeyPath: KeyPath) throws -> T {
return try decode(object) <| rootKeyPath
}
/// - Throws: DecodeError
public func decodeArray<T: Decodable where T.DecodedType == T>(object: AnyObject) throws -> [T] {
guard let array = object as? [AnyObject] else {
throw typeMismatch("Array", actual: object, keyPath: nil)
}
return try array.map(decode)
}
/// - Throws: DecodeError
public func decodeArray<T: Decodable where T.DecodedType == T>(object: AnyObject, rootKeyPath: KeyPath) throws -> [T] {
return try decode(object) <|| rootKeyPath
}
/// - Throws: DecodeError
public func decodeDictionary<T: Decodable where T.DecodedType == T>(object: AnyObject) throws -> [String: T] {
guard let dictionary = object as? [String: AnyObject] else {
throw typeMismatch("Dictionary", actual: object, keyPath: nil)
}
return try dictionary.reduce([:]) { (var accum: [String: T], element) in
let (key, value) = element
accum[key] = try decode(value) as T
return accum
}
}
/// - Throws: DecodeError
public func decodeDictionary<T: Decodable where T.DecodedType == T>(object: AnyObject, rootKeyPath: KeyPath) throws -> [String: T] {
return try decode(object) <|-| rootKeyPath
}
|
mit
|
317d72e4beb1b8214c992b3bf8105586
| 32.32 | 132 | 0.673469 | 3.929245 | false | false | false | false |
alvarofrutos/IRPFCalculatorLibrary
|
IRPFCalculatorLibrary/PersonalData.swift
|
1
|
4032
|
//
// PersonalData.swift
// IRPFCalculatorLibrary
//
// Created by Álvaro Frutos on 11/12/14.
// Copyright (c) 2014 Álvaro Frutos. All rights reserved.
//
import UIKit
// MARK: - Enums
enum Payments : Int {
case Pay12 = 12
case Pay14 = 14
case Pay15 = 15
case Pay16 = 16
static let all = [Pay12, Pay14, Pay15, Pay16]
}
enum FamilySituation : String {
case Status1 = "status_1"
case Status2 = "status_2"
case Others = "status_3"
static let all = [Status1, Status2, Others]
}
enum ProfessionalSituation : String {
case Employed = "employed"
case Pensioner = "pensioner"
case Unemployed = "unemployed"
case Others = "others"
static let all = [Employed, Pensioner, Unemployed, Others]
}
enum ProfessionalRelation : String {
case General = "general"
case OneYear = "one_year"
case Special = "special"
case Sporadic = "sporadic"
static let all = [General, OneYear, Special, Sporadic]
}
enum ContributionBasis : String {
case Basis1 = "basis_1"
case Basis2 = "basis_2"
case Basis3 = "basis_3"
case Basis4 = "basis_4"
case Basis5 = "basis_5"
case Basis6 = "basis_6"
case Basis7 = "basis_7"
static let all = [Basis1, Basis2, Basis3, Basis4 , Basis5, Basis6, Basis7]
}
enum ContractType : String {
case General = "general_type"
case FullTime = "full_time_type"
case PartialTime = "partial_time_type"
static let all = [General, FullTime, PartialTime]
}
enum Disability : String {
case None = "disability_no"
case Lv33 = "disability_33"
case Lv65 = "disability_65"
static let all = [None, Lv33, Lv65]
}
class PersonalData: NSObject {
// MARK: - Properties
var earnings : Double = 0.0
var payments : Payments = Payments.Pay14
var birthDate : NSDate
var familySituation : FamilySituation = .Others
var professionalSituation : ProfessionalSituation = .Employed
var professionalRelation : ProfessionalRelation = .General
var contributionBasis : ContributionBasis = .Basis1
var contractType : ContractType = .General
var disability : Disability = .None
var needsHelp : Bool = false
var mobility : Bool = false
var ceutaMelilla : Bool = false
var extendedActivity : Bool = false
var ascendants = [Ascendant]()
var descendants = [Descendant]()
var irreg1 : Double = 0.0
var irreg2 : Double = 0.0
var expenses : Double = 0.0
var compensatory : Bool = false
var compensatoryAmount : Double = 0.0
var annuity : Bool = false
var annuityAmount : Double = 0.0
var dwellingLoan : Bool = false
// MARK: - Methods
override init() {
birthDate = initBirthDate()
super.init()
}
// MARK: - Relatives handling
func numberOfRelatives() -> Int {
return ascendants.count + descendants.count
}
func numberOfAscendants() -> Int {
return ascendants.count
}
func numberOfDescendants() -> Int {
return descendants.count
}
func addAscendant() {
ascendants.append(Ascendant())
}
func addDescendant() {
descendants.append(Descendant())
}
func removeAscendantAtIndex(index: Int) {
ascendants.removeAtIndex(index)
}
func removeDescendantAtIndex(index: Int) {
descendants.removeAtIndex(index)
}
}
|
agpl-3.0
|
5e20f854b26fad9a05cee0eb1e7bc5b9
| 23.424242 | 78 | 0.539454 | 4.10387 | false | false | false | false |
banxi1988/Staff
|
Staff/RecordDateRangeHeaderView.swift
|
1
|
2966
|
//
// RecordDateRangeHeaderView.swift
// Staff
//
// Created by Haizhen Lee on 16/3/3.
// Copyright © 2016年 banxi1988. All rights reserved.
//
import Foundation
//UICollectionReusableView
// Build for target uimodel
import UIKit
import BXModel
import SwiftyJSON
import BXiOSUtils
import BXForm
//-RecordDateRangeHeaderView:v
//title[l15,t8,b8](f15,cpt)
//disclosure[r8,ver0,w60]:b
class RecordDateRangeHeaderView : UICollectionReusableView ,BXBindable {
let titleLabel = UILabel(frame:CGRectZero)
let disclosureButton = UIButton(type:.System)
let worked_timeLabel = UILabel(frame: CGRectZero)
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
var item:RecordDateRange?
func bind(item:RecordDateRange){
self.item = item
titleLabel.text = item.rangeTitle
NSNotificationCenter.defaultCenter().addObserverForName(AppEvents.ClockDataSetChanged, object: nil, queue: nil) { [weak self] (notf) -> Void in
self?.asyncCountWorkedTime(item)
}
asyncCountWorkedTime(item)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func asyncCountWorkedTime(item:RecordDateRange){
bx_async{ [weak self] in
let clockStatus = ClockRecordHelper.clockStatusInRange(item)
bx_runInUiThread{
self?.worked_timeLabel.text = "时长累计: " + clockStatus.worked_time
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var allOutlets :[UIView]{
return [titleLabel,disclosureButton,worked_timeLabel]
}
var allUIButtonOutlets :[UIButton]{
return [disclosureButton]
}
var allUILabelOutlets :[UILabel]{
return [titleLabel,worked_timeLabel]
}
func commonInit(){
for childView in allOutlets{
addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
func installConstaints(){
titleLabel.pa_bottom.eq(8).withLowPriority.install()
titleLabel.pa_top.eq(8).withLowPriority.install()
titleLabel.pa_centerY.install()
titleLabel.pa_leading.eq(15).install()
worked_timeLabel.pa_leading.eq(85).install()
worked_timeLabel.pa_centerY.install()
disclosureButton.pa_trailing.eq(8).install()
disclosureButton.pac_vertical(0)
disclosureButton.pa_width.eq(60).install()
}
func setupAttrs(){
backgroundColor = AppColors.colorPrimary
titleLabel.textColor = AppColors.primaryTextColor
titleLabel.font = UIFont.systemFontOfSize(15)
worked_timeLabel.textColor = AppColors.primaryTextColor
worked_timeLabel.font = UIFont.systemFontOfSize(13)
disclosureButton.hidden = true
disclosureButton.setTitle("统计", forState: .Normal)
disclosureButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
}
}
|
mit
|
5951a10e35d2ed0978317aa0c16bc07a
| 25.115044 | 147 | 0.712301 | 4.221745 | false | false | false | false |
anasmeister/nRF-Coventry-University
|
Pods/EVReflection/EVReflection/pod/EVExtensions.swift
|
1
|
3976
|
//
// EVExtensions.swift
// EVReflection
//
// Created by Edwin Vermeer on 9/2/15.
// Copyright © 2015 evict. All rights reserved.
//
import Foundation
/**
Implementation for Equatable ==
- parameter lhs: The object at the left side of the ==
- parameter rhs: The object at the right side of the ==
- returns: True if the objects are the same, otherwise false.
*/
public func == (lhs: EVObject, rhs: EVObject) -> Bool {
return EVReflection.areEqual(lhs, rhs: rhs)
}
/**
Implementation for Equatable !=
- parameter lhs: The object at the left side of the ==
- parameter rhs: The object at the right side of the ==
- returns: False if the objects are the the same, otherwise true.
*/
public func != (lhs: EVObject, rhs: EVObject) -> Bool {
return !EVReflection.areEqual(lhs, rhs: rhs)
}
/**
Extending Array with an initializer with a json string
*/
public extension Array where Element: NSObject {
/**
Initialize an array based on a json string
- parameter json: The json string
- parameter conversionOptions: Option set for the various conversion options.
*/
public init(json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize) {
self.init()
let arrayTypeInstance = getArrayTypeInstance(self)
let newArray = EVReflection.arrayFromJson(nil, type:arrayTypeInstance, json: json, conversionOptions: conversionOptions)
for item in newArray {
self.append(item)
}
}
/**
Initialize an array based on a dictionary
- parameter json: The json string
- parameter conversionOptions: Option set for the various conversion options.
*/
public init(dictionaryArray: [NSDictionary], conversionOptions: ConversionOptions = .DefaultDeserialize) {
self.init()
for item in dictionaryArray {
let arrayTypeInstance = getArrayTypeInstance(self)
if arrayTypeInstance is EVObject {
EVReflection.setPropertiesfromDictionary(item, anyObject: arrayTypeInstance as! EVObject)
self.append(arrayTypeInstance)
}
}
}
/**
Get the type of the object where this array is for
- parameter arr: this array
- returns: The object type
*/
public func getArrayTypeInstance<T: NSObject>(_ arr: Array<T>) -> T {
return arr.getTypeInstance()
}
/**
Get the type of the object where this array is for
- returns: The object type
*/
public func getTypeInstance<T: NSObject>(
) -> T {
let nsobjectype: NSObject.Type = T.self
let nsobject: NSObject = nsobjectype.init()
if let obj = nsobject as? T {
return obj
}
// Could not instantiate array item instance.
return T()
}
/**
Get the string representation of the type of the object where this array is for
- returns: The object type
*/
public func getTypeAsString() -> String {
let item = self.getTypeInstance()
return NSStringFromClass(type(of:item))
}
/**
Convert this array to a json string
- parameter conversionOptions: Option set for the various conversion options.
- returns: The json string
*/
public func toJsonString(_ conversionOptions: ConversionOptions = .DefaultSerialize) -> String {
return "[\n" + self.map({($0 as? EVObject ?? EVObject()).toJsonString(conversionOptions)}).joined(separator: ", \n") + "\n]"
}
/**
Returns the dictionary representation of this array.
- parameter conversionOptions: Option set for the various conversion options.
- returns: The array of dictionaries
*/
public func toDictionaryArray(_ conversionOptions: ConversionOptions = .DefaultSerialize) -> NSArray {
return self.map({($0 as? EVObject ?? EVObject()).toDictionary(conversionOptions)}) as NSArray
}
}
|
bsd-3-clause
|
f02598611eedd6e151d664f7238893d0
| 29.343511 | 132 | 0.647799 | 4.606025 | false | false | false | false |
mcxiaoke/learning-ios
|
ios_programming_4th/HypnoNerd-ch6/HypnoNerd/HypnosisterView.swift
|
1
|
1808
|
//
// HypnosisterView.swift
// Hypnosister
//
// Created by Xiaoke Zhang on 2017/8/15.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import UIKit
class HypnosisterView: UIView {
var circleColor = UIColor.lightGray {
didSet {
setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) {
let bounds = self.bounds
var center = CGPoint()
center.x = bounds.origin.x + bounds.size.width/2.0;
center.y = bounds.origin.y + bounds.size.height/2.0;
let maxRadius = hypot(bounds.size.width, bounds.size.height)/2.0;
let path = UIBezierPath()
var currentRadius = maxRadius
while currentRadius>0 {
path.move(to: CGPoint(x:center.x+currentRadius, y:center.y))
path.addArc(withCenter: center,
radius: currentRadius,
startAngle: 0.0,
endAngle: CGFloat(Double.pi*2),
clockwise: true)
currentRadius -= 20
}
path.lineWidth = 10
circleColor.setStroke()
path.stroke()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let red = CGFloat(arc4random_uniform(100))/100.0
let green = CGFloat(arc4random_uniform(100))/100.0
let blue = CGFloat(arc4random_uniform(100))/100.0
let color = UIColor(red:red, green:green, blue:blue, alpha:1.0)
self.circleColor = color
}
}
|
apache-2.0
|
3910ed4a233df707126a5b3ce47b261f
| 28.590164 | 79 | 0.572853 | 4.187935 | false | false | false | false |
BENMESSAOUD/RSS
|
News/ViewControllers/DetailNewsViewController.swift
|
1
|
1653
|
//
// DetailNewsViewController.swift
// News
//
// Created by Mahmoud Ben Messaoud on 18/03/2017.
// Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved.
//
import UIKit
import Kingfisher
class DetailNewsViewController: UIViewController {
var news: Item?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionText: UITextView!
@IBOutlet weak var newsPhoto: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var siteButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = news?.title ?? kEmptyString
if let newsDate = news?.date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss"
self.dateLabel.text = dateFormatter.string(from: newsDate)
}
else{
self.dateLabel.text = kEmptyString
}
newsPhoto.kf.indicatorType = .activity
newsPhoto.kf.setImage(with: news, placeholder: #imageLiteral(resourceName: "loadingImage"), options: [.transition(.fade(1))], progressBlock: nil, completionHandler: nil)
descriptionText.text = news?.description ?? kEmptyString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func goToSite(_ sender: Any) {
guard let link = news?.link, let url = URL(string: link) else {
return
}
if UIApplication.shared.canOpenURL(url){
UIApplication.shared.open(url, completionHandler: nil)
}
}
}
|
mit
|
2d92449251c4cc47c1b03a5693a22ca5
| 33.416667 | 177 | 0.65678 | 4.653521 | false | false | false | false |
andreyFreeman/EasyCoreData
|
Demo/EasyCoreDataDemo/EasyCoreDataDemo/AlbumDetailsVC.swift
|
1
|
3138
|
//
// AlbumDetailsVC.swift
// EasyCoreDataDemo
//
// Created by Andrey Kladov on 02/05/15.
// Copyright (c) 2015 Andrey Kladov. All rights reserved.
//
import UIKit
import CoreData
import EasyCoreData
class AlbumDetailsVC: UITableViewController {
@IBOutlet weak var coverImageView: UIImageView!
@IBOutlet weak var artistLabel: UILabel!
@IBOutlet weak var albumTitleLabel: UILabel!
@IBOutlet weak var genreLabel: UILabel!
private struct Consts {
static let tableViewCell = "trackCell"
}
var album: Album?
var items: [Track] = []
override func viewDidLoad() {
super.viewDidLoad()
switch (album?.tracks?.count, album?.trackCount, album) {
case (.Some(let actual), .Some(let expected), .Some(let album)) where actual == Int(expected):
items = NSManagedObjectContext.mainThreadContext.fetchObjects(Track.self, predicate: NSPredicate(format: "album == %@", album), sortDescriptors: [NSSortDescriptor(key: "sortingOrder", ascending: true)])
case (_, _, .Some(let album)):
SVProgressHUD.showWithStatus(NSLocalizedString("Loading songs...", comment: ""), maskType: .Gradient)
APIController.sharedController.loadSongsForAlbum(album) { [weak self] objects, error in
SVProgressHUD.dismiss()
if let err = error {
UIAlertView(title: NSLocalizedString("Oops", comment: ""), message: err.localizedDescription, delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "")).show()
} else if let tracks = objects {
self?.items = tracks
}
self?.tableView?.reloadData()
}
default: break
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reloadData()
}
func reloadData() {
artistLabel?.text = album?.artist
albumTitleLabel?.text = album?.title
genreLabel?.text = album?.genre
if let url = album?.artworkUrl100 {
coverImageView?.sd_setImageWithURL(NSURL(string: url)) { [weak self] _ in self?.coverImageView?.runFade(0.2) }
} else {
coverImageView?.image = nil
}
tableView?.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Consts.tableViewCell, forIndexPath: indexPath)
let track = items[indexPath.row]
(cell.contentView.viewWithTag(101) as? UILabel)?.text = "\(track.sortingOrder+1)."
(cell.contentView.viewWithTag(102) as? UILabel)?.text = track.title
var secs = Int(track.trackTimeMillis)/1000
var mins = secs/60
secs%=60
let hours = mins/60
mins%=60
let twoDigitsFormatted = { (time: Int) -> String in
return String(format: "%02d", time)
}
(cell.contentView.viewWithTag(103) as? UILabel)?.text = {
if hours > 0 { return "\(hours):" }
return ""
}()+"\(twoDigitsFormatted(mins)):\(twoDigitsFormatted(secs))"
return cell
}
}
|
mit
|
1ad064defd4546ca767049fe3cf99394
| 32.382979 | 205 | 0.701721 | 3.992366 | false | false | false | false |
firemuzzy/slugg
|
mobile/Slug/Slug/controllers/HomeWorkSetupViewController.swift
|
1
|
2634
|
//
// HomeWorkSetupViewController.swift
// Slug
//
// Created by Andrew Charkin on 3/21/15.
// Copyright (c) 2015 Slug. All rights reserved.
//
import UIKit
import Parse
class HomeWorkSetupViewController: UIViewController {
@IBOutlet weak var homeAddress: UILabel!
@IBOutlet weak var companyName: UILabel!
@IBOutlet weak var homeImage: UIImageView!
@IBOutlet weak var workImage: UIImageView!
@IBOutlet weak var setHome: UIButton!
@IBOutlet weak var setWork: UIButton!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.companyName.text = SlugUser.currentUser()?.company()?.name
if let name = SlugUser.currentUser()?.company()?.name, image = UIImage(named: name.lowercaseString) {
workImage.image = image
companyName.text = ""
}
if let location = UserLocation.sharedInstance.currentLocation {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
if error != nil {
println("error in reverse geocoding: \(error.localizedDescription)")
return
}
if let placemark = placemarks.first as? CLPlacemark {
let addressArray = [placemark.thoroughfare, placemark.subLocality].filter{ $0 != nil}.map{$0!}
let address = " ".join(addressArray)
self.homeAddress.text = address
}
})
}
if let attributedText = setHome.titleLabel?.attributedText as? NSMutableAttributedString {
attributedText.addAttribute(NSKernAttributeName, value: 2.3 , range: NSMakeRange(0, attributedText.length))
setHome.setAttributedTitle(attributedText, forState: .Normal)
}
if let attributedText = setWork.titleLabel?.attributedText as? NSMutableAttributedString {
attributedText.addAttribute(NSKernAttributeName, value: 2.3, range: NSMakeRange(0, attributedText.length))
setWork.setAttributedTitle(attributedText, forState: .Normal)
}
}
@IBAction func doneCLicked(sender: AnyObject) {
if let user = SlugUser.currentUser(), let userCompany = user.company() {
if let coordinate = UserLocation.sharedInstance.currentLocation?.coordinate {
user.home = PFGeoPoint(latitude: coordinate.latitude, longitude: coordinate.longitude)
user.work = PFGeoPoint(latitude: userCompany.latitude, longitude: userCompany.longitude)
user.parseObj.saveInBackgroundWithBlock(nil)
self.performSegueWithIdentifier("UnwindToRoot", sender: self)
}
} else {
self.performSegueWithIdentifier("UnwindToRoot", sender: self)
}
}
}
|
mit
|
b59e932b7cad7d57ac91ce07df0f4559
| 36.098592 | 113 | 0.700456 | 4.695187 | false | false | false | false |
Nathan1994/About-me
|
About me/About me/ExperiencePresentingAnimator.swift
|
1
|
2955
|
//
// ExperiencePresentingAnimator.swift
// About me
//
// Created by Nathan on 4/26/15.
// Copyright (c) 2015 TAC. All rights reserved.
//
import UIKit
class ExperiencePresentingAnimator: NSObject,UIViewControllerAnimatedTransitioning {
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromView = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!.view
fromView.tintAdjustmentMode = UIViewTintAdjustmentMode.Dimmed
fromView.userInteractionEnabled = true
let dimmingView = UIView(frame: fromView.bounds)
dimmingView.backgroundColor = UIColor.grayColor()
dimmingView.layer.opacity = 0.3
let recognizer = UITapGestureRecognizer(target: transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!, action: "backgroundDidPressed")
dimmingView.addGestureRecognizer(recognizer)
let toView = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!.view
if CGSizeEqualToSize(UIScreen.mainScreen().bounds.size, CGSizeMake(320, 480)){
toView.frame = CGRectMake(0, 0, CGRectGetWidth(transitionContext.containerView()!.bounds)-50,CGRectGetHeight(transitionContext.containerView()!.bounds) - 100)
}
else{
toView.frame = CGRectMake(0, 0, CGRectGetWidth(transitionContext.containerView()!.bounds)-50,CGRectGetHeight(transitionContext.containerView()!.bounds) - 200)
}
toView.center = CGPointMake(-transitionContext.containerView()!.center.x, transitionContext.containerView()!.center.y)
transitionContext.containerView()!.addSubview(toView)
transitionContext.containerView()!.insertSubview(dimmingView, atIndex: 0);
let positionAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionX)
positionAnimation.toValue = transitionContext.containerView()!.center.x
positionAnimation.springBounciness = 10
positionAnimation.completionBlock = {(anim : POPAnimation?,finished : Bool) in transitionContext.completeTransition(true)}
let scaleAnimation = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
scaleAnimation.springBounciness = 20
scaleAnimation.fromValue = NSValue(CGPoint: CGPointMake(1.2, 1.4))
let opacityAnimation = POPBasicAnimation(propertyNamed: kPOPLayerOpacity)
opacityAnimation.toValue = 0.2
toView.layer.pop_addAnimation(positionAnimation, forKey:"positionAnimation")
toView.layer.pop_addAnimation(scaleAnimation, forKey: "scaleAnimation")
dimmingView.layer.pop_addAnimation(opacityAnimation, forKey: "opacityAnimation")
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5;
}
}
|
mit
|
c31971e448efcb3e2da147bcd0a8d8b2
| 45.920635 | 170 | 0.72555 | 6.143451 | false | false | false | false |
ChrisChares/SwiftToolbelt
|
Toolbelt/Result.swift
|
1
|
3495
|
//
// Result.swift
// HuntFish
//
// Created by Chris Chares on 1/20/16.
// Copyright © 2016 303 Software. All rights reserved.
//
import Foundation
/**
A wrapper that allows us to utilize native Swift error handling (do - try - catch - defer) with asynchronous operations. The idea is derived from Benedikt Terhechte's excellent post http://appventure.me/2015/06/19/swift-try-catch-asynchronous-closures/
*/
open class Result<T> {
public typealias Eval = () throws -> T
fileprivate let fn: Eval
/**
Create a new Result struct with the function to be evaluated
- Parameter fn: The function to evaluate
- Returns: A new Result struct wrapping the function
*/
public init(_ fn: @escaping Eval) {
self.fn = fn
}
/**
Evaluate the wrapped function
- Throws: Whatever error the original asynchronous action threw
- Returns: The object associated with a success
*/
open func eval() throws -> T {
return try fn()
}
/**
Evaluate the wrapped function and return an error optional based on result
*/
open var error: Error? {
return ErrorOptional(eval)
}
/**
For other situations where response doesn't matter, only errors do
*/
open func rethrow() throws {
_ = try fn()
}
}
/**
Maps any Result<E> to Result<Void>. Useful for chaining
*/
public func AnyResult<E>(_ fn: @escaping (Result<Void>) -> Void) -> (Result<E>) -> Void {
return { result in
if let error = result.error {
fn(Result({throw error}))
} else {
fn(Result({}))
}
}
}
/**
Creates one callback out of multiple of the same type
*/
public func ResultAccumulator<T>(_ fn: @escaping (Result<[T]>) -> Void) -> () -> (Result<T>) -> Void {
var results = [T]()
var requestCount: Int = 0
var errored: Bool = false
return {
requestCount = requestCount + 1
return { result in
guard errored == false else {
// All results are cancelled because one failed
return
}
do {
results.append(try result.eval())
if results.count == requestCount {
fn(Result({results}))
}
} catch let error {
errored = true
fn(Result({throw error}))
}
}
}
}
public func ErrorOptional<T>(_ fn: () throws -> T) -> Error? {
do {
_ = try fn()
return nil
} catch let error {
return error
}
}
/*
Wrap makes async functions w/ callbacks less awkward as it lets you write in a more linear fashion
*/
public func wrap<T>(_ cb: (Result<T>) -> Void, fn: @escaping () throws -> T) {
cb(Result({try fn()}))
}
/*
Background wrap works similiarly to wrap, except it performs the passed function on a background thread. Results / errors are returned on the main thread
*/
public func backgroundWrap<T>(_ cb: @escaping (Result<T>) -> Void, fn: @escaping () throws -> T) {
let main = DispatchQueue.main
let bg = DispatchQueue.global(qos: .background)
bg.async {
do {
let result = try fn()
main.async { cb(Result({result})) }
} catch let error {
main.async { cb(Result({throw error})) }
}
}
}
|
mit
|
1d32793eacb162cc9db8a84126e59906
| 25.671756 | 257 | 0.556096 | 4.31358 | false | false | false | false |
DonMag/CellTest2
|
CellTest2/CellTest2/TableViewController.swift
|
1
|
2519
|
//
// TableViewController.swift
// TestMultilineLabelInTableCells
//
// Created by JB on 08/07/2017.
// Copyright © 2017 JB. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var rightText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse at lacus quis leo eleifend viverra in a est. Curabitur elit urna, lobortis et justo ut, aliquam imperdiet sapien. Maecenas gravida ante vitae hendrerit congue. Phasellus id erat ligula. Duis malesuada condimentum mattis. Donec tellus diam, rutrum sit amet nisl ultricies, accumsan commodo risus. Vestibulum elit ante, mollis nec enim at, imperdiet dictum erat. Proin laoreet dolor id est egestas, ultricies tincidunt elit pretium. Phasellus posuere, metus in laoreet mattis, velit odio mollis risus, nec pharetra tellus odio in dolor. Maecenas tincidunt END OF TEXT"
var leftText1 = "Test aa"
var leftText2 = "Test bb"
override func viewDidLoad() {
super.viewDidLoad()
// Get dynamic cell heights working
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 30.0
leftText1 += " Longer"
leftText2 += " Longer"
// rightText = "One line on right"
// leftText1 += " Now it's Too much Longer"
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// Configure the cell...
// We'll go Cell 3 / Cell 2 / Cell 1 / etc....
switch indexPath.row % 3 {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell3", for: indexPath) as! TableViewCell3
cell.leftLabel1.text = leftText1
cell.leftLabel2.text = leftText2
cell.rightLabel.text = rightText
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as! TableViewCell1
cell.leftLabel1.text = leftText1
cell.leftLabel2.text = leftText2
cell.rightLabel.text = rightText
return cell
case 2:
// let case 2 fall through to default
break
default:
break
}
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath) as! TableViewCell2
cell.leftLabel1.text = leftText1
cell.leftLabel2.text = leftText2
cell.rightLabel.text = rightText
return cell
}
}
|
mit
|
2e64261e01b4e22bb75db2f5ce95ab5e
| 30.08642 | 653 | 0.732724 | 3.965354 | false | false | false | false |
karthik-ios-dev/MySwiftExtension
|
Pod/Classes/Commom-Extensions.swift
|
1
|
4821
|
//
// Extensions.swift
// DateHelper
//
// Created by Karthik on 10/29/15.
// Copyright © 2015 Karthik. All rights reserved.
//
import UIKit
import Foundation
extension UITableView{
public func scrollToTop(animated animated: Bool){
scrollRectToVisible(CGRectMake(0, 0, 1, 0), animated: animated)
}
}
public extension NSObject {
/**
This will run closure after delay. Invokation will be on main_queue.
- parameter delay: is number of seconds to delay
*/
func delay(delay: Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}
class CachedDateFormatter {
/*
1.Will store the Value in Dict
2.search for key in next call
3.Returns if exist,
4.else create new one
.. call by
let dateFormatter = CachedDateFormatter.sharedInstance.formatterWith(format: "yyyy-MM-dd'-'HHmm", timeZone: NSTimeZone.localTimeZone(), locale: NSLocale(localeIdentifier: "en_US"))
*/
static let sharedInstance = CachedDateFormatter()
var cachedDateFormatters :[String: NSDateFormatter] = [:]
func formatterWith(format format: String, timeZone: NSTimeZone = NSTimeZone.localTimeZone(), locale: NSLocale = NSLocale(localeIdentifier: "en_US")) -> NSDateFormatter {
let key = "\(format.hashValue)\(timeZone.hashValue)\(locale.hashValue)"
if let cachedDateFormatter = cachedDateFormatters[key] {
return cachedDateFormatter
}
else {
let newDateFormatter = NSDateFormatter()
newDateFormatter.dateFormat = format
newDateFormatter.timeZone = timeZone
newDateFormatter.locale = locale
cachedDateFormatters[key] = newDateFormatter
return newDateFormatter
}
}
}
extension UIViewController{
public var isModal: Bool {
return self.presentingViewController?.presentedViewController == self
|| (self.navigationController != nil && self.navigationController?.presentingViewController?.presentedViewController == self.navigationController)
|| self.tabBarController?.presentingViewController is UITabBarController
}
}
//MARK: Bool Extension
extension Bool{
public func toInt() -> Int{
switch self {
case true:
return 1
case false:
return 0
}
}
public func toString() -> String{
return String(self)
}
}
//MARK: NSUserDefaults setter
extension NSUserDefaults{
public func setLong(value: Int64, forKey key: String){
NSUserDefaults.standardUserDefaults().setObject(value.toNumber_64Bit, forKey: key)
NSUserDefaults().synchronize()
}
public func setColor(color: UIColor?, forKey key: String) {
var colorData: NSData?
if let color = color {
colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
}
setObject(colorData, forKey: key)
}
}
//MARK: NSUserDefaults getter
extension NSUserDefaults{
public func longForKey(key: String) -> Int64?{
if let tempNum = NSUserDefaults.standardUserDefaults().objectForKey(key) as? NSNumber{
return tempNum.toInt64
}
return nil
}
public func colorForKey(key: String) -> UIColor? {
var color: UIColor?
if let colorData = dataForKey(key) {
color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
}
return color
}
}
extension NSCalendar{
class func gregorianCalendar() -> NSCalendar {
return NSCalendar(identifier: NSCalendarIdentifierGregorian)!
}
}
extension NSTimeInterval {
public var second: NSTimeInterval {
return self.seconds
}
public var seconds: NSTimeInterval {
return self
}
public var minute: NSTimeInterval {
return self.minutes
}
public var minutes: NSTimeInterval {
let secondsInAMinute = 60 as NSTimeInterval
return self * secondsInAMinute
}
public var day: NSTimeInterval {
return self.days
}
public var days: NSTimeInterval {
let secondsInADay = 86_400 as NSTimeInterval
return self * secondsInADay
}
public var before: NSDate {
let timeInterval = self
return NSDate().dateByAddingTimeInterval(-timeInterval)
}
public var after : NSDate{
let timeInterval = self
return NSDate().dateByAddingTimeInterval(+timeInterval)
}
}
|
mit
|
7f73957a43505ed897b76a88996a579d
| 23.596939 | 184 | 0.623859 | 5.233442 | false | false | false | false |
Akshay-iOS-Developer/iFloatingActionButton
|
iFloatingActionButton/Classes/FloatingItem.swift
|
1
|
725
|
//
// FloatingItem.swift
// iFloatingButton
//
// Created by Akshay Agrawal on 28/06/17.
// Copyright © 2017 Akshay Agrawal. All rights reserved.
//
import UIKit
public class FloatingItem: NSObject {
public var title:String
public var titleTextColor:UIColor
public var image:UIImage
public var imageBackGroundColor:UIColor
public var titleFont:UIFont
internal var itemClickHandler:(() -> Void)? = nil
public override init() {
title = ""
titleTextColor = UIColor.black
image = UIImage()
imageBackGroundColor = UIColor.init(colorLiteralRed: 255/255.0, green: 102/255.0, blue: 178/255.0, alpha: 1)
titleFont = UIFont.systemFont(ofSize: 15)
}
}
|
mit
|
a10d24b675af66a8f8572ca5086f5aee
| 25.814815 | 116 | 0.674033 | 4.022222 | false | false | false | false |
edwardaux/Ogra
|
Sources/Encodable.swift
|
2
|
3750
|
//
// Encodable.swift
// Ogra
//
// Created by Craig Edwards on 27/07/2015.
// Copyright © 2015 Craig Edwards. All rights reserved.
//
import Foundation
import Argo
public protocol Encodable {
func encode() -> JSON
}
extension JSON: Encodable {
public func encode() -> JSON {
return self
}
}
extension String: Encodable {
public func encode() -> JSON {
return .string(self)
}
}
extension Bool: Encodable {
public func encode() -> JSON {
return .bool(self)
}
}
extension Int: Encodable {
public func encode() -> JSON {
return .number(self as NSNumber)
}
}
extension Double: Encodable {
public func encode() -> JSON {
return .number(self as NSNumber)
}
}
extension Float: Encodable {
public func encode() -> JSON {
return .number(self as NSNumber)
}
}
extension UInt: Encodable {
public func encode() -> JSON {
return .number(self as NSNumber)
}
}
extension UInt64: Encodable {
public func encode() -> JSON {
return .number(NSNumber(value: self))
}
}
extension Optional where Wrapped: Encodable {
public func encode() -> JSON {
switch self {
case .none: return .null
case .some(let v): return v.encode()
}
}
}
extension Collection where Self: ExpressibleByDictionaryLiteral, Self.Key: ExpressibleByStringLiteral, Self.Value: Encodable, Iterator.Element == (key: Self.Key, value: Self.Value) {
public func encode() -> JSON {
var values = [String : JSON]()
for (key, value) in self {
values[String(describing: key)] = value.encode()
}
return .object(values)
}
}
extension Optional where Wrapped: Collection & ExpressibleByDictionaryLiteral, Wrapped.Key: ExpressibleByStringLiteral, Wrapped.Value: Encodable, Wrapped.Iterator.Element == (key: Wrapped.Key, value: Wrapped.Value) {
public func encode() -> JSON {
return self.map { $0.encode() } ?? .null
}
}
extension Collection where Self: ExpressibleByArrayLiteral, Self.Element: Encodable, Iterator.Element: Encodable {
public func encode() -> JSON {
return JSON.array(self.map { $0.encode() })
}
}
extension Optional where Wrapped: Collection & ExpressibleByArrayLiteral, Wrapped.Element: Encodable, Wrapped.Iterator.Element == Wrapped.Element {
public func encode() -> JSON {
return self.map { $0.encode() } ?? .null
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == String {
public func encode() -> JSON {
return .string(self.rawValue)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Int {
public func encode() -> JSON {
return .number(self.rawValue as NSNumber)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Double {
public func encode() -> JSON {
return .number(self.rawValue as NSNumber)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == Float {
public func encode() -> JSON {
return .number(self.rawValue as NSNumber)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == UInt {
public func encode() -> JSON {
return .number(self.rawValue as NSNumber)
}
}
extension Encodable where Self: RawRepresentable, Self.RawValue == UInt64 {
public func encode() -> JSON {
return .number(NSNumber(value: self.rawValue))
}
}
extension JSON {
public func JSONObject() -> Any {
switch self {
case .null: return NSNull()
case .string(let value): return value
case .number(let value): return value
case .array(let array): return array.map { $0.JSONObject() }
case .bool(let value): return value
case .object(let object):
var dict: [Swift.String : Any] = [:]
for (key, value) in object {
dict[key] = value.JSONObject()
}
return dict as Any
}
}
}
|
mit
|
0432d3f3e0318f626f57f035bc33990e
| 23.503268 | 216 | 0.677247 | 3.686332 | false | false | false | false |
hodinkee/escapement-swift
|
Escapement/Paragraph.swift
|
1
|
3136
|
//
// Paragraph.swift
// Escapement
//
// Created by Caleb Davenport on 7/16/15.
// Copyright (c) 2015 Hodinkee. All rights reserved.
//
struct Paragraph {
var text: String
var entities: [Entity]
}
extension Paragraph {
func makeJSON() -> [String: Any] {
var dictionary = [String: Any]()
dictionary["text"] = text
dictionary["entities"] = entities.map({ $0.makeJSON() })
return dictionary
}
init?(json: [String: Any]) {
guard let text = json["text"] as? String else {
return nil
}
self.text = text
guard let entities = json["entities"] as? [Any] else {
return nil
}
self.entities = entities.flatMap({ $0 as? [String: Any] }).flatMap(Entity.init)
}
}
extension Paragraph {
func attributedString(with stylesheet: Stylesheet) -> NSAttributedString {
var attributes = stylesheet["*"]
attributes[StringAttributeName.escapementBold] = false
attributes[StringAttributeName.escapementItalic] = false
let string = NSMutableAttributedString(string: text, attributes: attributes)
for entity in entities {
let range = NSRange(entity.range)
switch entity.tag {
case "a":
if let URL = entity.href {
string.addAttribute(NSLinkAttributeName, value: URL, range: range)
}
case "strong", "b":
string.addAttribute(StringAttributeName.escapementBold, value: true, range: range)
case "em", "i":
string.addAttribute(StringAttributeName.escapementItalic, value: true, range: range)
case "s", "del":
string.addAttribute(NSStrikethroughStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: range)
case "u":
string.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: range)
default:
()
}
string.addAttributes(stylesheet[entity.tag], range: range)
}
string.enumerateAttributes(in: NSRange(0..<string.length), options: [], using: { attributes, range, _ in
var descriptor = (attributes[NSFontAttributeName] as? UIFont)?.fontDescriptor
if let bold = attributes[StringAttributeName.escapementBold] as? Bool, bold {
descriptor = descriptor?.boldFontDescriptor
}
if let italic = attributes[StringAttributeName.escapementItalic] as? Bool, italic {
descriptor = descriptor?.italicFontDescriptor
}
if let descriptor = descriptor {
let font = UIFont(descriptor: descriptor, size: 0)
string.addAttribute(NSFontAttributeName, value: font, range: range)
}
})
return NSAttributedString(attributedString: string)
}
}
extension Paragraph: Equatable {
static func == (lhs: Paragraph, rhs: Paragraph) -> Bool {
return lhs.text == rhs.text && lhs.entities == rhs.entities
}
}
|
mit
|
beb947a00b28b45147e38ae7264706a0
| 33.461538 | 130 | 0.603316 | 4.839506 | false | false | false | false |
grafiti-io/SwiftCharts
|
SwiftCharts/Layers/ChartShowCoordsLinesLayer.swift
|
1
|
2627
|
//
// ChartShowCoordsLinesLayer.swift
// swift_charts
//
// Created by ischuetz on 19/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartShowCoordsLinesLayer<T: ChartPoint>: ChartPointsLayer<T> {
fileprivate var view: UIView?
fileprivate var activeChartPoint: T?
public init(xAxis: ChartAxis, yAxis: ChartAxis, chartPoints: [T]) {
super.init(xAxis: xAxis, yAxis: yAxis, chartPoints: chartPoints)
}
open func showChartPointLines(_ chartPoint: T, chart: Chart) {
if let view = self.view {
activeChartPoint = chartPoint
for v in view.subviews {
v.removeFromSuperview()
}
let screenLoc = chartPointScreenLoc(chartPoint)
let hLine = UIView(frame: CGRect(x: screenLoc.x, y: screenLoc.y, width: 0, height: 1))
let vLine = UIView(frame: CGRect(x: screenLoc.x, y: screenLoc.y, width: 0, height: 1))
for lineView in [hLine, vLine] {
lineView.backgroundColor = UIColor.black
view.addSubview(lineView)
}
func finalState() {
let axisOriginX = modelLocToScreenLoc(x: xAxis.first)
let axisOriginY = modelLocToScreenLoc(y: yAxis.first)
let axisLengthY = axisOriginY - modelLocToScreenLoc(y: yAxis.last)
hLine.frame = CGRect(x: axisOriginX, y: screenLoc.y, width: screenLoc.x - axisOriginX, height: 1)
vLine.frame = CGRect(x: screenLoc.x, y: screenLoc.y, width: 1, height: axisLengthY - screenLoc.y)
}
if isTransform {
finalState()
} else {
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
finalState()
}, completion: nil)
}
}
}
override open func display(chart: Chart) {
let view = UIView(frame: chart.bounds)
view.isUserInteractionEnabled = true
chart.addSubview(view)
self.view = view
}
open override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) {
super.zoom(x, y: y, centerX: centerX, centerY: centerY)
updateChartPointsScreenLocations()
}
open override func pan(_ deltaX: CGFloat, deltaY: CGFloat) {
super.pan(deltaX, deltaY: deltaY)
updateChartPointsScreenLocations()
}
}
|
apache-2.0
|
7ee9a338f75ba8271f8ccf0ae535da42
| 33.116883 | 113 | 0.564142 | 4.608772 | false | false | false | false |
wangguangfeng/STUIComponent
|
STUIComponent/STUIComponent/Components/LineSpacingLabel.swift
|
2
|
938
|
//
// LineSpacingLabel.swift
// STUIComponent
//
// Created by XuAzen on 16/2/29.
// Copyright © 2016年 st company. All rights reserved.
//
import UIKit
public class LineSpacingLabel: UILabel {
public var lineSpacing : CGFloat! = 5 // 默认为5
{
didSet{
layoutSubviews()
}
}
override public func layoutSubviews() {
super.layoutSubviews()
// 设定行距
if let oldText = text {
let spacingText = NSMutableAttributedString(string: oldText)
let paragraphStyle = NSMutableParagraphStyle()
if let notNilLineSpacing = lineSpacing {
paragraphStyle.lineSpacing = notNilLineSpacing
spacingText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, oldText.characters.count))
attributedText = spacingText
}
}
}
}
|
mit
|
00f8b14e131e250a464c49257179c604
| 26.909091 | 143 | 0.614549 | 5.06044 | false | false | false | false |
dvor/Antidote
|
Antidote/ProfileSettings.swift
|
2
|
1749
|
// 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
private struct Constants {
static let UnlockPinCodeKey = "UnlockPinCodeKey"
static let UseTouchIDKey = "UseTouchIDKey"
static let LockTimeoutKey = "LockTimeoutKey"
}
class ProfileSettings: NSObject, NSCoding {
enum LockTimeout: String {
case Immediately
case Seconds30
case Minute1
case Minute2
case Minute5
}
/// Pin code used to unlock device.
var unlockPinCode: String?
/// Whether use Touch ID for unlocking Antidote.
var useTouchID: Bool
/// Time after which Antidote will be blocked in background.
var lockTimeout: LockTimeout
required override init() {
unlockPinCode = nil
useTouchID = false
lockTimeout = .Immediately
super.init()
}
required init(coder aDecoder: NSCoder) {
unlockPinCode = aDecoder.decodeObject(forKey: Constants.UnlockPinCodeKey) as? String
useTouchID = aDecoder.decodeBool(forKey: Constants.UseTouchIDKey)
if let rawTimeout = aDecoder.decodeObject(forKey: Constants.LockTimeoutKey) as? String {
lockTimeout = LockTimeout(rawValue: rawTimeout) ?? .Immediately
}
else {
lockTimeout = .Immediately
}
super.init()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(unlockPinCode, forKey: Constants.UnlockPinCodeKey)
aCoder.encode(useTouchID, forKey: Constants.UseTouchIDKey)
aCoder.encode(lockTimeout.rawValue, forKey: Constants.LockTimeoutKey)
}
}
|
mit
|
ef449368c1a027b8be0e528b578f766b
| 29.155172 | 96 | 0.674671 | 4.473146 | false | false | false | false |
kickstarter/ios-oss
|
Kickstarter-iOS/Features/AddNewCard/Views/SettingsFormFieldView.swift
|
1
|
1456
|
import Library
import Prelude
import UIKit
final class SettingsFormFieldView: UIView, NibLoading {
@IBOutlet var textField: UITextField!
@IBOutlet var titleLabel: UILabel!
@IBOutlet fileprivate var separatorView: UIView!
@IBOutlet fileprivate var stackView: UIStackView!
var autocapitalizationType: UITextAutocapitalizationType = .none
var returnKeyType: UIReturnKeyType = .default
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = self.view(fromNib: .SettingsFormFieldView) else {
fatalError("Failed to load view")
}
view.frame = self.bounds
self.addSubview(view)
}
override func bindStyles() {
super.bindStyles()
_ = self.titleLabel
|> settingsTitleLabelStyle
|> titleLabelStyle
_ = self.textField
|> formFieldStyle
|> textFieldStyle
|> \.autocapitalizationType .~ self.autocapitalizationType
|> \.returnKeyType .~ self.returnKeyType
|> \.accessibilityLabel .~ self.titleLabel.text
_ = self.separatorView
|> separatorStyle
}
}
// MARK: - Styles
private let titleLabelStyle: LabelStyle = { (label: UILabel) in
label
|> \.isAccessibilityElement .~ false
|> \.adjustsFontForContentSizeCategory .~ true
}
private let textFieldStyle: TextFieldStyle = { (textField: UITextField) in
textField
|> \.textAlignment .~ NSTextAlignment.right
|> \.textColor .~ UIColor.ksr_support_400
}
|
apache-2.0
|
a662d7b94d42e09e899b645a5c2ed747
| 24.54386 | 74 | 0.703297 | 4.952381 | false | false | false | false |
dvor/Antidote
|
Antidote/ChatIncomingCallCell.swift
|
2
|
2575
|
// 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 UIKit
import SnapKit
private struct Constants {
static let LeftOffset = 20.0
static let ImageViewToLabelOffset = 5.0
static let ImageViewYOffset = -1.0
static let VerticalOffset = 8.0
}
class ChatIncomingCallCell: ChatMovableDateCell {
fileprivate var callImageView: UIImageView!
fileprivate var label: UILabel!
override func setupWithTheme(_ theme: Theme, model: BaseCellModel) {
super.setupWithTheme(theme, model: model)
guard let incomingModel = model as? ChatIncomingCallCellModel else {
assert(false, "Wrong model \(model) passed to cell \(self)")
return
}
label.textColor = theme.colorForType(.ChatListCellMessage)
callImageView.tintColor = theme.colorForType(.LinkText)
if incomingModel.answered {
label.text = String(localized: "chat_call_message") + String(timeInterval: incomingModel.callDuration)
}
else {
label.text = String(localized: "chat_missed_call_message")
}
}
override func createViews() {
super.createViews()
let image = UIImage.templateNamed("start-call-small")
callImageView = UIImageView(image: image)
contentView.addSubview(callImageView)
label = UILabel()
label.font = UIFont.antidoteFontWithSize(16.0, weight: .light)
contentView.addSubview(label)
}
override func installConstraints() {
super.installConstraints()
callImageView.snp.makeConstraints {
$0.centerY.equalTo(label).offset(Constants.ImageViewYOffset)
$0.leading.equalTo(contentView).offset(Constants.LeftOffset)
}
label.snp.makeConstraints {
$0.top.equalTo(contentView).offset(Constants.VerticalOffset)
$0.bottom.equalTo(contentView).offset(-Constants.VerticalOffset)
$0.leading.equalTo(callImageView.snp.trailing).offset(Constants.ImageViewToLabelOffset)
}
}
}
// Accessibility
extension ChatIncomingCallCell {
override var accessibilityLabel: String? {
get {
return label.text
}
set {}
}
}
// ChatEditable
extension ChatIncomingCallCell {
override func shouldShowMenu() -> Bool {
return true
}
override func menuTargetRect() -> CGRect {
return label.frame
}
}
|
mit
|
6120f489ea4b4750dc805ae6ba2ef9b5
| 28.94186 | 114 | 0.661359 | 4.54947 | false | false | false | false |
apple/swift-nio
|
Sources/NIOWebSocket/NIOWebSocketFrameAggregator.swift
|
1
|
6057
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
/// `NIOWebSocketFrameAggregator` buffers inbound fragmented `WebSocketFrame`'s and aggregates them into a single `WebSocketFrame`.
/// It guarantees that a `WebSocketFrame` with an `opcode` of `.continuation` is never forwarded.
/// Frames which are not fragmented are just forwarded without any processing.
/// Fragmented frames are unmasked, concatenated and forwarded as a new `WebSocketFrame` which is either a `.binary` or `.text` frame.
/// `extensionData`, `rsv1`, `rsv2` and `rsv3` are lost if a frame is fragmented because they cannot be concatenated.
/// - Note: `.ping`, `.pong`, `.closeConnection` frames are forwarded during frame aggregation
public final class NIOWebSocketFrameAggregator: ChannelInboundHandler {
public enum Error: Swift.Error {
case nonFinalFragmentSizeIsTooSmall
case tooManyFragments
case accumulatedFrameSizeIsTooLarge
case receivedNewFrameWithoutFinishingPrevious
case didReceiveFragmentBeforeReceivingTextOrBinaryFrame
}
public typealias InboundIn = WebSocketFrame
public typealias InboundOut = WebSocketFrame
private let minNonFinalFragmentSize: Int
private let maxAccumulatedFrameCount: Int
private let maxAccumulatedFrameSize: Int
private var bufferedFrames: [WebSocketFrame] = []
private var accumulatedFrameSize: Int = 0
/// Configures a `NIOWebSocketFrameAggregator`.
/// - Parameters:
/// - minNonFinalFragmentSize: Minimum size in bytes of a fragment which is not the last fragment of a complete frame. Used to defend against many really small payloads.
/// - maxAccumulatedFrameCount: Maximum number of fragments which are allowed to result in a complete frame.
/// - maxAccumulatedFrameSize: Maximum accumulated size in bytes of buffered fragments. It is essentially the maximum allowed size of an incoming frame after all fragments are concatenated.
public init(
minNonFinalFragmentSize: Int,
maxAccumulatedFrameCount: Int,
maxAccumulatedFrameSize: Int
) {
self.minNonFinalFragmentSize = minNonFinalFragmentSize
self.maxAccumulatedFrameCount = maxAccumulatedFrameCount
self.maxAccumulatedFrameSize = maxAccumulatedFrameSize
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = unwrapInboundIn(data)
do {
switch frame.opcode {
case .continuation:
guard let firstFrameOpcode = self.bufferedFrames.first?.opcode else {
throw Error.didReceiveFragmentBeforeReceivingTextOrBinaryFrame
}
try self.bufferFrame(frame)
guard frame.fin else { break }
// final frame received
let aggregatedFrame = self.aggregateFrames(
opcode: firstFrameOpcode,
allocator: context.channel.allocator
)
self.clearBuffer()
context.fireChannelRead(wrapInboundOut(aggregatedFrame))
case .binary, .text:
if frame.fin {
guard self.bufferedFrames.isEmpty else {
throw Error.receivedNewFrameWithoutFinishingPrevious
}
// fast path: no need to check any constraints nor unmask and copy data
context.fireChannelRead(data)
} else {
try self.bufferFrame(frame)
}
default:
// control frames can't be fragmented
context.fireChannelRead(data)
}
} catch {
// free memory early
self.clearBuffer()
context.fireErrorCaught(error)
}
}
private func bufferFrame(_ frame: WebSocketFrame) throws {
guard self.bufferedFrames.isEmpty || frame.opcode == .continuation else {
throw Error.receivedNewFrameWithoutFinishingPrevious
}
guard frame.fin || frame.length >= self.minNonFinalFragmentSize else {
throw Error.nonFinalFragmentSizeIsTooSmall
}
guard self.bufferedFrames.count < self.maxAccumulatedFrameCount else {
throw Error.tooManyFragments
}
// if this is not a final frame, we will at least receive one more frame
guard frame.fin || (self.bufferedFrames.count + 1) < self.maxAccumulatedFrameCount else {
throw Error.tooManyFragments
}
self.bufferedFrames.append(frame)
self.accumulatedFrameSize += frame.length
guard self.accumulatedFrameSize <= self.maxAccumulatedFrameSize else {
throw Error.accumulatedFrameSizeIsTooLarge
}
}
private func aggregateFrames(opcode: WebSocketOpcode, allocator: ByteBufferAllocator) -> WebSocketFrame {
var dataBuffer = allocator.buffer(capacity: self.accumulatedFrameSize)
for frame in self.bufferedFrames {
var unmaskedData = frame.unmaskedData
dataBuffer.writeBuffer(&unmaskedData)
}
return WebSocketFrame(fin: true, opcode: opcode, data: dataBuffer)
}
private func clearBuffer() {
self.bufferedFrames.removeAll(keepingCapacity: true)
self.accumulatedFrameSize = 0
}
}
#if swift(>=5.6)
@available(*, unavailable)
extension NIOWebSocketFrameAggregator: Sendable {}
#endif
|
apache-2.0
|
687658ad96f0b6e984ecd4c1992e0510
| 41.356643 | 195 | 0.6386 | 5.336564 | false | false | false | false |
openHPI/xikolo-ios
|
iOS/Views/RefreshControl.swift
|
1
|
1097
|
//
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import BrightFutures
import Common
import UIKit
class RefreshControl: UIRefreshControl {
typealias Action = () -> Future<Void, XikoloError>
typealias PostAction = () -> Void
static let minimumSpinningTime: DispatchTimeInterval = 750.milliseconds
let action: Action
let postAction: PostAction
init(action: @escaping Action, postAction: @escaping PostAction) {
self.action = action
self.postAction = postAction
super.init()
self.addTarget(self, action: #selector(callAction), for: .valueChanged)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func callAction() {
let deadline = Self.minimumSpinningTime.fromNow
self.action().onSuccess { _ in
self.postAction()
}.earliest(at: deadline).onComplete(immediateOnMainExecutionContext) { _ in
self.endRefreshing()
}
}
}
|
gpl-3.0
|
bdcfa06ef8213b12d864a50e674bd659
| 25.731707 | 83 | 0.659672 | 4.473469 | false | false | false | false |
simplymadeapps/SMASaveSystem
|
Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift
|
4
|
12204
|
//
// SHA2.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 24/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
final class SHA2 : HashProtocol {
var size:Int { return variant.rawValue }
let variant:SHA2.Variant
let message: Array<UInt8>
init(_ message:Array<UInt8>, variant: SHA2.Variant) {
self.variant = variant
self.message = message
}
enum Variant: RawRepresentable {
case sha224, sha256, sha384, sha512
typealias RawValue = Int
var rawValue: RawValue {
switch (self) {
case .sha224:
return 224
case .sha256:
return 256
case .sha384:
return 384
case .sha512:
return 512
}
}
init?(rawValue: RawValue) {
switch (rawValue) {
case 224:
self = .sha224
break;
case 256:
self = .sha256
break;
case 384:
self = .sha384
break;
case 512:
self = .sha512
break;
default:
return nil
}
}
var size:Int { return self.rawValue }
private var h:[UInt64] {
switch (self) {
case .sha224:
return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]
case .sha256:
return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]
case .sha384:
return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4]
case .sha512:
return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179]
}
}
private var k:[UInt64] {
switch (self) {
case .sha224, .sha256:
return [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]
case .sha384, .sha512:
return [0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538,
0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe,
0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235,
0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab,
0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725,
0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed,
0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218,
0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53,
0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373,
0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c,
0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6,
0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc,
0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817]
}
}
private func resultingArray<T>(hh:[T]) -> ArraySlice<T> {
switch (self) {
case .sha224:
return hh[0..<7]
case .sha384:
return hh[0..<6]
default:
break;
}
return ArraySlice(hh)
}
}
//FIXME: I can't do Generic func out of calculate32 and calculate64 (UInt32 vs UInt64), but if you can - please do pull request.
func calculate32() -> Array<UInt8> {
var tmpMessage = self.prepare(64)
// hash values
var hh = Array<UInt32>()
variant.h.forEach {(h) -> () in
hh.append(UInt32(h))
}
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage += (message.count * 8).bytes(64 / 8)
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 32-bit words into sixty-four 32-bit words:
var M:Array<UInt32> = Array<UInt32>(count: variant.k.count, repeatedValue: 0)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start = chunk.startIndex + (x * sizeofValue(M[x]))
let end = start + sizeofValue(M[x])
let le = toUInt32Array(chunk[start..<end])[0]
M[x] = le.bigEndian
break
default:
let s0 = rotateRight(M[x-15], n: 7) ^ rotateRight(M[x-15], n: 18) ^ (M[x-15] >> 3) //FIXME: n
let s1 = rotateRight(M[x-2], n: 17) ^ rotateRight(M[x-2], n: 19) ^ (M[x-2] >> 10)
M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
var F = hh[5]
var G = hh[6]
var H = hh[7]
// Main loop
for j in 0..<variant.k.count {
let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22)
let maj = (A & B) ^ (A & C) ^ (B & C)
let t2 = s0 &+ maj
let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25)
let ch = (E & F) ^ ((~E) & G)
let t1 = H &+ s1 &+ ch &+ UInt32(variant.k[j]) &+ M[j]
H = G
G = F
F = E
E = D &+ t1
D = C
C = B
B = A
A = t1 &+ t2
}
hh[0] = (hh[0] &+ A)
hh[1] = (hh[1] &+ B)
hh[2] = (hh[2] &+ C)
hh[3] = (hh[3] &+ D)
hh[4] = (hh[4] &+ E)
hh[5] = (hh[5] &+ F)
hh[6] = (hh[6] &+ G)
hh[7] = (hh[7] &+ H)
}
// Produce the final hash value (big-endian) as a 160 bit number:
var result = Array<UInt8>()
result.reserveCapacity(hh.count / 4)
variant.resultingArray(hh).forEach {
let item = $0.bigEndian
result += [UInt8(item & 0xff), UInt8((item >> 8) & 0xff), UInt8((item >> 16) & 0xff), UInt8((item >> 24) & 0xff)]
}
return result
}
func calculate64() -> Array<UInt8> {
var tmpMessage = self.prepare(128)
// hash values
var hh = [UInt64]()
variant.h.forEach {(h) -> () in
hh.append(h)
}
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage += (message.count * 8).bytes(64 / 8)
// Process the message in successive 1024-bit chunks:
let chunkSizeBytes = 1024 / 8 // 128
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 64-bit words into eighty 64-bit words:
var M = [UInt64](count: variant.k.count, repeatedValue: 0)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start = chunk.startIndex + (x * sizeofValue(M[x]))
let end = start + sizeofValue(M[x])
let le = toUInt64Array(chunk[start..<end])[0]
M[x] = le.bigEndian
break
default:
let s0 = rotateRight(M[x-15], n: 1) ^ rotateRight(M[x-15], n: 8) ^ (M[x-15] >> 7)
let s1 = rotateRight(M[x-2], n: 19) ^ rotateRight(M[x-2], n: 61) ^ (M[x-2] >> 6)
M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
var F = hh[5]
var G = hh[6]
var H = hh[7]
// Main loop
for j in 0..<variant.k.count {
let s0 = rotateRight(A,n: 28) ^ rotateRight(A,n: 34) ^ rotateRight(A,n: 39) //FIXME: n:
let maj = (A & B) ^ (A & C) ^ (B & C)
let t2 = s0 &+ maj
let s1 = rotateRight(E,n: 14) ^ rotateRight(E,n: 18) ^ rotateRight(E,n: 41)
let ch = (E & F) ^ ((~E) & G)
let t1 = H &+ s1 &+ ch &+ variant.k[j] &+ UInt64(M[j])
H = G
G = F
F = E
E = D &+ t1
D = C
C = B
B = A
A = t1 &+ t2
}
hh[0] = (hh[0] &+ A)
hh[1] = (hh[1] &+ B)
hh[2] = (hh[2] &+ C)
hh[3] = (hh[3] &+ D)
hh[4] = (hh[4] &+ E)
hh[5] = (hh[5] &+ F)
hh[6] = (hh[6] &+ G)
hh[7] = (hh[7] &+ H)
}
// Produce the final hash value (big-endian)
var result = Array<UInt8>()
result.reserveCapacity(hh.count / 4)
variant.resultingArray(hh).forEach {
let item = $0.bigEndian
var partialResult = Array<UInt8>()
partialResult.reserveCapacity(8)
for i in 0..<8 {
let shift = UInt64(8 * i)
partialResult.append(UInt8((item >> shift) & 0xff))
}
result += partialResult
}
return result
}
}
|
mit
|
dee4c44d6f834a58a425b285e9bdc53b
| 41.646853 | 183 | 0.504346 | 3.051288 | false | false | false | false |
myandy/shi_ios
|
shishi/Util/AssetsLibraryUtil.swift
|
1
|
6060
|
//
// AssetsLibraryUtil.swift
// post
//
// Created by yyf on 2016/11/30.
// Copyright © 2016年 leo. All rights reserved.
//
import Photos
//import AssetsLibrary
class AssetsLibraryUtil: NSObject {
open static let `default`: AssetsLibraryUtil = {
return AssetsLibraryUtil()
}()
public typealias SaveHandle = ((_ url:URL?, _ localIdentifier:String?, _ error:Error?) -> Void)
// private var isShouldSave = false
// private var filePathSouldSave: String?
// private var saveHandleShouldSave: SaveHandle?
override init() {
super.init()
// NotificationCenter.default.addObserver(self, selector: #selector(self.becomeActive), name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
}
deinit {
// NotificationCenter.default.removeObserver(self)
}
//将视频保存到assets-library并返回路径,localIdentifier
//请注意多线程问题,
func saveVideoFile(filePath: String, handle: SaveHandle?) {
if !self.hasPermissions() {
PHPhotoLibrary.requestAuthorization({ [unowned self] (status) in
log.debug("\(status)")
if status == .denied {
let error = NSError(domain: "user restricted", code: 0, userInfo: nil)
handle?(nil, nil, error)
}
else {
self.doSaveVideoFile(filePath: filePath, handle: handle)
}
})
return
}
self.doSaveVideoFile(filePath: filePath, handle: handle)
}
func saveImageFile(filePath: String, handle: SaveHandle?) {
if !self.hasPermissions() {
PHPhotoLibrary.requestAuthorization({ [unowned self] (status) in
log.debug("\(status)")
if status == .denied {
let error = NSError(domain: "user restricted", code: 0, userInfo: nil)
handle?(nil, nil, error)
}
else {
self.doSaveImageFile(filePath: filePath, handle: handle)
}
})
return
}
self.doSaveImageFile(filePath: filePath, handle: handle)
}
func doSaveVideoFile(filePath: String, handle: SaveHandle?) {
let videoURL = URL(fileURLWithPath: filePath)
let photoLibrary = PHPhotoLibrary.shared()
var videoAssetPlaceholder:PHObjectPlaceholder!
photoLibrary.performChanges({
let request = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
videoAssetPlaceholder = request!.placeholderForCreatedAsset
}, completionHandler: { success, error in
if success {
let localID = videoAssetPlaceholder.localIdentifier
var assetID = localID.replacingOccurrences( of:
"/.*", with: "")
assetID = assetID.components(separatedBy: "/").first!
// let ext = "mp4"
let ext = (filePath as NSString).pathExtension
let assetURLStr =
"assets-library://asset/asset.\(ext)?id=\(assetID)&ext=\(ext)"
// Do something with assetURLStr
handle?(URL(string: assetURLStr), localID, nil)
}
else {
handle?(nil, nil, error)
}
})
}
func doSaveImageFile(filePath: String, handle: SaveHandle?) {
let fileURL = URL(fileURLWithPath: filePath)
let photoLibrary = PHPhotoLibrary.shared()
var fileAssetPlaceholder:PHObjectPlaceholder!
photoLibrary.performChanges({
let request = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: fileURL)
fileAssetPlaceholder = request!.placeholderForCreatedAsset
}, completionHandler: { success, error in
if success {
let localID = fileAssetPlaceholder.localIdentifier
var assetID = localID.replacingOccurrences( of:
"/.*", with: "")
assetID = assetID.components(separatedBy: "/").first!
// let ext = "mp4"
let ext = (filePath as NSString).pathExtension
let assetURLStr =
"assets-library://asset/asset.\(ext)?id=\(assetID)&ext=\(ext)"
// Do something with assetURLStr
handle?(URL(string: assetURLStr), localID, nil)
}
else {
handle?(nil, nil, error)
}
})
}
func assetsLibraryRemoveFile( with localAssetIdentifier : String) {
// Find asset that we previously stored
let assets = PHAsset.fetchAssets(withLocalIdentifiers: [localAssetIdentifier], options: PHFetchOptions())
// Fetch asset, if found, delete it
if let fetchedAssets = assets.firstObject {
let delShotsAsset: NSMutableArray! = NSMutableArray()
delShotsAsset.add(fetchedAssets)
PHPhotoLibrary.shared().performChanges({ () -> Void in
// Delete asset
PHAssetChangeRequest.deleteAssets(delShotsAsset)
}, completionHandler: { (success, error) -> Void in
})
}
}
/**
判断相册权限
- returns: 有权限返回ture, 没权限返回false
*/
func hasPermissions() -> Bool {
let status:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
if status != .authorized {
return false
}else {
return true
}
}
}
|
apache-2.0
|
60788e42b100bf176c994b6cb77ee6d5
| 33.188571 | 161 | 0.535183 | 5.48396 | false | false | false | false |
skedgo/tripkit-ios
|
Sources/TripKit/UIKit/UIColor+TripKitDefault.swift
|
1
|
6094
|
//
// UIColor+TripGoDefault.swift
// TripKitUI-iOS
//
// Created by Kuan Lun Huang on 19/9/19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
extension UIColor {
static let tripgoTintColor: UIColor = {
#if targetEnvironment(macCatalyst)
// Catalyst prefers the system accent color, which we can get like this
let dummyButton = UIButton()
return dummyButton.tintColor
#else
if #available(iOS 13.0, *) {
return UIColor { traits in
switch traits.userInterfaceStyle {
case .dark: return #colorLiteral(red: 0, green: 0.8, blue: 0.4, alpha: 1)
case _: return #colorLiteral(red: 0, green: 0.8, blue: 0.4, alpha: 1)
}
}
} else { return #colorLiteral(red: 0, green: 0.8, blue: 0.4, alpha: 1) }
#endif
}()
// MARK: - Buttons
static let tripgoFilledButtonBackground: UIColor = .tkAppTintColor
static let tripgoFilledButtonTextColor: UIColor = .white
static let tripgoEmptyButtonBackground: UIColor = .tkBackground
static let tripgoEmptyButtonTextColor: UIColor = .tkLabelPrimary
// MARK: - Background
static let tripgoBackground = UIColor(named: "TKBackground", in: .tripKit, compatibleWith: nil)!
static let tripgoBackgroundSecondary = UIColor(named: "TKBackgroundSecondary", in: .tripKit, compatibleWith: nil)!
static let tripgoBackgroundTile = UIColor.tkBackground
static let tripgoBackgroundBelowTile = UIColor.tkBackgroundSecondary
static let tripgoBackgroundGrouped = UIColor.tkBackgroundSecondary
static let tripgoBackgroundSelected: UIColor = {
if #available(iOS 13.0, *) {
return UIColor { traits in
switch traits.userInterfaceStyle {
case .dark:
return #colorLiteral(red: 0.2274509804, green: 0.2274509804, blue: 0.2352941176, alpha: 1)
case _:
return #colorLiteral(red: 0.8196078431, green: 0.8196078431, blue: 0.8392156863, alpha: 1)
}
}
} else {
return #colorLiteral(red: 0.8196078431, green: 0.8196078431, blue: 0.8392156863, alpha: 1)
}
}()
// MARK: - Labels
static let tripgoLabelPrimary = UIColor(named: "TKLabelPrimary", in: .tripKit, compatibleWith: nil)!
static let tripgoLabelSecondary = UIColor(named: "TKLabelSecondary", in: .tripKit, compatibleWith: nil)!
static let tripgoLabelTertiary = UIColor(named: "TKLabelTertiary", in: .tripKit, compatibleWith: nil)!
static let tripgoLabelQuarternary = UIColor(named: "TKLabelQuarternary", in: .tripKit, compatibleWith: nil)!
// MARK: - States
static let tripgoStateError = UIColor(named: "TKStateError", in: .tripKit, compatibleWith: nil)!
static let tripgoStateWarning = UIColor(named: "TKStateWarning", in: .tripKit, compatibleWith: nil)!
static let tripgoStateSuccess = UIColor(named: "TKStateSuccess", in: .tripKit, compatibleWith: nil)!
// MARK: - Accessories
static let tripgoSeparator: UIColor = {
if #available(iOS 13.0, *) {
return .separator
} else {
return #colorLiteral(red: 0.8196078431, green: 0.8196078431, blue: 0.831372549, alpha: 1)
}
}()
static let tripgoSeparatorSubtle: UIColor = {
if #available(iOS 13.0, *) {
return UIColor { traits in
switch traits.userInterfaceStyle {
case .dark:
return #colorLiteral(red: 0.1000000015, green: 0.1000000015, blue: 0.1000000015, alpha: 1)
case _:
return #colorLiteral(red: 0.9053974748, green: 0.9053974748, blue: 0.9053974748, alpha: 1)
}
}
} else {
return #colorLiteral(red: 0.9053974748, green: 0.9053974748, blue: 0.9053974748, alpha: 1)
}
}()
static let tripgoMapOverlay: UIColor = {
if #available(iOS 13.0, *) {
return UIColor { traits in
switch (traits.userInterfaceStyle, traits.accessibilityContrast) {
case (.dark, _):
return #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.9)
case (_, _):
return #colorLiteral(red: 0.2039215686, green: 0.3058823529, blue: 0.4274509804, alpha: 0.5)
}
}
} else {
return #colorLiteral(red: 0.2039215686, green: 0.3058823529, blue: 0.4274509804, alpha: 0.5)
}
}()
static let tripgoSheetOverlay: UIColor = {
if #available(iOS 13.0, *) {
return UIColor { traits in
switch (traits.userInterfaceStyle, traits.accessibilityContrast) {
case (.dark, _):
return #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.8)
case (_, _):
return #colorLiteral(red: 0.2039215686, green: 0.3058823529, blue: 0.4274509804, alpha: 0.8)
}
}
} else {
return #colorLiteral(red: 0.2039215686, green: 0.3058823529, blue: 0.4274509804, alpha: 0.8)
}
}()
static let tripgoStatusBarOverlay: UIColor = {
if #available(iOS 13.0, *) {
return UIColor { traits in
switch (traits.userInterfaceStyle, traits.accessibilityContrast) {
case (.dark, _):
return #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.8)
case (_, _):
return #colorLiteral(red: 0.2039215686, green: 0.3058823529, blue: 0.4274509804, alpha: 0.7)
}
}
} else {
return #colorLiteral(red: 0.2039215686, green: 0.3058823529, blue: 0.4274509804, alpha: 0.7)
}
}()
// MARK: - Neutral
private static let tripgoBlack = UIColor(red: 33/255, green: 42/255, blue: 51/255, alpha: 1)
static let tripgoNeutral = UIColor(named: "TKNeutral", in: .tripKit, compatibleWith: nil)!
static let tripgoNeutral1 = UIColor(named: "TKNeutral1", in: .tripKit, compatibleWith: nil)!
static let tripgoNeutral2 = UIColor(named: "TKNeutral2", in: .tripKit, compatibleWith: nil)!
static let tripgoNeutral3 = UIColor(named: "TKNeutral3", in: .tripKit, compatibleWith: nil)!
static let tripgoNeutral4 = UIColor(named: "TKNeutral4", in: .tripKit, compatibleWith: nil)!
static let tripgoNeutral5 = UIColor(named: "TKNeutral5", in: .tripKit, compatibleWith: nil)!
}
#endif
|
apache-2.0
|
bde9d323e1179697bd867d3234de5ef3
| 37.08125 | 116 | 0.656491 | 3.626786 | false | false | false | false |
material-motion/material-motion-swift
|
src/interactions/TransitionTween.swift
|
2
|
4384
|
/*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
/**
A transition tween animates a property between two states of a transition using a Tween.
A transition tween can be associated with many properties. Each property receives its own distinct
animator.
**Constraints**
T-value constraints may be applied to this interaction.
*/
public final class TransitionTween<T>: Tween<T> {
/**
The values to use when the transition is moving backward.
*/
public let backwardValues: [T]
/**
The values to use when the transition is moving forward.
*/
public let forwardValues: [T]
/**
The key positions to use when the transition is moving backward.
*/
public let backwardKeyPositions: [CGFloat]
/**
The key positions to use when the transition is moving forward.
*/
public let forwardKeyPositions: [CGFloat]
/**
Creates a transition tween.
- parameter system: Often coreAnimation. Can be another system if a system support library is available.
*/
public init(duration: CGFloat,
forwardValues: [T],
direction: ReactiveProperty<TransitionDirection>,
delayBefore: CGFloat = 0,
delayAfter: CGFloat = 0,
forwardKeyPositions: [CGFloat] = [],
system: @escaping TweenToStream<T> = coreAnimation,
timeline: Timeline? = nil) {
self.forwardValues = forwardValues
self.backwardValues = forwardValues.reversed()
self.forwardKeyPositions = forwardKeyPositions
self.backwardKeyPositions = forwardKeyPositions.reversed().map { 1 - $0 }
let values = direction == .forward ? forwardValues : backwardValues
self.direction = direction
self.toggledValues = direction.dedupe().rewrite([.backward: backwardValues, .forward: forwardValues])
self.toggledOffsets = direction.dedupe().rewrite([.backward: backwardKeyPositions, .forward: forwardKeyPositions])
self.toggledDelay = direction.dedupe().rewrite([.backward: delayAfter, .forward: delayBefore])
super.init(duration: duration, values: values, system: system, timeline: timeline)
}
/**
Creates a transition tween.
- parameter system: Often coreAnimation. Can be another system if a system support library is available.
*/
convenience public init(duration: DispatchTimeInterval,
forwardValues: [T],
direction: ReactiveProperty<TransitionDirection>,
forwardKeyPositions: [CGFloat] = [],
system: @escaping TweenToStream<T> = coreAnimation,
timeline: Timeline? = nil) {
let durationInSeconds = duration.toSeconds()
self.init(duration: durationInSeconds, forwardValues: forwardValues, direction: direction, forwardKeyPositions: forwardKeyPositions, system: system, timeline: timeline)
}
public override func add(to property: ReactiveProperty<T>,
withRuntime runtime: MotionRuntime,
constraints: ConstraintApplicator<T>? = nil) {
let unlocked = createProperty(withInitialValue: false)
runtime.connect(direction.dedupe().rewriteTo(false), to: unlocked)
runtime.connect(toggledDelay, to: delay)
runtime.connect(toggledValues, to: values)
runtime.connect(toggledOffsets, to: offsets)
super.add(to: property, withRuntime: runtime) {
var stream = $0
if let constraints = constraints {
stream = constraints($0)
}
return stream.valve(openWhenTrue: unlocked)
}
runtime.connect(direction.dedupe().rewriteTo(true), to: unlocked)
}
private let direction: ReactiveProperty<TransitionDirection>
private let toggledValues: MotionObservable<[T]>
private let toggledOffsets: MotionObservable<[CGFloat]>
private let toggledDelay: MotionObservable<CGFloat>
}
|
apache-2.0
|
772c4e5d733d81af483f0c92429fb2af
| 36.793103 | 172 | 0.710082 | 4.729234 | false | false | false | false |
Bing0/ThroughWall
|
ChiselLogViewer/HexViewController.swift
|
1
|
1171
|
//
// HexViewController.swift
// ChiselLogViewer
//
// Created by Bingo on 10/07/2017.
// Copyright © 2017 Wu Bin. All rights reserved.
//
import Cocoa
class HexViewController: NSViewController {
@IBOutlet var textView: NSTextView!
var data: Data?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
showHex()
}
func showHex() {
if let data = data {
let hexes = [UInt8](data)
var str = ""
var text = ""
for (index, hex) in hexes.enumerated() {
str = str + String(format: "%02X ", hex)
let scalar = UnicodeScalar(hex)
if iswprint(Int32(scalar.value)) == 0 {
text = text + "."
}else{
text = text + String(scalar)
}
if index % 16 == 15 {
str = str + " ; " + text + "\n"
text = ""
}
}
textView.string = str
textView.font = NSFont(name: "Menlo", size: 13)
}
}
}
|
gpl-3.0
|
1924d5acb16c9811916dd66ff192fde3
| 24.434783 | 59 | 0.437607 | 4.415094 | false | false | false | false |
kevinvanderlugt/Exercism-Solutions
|
swift/perfect-numbers/PerfectNumbersTest.swift
|
1
|
1110
|
import Foundation
import XCTest
class PerfectNumbersTest: XCTestCase {
func testPerfect() {
let numberClassifier = NumberClassifier(number: 6)
let expectedValue = NumberClassification.Perfect
let result = numberClassifier.classification
XCTAssertEqual(result,expectedValue)
}
func testPerfectAgain() {
let numberClassifier = NumberClassifier(number: 28)
let expectedValue = NumberClassification.Perfect
let result = numberClassifier.classification
XCTAssertEqual(result,expectedValue)
}
func testDeficient() {
let numberClassifier = NumberClassifier(number: 13)
let expectedValue = NumberClassification.Deficient
let result = numberClassifier.classification
XCTAssertEqual(result,expectedValue)
}
func testAbundent() {
let numberClassifier = NumberClassifier(number: 12)
let expectedValue = NumberClassification.Abundent
let result = numberClassifier.classification
XCTAssertEqual(result,expectedValue)
}
}
|
mit
|
5fc4b601cc7c9deef1a7171b944b2d08
| 27.461538 | 59 | 0.687387 | 5.577889 | false | true | false | false |
apple/swift-syntax
|
Sources/SwiftParserDiagnostics/MissingNodesError.swift
|
1
|
13590
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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 SwiftDiagnostics
@_spi(RawSyntax) import SwiftSyntax
import SwiftBasicFormat
// MARK: - Shared code
/// Returns the bottommost node that is an ancestor of all nodes in `nodes`.
fileprivate func findCommonAncestor(_ nodes: [Syntax]) -> Syntax? {
return findCommonAncestorOrSelf(nodes.compactMap({ $0.parent }))
}
fileprivate enum NodesDescriptionPart {
case tokensWithDefaultText([TokenSyntax])
case tokenWithoutDefaultText(TokenSyntax)
case node(Syntax)
func description(format: Bool) -> String? {
switch self {
case .tokensWithDefaultText(var tokens):
if format {
tokens = tokens.map({ BasicFormat().visit($0) })
}
if !tokens.isEmpty {
tokens[0] = tokens[0].withLeadingTrivia([])
tokens[tokens.count - 1] = tokens[tokens.count - 1].withTrailingTrivia([])
}
let tokenContents = tokens.map(\.description).joined()
return "'\(tokenContents)'"
case .tokenWithoutDefaultText(let token):
if let childName = token.childNameInParent {
return childName
}
return token.tokenKind.decomposeToRaw().rawKind.nameForDiagnostics
case .node(let node):
var walk: Syntax = node
while true {
if let childName = walk.childNameInParent {
return childName
}
if let parent = walk.parent, parent.children(viewMode: .all).count == 1 {
// If walk is the only node in its parent, check if that parent has a childNameForDiagnostics
walk = parent
} else {
break
}
}
return node.nodeTypeNameForDiagnostics(allowBlockNames: true)
}
}
static func descriptionParts<S: Sequence>(for nodes: S) -> [NodesDescriptionPart] where S.Element == Syntax {
var parts: [NodesDescriptionPart] = []
for missingNode in nodes {
if let token = missingNode.as(TokenSyntax.self) {
let newPart: NodesDescriptionPart
if token.presence == .present {
newPart = .tokensWithDefaultText([token])
} else {
let (rawKind, text) = token.tokenKind.decomposeToRaw()
if let text = text, !text.isEmpty {
let presentToken = TokenSyntax(token.tokenKind, presence: .present)
newPart = .tokensWithDefaultText([presentToken])
} else if let defaultText = rawKind.defaultText {
let newKind = TokenKind.fromRaw(kind: rawKind, text: String(syntaxText: defaultText))
let presentToken = TokenSyntax(newKind, presence: .present)
newPart = .tokensWithDefaultText([presentToken])
} else {
newPart = .tokenWithoutDefaultText(token)
}
}
switch (parts.last, newPart) {
case (.tokensWithDefaultText(let previousTokens), .tokensWithDefaultText(let newTokens)):
parts[parts.count - 1] = .tokensWithDefaultText(previousTokens + newTokens)
default:
parts.append(newPart)
}
} else {
let part = NodesDescriptionPart.node(missingNode)
if part.description(format: false) == nil {
// If the new part doesn't have a good name, create one from all the tokens that are missing within it.
parts += descriptionParts(for: missingNode.children(viewMode: .all))
} else {
parts.append(part)
}
}
}
return parts
}
}
/// Returns a string that describes `missingNodes`.
/// If `commonParent` is not `nil`, `missingNodes` are expected to all be children of `commonParent`.
/// If `format` is `true`, `BasicFormat` will be used to format the tokens prior to printing. This is useful if the nodes have been synthesized.
func nodesDescription<SyntaxType: SyntaxProtocol>(_ nodes: [SyntaxType], format: Bool) -> String {
return nodesDescriptionAndCommonParent(nodes, format: format).description
}
/// Same as `nodesDescription` but if a common ancestor was used to describe `missingNodes`, also return that `commonAncestor`
func nodesDescriptionAndCommonParent<SyntaxType: SyntaxProtocol>(_ nodes: [SyntaxType], format: Bool) -> (commonAncestor: Syntax?, description: String) {
let missingSyntaxNodes = nodes.map(Syntax.init)
// If all tokens in the parent are missing, return the parent type name.
if let commonAncestor = findCommonAncestor(missingSyntaxNodes),
commonAncestor.isMissingAllTokens,
let firstToken = commonAncestor.firstToken(viewMode: .all),
let lastToken = commonAncestor.lastToken(viewMode: .all),
missingSyntaxNodes.contains(Syntax(firstToken)),
missingSyntaxNodes.contains(Syntax(lastToken)) {
if let nodeTypeName = commonAncestor.nodeTypeNameForDiagnostics(allowBlockNames: true) {
return (commonAncestor, nodeTypeName)
} else if let nodeTypeName = commonAncestor.childNameInParent {
return (commonAncestor, nodeTypeName)
}
}
let partDescriptions = NodesDescriptionPart.descriptionParts(for: missingSyntaxNodes).map({ $0.description(format: format) ?? "syntax" })
switch partDescriptions.count {
case 0:
return (nil, "syntax")
case 1:
return (nil, "\(partDescriptions.first!)")
case 2:
return (nil, "\(partDescriptions.first!) and \(partDescriptions.last!)")
default:
return (nil, "\(partDescriptions[0..<partDescriptions.count - 1].joined(separator: ", ")), and \(partDescriptions.last!)")
}
}
fileprivate extension TokenKind {
var isStartMarker: Bool {
switch self {
case .leftBrace, .leftAngle, .leftParen, .leftSquareBracket:
return true
default:
return false
}
}
var isEndMarker: Bool {
return matchingStartMarkerKind != nil
}
var matchingStartMarkerKind: TokenKind? {
switch self {
case .rightBrace:
return .leftBrace
case .rightAngle:
return .leftAngle
case .rightParen:
return .leftParen
case .rightSquareBracket:
return .leftSquareBracket
case .stringQuote, .multilineStringQuote, .rawStringDelimiter:
return self
default:
return nil
}
}
}
/// Checks whether a node contains any tokens (missing or present)
fileprivate class HasTokenChecker: SyntaxAnyVisitor {
var hasToken: Bool = false
override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind {
if hasToken {
// If we already saw a present token, we don't need to continue.
return .skipChildren
} else {
return .visitChildren
}
}
override func visit(_ node: TokenSyntax) -> SyntaxVisitorContinueKind {
hasToken = true
return .visitChildren
}
}
fileprivate extension SyntaxProtocol {
/// Returns `true` if the tree contains any tokens (either missing or present).
var hasTokens: Bool {
let checker = HasTokenChecker(viewMode: .all)
checker.walk(Syntax(self))
return checker.hasToken
}
}
// MARK: - Error
public struct MissingNodesError: ParserError {
public let missingNodes: [Syntax]
init(missingNodes: [Syntax]) {
assert(!missingNodes.isEmpty)
self.missingNodes = missingNodes
}
/// If applicable, returns a string that describes after which node the nodes are expected.
private var afterClause: String? {
guard let firstMissingNode = missingNodes.first else {
return nil
}
if let missingDecl = firstMissingNode.as(MissingDeclSyntax.self) {
if let lastModifier = missingDecl.modifiers?.last {
return "after '\(lastModifier.name.text)' modifier"
} else if missingDecl.attributes != nil {
return "after attribute"
}
}
return nil
}
/// If applicable, returns a string that describes the node in which the missing nodes are expected.
private func parentContextClause(anchor: Syntax?) -> String? {
// anchorParent is the first parent that has a type name for diagnostics.
guard let (anchorParent, anchorTypeName) = anchor?.ancestorOrSelf(mapping: { (node: Syntax) -> (Syntax, String)? in
if let name = node.nodeTypeNameForDiagnostics(allowBlockNames: false) {
return (node, name)
} else {
return nil
}
}) else {
return nil
}
if anchorParent.is(SourceFileSyntax.self) {
return nil
}
let isFirstTokenStartMarker = missingNodes.first?.as(TokenSyntax.self)?.tokenKind.isStartMarker ?? false
let isLastTokenEndMarker = missingNodes.last?.as(TokenSyntax.self)?.tokenKind.isEndMarker ?? false
switch (isFirstTokenStartMarker, isLastTokenEndMarker) {
case (true, false) where Syntax(anchorParent.firstToken(viewMode: .all)) == missingNodes.first:
return "to start \(anchorTypeName)"
case (false, true) where Syntax(anchorParent.lastToken(viewMode: .all)) == missingNodes.last:
return "to end \(anchorTypeName)"
default:
return "in \(anchorTypeName)"
}
}
public var message: String {
let (anchor, description) = nodesDescriptionAndCommonParent(missingNodes, format: true)
var message = "expected \(description)"
if let afterClause = afterClause {
message += " \(afterClause)"
}
if let parentContextClause = parentContextClause(anchor: anchor?.parent ?? findCommonAncestor(missingNodes)) {
message += " \(parentContextClause)"
}
return message
}
}
// MARK: - Note
public struct MatchingOpeningTokenNote: ParserNote {
let openingToken: TokenSyntax
public var message: String { "to match this opening '\(openingToken.text)'" }
}
// MARK: - Fix-It
public struct InsertTokenFixIt: ParserFixIt {
public let missingNodes: [Syntax]
init(missingNodes: [Syntax]) {
assert(!missingNodes.isEmpty)
self.missingNodes = missingNodes
}
public var message: String { "insert \(nodesDescription(missingNodes, format: true))" }
}
// MARK: - Generate Error
extension ParseDiagnosticsGenerator {
func handleMissingSyntax<T: SyntaxProtocol>(_ node: T) -> SyntaxVisitorContinueKind {
if shouldSkip(node) {
return .skipChildren
}
/// Ancestors that don't contain any tokens are not very interesting to merge diagnostics (because there can't be any missing tokens we can merge them with).
/// Find the first ancestor that contains any tokens.
var ancestorWithTokens = node.parent
var index = node.index
while let unwrappedParent = ancestorWithTokens, !unwrappedParent.hasTokens {
ancestorWithTokens = unwrappedParent.parent
index = unwrappedParent.index
}
// Walk all upcoming sibling to see if they are also missing to handle them in this diagnostic.
// If this is the case, handle all of them in this diagnostic.
var missingNodes = [Syntax(node)]
if let parentWithTokens = ancestorWithTokens {
let siblings = parentWithTokens.children(viewMode: .all)
let siblingsAfter = siblings[siblings.index(after: index)...]
for sibling in siblingsAfter {
if sibling.as(TokenSyntax.self)?.presence == .missing {
// Handle missing sibling tokens
missingNodes += [sibling]
} else if sibling.raw.kind.isMissing {
// Handle missing sibling nodes (e.g. MissingDeclSyntax)
missingNodes += [sibling]
} else if sibling.isMissingAllTokens && sibling.hasTokens {
missingNodes += [sibling]
} else if sibling.isCollection && sibling.children(viewMode: .sourceAccurate).count == 0 {
// Skip over any syntax collections without any elements while looking ahead for further missing nodes.
} else {
// Otherwise we have found a present node, so stop looking ahead.
break
}
}
} else {
missingNodes = []
}
let changes = missingNodes.enumerated().map { (index, missingNode) -> FixIt.Changes in
if index == 0, let token = missingNode.as(TokenSyntax.self), token.tokenKind.isPunctuation == true, token.previousToken(viewMode: .sourceAccurate)?.tokenKind.isPunctuation == false {
return .makePresentBeforeTrivia(token)
} else {
return .makePresent(missingNode)
}
}
let fixIt = FixIt(
message: InsertTokenFixIt(missingNodes: missingNodes),
changes: changes
)
var notes: [Note] = []
if missingNodes.count == 1,
let token = missingNodes.last?.as(TokenSyntax.self),
let matchingStartMarkerKind = token.tokenKind.matchingStartMarkerKind,
let startToken = token.parent?.children(viewMode: .sourceAccurate).lazy.compactMap({ $0.as(TokenSyntax.self) }).first(where: { $0.tokenKind == matchingStartMarkerKind }) {
notes.append(Note(node: Syntax(startToken), message: MatchingOpeningTokenNote(openingToken: startToken)))
}
let position: AbsolutePosition
if node.shouldBeInsertedAfterNextTokenTrivia, let nextToken = node.nextToken(viewMode: .sourceAccurate) {
position = nextToken.positionAfterSkippingLeadingTrivia
} else {
position = node.endPosition
}
addDiagnostic(
node,
position: position,
MissingNodesError(missingNodes: missingNodes),
notes: notes,
fixIts: [fixIt],
handledNodes: missingNodes.map(\.id)
)
return .visitChildren
}
}
|
apache-2.0
|
8595aa0200116f522a0d1179d1096fa9
| 35.72973 | 188 | 0.6766 | 4.395213 | false | false | false | false |
february29/Learning
|
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Debug.swift
|
94
|
3752
|
//
// Debug.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
import class Foundation.DateFormatter
extension ObservableType {
/**
Prints received events for all observers on standard output.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter identifier: Identifier that is printed together with event description to standard output.
- parameter trimOutput: Should output be trimmed to max 40 characters.
- returns: An observable sequence whose events are printed to standard output.
*/
public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function)
-> Observable<E> {
return Debug(source: self, identifier: identifier, trimOutput: trimOutput, file: file, line: line, function: function)
}
}
fileprivate let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
fileprivate func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) {
print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)")
}
final fileprivate class DebugSink<Source: ObservableType, O: ObserverType> : Sink<O>, ObserverType where O.E == Source.E {
typealias Element = O.E
typealias Parent = Debug<Source>
private let _parent: Parent
private let _timestampFormatter = DateFormatter()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_timestampFormatter.dateFormat = dateFormat
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "subscribed")
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
let maxEventTextLength = 40
let eventText = "\(event)"
let eventNormalized = (eventText.characters.count > maxEventTextLength) && _parent._trimOutput
? String(eventText.characters.prefix(maxEventTextLength / 2)) + "..." + String(eventText.characters.suffix(maxEventTextLength / 2))
: eventText
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "Event \(eventNormalized)")
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
override func dispose() {
if !self.disposed {
logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "isDisposed")
}
super.dispose()
}
}
final fileprivate class Debug<Source: ObservableType> : Producer<Source.E> {
fileprivate let _identifier: String
fileprivate let _trimOutput: Bool
fileprivate let _source: Source
init(source: Source, identifier: String?, trimOutput: Bool, file: String, line: UInt, function: String) {
_trimOutput = trimOutput
if let identifier = identifier {
_identifier = identifier
}
else {
let trimmedFile: String
if let lastIndex = file.lastIndexOf("/") {
trimmedFile = file[file.index(after: lastIndex) ..< file.endIndex]
}
else {
trimmedFile = file
}
_identifier = "\(trimmedFile):\(line) (\(function))"
}
_source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Source.E {
let sink = DebugSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
|
mit
|
e119df82a6c334853988d1f011d0b5bd
| 35.417476 | 148 | 0.648627 | 4.535671 | false | false | false | false |
bubnov/SBTableViewAdapter
|
TableViewAdapter/TableViewAdapter.swift
|
2
|
15594
|
//
// TableViewAdapter.swift
// Collections
//
// Created by Bubnov Slavik on 02/03/2017.
// Copyright © 2017 Bubnov Slavik. All rights reserved.
//
import UIKit
public class TableViewAdapter: NSObject, UITableViewDataSource, UITableViewDelegate, CollectionViewAdapterType, ReloadableAdapterType {
//MARK: - Public
public var sections: [CollectionSectionType] = []
public var mappers: [AbstractMapper] = []
public var selectionHandler: ((CollectionItemType) -> Void)?
public var accessoryButtonHandler: ((CollectionItemType) -> Void)?
public var logger: ((String) -> Void)?
public func assign(to view: UIView) {
guard let view = view as? UITableView else { fatalError("UITableView is expected") }
tableView = view
view.delegate = self
view.dataSource = self
view.estimatedSectionHeaderHeight = 10
view.estimatedSectionFooterHeight = 10
view.estimatedRowHeight = 44
view.sectionHeaderHeight = UITableViewAutomaticDimension
view.sectionFooterHeight = UITableViewAutomaticDimension
view.rowHeight = UITableViewAutomaticDimension
view.reloadData()
view.reloadSections(
NSIndexSet(indexesIn: NSMakeRange(0, view.dataSource!.numberOfSections!(in: view))) as IndexSet,
with: .automatic
)
tableViewPositionManager = TableViewPositionManager(
tableView: view,
idResolver: { [weak self] indexPath in
return self?._item(atIndexPath: indexPath)?.uid
},
indexPathResolver: { [weak self] id -> IndexPath? in
for section in (self?.sections ?? []).enumerated() {
for item in (section.element.items ?? []).enumerated() {
if item.element.uid == id {
return IndexPath(row: item.offset, section: section.offset)
}
}
}
return nil
}
)
tableViewPositionManager.logger = logger
}
//MARK: - ReloadableAdapterType
internal func reloadAll() {
tableViewPositionManager.keepPosition {
tableView?.reloadData()
}
}
internal func reloadItem(at index: Int, section: Int, animation: UITableViewRowAnimation? = nil) {
guard let tableView = tableView, section < tableView.numberOfSections, index < tableView.numberOfRows(inSection: section) else { return }
tableViewPositionManager.keepPosition {
if _UIAndDataAreDesynchronized() {
tableView.reloadData()
}
else {
tableView.beginUpdates()
tableView.reloadRows(at: [IndexPath(row: index, section: section)], with: animation ?? .automatic)
tableView.endUpdates()
}
}
}
internal func reloadSection(at index: Int, animation: UITableViewRowAnimation? = nil) {
guard let tableView = tableView, index < tableView.numberOfSections else { return }
tableViewPositionManager.keepPosition {
if _UIAndDataAreDesynchronized() {
tableView.reloadData()
}
else {
tableView.beginUpdates()
tableView.reloadSections(IndexSet(integer: index), with: animation ?? .automatic)
tableView.endUpdates()
}
}
}
//MARK: - Private
private weak var tableView: UITableView?
private var registeredIds: [String] = []
private var tableViewPositionManager: TableViewPositionManagerType!
private enum ViewType {
case Item, Header, Footer
}
private func _UIAndDataAreDesynchronized() -> Bool {
guard let tableView = tableView else { return true }
for sectionInfo in sections.enumerated() {
if let items = sectionInfo.element.items, items.count != tableView.numberOfRows(inSection: sectionInfo.offset) {
return true
}
}
return false
}
private func _section(atIndex index: Int) -> CollectionSectionType? {
guard (0..<sections.count).contains(index) else { return nil }
let section = sections[index]
if let internalSection = section as? InternalCollectionSectionType {
internalSection._index = index
internalSection._adapter = self
}
return section
}
private func _section(atIndexPath indexPath: IndexPath) -> CollectionSectionType? {
return _section(atIndex: indexPath.section)
}
private func _header(atIndex index: Int) -> CollectionItemType? {
return _item(atIndexPath: IndexPath(item: 0, section: index), viewType: .Header)
}
private func _footer(atIndex index: Int) -> CollectionItemType? {
return _item(atIndexPath: IndexPath(item: 0, section: index), viewType: .Footer)
}
private func _item(atIndexPath indexPath: IndexPath, viewType: ViewType? = .Item) -> CollectionItemType? {
guard let section = _section(atIndexPath: indexPath) else { return nil }
var item: CollectionItemType?
switch viewType! {
case .Item:
if indexPath.item < section.items?.count ?? 0 {
item = section.items?[indexPath.item]
} else if section.dynamicItemMapper != nil {
item = Item(value: indexPath.row, mapper: section.dynamicItemMapper)
}
case .Header:
item = section.header
case .Footer:
item = section.footer
}
guard item != nil else { return nil }
if let internalItem = item as? InternalCollectionItemType {
internalItem._index = indexPath.item
internalItem._section = section as? ReloadableSectionType
}
if item!.mapper == nil {
_ = _resolveMapperForItem(item!, section: section, viewType: viewType)
}
/// Register views
let mapper = (item!.mapper)!
let id = item!.id
if !registeredIds.contains(id) {
registeredIds.append(id)
/// Resolve optional nib
var nib: UINib? = nil
let className = "\(mapper.targetClass)"
if Bundle.main.path(forResource: className, ofType: "nib") != nil {
nib = UINib(nibName: className, bundle: nil)
}
/// Register class/nib
switch viewType! {
case .Item:
if nib != nil {
tableView?.register(nib, forCellReuseIdentifier: id)
} else {
tableView?.register(mapper.targetClass, forCellReuseIdentifier: id)
}
case .Header, .Footer:
if nib != nil {
tableView?.register(nib, forHeaderFooterViewReuseIdentifier: id)
} else {
tableView?.register(mapper.targetClass, forHeaderFooterViewReuseIdentifier: id)
}
}
}
return item
}
private func _resolveMapperForItem(_ item: CollectionItemType, section: CollectionSectionType, viewType: ViewType? = .Item) -> AbstractMapper? {
if let mapper = item.mapper {
return mapper
}
var resolvedMapper: AbstractMapper?
for (_, mapper) in section.mappers.enumerated() {
if mapper.id == item.id {
resolvedMapper = mapper
break
}
}
if resolvedMapper == nil {
for (_, mapper) in mappers.enumerated() {
if mapper.id == item.id {
resolvedMapper = mapper
break
}
}
}
if resolvedMapper == nil {
switch viewType! {
case .Item:
resolvedMapper = Mapper<AnyObject, UITableViewCell> { value, cell in
cell.textLabel?.text = (value != nil) ? "\(value!)" : nil
}
case .Header:
resolvedMapper = Mapper<AnyObject, TableViewHeaderFooterView> { value, view in
view.label.text = (value != nil) ? "\(value!)" : nil
view.setNeedsUpdateConstraints()
view.invalidateIntrinsicContentSize()
}
case .Footer:
resolvedMapper = Mapper<AnyObject, TableViewHeaderFooterView> { value, view in
view.label.text = (value != nil) ? "\(value!)" : nil
}
}
}
item.mapper = resolvedMapper
return resolvedMapper
}
// MARK: - UITableViewDataSource
public func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = _section(atIndex: section), !section.isHidden else { return 0 }
return section.dynamicItemCount ?? section.items?.count ?? 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let item = _item(atIndexPath: indexPath as IndexPath) {
if let cell = tableView.dequeueReusableCell(withIdentifier: item.id) {
item.mapper?.apply(item.value, to: cell)
return cell
}
}
return UITableViewCell()
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let header = _header(atIndex: section), _section(atIndex: section)?.isHidden != true {
if let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: header.id) {
if var headerViewType = headerView as? TableViewHeaderFooterViewType {
headerViewType.isFooter = false
headerViewType.isFirst = (section == 0)
headerViewType.tableViewStyle = tableView.style
headerView.setNeedsUpdateConstraints()
}
header.mapper?.apply(header.value, to: headerView)
return headerView
}
}
return UITableViewHeaderFooterView()
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if let footer = _footer(atIndex: section), _section(atIndex: section)?.isHidden != true {
if let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: footer.id) {
if var footerViewType = footerView as? TableViewHeaderFooterViewType {
footerViewType.isFooter = true
footerViewType.isFirst = (section == 0)
footerViewType.tableViewStyle = tableView.style
footerView.setNeedsUpdateConstraints()
}
footer.mapper?.apply(footer.value, to: footerView)
return footerView
}
}
return UITableViewHeaderFooterView()
}
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
var titles: [String] = []
for section in sections {
if let indexTitle = section.indexTitle {
titles.append(indexTitle)
}
}
return titles
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return _item(atIndexPath: indexPath as IndexPath)?.editable ?? true
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard let item = _item(atIndexPath: indexPath as IndexPath) else { return }
item.commitEditingStyle?(editingStyle, item)
}
// MARK: - UITableViewDelegate
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
guard let item = _item(atIndexPath: indexPath as IndexPath) else { return }
if let handler = item.selectionHandler {
handler(item)
return
}
if let section = _section(atIndex: indexPath.section),
let handler = section.selectionHandler {
handler(item)
return
}
selectionHandler?(item)
}
public func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
guard let item = _item(atIndexPath: indexPath as IndexPath) else { return }
if let handler = item.accessoryButtonHandler {
handler(item)
return
}
if let section = _section(atIndex: indexPath.section),
let handler = section.accessoryButtonHandler {
handler(item)
return
}
accessoryButtonHandler?(item)
}
public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
guard _section(atIndex: section)?.isHidden != true else { return 0 }
return tableView.estimatedSectionHeaderHeight
}
public func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
guard _section(atIndex: section)?.isHidden != true else { return 0 }
return tableView.estimatedSectionFooterHeight
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard _section(atIndex: section)?.isHidden != true else { return 0 }
guard _header(atIndex: section) != nil else {
guard tableView.style == .grouped else { return 0 }
guard _section(atIndex: section - 1)?.footer != nil else { return 35 }
return 16
}
return tableView.sectionHeaderHeight
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard _section(atIndex: section)?.isHidden != true else { return 0 }
guard _footer(atIndex: section) != nil else {
guard tableView.style == .grouped else { return 0 }
guard let nextSection = _section(atIndex: section + 1) else { return 16 }
guard nextSection.header != nil else { return 0 }
return 16
}
return tableView.sectionFooterHeight
}
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return _item(atIndexPath: indexPath as IndexPath)?.editingStyle ?? .none
}
public func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return _item(atIndexPath: indexPath as IndexPath)?.titleForDeleteConfirmationButton
}
public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return _item(atIndexPath: indexPath as IndexPath)?.editActions
}
}
|
mit
|
49673312f986f9b48442a16d255ad249
| 37.788557 | 148 | 0.588982 | 5.557021 | false | false | false | false |
mumbler/PReVo-iOS
|
DatumbazKonstruilo/DatumbazKonstruilo/XMLLegiloj (provaj, ne uzataj)/LiteroXMLLegilo.swift
|
1
|
2750
|
//
// LiteroXMLLegilo.swift
// DatumbazKonstruilo
//
// Created by Robin Hill on 3/17/20.
// Copyright © 2020 Robin Hill. All rights reserved.
//
import Foundation
import CoreData
class LiteroXMLLegilo: NSObject, XMLParserDelegate {
public var literoj = [String: String]()
private let konteksto: NSManagedObjectContext
private var atendLiteroj = [String:String]()
init(_ konteksto: NSManagedObjectContext) {
self.konteksto = konteksto
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if elementName == "l",
let nomo = attributeDict["nomo"],
let kodo = attributeDict["kodo"] {
if kodo.count > 2 && kodo.prefix(2) == "#x" {
let numero = kodo[kodo.index(kodo.startIndex, offsetBy: 2)...]
if let intLitero = Int(numero, radix: 16),
let scalarLitero = UnicodeScalar(intLitero) {
let strLitero = String(scalarLitero)
literoj[nomo] = strLitero
if let atendata = atendLiteroj[nomo] {
literoj[atendata] = strLitero
atendLiteroj[nomo] = nil
}
}
} else {
let partoj = kodo.split(separator: ";")
if partoj.count == 1 {
atendLiteroj[kodo] = nomo
} else if partoj.count > 1 {
var sumo = ""
for parto in partoj {
if parto == "&" { continue }
if let trovo = literoj[String(parto)] {
sumo += trovo
}
}
literoj[nomo] = sumo
}
}
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
}
}
// MARK: - Vokilo
extension LiteroXMLLegilo {
public static func legiDosieron(_ literoURL: URL, enKontekston konteksto: NSManagedObjectContext) -> [String: String] {
var literoj = [String: String]()
let literoLegilo = LiteroXMLLegilo(konteksto)
if let parser = XMLParser(contentsOf: literoURL) {
parser.delegate = literoLegilo
parser.parse()
literoj = literoLegilo.literoj
}
return literoj
}
}
|
mit
|
3044d24e00618e04fbffea236046382b
| 32.120482 | 179 | 0.516915 | 4.391374 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
Trust/Settings/ViewControllers/NotificationsViewController.swift
|
1
|
3010
|
// Copyright DApps Platform Inc. All rights reserved.
import UIKit
import Eureka
struct NotificationChange: Codable {
let isEnabled: Bool
let preferences: Preferences
}
enum NotificationChanged {
case state(isEnabled: Bool)
case preferences(Preferences)
}
final class NotificationsViewController: FormViewController {
private let viewModel = NotificationsViewModel()
private let preferencesController: PreferencesController
private struct Keys {
static let pushNotifications = "pushNotifications"
static let payment = "payment"
}
var didChange: ((_ change: NotificationChanged) -> Void)?
private static var isPushNotificationEnabled: Bool {
guard let settings = UIApplication.shared.currentUserNotificationSettings else { return false }
return UIApplication.shared.isRegisteredForRemoteNotifications && !settings.types.isEmpty
}
private var showOptionsCondition: Condition {
return Condition.predicate(NSPredicate(format: "$\(Keys.pushNotifications) == false"))
}
init(
preferencesController: PreferencesController = PreferencesController()
) {
self.preferencesController = preferencesController
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = viewModel.title
form +++ Section()
<<< SwitchRow(Keys.pushNotifications) {
$0.title = NSLocalizedString("settings.allowPushNotifications.button.title", value: "Allow Push Notifications", comment: "")
$0.value = NotificationsViewController.isPushNotificationEnabled
}.onChange { [unowned self] row in
self.didChange?(.state(isEnabled: row.value ?? false))
}
+++ Section(
footer: NSLocalizedString(
"settings.pushNotifications.allowPushNotifications.footer",
value: "You will be notified for sent and received transactions.",
comment: ""
)
) {
$0.hidden = showOptionsCondition
}
<<< SwitchRow(Keys.payment) { [weak self] in
$0.title = NSLocalizedString("settings.pushNotifications.payment.button.title", value: "Sent and Receive", comment: "")
$0.value = true
$0.hidden = self?.showOptionsCondition
$0.disabled = Condition(booleanLiteral: true)
}.cellSetup { cell, _ in
cell.switchControl.isEnabled = false
}
}
func updatePreferences() {
didChange?(.preferences(
NotificationsViewController.getPreferences()
))
}
static func getPreferences() -> Preferences {
//let preferencesController = PreferencesController()
let preferences = Preferences()
return preferences
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
9cdffa82bd7bc47ec304ff984185e74a
| 31.365591 | 140 | 0.649502 | 5.512821 | false | false | false | false |
4taras4/totp-auth
|
TOTP/ViperModules/FolderSettings/Module/Assembly/FolderSettingsAssemblyContainer.swift
|
1
|
1301
|
//
// FolderSettingsFolderSettingsAssemblyContainer.swift
// TOTP
//
// Created by Tarik on 15/02/2021.
// Copyright © 2021 Taras Markevych. All rights reserved.
//
import Swinject
final class FolderSettingsAssemblyContainer: Assembly {
func assemble(container: Container) {
container.register(FolderSettingsInteractor.self) { (_, presenter: FolderSettingsPresenter) in
let interactor = FolderSettingsInteractor()
interactor.output = presenter
return interactor
}
container.register(FolderSettingsRouter.self) { (_, viewController: FolderSettingsViewController) in
let router = FolderSettingsRouter()
router.transitionHandler = viewController
return router
}
container.register(FolderSettingsPresenter.self) { (r, viewController: FolderSettingsViewController) in
let presenter = FolderSettingsPresenter()
presenter.view = viewController
presenter.interactor = r.resolve(FolderSettingsInteractor.self, argument: presenter)
presenter.router = r.resolve(FolderSettingsRouter.self, argument: viewController)
return presenter
}
container.storyboardInitCompleted(FolderSettingsViewController.self) { r, viewController in
viewController.output = r.resolve(FolderSettingsPresenter.self, argument: viewController)
}
}
}
|
mit
|
23879a04f4b8c41a7979e1b9140b048a
| 29.952381 | 105 | 0.769231 | 4.49827 | false | false | false | false |
frtlupsvn/Vietnam-To-Go
|
Pods/Former/Former/RowFormers/TextFieldRowFormer.swift
|
1
|
5162
|
//
// TextFieldRowFormer.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/25/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public protocol TextFieldFormableRow: FormableRow {
func formTextField() -> UITextField
func formTitleLabel() -> UILabel?
}
public final class TextFieldRowFormer<T: UITableViewCell where T: TextFieldFormableRow>
: BaseRowFormer<T>, Formable {
// MARK: Public
override public var canBecomeEditing: Bool {
return enabled
}
public var text: String?
public var placeholder: String?
public var attributedPlaceholder: NSAttributedString?
public var textDisabledColor: UIColor? = .lightGrayColor()
public var titleDisabledColor: UIColor? = .lightGrayColor()
public var titleEditingColor: UIColor?
public var returnToNextRow = true
public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: (T -> Void)? = nil) {
super.init(instantiateType: instantiateType, cellSetup: cellSetup)
}
public final func onTextChanged(handler: (String -> Void)) -> Self {
onTextChanged = handler
return self
}
public override func cellInitialized(cell: T) {
super.cellInitialized(cell)
let textField = cell.formTextField()
textField.delegate = observer
let events: [(Selector, UIControlEvents)] = [("textChanged:", .EditingChanged),
("editingDidBegin:", .EditingDidBegin),
("editingDidEnd:", .EditingDidEnd)]
events.forEach {
textField.addTarget(self, action: $0.0, forControlEvents: $0.1)
}
}
public override func update() {
super.update()
cell.selectionStyle = .None
let titleLabel = cell.formTitleLabel()
let textField = cell.formTextField()
textField.text = text
_ = placeholder.map { textField.placeholder = $0 }
_ = attributedPlaceholder.map { textField.attributedPlaceholder = $0 }
textField.userInteractionEnabled = false
if enabled {
if isEditing {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() }
_ = titleEditingColor.map { titleLabel?.textColor = $0 }
} else {
_ = titleColor.map { titleLabel?.textColor = $0 }
titleColor = nil
}
_ = textColor.map { textField.textColor = $0 }
textColor = nil
} else {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() }
if textColor == nil { textColor = textField.textColor ?? .blackColor() }
titleLabel?.textColor = titleDisabledColor
textField.textColor = textDisabledColor
}
}
public override func cellSelected(indexPath: NSIndexPath) {
let textField = cell.formTextField()
if !textField.editing {
textField.userInteractionEnabled = true
textField.becomeFirstResponder()
}
}
// MARK: Private
private final var onTextChanged: (String -> Void)?
private final var textColor: UIColor?
private final var titleColor: UIColor?
private lazy var observer: Observer<T> = Observer<T>(textFieldRowFormer: self)
private dynamic func textChanged(textField: UITextField) {
if enabled {
let text = textField.text ?? ""
self.text = text
onTextChanged?(text)
}
}
private dynamic func editingDidBegin(textField: UITextField) {
let titleLabel = cell.formTitleLabel()
if titleColor == nil { textColor = textField.textColor ?? .blackColor() }
_ = titleEditingColor.map { titleLabel?.textColor = $0 }
}
private dynamic func editingDidEnd(textField: UITextField) {
let titleLabel = cell.formTitleLabel()
if enabled {
_ = titleColor.map { titleLabel?.textColor = $0 }
titleColor = nil
} else {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() }
_ = titleEditingColor.map { titleLabel?.textColor = $0 }
}
cell.formTextField().userInteractionEnabled = false
}
}
private class Observer<T: UITableViewCell where T: TextFieldFormableRow>: NSObject, UITextFieldDelegate {
private weak var textFieldRowFormer: TextFieldRowFormer<T>?
init(textFieldRowFormer: TextFieldRowFormer<T>) {
self.textFieldRowFormer = textFieldRowFormer
}
private dynamic func textFieldShouldReturn(textField: UITextField) -> Bool {
guard let textFieldRowFormer = textFieldRowFormer else { return false }
if textFieldRowFormer.returnToNextRow {
let returnToNextRow = (textFieldRowFormer.former?.canBecomeEditingNext() ?? false) ?
textFieldRowFormer.former?.becomeEditingNext :
textFieldRowFormer.former?.endEditing
returnToNextRow?()
}
return !textFieldRowFormer.returnToNextRow
}
}
|
mit
|
c4e5039c73fb8850dd0b286b1df9c977
| 34.6 | 107 | 0.626623 | 5.260958 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/WalletPayload/Tests/WalletPayloadKitTests/General/WalletPersistenceTests.swift
|
1
|
9954
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import KeychainKit
@testable import WalletPayloadDataKit
@testable import WalletPayloadKit
import Combine
import KeychainKitMock
import XCTest
class WalletPersistenceTests: XCTestCase {
private var cancellables: Set<AnyCancellable>!
private var mockKeychainAccess: KeychainAccessMock!
private var persistenceQueue: DispatchQueue!
let expectedState = WalletRepoState(
credentials: WalletCredentials(
guid: "guid",
sharedKey: "sharedKey",
sessionToken: "sessionToken",
password: "password"
),
properties: WalletProperties(
syncPubKeys: false,
language: "en",
authenticatorType: .standard
),
walletPayload: .empty
)
override func setUp() {
super.setUp()
mockKeychainAccess = KeychainAccessMock(service: "")
persistenceQueue = DispatchQueue(label: "a-queue")
cancellables = []
}
override func tearDown() {
mockKeychainAccess = nil
persistenceQueue = nil
cancellables = nil
super.tearDown()
}
func test_wallet_persistence_can_retrieve_state() throws {
// given a stored state
let expectedStateAsData = try walletRepoStateEncoder(expectedState).get()
mockKeychainAccess.readResult = .success(expectedStateAsData)
// when retrieving an initial state
let retrievedState: WalletRepoState? = retrieveWalletRepoState(
keychainAccess: mockKeychainAccess
)
// expected decoded state should not include the password
let retrievedExpectedState = WalletRepoState(
credentials: WalletCredentials(
guid: "guid",
sharedKey: "sharedKey",
sessionToken: "sessionToken",
password: ""
),
properties: WalletProperties(
syncPubKeys: false,
language: "en",
authenticatorType: .standard
),
walletPayload: .empty
)
// then
XCTAssertTrue(mockKeychainAccess.readCalled)
XCTAssertEqual(retrievedState, retrievedExpectedState)
}
func test_wallet_persistence_state_is_nil_in_case_of_error() throws {
// given a success read
let successReadResult = Result<Data, KeychainAccessError>.success(Data())
let failureReadResult = Result<Data, KeychainAccessError>.failure(.readFailure(.itemNotFound(account: "")))
// given a failed decoder
var mockDecoderCalled = false
var decodeResult: Result<WalletRepoState, WalletRepoStateCodingError> = .success(.empty)
let mockDecoder: WalletRepoStateDecoding = { _ in
mockDecoderCalled = true
return decodeResult
}
// given
mockKeychainAccess.readResult = successReadResult
decodeResult = .failure(
.decodingFailed(
DecodingError.dataCorrupted(
.init(codingPath: [], debugDescription: "")
)
)
)
// when retrieving an initial state
var retrievedState: WalletRepoState? = retrieveWalletRepoState(
keychainAccess: mockKeychainAccess,
decoder: mockDecoder
)
// then
XCTAssertTrue(mockKeychainAccess.readCalled)
XCTAssertTrue(mockDecoderCalled)
XCTAssertNil(retrievedState)
// given
mockKeychainAccess.readResult = failureReadResult
decodeResult = .success(.empty)
// when retrieving an initial state
retrievedState = retrieveWalletRepoState(
keychainAccess: mockKeychainAccess,
decoder: mockDecoder
)
// then
XCTAssertTrue(mockKeychainAccess.readCalled)
XCTAssertTrue(mockDecoderCalled)
XCTAssertNil(retrievedState)
}
func test_wallet_persistence_can_retrieve_state_as_publisher() throws {
// given a stored state
let expectedStateAsData = try walletRepoStateEncoder(expectedState).get()
mockKeychainAccess.readResult = .success(expectedStateAsData)
let walletPersistence = WalletRepoPersistence(
repo: WalletRepo(initialState: .empty),
keychainAccess: mockKeychainAccess,
queue: persistenceQueue,
encoder: walletRepoStateEncoder,
decoder: walletRepoStateDecoder
)
let expectation = expectation(description: "retrieved wallet repo state")
// expected decoded state should not include the password
let retrievedExpectedState = WalletRepoState(
credentials: WalletCredentials(
guid: "guid",
sharedKey: "sharedKey",
sessionToken: "sessionToken",
password: ""
),
properties: WalletProperties(
syncPubKeys: false,
language: "en",
authenticatorType: .standard
),
walletPayload: .empty
)
// when retrieving an initial state
var receivedState: WalletRepoState?
walletPersistence.retrieve()
.sink(
receiveCompletion: { _ in },
receiveValue: { state in
receivedState = state
expectation.fulfill()
}
)
.store(in: &cancellables)
wait(for: [expectation], timeout: 1)
// then
XCTAssertTrue(mockKeychainAccess.readCalled)
XCTAssertEqual(receivedState, retrievedExpectedState)
}
func test_wallet_persistence_can_persist_changes() throws {
// given a success result
mockKeychainAccess.writeResult = .success(())
let walletRepo = WalletRepo(initialState: .empty)
var mockEncoderCalled = false
let mockEncoder: WalletRepoStateEncoding = { data in
mockEncoderCalled = true
return walletRepoStateEncoder(data)
}
let walletPersistence = WalletRepoPersistence(
repo: walletRepo,
keychainAccess: mockKeychainAccess,
queue: persistenceQueue,
encoder: mockEncoder,
decoder: walletRepoStateDecoder
)
let expectation = expectation(description: "can persist successfully")
expectation.expectedFulfillmentCount = 2
walletPersistence
.beginPersisting()
.print()
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { _ in },
receiveValue: { [mockKeychainAccess] _ in
XCTAssertTrue(mockEncoderCalled)
XCTAssertTrue(mockKeychainAccess!.writeCalled)
expectation.fulfill()
}
)
.store(in: &cancellables)
// setting a value to the repo should trigger a write
walletRepo.set(keyPath: \.credentials.guid, value: "a-guid")
wait(for: [expectation], timeout: 5)
}
func test_wallet_persistence_can_persist_changes_skipping_duplicates() throws {
// given a success result
mockKeychainAccess.writeResult = .success(())
let walletRepo = WalletRepo(initialState: .empty)
let walletPersistence = WalletRepoPersistence(
repo: walletRepo,
keychainAccess: mockKeychainAccess,
queue: persistenceQueue,
encoder: walletRepoStateEncoder,
decoder: walletRepoStateDecoder
)
let expectation = expectation(description: "can persist successfully")
expectation.expectedFulfillmentCount = 2
walletPersistence
.beginPersisting()
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { _ in },
receiveValue: { [mockKeychainAccess] _ in
XCTAssertTrue(mockKeychainAccess!.writeCalled)
expectation.fulfill()
}
)
.store(in: &cancellables)
// setting a value to the repo should trigger a write
walletRepo.set(keyPath: \.credentials.guid, value: "a-guid")
// setting the same value should not trigger another write
walletRepo.set(keyPath: \.credentials.guid, value: "a-guid")
wait(for: [expectation], timeout: 5)
}
func test_wallet_persistence_retrieves_correct_error() throws {
// given a write error
let expectedWriteError: KeychainAccessError = .writeFailure(.writeFailed(account: "", status: -1))
mockKeychainAccess.writeResult = .failure(expectedWriteError)
let walletRepo = WalletRepo(initialState: .empty)
let walletPersistence = WalletRepoPersistence(
repo: walletRepo,
keychainAccess: mockKeychainAccess,
queue: persistenceQueue,
encoder: walletRepoStateEncoder,
decoder: walletRepoStateDecoder
)
let expectation = expectation(description: "should receive error")
expectation.expectedFulfillmentCount = 1
walletPersistence
.beginPersisting()
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { completion in
guard case .failure(let error) = completion else {
return
}
XCTAssertEqual(
error,
.keychainFailure(expectedWriteError)
)
expectation.fulfill()
},
receiveValue: { _ in }
)
.store(in: &cancellables)
wait(for: [expectation], timeout: 5)
}
}
|
lgpl-3.0
|
72aeab2f796f2ae4ae2288754ff2120c
| 31.848185 | 115 | 0.596905 | 5.563443 | false | false | false | false |
alokard/savings-assistant
|
savings-assistant/FilterViewController.swift
|
3
|
8946
|
//
// FilterViewController.swift
// savings-assistant
//
// Created by Chris Amanse on 8/2/15.
// Copyright (c) 2015 Joe Christopher Paul Amanse. All rights reserved.
//
import UIKit
import RealmSwift
class FilterViewController: UIViewController {
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var earningsLabel: UILabel!
@IBOutlet weak var expensesLabel: UILabel!
@IBOutlet weak var totalAmountLabel: UILabel!
@IBOutlet weak var dateRangeLabel: UILabel!
var dateRange: DateRange = DateRange(startDate: NSDate().startOf(.Day), endDate: NSDate().endOf(.Day)) {
didSet {
updateFilter()
}
}
weak var account: Account?
private var _filteredTransactions: Results<Transaction>?
var filteredTransactions: Results<Transaction> {
if _filteredTransactions == nil {
_filteredTransactions = Realm().objects(Transaction).filter("account = %@", account ?? nil as COpaquePointer).filter(transactionsPredicate).sorted("date", ascending: false)
}
return _filteredTransactions!
}
var transactionsPredicate: NSPredicate = NSPredicate(format: "TRUEPREDICATE") {
didSet {
_filteredTransactions = nil
configureView()
tableView.reloadData()
}
}
var realmNotificationToken: NotificationToken?
var adjustedTableViewOffset = false
let numberFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
configureView()
// Load cell nib
let expenseNib = UINib(nibName: "ExpenseTableViewCell", bundle: NSBundle.mainBundle())
tableView.registerNib(expenseNib, forCellReuseIdentifier: "ExpenseCell")
// Self-sizing cell
tableView.estimatedRowHeight = ExpenseTableViewCell.estimatedRowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.reloadData() // Bug on some versions of iOS, cells don't size correctly the first time
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateInsetsAndOffsets()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Reconfigure view and reload data on appear
configureView()
tableView.reloadData()
// Add realm notification
println("Filter: Adding realm notification")
realmNotificationToken = Realm().addNotificationBlock({ (notification, realm) -> Void in
println("Filter: RealmNotification received")
// Reset filtered transactions
self._filteredTransactions = nil
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Left)
// Reconfigure view
self.configureView()
})
dateRange = DateRange(startDate: self.dateRange.startDate, endDate: self.dateRange.endDate)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// Clear realm notification
println("Filter: Removing realm notification")
if let notificationToken = realmNotificationToken {
Realm().removeNotification(notificationToken)
}
realmNotificationToken = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Convenience functions
func configureView() {
// Configure view for filtered transactions
if isViewLoaded() {
let totalAmount: Double = filteredTransactions.sum("amount")
let totalEarnings: Double = filteredTransactions.filter("amount > 0").sum("amount")
let totalExpenses: Double = filteredTransactions.filter("amount < 0").sum("amount")
totalAmountLabel.text = numberFormatter.stringFromNumber(NSNumber(double: totalAmount))
earningsLabel.text = numberFormatter.stringFromNumber(NSNumber(double: totalEarnings))
expensesLabel.text = numberFormatter.stringFromNumber(NSNumber(double: totalExpenses))
// Date range label
updateDateRangeLabel()
}
}
func updateInsetsAndOffsets() {
let headerViewHeight = headerView.frame.height
let insets = UIEdgeInsets(top: headerViewHeight, left: 0, bottom: 0, right: 0)
tableView.scrollIndicatorInsets = insets
tableView.contentInset = insets
// Adjust offset once only (initial load)
if !adjustedTableViewOffset {
tableView.contentOffset = CGPoint(x: 0, y: -headerViewHeight)
adjustedTableViewOffset = true
}
}
func updateDateRangeLabel() {
let startDateString = dateRange.startDate.toStringWithDateStyle(.MediumStyle, andTimeStyle: nil)
let endDateString = dateRange.endDate.toStringWithDateStyle(.MediumStyle, andTimeStyle: nil)
dateRangeLabel.text = "\(startDateString) - \(endDateString)"
}
func updateFilter() {
// Set predicate
transactionsPredicate = NSPredicate(format: "date => %@ && date <= %@", dateRange.startDate, dateRange.endDate)
// Update label
updateDateRangeLabel()
}
// MARK: Actions
@IBAction func didPressRange(sender: AnyObject) {
performSegueWithIdentifier("showRange", sender: sender)
}
// MARK: Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showTransaction" {
if let destinationVC = (segue.destinationViewController as? UINavigationController)?.topViewController as? UpdateTransactionViewController {
destinationVC.account = account
if let indexPath = tableView.indexPathForSelectedRow() {
destinationVC.transaction = filteredTransactions[indexPath.row]
}
}
} else if segue.identifier == "showRange" {
if let destinationVC = (segue.destinationViewController as? UINavigationController)?.topViewController as? RangeViewController {
destinationVC.delegate = self
destinationVC.dateRange = dateRange
}
}
}
}
// MARK: - Table view data source
extension FilterViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredTransactions.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ExpenseCell") as! ExpenseTableViewCell
let currentTransaction = filteredTransactions[indexPath.row]
cell.expenseTitleLabel.text = currentTransaction.name
cell.amountLabel.text = numberFormatter.stringFromNumber(NSNumber(double: currentTransaction.amount))
cell.dateLabel.text = currentTransaction.date.toStringWithDateStyle(.MediumStyle, andTimeStyle: .ShortStyle)
cell.updateAmountLabelTextColorForAmount(currentTransaction.amount)
return cell
}
// Editing style
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let transaction = filteredTransactions[indexPath.row]
let realm = Realm()
realm.write({ () -> Void in
realm.delete(transaction)
})
} 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.
}
}
}
// MARK: - Table view delegate
extension FilterViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("showTransaction", sender: nil)
}
}
// MARK: - Range view controller delegate
extension FilterViewController: RangeViewControllerDelegate {
func rangeViewControllerDidFinish(controller: RangeViewController) {
dateRange = DateRange(startDate: controller.dateRange.startDate.startOf(.Day), endDate: controller.dateRange.endDate.endOf(.Day))
println("Filter: \(dateRange.endDate)")
}
}
|
gpl-2.0
|
dad88587ba2ab6515705a52fafc29aeb
| 36.435146 | 184 | 0.656047 | 5.824219 | false | false | false | false |
tensorflow/examples
|
lite/examples/pose_estimation/ios/PoseEstimation/ML/Models/PoseNet.swift
|
1
|
10860
|
// Copyright 2021 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import Accelerate
import Foundation
import TensorFlowLite
/// A wrapper to run pose estimation using the PoseNet model.
final class PoseNet: PoseEstimator {
// MARK: - Private Properties
/// TensorFlow Lite `Interpreter` object for performing inference on a given model.
private var interpreter: Interpreter
/// TensorFlow lite `Tensor` of model input and output.
private var inputTensor: Tensor
private var heatsTensor: Tensor
private var offsetsTensor: Tensor
private let imageMean: Float = 127.5
private let imageStd: Float = 127.5
/// Model files
private let posenetFile = FileInfo(name: "posenet", ext: "tflite")
// MARK: - Initialization
/// A failable initializer for `ModelDataHandler`. A new instance is created if the model is
/// successfully loaded from the app's main bundle. Default `threadCount` is 2.
init(threadCount: Int, delegate: Delegates) throws {
// Construct the path to the model file.
guard
let modelPath = Bundle.main.path(forResource: posenetFile.name, ofType: posenetFile.ext)
else {
fatalError("Failed to load the model file.")
}
// Specify the options for the `Interpreter`.
var options = Interpreter.Options()
options.threadCount = threadCount
// Specify the delegates for the `Interpreter`.
var delegates: [Delegate]?
switch delegate {
case .gpu:
delegates = [MetalDelegate()]
case .npu:
if let coreMLDelegate = CoreMLDelegate() {
delegates = [coreMLDelegate]
} else {
delegates = nil
}
case .cpu:
delegates = nil
}
// Create the `Interpreter`.
interpreter = try Interpreter(modelPath: modelPath, options: options, delegates: delegates)
// Initialize input and output `Tensor`s.
// Allocate memory for the model's input `Tensor`s.
try interpreter.allocateTensors()
// Get allocated input and output `Tensor`s.
inputTensor = try interpreter.input(at: 0)
heatsTensor = try interpreter.output(at: 0)
offsetsTensor = try interpreter.output(at: 1)
}
/// Runs PoseEstimation model with given image with given source area to destination area.
///
/// - Parameters:
/// - on: Input image to run the model.
/// - from: Range of input image to run the model.
/// - to: Size of view to render the result.
/// - Returns: Result of the inference and the times consumed in every steps.
func estimateSinglePose(on pixelBuffer: CVPixelBuffer) throws -> (Person, Times) {
// Start times of each process.
let preprocessingStartTime: Date
let inferenceStartTime: Date
let postprocessingStartTime: Date
// Processing times in seconds.
let preprocessingTime: TimeInterval
let inferenceTime: TimeInterval
let postprocessingTime: TimeInterval
preprocessingStartTime = Date()
guard let data = preprocess(pixelBuffer) else {
os_log("Preprocessing failed.", type: .error)
throw PoseEstimationError.preprocessingFailed
}
preprocessingTime = Date().timeIntervalSince(preprocessingStartTime)
// Run inference with the TFLite model.
inferenceStartTime = Date()
do {
try interpreter.copy(data, toInputAt: 0)
// Run inference by invoking the `Interpreter`.
try interpreter.invoke()
// Get the output `Tensor` to process the inference results.
heatsTensor = try interpreter.output(at: 0)
offsetsTensor = try interpreter.output(at: 1)
} catch let error {
os_log(
"Failed to invoke the interpreter with error: %s", type: .error,
error.localizedDescription)
throw PoseEstimationError.inferenceFailed
}
inferenceTime = Date().timeIntervalSince(inferenceStartTime)
postprocessingStartTime = Date()
guard let result = postprocess(to: pixelBuffer.size) else {
os_log("Postprocessing failed.", type: .error)
throw PoseEstimationError.postProcessingFailed
}
postprocessingTime = Date().timeIntervalSince(postprocessingStartTime)
let times = Times(
preprocessing: preprocessingTime,
inference: inferenceTime,
postprocessing: postprocessingTime)
return (result, times)
}
// MARK: - Private functions to run model
/// Preprocesses given rectangle image to be `Data` of desired size by cropping and resizing it.
///
/// - Parameters:
/// - of: Input image to crop and resize.
/// - from: Target area to be cropped and resized.
/// - Returns: The cropped and resized image. `nil` if it can not be processed.
private func preprocess(_ pixelBuffer: CVPixelBuffer) -> Data? {
let sourcePixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer)
assert(
sourcePixelFormat == kCVPixelFormatType_32BGRA
|| sourcePixelFormat == kCVPixelFormatType_32ARGB)
// Resize `targetSquare` of input image to `modelSize`.
let dimensions = inputTensor.shape.dimensions
let inputWidth = dimensions[1]
let inputHeight = dimensions[2]
let modelSize = CGSize(width: inputWidth, height: inputHeight)
guard let thumbnail = pixelBuffer.resized(to: modelSize) else {
return nil
}
// Remove the alpha component from the image buffer to get the initialized `Data`.
return thumbnail.rgbData(isModelQuantized: false, imageMean: imageMean, imageStd: imageStd)
}
/// Postprocesses output `Tensor`s to `Result` with size of view to render the result.
///
/// - Parameters:
/// - to: Size of view to be displayed.
/// - Returns: Postprocessed `Result`. `nil` if it can not be processed.
private func postprocess(to viewSize: CGSize) -> Person? {
// MARK: Formats output tensors
// Convert `Tensor` to `FlatArray`. As PoseEstimation is not quantized, convert them to Float
// type `FlatArray`.
let heats = FlatArray<Float32>(tensor: heatsTensor)
let offsets = FlatArray<Float32>(tensor: offsetsTensor)
let outputHeight = heats.dimensions[1]
let outputWidth = heats.dimensions[2]
let keyPointSize = heats.dimensions[3]
// MARK: Find position of each key point
// Finds the (row, col) locations of where the keypoints are most likely to be. The highest
// `heats[0, row, col, keypoint]` value, the more likely `keypoint` being located in (`row`,
// `col`).
let keypointPositions = (0..<keyPointSize).map { keypoint -> (Int, Int) in
var maxValue = heats[0, 0, 0, keypoint]
var maxRow = 0
var maxCol = 0
for row in 0..<outputHeight {
for col in 0..<outputWidth {
if heats[0, row, col, keypoint] > maxValue {
maxValue = heats[0, row, col, keypoint]
maxRow = row
maxCol = col
}
}
}
return (maxRow, maxCol)
}
// MARK: Calculates total confidence score
// Calculates total confidence score of each key position.
let totalScoreSum = keypointPositions.enumerated().reduce(0.0) { accumulator, elem -> Float32 in
accumulator + sigmoid(heats[0, elem.element.0, elem.element.1, elem.offset])
}
let totalScore = totalScoreSum / Float32(keyPointSize)
// MARK: Calculate key point position on model input
// Calculates `KeyPoint` coordination model input image with `offsets` adjustment.
let dimensions = inputTensor.shape.dimensions
let inputHeight = dimensions[1]
let inputWidth = dimensions[2]
let coords = keypointPositions.enumerated().map { index, elem -> (y: Float32, x: Float32) in
let (y, x) = elem
let yCoord =
Float32(y) / Float32(outputHeight - 1) * Float32(inputHeight)
+ offsets[0, y, x, index]
let xCoord =
Float32(x) / Float32(outputWidth - 1) * Float32(inputWidth)
+ offsets[0, y, x, index + keyPointSize]
return (y: yCoord, x: xCoord)
}
// MARK: Transform key point position and make lines
// Make `Result` from `keypointPosition'. Each point is adjusted to `ViewSize` to be drawn.
var result = Person(keyPoints: [], score: totalScore)
for (index, part) in BodyPart.allCases.enumerated() {
let x = CGFloat(coords[index].x) * viewSize.width / CGFloat(inputWidth)
let y = CGFloat(coords[index].y) * viewSize.height / CGFloat(inputHeight)
let keyPoint = KeyPoint(bodyPart: part, coordinate: CGPoint(x: x, y: y))
result.keyPoints.append(keyPoint)
}
return result
}
/// Run inference with given `Data`
///
/// Parameter `from`: `Data` of input image to run model.
private func inference(from data: Data) {
// Copy the initialized `Data` to the input `Tensor`.
do {
try interpreter.copy(data, toInputAt: 0)
// Run inference by invoking the `Interpreter`.
try interpreter.invoke()
// Get the output `Tensor` to process the inference results.
heatsTensor = try interpreter.output(at: 0)
offsetsTensor = try interpreter.output(at: 1)
} catch let error {
os_log(
"Failed to invoke the interpreter with error: %s", type: .error,
error.localizedDescription)
return
}
}
/// Returns value within [0,1].
private func sigmoid(_ x: Float32) -> Float32 {
return (1.0 / (1.0 + exp(-x)))
}
}
// MARK: - Wrappers
/// Struct for handling multidimension `Data` in flat `Array`.
fileprivate struct FlatArray<Element: AdditiveArithmetic> {
private var array: [Element]
var dimensions: [Int]
init(tensor: Tensor) {
dimensions = tensor.shape.dimensions
array = tensor.data.toArray(type: Element.self)
}
private func flatIndex(_ indices: [Int]) -> Int {
guard indices.count == dimensions.count else {
fatalError("Invalid index: got \(indices.count) index(es) for \(dimensions.count) index(es).")
}
var result = 0
for (dimension, index) in zip(dimensions, indices) {
guard dimension > index else {
fatalError("Invalid index: \(index) is bigger than \(dimension)")
}
result = dimension * result + index
}
return result
}
subscript(_ index: Int...) -> Element {
get {
return array[flatIndex(index)]
}
set(newValue) {
array[flatIndex(index)] = newValue
}
}
}
|
apache-2.0
|
abd5dd753432effdbd0c48c7a5086735
| 35.2 | 100 | 0.670994 | 4.210934 | false | false | false | false |
Jnosh/swift
|
test/decl/func/functions.swift
|
6
|
8932
|
// RUN: %target-typecheck-verify-swift
infix operator ====
infix operator <<<<
infix operator <><>
// <rdar://problem/13782566>
// Check that func op<T>() parses without a space between the name and the
// generic parameter list.
func ====<T>(x: T, y: T) {}
func <<<<<T>(x: T, y: T) {}
func <><><T>(x: T, y: T) {}
//===--- Check that we recover when the parameter tuple is missing.
func recover_missing_parameter_tuple_1 { // expected-error {{expected '(' in argument list of function declaration}} {{39-39=()}}
}
func recover_missing_parameter_tuple_1a // expected-error {{expected '(' in argument list of function declaration}} {{40-40=()}}
{
}
func recover_missing_parameter_tuple_2<T> { // expected-error {{expected '(' in argument list of function declaration}} {{42-42=()}} expected-error {{generic parameter 'T' is not used in function signature}}
}
func recover_missing_parameter_tuple_3 -> Int { // expected-error {{expected '(' in argument list of function declaration}} {{39-39=()}}
}
func recover_missing_parameter_tuple_4<T> -> Int { // expected-error {{expected '(' in argument list of function declaration}} {{42-42=()}} expected-error {{generic parameter 'T' is not used in function signature}}
}
//===--- Check that we recover when the function return type is missing.
// Note: Don't move braces to a different line here.
func recover_missing_return_type_1() -> // expected-error {{expected type for function result}}
{
}
func recover_missing_return_type_2() -> // expected-error {{expected type for function result}} expected-error{{expected '{' in body of function declaration}}
// Note: Don't move braces to a different line here.
func recover_missing_return_type_3 -> // expected-error {{expected '(' in argument list of function declaration}} {{35-35=()}} expected-error {{expected type for function result}}
{
}
//===--- Check that we recover if ':' was used instead of '->' to specify the return type.
func recover_colon_arrow_1() : Int { } // expected-error {{expected '->' after function parameter tuple}} {{30-31=->}}
func recover_colon_arrow_2() : { } // expected-error {{expected '->' after function parameter tuple}} {{30-31=->}} expected-error {{expected type for function result}}
func recover_colon_arrow_3 : Int { } // expected-error {{expected '->' after function parameter tuple}} {{28-29=->}} expected-error {{expected '(' in argument list of function declaration}}
func recover_colon_arrow_4 : { } // expected-error {{expected '->' after function parameter tuple}} {{28-29=->}} expected-error {{expected '(' in argument list of function declaration}} expected-error {{expected type for function result}}
func recover_colon_arrow_5():Int { } // expected-error {{expected '->' after function parameter tuple}} {{29-30= -> }}
func recover_colon_arrow_6(): Int { } // expected-error {{expected '->' after function parameter tuple}} {{29-30= ->}}
func recover_colon_arrow_7() :Int { } // expected-error {{expected '->' after function parameter tuple}} {{30-31=-> }}
//===--- Check that we recover if the function does not have a body, but the
//===--- context requires the function to have a body.
func recover_missing_body_1() // expected-error {{expected '{' in body of function declaration}}
func recover_missing_body_2() // expected-error {{expected '{' in body of function declaration}}
-> Int
// Ensure that we don't skip over the 'func g' over to the right paren in
// function g, while recovering from parse error in f() parameter tuple. We
// should produce the error about missing right paren.
//
// FIXME: The errors are awful. We should produce just the error about paren.
func f_recover_missing_tuple_paren(_ a: Int // expected-note {{to match this opening '('}} expected-error{{expected '{' in body of function declaration}} expected-error {{expected ')' in parameter}}
func g_recover_missing_tuple_paren(_ b: Int) {
}
//===--- Parse errors.
func parseError1a(_ a: ) {} // expected-error {{expected parameter type following ':'}} {{23-23= <#type#>}}
func parseError1b(_ a: // expected-error {{expected parameter type following ':'}} {{23-23= <#type#>}}
) {}
func parseError2(_ a: Int, b: ) {} // expected-error {{expected parameter type following ':'}} {{30-30= <#type#>}}
func parseError3(_ a: unknown_type, b: ) {} // expected-error {{use of undeclared type 'unknown_type'}} expected-error {{expected parameter type following ':'}} {{39-39= <#type#>}}
func parseError4(_ a: , b: ) {} // expected-error 2{{expected parameter type following ':'}}
func parseError5(_ a: b: ) {} // expected-error {{use of undeclared type 'b'}} expected-error {{expected ',' separator}} {{24-24=,}} expected-error {{expected parameter name followed by ':'}}
func parseError6(_ a: unknown_type, b: ) {} // expected-error {{use of undeclared type 'unknown_type'}} expected-error {{expected parameter type following ':'}} {{39-39= <#type#>}}
func parseError7(_ a: Int, goo b: unknown_type) {} // expected-error {{use of undeclared type 'unknown_type'}}
public func foo(_ a: Bool = true) -> (b: Bar, c: Bar) {} // expected-error {{use of undeclared type 'Bar'}}
func parenPatternInArg((a): Int) -> Int { // expected-error {{expected parameter name followed by ':'}}
return a // expected-error {{use of unresolved identifier 'a'}}
}
parenPatternInArg(0) // expected-error {{argument passed to call that takes no arguments}}
var nullaryClosure: (Int) -> Int = {_ in 0}
_ = nullaryClosure(0)
// rdar://16737322 - This argument is an unnamed argument that has a labeled
// tuple type as the type. Because the labels are in the type, they are not
// parameter labels, and they are thus not in scope in the body of the function.
// expected-error@+1{{unnamed parameters must be written}} {{27-27=_: }}
func destructureArgument( (result: Int, error: Bool) ) -> Int {
return result
}
// The former is the same as this:
func destructureArgument2(_ a: (result: Int, error: Bool) ) -> Int {
return result // expected-error {{use of unresolved identifier 'result'}}
}
class ClassWithObjCMethod {
@objc
func someMethod(_ x : Int) {}
}
func testObjCMethodCurry(_ a : ClassWithObjCMethod) -> (Int) -> () {
return a.someMethod
}
// We used to crash on this.
func rdar16786220(inout let c: Int) -> () { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{25-29=}}
// expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}}{{19-24=}}{{32-32=inout }}
c = 42
}
// <rdar://problem/17763388> ambiguous operator emits same candidate multiple times
infix operator !!!
func !!!<T>(lhs: Array<T>, rhs: Array<T>) -> Bool { return false }
func !!!<T>(lhs: UnsafePointer<T>, rhs: UnsafePointer<T>) -> Bool { return false }
_ = [1] !!! [1] // unambiguously picking the array overload.
// <rdar://problem/16786168> Functions currently permit 'var inout' parameters
func var_inout_error(inout var x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{28-32=}}
// expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{22-27=}}{{36-36=inout }}
// Unnamed parameters require the name "_":
func unnamed(Int) { } // expected-error{{unnamed parameters must be written with the empty name '_'}}{{14-14=_: }}
func typeAttrBeforeParamDecl(@convention(c) _: () -> Void) {} // expected-error{{attribute can only be applied to types, not declarations}}
// FIXME: Bad diagnostics
func bareTypeWithAttr(@convention(c) () -> Void) {} // expected-error{{attribute can only be applied to types, not declarations}}
// expected-error @-1 {{unnamed parameters must be written with the empty name '_'}} {{38-38=_: }}
// Test fixits on curried functions.
func testCurryFixits() {
func f1(_ x: Int)(y: Int) {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{19-21=, }}
func f1a(_ x: Int, y: Int) {}
func f2(_ x: Int)(y: Int)(z: Int) {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{19-21=, }} {{27-29=, }}
func f2a(_ x: Int, y: Int, z: Int) {}
func f3(_ x: Int)() {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{19-21=}}
func f3a(_ x: Int) {}
func f4()(x: Int) {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{11-13=}}
func f4a(_ x: Int) {}
func f5(_ x: Int)()(y: Int) {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{19-21=}} {{21-23=, }}
func f5a(_ x: Int, y: Int) {}
}
// Bogus diagnostic talking about a 'var' where there is none
func invalidInOutParam(x: inout XYZ) {}
// expected-error@-1{{use of undeclared type 'XYZ'}}
|
apache-2.0
|
ca44331b392cc89139b5b38946e095c3
| 51.541176 | 244 | 0.675101 | 3.74979 | false | false | false | false |
priyax/TextToSpeech
|
textToTableViewController/textToTableViewController/ReadRecipesController.swift
|
1
|
12445
|
//
// ReadRecipes
// textToTableViewController
//
// Created by Priya Xavier on 10/3/16.
// Copyright © 2016 Guild/SA. All rights reserved.
//
import UIKit
import AVFoundation
class ReadRecipesController: UIViewController, UITableViewDelegate, UITableViewDataSource,AVSpeechSynthesizerDelegate, UITextViewDelegate {
var recipeToLoad: RecipeData?
@IBOutlet weak var saveBtn: UIButton!
struct myRecipeStruct {
var recipeName: String?
var recipePart: RecipePart
}
enum RecipePart {
case title
case ingredients
case instructions
}
var myRecipeStructArray = [myRecipeStruct]()
var recipeArrayFromSelectedRow = [myRecipeStruct]()
var startReadingIndex = 0
var rowIsSelected = false
@IBOutlet weak var tableView: UITableView!
var synthesizer = AVSpeechSynthesizer()
@IBOutlet weak var startReading: UIButton!
@IBOutlet weak var pauseReading: UIButton!
@IBOutlet weak var editBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Convert recipe data from a RecipeData Object to an array of myRecipeStruct type data
if let recipe = recipeToLoad {
if let title = recipe.title {
myRecipeStructArray.append(myRecipeStruct(recipeName: title, recipePart: RecipePart.title))
}
if let ingredients = recipe.ingredients {
for i in ingredients {
myRecipeStructArray.append(myRecipeStruct(recipeName: i, recipePart: RecipePart.ingredients))
}
}
if let instructions = recipe.instructions {
for i in instructions {
//Check if string in empty
if !i.isEmpty {
// myRecipeArray.append("\(i).")
myRecipeStructArray.append(myRecipeStruct(recipeName: i, recipePart: RecipePart.instructions))
}
}
}
}
//Make resizable cell width
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 70
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Action Buttons
@IBAction func startReading(_ sender: UIButton) {
if synthesizer.isPaused == true && rowIsSelected == false {
// start reading after being paused
synthesizer.continueSpeaking()
}
else if rowIsSelected == true {
// start reading from selected row whether synthesiser was paused or not
for recipeStruct in myRecipeStructArray[startReadingIndex...myRecipeStructArray.count - 1 ] {
callSpeechSynthesizer(step: recipeStruct.recipeName!)
rowIsSelected = false
}
} else {
//start reading from beginning
for recipeStruct in myRecipeStructArray {
callSpeechSynthesizer(step: recipeStruct.recipeName!)
}
}
}
@IBAction func pauseReading(_ sender: UIButton) {
if synthesizer.isSpeaking {
synthesizer.pauseSpeaking(at: AVSpeechBoundary.immediate)
// print("Is PAUSED")
}
}
@IBAction func stopReading(_ sender: UIButton) {
synthesizer.stopSpeaking(at: AVSpeechBoundary.word)
startReadingIndex = 0
rowIsSelected = false
}
@IBAction func editRecipe(_ sender: UIButton) {
editBtn.isEnabled = false
//print("Number of visible cells = \(tableView.visibleCells.count)")
for j in 0...tableView.visibleCells.count - 1 {
// print("Count j = \(j)")
let cell = tableView.visibleCells[j] as! RecipeTableViewCell
cell.recipeTextView.isUserInteractionEnabled = true
// cell.recipeTextView.isEditable = true
}
}
@IBAction func backBtn(_ sender: UIButton) {
synthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
navigationController!.popViewController(animated: true)
}
//Speech Synthesizer
func callSpeechSynthesizer(step: String) {
let utterance = AVSpeechUtterance(string: step)
// print(utterance)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
utterance.rate = 0.45
utterance.pitchMultiplier = 1
// print(utterance.voice?.language)
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
do{
try AVAudioSession.sharedInstance().setActive(true)
}catch{
}
}catch{
}
synthesizer.speak(utterance)
}
@IBAction func saveBtn(_ sender: UIButton) {
var titleToSave = String()
var ingredientsToSave = [String]()
var instructionsToSave = [String]()
// print("TableView Section = \(tableView.numberOfRows(inSection: 0))")
for i in myRecipeStructArray {
switch i.recipePart {
case .title: if let t = i.recipeName {
titleToSave = t
// print(t)
}
case .ingredients : if let r = i.recipeName {
ingredientsToSave.append(r)
// print(r)
}
case .instructions: if let s = i.recipeName {
instructionsToSave.append(s)
//print(s)
}
}
}
recipeToLoad?.title = titleToSave
recipeToLoad?.ingredients = ingredientsToSave
recipeToLoad?.instructions = instructionsToSave
if (BackendlessManager.sharedInstance.isUserLoggedIn()) {
saveBtn.isEnabled = false
BackendlessManager.sharedInstance.saveRecipe(recipeData: recipeToLoad!,
completion: {
self.saveBtn.isEnabled = true
self.synthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
// print("Segue to Table of Saved Recipes after data is saved in BE")
self.performSegue(withIdentifier: "unwindToSavedRecipes", sender: self)
}, error: {
// It was NOT saved to the database! - tell the user and DON'T call performSegue.
let alertController = UIAlertController(title: "Save Error",
message: "Oops! We couldn't save your Recipe at this time.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
self.saveBtn.isEnabled = true
})
} else {
// If not logged in then user is prompted to register or sign in
// Create an alert that unwinds to register/log in page with recipe to save
let alertController = UIAlertController(title: "Sign In to save this recipe", message: "Do you want to continue to save this recipe?", preferredStyle: .actionSheet)
let okAction = UIAlertAction(title: "OK", style: .default,
handler: {action in
self.saveRecipeToArchiver()
self.performSegue(withIdentifier: "unwindToWelcomeViewController", sender: self)})
alertController.addAction(okAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
// Save to NSKeyed Archiver
func saveRecipeToArchiver() {
if let recipeToLoad = recipeToLoad {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(recipeToLoad, toFile: RecipeData.ArchiverUrl.path)
if !isSuccessfulSave {
print("Failed to archive recipe")
}
else {print("Saved recipe to archive")}
}
}
// From UITableViewDataSource protocol.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// From UITableViewDataSource protocol.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myRecipeStructArray.count
}
// From UITableViewDataSource protocol.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "recipeTableViewCell", for: indexPath) as! RecipeTableViewCell
let index = (indexPath as IndexPath).row
cell.index = index
cell.recipeTextView.text = myRecipeStructArray[index].recipeName
// print("Row Number = \((indexPath as IndexPath).row)")
// print("\(cell.recipeTextView.text)")
cell.recipeTextView.isUserInteractionEnabled = false
cell.recipeTextView.delegate = self
return cell
}
// From UITableViewDelegate protocol.
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return true
}
// From UITableViewDelegate protocol.
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
}
// From UITableViewDelegate protocol.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.contentView.backgroundColor = UIColor.brown
//change start of reading
if editBtn.isEnabled == true {
synthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
startReadingIndex = indexPath.row
// print("start reading index = \(startReadingIndex)")
rowIsSelected = true
}
}
// Method gets called when the keyboard return key pressed
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String)-> Bool {
if(text == "\n")
{
view.endEditing(true)
return false
}
else
{
return true
}
}
//Hide Keyboard when user touches outside keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
//Presses return key to exit keyboard
func textFieldShouldReturn(_ textView: UITextView) -> Bool {
textView.resignFirstResponder()
return (true)
}
//Update text view after editing
func textViewDidEndEditing(_ textView: UITextView) {
// print("Number of rows = \(tableView.numberOfRows(inSection: 0))")
// print("Number of visible rows = \(tableView.visibleCells.count)")
for cell in tableView.visibleCells {
if let cell = cell as? RecipeTableViewCell {
myRecipeStructArray[cell.index!].recipeName = cell.recipeTextView.text
// cell.recipeTextView.isEditable = false
cell.recipeTextView.isUserInteractionEnabled = false
}
}
editBtn.isEnabled = true
}
}
|
mit
|
8497e37b67f9a14733ab50fdd65aae3c
| 32.184 | 172 | 0.562842 | 5.806813 | false | false | false | false |
petester42/RxSwift
|
RxSwift/Disposables/SerialDisposable.swift
|
8
|
2238
|
//
// SerialDisposable.swift
// Rx
//
// Created by Krunoslav Zaher on 3/12/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*/
public class SerialDisposable : DisposeBase, Cancelable {
private var _lock = SpinLock()
// state
private var _current = nil as Disposable?
private var _disposed = false
/**
- returns: Was resource disposed.
*/
public var disposed: Bool {
get {
return _disposed
}
}
/**
Initializes a new instance of the `SerialDisposable`.
*/
override public init() {
super.init()
}
/**
Gets or sets the underlying disposable.
Assigning this property disposes the previous disposable object.
If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object.
*/
public var disposable: Disposable {
get {
return _lock.calculateLocked {
return self.disposable
}
}
set (newDisposable) {
let disposable: Disposable? = _lock.calculateLocked {
if _disposed {
return newDisposable
}
else {
let toDispose = _current
_current = newDisposable
return toDispose
}
}
if let disposable = disposable {
disposable.dispose()
}
}
}
/**
Disposes the underlying disposable as well as all future replacements.
*/
public func dispose() {
_dispose()?.dispose()
}
private func _dispose() -> Disposable? {
_lock.lock(); defer { _lock.unlock() }
if _disposed {
return nil
}
else {
_disposed = true
let current = _current
_current = nil
return current
}
}
}
|
mit
|
c90afb7438d4105f3d2d0e15d9ca8ec0
| 24.735632 | 192 | 0.550492 | 5.432039 | false | false | false | false |
LegACy99/Project-Tube-Swift
|
Project Tube/src/game/TubeSegment.swift
|
1
|
5989
|
//
// TubeSegment.swift
// Project Tube
//
// Created by LegACy on 7/7/14.
// Copyright (c) 2014 Raka Mahesa. All rights reserved.
//
import SceneKit;
class TubeSegment {
init(tiles: Int[], startOrbit: SCNVector3, endOrbit: SCNVector3, startY: Float, endY: Float, startX: Float, endX: Float) {
//Save
m_EndAngleY = endY;
m_EndAngleX = endX;
m_StartAngleY = startY;
m_StartAngleX = startX;
m_StartOrbit = startOrbit;
m_EndOrbit = endOrbit;
//Create nodes
m_Segment = SCNNode();
m_SegmentOrbit = SCNNode();
m_SegmentOrbit.addChildNode(m_Segment);
//For each tiles
let Degree: Float = 360.0 / Float(tiles.count);
for var i = 0; i < tiles.count; i++ {
//If not empty
if (tiles[i] > 0) {
//Create floor
let Floor = SCNNode();
Floor.position = SCNVector3(x: 2, y: 0, z: 0);
Floor.geometry = SCNBox(width: 0.25, height: 1.2, length: CGFloat(SEGMENT_TILE_LENGTH), chamferRadius: 0.02);
//Create material for floor
Floor.geometry.firstMaterial = SCNMaterial();
Floor.geometry.firstMaterial.diffuse.contents = UIColor(red: 1, green: 0, blue: 0, alpha: 1);
Floor.geometry.firstMaterial.locksAmbientWithDiffuse = true;
//Create slice
let Slice = SCNNode();
Slice.rotation = SCNVector4(x: 0, y: 0, z: 1, w: Float(i) * Degree / 180.0 * Float(M_PI));
Slice.addChildNode(Floor);
//Add to segment
m_Segment.addChildNode(Slice);
}
}
//Set angle
let Opposite = m_EndAngleY < m_StartAngleY || m_EndAngleX < m_StartAngleX;
let AngleY = ((m_StartAngleY + m_EndAngleY) / 2.0) / 180.0 * Float(M_PI);
let AngleX = ((m_StartAngleX + m_EndAngleX) / 2.0) / 180.0 * Float(M_PI);
let XRotation = SCNMatrix4MakeRotation(AngleX, -1, 0, 0);
let YRotation = SCNMatrix4MakeRotation(AngleY, 0, 1, 0);
m_SegmentOrbit.transform = SCNMatrix4Mult(XRotation, YRotation);
//Set position
var OrbitX = (m_StartOrbit.x + m_EndOrbit.x) / 2.0;
var OrbitY = (m_StartOrbit.y + m_EndOrbit.y) / 2.0;
var OrbitZ = (m_StartOrbit.z + m_EndOrbit.z) / 2.0;
m_SegmentOrbit.position = SCNVector3(x: OrbitX, y: OrbitY, z: OrbitZ);
m_Segment.position = SCNVector3(x: Opposite ? -SEGMENT_ORBIT_DISTANCE : SEGMENT_ORBIT_DISTANCE, y: 0, z: 0);
if (m_StartAngleX != m_EndAngleX) {
//
m_Segment.position = SCNVector3(x: 0, y: Opposite ? -SEGMENT_ORBIT_DISTANCE : SEGMENT_ORBIT_DISTANCE, z: 0);
}
}
//More specific class constructors
class func create(tiles: Int[], orbit: SCNVector3, angleY: Float, startX: Float, endX: Float) -> TubeSegment {
return TubeSegment(tiles: tiles, startOrbit: orbit, endOrbit: orbit, startY: angleY, endY: angleY, startX: startX, endX: endX); }
class func create(tiles: Int[], orbit: SCNVector3, angleX: Float, startY: Float, endY: Float) -> TubeSegment {
return TubeSegment(tiles: tiles, startOrbit: orbit, endOrbit: orbit, startY: startY, endY: endY, startX: angleX, endX: angleX); }
class func create(tiles: Int[], startOrbit: SCNVector3, endOrbit: SCNVector3, angleY: Float, angleX: Float) -> TubeSegment {
return TubeSegment(tiles: tiles, startOrbit: startOrbit, endOrbit: endOrbit, startY: angleY, endY: angleY, startX: angleX, endX: angleX); }
//Accessors
func getNode() -> SCNNode { return m_SegmentOrbit; }
func getEndOrbit() -> SCNVector3 { return m_EndOrbit; }
func getStartOrbit() -> SCNVector3 { return m_StartOrbit; }
func getStartAngleY() -> Float { return m_StartAngleY; }
func getStartAngleX() -> Float { return m_StartAngleX; }
func getEndAngleY() -> Float { return m_EndAngleY; }
func getEndAngleX() -> Float { return m_EndAngleX; }
func getIntermediateAngle(factor: Float) -> SCNVector3 {
//Calculate angle
let AngleY = m_StartAngleY + (factor * (m_EndAngleY - m_StartAngleY));
let AngleX = m_StartAngleX + (factor * (m_EndAngleX - m_StartAngleX));
//Return
return SCNVector3(x: AngleX, y: AngleY, z: 0);
}
func getIntermediatePosition(factor: Float) -> SCNVector3 {
//Initialize
var Result = SCNVector3(x: 0, y: 0, z: 0);
let Angle = getIntermediateAngle(factor);
//If angled
if (m_StartAngleY != m_EndAngleY || m_StartAngleX != m_EndAngleX) {
//Calculate position
let RadianX = Angle.x / 180.0 * Float(M_PI);
let RadianY = Angle.y / 180.0 * Float(M_PI);
let X = m_StartOrbit.x + (cosf(RadianY) * m_Segment.position.x);
let Y = m_StartOrbit.y + (cosf(RadianX) * m_Segment.position.y);
//let Z = m_StartOrbit.z + (-sinf(RadianY) * m_Segment.position.x); //Horizontal
let Z = m_StartOrbit.z + (-sinf(RadianX) * m_Segment.position.y); //Vertical
Result = SCNVector3(x: X, y: Y, z: Z);
} else {
//Get intermediate orbit
let OrbitX = m_StartOrbit.x + ((m_EndOrbit.x - m_StartOrbit.x) * factor);
let OrbitY = m_StartOrbit.y + ((m_EndOrbit.y - m_StartOrbit.y) * factor);
let OrbitZ = m_StartOrbit.z + ((m_EndOrbit.z - m_StartOrbit.z) * factor);
//Calculate position
let Radian = Angle.y / 180.0 * Float(M_PI);
let X = OrbitX + (cosf(Radian) * SEGMENT_ORBIT_DISTANCE);
let Z = OrbitZ + (-sinf(Radian) * SEGMENT_ORBIT_DISTANCE);
Result = SCNVector3(x: X, y: OrbitY, z: Z);
}
//Return
return Result;
}
func getFlippedOrbit(orbit: SCNVector3) -> SCNVector3 {
//Calculate
let Final = getIntermediatePosition(1);
let X = orbit.x + ((Final.x - orbit.x) * 2);
let Y = orbit.y + ((Final.y - orbit.y) * 2);
let Z = orbit.z + ((Final.z - orbit.z) * 2);
//Return
return SCNVector3(x: X, y: Y, z: Z);
}
func rotate(angle: Float) {
//Rotate
m_Segment.rotation = SCNVector4(x: 0, y: 0, z: 1, w: angle);
}
//Data
var m_EndAngleY: Float;
var m_EndAngleX: Float;
var m_StartAngleY: Float;
var m_StartAngleX: Float;
var m_StartOrbit: SCNVector3;
var m_EndOrbit: SCNVector3;
//Nodes
var m_Segment: SCNNode;
var m_SegmentOrbit: SCNNode;
}
//Public constants
let SEGMENT_TILE_LENGTH: Float = 2.2;
let SEGMENT_ORBIT_DISTANCE: Float = 10;
|
mit
|
9c53e7d782efe6d1f2d990b18e4db8cd
| 36.198758 | 141 | 0.655535 | 2.718566 | false | false | false | false |
squarefrog/dailydesktop
|
DailyDesktopTests/Networking/BingProviderTests.swift
|
1
|
9099
|
// Copyright © 2016 Paul Williamson. All rights reserved.
import XCTest
@testable import DailyDesktop
class BingProviderTests: XCTestCase {
var baseURL: URL!
var fullURL: URL!
override func setUp() {
super.setUp()
var string = "https://www.bing.com/HPImageArchive.aspx?format=js"
baseURL = URL(string: string)!
let mkt = NSLocale.current.iso3166code
string.append("&idx=0&n=1&mkt=\(mkt)")
fullURL = URL(string: string)!
}
func test_BingProvider_CanBeInstantiatedWithASessionConfiguration() {
// Given
let session = URLSession.shared
// When
let provider = BingProvider(session: session)
// Then
XCTAssertEqual(provider.session, session)
}
func test_BingProvider_ShouldHaveABaseURL() {
// Given
let provider = BingProvider(session: URLSession.shared)
// When
let baseURL = provider.baseURL
// Then
XCTAssertEqual(baseURL.absoluteString, "https://www.bing.com/HPImageArchive.aspx?format=js")
}
func test_BingProvider_WhenFetchingLatestImage_UsesCorrectURL() {
// Given
let session = FakeSession()
XCTAssertNil(session.requestedURL)
let provider = BingProvider(session: session)
// When
provider.fetchLatestImage { _ in }
// Then
XCTAssertEqual(session.requestedURL, fullURL)
}
func test_BingProvider_WhenFetchingLatestImage_ReturnsData() {
// Given
let session = FakeSession()
session.response = HTTPURLResponse(url: fullURL, statusCode: 200, httpVersion: nil, headerFields: nil)
let jsonData = try! Fixture.bing.nsData()
session.data = jsonData
let provider = BingProvider(session: session)
var returnedData: Data?
let expectation = self.expectation(description: "Should call completion block")
// When
provider.fetchLatestImage { result in
switch result {
case .success(let data): returnedData = data
case .failure: XCTFail("Should not return failure result")
}
expectation.fulfill()
}
// Then
waitForExpectations(timeout: 1.0, handler: nil)
XCTAssertEqual(returnedData, jsonData as Data)
}
func test_BingProvider_WhenFetchingLatestImage_ShouldReturnError() {
// Given
let session = FakeSession()
let error = NSError(domain: "bing.tests", code: 404, userInfo: nil)
session.error = error
let provider = BingProvider(session: session)
var returnedError: BingProviderError?
let expectation = self.expectation(description: "Should pass error back")
// When
provider.fetchLatestImage { result in
switch result {
case .success: XCTFail("Should not return success result")
case .failure(let error): returnedError = error
}
expectation.fulfill()
}
// Then
waitForExpectations(timeout: 1.0, handler: nil)
XCTAssertEqual(returnedError, BingProviderError.networkError(error))
}
func test_BingProvider_WhenFetchingLatestImage_ShouldCreateHTTPError() {
// Given
let session = FakeSession()
session.response = HTTPURLResponse(url: fullURL, statusCode: 404, httpVersion: nil, headerFields: nil)
let provider = BingProvider(session: session)
var returnedError: BingProviderError?
let expectation = self.expectation(description: "Should pass error back")
// When
provider.fetchLatestImage { result in
switch result {
case .success: XCTFail("Should not return successful result")
case .failure(let error): returnedError = error
}
expectation.fulfill()
}
// Then
waitForExpectations(timeout: 1.0, handler: nil)
XCTAssertEqual(returnedError, BingProviderError.httpCode(404))
}
func test_BingProvider_WhenFetchingLatestImage_ShouldCreateEmptyResponseError() {
// Given
let session = FakeSession()
let provider = BingProvider(session: session)
var returnedError: BingProviderError?
let expectation = self.expectation(description: "Should pass error back")
// When
provider.fetchLatestImage { result in
switch result {
case .success: XCTFail("Should not return successful result")
case .failure(let error): returnedError = error
}
expectation.fulfill()
}
// Then
waitForExpectations(timeout: 1.0, handler: nil)
XCTAssertEqual(returnedError, BingProviderError.emptyResponse)
}
func test_BingProvider_WhenFetchingLatestImage_ShouldCreateEmptyDataError() {
// Given
let session = FakeSession()
session.response = HTTPURLResponse(url: fullURL, statusCode: 200, httpVersion: nil, headerFields: nil)
let provider = BingProvider(session: session)
var returnedError: BingProviderError?
let expectation = self.expectation(description: "Should pass error back")
// When
provider.fetchLatestImage { result in
switch result {
case .success: XCTFail("Should not return successful result")
case .failure(let error): returnedError = error
}
expectation.fulfill()
}
// Then
waitForExpectations(timeout: 1.0, handler: nil)
XCTAssertEqual(returnedError, BingProviderError.emptyData)
}
func test_BingProvider_WhenFetchingLatestImage_CallsResume() {
// Given
let session = FakeSession()
let provider = BingProvider(session: session)
// When
provider.fetchLatestImage { _ in }
// Then
guard let task = session.dataTask else { return XCTFail("Should have valid session data task") }
XCTAssertTrue(task.resumeCalled)
}
func test_BingProvider_ShouldAllowFetchingMultipleImages() {
// Given
let session = FakeSession()
XCTAssertNil(session.requestedURL)
let provider = BingProvider(session: session)
let urlString = fullURL.absoluteString.replacingOccurrences(of: "n=1", with: "n=3")
let imageURL = URL(string: urlString)!
// When
provider.fetchLatestImages(count: 3) { _ in }
// Then
XCTAssertEqual(session.requestedURL, imageURL)
}
func test_BingProvider_WhenDownloadingImage_UsesCorrectURL() {
// Given
let url = URL(string: "https://www.bing.com/image.jpg")!
let webUrl = URL(string: "https://www.bing.com")!
let model = ImageModel(date: Date(),
url: url,
description: "",
webPageURL: webUrl)
let session = FakeSession()
let provider = BingProvider(session: session)
// When
provider.download(image: model) { _ in }
// Then
XCTAssertEqual(session.requestedURL, model.url)
}
func test_BingProvider_WhenDownloadingImage_PassesData() {
// Given
let url = URL(string: "https://www.bing.com/image.jpg")!
let webUrl = URL(string: "https://www.bing.com")!
let model = ImageModel(date: Date(),
url: url,
description: "",
webPageURL: webUrl)
let session = FakeSession()
session.response = HTTPURLResponse(url: fullURL, statusCode: 200, httpVersion: nil, headerFields: nil)
let data = Data()
session.data = data
let provider = BingProvider(session: session)
var returnedData: Data?
let expectation = self.expectation(description: "Should call completion block")
// When
provider.download(image: model) { result in
switch result {
case .success(let data): returnedData = data
case .failure: XCTFail("Should not return failure result")
}
expectation.fulfill()
}
// Then
waitForExpectations(timeout: 1.0, handler: nil)
XCTAssertEqual(returnedData, data)
}
func test_BingProvider_WhenDownloadingImage_CallsResume() {
// Given
let url = URL(string: "https://www.bing.com/image.jpg")!
let webUrl = URL(string: "https://www.bing.com")!
let model = ImageModel(date: Date(),
url: url,
description: "",
webPageURL: webUrl)
let session = FakeSession()
let provider = BingProvider(session: session)
// When
provider.download(image: model) { _ in }
// Then
guard let task = session.dataTask else { return XCTFail("Should have session dataTask") }
XCTAssertTrue(task.resumeCalled)
}
}
|
mit
|
740b89074ad46db1de27f6d056cd9b5a
| 30.700348 | 110 | 0.606837 | 4.896663 | false | true | false | false |
kikettas/Swarkn
|
Swarkn/Classes/LoadingModalViewController.swift
|
1
|
3040
|
//
// LoadingModalViewController.swift
//
// Created by kikettas on 19/10/2016.
// Copyright © 2016. All rights reserved.
//
import Foundation
open class LoadingModalViewController: UIViewController {
fileprivate let activityView = ActivityView()
public init(message: String) {
super.init(nibName: nil, bundle: nil)
modalTransitionStyle = .crossDissolve
modalPresentationStyle = .overFullScreen
activityView.messageLabel.text = message
view = activityView
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class ActivityView: UIView {
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
let boundingBoxView = UIView(frame: CGRect.zero)
let messageLabel = UILabel(frame: CGRect.zero)
init() {
super.init(frame: CGRect.zero)
backgroundColor = UIColor(white: 0.0, alpha: 0.5)
boundingBoxView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
boundingBoxView.layer.cornerRadius = 12.0
activityIndicatorView.startAnimating()
messageLabel.font = UIFont.boldSystemFont(ofSize: UIFont.labelFontSize)
messageLabel.textColor = UIColor.white
messageLabel.textAlignment = .center
messageLabel.shadowColor = UIColor.black
messageLabel.shadowOffset = CGSize(width: 0.0, height: 1.0)
messageLabel.numberOfLines = 0
addSubview(boundingBoxView)
addSubview(activityIndicatorView)
addSubview(messageLabel)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
boundingBoxView.frame.size.width = 160.0
boundingBoxView.frame.size.height = 160.0
boundingBoxView.frame.origin.x = ceil((bounds.width / 2.0) - (boundingBoxView.frame.width / 2.0))
boundingBoxView.frame.origin.y = ceil((bounds.height / 2.0) - (boundingBoxView.frame.height / 2.0))
activityIndicatorView.frame.origin.x = ceil((bounds.width / 2.0) - (activityIndicatorView.frame.width / 2.0))
activityIndicatorView.frame.origin.y = ceil((bounds.height / 2.0) - (activityIndicatorView.frame.height / 2.0))
let messageLabelSize = messageLabel.sizeThatFits(CGSize(width: 160.0 - 20.0 * 2.0, height: CGFloat.greatestFiniteMagnitude))
messageLabel.frame.size.width = messageLabelSize.width
messageLabel.frame.size.height = messageLabelSize.height
messageLabel.frame.origin.x = ceil((bounds.width / 2.0) - (messageLabel.frame.width / 2.0))
messageLabel.frame.origin.y = ceil(activityIndicatorView.frame.origin.y + activityIndicatorView.frame.size.height + ((boundingBoxView.frame.height - activityIndicatorView.frame.height) / 4.0) - (messageLabel.frame.height / 2.0))
}
}
|
mit
|
ec44d19bb2dff77324154df7ba124c6e
| 38.986842 | 236 | 0.677526 | 4.563063 | false | false | false | false |
belatrix/iOSAllStarsRemake
|
AllStars/AllStars/WebService/OSPWebModel.swift
|
1
|
44991
|
//
// OSPWebModel.swift
// BookShelf
//
// Created by Flavio Franco Tunqui on 7/6/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import UIKit
class OSPWebModel: NSObject {
// MARK: - User
class func logInUser(user : User, withCompletion completion : (userSession : UserSession?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let dic : [String : AnyObject] =
["username" : user.user_username!,
"password" : user.user_password!]
let path = "api/employee/authenticate/"
OSPWebSender.sharedInstance.doPOST(path, withParameters: dic) {(response, successful) in
if (response != nil) {
if (successful) {
completion(userSession: OSPWebTranslator.parseUserSessionBE(response as! [String : AnyObject]), errorResponse: nil, successful: successful)
} else {
completion(userSession: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(userSession: nil, errorResponse: nil, successful: successful)
}
}
}
class func registerUserDevice(userDevice : UserDevice, withToken token : String, withCompletion completion : (userDevice : UserDevice?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let dic : [String : AnyObject] =
["employee_id" : userDevice.user_id!,
"ios_device" : userDevice.user_ios_id!]
let path = "/api/employee/\(userDevice.user_id!)/register/device/"
OSPWebSender.sharedInstance.doPOSTWithToken(path, withParameters: dic, withToken: token) {(response, successful) in
if (response != nil) {
if (successful) {
completion(userDevice: OSPWebTranslator.parseUserDevice(response as! [String : AnyObject]), errorResponse: nil, successful: successful)
} else {
completion(userDevice: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(userDevice: nil, errorResponse: nil, successful: successful)
}
}
}
class func createUser(email : String, withCompletion completion : (errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let dic : [String : AnyObject] =
["email" : email]
let path = "api/employee/create/"
OSPWebSender.sharedInstance.doPOST(path, withParameters: dic) {(response, successful) in
if (response != nil) {
if (successful) {
completion(errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
} else {
completion(errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(errorResponse: nil, successful: successful)
}
}
}
class func forgotPassword(email : String, withCompletion completion : (errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "/api/employee/reset/password/" + email + "/"
OSPWebSender.sharedInstance.doGET(path) {(response, successful) in
if (response != nil) {
if (successful) {
completion(errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
} else {
completion(errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(errorResponse: nil, successful: successful)
}
}
}
class func resetUserPassword(userSession : UserSession?, currentPassword : String, newPassword : String, withCompletion completion : (user : User?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/\(userSession!.session_user_id!)/update/password/"
let dic : [String : AnyObject] =
["current_password" : currentPassword,
"new_password" : newPassword]
OSPWebSender.sharedInstance.doPOSTWithToken(path, withParameters: dic, withToken: userSession!.session_token!) {(response, successful) in
if (response != nil) {
if (successful) {
completion(user: OSPWebTranslator.parseUserBE(response as! [String : AnyObject]), errorResponse: nil, successful: successful)
} else {
completion(user: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(user: nil, errorResponse: nil, successful: successful)
}
}
}
class func createParticipant(fullName : String, email : String, socialNetworkType : Int, socialNetworkId : String, withCompletion completion : (userGuest : UserGuest?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/event/participant/"
var socialNetworkIdKey = ""
if (socialNetworkType == 1) {
socialNetworkIdKey = "facebook_id"
} else if (socialNetworkType == 2) {
socialNetworkIdKey = "twitter_id"
}
let dic : [String : AnyObject] =
["fullname" : fullName,
"email" : email,
socialNetworkIdKey : socialNetworkId]
OSPWebSender.sharedInstance.doPOST(path, withParameters: dic) {(response, successful) in
if (response != nil) {
if (successful) {
completion(userGuest: OSPWebTranslator.parseUserGuestBE(response as! [String : AnyObject]), errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
} else {
completion(userGuest: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(userGuest: nil, errorResponse: nil, successful: successful)
}
}
}
class func getUserInformation(user : User, withToken token : String, withCompletion completion : (user : User?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/\(user.user_pk!)/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let objUsuario = OSPWebTranslator.parseUserBE(response as! [String : AnyObject])
objUsuario.user_pk = user.user_pk
completion(user: objUsuario, errorResponse: nil, successful: successful)
} else {
completion(user: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject], withCode: statusCode ?? 0), successful: successful)
}
} else {
completion(user: nil, errorResponse: nil, successful: successful)
}
}
}
class func updateUser(user : User, withToken token : String, withCompletion completion : (user : User?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/\(user.user_pk!)/update/"
let dic : [String : AnyObject] =
["first_name" : user.user_first_name!,
"last_name" : user.user_last_name!,
"skype_id" : user.user_skype_id!,
"location" : user.user_location_id!]
OSPWebSender.sharedInstance.doPATCHWithToken(path, withParameters: dic, withToken: token) {(response, successful) in
if (response != nil) {
if (successful) {
completion(user: OSPWebTranslator.parseUserBE(response as! [String : AnyObject]), errorResponse: nil, successful: successful)
} else {
completion(user: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(user: nil, errorResponse: nil, successful: successful)
}
}
}
class func updatePhoto(user : User, withToken token : String, withImage image : NSData, withCompletion completion : (user : User?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/\(user.user_pk!)/avatar/"
OSPWebSender.sharedInstance.doMultipartWithToken(path, withParameters: nil, withImage: image, withToken: token) {(response, successful) in
if (response != nil) {
if (successful) {
completion(user: OSPWebTranslator.parseUserBE(response as! [String : AnyObject]), errorResponse: nil, successful: successful)
} else {
completion(user: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(user: nil, errorResponse: nil, successful: successful)
}
}
}
class func rateUser(rate : RateUserBE, withToken token : String, withCompletion completion : (errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let userFromID = rate.rate_fromUser!.user_pk
let userToID = rate.rate_toUser!.user_pk
let path = "api/star/\(userFromID!)/give/star/to/\(userToID!)/"
let dic : [String : AnyObject] =
["category" : rate.rate_category!.category_pk!,
"subcategory" : rate.rate_subCategory!.subCategory_pk!,
"keyword" : rate.rate_keyword!.keyword_pk!,
"text" : rate.rate_comment]
OSPWebSender.sharedInstance.doPOSTWithToken(path, withParameters: dic, withToken: token) {(response, successful) in
if (response != nil) {
if (successful) {
let errorResponse = ErrorResponse()
completion(errorResponse: errorResponse, successful: successful)
} else {
completion(errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(errorResponse: nil, successful: successful)
}
}
}
class func listKeyWordsWithToken(token : String, withCompletion completion : (arrayKeywords : NSMutableArray?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/category/keyword/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let arrayResponse : NSArray? = response as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseKeywordBE(obj as! NSDictionary))
})
completion(arrayKeywords: arrayTemp, errorResponse: nil, successful: successful)
} else {
completion(arrayKeywords: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(arrayKeywords: nil, errorResponse: nil, successful: successful)
}
}
}
class func listAllCategoriesToUser(user : User, withToken token : String, withCompletion completion : (arrayCategories : NSMutableArray?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let userID = user.user_pk
let path = "api/employee/\(userID!)/category/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let arrayResponse : NSArray? = response as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseCategoryBE(obj as! NSDictionary))
})
completion(arrayCategories: arrayTemp, errorResponse: nil, successful: successful)
} else {
completion(arrayCategories: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(arrayCategories: nil, errorResponse: nil, successful: successful)
}
}
}
class func listStarUserSubCategoriesToUser(user : User, toSubCategory subCategory : StarSubCategoryBE, withToken token : String, withCompletion completion : (arrayUsers : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let userID = user.user_pk
let path = "api/star/\(userID!)/subcategory/\(subCategory.starSubCategoy_id!)/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseUserQualifyBE(obj as! NSDictionary))
})
completion(arrayUsers: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayUsers: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(arrayUsers: nil, nextPage: nil, errorResponse: nil, successful: successful)
}
}
}
class func listStarUserSubCategoriesToPage(page : String, withToken token : String, withCompletion completion : (arrayUsers : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
OSPWebSender.sharedInstance.doGETWithToken(page, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseUserQualifyBE(obj as! NSDictionary))
})
completion(arrayUsers: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayUsers: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayUsers: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
// MARK: - List
class func listLocations(token : String, withCompletion completion : (arrayLocations : NSMutableArray?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/location/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let arrayResponse : NSArray? = response as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseLocationBE(obj as! NSDictionary))
})
completion(arrayLocations: arrayTemp, errorResponse: nil, successful: successful)
} else {
completion(arrayLocations: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(arrayLocations: nil, errorResponse: nil, successful: successful)
}
}
}
class func listUserSkills(user : User, withToken token : String,
withCompletion completion : (skills : [KeywordBE]?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "/api/employee/\(user.user_pk!)/skills/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
var skillsTemp = [KeywordBE]()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
skillsTemp.append(OSPWebTranslator.parseKeywordBE(obj as! NSDictionary))
})
completion(skills: skillsTemp, nextPage: nextPage, errorResponse: nil, successful: successful)
} else {
completion(skills: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(skills: nil, nextPage: nil, errorResponse: nil, successful: successful)
}
}
}
class func listUserSkillsToPage(page : String, withToken token : String,
withCompletion completion : (skills : [KeywordBE]?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
OSPWebSender.sharedInstance.doGETWithToken(page, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
var skillsTemp = [KeywordBE]()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
skillsTemp.append(OSPWebTranslator.parseKeywordBE(obj as! NSDictionary))
})
completion(skills: skillsTemp, nextPage: nextPage, errorResponse: nil, successful: successful)
} else {
completion(skills: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(skills: nil, nextPage: nil, errorResponse: nil, successful: successful)
}
}
}
class func listStarSubCategoriesToUser(user : User, withToken token : String, withCompletion completion : (arrayCategories : NSMutableArray?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/star/\(user.user_pk!)/subcategory/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseStarSubCategoryBE(obj as! NSDictionary))
})
completion(arrayCategories: arrayTemp, errorResponse: nil, successful: successful)
} else {
completion(arrayCategories: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(arrayCategories: nil, errorResponse: nil, successful: successful)
}
}
}
// MARK: - Employee
class func listEmployeeWithToken(token : String, withCompletion completion : (arrayEmployees : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseUserBE(obj as! NSDictionary))
})
completion(arrayEmployees: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listEmployeeToPage(page : String, withToken token : String, withCompletion completion : (arrayEmployees : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
OSPWebSender.sharedInstance.doGETWithToken(page, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseUserBE(obj as! NSDictionary))
})
completion(arrayEmployees: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listEmployeeWithText(text : String, withToken token : String, withCompletion completion : (arrayEmployees : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/list/?search=\(text)"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseUserBE(obj as! NSDictionary))
})
completion(arrayEmployees: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listStarKeywordWithToken(token : String, withCompletion completion : (arrayKeywords : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/star/keyword/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseStarKeywordBE(obj as! NSDictionary))
})
completion(arrayKeywords: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayKeywords: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayKeywords: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listStarKeywordToPage(page : String, withToken token : String, withCompletion completion : (arrayKeywords : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
OSPWebSender.sharedInstance.doGETWithToken(page, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseStarKeywordBE(obj as! NSDictionary))
})
completion(arrayKeywords: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayKeywords: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayKeywords: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listStarKeywordWithText(text : String, withToken token : String, withCompletion completion : (arrayEmployees : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/star/keyword/list/?search=\(text)"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseStarKeywordBE(obj as! NSDictionary))
})
completion(arrayEmployees: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listEvents(searchstring: String?, withCompletion completion : (arrayEmployees : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
var searchPostfix = ""
if let keyWord = searchstring where keyWord != "" {
searchPostfix = "?search=" + keyWord
}
let path = "api/event/list/" + searchPostfix
OSPWebSender.sharedInstance.doGET(path) {(response, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseEvent(obj as! NSDictionary))
})
completion(arrayEmployees: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listEmployeeKeywordWithToken(starKeyword : StarKeywordBE, withToken token : String, withCompletion completion : (arrayEmployees : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/star/keyword/\(starKeyword.keyword_pk!)/list/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseUserTagBE(obj as! NSDictionary))
})
completion(arrayEmployees: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listEmployeeKeywordToPage(page : String, withToken token : String, withCompletion completion : (arrayEmployees : NSMutableArray?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
OSPWebSender.sharedInstance.doGETWithToken(page, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseUserTagBE(obj as! NSDictionary))
})
completion(arrayEmployees: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayEmployees: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listUserRankingToKind(kind : String, withToken token : String, withCompletion completion : (arrayUsersRanking : NSMutableArray?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/list/top/\(kind)/15/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
let arrayResponse : NSArray? = response as? NSArray
let arrayTemp = NSMutableArray()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.addObject(OSPWebTranslator.parseUserRankingBE(obj as! NSDictionary))
})
completion(arrayUsersRanking: arrayTemp, errorResponse: nil, successful: successful)
} else {
completion(arrayUsersRanking: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(arrayUsersRanking: nil, errorResponse: nil, successful: successful)
}
}
}
class func addSkillToUser(user : User, skillName: String, withToken token : String, withCompletion completion : (skills : [KeywordBE]?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "/api/employee/\(user.user_pk!)/skills/add/"
let dic : [String : AnyObject] =
["skill" : skillName]
OSPWebSender.sharedInstance.doPATCHWithToken(path, withParameters: dic, withToken: token) {(response, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
let arrayResponse = dic["results"] as? NSArray
var skillsTemp = [KeywordBE]()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
skillsTemp.append(OSPWebTranslator.parseKeywordBE(obj as! NSDictionary))
})
completion(skills: skillsTemp, errorResponse: nil, successful: successful)
} else {
completion(skills: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(skills: nil, errorResponse: nil, successful: successful)
}
}
}
class func deleteUserSkill(user : User, skillName: String, withToken token : String, withCompletion completion : (skills : [KeywordBE]?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "api/employee/\(user.user_pk!)/skills/remove/"
let dic : [String : AnyObject] = ["skill" : skillName]
OSPWebSender.sharedInstance.doPATCHWithToken(path, withParameters: dic, withToken: token) {(response, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
let arrayResponse = dic["results"] as? NSArray
var skillsTemp = [KeywordBE]()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
skillsTemp.append(OSPWebTranslator.parseKeywordBE(obj as! NSDictionary))
})
completion(skills: skillsTemp, errorResponse: nil, successful: successful)
} else {
completion(skills: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: successful)
}
} else {
completion(skills: nil, errorResponse: nil, successful: successful)
}
}
}
// MARK: - Activities
class func listActivities(userID: String, withToken token : String, withCompletion completion : (arrayActivities : [Activity]?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "/api/activity/get/notification/employee/" + userID + "/all/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) { (response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
var arrayTemp = [Activity]()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.append(OSPWebTranslator.parseActivity(obj as! NSDictionary))
})
completion(arrayActivities: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayActivities: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayActivities: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
class func listActivitiesToPage(page: String, withToken token : String, withCompletion completion : (arrayActivities : [Activity]?, nextPage : String?, errorResponse : ErrorResponse?, successful : Bool) -> Void) {
OSPWebSender.sharedInstance.doGETWithToken(page, withToken: token) { (response, statusCode, successful) in
if (response != nil) {
if (successful) {
let dic = response as! NSDictionary
var nextPage = dic["next"] as? String
nextPage = nextPage?.replace(Constants.WEB_SERVICES, withString: "")
let arrayResponse = dic["results"] as? NSArray
var arrayTemp = [Activity]()
arrayResponse?.enumerateObjectsUsingBlock({ (obj, idx, stop) in
arrayTemp.append(OSPWebTranslator.parseActivity(obj as! NSDictionary))
})
completion(arrayActivities: arrayTemp, nextPage: nextPage, errorResponse: nil, successful: true)
} else {
completion(arrayActivities: nil, nextPage: nil, errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject]), successful: false)
}
} else {
completion(arrayActivities: nil, nextPage: nil, errorResponse: nil, successful: false)
}
}
}
// MARK: - Logout
class func doLogout(token : String, withCompletion completion : (errorResponse : ErrorResponse?, successful : Bool) -> Void) {
let path = "/api/employee/logout/"
OSPWebSender.sharedInstance.doGETWithToken(path, withToken: token) {(response, statusCode, successful) in
if (response != nil) {
if (successful) {
completion(errorResponse: nil, successful: successful)
} else {
completion(errorResponse: OSPWebTranslator.parseErrorMessage(response as! [String : AnyObject], withCode: statusCode), successful: successful)
}
} else {
completion(errorResponse: nil, successful: successful)
}
}
}
}
|
mit
|
85a2f007d5c3224655ac95dcd328d4b8
| 50.536082 | 273 | 0.564414 | 5.505384 | false | false | false | false |
hooman/swift
|
stdlib/public/Concurrency/AsyncPrefixWhileSequence.swift
|
3
|
4276
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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
@available(SwiftStdlib 5.5, *)
extension AsyncSequence {
/// Returns an asynchronous sequence, containing the initial, consecutive
/// elements of the base sequence that satisfy the given predicate.
///
/// Use `prefix(while:)` to produce values while elements from the base
/// sequence meet a condition you specify. The modified sequence ends when
/// the predicate closure returns `false`.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `prefix(while:)` method causes the modified
/// sequence to pass along values so long as they aren’t divisible by `2` and
/// `3`. Upon reaching `6`, the sequence ends:
///
/// let stream = Counter(howHigh: 10)
/// .prefix { $0 % 2 != 0 || $0 % 3 != 0 }
/// for try await number in stream {
/// print("\(number) ", terminator: " ")
/// }
/// // prints "1 2 3 4 5"
///
/// - Parameter predicate: A closure that takes an element as a parameter and
/// returns a Boolean value indicating whether the element should be
/// included in the modified sequence.
/// - Returns: An asynchronous sequence of the initial, consecutive
/// elements that satisfy `predicate`.
@inlinable
public __consuming func prefix(
while predicate: @escaping (Element) async -> Bool
) rethrows -> AsyncPrefixWhileSequence<Self> {
return AsyncPrefixWhileSequence(self, predicate: predicate)
}
}
/// An asynchronous sequence, containing the initial, consecutive
/// elements of the base sequence that satisfy a given predicate.
@available(SwiftStdlib 5.5, *)
@frozen
public struct AsyncPrefixWhileSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let predicate: (Base.Element) async -> Bool
@inlinable
init(
_ base: Base,
predicate: @escaping (Base.Element) async -> Bool
) {
self.base = base
self.predicate = predicate
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncPrefixWhileSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The prefix-while sequence produces whatever type of element its base
/// iterator produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the prefix-while sequence.
@frozen
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var predicateHasFailed = false
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let predicate: (Base.Element) async -> Bool
@inlinable
init(
_ baseIterator: Base.AsyncIterator,
predicate: @escaping (Base.Element) async -> Bool
) {
self.baseIterator = baseIterator
self.predicate = predicate
}
/// Produces the next element in the prefix-while sequence.
///
/// If the predicate hasn't yet failed, this method gets the next element
/// from the base sequence and calls the predicate with it. If this call
/// succeeds, this method passes along the element. Otherwise, it returns
/// `nil`, ending the sequence.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
if !predicateHasFailed, let nextElement = try await baseIterator.next() {
if await predicate(nextElement) {
return nextElement
} else {
predicateHasFailed = true
}
}
return nil
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), predicate: predicate)
}
}
|
apache-2.0
|
496f6b4318b789887795f517c9d79e63
| 33.467742 | 80 | 0.657698 | 4.727876 | false | false | false | false |
AimobierCocoaPods/Auxiliary
|
Classes/YAxis/Auxiliary+bottom.swift
|
1
|
6561
|
//
// Auxiliary+bottom.swift
// Test
//
// Created by 荆文征 on 2018/12/21.
// Copyright © 2018 aimobier.cloud. All rights reserved.
//
import UIKit
extension ViewAuxiliary{
/// Setting View's bottom greaterThanOrEqual otherAnchor, the bottom constraint = other.bottom * multiplier
///
/// - Parameters:
/// - other: object of reference
/// - Returns: View's Auxiliary
@discardableResult
public func bottom(_ other: LayoutYAxisAnchor) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.equal,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: other,
constant: 0,
multiplier: 1)
return self
}
/// Setting View's bottom greaterThanOrEqual value, the bottom constraint = constant
///
/// - Parameters:
/// - constant: constraint value
/// - Returns: View's Auxiliary
@discardableResult
public func bottom(_ constant: CGFloat = 0) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.equal,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: nil,
constant: constant,
multiplier: 1)
return self
}
/// Setting View's bottom greaterThanOrEqual value, the bottom constraint = other.bottom * multiplier + constant
///
/// - Parameters:
/// - other: object of reference
/// - constant: constant value
/// - multiplier: multiplier
/// - Returns: View's Auxiliary
@discardableResult
public func bottom(other: LayoutYAxisAnchor,constant: CGFloat,multiplier: CGFloat = 1) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.equal,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: other,
constant: constant,
multiplier: multiplier)
return self
}
}
extension ViewAuxiliary{
/// Setting View's bottom greaterThanOrEqual otherAnchor, the bottom constraint = other.bottom * multiplier
///
/// - Parameters:
/// - other: object of reference
/// - Returns: View's Auxiliary
@discardableResult
public func bottomLessThanOrEqual(_ other: LayoutYAxisAnchor) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.lessThanOrEqual,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: other,
constant: 0,
multiplier: 1)
return self
}
/// Setting View's bottom greaterThanOrEqual value, the bottom constraint = constant
///
/// - Parameters:
/// - constant: constraint value
/// - Returns: View's Auxiliary
@discardableResult
public func bottomLessThanOrEqual(_ constant: CGFloat = 0) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.lessThanOrEqual,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: nil,
constant: constant,
multiplier: 1)
return self
}
/// Setting View's bottom greaterThanOrEqual value, the bottom constraint = other.bottom * multiplier + constant
///
/// - Parameters:
/// - other: object of reference
/// - constant: constant value
/// - multiplier: multiplier
/// - Returns: View's Auxiliary
@discardableResult
public func bottomLessThanOrEqual(other: LayoutYAxisAnchor,constant: CGFloat,multiplier: CGFloat = 1) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.lessThanOrEqual,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: other,
constant: constant,
multiplier: multiplier)
return self
}
}
extension ViewAuxiliary{
/// Setting View's bottom greaterThanOrEqual otherAnchor, the bottom constraint = other.bottom * multiplier
///
/// - Parameters:
/// - other: object of reference
/// - Returns: View's Auxiliary
@discardableResult
public func bottomGreaterThanOrEqual(_ other: LayoutYAxisAnchor) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.greaterThanOrEqual,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: other,
constant: 0,
multiplier: 1)
return self
}
/// Setting View's bottom greaterThanOrEqual value, the bottom constraint = constant
///
/// - Parameters:
/// - constant: constraint value
/// - Returns: View's Auxiliary
@discardableResult
public func bottomGreaterThanOrEqual(_ constant: CGFloat = 0) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.greaterThanOrEqual,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: nil,
constant: constant,
multiplier: 1)
return self
}
/// Setting View's bottom greaterThanOrEqual value, the bottom constraint = other.bottom * multiplier + constant
///
/// - Parameters:
/// - other: object of reference
/// - constant: constant value
/// - multiplier: multiplier
/// - Returns: View's Auxiliary
@discardableResult
public func bottomGreaterThanOrEqual(other: LayoutYAxisAnchor,constant: CGFloat,multiplier: CGFloat = 1) -> ViewAuxiliary{
yAxisConstraintMethod(related: NSLayoutConstraint.Relation.greaterThanOrEqual,
baseAttribute: NSLayoutConstraint.Attribute.bottom,
other: other,
constant: constant,
multiplier: multiplier)
return self
}
}
|
mit
|
3c067b21e8f1f51f9330e40276340d7b
| 35.820225 | 126 | 0.569118 | 6.096744 | false | false | false | false |
ancode-cn/Meizhi
|
Meizhi/Classes/business/discover/DoubleTextView.swift
|
1
|
3463
|
//
// DoubleTextView.swift
// SmallDay
// 项目GitHub地址: https://github.com/ZhongTaoTian/SmallDay
// 项目思路和架构讲解博客: http://www.jianshu.com/p/bcc297e19a94
// Created by MacBook on 15/8/16.
// Copyright (c) 2015年 维尼的小熊. All rights reserved.
// 探店的titleView
import UIKit
class DoubleTextView: UIView {
private var buttonArr = [NoHighlightButton]()
private let textColorFroNormal: UIColor = UIColor(red: 100 / 255.0, green: 100 / 255.0, blue: 100 / 255.0, alpha: 1)
private let textFont: UIFont = Constant.TITLE_FONT
private let bottomLineView: UIView = UIView()
private var selectedBtn: UIButton?
weak var delegate: DoubleTextViewDelegate?
convenience init(textArr:[String]){
self.init()
if textArr.count > 0{
var i:Int = 0
for str in textArr{
let btn = NoHighlightButton()
buttonArr.append(btn)
setButton(btn, title: str, tag: 100 + i)
i += 1
}
}
// 设置底部线条View
setBottomLineView()
if buttonArr.count > 0{
titleButtonClick(buttonArr[0])
}
}
private func setBottomLineView() {
bottomLineView.backgroundColor = UIColor(red: 60 / 255.0, green: 60 / 255.0, blue: 60 / 255.0, alpha: 1)
addSubview(bottomLineView)
}
private func setButton(button: UIButton, title: String, tag: Int) {
button.setTitleColor(UIColor.blackColor(), forState: .Selected)
button.setTitleColor(textColorFroNormal, forState: .Normal)
button.titleLabel?.font = textFont
button.tag = tag
button.addTarget(self, action: "titleButtonClick:", forControlEvents: .TouchUpInside)
button.setTitle(title, forState: .Normal)
addSubview(button)
}
override func layoutSubviews() {
super.layoutSubviews()
if buttonArr.count > 0{
let height = self.frame.size.height
let btnW = self.frame.size.width / CGFloat(buttonArr.count)
var i:CGFloat = 0
for btn in buttonArr{
btn.frame = CGRectMake(btnW * i, 0, btnW, height)
i += 1
}
bottomLineView.frame = CGRectMake(0, height - 2, btnW, 2)
}
}
func titleButtonClick(sender: UIButton) {
selectedBtn?.selected = false
sender.selected = true
selectedBtn = sender
bottomViewScrollTo(sender.tag - 100)
delegate?.doubleTextView(self, didClickBtn: sender, forIndex: sender.tag - 100)
}
func bottomViewScrollTo(index: Int) {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.bottomLineView.frame.origin.x = CGFloat(index) * self.bottomLineView.frame.width
})
}
func clickBtnToIndex(index: Int) {
let btn: NoHighlightButton = self.viewWithTag(index + 100) as! NoHighlightButton
self.titleButtonClick(btn)
}
}
/// DoubleTextViewDelegate协议
protocol DoubleTextViewDelegate: NSObjectProtocol{
func doubleTextView(doubleTextView: DoubleTextView, didClickBtn btn: UIButton, forIndex index: Int)
}
/// 没有高亮状态的按钮
class NoHighlightButton: UIButton {
/// 重写setFrame方法
override var highlighted: Bool {
didSet{
super.highlighted = false
}
}
}
|
mit
|
019346e34aed729ec7f7feff236319ff
| 31.747573 | 120 | 0.615476 | 4.179678 | false | false | false | false |
classmere/app
|
Classmere/Classmere/Views/TableViewCells/SectionCell.swift
|
1
|
9440
|
import UIKit
import PureLayout
extension UpdatableCell where Self: SectionCell {
func update(with model: Section) {
termLabel.text = Utilities.parseTerm(model.term)
if let meetingTime = model.meetingTimes?.first {
let days = meetingTime.days ?? "No meeting times specified"
let building = meetingTime.buildingCode ?? "No location specified"
let roomNumber = Utilities.optionalDescriptionOrEmptyString(meetingTime.roomNumber)
if let startTime = meetingTime.startTime, let endTime = meetingTime.endTime {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
let startTime = dateFormatter.string(from: startTime)
let endTime = dateFormatter.string(from: endTime)
dayLabel.text = "\(days) \(startTime) - \(endTime)"
} else {
dayLabel.text = days
}
locationLabel.text = "\(building) \(roomNumber)"
} else {
dayLabel.text = "No meeting times specified"
locationLabel.text = "No location specified"
}
instructorLabel.text = model.instructor
typeLabel.text = model.type
if let currentlyEnrolled = model.enrollmentCurrent, let enrollmentCapacity = model.enrollmentCapacity {
let spotsLeft = enrollmentCapacity - currentlyEnrolled
enrolledLabel.text = "\(currentlyEnrolled) student(s) enrolled, \(spotsLeft) spots left"
}
if let startDate = model.startDate, let endDate = model.endDate {
dateLabel.text = "\(startDate) - \(endDate)"
}
if let crn = model.crn {
crnLabel.text = "CRN: \(crn)"
}
selectionStyle = .none
updateConstraintsIfNeeded()
}
}
extension SectionCell: UpdatableCell {}
final class SectionCell: UITableViewCell {
var didSetupConstraints = false
var dayIconLabel: UILabel = UILabel.newAutoLayout()
var instructorIconLabel: UILabel = UILabel.newAutoLayout()
var locationIconLabel: UILabel = UILabel.newAutoLayout()
var typeIconLabel: UILabel = UILabel.newAutoLayout()
var enrolledIconLabel: UILabel = UILabel.newAutoLayout()
var dateIconLabel: UILabel = UILabel.newAutoLayout()
var crnIconLabel: UILabel = UILabel.newAutoLayout()
var termLabel: UILabel = UILabel.newAutoLayout()
var dayLabel: UILabel = UILabel.newAutoLayout()
var instructorLabel: UILabel = UILabel.newAutoLayout()
var locationLabel: UILabel = UILabel.newAutoLayout()
var typeLabel: UILabel = UILabel.newAutoLayout()
var enrolledLabel: UILabel = UILabel.newAutoLayout()
var dateLabel: UILabel = UILabel.newAutoLayout()
var crnLabel: UILabel = UILabel.newAutoLayout()
// MARK: - Initialization
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
// MARK: - Setup
func setupViews() {
let iconLabels = [
dayIconLabel,
instructorIconLabel,
locationIconLabel,
typeIconLabel,
enrolledIconLabel,
dateIconLabel,
crnIconLabel
]
let infoLabels = [
dayLabel,
instructorLabel,
locationLabel,
typeLabel,
enrolledLabel,
dateLabel,
crnLabel
]
let labelTitles = [
"Days",
"Instructor",
"Location",
"Type",
"Enrolled",
"Dates",
"CRN"
]
for iconLabel in zip(iconLabels, labelTitles) {
iconLabel.0.lineBreakMode = .byTruncatingTail
iconLabel.0.numberOfLines = 0
iconLabel.0.textAlignment = .center
iconLabel.0.text = EmojiFactory.emojiFromSectionProperty(iconLabel.1)
contentView.addSubview(iconLabel.0)
}
for infoLabel in infoLabels {
infoLabel.lineBreakMode = .byTruncatingTail
infoLabel.numberOfLines = 1
infoLabel.textAlignment = .left
infoLabel.textColor = Theme.Color.dark.uicolor
infoLabel.font = UIFont(name: "HelveticaNeue", size: 13)
contentView.addSubview(infoLabel)
}
termLabel.lineBreakMode = .byTruncatingTail
termLabel.numberOfLines = 1
termLabel.adjustsFontSizeToFitWidth = true
termLabel.minimumScaleFactor = 0.1
termLabel.textAlignment = .left
termLabel.textColor = .darkGray
termLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
contentView.addSubview(termLabel)
}
// MARK: - Layout
override func updateConstraints() {
if !didSetupConstraints {
NSLayoutConstraint.autoSetPriority(UILayoutPriority.required) {
self.dayIconLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.instructorIconLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.locationIconLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.typeIconLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.enrolledIconLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.dateIconLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.crnIconLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.termLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.dayLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.instructorLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.locationLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.typeLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.enrolledLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.dateLabel.autoSetContentCompressionResistancePriority(for: .vertical)
self.crnLabel.autoSetContentCompressionResistancePriority(for: .vertical)
}
termLabel.autoPinEdge(toSuperviewEdge: .top, withInset: 10)
termLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: 10)
termLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: 10)
dayIconLabel.autoPinEdge(.leading, to: .leading, of: termLabel)
dayIconLabel.autoAlignAxis(.horizontal, toSameAxisOf: termLabel, withOffset: 40)
instructorIconLabel.autoPinEdge(.leading, to: .leading, of: dayIconLabel)
instructorIconLabel.autoAlignAxis(.horizontal, toSameAxisOf: dayIconLabel, withOffset: 40)
locationIconLabel.autoPinEdge(.leading, to: .leading, of: instructorIconLabel)
locationIconLabel.autoAlignAxis(.horizontal, toSameAxisOf: instructorIconLabel, withOffset: 40)
typeIconLabel.autoPinEdge(.leading, to: .leading, of: locationIconLabel)
typeIconLabel.autoAlignAxis(.horizontal, toSameAxisOf: locationIconLabel, withOffset: 40)
enrolledIconLabel.autoPinEdge(.leading, to: .leading, of: typeIconLabel)
enrolledIconLabel.autoAlignAxis(.horizontal, toSameAxisOf: typeIconLabel, withOffset: 40)
dateIconLabel.autoPinEdge(.leading, to: .leading, of: enrolledIconLabel)
dateIconLabel.autoAlignAxis(.horizontal, toSameAxisOf: enrolledIconLabel, withOffset: 40)
crnIconLabel.autoPinEdge(.leading, to: .leading, of: dateIconLabel)
crnIconLabel.autoAlignAxis(.horizontal, toSameAxisOf: dateIconLabel, withOffset: 40)
dayLabel.autoPinEdge(.leading, to: .trailing, of: dayIconLabel, withOffset: 20)
dayLabel.autoAlignAxis(.horizontal, toSameAxisOf: dayIconLabel)
instructorLabel.autoPinEdge(.leading, to: .leading, of: dayLabel)
instructorLabel.autoAlignAxis(.horizontal, toSameAxisOf: dayLabel, withOffset: 40)
locationLabel.autoPinEdge(.leading, to: .leading, of: instructorLabel)
locationLabel.autoAlignAxis(.horizontal, toSameAxisOf: instructorLabel, withOffset: 40)
typeLabel.autoPinEdge(.leading, to: .leading, of: locationLabel)
typeLabel.autoAlignAxis(.horizontal, toSameAxisOf: locationLabel, withOffset: 40)
enrolledLabel.autoPinEdge(.leading, to: .leading, of: typeLabel)
enrolledLabel.autoAlignAxis(.horizontal, toSameAxisOf: typeLabel, withOffset: 40)
dateLabel.autoPinEdge(.leading, to: .leading, of: enrolledLabel)
dateLabel.autoAlignAxis(.horizontal, toSameAxisOf: enrolledLabel, withOffset: 40)
crnLabel.autoPinEdge(.leading, to: .leading, of: dateLabel)
crnLabel.autoAlignAxis(.horizontal, toSameAxisOf: dateLabel, withOffset: 40)
didSetupConstraints = true
}
super.updateConstraints()
}
}
|
gpl-3.0
|
86fb7d5ae8b8fa99d000274de5b894c6
| 41.714932 | 111 | 0.663453 | 5.083468 | false | false | false | false |
editfmah/AeonAPI
|
Sources/ResultProcessor.swift
|
1
|
11560
|
//
// ResultProcessor.swift
// AeonAPI
//
// Created by Adrian Herridge on 24/06/2017.
//
//
import Foundation
import SWSQLite
import Dispatch
import SwiftyJSON
class ResultProcessor {
init() {
execute()
}
func execute() {
DispatchQueue.global(qos: .background).async {
var count = 0
while true {
Thread.sleep(forTimeInterval: 0.1)
// query for the oldest unprocessed result
let results = resultsdb.query(sql: "SELECT * FROM TaskResult WHERE status = ? LIMIT 1", params: [TaskStatus.TaskStatusNotExecuted.rawValue])
if results.error == nil && results.results.count > 0 {
let r = TaskResult(results.results[0])
switch r.type! {
case TaskType.TaskTypeAeonSimpleWalletBalanceUpdate.rawValue:
var balance: Double = 0
var balance_unlocked: Double = 0
let result = r.result!
let j = JSON(data: result.data(using: .utf8, allowLossyConversion: false)!)
if j["balance"].exists() {
balance = j["balance"].doubleValue
balance_unlocked = j["unlocked"].doubleValue
logger.output(LOGGER_ALL,"processed balance \(balance) with unlocked \(balance_unlocked)")
_ = walletsdb.execute(sql: "UPDATE Wallet SET wallet_balance = ?,wallet_unlocked_balance = ?, wallet_modified = ?, wallet_status = ? WHERE _id_ = ?", params: [balance, balance_unlocked, Date().timeIntervalSince1970,WalletStatusOnline, r.wallet_id!])
}
case TaskType.TaskTypeAeonSimpleWalletReadTransactions.rawValue:
let result = r.result!
let j = JSON(data: result.data(using: .utf8, allowLossyConversion: false)!)
if j["succeeded"].exists() && j["succeeded"].boolValue {
// group all of the transactions together into a dictionary
var data: [String:Double] = [:]
for t in j["transfers"].arrayValue {
var id = t["id"].stringValue
id = id.replacingOccurrences(of: "<", with: "")
id = id.replacingOccurrences(of: ">", with: "")
if data[id] == nil {
data[id] = Double(0.0)
}
var value = data[id]!
value += t["amount"].doubleValue
data[id] = value
}
for id in data.keys {
let amount = data[id]!
if transdb.query(sql: "SELECT * FROM Trans WHERE trans_wallet_id = ? AND trans_id = ?", params: [r.wallet_id!, id]).results.count == 0 {
logger.output(LOGGER_ALL,"writing new transaction for wallet <\(r.wallet_id!)> id <\(id)>")
let newTrans = Trans()
newTrans.trans_modified = Date().timeIntervalSince1970
newTrans.trans_date = TransactionDate.DateForTransaction(id)
newTrans.trans_wallet_id = r.wallet_id
newTrans.trans_id = id
newTrans.trans_description = "Incoming transfer"
newTrans.trans_amount = amount
newTrans.trans_type = TransactionType.Deposit.rawValue
newTrans.trans_status = TransactionStatus.Complete.rawValue
_ = transdb.execute(compiledAction: newTrans.Commit())
}
}
}
case TaskType.TaskTypeAeonSimpleWalletRefresh.rawValue:
let result = r.result!
let j = JSON(data: result.data(using: .utf8, allowLossyConversion: false)!)
if j["succeeded"].exists() && j["succeeded"].boolValue {
// do nothing
}
case TaskType.TaskTypeAeonSimpleWalletReadSeed.rawValue:
let result = r.result!
let j = JSON(data: result.data(using: .utf8, allowLossyConversion: false)!)
if j["succeeded"].exists() && j["succeeded"].boolValue {
let seed = j["seed"].stringValue
logger.output(LOGGER_ALL,"seed found: \(seed)")
if walletsdb.execute(sql: "UPDATE Wallet SET wallet_seed = ?, wallet_modified = ? WHERE _id_ = ?", params: [seed,Date().timeIntervalSince1970, r.wallet_id!]).error == nil {
logger.output(LOGGER_ALL,"Wallet<\(r.wallet_id!)>: seed updated")
}
}
case TaskType.TaskTypeCoinMarketEUR.rawValue:
let result = r.result!
let jsonArray = JSON(data: result.data(using: .utf8, allowLossyConversion: false)!)
if jsonArray != nil {
if jsonArray.array != nil && jsonArray.array!.count > 0 {
let json = jsonArray.array![0]
if json["price_eur"].exists() {
self.WriteRate(currency: "EUR", name: "Euro", value: json["price_eur"].stringValue, pc_change: json["percent_change_24h"].stringValue)
} else {
r.status = TaskStatus.TaskStatusErroredProcessing.rawValue
_ = resultsdb.execute(compiledAction: r.Commit())
}
} else {
r.status = TaskStatus.TaskStatusErroredProcessing.rawValue
_ = resultsdb.execute(compiledAction: r.Commit())
}
} else {
r.status = TaskStatus.TaskStatusErroredProcessing.rawValue
_ = resultsdb.execute(compiledAction: r.Commit())
}
case TaskType.TaskTypeCoinMarketGBP.rawValue:
let result = r.result!
let jsonArray = JSON(data: result.data(using: .utf8, allowLossyConversion: false)!)
if jsonArray != nil {
if jsonArray.array != nil && jsonArray.array!.count > 0 {
let json = jsonArray.array![0]
if json["price_gbp"].exists() {
self.WriteRate(currency: "GBP", name: "Pound Sterling", value: json["price_gbp"].stringValue, pc_change: json["percent_change_24h"].stringValue)
}
if json["price_usd"].exists() {
self.WriteRate(currency: "USD", name: "US Dollar", value: json["price_usd"].stringValue, pc_change: json["percent_change_24h"].stringValue)
}
if json["price_btc"].exists() {
self.WriteRate(currency: "BTC", name: "Bitcoin", value: json["price_btc"].stringValue, pc_change: json["percent_change_24h"].stringValue)
}
} else {
// error
}
} else {
// error
}
default:
break
}
r.status = TaskStatus.TaskStatusCompleted.rawValue
_ = resultsdb.execute(compiledAction: r.Commit())
}
count += 1
if count > (5*60) {
count = 0
_ = resultsdb.query(sql: "DELETE FROM TaskResult WHERE status = ?", params: [TaskStatus.TaskStatusCompleted.rawValue])
logger.output(LOGGER_ALL,"cleaned spent records from TaskResult table")
}
}
}
}
func WriteRate(currency: String, name: String, value: String, pc_change: String) {
let dvalue = Double(value) ?? 0.00
var rate = Rate()
let results = ratesdb.query(sql: "SELECT * FROM Rate WHERE exch_currency = ?", params: [currency])
if results.error == nil && results.results.count > 0 {
rate = Rate(results.results[0])
}
rate.exch_currency = currency
rate.exch_currency_name = name
rate.exch_value = dvalue
rate.exch_modified = Date().timeIntervalSince1970
rate.exch_pc_change_24hr = Double(pc_change) ?? 0.0
if ratesdb.execute(compiledAction: rate.Commit()).error == nil {
logger.output(LOGGER_ALL,"updated currency \(currency) with new value \(dvalue)")
}
}
}
|
mit
|
0296218be8e62bf5cb20146d48ab68ca
| 45.425703 | 277 | 0.381401 | 6.422222 | false | false | false | false |
s-emp/TinkoffChat
|
TinkoffChat/TinkoffChat/Modules/Profile/CoreLayout/Locale/GCDDataManger.swift
|
1
|
1681
|
////
//// Locale.swift
//// TinkoffChat
////
//// Created by Сергей Мельников on 29.10.2017.
//// Copyright © 2017 Сергей Мельников. All rights reserved.
////
import Foundation
class GCDDataManager: DataManager {
private func checkDirectory() -> URL? {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
}
private var fileName: String = "user.txt"
func prepareObject(fileName: String) {
self.fileName = fileName
}
func saveUser(_ user: User, callback: @escaping (Bool) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
guard let path = self.checkDirectory() else { return }
do {
let jsonUser = try JSONEncoder().encode(user)
try jsonUser.write(to: path.appendingPathComponent(self.fileName))
callback(true)
} catch {
print("could't create file text.txt because of error: \(error)")
callback(false)
}
}
}
func loadUser(callback: @escaping (User?) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
guard let path = self.checkDirectory() else {
callback(nil)
return
}
do {
let data = try Data(contentsOf: path.appendingPathComponent(self.fileName))
callback(try JSONDecoder().decode(User.self, from: data))
return
} catch {
print(error.localizedDescription)
callback(nil)
return
}
}
}
}
|
mit
|
77f776cd811f4230781cc0c99aba2c8d
| 29.555556 | 91 | 0.553333 | 4.583333 | false | false | false | false |
LightD/ivsa-server
|
Sources/App/Middlewares/TokenAuthMiddleware.swift
|
1
|
2321
|
//
// TokenAuthMiddleware.swift
// ivsa
//
// Created by Light Dream on 19/11/2016.
//
//
import Foundation
import HTTP
import Vapor
import Auth
final class TokenAuthMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
// if there's no access token, we flip nigga!!
guard let accessToken = request.auth.header?.bearer else {
throw Abort.custom(status: .networkAuthenticationRequired, message: "Unauthenticated users request this.")
}
do {
// check if the access token is valid
let _ = try request.ivsaAuth.login(accessToken)
}
catch {
throw Abort.custom(status: .badRequest, message: "Invalid authentication credentials")
}
// authenticated and everything, perform the request
return try next.respond(to: request)
}
}
public final class TokenAuthHelper {
let request: Request
init(request: Request) { self.request = request }
public var header: Authorization? {
guard let authorization = request.headers["Authorization"] else {
return nil
}
return Authorization(header: authorization)
}
func login(_ credentials: Credentials) throws -> IVSAUser {
return try IVSAUser.authenticate(credentials: credentials) as! IVSAUser
}
func logout() throws {
// first find the user, then update it with a clear session
var user = try self.user()
user.accessToken = nil
try user.save()
}
func user() throws -> IVSAUser {
// first find the user
guard let bearerToken = self.header?.bearer else {
throw Abort.custom(status: .unauthorized, message: "Autenticate first, then try again.")
}
guard let user = try IVSAUser.query().filter("access_token", bearerToken.string).first() else {
throw Abort.custom(status: .unauthorized, message: "Invalid credentials.")
}
return user
}
}
extension Request {
public var ivsaAuth: TokenAuthHelper {
let helper = TokenAuthHelper(request: self)
return helper
}
}
|
mit
|
bf1df12b38e2c479df13122a927604c8
| 25.988372 | 118 | 0.601034 | 4.71748 | false | false | false | false |
khizkhiz/swift
|
validation-test/compiler_crashers_fixed/00176-vtable.swift
|
1
|
12860
|
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b<d-> d { class d:b class b
class l {
func f((k, l() -> f
}
class d
}
class i: d, g {
l func d() -> f {
m ""
}
}
}
func m<j n j: g, j: d
let l = h
l()
f
protocol l : f { func f
protocol g
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
protocol f {
k g d {
k d
k k
}
j j<l : d> : d {
k , d>
}
class f: f {
}
class B : l {
}
k l = B
class f<i : f
)
func n<w>() -> (w, w -> w) -> w {
o m o.q = {
}
{
w) {
k }
}
protocol n {
class func q()
}
class o: n{ class func q {}
func p(e: Int = x) {
}
let c = p
c()
func r<o: y, s q n<s> ==(r(t))
protocol p : p {
}
protocol p {
class func c()
}
class e: p {
class func c() { }
}
(e() u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) {
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
i)
import Foundation
class q<k>: NSObject {
var j: k
e ^(l: m, h) -> h {
f !(l)
}
protocol l {
d g n()
}
class h: l {
class g n() { }
}
(h() o l).p.n()
class l<n : h,
q
var m: Int -> Int = {
n $0
o: Int = { d, l f
n l(d)
}(k, m)
protocol j {
typealias d
typealias n = d
typealias l = d}
class g<q : l, m : l p q.g == m> : j {
}
class g<q, m> {
}
protocol l {
typealias g
d)
func e(h: b) -> <f>(() -> f) -> b {
return { c):h())" }
}
func b<d {
enum b {
func c
var _ = c
}
}
}
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
p d
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class r {
typealias n = n
struct c<e> {
let d: i h
}
func f(h: b) -> <e>(()-> e
func d(b: String-> <c>() -> c)
class A<T : A> {
}
class a {
typealias b = b
}
b
protocol d : b { func b
func d(e: = { (g: h, f: h -> h) -> h in
return f(g)
}
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
func a<d>() -> [c{ enum b {
case c
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
d ""
e}
class d {
func b((Any, d)typealias b = b
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
func r<t>() {
f f {
i i
}
}
struct i<o : u> {
o f: o
}
func r<o>() -> [i<o>] {
p []
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
typealias h = n
protocol g {
func i() -> l func o() -> m {
q""
}
}
func j<t k t: g, t: n>(s: t) {
s.i()
}
protocol r {
}
protocol f : r {
}
protocol i : r {
}
j
protocol a {
}
protocol h : a {
}
protocol k : a {
}
protocol g {
j n = a
}
struct n : g {
j n = h
}
func i<h : h, f : g m f.n == h> (g: f) {
}
func i<n : g m n.n = o) {
}
let k = a
k()
h
protocol k : h { func h
k
protocol a : a {
}
func b(c) -> <d>(() -> d) {
}
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
self.b = b
}
}
protocol A {
typealias B
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
}
}
protocol l {
class func i()
}
class o: l{ class func i {}
class h: h {
}
class m : C {
}
typealias C = m
func s<S: y, t i o<t> == S.k.b>(r : S) -> t? {
j (u : t?) q r {
l let g = u {
p g
}
}
p v
}
let r : [n?] = [w o = h
typealias h = x<g<h
struct l<e : Sequence> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
class A<T : A> {
}
func c<d {
enum c {
func e
var _ = e
}
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicl A {
{
typealias b = b
d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}}
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
class f<d : d, j : d k d.l == j> {
}
protocol d {
i l
i i
}
struct l<l : d> : d {
i j i() {
l.i()
}
}
protocol f {
}
protocol d : f {
func i(f: g) -> <j>(() -> j) -> g { func g
k, l {
typealias l = m<k<m>, f>
}
class j {
func y((Any, j))(v: (Any, AnyObject)) {
y(v)
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
({})
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
u n
}
y q<x> {
s w(x, () -> ())
}
o n {
func j() p
}
class r {
func s() -> p {
t ""
}
}
class w: r, n {
k v: ))] = []
}
class n<x : n>
func p<p>() -> (p, p -> p) -> p {
l c l.l = {
}
{
p) {
(e: o, h:o) -> e
})
}
j(k(m, k(2, 3)))
func l(p: j) -> <n>(() -> n
}
e
protocol h : e { func e
func r(d: t, k: t) -> (((t, t) -> t) -i g {
p m
func e(m)
}
struct e<j> : g {
func e(
h s: n -> n = {
return $u
}
l o: n = { (d: n, o: n -> n) -> n q
return o(d)
}
class A: A {
}
class B : C {
}
typealias C = B
n)
func f<o>() -> (o, o -> o) -> o {
o m o.j = {
}
{
o) {
r }
}
p q) {
}
o m = j
m()
class m {
func r((Any, m))(j: (Any, AnyObject)) {
r(j)
}
}
func m<o {
r m {
func n
n _ = n
}
}
class k<l : k
w
class x<u>: d {
l i: u
init(i: u) {
o.i = j {
r { w s "\(f): \(w())" }
}
protocol h {
q k {
t w
}
w
protocol k : w { func v <h: h m h.p == k>(l: h.p) {
}
}
protocol h {
n func w(w:
}
class h<u : h> {
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
u) {
o }
}
s m {
class func s()
}
class p: m{ class func s {}
s p {
func m() -> String
}
class n {
func p() -> String {
q ""
}
}
class e: n, p {
v func> String {
q ""
}
{
r m = m
}
func s<o : m, o : p o o.m == o> (m: o) {
}
func s<v : p o v.m == m> (u: String) -> <t>(() -> t) -
struct c<d: Sequence, b where Optional<b> == d.Iterator.Element>
func f<m>() -> (m, m -> m) -> m {
e c e.i = {
}
{
m) {
n }
}
protocol f {
class func i()
}
class e: f{ class func i {}
func n<j>() -> (j, j -> j) -> j {
var m: ((j> j)!
f m
}
protocol k {
typealias m
}
struct e<j : k> {n: j
let i: j.m
}
l
({})
protocol f : f {
}
func h<d {
enum h {
func e
var _ = e
}
}
protocol e {
e func e()
}
struct h {
var d: e.h
func e() {
d.e()
}
}
protocol f {
i []
}
func f<g>() -> (g, g -> g) -> g
struct c<d : Sequence> {
var b: [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type
func e() {
d.e()
}
}
b
protocol c : b { func b
otocol A {
E == F>(f: B<T>)
}
struct }
}
func a(b: Int = 0) {
}
let c = a
c()
protocol p {
class func g()
}
class h: p {
class func g() { }
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
o t = p
}
struct h : n {
t : n q m.t == m> (h: m) {
}
func q<t : n q t.t == g> (h: t) {
}
q(h())
func r(g: m) -> <s>(() -> s) -> n
}func h(c: j) -> <i>(() -> i) -> b {
f j = e
func j<i k i.l == j>(d: B<i>)
f g
}
struct d<i : b> : b {
typealias b = i
typealias g = a<d<i>i) {
}
let d = a
d()
a=d g a=d
protocol a : a {
}
class a {
typealias b = b
func b<e>(e : e) -> c { e
)
func t<v>() -> (v, v -> v) -> v {
var d: ((v, v -> v) -> v)!
q d
}
protocol t {
}
protocol d : t {
}
protocol g : t {
}
s
q l
})
}
d(t(u, t(w, y)))
protocol e {
r j
}
struct m<v : e> {
k x: v
k x: v.j
}
protocol n {
g == o>(n: m<v>) {
}
}
struct e<v> {
k t: [(v, () -> ())] = [](m)
}
struct d<x> : e {
func d(d: d.p) {
}
}
class e<v : e> {
}
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
)
var d = b
=b as c=b
func d() -> String {
return 1
k f {
typealias c
}
class g<i{
}
d(j i)
class h {
typealias i = i
}
protocol A {
func c()l k {
func l() -> g {
m ""
}
}
class C: k, A {
j func l()q c() -> g {
m ""
}
}
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
import Foundation
class Foo<T>: NSObject {
var foo: T
init(foo: T) {
B>(t: T) {
t.y) -> Any) -> Any l
k s(j, t)
}
}
func b(s: (((Any, Any) -> Any) -> Any)
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g = g
func a<T>() {
enum b {
case c
}
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
class func f()
}
class d: c{ class func f {}
struct d<c : f,f where g.i == c.i>
class k<g>: d {
var f: g
init(f: g) {
self.f = f
l. d {
typealias i = l
typealias j = j<i<l>, i>
}
class j {
typealias d = d
func f() {
({})
}
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h: j, m {
q o m() -> String {
n ""
}
o u() -> S, q> {
}
protocol u {
typealias u
}
class p {
typealias u = u
func k<q {
enum k {
func j
var _ = j
}
}
class x {
s m
func j(m)
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
let u: v.l
}
protocol y {
o= p>(r: m<v>)
}
struct D : y {
s p = Int
func y<v k r {
s m
}
class y<D> {
w <r:
func j<v x: v) {
x.k()
}
func x(j: Int = a) {
}
let k = x
func g<h>() -> (h, h -> h) -> h {
f f: ((h, h -> h) -> h)!
j f
}
protocol f {
class func j()
}
struct i {
f d: f.i
func j() {
d.j()
}
}
class g {
typealias f = f
}
func g(f: Int = k) {
}
let i = g
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
o
class w<r>: c {
init(g: r) {
n.g = g
s.init()
(t: o
struct t : o {
p v = t
}
q t<where n.v == t<v : o u m : v {
}
struct h<t, j: v where t.h == j
struct A<T> {
let a: [(T, () -> ())] = []
}
func f<r>() -> (r, r -> r) -> r {
f r f.j = {
}
{
r) {
s }
}
protocol f {
class func j()
}
class f: f{ class func j {}
protocol j {
class func m()
}
class r: j {
class func m() { }
}
(r() n j).p.m()
j=k n j=k
protocol r {
class func q()
}
s m {
m f: r.q
func q() {
f.q()
}
(l, () -> ())
}
func f<l : o>(r: l)
import Foundation
class m<j>: NSObject {
var h: j
g -> k = l $n
}
b f: _ = j() {
}
}
func k<g {
enum k {
func l
var _ = l
}
class d {
func l<j where j: h, j: d>(l: j) {
l.k()
}
func i(k: b) -> <j>(() -> j) -> b {
f { m m "\(k): \(m())" }
}
protocol h
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
}
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
protocol a {
}
protocol b : a {
}
protocol c : a {
}
protocol d {
typealias f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
i(e())
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
class func i()
}
class k: c{ class func i {
a
}
struct e : f {
i f = g
}
func i<g : g, e : f where e.f == g> (c: e) {
}
func i<h : f where h.f == c> (c: h) {
}
i(e())
class a<f : g, g alias g = g
|
apache-2.0
|
f8cea2a6c58f2ed0e6b5beb61baa3f46
| 11.96371 | 87 | 0.406454 | 2.277719 | false | false | false | false |
Shaunthehugo/Study-Buddy
|
StudyBuddy/SettingsTableViewController.swift
|
1
|
3483
|
//
// SettingsTableViewController.swift
// StudyBuddy
//
// Created by Shaun Dougherty on 2/21/16.
// Copyright © 2016 foru. All rights reserved.
//
import UIKit
import Parse
import Crashlytics
class SettingsTableViewController: UITableViewController {
@IBOutlet weak var tutorCell: UITableViewCell!
@IBOutlet weak var availablitySwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
if availablitySwitch.on {
PFUser.currentUser()!["available"] = true
PFUser.currentUser()!["availableText"] = "true"
} else {
PFUser.currentUser()!["available"] = false
PFUser.currentUser()!["availableText"] = "false"
}
PFUser.currentUser()?.saveInBackground()
tableView.beginUpdates()
tableView.endUpdates()
}
override func viewDidAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ConversationViewController.loadMessages), name: "checkStatus", object: nil)
getStatus()
if availablitySwitch.on {
PFUser.currentUser()!["available"] = true
PFUser.currentUser()!["availableText"] = "true"
} else {
PFUser.currentUser()!["available"] = false
PFUser.currentUser()!["availableText"] = "false"
}
PFUser.currentUser()?.saveInBackground()
tableView.beginUpdates()
tableView.endUpdates()
}
func getStatus() {
PFUser.currentUser()?.fetchInBackgroundWithBlock({ (object: PFObject?, error: NSError?) in
let status: Bool = PFUser.currentUser()!["available"] as! Bool
if status == true {
self.availablitySwitch.setOn(true, animated: true)
} else {
self.availablitySwitch.setOn(false, animated: true)
}
})
}
@IBAction func switchValueChanged(sender: UISwitch) {
tableView.beginUpdates()
tableView.endUpdates()
if availablitySwitch.on {
PFUser.currentUser()!["available"] = true
PFUser.currentUser()!["availableText"] = "true"
} else {
PFUser.currentUser()!["available"] = false
PFUser.currentUser()!["availableText"] = "false"
}
PFUser.currentUser()?.saveInBackground()
}
@IBAction func logOutTapped(sender: AnyObject) {
PFUser.logOutInBackgroundWithBlock { (error: NSError?) -> Void in
if error == nil {
self.performSegueWithIdentifier("LogOut", sender: self)
} else {
Crashlytics.sharedInstance().recordError(error!)
print(error?.localizedDescription)
}
}
print(PFUser.currentUser())
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 6
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 3 {
performSegueWithIdentifier("changeEmail", sender: self)
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 && PFUser.currentUser()!["tutor"] as! Bool == false {
return 0
}
return 44
}
}
|
mit
|
9df0d47adae6a2a1531e4b61d78b8fb5
| 29.017241 | 158 | 0.670017 | 4.516213 | false | false | false | false |
ahoppen/swift
|
test/type/types.swift
|
5
|
7511
|
// RUN: %target-typecheck-verify-swift
var a : Int
func test() {
var y : a // expected-error {{cannot find type 'a' in scope}}
var z : y // expected-error {{cannot find type 'y' in scope}}
var w : Swift.print // expected-error {{no type named 'print' in module 'Swift'}}
}
var b : (Int) -> Int = { $0 }
var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}}
var d2 : () -> Int = { 4 }
var d3 : () -> Float = { 4 }
var d4 : () -> Int = { d2 } // expected-error{{function 'd2' was used as a property; add () to call it}} {{26-26=()}}
if #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) {
var e0 : [Int]
e0[] // expected-error {{missing argument for parameter #1 in call}} {{6-6=<#Int#>}}
}
var f0 : [Float]
var f1 : [(Int,Int)]
var g : Swift // expected-error {{cannot find type 'Swift' in scope}} expected-note {{cannot use module 'Swift' as a type}}
var h0 : Int?
_ = h0 == nil // no-warning
var h1 : Int??
_ = h1! == nil // no-warning
var h2 : [Int?]
var h3 : [Int]?
var h3a : [[Int?]]
var h3b : [Int?]?
var h4 : ([Int])?
var h5 : ([([[Int??]])?])?
var h7 : (Int,Int)?
var h8 : ((Int) -> Int)?
var h9 : (Int?) -> Int?
var h10 : Int?.Type?.Type
var i = Int?(42)
func testInvalidUseOfParameterAttr() {
var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' may only be used on parameters}}
func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' may only be used on parameters}}
var bad_is : (Int) -> (__shared Int, Int) // expected-error {{'__shared' may only be used on parameters}}
func bad_is2(_ a: (__shared Int, Int)) {} // expected-error {{'__shared' may only be used on parameters}}
var bad_iow : (Int) -> (__owned Int, Int) // expected-error {{'__owned' may only be used on parameters}}
func bad_iow2(_ a: (__owned Int, Int)) {} // expected-error {{'__owned' may only be used on parameters}}
}
// <rdar://problem/15588967> Array type sugar default construction syntax doesn't work
func test_array_construct<T>(_: T) {
_ = [T]() // 'T' is a local name
_ = [Int]() // 'Int is a global name'
_ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name.
_ = [UnsafeMutablePointer<Int?>]() // Nesting.
_ = [([UnsafeMutablePointer<Int>])]()
_ = [(String, Float)]()
}
extension Optional {
init() {
self = .none
}
}
// <rdar://problem/15295763> default constructing an optional fails to typecheck
func test_optional_construct<T>(_: T) {
_ = T?() // Local name.
_ = Int?() // Global name
_ = (Int?)() // Parenthesized name.
}
// Test disambiguation of generic parameter lists in expression context.
struct Gen<T> {}
var y0 : Gen<Int?>
var y1 : Gen<Int??>
var y2 : Gen<[Int?]>
var y3 : Gen<[Int]?>
var y3a : Gen<[[Int?]]>
var y3b : Gen<[Int?]?>
var y4 : Gen<([Int])?>
var y5 : Gen<([([[Int??]])?])?>
var y7 : Gen<(Int,Int)?>
var y8 : Gen<((Int) -> Int)?>
var y8a : Gen<[([Int]?) -> Int]>
var y9 : Gen<(Int?) -> Int?>
var y10 : Gen<Int?.Type?.Type>
var y11 : Gen<Gen<Int>?>
var y12 : Gen<Gen<Int>?>?
var y13 : Gen<Gen<Int?>?>?
var y14 : Gen<Gen<Int?>>?
var y15 : Gen<Gen<Gen<Int?>>?>
var y16 : Gen<Gen<Gen<Int?>?>>
var y17 : Gen<Gen<Gen<Int?>?>>?
var z0 = Gen<Int?>()
var z1 = Gen<Int??>()
var z2 = Gen<[Int?]>()
var z3 = Gen<[Int]?>()
var z3a = Gen<[[Int?]]>()
var z3b = Gen<[Int?]?>()
var z4 = Gen<([Int])?>()
var z5 = Gen<([([[Int??]])?])?>()
var z7 = Gen<(Int,Int)?>()
var z8 = Gen<((Int) -> Int)?>()
var z8a = Gen<[([Int]?) -> Int]>()
var z9 = Gen<(Int?) -> Int?>()
var z10 = Gen<Int?.Type?.Type>()
var z11 = Gen<Gen<Int>?>()
var z12 = Gen<Gen<Int>?>?()
var z13 = Gen<Gen<Int?>?>?()
var z14 = Gen<Gen<Int?>>?()
var z15 = Gen<Gen<Gen<Int?>>?>()
var z16 = Gen<Gen<Gen<Int?>?>>()
var z17 = Gen<Gen<Gen<Int?>?>>?()
y0 = z0
y1 = z1
y2 = z2
y3 = z3
y3a = z3a
y3b = z3b
y4 = z4
y5 = z5
y7 = z7
y8 = z8
y8a = z8a
y9 = z9
y10 = z10
y11 = z11
y12 = z12
y13 = z13
y14 = z14
y15 = z15
y16 = z16
y17 = z17
// Type repr formation.
// <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr)
let tupleTypeWithNames = (age:Int, count:Int)(4, 5)
let dictWithTuple = [String: (age:Int, count:Int)]()
// <rdar://problem/21684837> typeexpr not being formed for postfix !
let bb2 = [Int!](repeating: nil, count: 2) // expected-warning {{using '!' is not allowed here; treating this as '?' instead}}{{15-16=?}}
// <rdar://problem/21560309> inout allowed on function return type
func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' may only be used on parameters}}
r21560309 { x in x }
// <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties
class r21949448 {
var myArray: inout [Int] = [] // expected-error {{'inout' may only be used on parameters}}
}
// SE-0066 - Standardize function type argument syntax to require parentheses
let _ : Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{12-12=)}}
let _ : inout Int -> Float // expected-error {{'inout' may only be used on parameters}}
// expected-error@-1 {{single argument function types require parentheses}} {{15-15=(}} {{18-18=)}}
func testNoParenFunction(x: Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{32-32=)}}
func testNoParenFunction(x: inout Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{35-35=(}} {{38-38=)}}
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{15-34=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{15-39=UnsafeMutableRawPointer}}
class C {
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{17-36=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{17-41=UnsafeMutableRawPointer}}
func foo3() {
let _ : UnsafePointer<Void> // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{13-32=UnsafeRawPointer}}
let _ : UnsafeMutablePointer<Void> // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{13-39=UnsafeMutableRawPointer}}
}
}
let _ : inout @convention(c) (Int) -> Int // expected-error {{'inout' may only be used on parameters}}
func foo3(inout a: Int -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{11-16=}} {{20-20=inout }}
// expected-error @-1 {{single argument function types require parentheses}} {{20-20=(}} {{23-23=)}}
func sr5505(arg: Int) -> String {
return "hello"
}
var _: sr5505 = sr5505 // expected-error {{cannot find type 'sr5505' in scope}}
typealias A = (inout Int ..., Int ... = [42, 12]) -> Void // expected-error {{'inout' must not be used on variadic parameters}}
// expected-error@-1 {{only a single element can be variadic}} {{35-39=}}
// expected-error@-2 {{default argument not permitted in a tuple type}} {{39-49=}}
|
apache-2.0
|
45cc814fd256a49fe2ec539f2d829940
| 37.321429 | 175 | 0.618027 | 3.198893 | false | false | false | false |
lixiangzhou/ZZSwiftTool
|
ZZSwiftTool/ZZSwiftTool/ZZExtension/ZZUIExtension/UIDevice+ZZExtension.swift
|
1
|
7544
|
//
// UIDevice+ZZExtension.swift
// ZZSwiftTool
//
// Created by lixiangzhou on 2017/3/21.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
public let zz_device = UIDevice.current
/// 具体参照: https://www.theiphonewiki.com/wiki/Models
fileprivate let zz_deviceVersion: (identifier: String, version: ZZDeviceVersion) = {
var systemInfo = utsname()
uname(&systemInfo)
let identifier = String(validatingUTF8: NSString(bytes: &systemInfo.machine, length: Int(_SYS_NAMELEN), encoding: String.Encoding.ascii.rawValue)!.utf8String!) ?? "unknown"
switch identifier {
/*** iPhone ***/
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return (identifier: identifier, version:ZZDeviceVersion.iPhone_4)
case "iPhone4,1", "iPhone4,2", "iPhone4,3": return (identifier: identifier, version:ZZDeviceVersion.iPhone_4S)
case "iPhone5,1", "iPhone5,2": return (identifier: identifier, version:ZZDeviceVersion.iPhone_5)
case "iPhone5,3", "iPhone5,4": return (identifier: identifier, version:ZZDeviceVersion.iPhone_5C)
case "iPhone6,1", "iPhone6,2": return (identifier: identifier, version:ZZDeviceVersion.iPhone_5S)
case "iPhone7,2": return (identifier: identifier, version:ZZDeviceVersion.iPhone_6)
case "iPhone7,1": return (identifier: identifier, version:ZZDeviceVersion.iPhone_6_Plus)
case "iPhone8,1": return (identifier: identifier, version:ZZDeviceVersion.iPhone_6S)
case "iPhone8,2": return (identifier: identifier, version:ZZDeviceVersion.iPhone_6S_Plus)
case "iPhone8,4": return (identifier: identifier, version:ZZDeviceVersion.iPhone_SE)
case "iPhone9,1", "iPhone9,3": return (identifier: identifier, version:ZZDeviceVersion.iPhone_7)
case "iPhone9,2", "iPhone9,4": return (identifier: identifier, version:ZZDeviceVersion.iPhone_7_Plus)
/*** iPad ***/
case "iPad1,1": return (identifier: identifier, version:ZZDeviceVersion.iPad)
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return (identifier: identifier, version:ZZDeviceVersion.iPad_2)
case "iPad3,1", "iPad3,2", "iPad3,3": return (identifier: identifier, version:ZZDeviceVersion.iPad_3)
case "iPad3,4", "iPad3,5", "iPad3,6": return (identifier: identifier, version:ZZDeviceVersion.iPad_4)
case "iPad4,1", "iPad4,2", "iPad4,3": return (identifier: identifier, version:ZZDeviceVersion.iPad_Air)
case "iPad5,3", "iPad5,4": return (identifier: identifier, version:ZZDeviceVersion.iPad_Air_2)
case "iPad2,5", "iPad2,6", "iPad2,7": return (identifier: identifier, version:ZZDeviceVersion.iPad_Mini)
case "iPad4,4", "iPad4,5", "iPad4,6": return (identifier: identifier, version:ZZDeviceVersion.iPad_Mini_2)
case "iPad4,7", "iPad4,8", "iPad4,9": return (identifier: identifier, version:ZZDeviceVersion.iPad_Mini_3)
case "iPad5,1", "iPad5,2": return (identifier: identifier, version:ZZDeviceVersion.iPad_Mini_4)
case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8": return (identifier: identifier, version:ZZDeviceVersion.iPad_Pro)
/*** iPod ***/
case "iPod1,1": return (identifier: identifier, version:ZZDeviceVersion.iPodTouch_1)
case "iPod2,1": return (identifier: identifier, version:ZZDeviceVersion.iPodTouch_2)
case "iPod3,1": return (identifier: identifier, version:ZZDeviceVersion.iPodTouch_3)
case "iPod4,1": return (identifier: identifier, version:ZZDeviceVersion.iPodTouch_4)
case "iPod5,1": return (identifier: identifier, version:ZZDeviceVersion.iPodTouch_5)
case "iPod7,1": return (identifier: identifier, version:ZZDeviceVersion.iPodTouch_6)
/*** Simulator ***/
case "i386", "x86_64": return (identifier: identifier, version:ZZDeviceVersion.simulator)
default: return (identifier: identifier, version:ZZDeviceVersion.unknown)
}
}()
public enum ZZDeviceType: String {
case iPhone
case iPad
case iPod
case simulator
case unknown
}
public enum ZZDeviceVersion: String {
/*** iPhone ***/
case iPhone_4
case iPhone_4S
case iPhone_5
case iPhone_5C
case iPhone_5S
case iPhone_6
case iPhone_6_Plus
case iPhone_6S
case iPhone_6S_Plus
case iPhone_SE
case iPhone_7
case iPhone_7_Plus
/*** iPad ***/
case iPad
case iPad_2
case iPad_Mini
case iPad_3
case iPad_4
case iPad_Air
case iPad_Mini_2
case iPad_Air_2
case iPad_Mini_3
case iPad_Mini_4
case iPad_Pro
/*** iPod ***/
case iPodTouch_1
case iPodTouch_2
case iPodTouch_3
case iPodTouch_4
case iPodTouch_5
case iPodTouch_6
/*** Simulator ***/
case simulator
/*** Unknown ***/
case unknown
}
public extension UIDevice {
/// 是否iPad
var zz_isPad: Bool {
return zz_type == .iPad
}
/// 是否iPhone
var zz_isPhone: Bool {
return zz_type == .iPhone
}
/// 是否iPod
var zz_isPod: Bool {
return zz_type == .iPod
}
/// 是否Simulator
var zz_isSimulator: Bool {
return zz_type == .simulator
}
/// 设备类型
var zz_type: ZZDeviceType {
let identifier = zz_deviceVersion.identifier
if identifier.contains("iPhone") {
return .iPhone
} else if identifier.contains("iPad") {
return .iPad
} else if identifier.contains("iPod") {
return .iPod
} else if identifier == "i386" || identifier == "x86_64" {
return .simulator
} else {
return .unknown
}
}
/// 设备版本
var zz_version: ZZDeviceVersion {
return zz_deviceVersion.version
}
/// 设备 identifier
var zz_identifier: String {
return zz_deviceVersion.identifier
}
/// 是否可打电话
var zz_canMakePhoneCall: Bool {
return zz_application.canOpenURL(URL(string: "tel://")!)
}
/// 设备 uuid
var zz_uuidString: String? {
return zz_device.identifierForVendor?.uuidString
}
/// 获取磁盘大小(字节),获取失败返回-1
var zz_systemSize: Double {
guard let attr = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) else {
return -1
}
guard let space = attr[FileAttributeKey.systemSize] as? Double else {
return -1
}
return space
}
/// 获取磁盘可用大小(字节),获取失败返回-1
var zz_systemFreeSize: Double {
guard let attr = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) else {
return -1
}
guard let space = attr[FileAttributeKey.systemFreeSize] as? Double else {
return -1
}
return space
}
}
|
mit
|
16756aba4d30699777574d9ce3079ac8
| 36.639594 | 176 | 0.586514 | 4.040872 | false | false | false | false |
legendecas/Rocket.Chat.iOS
|
Rocket.Chat/Controllers/Auth/AuthViewController.swift
|
1
|
7815
|
//
// AuthViewController.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/6/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import UIKit
import SafariServices
import OnePasswordExtension
final class AuthViewController: BaseViewController, AuthManagerInjected {
internal var connecting = false
var serverURL: URL!
var serverPublicSettings: AuthSettings?
@IBOutlet weak var viewFields: UIView! {
didSet {
viewFields.layer.cornerRadius = 4
viewFields.layer.borderColor = UIColor.RCLightGray().cgColor
viewFields.layer.borderWidth = 0.5
}
}
@IBOutlet weak var onePasswordButton: UIButton! {
didSet {
onePasswordButton.isHidden = !OnePasswordExtension.shared().isAppExtensionAvailable()
}
}
@IBOutlet weak var textFieldUsername: UITextField!
@IBOutlet weak var textFieldPassword: UITextField!
@IBOutlet weak var visibleViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var buttonAuthenticateGoogle: UIButton! {
didSet {
buttonAuthenticateGoogle.layer.cornerRadius = 3
}
}
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
title = serverURL.host
self.updateAuthenticationMethods()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow(_:)),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide(_:)),
name: NSNotification.Name.UIKeyboardWillHide,
object: nil
)
if !connecting {
textFieldUsername.becomeFirstResponder()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let identifier = segue.identifier else { return }
switch identifier {
case "TwoFactor":
guard let controller = segue.destination as? TwoFactorAuthenticationViewController else { break }
controller.username = textFieldUsername.text ?? ""
controller.password = textFieldPassword.text ?? ""
default:
break
}
}
// MARK: Keyboard Handlers
override func keyboardWillShow(_ notification: Notification) {
if let keyboardSize = ((notification as NSNotification).userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
visibleViewBottomConstraint.constant = keyboardSize.height
}
}
override func keyboardWillHide(_ notification: Notification) {
visibleViewBottomConstraint.constant = 0
}
// MARK: Authentication methods
fileprivate func updateAuthenticationMethods() {
guard let settings = self.serverPublicSettings else { return }
self.buttonAuthenticateGoogle.isHidden = !settings.isGoogleAuthenticationEnabled
}
internal func handleAuthenticationResponse(_ response: SocketResponse) {
stopLoading()
if response.isError() {
if let error = response.result["error"].dictionary {
// User is using 2FA
if error["error"]?.string == "totp-required" {
performSegue(withIdentifier: "TwoFactor", sender: nil)
return
}
let alert = UIAlertController(
title: localized("error.socket.default_error_title"),
message: error["message"]?.string ?? localized("error.socket.default_error_message"),
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
} else {
if let user = authManager.currentUser() {
if user.username != nil {
dismiss(animated: true, completion: nil)
} else {
performSegue(withIdentifier: "RequestUsername", sender: nil)
}
}
}
}
// MARK: Loaders
func startLoading() {
textFieldUsername.alpha = 0.5
textFieldPassword.alpha = 0.5
connecting = true
activityIndicator.startAnimating()
textFieldUsername.resignFirstResponder()
textFieldPassword.resignFirstResponder()
}
func stopLoading() {
textFieldUsername.alpha = 1
textFieldPassword.alpha = 1
connecting = false
activityIndicator.stopAnimating()
}
// MARK: IBAction
func authenticateWithUsernameOrEmail() {
let email = textFieldUsername.text ?? ""
let password = textFieldPassword.text ?? ""
startLoading()
if serverPublicSettings?.isLDAPAuthenticationEnabled ?? false {
let params = [
"ldap": true,
"username": email,
"ldapPass": password,
"ldapOptions": []
] as [String : Any]
authManager.auth(params: params, completion: self.handleAuthenticationResponse)
} else {
authManager.auth(email, password: password, completion: self.handleAuthenticationResponse)
}
}
@IBAction func buttonAuthenticateGoogleDidPressed(_ sender: Any) {
authenticateWithGoogle()
}
@IBAction func buttonTermsDidPressed(_ sender: Any) {
var components = URLComponents()
components.scheme = "https"
components.host = self.serverURL.host
if var newURL = components.url {
newURL = newURL.appendingPathComponent("terms-of-service")
let controller = SFSafariViewController(url: newURL)
present(controller, animated: true, completion: nil)
}
}
@IBAction func buttonPolicyDidPressed(_ sender: Any) {
var components = URLComponents()
components.scheme = "https"
components.host = self.serverURL.host
if var newURL = components.url {
newURL = newURL.appendingPathComponent("privacy-policy")
let controller = SFSafariViewController(url: newURL)
present(controller, animated: true, completion: nil)
}
}
@IBAction func buttonOnePasswordDidPressed(_ sender: Any) {
let siteURL = serverPublicSettings?.siteURL ?? ""
OnePasswordExtension.shared().findLogin(forURLString: siteURL, for: self, sender: sender) { [weak self] (login, _) in
if login == nil {
return
}
self?.textFieldUsername.text = login?[AppExtensionUsernameKey] as? String
self?.textFieldPassword.text = login?[AppExtensionPasswordKey] as? String
self?.authenticateWithUsernameOrEmail()
}
}
}
extension AuthViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !connecting
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if connecting {
return false
}
if textField == textFieldUsername {
textFieldPassword.becomeFirstResponder()
}
if textField == textFieldPassword {
authenticateWithUsernameOrEmail()
}
return true
}
}
|
mit
|
9b1897556308839b53142ad9a914c778
| 31.156379 | 134 | 0.620425 | 5.522261 | false | false | false | false |
darkerk/v2ex
|
V2EX/ViewControllers/CreateTopicViewController.swift
|
1
|
4603
|
//
// CreateTopicViewController.swift
// V2EX
//
// Created by darker on 2017/4/11.
// Copyright © 2017年 darker. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Moya
import PKHUD
@objc protocol CreateTopicViewControllerDelegate: class {
@objc optional func createTopicSuccess(viewcontroller: CreateTopicViewController)
}
class CreateTopicViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var textView: PlaceHolderTextView!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var textViewBottom: NSLayoutConstraint!
@IBOutlet weak var lineView: UIView!
weak var delegate: CreateTopicViewControllerDelegate?
var nodeHref: String = ""
fileprivate let disposeBag = DisposeBag()
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = AppStyle.shared.theme.tableBackgroundColor
textField.backgroundColor = AppStyle.shared.theme.tableBackgroundColor
textField.attributedPlaceholder = NSAttributedString(string: "标题", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15), NSAttributedString.Key.foregroundColor: AppStyle.shared.theme.textPlaceHolderColor])
textView.backgroundColor = AppStyle.shared.theme.tableBackgroundColor
textView.placeHolderColor = AppStyle.shared.theme.textPlaceHolderColor
if AppStyle.shared.theme == .night {
textField.keyboardAppearance = .dark
textView.keyboardAppearance = .dark
}
lineView.backgroundColor = AppStyle.shared.theme.separatorColor
let titleValid = textField.rx.text.orEmpty.map({$0.isEmpty == false}).share(replay: 1)
let contentValid = textView.rx.text.orEmpty.map({$0.isEmpty == false}).share(replay: 1)
let allValid = Observable.combineLatest(titleValid, contentValid) { $0 && $1 }.share(replay: 1)
allValid.bind(to: sendButton.rx.isEnabled).disposed(by: disposeBag)
textField.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: {[weak textView] in
textView?.becomeFirstResponder()
}).disposed(by: disposeBag)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
textField.becomeFirstResponder()
}
@IBAction func sendAction(_ sender: Any) {
guard let titleText = textField.text, let content = textView.text else {
return
}
view.endEditing(true)
HUD.show()
API.provider.request(.once).flatMap { response -> Observable<Response> in
if let once = HTMLParser.shared.once(html: response.data) {
return API.provider.request(.createTopic(nodeHref: self.nodeHref, title: titleText, content: content, once: once))
}else {
return Observable.error(NetError.message(text: "获取once失败"))
}
}.share(replay: 1).subscribe(onNext: { response in
HUD.showText("发布成功!")
self.delegate?.createTopicSuccess?(viewcontroller: self)
self.navigationController?.popViewController(animated: true)
}, onError: {error in
HUD.showText(error.message)
}).disposed(by: disposeBag)
}
@objc func keyboardWillChangeFrame(_ notification: Notification) {
guard let info = notification.userInfo as? [String: Any] else {
return
}
let frameEnd = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let duration = (info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let curve = (info[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).uintValue
let options = UIView.AnimationOptions(rawValue: curve << 16)
self.textViewBottom.constant = frameEnd.height
UIView.animate(withDuration: duration,
delay: 0,
options: options,
animations: {
self.view.layoutIfNeeded()
},
completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
fbf074511c100d0d642cde21a35d58ff
| 39.157895 | 232 | 0.657711 | 5.226027 | false | false | false | false |
mightydeveloper/swift
|
test/Parse/type_expr.swift
|
10
|
5549
|
// RUN: %target-parse-verify-swift
// Types in expression contexts must be followed by a member access or
// constructor call.
struct Foo {
struct Bar {
init() {}
static var prop: Int = 0
static func meth() {}
func instMeth() {}
}
init() {}
static var prop: Int = 0
static func meth() {}
func instMeth() {}
}
protocol Zim {
typealias Zang
init()
// TODO class var prop: Int { get }
static func meth() {} // expected-error{{protocol methods may not have bodies}}
func instMeth() {} // expected-error{{protocol methods may not have bodies}}
}
protocol Bad {
init() {} // expected-error{{protocol initializers may not have bodies}}
}
struct Gen<T> {
struct Bar { // expected-error{{nested in generic type}}
init() {}
static var prop: Int { return 0 }
static func meth() {}
func instMeth() {}
}
init() {}
static var prop: Int { return 0 }
static func meth() {}
func instMeth() {}
}
func unqualifiedType() {
_ = Foo.self
_ = Foo.self
_ = Foo()
_ = Foo.prop
_ = Foo.meth
let _ : () = Foo.meth()
_ = Foo.instMeth
_ = Foo // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{10-10=()}} expected-note{{use '.self'}} {{10-10=.self}}
_ = Foo.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{11-22=self}}
_ = Bad // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{use '.self' to reference the type object}}{{10-10=.self}}
}
func qualifiedType() {
_ = Foo.Bar.self
let _ : Foo.Bar.Type = Foo.Bar.self
let _ : Foo.Protocol = Foo.self // expected-error{{cannot use 'Protocol' with non-protocol type 'Foo'}}
_ = Foo.Bar()
_ = Foo.Bar.prop
_ = Foo.Bar.meth
let _ : () = Foo.Bar.meth()
_ = Foo.Bar.instMeth
_ = Foo.Bar // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{14-14=()}} expected-note{{use '.self'}} {{14-14=.self}}
_ = Foo.Bar.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{15-26=self}}
}
/* TODO allow '.Type' in expr context
func metaType() {
let ty = Foo.Type.self
let metaTy = Foo.Type.self
let badTy = Foo.Type
let badMetaTy = Foo.Type.dynamicType
}
*/
func genType() {
_ = Gen<Foo>.self
_ = Gen<Foo>()
_ = Gen<Foo>.prop
_ = Gen<Foo>.meth
let _ : () = Gen<Foo>.meth()
_ = Gen<Foo>.instMeth
// Misparses because generic parameter disambiguation rejects '>' not
// followed by '.' or '('
_ = Gen<Foo> // expected-error{{not a postfix unary operator}}
_ = Gen<Foo>.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{16-27=self}}
}
func genQualifiedType() {
_ = Gen<Foo>.Bar.self
_ = Gen<Foo>.Bar()
_ = Gen<Foo>.Bar.prop
_ = Gen<Foo>.Bar.meth
let _ : () = Gen<Foo>.Bar.meth()
_ = Gen<Foo>.Bar.instMeth
_ = Gen<Foo>.Bar // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{19-19=()}} expected-note{{use '.self'}} {{19-19=.self}}
_ = Gen<Foo>.Bar.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{20-31=self}}
}
func archetype<T: Zim>(_: T) {
_ = T.self
_ = T()
// TODO let prop = T.prop
_ = T.meth
let _ : () = T.meth()
_ = T // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{8-8=()}} expected-note{{use '.self'}} {{8-8=.self}}
_ = T.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{9-20=self}}
}
func assocType<T: Zim where T.Zang: Zim>(_: T) {
_ = T.Zang.self
_ = T.Zang()
// TODO _ = T.Zang.prop
_ = T.Zang.meth
let _ : () = T.Zang.meth()
_ = T.Zang // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{13-13=()}} expected-note{{use '.self'}} {{13-13=.self}}
_ = T.Zang.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{14-25=self}}
}
class B {
class func baseMethod() {}
}
class D: B {
class func derivedMethod() {}
}
func derivedType() {
let _: B.Type = D.self
_ = D.baseMethod
let _ : () = D.baseMethod()
let _: D.Type = D.self
_ = D.derivedMethod
let _ : () = D.derivedMethod()
let _: B.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}}
let _: D.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}}
let _: D.Type.Type = D.dynamicType // expected-error{{'.dynamicType' is not allowed after a type name}} {{26-37=self}}
}
// Referencing a nonexistent member or constructor should not trigger errors
// about the type expression.
func nonexistentMember() {
let cons = Foo("this constructor does not exist") // expected-error{{argument passed to call that takes no arguments}}
let prop = Foo.nonexistent // expected-error{{type 'Foo' has no member 'nonexistent'}}
let meth = Foo.nonexistent() // expected-error{{type 'Foo' has no member 'nonexistent'}}
}
protocol P {}
func meta_metatypes() {
let _: P.Protocol = P.self
_ = P.Type.self
_ = P.Protocol.self
_ = P.Protocol.Protocol.self // expected-error{{cannot use 'Protocol' with non-protocol type 'P.Protocol'}}
_ = P.Protocol.Type.self
_ = B.Type.self
}
|
apache-2.0
|
dac0a5ac7047e43eb524c5f6571617f8
| 31.261628 | 186 | 0.632907 | 3.377358 | false | false | false | false |
atrick/swift
|
test/StringProcessing/Parse/forward-slash-regex.swift
|
1
|
9865
|
// RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking
// REQUIRES: swift_in_compiler
// REQUIRES: concurrency
prefix operator / // expected-error {{prefix operator may not contain '/'}}
prefix operator ^/ // expected-error {{prefix operator may not contain '/'}}
prefix operator /^/ // expected-error {{prefix operator may not contain '/'}}
precedencegroup P {
associativity: left
}
// Fine.
infix operator /^/ : P
func /^/ (lhs: Int, rhs: Int) -> Int { 0 }
let i = 0 /^/ 1/^/3
let x = /abc/
_ = /abc/
_ = /x/.self
_ = /\//
_ = /\\/
// These unfortunately become infix `=/`. We could likely improve the diagnostic
// though.
let z=/0/
// expected-error@-1 {{type annotation missing in pattern}}
// expected-error@-2 {{consecutive statements on a line must be separated by ';'}}
// expected-error@-3 {{expected expression after unary operator}}
// expected-error@-4 {{cannot find operator '=/' in scope}}
// expected-error@-5 {{'/' is not a postfix unary operator}}
_=/0/
// expected-error@-1 {{'_' can only appear in a pattern or on the left side of an assignment}}
// expected-error@-2 {{cannot find operator '=/' in scope}}
// expected-error@-3 {{'/' is not a postfix unary operator}}
_ = /x
// expected-error@-1 {{unterminated regex literal}}
_ = !/x/
// expected-error@-1 {{cannot convert value of type 'Regex<Substring>' to expected argument type 'Bool'}}
_ = /x/! // expected-error {{cannot force unwrap value of non-optional type 'Regex<Substring>'}}
_ = /x/ + /y/ // expected-error {{binary operator '+' cannot be applied to two 'Regex<Substring>' operands}}
_ = /x/+/y/
// expected-error@-1 {{cannot find operator '+/' in scope}}
// expected-error@-2 {{'/' is not a postfix unary operator}}
// expected-error@-3 {{cannot find 'y' in scope}}
_ = /x/?.blah
// expected-error@-1 {{cannot use optional chaining on non-optional value of type 'Regex<Substring>'}}
// expected-error@-2 {{value of type 'Regex<Substring>' has no member 'blah'}}
_ = /x/!.blah
// expected-error@-1 {{cannot force unwrap value of non-optional type 'Regex<Substring>'}}
// expected-error@-2 {{value of type 'Regex<Substring>' has no member 'blah'}}
_ = /x /? // expected-error {{cannot use optional chaining on non-optional value of type 'Regex<Substring>'}}
.blah // expected-error {{value of type 'Regex<Substring>' has no member 'blah'}}
_ = 0; /x / // expected-warning {{regular expression literal is unused}}
_ = /x / ? 0 : 1 // expected-error {{cannot convert value of type 'Regex<Substring>' to expected condition type 'Bool'}}
_ = .random() ? /x / : .blah // expected-error {{type 'Regex<Substring>' has no member 'blah'}}
_ = /x/ ?? /x/ // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'Regex<Substring>', so the right side is never used}}
_ = /x / ?? /x / // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'Regex<Substring>', so the right side is never used}}
_ = /x/??/x/ // expected-error {{'/' is not a postfix unary operator}}
_ = /x/ ... /y/ // expected-error {{referencing operator function '...' on 'Comparable' requires that 'Regex<Substring>' conform to 'Comparable'}}
_ = /x/.../y/
// expected-error@-1 {{missing whitespace between '...' and '/' operators}}
// expected-error@-2 {{'/' is not a postfix unary operator}}
// expected-error@-3 {{cannot find 'y' in scope}}
_ = /x /...
// expected-error@-1 {{unary operator '...' cannot be applied to an operand of type 'Regex<Substring>'}}
// expected-note@-2 {{overloads for '...' exist with these partially matching parameter lists}}
do {
_ = true / false /; // expected-error {{expected expression after operator}}
}
_ = "\(/x/)"
func defaulted(x: Regex<Substring> = /x/) {}
func foo<T>(_ x: T, y: T) {}
foo(/abc/, y: /abc /)
func bar<T>(_ x: inout T) {}
// TODO: We split this into a prefix '&', but inout is handled specially when
// parsing an argument list. This shouldn't matter anyway, but we should at
// least have a custom diagnostic.
bar(&/x/)
// expected-error@-1 {{'&' is not a prefix unary operator}}
struct S {
subscript(x: Regex<Substring>) -> Void { () }
}
func testSubscript(_ x: S) {
x[/x/]
x[/x /]
}
func testReturn() -> Regex<Substring> {
if .random() {
return /x/
}
return /x /
}
func testThrow() throws {
throw /x / // expected-error {{thrown expression type 'Regex<Substring>' does not conform to 'Error'}}
}
_ = [/abc/, /abc /]
_ = [/abc/:/abc/] // expected-error {{generic struct 'Dictionary' requires that 'Regex<Substring>' conform to 'Hashable'}}
_ = [/abc/ : /abc/] // expected-error {{generic struct 'Dictionary' requires that 'Regex<Substring>' conform to 'Hashable'}}
_ = [/abc /:/abc /] // expected-error {{generic struct 'Dictionary' requires that 'Regex<Substring>' conform to 'Hashable'}}
_ = [/abc /: /abc /] // expected-error {{generic struct 'Dictionary' requires that 'Regex<Substring>' conform to 'Hashable'}}
_ = (/abc/, /abc /)
_ = ((/abc /))
_ = { /abc/ }
_ = {
/abc/
}
let _: () -> Int = {
0
/ 1 /
2
}
_ = {
0 // expected-warning {{integer literal is unused}}
/1 / // expected-warning {{regular expression literal is unused}}
2 // expected-warning {{integer literal is unused}}
}
// Operator chain, as a regex literal may not start with space.
_ = 2
/ 1 / .bitWidth
_ = 2
/1/ .bitWidth // expected-error {{value of type 'Regex<Substring>' has no member 'bitWidth'}}
_ = 2
/ 1 /
.bitWidth
_ = 2
/1 /
.bitWidth // expected-error {{value of type 'Regex<Substring>' has no member 'bitWidth'}}
let z =
/y/
// While '.' is technically an operator character, it seems more likely that
// the user hasn't written the member name yet.
_ = 0. / 1 / 2 // expected-error {{expected member name following '.'}}
_ = 0 . / 1 / 2 // expected-error {{expected member name following '.'}}
switch "" {
case /x/:
break
case _ where /x /:
// expected-error@-1 {{cannot convert value of type 'Regex<Substring>' to expected condition type 'Bool'}}
break
default:
break
}
do {} catch /x / {}
// expected-error@-1 {{expression pattern of type 'Regex<Substring>' cannot match values of type 'any Error'}}
// expected-error@-2 {{binary operator '~=' cannot be applied to two 'any Error' operands}}
// expected-warning@-3 {{'catch' block is unreachable because no errors are thrown in 'do' block}}
switch /x / {
default:
break
}
if /x / {} // expected-error {{cannot convert value of type 'Regex<Substring>' to expected condition type 'Bool'}}
if /x /.smth {} // expected-error {{value of type 'Regex<Substring>' has no member 'smth'}}
func testGuard() {
guard /x/ else { return } // expected-error {{cannot convert value of type 'Regex<Substring>' to expected condition type 'Bool'}}
}
for x in [0] where /x/ {} // expected-error {{cannot convert value of type 'Regex<Substring>' to expected condition type 'Bool'}}
typealias Magic<T> = T
_ = /x/ as Magic
_ = /x/ as! String // expected-warning {{cast from 'Regex<Substring>' to unrelated type 'String' always fails}}
_ = type(of: /x /)
do {
let /x / // expected-error {{expected pattern}}
}
_ = try /x/; _ = try /x /
// expected-warning@-1 2{{no calls to throwing functions occur within 'try' expression}}
_ = try? /x/; _ = try? /x /
// expected-warning@-1 2{{no calls to throwing functions occur within 'try' expression}}
_ = try! /x/; _ = try! /x /
// expected-warning@-1 2{{no calls to throwing functions occur within 'try' expression}}
_ = await /x / // expected-warning {{no 'async' operations occur within 'await' expression}}
/x/ = 0 // expected-error {{cannot assign to value: literals are not mutable}}
/x/() // expected-error {{cannot call value of non-function type 'Regex<Substring>'}}
// We treat the following as comments, as it seems more likely the user has
// written a comment and is still in the middle of writing the characters before
// it.
_ = /x// comment
// expected-error@-1 {{unterminated regex literal}}
_ = /x // comment
// expected-error@-1 {{unterminated regex literal}}
_ = /x/*comment*/
// expected-error@-1 {{unterminated regex literal}}
// These become regex literals, unless surrounded in parens.
func baz(_ x: (Int, Int) -> Int, _ y: (Int, Int) -> Int) {} // expected-note 2{{'baz' declared here}}
baz(/, /)
// expected-error@-1 {{cannot convert value of type 'Regex<Substring>' to expected argument type '(Int, Int) -> Int'}}
// expected-error@-2 {{missing argument for parameter #2 in call}}
baz(/,/)
// expected-error@-1 {{cannot convert value of type 'Regex<Substring>' to expected argument type '(Int, Int) -> Int'}}
// expected-error@-2 {{missing argument for parameter #2 in call}}
baz((/), /)
func bazbaz(_ x: (Int, Int) -> Int, _ y: Int) {}
bazbaz(/, 0)
func qux<T>(_ x: (Int, Int) -> Int, _ y: T) -> Int { 0 }
do {
_ = qux(/, 1) / 2
// expected-error@-1:15 {{cannot parse regular expression: closing ')' does not balance any groups openings}}
// expected-error@-2:19 {{expected ',' separator}}
}
do {
_ = qux(/, "(") / 2
// expected-error@-1 {{cannot convert value of type 'Regex<(Substring, Substring)>' to expected argument type '(Int, Int) -> Int'}}
// expected-error@-2:21 {{expected ',' separator}}
}
_ = qux(/, 1) // this comment tests to make sure we don't try and end the regex on the starting '/' of '//'.
let arr: [Double] = [2, 3, 4]
_ = arr.reduce(1, /) / 3
_ = arr.reduce(1, /) + arr.reduce(1, /)
// Fine.
_ = /./
// You need to escape if you want a regex literal to start with these characters.
_ = /\ /
_ = / / // expected-error {{regex literal may not start with space; add backslash to escape}} {{6-6=\}}
_ = /\)/
_ = /)/ // expected-error {{closing ')' does not balance any groups openings}}
_ = /,/
_ = /}/
_ = /]/
_ = /:/
_ = /;/
// Don't emit diagnostics here, as we re-lex.
_ = /0xG/
_ = /0oG/
_ = /"/
_ = /'/
_ = /<#placeholder#>/
|
apache-2.0
|
a5531504b7ad4b7c680ae435067d27d6
| 33.735915 | 156 | 0.641156 | 3.379582 | false | false | false | false |
breadwallet/breadwallet-ios
|
breadwallet/src/Environment.swift
|
1
|
2797
|
//
// Environment.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-06-20.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
// swiftlint:disable type_name
/// Environment Flags
struct E {
static let isTestnet: Bool = {
#if TESTNET
return true
#else
return false
#endif
}()
static let isTestFlight: Bool = {
#if TESTFLIGHT
return true
#else
return false
#endif
}()
static let isSimulator: Bool = {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}()
static let isDebug: Bool = {
#if DEBUG
return true
#else
return false
#endif
}()
static let isScreenshots: Bool = {
#if SCREENSHOTS
return true
#else
return false
#endif
}()
static let isRunningTests: Bool = {
#if DEBUG
return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
#else
return false
#endif
}()
static var isIPhone4: Bool {
#if IS_EXTENSION_ENVIRONMENT
return false
#else
return UIApplication.shared.keyWindow?.bounds.height == 480.0
#endif
}
static var isIPhone5: Bool {
#if IS_EXTENSION_ENVIRONMENT
return false
#else
let bounds = UIApplication.shared.keyWindow?.bounds
return bounds?.width == 320 && bounds?.height == 568
#endif
}
static var isIPhone6: Bool {
#if IS_EXTENSION_ENVIRONMENT
return false
#else
let bounds = UIApplication.shared.keyWindow?.bounds
return bounds?.width == 375 && bounds?.height == 667
#endif
}
static let isIPhoneX: Bool = {
#if IS_EXTENSION_ENVIRONMENT
return false
#else
return (UIScreen.main.bounds.size.height == 812.0) || (UIScreen.main.bounds.size.height == 896.0)
#endif
}()
static var isIPhone6OrSmaller: Bool {
#if IS_EXTENSION_ENVIRONMENT
return false
#else
return isIPhone6 || isIPhone5 || isIPhone4
#endif
}
static var isSmallScreen: Bool {
#if IS_EXTENSION_ENVIRONMENT
return false
#else
let bounds = UIApplication.shared.keyWindow?.bounds
return bounds?.width == 320
#endif
}
static let osVersion: String = {
let os = ProcessInfo().operatingSystemVersion
return String(os.majorVersion) + "." + String(os.minorVersion) + "." + String(os.patchVersion)
}()
}
|
mit
|
472067d52f8b90429f7aef46ae3c4e5e
| 22.495798 | 105 | 0.548999 | 4.755102 | false | true | false | false |
sjtu-meow/iOS
|
Meow/SearchResultTableView.swift
|
1
|
905
|
//
// SearchResultTableView.swift
// Meow
//
// Created by 林武威 on 2017/7/12.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import UIKit
class SearchResultTableView: UITableView, UITableViewDelegate {
class func addTo(superview: UIView) -> Self {
let view = self.init()
view.translatesAutoresizingMaskIntoConstraints=false
superview.addSubview(view)
view.leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
view.topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
view.rowHeight = UITableViewAutomaticDimension
view.estimatedRowHeight = 100
return view
}
}
|
apache-2.0
|
66667dc0a04af2c5f56398cbc812a17d
| 25.787879 | 85 | 0.684389 | 4.883978 | false | false | false | false |
coderMONSTER/iosstar
|
iOSStar/Scenes/ChatView/YDSSessionViewController.swift
|
1
|
2226
|
//
// YDSSessionViewController.swift
// iOSStar
//
// Created by sum on 2017/5/10.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class YDSSessionViewController: NTESSessionViewController {
var isbool : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.init(hexString: "FAFAFA")
self.navigationItem.rightBarButtonItem = UIBarButtonItem.creatRightBarButtonItem(title: "星聊须知", target: self, action: #selector(rightButtonClick))
// Do any additional setup after loading the view.
}
func rightButtonClick() {
// print("点击了右边的按钮吧")
let vc = BaseWebVC()
vc.loadRequest = "http://122.144.169.219:3389/talk"
vc.navtitle = "星聊须知"
self.navigationController?.pushViewController(vc, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//- (void)sendMessage:(NIMMessage *)message
override func send(_ message: NIMMessage!) {
// 消息类型 message.messageType
// self.starcode
// super.send(message)
if let phone = UserDefaults.standard.object(forKey: "phone") as? String {
let requestModel = ReduceTimeModel()
requestModel.starcode = starcode
requestModel.phone = phone
requestModel.deduct_amount = 1
AppAPIHelper.user().reduceTime(requestModel: requestModel, complete: { (response) in
super.send(message)
}, error: { (error) in
super.send(message)
})
}
}
/*
// 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.
}
*/
}
|
gpl-3.0
|
6e7ea64d2defb96009f240019e8c29ee
| 26.961538 | 154 | 0.607061 | 4.73102 | false | false | false | false |
keepcalmandcodecodecode/SweetSpinners
|
Example/SweetSpinners/ViewController.swift
|
1
|
1513
|
//
// ViewController.swift
// SweetSpinners
//
// Created by keepcalmandcodecodecode on 01/14/2016.
// Copyright (c) 2016 keepcalmandcodecodecode. All rights reserved.
//
import UIKit
import UIViewSweets
import SweetSpinners
class ViewController: UIViewController {
var showBtn:UIButton!
var isSpinnerShowing:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
showBtn = UIButton(type: .System)
showBtn.frame = CGRect(x: 0, y: 0, width: 100, height: 80)
showBtn.setTitle("Show", forState: .Normal)
showBtn.setTitle("Show", forState: .Application)
showBtn.addTarget(self, action: "show", forControlEvents: .TouchUpInside)
self.view.addSubview(showBtn)
// Do any additional setup after loading the view, typically from a nib.
}
func show(){
if(isSpinnerShowing){
SweetSpinner.hide(self.view)
isSpinnerShowing = false
} else {
SweetSpinner.show(self.view,withType:.TwoCirclesSpinner)
isSpinnerShowing = true
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
showBtn.center = CGPointMake(self.view.width/2.0,self.view.height - 100)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
e47436e42c095866dc7b62d17d87b050
| 29.877551 | 81 | 0.659617 | 4.286119 | false | false | false | false |
wireapp/wire-ios-sync-engine
|
Source/E2EE/APSSignalingKeysStore.swift
|
1
|
3106
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireTransport
import WireUtilities
public struct SignalingKeys {
let verificationKey: Data
let decryptionKey: Data
init(verificationKey: Data? = nil, decryptionKey: Data? = nil) {
self.verificationKey = verificationKey ?? NSData.secureRandomData(ofLength: APSSignalingKeysStore.defaultKeyLengthBytes)
self.decryptionKey = decryptionKey ?? NSData.secureRandomData(ofLength: APSSignalingKeysStore.defaultKeyLengthBytes)
}
}
@objcMembers
public final class APSSignalingKeysStore: NSObject {
public var apsDecoder: ZMAPSMessageDecoder!
internal var verificationKey: Data!
internal var decryptionKey: Data!
internal static let verificationKeyAccountName = "APSVerificationKey"
internal static let decryptionKeyAccountName = "APSDecryptionKey"
internal static let defaultKeyLengthBytes: UInt = 256 / 8
public init?(userClient: UserClient) {
super.init()
if let verificationKey = userClient.apsVerificationKey, let decryptionKey = userClient.apsDecryptionKey {
self.verificationKey = verificationKey
self.decryptionKey = decryptionKey
self.apsDecoder = ZMAPSMessageDecoder(encryptionKey: decryptionKey, macKey: verificationKey)
} else {
return nil
}
}
/// use this method to create new keys, e.g. for client registration or update
static func createKeys() -> SignalingKeys {
return SignalingKeys()
}
/// we previously stored keys in the key chain. use this method to retreive the previously stored values to move them into the selfClient
static func keysStoredInKeyChain() -> SignalingKeys? {
guard let verificationKey = ZMKeychain.data(forAccount: self.verificationKeyAccountName),
let decryptionKey = ZMKeychain.data(forAccount: self.decryptionKeyAccountName)
else { return nil }
return SignalingKeys(verificationKey: verificationKey, decryptionKey: decryptionKey)
}
static func clearSignalingKeysInKeyChain() {
ZMKeychain.deleteAllKeychainItems(withAccountName: self.verificationKeyAccountName)
ZMKeychain.deleteAllKeychainItems(withAccountName: self.decryptionKeyAccountName)
}
public func decryptDataDictionary(_ payload: [AnyHashable: Any]!) -> [AnyHashable: Any]! {
return self.apsDecoder.decodeAPSPayload(payload)
}
}
|
gpl-3.0
|
0ddfd1629469c46c5a16e2eab7b0d901
| 39.868421 | 141 | 0.735673 | 4.698941 | false | false | false | false |
cabarique/TheProposalGame
|
MyProposalGame/Scenes/FinaleScene.swift
|
1
|
1923
|
//
// FinaleScene.swift
// MyProposalGame
//
// Created by Luis Cabarique on 11/28/16.
// Copyright © 2016 Luis Cabarique. All rights reserved.
//
import SpriteKit
class FinaleScreen: SGScene {
let sndButtonClick = SKAction.playSoundFileNamed("button_click.wav", waitForCompletion: false)
var finaleScene:Int = 1
var background: SKSpriteNode!
override func didMoveToView(view: SKView) {
layoutScene()
}
func layoutScene() {
let buttonScale: CGFloat = 0.62
let buttonAtlas = SKTextureAtlas(named: "Button")
let homeButton = SKSpriteNode(texture: buttonAtlas.textureNamed("arrowR"))
homeButton.zPosition = 10
homeButton.alpha = 0.7
homeButton.setScale(buttonScale)
homeButton.posByCanvas(0.9, y: 0.2)
homeButton.name = "Next"
addChild(homeButton)
background = SKSpriteNode(imageNamed: "FINALE_0\(finaleScene)")
background.posByCanvas(0.5, y: 0.5)
background.setScale(0.8)
background.zPosition = -1
addChild(background)
}
override func screenInteractionStarted(location: CGPoint) {
for node in nodesAtPoint(location) {
if let theNode:SKNode = node,
let nodeName = theNode.name {
if nodeName == "Next"{
self.runAction(sndButtonClick)
nextGame(finaleScene)
}
}
}
}
private func nextGame(index: Int){
finaleScene = index + 1
if finaleScene > 2 {
let nextScene = LevelSelect(size: self.scene!.size)
nextScene.scaleMode = self.scaleMode
self.view?.presentScene(nextScene)
}else{
background.texture = SKTexture(imageNamed: "FINALE_0\(finaleScene)")
}
}
}
|
mit
|
1c005c2f3d76c3a881d6c2b4648203fa
| 26.855072 | 98 | 0.578564 | 4.449074 | false | false | false | false |
XeresRazor/Swift2Posix
|
Swift2Posix/Swift2Posix/IO/File/File.swift
|
1
|
25349
|
//
// File.swift
// Swift2Posix
//
// Created by David Green on 7/28/15.
// Copyright © 2015 David Green. All rights reserved.
//
import Darwin
public class File {
public enum FileMode: String {
case Read = "r"
case Write = "w"
case Append = "a"
case ReadExtended = "r+"
case WriteExtended = "w+"
case AppendExtended = "a+"
case WriteAccess = "wx"
case WriteExtendedAccess = "w+x"
}
public enum FileError: ErrorType {
case FileNotOpenedError
case FileOpenError
case EndOfFileError
case FileIOError(errorCode: Int)
case SeekFailedError
}
public enum SeekStyle {
case Set
case Current
case End
}
private var fileHandle: UnsafeMutablePointer<FILE> = nil
// TODO: Document all of this.
public func open(filename: String, mode: FileMode) throws {
self.fileHandle = fopen(filename, mode.rawValue)
if self.fileHandle == nil {
throw FileError.FileOpenError
}
}
public func close() {
if self.fileHandle != nil {
fclose(self.fileHandle)
self.fileHandle = nil
}
}
// MARK: - Seeking
public func tell() throws -> Int {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let position = ftell(self.fileHandle)
if position == Int(EOF) {
throw FileError.EndOfFileError
}
return position
}
public func seek(offset: Int, origin: SeekStyle) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var seekStyle: Int32
switch origin {
case .Set:
seekStyle = SEEK_SET
case .Current:
seekStyle = SEEK_CUR
case .End:
seekStyle = SEEK_END
}
let result = fseek(self.fileHandle, offset, seekStyle)
if result != 0 {
throw FileError.SeekFailedError
}
}
// MARK: - Read functionality
public func readUInt8() throws -> UInt8 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = UInt8(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readUInt8Array(count: Int) throws -> [UInt8] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [UInt8](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readInt8() throws -> Int8 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = Int8(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readInt8Array(count: Int) throws -> [Int8] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [Int8](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readUInt16() throws -> UInt16 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = UInt16(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readUInt16Array(count: Int) throws -> [UInt16] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [UInt16](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readInt16() throws -> Int16 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = Int16(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readInt16Array(count: Int) throws -> [Int16] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [Int16](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readUInt32() throws -> UInt32 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = UInt32(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readUInt32Array(count: Int) throws -> [UInt32] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [UInt32](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readInt32() throws -> Int32 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = Int32(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readInt32Array(count: Int) throws -> [Int32] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [Int32](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readUInt64() throws -> UInt64 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = UInt64(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readUInt64Array(count: Int) throws -> [UInt64] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [UInt64](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readInt64() throws -> Int64 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = Int64(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readInt64Array(count: Int) throws -> [Int64] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [Int64](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readFloat32() throws -> Float32 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = Float32(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readFloat32Array(count: Int) throws -> [Float32] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [Float32](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readFloat64() throws -> Float64 {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
var buffer = Float64(0)
let size = sizeof(buffer.dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
public func readFloat64Array(count: Int) throws -> [Float64] {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
var buffer = [Float64](count: count, repeatedValue: 0)
let size = sizeof(buffer[0].dynamicType)
let readCount = fread(&buffer, size, count, self.fileHandle)
if readCount != count {
if feof(self.fileHandle) != 0 {
throw FileError.EndOfFileError
}
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
return buffer
}
// MARK: - Read functionality
public func writeUInt8(var value: UInt8) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeUInt8Array(var values: [UInt8]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeInt8(var value: Int8) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeInt8Array(var values: [Int8]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeUInt16(var value: UInt16) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeUInt16Array(var values: [UInt16]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeInt16(var value: Int16) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeInt16Array(var values: [Int16]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeUInt32(var value: UInt32) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeUInt32Array(var values: [UInt32]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeInt32(var value: Int32) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeInt32Array(var values: [Int32]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeUInt64(var value: UInt64) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeUInt64Array(var values: [UInt64]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeInt64(var value: Int64) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeInt64Array(var values: [Int64]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeFloat32(var value: Float32) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeFloat32Array(var values: [Float32]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeFloat64(var value: Float64) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = 1
let size = sizeof(value.dynamicType)
let writeCount = fwrite(&value, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
public func writeFloat64Array(var values: [Float64]) throws {
guard self.fileHandle != nil else {
throw FileError.FileNotOpenedError
}
let count = values.count
let size = sizeof(values[0].dynamicType)
let writeCount = fwrite(&values, size, count, self.fileHandle)
if writeCount != count {
let error = ferror(self.fileHandle)
throw FileError.FileIOError(errorCode: Int(error))
}
}
}
|
mit
|
2ee9ec342aab04b292ada3b56e44813f
| 29.24821 | 70 | 0.545408 | 4.887775 | false | false | false | false |
Friend-LGA/LGSideMenuController
|
LGSideMenuController/Extensions/LGSideMenuController+GesturesHandler.swift
|
1
|
14050
|
//
// LGSideMenuController+GesturesHandler.swift
// LGSideMenuController
//
//
// The MIT License (MIT)
//
// Copyright © 2015 Grigorii Lutkov <[email protected]>
// (https://github.com/Friend-LGA/LGSideMenuController)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
extension LGSideMenuController {
// MARK: - UIGestureRecognizerDelegate -
open func gestureRecognizer(_ gesture: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
guard !self.isAnimating,
self.rootView != nil,
self.leftView != nil || self.rightView != nil else { return false }
// TODO: Make animations interraptable with this gesture using UIViewPropertyAnimator
// When min supported iOS version will be 10.0
let isLeftViewActive = self.leftView != nil && self.isLeftViewEnabled && !self.isLeftViewAlwaysVisible
let isRightViewActive = self.rightView != nil && self.isRightViewEnabled && !self.isRightViewAlwaysVisible
if gesture == self.tapGesture {
guard !self.isRootViewShowing,
(isLeftViewActive && self.shouldLeftViewHideOnTouch) ||
(isRightViewActive && self.shouldRightViewHideOnTouch),
let touchView = touch.view,
let rootContainerClipToBorderView = self.rootContainerClipToBorderView else { return false }
return touchView == rootContainerClipToBorderView
}
if gesture == self.panGestureForLeftView {
guard isLeftViewActive && self.isLeftViewSwipeGestureEnabled && self.isRightViewHidden else { return false }
let location = touch.location(in: self.view)
return isLocationInLeftSwipeableRect(location)
}
if gesture == self.panGestureForRightView {
guard isRightViewActive && self.isRightViewSwipeGestureEnabled && self.isLeftViewHidden else { return false }
let location = touch.location(in: self.view)
return isLocationInRightSwipeableRect(location)
}
return false
}
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// 1. We need to hande swipeGestureArea == .full
// 2. For some reason UINavigationController interactivePopGestureRecognizer behaviour is unpredictable,
// sometimes it is failing and sometimes it is not. Better we will have it with higher priority but predictable.
if otherGestureRecognizer == self.panGestureForLeftView ||
otherGestureRecognizer == self.panGestureForRightView ||
otherGestureRecognizer is UIScreenEdgePanGestureRecognizer {
return false
}
return true
}
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// We need to hande swipeGestureArea == .full
return otherGestureRecognizer == self.panGestureForLeftView || otherGestureRecognizer == self.panGestureForRightView
}
// MARK: - UIGestureRecognizer Targets -
@objc
open func handleTapGesture(gesture: UITapGestureRecognizer) {
guard gesture.state == .ended else { return }
if self.isLeftViewVisible {
self.hideLeftView(animated: self.shouldLeftViewHideOnTouchAnimated)
}
else if self.isRightViewVisible {
self.hideRightView(animated: self.shouldRightViewHideOnTouchAnimated)
}
}
@objc
open func handlePanGestureForLeftView(gesture: UIPanGestureRecognizer) {
// Both pan gestures can be recognized in case of swipeGestureArea == .full
guard self.isRightViewHidden else { return }
let location = gesture.location(in: self.view)
let velocity = gesture.velocity(in: self.view)
if self.isLeftViewVisibilityStable,
gesture.state == .began || gesture.state == .changed {
if self.isLeftViewShowing ? velocity.x < 0.0 : velocity.x > 0.0 {
self.leftViewGestureStartX = location.x
self.isLeftViewShowingBeforeGesture = self.isLeftViewShowing
if self.isLeftViewShowing {
self.hideLeftViewPrepare()
}
else {
self.showLeftViewPrepare(updateStatusBar: true)
}
}
}
else if self.isLeftViewVisibilityChanging,
gesture.state == .changed || gesture.state == .ended || gesture.state == .cancelled,
let leftViewGestureStartX = self.leftViewGestureStartX {
let shiftedAmount = self.isLeftViewShowingBeforeGesture ? leftViewGestureStartX - location.x : location.x - leftViewGestureStartX
let percentage = self.calculatePercentage(shiftedAmount: shiftedAmount,
viewWidth: self.leftViewWidth,
isViewShowingBeforeGesture: self.isLeftViewShowingBeforeGesture)
if gesture.state == .changed {
if velocity.x > 0.0 {
self.showLeftViewPrepare(updateStatusBar: false)
}
else if velocity.x < 0.0 {
self.hideLeftViewPrepare()
}
self.validateRootViewsTransforms(percentage: percentage)
self.validateLeftViewsTransforms(percentage: percentage)
self.validateRightViewsTransforms(percentage: percentage)
}
else if gesture.state == .ended || gesture.state == .cancelled {
if percentage == 1.0 {
// We can start showing the view and ended the gesture without moving the view even by 1%
self.showLeftViewPrepare(updateStatusBar: false)
self.showLeftViewDone()
}
else if percentage == 0.0 {
// We can start hiding the view and ended the gesture without moving the view even by 1%
self.hideLeftViewPrepare()
self.hideLeftViewDone(updateStatusBar: true)
}
else if (percentage < 1.0 && velocity.x > 0.0) || (velocity.x == 0.0 && percentage >= 0.5) {
self.showLeftViewPrepare(updateStatusBar: false)
self.showLeftViewActions(animated: true)
}
else if (percentage > 0.0 && velocity.x < 0.0) || (velocity.x == 0.0 && percentage < 0.5) {
self.hideLeftViewPrepare()
self.hideLeftViewActions(animated: true)
}
self.leftViewGestureStartX = nil
}
}
}
@objc
open func handlePanGestureForRightView(gesture: UIPanGestureRecognizer) {
// Both pan gestures can be recognized in case of swipeGestureArea == .full
guard self.isLeftViewHidden else { return }
let location = gesture.location(in: self.view)
let velocity = gesture.velocity(in: self.view)
if self.isRightViewVisibilityStable,
gesture.state == .began || gesture.state == .changed {
if self.isRightViewShowing ? velocity.x > 0.0 : velocity.x < 0.0 {
self.rightViewGestureStartX = location.x
self.isRightViewShowingBeforeGesture = self.isRightViewShowing
if self.isRightViewShowing {
self.hideRightViewPrepare()
}
else {
self.showRightViewPrepare(updateStatusBar: true)
}
}
}
else if self.isRightViewVisibilityChanging,
gesture.state == .changed || gesture.state == .ended || gesture.state == .cancelled,
let rightViewGestureStartX = self.rightViewGestureStartX {
let shiftedAmount = self.isRightViewShowingBeforeGesture ? location.x - rightViewGestureStartX : rightViewGestureStartX - location.x
let percentage = self.calculatePercentage(shiftedAmount: shiftedAmount,
viewWidth: self.rightViewWidth,
isViewShowingBeforeGesture: self.isRightViewShowingBeforeGesture)
if gesture.state == .changed {
if velocity.x < 0.0 {
self.showRightViewPrepare(updateStatusBar: false)
}
else if velocity.x > 0.0 {
self.hideRightViewPrepare()
}
self.validateRootViewsTransforms(percentage: percentage)
self.validateRightViewsTransforms(percentage: percentage)
self.validateLeftViewsTransforms(percentage: percentage)
}
else if gesture.state == .ended || gesture.state == .cancelled {
if percentage == 1.0 {
// We can start showing the view and ended the gesture without moving the view even by 1%
self.showRightViewPrepare(updateStatusBar: false)
self.showRightViewDone()
}
else if percentage == 0.0 {
// We can start hiding the view and ended the gesture without moving the view even by 1%
self.hideRightViewPrepare()
self.hideRightViewDone(updateStatusBar: true)
}
else if (percentage < 1.0 && velocity.x < 0.0) || (velocity.x == 0.0 && percentage >= 0.5) {
self.showRightViewPrepare(updateStatusBar: false)
self.showRightViewActions(animated: true)
}
else if (percentage > 0.0 && velocity.x > 0.0) || (velocity.x == 0.0 && percentage < 0.5) {
self.hideRightViewPrepare()
self.hideRightViewActions(animated: true)
}
self.rightViewGestureStartX = nil
}
}
}
// MARK: - Helpers -
private func isLocationInLeftSwipeableRect(_ location: CGPoint) -> Bool {
guard let rootContainerView = self.rootContainerView,
let leftContainerView = self.leftContainerView else { return false }
let borderX = (self.leftViewPresentationStyle.isAbove && self.isLeftViewVisible) ? leftContainerView.frame.maxX : rootContainerView.frame.minX
let originX = borderX - self.leftViewSwipeGestureRange.left
let width: CGFloat = {
if self.leftViewSwipeGestureArea == .full || self.isLeftViewVisible {
return self.view.bounds.width - originX
}
else {
return self.leftViewSwipeGestureRange.left + self.leftViewSwipeGestureRange.right
}
}()
let swipeableRect = CGRect(x: originX,
y: 0.0,
width: width,
height: self.view.bounds.height)
return swipeableRect.contains(location)
}
private func isLocationInRightSwipeableRect(_ location: CGPoint) -> Bool {
guard let rootContainerView = self.rootContainerView,
let rightContainerView = self.rightContainerView else { return false }
let borderX = (self.rightViewPresentationStyle.isAbove && self.isRightViewVisible) ? rightContainerView.frame.minX : rootContainerView.frame.maxX
let originX: CGFloat = {
if self.rightViewSwipeGestureArea == .full || self.isRightViewVisible {
return 0.0
}
else {
return borderX - self.rightViewSwipeGestureRange.left
}
}()
let width: CGFloat = {
if self.rightViewSwipeGestureArea == .full || self.isRightViewVisible {
return borderX - originX + self.rightViewSwipeGestureRange.right
}
else {
return self.rightViewSwipeGestureRange.left + self.rightViewSwipeGestureRange.right
}
}()
let swipeableRect = CGRect(x: originX,
y: 0.0,
width: width,
height: self.view.bounds.height)
return swipeableRect.contains(location)
}
private func calculatePercentage(shiftedAmount: CGFloat, viewWidth: CGFloat, isViewShowingBeforeGesture: Bool) -> CGFloat {
var percentage = shiftedAmount / viewWidth
if percentage < 0.0 {
percentage = 0.0
}
else if percentage > 1.0 {
percentage = 1.0
}
if isViewShowingBeforeGesture {
percentage = 1.0 - percentage
}
return percentage
}
}
|
mit
|
afc780ed4cfc5b1de0feb5d570efe5c2
| 43.6 | 162 | 0.608869 | 5.224619 | false | false | false | false |
juvs/FormValidators
|
Example/Tests/Tests.swift
|
1
|
1164
|
// https://github.com/Quick/Quick
import Quick
import Nimble
import FormValidators
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
|
mit
|
a089baa6dd1e3f5bde604a9b8a34a54a
| 22.16 | 60 | 0.360104 | 5.514286 | false | false | false | false |
gouyz/GYZBaking
|
baking/Classes/Home/Controller/GYZBusinessVC.swift
|
1
|
21952
|
//
// GYZBusinessVC.swift
// baking
// 店铺详情页
// Created by gouyz on 2017/3/27.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
import MBProgressHUD
/** 偏移方法操作枚举 */
enum headerMenuShowType:UInt {
case up = 1 // 固定在navigation上面
case buttom = 2 // 固定在navigation下面
}
class GYZBusinessVC: GYZBaseVC,UIScrollViewDelegate,GYZSegmentViewDelegate,GYZGoodsVCDelegate,GYZBusinessConmentVCDelegate,GYZBusinessDetailVCDelegate,GYZBusinessHeaderViewDelegate {
var backgroundScrollView:UIScrollView?// 底部scrollView
var menuView:GYZSegmentView!// 菜单
var headerView:GYZBusinessHeaderView!
var topView:GYZNavBarView!// 假TitleView
var tableViewArr:Array<UIScrollView> = []// 存放scrollView
var titlesArr:Array = ["商品","评价","商家"] // 存放菜单的内容
var scrollY:CGFloat = 0// 记录当偏移量
var scrollX:CGFloat = 0// 记录当偏移量
var navigaionTitle: String? // title
let goodsVC = GYZGoodsVC()
let detailVC = GYZBusinessDetailVC(style: UITableViewStyle.grouped)
/// 商家ID
var shopId: String = ""
var shopGoodsModels: GYZShopGoodsModel?
///选择的商品信息,用于定位商品位置
var selectGoodsInfo: GoodInfoModel?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named:"icon_search_white"), style: .done, target: self, action: #selector(searchClick))
setUI()
requestCartInfo()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.isTranslucent = true
// didAppear隐藏,不会让整个页面向上移动64
self.navigationController?.navigationBar.alpha = 0
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.navigationBar.isTranslucent = false
// 消失的时候恢复
self.navigationController?.navigationBar.alpha = 1
}
func setUI(){
self.automaticallyAdjustsScrollViewInsets = false
layoutBackgroundScrollView()
layoutHeaderMenuView()
layoutTopView()
}
/** 创建底部scrollView,并将tableViewController添加到上面 */
func layoutBackgroundScrollView(){
// 需要创建到高度0上,所以backgroundScrollView.y要等于-64
self.backgroundScrollView = UIScrollView(frame:CGRect(x: 0,y: 0,width: kScreenWidth,height: kScreenHeight))
self.backgroundScrollView?.isPagingEnabled = true
self.backgroundScrollView?.bounces = false
self.backgroundScrollView?.delegate = self
let floatArrCount = CGFloat(titlesArr.count)
self.backgroundScrollView?.contentSize = CGSize(width: floatArrCount*kScreenWidth,height: self.view.frame.size.height)
// 给scrollY赋初值避免一上来滑动就乱
scrollY = -kScrollHorizY // tableView自己持有的偏移量和赋值时给的偏移量符号是相反的
///添加商品view
// tableView顶部流出HeaderView和MenuView的位置
goodsVC.leftTableView.contentInset = UIEdgeInsetsMake(kScrollHorizY, 0, 0, 0 )
goodsVC.rightTableView.contentInset = UIEdgeInsetsMake(kScrollHorizY, 0, 0, 0 )
goodsVC.delegate = self
goodsVC.shopId = shopId
goodsVC.view.frame = CGRect(x: 0,y: 0, width: kScreenWidth, height: kScreenHeight)
// 将tableViewVC添加进数组方便管理
tableViewArr.append(goodsVC.rightTableView)
self.addChildViewController(goodsVC)
// 需要用到的时候再添加到view上,避免一上来就占用太多资源
backgroundScrollView?.addSubview(goodsVC.rightTableView)
backgroundScrollView?.addSubview(goodsVC.leftTableView)
backgroundScrollView?.addSubview(goodsVC.bottomView)
backgroundScrollView?.addSubview(goodsVC.topScrollView)
///添加评论
let conmentVC = GYZBusinessConmentVC(style: UITableViewStyle.plain)
// tableView顶部流出HeaderView和MenuView的位置
conmentVC.tableView.contentInset = UIEdgeInsetsMake(kScrollHorizY, 0, 0, 0 )
conmentVC.delegate = self
conmentVC.memberId = shopId
conmentVC.view.frame = CGRect(x: kScreenWidth,y: 0, width: self.view.frame.size.width, height: kScreenHeight)
// 将tableViewVC添加进数组方便管理
tableViewArr.append(conmentVC.tableView)
self.addChildViewController(conmentVC)
conmentVC.requestConmentListData()
//let detailVC = GYZBusinessDetailVC(style: UITableViewStyle.grouped)
// tableView顶部流出HeaderView和MenuView的位置
detailVC.tableView.contentInset = UIEdgeInsetsMake(kScrollHorizY, 0, 0, 0 )
detailVC.delegate = self
detailVC.view.frame = CGRect(x: 2 * kScreenWidth,y: 0, width: self.view.frame.size.width, height: kScreenHeight)
// 将tableViewVC添加进数组方便管理
tableViewArr.append(detailVC.tableView)
self.addChildViewController(detailVC)
self.view.addSubview(backgroundScrollView!)
}
/** 创建HeaderView和MenuView */
func layoutHeaderMenuView(){
// headerView
headerView = GYZBusinessHeaderView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kHeaderHight))
headerView.delegate = self
self.view.addSubview(headerView)
// MenuView
menuView = GYZSegmentView(frame:CGRect(x: 0,y: headerView.frame.maxY,width: kScreenWidth,height: kTitleHeight))
menuView.delegate = self
menuView.setUIWithArr(titlesArr)
self.view.addSubview(self.menuView)
}
// 搭建假NAvigation...
func layoutTopView(){
// 创建假Title
topView = GYZNavBarView.init(frame: CGRect(x: 0,y: 0, width: kScreenWidth, height: kTitleAndStateHeight))
self.view.addSubview(topView)
topView.backBtn.addTarget(self, action: #selector(clickBackBtn), for: .touchUpInside)
topView.rightBtn.addTarget(self, action: #selector(searchClick), for: .touchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 返回
func clickBackBtn(){
_ = navigationController?.popViewController(animated: true)
}
/// 搜索
func searchClick(){
let searchVC = GYZShopSerchGoodsVC()
searchVC.shopId = shopId
searchVC.blockGoodsInfo = { [weak self] (goodsInfo) in
self?.selectGoodsInfo = goodsInfo
self?.dealSearchResult()
}
let navVC = GYZBaseNavigationVC(rootViewController : searchVC)
self.present(navVC, animated: false, completion: nil)
}
/// 处理搜索返回的数据
///
/// - Parameter goodsInfo:
func dealSearchResult(){
if selectGoodsInfo != nil {
var selectParentIndex : Int = 0
var selectChildIndex : Int = 0
for (index,item) in goodsVC.categoryParentData.enumerated() {
if item == selectGoodsInfo?.class_member_name{
goodsVC.topScrollView.zk_itemClick(by: index)
selectParentIndex = index
break
}
}
for (index,item) in goodsVC.categoryData[selectParentIndex].enumerated() {
if item.class_member_id == selectGoodsInfo?.class_child_member_id{
selectChildIndex = index
break
}
}
for (index,item) in goodsVC.foodData[selectParentIndex][selectChildIndex].enumerated() {
if item.id == selectGoodsInfo?.id {
goodsVC.selectRightRow(row: index, section: selectChildIndex)
goodsVC.selectRow(index: selectChildIndex)
break
}
}
}
}
/// 增加收藏
func requestAddFavourite(){
weak var weakSelf = self
createHUD(message: "加载中...")
GYZNetWork.requestNetwork("User/addCollect", parameters: ["type":"1","member_id":shopId,"user_id": userDefaults.string(forKey: "userId") ?? ""], success: { (response) in
weakSelf?.hud?.hide(animated: true)
// GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
let itemInfo = data["info"]
if itemInfo["is_collect"].stringValue == "0"{
weakSelf?.headerView.favoriteBtn.backgroundColor = UIColor.clear
}else{
weakSelf?.headerView.favoriteBtn.backgroundColor = kYellowFontColor
}
}
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}, failture: { (error) in
weakSelf?.hud?.hide(animated: true)
GYZLog(error)
})
}
/** 因为频繁用到header和menu的固定,所以声明一个方法用于偷懒 */
func headerMenuViewShowType(_ showType:headerMenuShowType){
switch showType {
case .up:
menuView.frame.origin.y = kTitleAndStateHeight
headerView.frame.origin.y = -kHeaderHight+kTitleAndStateHeight
self.navigationController?.navigationBar.alpha = 1
break
case .buttom:
headerView.frame.origin.y = 0
menuView.frame.origin.y = headerView.frame.maxY
self.navigationController?.navigationBar.alpha = 0
break
}
}
// MARK:GYZBusinessDetailVCDelegate
func detailsDidScrollPassY(_ tableviewScrollY: CGFloat) {
scrollPassY(viewScrollY: tableviewScrollY)
}
///MARK: GYZBusinessConmentVCDelegate
func conmentDidScrollPassY(_ tableviewScrollY: CGFloat) {
scrollPassY(viewScrollY: tableviewScrollY)
}
// MARK:GYZGoodsVCDelegate
func goodsDidScrollPassY(_ tableviewScrollY: CGFloat) {
scrollPassY(viewScrollY: tableviewScrollY)
goodsVC.leftTableView.contentInset = UIEdgeInsetsMake(menuView.frame.maxY, 0, 0, 0 )
goodsVC.rightTableView.contentInset = UIEdgeInsetsMake(menuView.frame.maxY, 0, 0, 0 )
goodsVC.topScrollView.frame = CGRect.init(x: 0, y: menuView.frame.maxY, width: kScreenWidth, height: kTitleHeight)
}
/// 依据代理计算y值
///
/// - Parameter viewScrollY:
func scrollPassY(viewScrollY: CGFloat){
// 计算每次改变的值
let seleoffSetY = viewScrollY - scrollY
// 将scrollY的值同步
scrollY = viewScrollY
// 偏移量超出Navigation之上
if scrollY >= -kTitleHeight-kTitleAndStateHeight {
headerMenuViewShowType(.up)
}else if scrollY <= -kScrollHorizY {
// 偏移量超出Navigation之下
headerMenuViewShowType(.buttom)
}else{
// 剩下的只有需要跟随的情况了
// 将headerView的y值按照偏移量更改
headerView.frame.origin.y -= seleoffSetY
menuView.frame.origin.y = headerView.frame.maxY
// 基准线 用于当做计算0-1的..被除数..分母...
let datumLine = -kTitleHeight-kTitleAndStateHeight + kScrollHorizY
// 计算当前的值..除数...分子..
let nowY = scrollY + kTitleHeight+kTitleAndStateHeight
// 一个0-1的值
let nowAlpa = 1+nowY/datumLine
self.navigationController?.navigationBar.alpha = nowAlpa
}
}
// MARK:GYZSegmentViewDelegate
func segmentViewSelectIndex(_ index: Int) {
// 0.3秒的动画为了显得不太突兀
UIView.animate(withDuration: 0.3, animations: {
self.backgroundScrollView?.contentOffset = CGPoint(x: kScreenWidth*CGFloat(index),y: 0)
})
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 判断是否有X变动,这里只处理横向滑动
if scrollX == scrollView.contentOffset.x{
return;
}
// 当tableview滑动到很靠上的时候,下一个tableview出现时只用在menuView之下
if scrollY >= -kTitleHeight-kTitleAndStateHeight {
scrollY = -kTitleHeight-kTitleAndStateHeight
}
for (index,scroView) in tableViewArr.enumerated() {
scroView.contentOffset = CGPoint(x: 0, y: scrollY)
if index == 0 {
goodsVC.leftTableView.contentOffset = CGPoint(x: 0, y: scrollY)
}
}
// 用于改变menuView的状态
let rate = (scrollView.contentOffset.x/kScreenWidth)
self.menuView.scrollToRate(rate)
let index = Int(rate+0.7)
// +0.7的意思是 当滑动到30%的时候加载下一个tableView
backgroundScrollView?.addSubview(tableViewArr[index])
if index == 0 {
backgroundScrollView?.addSubview(goodsVC.leftTableView)
backgroundScrollView?.addSubview(goodsVC.bottomView)
backgroundScrollView?.addSubview(goodsVC.topScrollView)
if goodsVC.foodData.count > 0 && goodsVC.categoryData.count > 0{
goodsVC.leftTableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .top)
}
goodsVC.leftTableView.contentInset = UIEdgeInsetsMake(menuView.frame.maxY, 0, 0, 0 )
goodsVC.rightTableView.contentInset = UIEdgeInsetsMake(menuView.frame.maxY, 0, 0, 0 )
goodsVC.topScrollView.frame = CGRect.init(x: 0, y: menuView.frame.maxY, width: kScreenWidth, height: kTitleHeight)
}
// 记录x
scrollX = scrollView.contentOffset.x
}
/// 获取购物车信息
func requestCartInfo(){
weak var weakSelf = self
createHUD(message: "加载中...")
GYZNetWork.requestNetwork("User/myCard", parameters: ["user_id":userDefaults.string(forKey: "userId") ?? "","member_id": shopId], success: { (response) in
GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
weakSelf?.requestShopGoodsInfo()
guard let itemInfo = data["info"].array else { return }
if itemInfo.count == 0{
return
}
let memberInfo = itemInfo[0]["member_info"]
guard let goodList = memberInfo["goods_list"].array else { return }
for cart in goodList{
guard let itemInfo = cart.dictionaryObject else { return }
let model = CartModel.init(dict: itemInfo)
let goodId = model.good_id!
weakSelf?.goodsVC.selectGoodsAtts[goodId] = model.attr
weakSelf?.goodsVC.selectTotalNum += Int.init(model.num!)!
weakSelf?.goodsVC.selectTotalPrice += Float.init((model.attr?.price)!)! * Float.init(model.num!)!
let goodsModel = GoodInfoModel()
goodsModel.id = model.good_id
goodsModel.cn_name = model.cn_name
goodsModel.goods_img = model.goods_img
goodsModel.goods_thumb_img = model.goods_thumb_img
goodsModel.preferential_type = model.preferential_type
goodsModel.preferential_price = model.preferential_price
goodsModel.buy_num = model.buy_num
goodsModel.preferential_buy_num = model.preferential_buy_num
goodsModel.class_member_id = model.class_member_id
goodsModel.class_member_name = model.class_member_name
goodsModel.class_child_member_id = model.class_child_member_id
goodsModel.class_child_member_name = model.class_child_member_name
weakSelf?.goodsVC.selectGoodsItems[goodId] = goodsModel
weakSelf?.goodsVC.selectGoods[goodId] = Int.init(model.num!)!
weakSelf?.goodsVC.selectGoodsModels.append(goodsModel)
}
if weakSelf?.goodsVC.selectGoodsModels.count > 0{
weakSelf?.goodsVC.bottomView.dataSource = (weakSelf?.goodsVC.selectGoodsModels)!
}
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
// weakSelf?.hud?.hide(animated: true)
weakSelf?.requestShopGoodsInfo()
}
}, failture: { (error) in
// weakSelf?.hud?.hide(animated: true)
weakSelf?.requestShopGoodsInfo()
GYZLog(error)
})
}
/// 获取商家商品及商家信息
func requestShopGoodsInfo(){
weak var weakSelf = self
// createHUD(message: "加载中...")
GYZNetWork.requestNetwork("Goods/seachByMember", parameters: ["user_id":userDefaults.string(forKey: "userId") ?? "","member_id": shopId], success: { (response) in
weakSelf?.hud?.hide(animated: true)
GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
guard let itemInfo = data["info"].dictionaryObject else { return }
weakSelf?.shopGoodsModels = GYZShopGoodsModel.init(dict: itemInfo)
weakSelf?.setGoodsData()
weakSelf?.navigaionTitle = weakSelf?.shopGoodsModels?.member_info?.company_name
// 给title赋值..我也不知道为什么突然只能用这种方式赋值了,需要研究一下
weakSelf?.navigationController?.navigationBar.topItem?.title = weakSelf?.navigaionTitle
// 给假的title赋值
weakSelf?.topView.titleLab.text = weakSelf?.navigaionTitle
weakSelf?.setDetailsData()
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}
}, failture: { (error) in
weakSelf?.hud?.hide(animated: true)
GYZLog(error)
})
}
/// 设置商品数据
func setGoodsData(){
headerView.dataModel = shopGoodsModels
if shopGoodsModels?.goods?.count > 0 {
let model: GoodsCategoryModel = (shopGoodsModels?.goods![0].goods_class)!
var parentId: String = model.parent_class_id!
goodsVC.categoryParentData.append(model.parent_class_name!)
var childs: [GoodsCategoryModel] = [GoodsCategoryModel]()
var goods: [[GoodInfoModel]] = [[GoodInfoModel]]()
for (index,item) in (shopGoodsModels?.goods?.enumerated())! {
// if item.goods_list!.count == 0 {
// continue
// }
let categoryModel: GoodsCategoryModel = item.goods_class!
if parentId != categoryModel.parent_class_id {
parentId = categoryModel.parent_class_id!
goodsVC.categoryParentData.append(categoryModel.parent_class_name!)
///增加子类
goodsVC.categoryData.append(childs)
childs.removeAll()
goodsVC.foodData.append(goods)
goods.removeAll()
}
childs.append(categoryModel)
goods.append(item.goods_list!)
///最后一项时添加子类
if index == (shopGoodsModels?.goods?.count)! - 1 {
///增加子类
goodsVC.categoryData.append(childs)
childs.removeAll()
goodsVC.foodData.append(goods)
goods.removeAll()
}
}
goodsVC.shopInfo = shopGoodsModels?.member_info
goodsVC.changeBottomView()
goodsVC.topScrollView.zk_setItems(goodsVC.categoryParentData)
goodsVC.leftTableView.reloadData()
goodsVC.rightTableView.reloadData()
if goodsVC.foodData.count > 0 && goodsVC.categoryData.count > 0{
if selectGoodsInfo == nil {
goodsVC.leftTableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .top)
}else{
dealSearchResult()
}
}
}
}
/// 设置商家详情数据
func setDetailsData(){
detailVC.shopInfo = shopGoodsModels?.member_info
detailVC.tableView.reloadData()
}
///MARK GYZBusinessHeaderViewDelegate
func didFavouriteBusiness() {
requestAddFavourite()
}
}
|
mit
|
be8dea11db131af0f6f872d53cbedf0c
| 38.936782 | 182 | 0.587423 | 4.694213 | false | false | false | false |
taktem/TAKSwiftSupport
|
TAKSwiftSupport/Math/Easing.swift
|
1
|
1896
|
//
// Easing.swift
// TAKSwiftSupport
//
// Created by 西村 拓 on 2015/11/10.
// Copyright © 2015年 TakuNishimura. All rights reserved.
//
import UIKit
public enum EasingType: String {
case Unknown = "Unknown"
case NoAnimation = "NoAnimation"
case Linear = "Linear"
case EaseInOut = "EaseInOut"
}
/// イージングタイプと時間パラメータを指定して値と取得する
public class Easing: NSObject {
public class func timeToEasingCarve(
type type: EasingType,
time: CGFloat,
startValue: CGFloat,
changeValue: CGFloat,
duration: CGFloat) -> CGFloat {
let time = time < 0.0 ? time : 0.0
switch type {
case .Unknown:
return startValue
case .NoAnimation:
return changeValue
case .Linear:
return timeToEasingCarveLinear(
time: time,
startValue: startValue,
changeValue: changeValue,
duration: duration)
case .EaseInOut:
return timeToEasingCarveEaseInOut(
time: time,
startValue: startValue,
changeValue: changeValue,
duration: duration)
}
}
/**
Linear
*/
private class func timeToEasingCarveLinear(
time time: CGFloat,
startValue: CGFloat,
changeValue: CGFloat,
duration: CGFloat) -> CGFloat {
return changeValue / duration * time + startValue
}
/**
EaseInOut
*/
private class func timeToEasingCarveEaseInOut(
time time: CGFloat,
startValue: CGFloat,
changeValue: CGFloat,
duration: CGFloat) -> CGFloat {
return changeValue / duration * time + startValue
}
}
|
mit
|
b6b5226efdc87aa3f27e4d32b61202b4
| 24.109589 | 61 | 0.54719 | 4.980978 | false | false | false | false |
mas-cli/mas
|
Tests/MasKitTests/Formatters/AppListFormatterSpec.swift
|
1
|
2072
|
//
// AppListFormatterSpec.swift
// MasKitTests
//
// Created by Ben Chatelain on 8/23/2020.
// Copyright © 2020 mas-cli. All rights reserved.
//
import Nimble
import Quick
@testable import MasKit
public class AppListsFormatterSpec: QuickSpec {
override public func spec() {
// static func reference
let format = AppListFormatter.format(products:)
var products: [SoftwareProduct] = []
beforeSuite {
MasKit.initialize()
}
describe("app list formatter") {
beforeEach {
products = []
}
it("formats nothing as empty string") {
let output = format(products)
expect(output) == ""
}
it("can format a single product") {
let product = SoftwareProductMock(
appName: "Awesome App",
bundleIdentifier: "",
bundlePath: "",
bundleVersion: "19.2.1",
itemIdentifier: 12345
)
let output = format([product])
expect(output) == "12345 Awesome App (19.2.1)"
}
it("can format two products") {
products = [
SoftwareProductMock(
appName: "Awesome App",
bundleIdentifier: "",
bundlePath: "",
bundleVersion: "19.2.1",
itemIdentifier: 12345
),
SoftwareProductMock(
appName: "Even Better App",
bundleIdentifier: "",
bundlePath: "",
bundleVersion: "1.2.0",
itemIdentifier: 67890
),
]
let output = format(products)
expect(output) == "12345 Awesome App (19.2.1)\n67890 Even Better App (1.2.0)"
}
}
}
}
|
mit
|
980c6d8bdacdf10399e00b6eae11bf69
| 31.359375 | 111 | 0.441816 | 5.46438 | false | false | false | false |
myhyazid/WordPress-iOS
|
WordPress/Classes/Extensions/NSAttributedString+Helpers.swift
|
8
|
1609
|
import Foundation
extension NSAttributedString
{
/**
Note:
This method will embed a collection of assets, in the specified NSRange's. Since NSRange is an ObjC struct,
you'll need to wrap it up into a NSValue instance!
*/
public func stringByEmbeddingImageAttachments(embeds: [NSValue: UIImage]?) -> NSAttributedString {
// Allow nil embeds: behave as a simple NO-OP
if embeds == nil {
return self
}
// Proceed embedding!
let unwrappedEmbeds = embeds!
let theString = self.mutableCopy() as! NSMutableAttributedString
var rangeDelta = 0
for (value, image) in unwrappedEmbeds {
let imageAttachment = NSTextAttachment()
imageAttachment.bounds = CGRect(origin: CGPointZero, size: image.size)
imageAttachment.image = image
// Each embed is expected to add 1 char to the string. Compensate for that
let attachmentString = NSAttributedString(attachment: imageAttachment)
var correctedRange = value.rangeValue
correctedRange.location += rangeDelta
// Bounds Safety
let lastPosition = correctedRange.location + correctedRange.length
if lastPosition <= theString.length {
theString.replaceCharactersInRange(correctedRange, withAttributedString: attachmentString)
}
rangeDelta += attachmentString.length
}
return theString
}
}
|
gpl-2.0
|
42d10dc05f2cfcc31d44a219204a7e80
| 35.568182 | 115 | 0.604102 | 5.725979 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.