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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
norio-nomura/Base32
|
Tests/SecEncodeTransformTests/TTTDataTransformer.swift
|
1
|
2073
|
//
// TTTDataTransformer.swift
// Base32
//
// Created by 野村 憲男 on 9/25/16.
//
// Copyright (c) 2015 Norio Nomura
//
// 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 Security
#if os(macOS)
func TTTBase32EncodedString(from data: Data) -> String? {
if let transform = SecEncodeTransformCreate(kSecBase32Encoding, nil),
SecTransformSetAttribute(transform, kSecTransformInputAttributeName, data as NSData, nil),
let encodedData = SecTransformExecute(transform, nil) as? Data {
return String.init(data: encodedData, encoding: .utf8)
}
return nil
}
func TTTData(fromBase32EncodedString string: String) -> Data? {
if let data = string.data(using: .utf8) as NSData?,
let transform = SecDecodeTransformCreate(kSecBase32Encoding, nil),
SecTransformSetAttribute(transform, kSecTransformInputAttributeName, data, nil),
let decodedData = SecTransformExecute(transform, nil) as? Data {
return decodedData
}
return nil
}
#endif
|
mit
|
a51eb8cc1b4c30d0e6246aad8a4cca71
| 39.490196 | 98 | 0.736077 | 4.146586 | false | false | false | false |
coderMONSTER/iosstar
|
iOSStar/Scenes/Market/Controller/MarketFansListViewController.swift
|
1
|
4356
|
//
// MarketFansListViewController.swift
// iOSStar
//
// Created by J-bb on 17/5/17.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import MJRefresh
class MarketFansListViewController: MarketBaseViewController {
@IBOutlet weak var tableView: UITableView!
var index:Int = 0
var fansList:[OrderFansListModel]?
var isBuy = true
var isRefresh = true
override func viewDidLoad() {
super.viewDidLoad()
scrollView = tableView
tableView.bounces = true
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 450))
tableView.register(NoDataCell.self, forCellReuseIdentifier: NoDataCell.className())
tableView.register(FansListHeaderView.self, forHeaderFooterViewReuseIdentifier: "FansListHeaderView")
automaticallyAdjustsScrollViewInsets = false
requestFansList()
footer = MJRefreshAutoNormalFooter(refreshingBlock: {
self.isRefresh = false
self.requestFansList()
})
tableView.mj_footer = footer
}
func endRefres(count:Int) {
footer?.endRefreshing()
if count < 10 {
footer?.isHidden = true
}
}
func requestFansList() {
guard starCode != nil else {
return
}
let requestModel = FanListRequestModel()
requestModel.buySell = 0
requestModel.symbol = starCode!
requestModel.start = Int32(fansList?.count ?? 0)
AppAPIHelper.marketAPI().requestOrderFansList(requestModel: requestModel, complete: { (response) in
if let models = response as? [OrderFansListModel]{
if self.isRefresh {
self.fansList = models
} else {
self.fansList?.append(contentsOf: models)
}
self.endRefres(count:self.fansList!.count)
self.tableView.reloadData()
}
}) { (error) in
self.endRefres(count:1)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension MarketFansListViewController:UITableViewDelegate, UITableViewDataSource, SelectFansDelegate {
func selectAtIndex(index: Int) {
self.index = index
if index == 0 {
isBuy = true
} else {
isBuy = false
}
isRefresh = true
requestFansList()
//doSomething
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if fansList?.count ?? 0 == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: NoDataCell.className(), for: indexPath) as! NoDataCell
cell.setImageAndTitle(image: UIImage(named: "nodata_fanslist"), title: nil)
return cell
}
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "MarketSBFansCell", for: indexPath) as! MarketSBFansCell
cell.setOrderFans(model: fansList![indexPath.row], isBuy: isBuy)
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "MarketFansCell", for: indexPath) as! MarketFansCell
cell.setOrderFans(model: fansList![indexPath.row], isBuy: isBuy,index:indexPath.row)
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fansList?.count ?? 1
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "FansListHeaderView") as! FansListHeaderView
header.delegate = self
header.selectIndex(index:index)
return header
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if fansList?.count ?? 0 == 0 {
return 500
}
return 80
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 63
}
}
|
gpl-3.0
|
5ab210a2f59171d0504eef8fe74d9146
| 33.007813 | 125 | 0.620951 | 4.935374 | false | false | false | false |
vimeo/VimeoNetworking
|
Sources/Shared/Requests/Request+Channel.swift
|
1
|
2510
|
//
// Request+Channel.swift
// VimeoNetworking
//
// Created by Huebner, Rob on 4/25/16.
// Copyright © 2016 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// `Request` that returns a single `VIMChannel`
public typealias ChannelRequest = Request<VIMChannel>
/// `Request` that returns an array of `VIMChannel`
public typealias ChannelListRequest = Request<[VIMChannel]>
public extension Request {
private static var QueryKey: String { return "query" }
private static var ChannelsPath: String { return "/channels" }
/**
Create a new request to get a specific channel
- parameter channelURI: the channel's URI
- returns: a new `Request`
*/
static func getChannelRequest(forChannelURI channelURI: String) -> Request {
return Request(path: channelURI)
}
/**
Create a request to search for a channel
- parameter query: the string query to use for the search
- parameter refinements: optionally, any search refinement parameters to add to the query
- returns: a new `Request`
*/
static func queryChannels(withQuery query: String, refinements: VimeoClient.RequestParametersDictionary? = nil) -> Request {
var parameters = refinements ?? [:]
parameters[self.QueryKey] = query
return Request(path: self.ChannelsPath, parameters: parameters)
}
}
|
mit
|
1dfb9b04a62e15c93adcf5da3cbf8c7e
| 37.015152 | 128 | 0.705859 | 4.520721 | false | false | false | false |
tnantoka/Gradientor
|
Gradientor/AppDelegate.swift
|
1
|
2336
|
//
// AppDelegate.swift
// Gradientor
//
// Created by Tatsuya Tobioka on 2017/04/17.
// Copyright © 2017 tnantoka. All rights reserved.
//
import UIKit
import ReSwift
import ChameleonFramework
import Keys
import AdFooter
let mainStore = Store<AppState>(
reducer: appReducer,
state: nil
)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
setAppearance()
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = MaterialDesign.backgroundColor
let homeViewController = HomeViewController()
let navigationController = UINavigationController(rootViewController: homeViewController)
navigationController.isToolbarHidden = false
navigationController.toolbar.clipsToBounds = true
navigationController.toolbar.isTranslucent = false
navigationController.navigationBar.isTranslucent = false
navigationController.hidesNavigationBarHairline = true
AdFooter.shared.adMobAdUnitId = GradientorKeys().adMobBannerUnitID
AdFooter.shared.interstitial.adMobAdUnitId = GradientorKeys().adMobInterstitialUnitID
#if DEBUG
window?.rootViewController = navigationController
// window?.rootViewController = AdFooter.shared.wrap(navigationController)
#else
window?.rootViewController = AdFooter.shared.wrap(navigationController)
#endif
window?.makeKeyAndVisible()
AdFooter.shared.interstitial.load()
return true
}
// MARK: - Utilities
private func setAppearance() {
UINavigationBar.appearance().barTintColor = UIColor(hexString: "#F5F5F5")
UINavigationBar.appearance().tintColor = FlatBlue()
UINavigationBar.appearance().titleTextAttributes = [
NSForegroundColorAttributeName: UINavigationBar.appearance().tintColor
]
UIToolbar.appearance().barTintColor = UINavigationBar.appearance().barTintColor
UIToolbar.appearance().tintColor = UINavigationBar.appearance().tintColor
}
}
|
mit
|
fe21bf4bff988b29b1cdd7eb20f9e86d
| 32.357143 | 114 | 0.717773 | 5.866834 | false | false | false | false |
february29/Learning
|
swift/Fch_Contact/Fch_Contact/BBaseClass/BBaseConstant.swift
|
1
|
1490
|
//
// BBaseConstant.swift
// Fch_Contact
//
// Created by bai on 2017/10/31.
// Copyright © 2017年 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
/// 屏幕的宽
let BSCREENW = UIScreen.main.bounds.size.width
/// 屏幕的高
let BSCREENH = UIScreen.main.bounds.size.height
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
let isPad = UIDevice.current.userInterfaceIdiom == .pad
let isPhone = UIDevice.current.userInterfaceIdiom == .phone
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first ?? ""
let tempFolderPath = documentPath + "/temp"
/// 通知
let relodDataNotificationName = NSNotification.Name("fch_contact_reloadData")
let showAllDataNotificationName = NSNotification.Name("fch_contact_showAllData")
let changeFontNotificationName = NSNotification.Name("fch_contact_changeFont")
typealias BBaseHandler = ()->Void;
func BLocalizedString(key:String) -> String{
return Bundle.main.localizedString(forKey: key, value: nil, table: nil);
}
/// RGBA的颜色设置
func BRGBColor(r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor {
return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
/// 背景灰色
func BGlobalGrayColor() -> UIColor {
return BRGBColor(r: 240, g: 240, b: 240, a: 1)
}
/// 红色
func BGlobalRedColor() -> UIColor {
return BRGBColor(r: 166, g: 41, b: 40, a: 1.0)
}
|
mit
|
10c65186ee8737d12dd81d8da18fd73a
| 22.683333 | 109 | 0.716397 | 3.424096 | false | false | false | false |
fitpay/fitpay-ios-sdk
|
FitpaySDK/Rest/Models/CreditCard/CreditCard.swift
|
1
|
18211
|
import Foundation
@objcMembers open class CreditCard: NSObject, ClientModel, Serializable, SecretApplyable {
open var creditCardId: String?
open var userId: String?
@available(*, deprecated, message: "as of v1.0.3 - will stop being returned from the server")
open var isDefault: Bool?
open var created: String?
open var createdEpoch: TimeInterval?
open var state: TokenizationState?
open var causedBy: CreditCardInitiator?
open var cardType: String?
open var cardMetaData: CardMetadata?
open var termsAssetId: String?
open var termsAssetReferences: [TermsAssetReferences]?
open var eligibilityExpiration: String?
open var eligibilityExpirationEpoch: TimeInterval?
open var targetDeviceId: String?
open var targetDeviceType: String?
open var verificationMethods: [VerificationMethod]?
open var externalTokenReference: String?
/// Card information
///
/// parsed from encryptedData or top level object if card is from Commit
open var info: CardInfo?
open var topOfWalletAPDUCommands: [APDUCommand]?
open var tokenLastFour: String?
/// The reason a card provisioning failed. Returned in the payload of a non-apdu commit
open var provisioningFailedReason: ProvisioningFailedReason?
/// The credit card expiration month
@available(*, deprecated, message: "as of v1.3.2 - parsed into CardInfo always")
open var expMonth: Int?
/// The credit card expiration year in 4 digits
@available(*, deprecated, message: "as of v1.3.2 - parsed into CardInfo always")
open var expYear: Int?
/// returns true if acceptTermsResourceKey link is returned on the model and available to call
open var acceptTermsAvailable: Bool {
return links?[CreditCard.acceptTermsResourceKey] != nil
}
/// returns true if declineTermsResourceKey link is returned on the model and available to call
open var declineTermsAvailable: Bool {
return links?[CreditCard.declineTermsResourceKey] != nil
}
/// returns true if deactivateResourceKey link is returned on the model and available to call
open var deactivateAvailable: Bool {
return links?[CreditCard.deactivateResourceKey] != nil
}
/// returns true if reactivateResourceKey link is returned on the model and available to call
open var reactivateAvailable: Bool {
return links?[CreditCard.reactivateResourceKey] != nil
}
/// returns true if makeDefaultResourceKey link is returned on the model and available to call
open var makeDefaultAvailable: Bool {
return links?[CreditCard.makeDefaultResourceKey] != nil
}
/// returns true if transactionsResourceKey link is returned on the model and available to call
open var listTransactionsAvailable: Bool {
return links?[CreditCard.transactionsResourceKey] != nil
}
/// returns true if getVerificationMethodsKey link is returned on the model and available to call
open var verificationMethodsAvailable: Bool {
return links?[CreditCard.getVerificationMethodsKey] != nil
}
/// returns true if selectedVerificationKey link is returned on the model and available to call
open var selectedVerificationMethodAvailable: Bool {
return links?[CreditCard.selectedVerificationKey] != nil
}
/// returns the templated URL if webappCardKey link is returned on the model
open var webappCardLink: Link? {
return links?[CreditCard.webappCardKey]
}
var links: [String: Link]?
var encryptedData: String?
weak var client: RestClient? {
didSet {
verificationMethods?.forEach({ $0.client = client })
termsAssetReferences?.forEach({ $0.client = client })
cardMetaData?.client = client
}
}
// nested model to parse top of wallet commands correctly
private var offlineSeActions: OfflineSeActions?
private struct OfflineSeActions: Codable {
var topOfWallet: TopOfWallet?
struct TopOfWallet: Codable {
var apduCommands: [APDUCommand]?
}
}
private static let selfResourceKey = "self"
private static let acceptTermsResourceKey = "acceptTerms"
private static let declineTermsResourceKey = "declineTerms"
private static let deactivateResourceKey = "deactivate"
private static let reactivateResourceKey = "reactivate"
private static let makeDefaultResourceKey = "makeDefault"
private static let transactionsResourceKey = "transactions"
private static let getVerificationMethodsKey = "verificationMethods"
private static let selectedVerificationKey = "selectedVerification"
private static let webappCardKey = "webapp.card"
private enum CodingKeys: String, CodingKey {
case links = "_links"
case creditCardId
case userId
case isDefault = "default"
case created = "createdTs"
case createdEpoch = "createdTsEpoch"
case state
case causedBy
case cardType
case cardMetaData
case termsAssetId
case termsAssetReferences
case eligibilityExpiration
case eligibilityExpirationEpoch
case deviceRelationships
case encryptedData
case targetDeviceId
case targetDeviceType
case verificationMethods
case externalTokenReference
case offlineSeActions
case tokenLastFour
case provisioningFailedReason = "reason"
case expMonth
case expYear
}
// MARK: - Lifecycle
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
links = try? container.decode(.links)
creditCardId = try? container.decode(.creditCardId)
userId = try? container.decode(.userId)
created = try? container.decode(.created)
createdEpoch = try container.decode(.createdEpoch, transformer: NSTimeIntervalTypeTransform())
state = try? container.decode(.state)
causedBy = try? container.decode(.causedBy)
cardType = try? container.decode(.cardType)
cardMetaData = try? container.decode(.cardMetaData)
termsAssetId = try? container.decode(.termsAssetId)
termsAssetReferences = try? container.decode(.termsAssetReferences)
eligibilityExpiration = try? container.decode(.eligibilityExpiration)
eligibilityExpirationEpoch = try container.decode(.eligibilityExpirationEpoch, transformer: NSTimeIntervalTypeTransform())
encryptedData = try? container.decode(.encryptedData)
targetDeviceId = try? container.decode(.targetDeviceId)
targetDeviceType = try? container.decode(.targetDeviceType)
verificationMethods = try? container.decode(.verificationMethods)
externalTokenReference = try? container.decode(.externalTokenReference)
offlineSeActions = try? container.decode(.offlineSeActions)
topOfWalletAPDUCommands = offlineSeActions?.topOfWallet?.apduCommands
tokenLastFour = try? container.decode(.tokenLastFour)
provisioningFailedReason = try? container.decode(.provisioningFailedReason)
info = try? CardInfo(from: decoder)
expMonth = try? container.decode(.expMonth)
expYear = try? container.decode(.expYear)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try? container.encodeIfPresent(offlineSeActions, forKey: .offlineSeActions)
try? container.encodeIfPresent(links, forKey: .links)
try? container.encode(creditCardId, forKey: .creditCardId)
try? container.encode(userId, forKey: .userId)
try? container.encode(created, forKey: .created)
try? container.encode(createdEpoch, forKey: .createdEpoch, transformer: NSTimeIntervalTypeTransform())
try? container.encode(state, forKey: .state)
try? container.encode(causedBy, forKey: .causedBy)
try? container.encode(cardType, forKey: .cardType)
try? container.encode(cardMetaData, forKey: .cardMetaData)
try? container.encode(termsAssetId, forKey: .termsAssetId)
try? container.encode(termsAssetReferences, forKey: .termsAssetReferences)
try? container.encode(eligibilityExpiration, forKey: .eligibilityExpiration)
try? container.encode(eligibilityExpirationEpoch, forKey: .eligibilityExpirationEpoch, transformer: NSTimeIntervalTypeTransform())
try? container.encode(encryptedData, forKey: .encryptedData)
try? container.encode(targetDeviceId, forKey: .targetDeviceId)
try? container.encode(targetDeviceType, forKey: .targetDeviceType)
try? container.encode(verificationMethods, forKey: .verificationMethods)
try? container.encode(externalTokenReference, forKey: .externalTokenReference)
try? container.encode(tokenLastFour, forKey: .tokenLastFour)
try? container.encode(provisioningFailedReason, forKey: .provisioningFailedReason)
try? container.encode(expMonth, forKey: .expMonth)
try? container.encode(expYear, forKey: .expYear)
}
// MARK: - Public Functions
@available(*, deprecated, message: "as of v1.0.3")
@objc open func getIsDefault() -> Bool {
return isDefault ?? false
}
/**
Get acceptTerms url
- return acceptTerms url
*/
@objc open func getAcceptTermsUrl() -> String? {
return links?[CreditCard.acceptTermsResourceKey]?.href
}
/**
Update acceptTerms url
- param acceptTermsUrl url
*/
@objc open func setAcceptTermsUrl(acceptTermsUrl: String) {
guard let link = links?[CreditCard.acceptTermsResourceKey] else {
log.error("CREDIT_CARD: The card is not in a state to accept terms anymore")
return
}
link.href = acceptTermsUrl
}
/**
Get the the credit card. This is useful for updated the card with the most recent data and some properties change asynchronously
- parameter completion: CreditCardHandler closure
*/
@objc open func getCard(_ completion: @escaping RestClient.CreditCardHandler) {
let resource = CreditCard.selfResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(nil, composeError(resource))
return
}
client.makeGetCall(url, parameters: nil, completion: completion)
}
/**
Delete a single credit card from a user's profile. If you delete a card that is currently the default source, then the most recently added source will become the new default.
- parameter completion: DeleteCreditCardHandler closure
*/
@objc open func deleteCard(_ completion: @escaping RestClient.DeleteHandler) {
let resource = CreditCard.selfResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(composeError(resource))
return
}
client.makeDeleteCall(url, completion: completion)
}
/**
Update the details of an existing credit card
- parameter name: name
- parameter address: address
- parameter completion: UpdateCreditCardHandler closure
*/
@objc open func updateCard(name: String?, address: Address, completion: @escaping RestClient.CreditCardHandler) {
let resource = CreditCard.selfResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(nil, composeError(resource))
return
}
client.updateCreditCard(url, name: name, address: address, completion: completion)
}
/**
Indicates a user has accepted the terms and conditions presented when the credit card was first added to the user's profile
- parameter completion: AcceptTermsHandler closure
*/
@objc open func acceptTerms(_ completion: @escaping RestClient.CreditCardTransitionHandler) {
let resource = CreditCard.acceptTermsResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(false, nil, composeError(resource))
return
}
client.acceptCall(url, completion: completion)
}
/**
Indicates a user has declined the terms and conditions. Once declined the credit card will be in a final state, no other actions may be taken
- parameter completion: DeclineTermsHandler closure
*/
@objc open func declineTerms(_ completion: @escaping RestClient.CreditCardTransitionHandler) {
let resource = CreditCard.declineTermsResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(false, nil, composeError(resource))
return
}
client.acceptCall(url, completion: completion)
}
/**
Transition the credit card into a deactived state so that it may not be utilized for payment. This link will only be available for qualified credit cards that are currently in an active state.
- parameter causedBy: deactivation initiator
- parameter reason: deactivation reason
- parameter completion: DeactivateHandler closure
*/
open func deactivate(causedBy: CreditCardInitiator, reason: String, completion: @escaping RestClient.CreditCardTransitionHandler) {
let resource = CreditCard.deactivateResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(false, nil, composeError(resource))
return
}
client.activationCall(url, causedBy: causedBy, reason: reason, completion: completion)
}
/**
Transition the credit card into an active state where it can be utilized for payment. This link will only be available for qualified credit cards that are currently in a deactivated state.
- parameter causedBy: reactivation initiator
- parameter reason: reactivation reason
- parameter completion: ReactivateHandler closure
*/
open func reactivate(causedBy: CreditCardInitiator, reason: String, completion: @escaping RestClient.CreditCardTransitionHandler) {
let resource = CreditCard.reactivateResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(false, nil, composeError(resource))
return
}
client.activationCall(url, causedBy: causedBy, reason: reason, completion: completion)
}
/**
Mark the credit card as the default payment instrument. If another card is currently marked as the default, the default will automatically transition to the indicated credit card
- parameter completion: MakeDefaultHandler closure
*/
@objc open func makeDefault(deviceId: String? = nil, _ completion: @escaping RestClient.CreditCardTransitionHandler) {
let resource = CreditCard.makeDefaultResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(false, nil, composeError(resource))
return
}
client.makeCreditCardDefault(url, deviceId: deviceId, completion: completion)
}
/**
Provides a transaction history (if available) for the user, results are limited by provider.
- parameter limit: max number of profiles per page
- parameter offset: start index position for list of entities returned
- parameter completion: TransactionsHandler closure
*/
open func listTransactions(limit: Int, offset: Int, completion: @escaping RestClient.TransactionsHandler) {
let resource = CreditCard.transactionsResourceKey
guard let url = links?[resource]?.href, let client = client else {
completion(nil, composeError(resource))
return
}
client.makeGetCall(url, limit: limit, offset: offset, overrideHeaders: ["Accept": "application/vnd.fitpay-v2+json"], completion: completion)
}
/**
Provides a fresh list of available verification methods for the credit card when an issuer requires additional authentication to verify the identity of the cardholder.
- parameter completion: VerifyMethodsHandler closure
*/
open func getVerificationMethods(_ completion: @escaping RestClient.VerifyMethodsHandler) {
let resource = CreditCard.getVerificationMethodsKey
guard let url = links?[resource]?.href, let client = client else {
completion(nil, composeError(resource))
return
}
client.makeGetCall(url, parameters: nil, completion: completion)
}
/**
Provides a user selected verification method
- parameter completion: VerifyMethodsHandler closure
*/
open func getSelectedVerification(_ completion: @escaping RestClient.VerifyMethodHandler) {
let resource = CreditCard.selectedVerificationKey
guard let url = links?[resource]?.href, let client = client else {
completion(nil, composeError(resource))
return
}
client.makeGetCall(url, parameters: nil, completion: completion)
}
// MARK: - Internal Functions
func applySecret(_ secret: Foundation.Data, expectedKeyId: String?) {
info = JWE.decrypt(encryptedData, expectedKeyId: expectedKeyId, secret: secret)
}
// MARK: - Private Functions
private func composeError(_ resource: String) -> ErrorResponse? {
return ErrorResponse.clientUrlError(domain: CreditCard.self, client: client, url: links?[resource]?.href, resource: resource)
}
}
|
mit
|
66e213833af07a04e08dd7ca087fd3f9
| 40.482916 | 197 | 0.678216 | 5.151627 | false | false | false | false |
mas-cli/mas
|
Sources/MasKit/AppStore/ISStoreAccount.swift
|
1
|
2353
|
//
// ISStoreAccount.swift
// mas-cli
//
// Created by Andrew Naylor on 22/08/2015.
// Copyright (c) 2015 Andrew Naylor. All rights reserved.
//
import CommerceKit
import StoreFoundation
extension ISStoreAccount: StoreAccount {
static var primaryAccount: StoreAccount? {
var account: ISStoreAccount?
if #available(macOS 10.13, *) {
let group = DispatchGroup()
group.enter()
let accountService: ISAccountService = ISServiceProxy.genericShared().accountService
accountService.primaryAccount { (storeAccount: ISStoreAccount) in
account = storeAccount
group.leave()
}
_ = group.wait(timeout: .now() + 30)
} else {
// macOS 10.9-10.12
let accountStore = CKAccountStore.shared()
account = accountStore.primaryAccount
}
return account
}
static func signIn(username: String, password: String, systemDialog: Bool = false) throws -> StoreAccount {
var storeAccount: ISStoreAccount?
var maserror: MASError?
let accountService: ISAccountService = ISServiceProxy.genericShared().accountService
let client = ISStoreClient(storeClientType: 0)
accountService.setStoreClient(client)
let context = ISAuthenticationContext(accountID: 0)
context.appleIDOverride = username
if systemDialog {
context.appleIDOverride = username
} else {
context.demoMode = true
context.demoAccountName = username
context.demoAccountPassword = password
context.demoAutologinMode = true
}
let group = DispatchGroup()
group.enter()
// Only works on macOS Sierra and below
accountService.signIn(with: context) { success, account, error in
if success {
storeAccount = account
} else {
maserror = .signInFailed(error: error as NSError?)
}
group.leave()
}
if systemDialog {
group.wait()
} else {
_ = group.wait(timeout: .now() + 30)
}
if let account = storeAccount {
return account
}
throw maserror ?? MASError.signInFailed(error: nil)
}
}
|
mit
|
110298bd4b2e6b89c4305ef3145b11ee
| 28.049383 | 111 | 0.589885 | 4.821721 | false | false | false | false |
abunur/quran-ios
|
Quran/SQLiteAyahInfoPersistence.swift
|
1
|
2591
|
//
// AyahInfoPersistenceStorage.swift
// Quran
//
// Created by Ahmed El-Helw on 5/12/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import Foundation
import SQLite
import SQLitePersistence
struct SQLiteAyahInfoPersistence: AyahInfoPersistence, ReadonlySQLitePersistence {
fileprivate struct Columns {
let id = Expression<Int>("glyph_id")
let page = Expression<Int>("page_number")
let sura = Expression<Int>("sura_number")
let ayah = Expression<Int>("ayah_number")
let line = Expression<Int>("line_number")
let position = Expression<Int>("position")
let minX = Expression<Int>("min_x")
let maxX = Expression<Int>("max_x")
let minY = Expression<Int>("min_y")
let maxY = Expression<Int>("max_y")
}
fileprivate let glyphsTable = Table("glyphs")
fileprivate let columns = Columns()
var filePath: String { return Files.ayahInfoPath }
func getAyahInfoForPage(_ page: Int) throws -> [AyahNumber : [AyahInfo]] {
return try run { connection in
let query = glyphsTable.filter(columns.page == page)
var result = [AyahNumber: [AyahInfo]]()
for row in try connection.prepare(query) {
let ayah = AyahNumber(sura: row[columns.sura], ayah: row[columns.ayah])
var ayahInfoList = result[ayah] ?? []
ayahInfoList += [ getAyahInfoFromRow(row, ayah: ayah) ]
result[ayah] = ayahInfoList
}
return result
}
}
fileprivate func getAyahInfoFromRow(_ row: Row, ayah: AyahNumber) -> AyahInfo {
return AyahInfo(page: row[columns.page],
line: row[columns.line],
ayah: ayah,
position: row[columns.position],
minX: row[columns.minX],
maxX: row[columns.maxX],
minY: row[columns.minY],
maxY: row[columns.maxY])
}
}
|
gpl-3.0
|
5e5214c48f1672bedeab2a1d804f92e9
| 36.014286 | 87 | 0.611733 | 4.398981 | false | false | false | false |
Tatoeba/tatoeba-ios
|
Tatoeba/View Controllers/SentenceViewController.swift
|
1
|
3892
|
//
// SentenceViewController.swift
// Tatoeba
//
// Created by Jack Cook on 8/6/17.
// Copyright © 2017 Tatoeba. All rights reserved.
//
import Contacts
import CoreSpotlight
import MobileCoreServices
import UIKit
class SentenceViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Properties
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var sentence: Sentence!
private var wasPresentedModally = false
// MARK: - Types
private enum SentenceCellType {
case sentence(Sentence)
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
backButton.accessibilityLabel = TatoebaLocalizer.localize("Generic_Back")
titleLabel.text = TatoebaLocalizer.localize("Sentence_Title")
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView(frame: .zero)
if #available(iOS 9.0, *) {
let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
attributes.contentDescription = sentence.text
attributes.contentURL = URL(string: "https://tatoeba.org/sentences/show/\(sentence.id)")
attributes.identifier = "\(sentence.id)"
attributes.title = TatoebaLocalizer.localize("Sentence_Title")
let item = CSSearchableItem(uniqueIdentifier: "org.tatoeba.Tatoeba.\(sentence.id)", domainIdentifier: "sentences", attributeSet: attributes)
CSSearchableIndex.default().indexSearchableItems([item])
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if isBeingPresented {
backButton.setImage(#imageLiteral(resourceName: "Close"), for: .normal)
wasPresentedModally = true
}
}
// MARK: - Private Methods
private func cell(for indexPath: IndexPath) -> SentenceCellType {
switch indexPath.row {
case 0:
return .sentence(sentence)
default:
return .sentence(sentence.translations?[indexPath.row - 1] ?? sentence)
}
}
// MARK: - IBActions
@IBAction func backButton(_ sender: Any) {
if wasPresentedModally {
dismiss(animated: true)
} else {
navigationController?.popViewController(animated: true)
}
}
// MARK: - UITableViewDataSource Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sentence?.translations?.count ?? 0 + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch cell(for: indexPath) {
case .sentence(let sentence):
guard let cell = tableView.dequeueReusableCell(withIdentifier: SentenceCell.identifier) as? SentenceCell else {
break
}
cell.sentence = sentence
return cell
}
return UITableViewCell()
}
// MARK: - UITableViewDelegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch cell(for: indexPath) {
case .sentence(let sentence):
let maximumWidth = view.frame.size.width - SentenceCell.horizontalSpacing
return sentence.text.height(forMaxWidth: maximumWidth, withFont: .systemFont(ofSize: 16)) + SentenceCell.verticalSpacing
}
}
}
|
mit
|
ac8a2d5b0ae777bcda505333e4bf8d1d
| 31.697479 | 152 | 0.632742 | 5.293878 | false | false | false | false |
chayelheinsen/GamingStreams-tvOS-App
|
StreamCenter/HitboxChatMessageQueue.swift
|
3
|
6410
|
//
// HitboxChatMessageQueue.swift
// GamingStreamsTVApp
//
// Created by Olivier Boucher on 2015-10-20.
// Copyright © 2015 Rivus Media Inc. All rights reserved.
//
import Foundation
import UIKit
protocol HitboxChatMessageQueueDelegate {
func handleProcessedAttributedString(message: NSAttributedString)
}
class HitboxChatMessageQueue {
let opQueue : dispatch_queue_t
var processTimer : dispatch_source_t?
var timerPaused : Bool = true
let delegate : HitboxChatMessageQueueDelegate
let messageQueue : Queue<String>
let mqMutex : dispatch_semaphore_t
init(delegate : HitboxChatMessageQueueDelegate) {
self.mqMutex = dispatch_semaphore_create(1)
let queueAttr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_BACKGROUND, 0)
self.opQueue = dispatch_queue_create("com.hitbox.chatmq", queueAttr)
self.delegate = delegate
self.messageQueue = Queue<String>()
}
func addNewMessage(message : String) {
// For the data integrity - multiple threads can be accessing at the same time
dispatch_semaphore_wait(self.mqMutex, DISPATCH_TIME_FOREVER)
messageQueue.offer(message)
dispatch_semaphore_signal(self.mqMutex)
if processTimer == nil || self.timerPaused {
self.startProcessing()
}
}
func processAvailableMessages() {
var messagesArray = [String]()
// For data integrity - We do not want any thread adding messages as
// we are polling from the queue
dispatch_semaphore_wait(self.mqMutex, DISPATCH_TIME_FOREVER)
while(true){
if let message = self.messageQueue.poll() {
messagesArray.append(message)
}
else {
break
}
}
dispatch_semaphore_signal(self.mqMutex)
// We stop if there's not message to process, it will be reactivated when
// we receive a new message
if messagesArray.count == 0 {
self.stopProcessing()
return
}
for message in messagesArray {
//We need to remove ":::5"
guard let data = message[4..<message.characters.count].dataUsingEncoding(NSUTF8StringEncoding) else {
Logger.Warning("Could not remove the first 4 characters from the message\nThe message is probably corrupted\n\(message)")
return
}
do {
guard let msgJSON = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String : AnyObject] else {
Logger.Error("JSON object could not be casted as [String : AnyObject]")
return
}
if let name = msgJSON["name"] as? String, rawArgs = msgJSON["args"] as? [String] where name == "message" {
guard let argsData = rawArgs[0].dataUsingEncoding(NSUTF8StringEncoding), args = try NSJSONSerialization.JSONObjectWithData(argsData, options: .AllowFragments) as? [String : AnyObject] else {
Logger.Error("JSON object could not be casted as [String : AnyObject]")
return
}
if let method = args["method"] as? String {
switch method {
case "chatMsg" :
if let params = args["params"] as? [String : AnyObject] {
if let senderName = params["name"] as? String, text = params["text"] as? String, senderColor = params["nameColor"] as? String {
let sanitizedText = text.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
let attrString = getAttributedStringForMessage(HitboxChatMessage(senderName: senderName, senderDisplayColor: senderColor, message: sanitizedText))
delegate.handleProcessedAttributedString(attrString)
}
}
break
default:
break
}
}
}
} catch {
Logger.Error("Could not process message, JSON deserialization failed")
}
}
}
func startProcessing() {
if self.processTimer == nil && self.timerPaused {
Logger.Debug("Creating a new process timer")
self.timerPaused = false
self.processTimer = ConcurrencyHelpers.createDispatchTimer((1 * NSEC_PER_SEC)/2, leeway: (1 * NSEC_PER_SEC)/2, queue: opQueue, block: {
self.processAvailableMessages()
})
return
}
else if self.processTimer != nil && self.timerPaused {
Logger.Debug("Resuming existing process timer")
self.timerPaused = false
dispatch_resume(self.processTimer!)
return
}
Logger.Error("Conditions not met, could not start processing")
}
func stopProcessing() {
if processTimer != nil && !self.timerPaused {
Logger.Debug("Suspending process timer")
dispatch_suspend(self.processTimer!)
self.timerPaused = true
return
}
Logger.Error("Could not stop processing since timer is either nil or already paused")
}
private func getAttributedStringForMessage(message : HitboxChatMessage) -> NSAttributedString {
let attrMsg = NSMutableAttributedString(string: "\(message.senderName): \(message.message)")
let color = UIColor(hexString: "#\(message.senderDisplayColor)")
attrMsg.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: NSMakeRange(0, attrMsg.length))
attrMsg.addAttribute(NSForegroundColorAttributeName, value: color, range: NSMakeRange(0, message.senderName.characters.count))
attrMsg.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(18), range: NSMakeRange(0, attrMsg.length))
return attrMsg
}
}
|
mit
|
c811760247ea3f3e1072cc1e8b3b729c
| 42.310811 | 210 | 0.583866 | 5.223309 | false | false | false | false |
Eonil/Editor
|
Editor4/Apply.swift
|
1
|
5786
|
//
// Apply.swift
// Editor4
//
// Created by Hoon H. on 2016/04/30.
// Copyright © 2016 Eonil. All rights reserved.
//
private struct Dummy: DriverAccessible {}
private extension State {
private var driver: Driver {
get { return Dummy().driver }
}
}
extension State {
mutating func apply(action: UserAction) throws {
switch action {
case .Reset:
self = State()
case .Test(let action):
apply(action)
case .Shell(let action):
try applyOnShell((), action: action)
case .Workspace(let id, let action):
try apply(id , action: action)
case .Notify(let notification):
try apply(notification)
}
}
private mutating func apply(action: TestAction) {
switch action {
case .Test1:
print("Test1")
case .Test2CreateWorkspaceAt(let u):
// cargo
break
}
}
/// Shell is currently single, so it doesn't have an actual ID,
/// but an ID is required to be passed to shape interface consistent.
private mutating func applyOnShell(id: (), action: ShellAction) throws {
switch action {
case .Alert(let error):
// This will trigger outer loop to render the error.
throw error
default:
MARK_unimplemented()
}
}
private mutating func apply(id: WorkspaceID, action: WorkspaceAction) throws {
switch action {
case .File(let action):
try process(id) { workspaceState in
try applyOnWorkspace(&workspaceState, action: action)
}
default:
MARK_unimplemented()
}
}
private mutating func applyOnWorkspace(inout workspace: WorkspaceState, action: FileAction) throws {
switch action {
case .CreateFolderAndStartEditingName(let containerFileID, let newFileIndex, let newFolderName):
try workspace.createFolder(in: containerFileID, at: newFileIndex, with: newFolderName)
case .CreateFileAndStartEditingName(let containerFileID, let newFileIndex, let newFileName):
let newFolderState = FileState2(form: FileForm.Data,
phase: FilePhase.Editing,
name: newFileName)
let newFolderID = try workspace.files.insert(newFolderState, at: newFileIndex, to: containerFileID)
workspace.window.navigatorPane.file.selection.reset(newFolderID)
workspace.window.navigatorPane.file.editing = true
case .DeleteAllCurrentOrSelectedFiles:
let fileSequenceToDelete = workspace.window.navigatorPane.file.selection.getHighlightOrItems()
let uniqueFileIDs = Set(fileSequenceToDelete)
workspace.window.navigatorPane.file.selection.reset()
for fileID in uniqueFileIDs {
workspace.files.remove(fileID)
}
case .DeleteFiles(let fileIDs):
try workspace.deleteFiles(fileIDs)
case .SetHighlightedFile(let maybeNewFileID):
workspace.window.navigatorPane.file.selection.reset(maybeNewFileID)
case .StartEditingCurrentFileName:
guard workspace.window.navigatorPane.file.selection.getHighlightOrCurrent() != nil else { throw UserInteractionError.missingCurrentFile }
workspace.window.navigatorPane.file.editing = true
case .SetSelectedFiles(let currentFileID, let itemFileIDs):
workspace.window.navigatorPane.file.selection.reset(currentFileID, itemFileIDs)
case .Rename(let fileID, let newName):
let fileState = workspace.files[fileID]
if fileID == workspace.files.rootID {
// TODO: Support renaming of root node to rename the workspace...
MARK_unimplemented()
}
else {
let oldName = fileState.name
guard newName != oldName else { throw UserInteractionError.CannotRenameFileBecauseNewNameIsEqualToOldName }
guard workspace.files.queryAllSiblingFileStatesOf(fileID).contains({ $0.name == newName }) == false else { throw UserInteractionError.CannotRenameFileBecauseSameNameAlreadyExists }
try workspace.files.rename(fileID, to: newName)
assert(workspace.files.journal.logs.last != nil)
assert(workspace.files.journal.logs.last!.operation.isUpdate == true)
assert(workspace.files.journal.logs.last!.operation.key == fileID)
}
default:
MARK_unimplemented()
}
}
private mutating func apply(n: Notification) throws {
switch n {
case .Cargo(let n):
switch n {
case .Step(let newState):
cargo = newState
}
case .Platform(let n):
switch n {
case .ReloadWorkspace(let workspaceID, let newWorkspaceState):
assert(newWorkspaceState.location != nil)
try process(workspaceID) { workspaceState in
workspaceState = newWorkspaceState
}
}
}
}
}
private extension FileTree2 {
// private func querySuperfileStateOf(fileID: FileID2) -> FileState2? {
// guard let superfileID = self[fileID].superfileID else { return nil }
// return self[superfileID]
// }
private func queryAllSiblingFileStatesOf(fileID: FileID2) -> AnySequence<FileState2> {
guard let superfileID = self[fileID].superfileID else { return AnySequence([]) }
return AnySequence(self[superfileID].subfileIDs.map({ self[$0] }))
}
}
|
mit
|
41717cabb97774463b2156997373ea96
| 29.771277 | 196 | 0.612965 | 4.761317 | false | false | false | false |
jdbateman/Lendivine
|
Lendivine/DVNTableViewCell.swift
|
1
|
1626
|
//
// DVNTableViewCell.swift
// Lendivine
//
// Created by john bateman on 4/2/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// This base class provides common methods for a table view cell containing a loan.\
import UIKit
import CoreData
class DVNTableViewCell: UITableViewCell {
weak var parentTableView: UITableView? // The parent UITableView
weak var parentController: UITableViewController? // The parent UITableViewController
/*!
@brief Display an alert controller indicating the specified loan has already been added to the cart.
@discussion This is a convenience view function used by multiple table view cell classes in the Lendivine app.
@param (in) loan - An attempt was made to add this loan to the cart.
@param (in) controller - The parent view controller to host the alert.
*/
func showLoanAlreadyInCartAlert(loan: KivaLoan, controller: UIViewController) {
var message = "The selected loan has already been added to your cart."
if let name = loan.name {
message = "The loan requested by \(name) has already been added to your cart."
}
let alertController = UIAlertController(title: "Already in Cart", message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
// handle OK pressed in alert controller
}
alertController.addAction(okAction)
controller.presentViewController(alertController, animated: true, completion: nil)
}
}
|
mit
|
027f2b9286e0063209d303ea991bb4db
| 41.763158 | 118 | 0.690462 | 4.696532 | false | false | false | false |
lanjing99/RxSwiftDemo
|
10-combining-operators-in-practice/challenge/challenge2-2/OurPlanet/OurPlanet/CategoriesViewController.swift
|
1
|
4830
|
/*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import RxSwift
import RxCocoa
class CategoriesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
var activityIndicator: UIActivityIndicatorView!
let download = DownloadView()
let categories = Variable<[EOCategory]>([])
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator = UIActivityIndicatorView()
activityIndicator.color = .black
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: activityIndicator)
activityIndicator.startAnimating()
view.addSubview(download)
view.layoutIfNeeded()
print(download.frame)
categories
.asObservable()
.subscribe(onNext: { [weak self] _ in
DispatchQueue.main.async {
self?.tableView?.reloadData()
}
})
.addDisposableTo(disposeBag)
startDownload()
}
func startDownload() {
download.progress.progress = 0.0
download.label.text = "Download: 0%"
let eoCategories = EONET.categories
let downloadedEvents = eoCategories.flatMap { categories in
return Observable.from(categories.map { category in
EONET.events(forLast: 360, category: category)
})
}
.merge(maxConcurrent: 2)
let updatedCategories = eoCategories.flatMap { categories in
downloadedEvents.scan(categories) { updated, events in
return updated.map { category in
let eventsForCategory = EONET.filteredEvents(events: events, forCategory: category)
if !eventsForCategory.isEmpty {
var cat = category
cat.events = cat.events + eventsForCategory
return cat
}
return category
}
}
}
.do(onCompleted: { [weak self] in
DispatchQueue.main.async {
self?.activityIndicator.stopAnimating()
self?.download.isHidden = true
}
})
eoCategories.flatMap { categories in
return updatedCategories.scan(0) { count, _ in
return count + 1
}
.startWith(0)
.map { ($0, categories.count) }
}
.subscribe(onNext: { tuple in
DispatchQueue.main.async { [weak self] in
let progress = Float(tuple.0) / Float(tuple.1)
self?.download.progress.progress = progress
let percent = Int(progress * 100.0)
self?.download.label.text = "Download: \(percent)%"
}
})
.addDisposableTo(disposeBag)
eoCategories
.concat(updatedCategories)
.bindTo(categories)
.addDisposableTo(disposeBag)
}
// MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell")!
let category = categories.value[indexPath.row]
cell.textLabel?.text = "\(category.name) (\(category.events.count))"
cell.accessoryType = (category.events.count > 0) ? .disclosureIndicator
: .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let category = categories.value[indexPath.row]
if !category.events.isEmpty {
let eventsController = storyboard!.instantiateViewController(withIdentifier: "events") as! EventsViewController
eventsController.title = category.name
eventsController.events.value = category.events
navigationController!.pushViewController(eventsController, animated: true)
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
mit
|
f6c315dda6b5bf3394f029ec7363db3a
| 32.776224 | 117 | 0.698551 | 4.772727 | false | false | false | false |
KanChen2015/DRCCamera
|
DRCCamera/DRCCamera/DRCCustomImagePickerController.swift
|
1
|
10984
|
//
// DRCCustomImagePickerController.swift
// testSBR
//
// Created by Kan Chen on 9/24/15.
// Copyright © 2015 Kan Chen. All rights reserved.
//
import UIKit
@objc public protocol DRCCustomImagePickerControllerDelegate{
func customImagePickerDidFinishPickingImage(rectImage: UIImage, detectedRectImage: UIImage?)
}
public class DRCCustomImagePickerController: UIImagePickerController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CameraOverlayDelegate {
var imagePicker = UIImagePickerController()
var photoRatio : RectangleRatio?
var detectRatio: RectangleRatio?
public var enableImageDetecting:Bool = false
public var customDelegate: DRCCustomImagePickerControllerDelegate?
var parentVC: UIViewController?
// var method = 0
override public func viewDidLoad() {
super.viewDidLoad()
}
public func showImagePicker(inViewController parent: UIViewController){
if !UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.Rear){
return
}
let sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.sourceType = sourceType
var availableSource = UIImagePickerController.availableMediaTypesForSourceType(sourceType)
availableSource?.removeLast()
imagePicker.mediaTypes = availableSource!
imagePicker.delegate = self
imagePicker.showsCameraControls = false
let bundle = NSBundle(forClass: DRCCustomImagePickerController.classForCoder())
let xibs = bundle.loadNibNamed("CameraOverlay", owner: nil, options: nil)
// let xibs = NSBundle.mainBundle().loadNibNamed("CameraOverlay", owner: nil, options: nil)
let overlayView = xibs.first as? CameraOverlay
overlayView?.frame = imagePicker.cameraOverlayView!.frame
imagePicker.cameraOverlayView = overlayView
overlayView?.delegate = self
// overlayView?.method = self.method
setCameraCenter()
self.parentVC = parent
parentVC!.presentViewController(imagePicker, animated: true, completion: nil)
}
private func setCameraCenter(){
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone{
var transform = self.imagePicker.cameraViewTransform
let y = (UIScreen.mainScreen().bounds.height - (UIScreen.mainScreen().bounds.width * 4 / 3)) / 2
transform.ty = y
self.imagePicker.cameraViewTransform = transform
}
}
public func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
NSNotificationCenter.defaultCenter().postNotificationName("startProcessing", object: nil)
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { () -> Void in
print(image.imageOrientation.rawValue)
let rotatedPhoto: UIImage = ImageHandler.scaleAndRotateImage(image)
// let imageRef3 = CGImageCreateWithImageInRect(rotatedPhoto.CGImage, CGRectMake(image.size.width * self.photoRatio!.x, image.size.height * self.photoRatio!.y, image.size.width * self.photoRatio!.wp, image.size.height * self.photoRatio!.hp))
let rect = CGRectMake(rotatedPhoto.size.width * self.photoRatio!.x, rotatedPhoto.size.height * self.photoRatio!.y, rotatedPhoto.size.width * self.photoRatio!.wp, rotatedPhoto.size.height * self.photoRatio!.hp)
let imageRef3 = CGImageCreateWithImageInRect(rotatedPhoto.CGImage, rect)
let rectImage = UIImage(CGImage: imageRef3!)
let detectedRect : UIImage?
if let detectRatio = self.detectRatio{
let detectRect = CGRectMake(rotatedPhoto.size.width * detectRatio.x,
rotatedPhoto.size.height * detectRatio.y,
rotatedPhoto.size.width * detectRatio.wp,
rotatedPhoto.size.height * detectRatio.hp)
let detectedImageRef = CGImageCreateWithImageInRect(rotatedPhoto.CGImage, detectRect)
let detectedImage = UIImage(CGImage: detectedImageRef!)
detectedRect = self.detect(detectedImage)
}else{
detectedRect = self.detect(rectImage)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.parentVC?.dismissViewControllerAnimated(true, completion: { () -> Void in
self.customDelegate?.customImagePickerDidFinishPickingImage(rectImage, detectedRectImage: detectedRect)
})
})
}
}
//MARK: - OverlayDelegate
func cancelFromImagePicker() {
self.parentVC!.dismissViewControllerAnimated(true, completion: nil)
}
func saveInImagePicker(ratio: RectangleRatio, detectRatio: RectangleRatio?) {
imagePicker.takePicture()
self.photoRatio = ratio
self.detectRatio = detectRatio
}
func detect(image: UIImage) -> UIImage?{
if !enableImageDetecting {
return nil
}
let detector = CIDetector(ofType: CIDetectorTypeRectangle, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh, CIDetectorMinFeatureSize: 0.2])
let imageCI = CIImage(image: image)!
let opts = [CIDetectorAspectRatio: 1.6]
let features = detector.featuresInImage(imageCI, options: opts) as! [CIRectangleFeature]
if features.count == 0 {
return nil
}
if features.count > 1{
print("we found \(features.count) features")
}
//rotate it
let f = features[0]
var x = (f.topRight.x - f.topLeft.x)
var y = (f.topRight.y - f.topLeft.y)
var w = sqrt( x*x + y*y)
var slopeTop = y/x
x = (f.bottomRight.x - f.bottomLeft.x)
y = (f.bottomRight.y - f.bottomLeft.y)
let bottomSlope = y/x
slopeTop = (slopeTop + bottomSlope)/2
let wBottom = sqrt( x*x + y*y)
let degree = 180*(atan(Double(bottomSlope)) / M_PI )
x = (f.topLeft.x - f.bottomLeft.x)
y = (f.topLeft.y - f.bottomLeft.y)
var h = sqrt( x*x + y*y)
x = (f.topRight.x - f.bottomRight.x)
y = (f.topRight.y - f.bottomRight.y)
let hRight = sqrt( x*x + y*y)
// h = (h + hRight)/2
// w = (w + wBottom)/2
h = max(h, hRight)
w = max(w, wBottom)
let cardCI = cropCardByFeature(imageCI, feature: features[0])
let context = CIContext(options: nil)
let cgImage: CGImageRef = context.createCGImage(cardCI, fromRect: cardCI.extent)
var card:UIImage = UIImage(CGImage: cgImage)
card = card.imageRotatedByDegrees(CGFloat(degree), flip: false)
// let cardRotatedCI = CIImage(image: card)!
let centerX = card.size.width / 2
let centerY = card.size.height / 2
let cardRef = CGImageCreateWithImageInRect(card.CGImage, CGRectMake(centerX - w/2 , centerY - h/2, w , h ))
let card2 = UIImage(CGImage: cardRef!)
// let newF = detector.featuresInImage(cardRotatedCI, options: opts) as! [CIRectangleFeature]
//
// let aa = cropCardByFeature(cardRotatedCI, feature: newF[0])
// let context2 = CIContext(options: nil)
// let aaImage: CGImageRef = context2.createCGImage(aa, fromRect: aa.extent)
// let card2:UIImage = UIImage(CGImage: aaImage)
self.testImage = card2
let resultImage = detectImage(image, features: features)
let resultOverlay = detectImageWithOverlay(imageCI, features: features)
self.overlay = resultOverlay
// return resultImage
// return card2
// for f:CIRectangleFeature in features{
// var overlay = CIImage(color: CIColor(color: UIColor(red: 1, green: 0, blue: 0, alpha: 0.6)))
// overlay = overlay.imageByCroppingToRect(image.extent)
// overlay = overlay.imageByApplyingFilter("CIPerspectiveTransformWithExtent", withInputParameters: ["inputExtent": CIVector(x: 0, y: 0, z: 1, w: 1),
// "inputTopLeft": CIVector(CGPoint: f.topLeft), "inputTopRight": CIVector(CGPoint: f.topRight), "inputBottomLeft": CIVector(CGPoint: f.bottomLeft),"inputBottomRight": CIVector(CGPoint: f.bottomRight)])
// result = overlay.imageByCompositingOverImage(result)
//
// }
return ImageHandler.getImageCorrectedPerspectiv(imageCI, feature: f)
// let result2 = image
// var overlay = CIImage(color: CIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.7))
// overlay = overlay.imageByCroppingToRect(features[0].bounds)
//
// let ciimagewithoverlay = overlay.imageByCompositingOverImage(result2)
// resultImage.image = UIImage(CIImage:ciimagewithoverlay)
}
public var overlay: UIImage?
public var testImage: UIImage?
func detectImageWithOverlay(ciImage:CIImage,features: [CIRectangleFeature]) -> UIImage{
let f = features[0]
var overlay = CIImage(color: CIColor(color: UIColor(red: 1, green: 0, blue: 0, alpha: 0.6)))
overlay = overlay.imageByCroppingToRect(ciImage.extent)
overlay = overlay.imageByApplyingFilter("CIPerspectiveTransformWithExtent",
withInputParameters: ["inputExtent": CIVector(CGRect: ciImage.extent),
"inputTopLeft": CIVector(CGPoint: f.topLeft),
"inputTopRight": CIVector(CGPoint: f.topRight),
"inputBottomLeft": CIVector(CGPoint: f.bottomLeft),
"inputBottomRight": CIVector(CGPoint: f.bottomRight)]
)
let result = UIImage(CIImage:overlay.imageByCompositingOverImage(ciImage))
return result
}
// var degree:Double?
func detectImage(image:UIImage ,features: [CIRectangleFeature]) -> UIImage{
let featuresRect = features[0].bounds
let imageRef = CGImageCreateWithImageInRect(image.CGImage, featuresRect)
let resultImage = UIImage(CGImage: imageRef!)
return resultImage
}
private func cropCardByFeature(image: CIImage, feature: CIRectangleFeature) -> CIImage{
var card: CIImage
card = image.imageByApplyingFilter("CIPerspectiveTransformWithExtent",
withInputParameters: ["inputExtent": CIVector(CGRect: image.extent),
"inputTopLeft": CIVector(CGPoint: feature.topLeft),
"inputTopRight": CIVector(CGPoint: feature.topRight),
"inputBottomLeft": CIVector(CGPoint: feature.bottomLeft),
"inputBottomRight": CIVector(CGPoint: feature.bottomRight)]
)
card = image.imageByCroppingToRect(card.extent)
return card
}
}
|
mit
|
e40045fd6e30521e5a610f150207c2fa
| 45.935897 | 268 | 0.651917 | 4.544063 | false | false | false | false |
alskipp/SwiftForms
|
SwiftForms/cells/FormCheckCell.swift
|
2
|
1153
|
//
// FormCheckCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 22/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormCheckCell: FormTitleCell {
/// MARK: FormBaseCell
public override func configure() {
super.configure()
selectionStyle = .Default
accessoryType = .None
}
public override func update() {
super.update()
titleLabel.text = rowDescriptor.title
if let checkMk = rowDescriptor.value as? Bool where checkMk == true {
accessoryType = .Checkmark
} else {
accessoryType = .None
}
}
public override class func formViewController(formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) {
if let row = selectedRow as? FormCheckCell {
row.check()
}
}
/// MARK: Private interface
private func check() {
rowDescriptor.value = (rowDescriptor.value as? Bool).map { !$0 } ?? true
accessoryType = (rowDescriptor.value as! Bool) ? .Checkmark : .None
}
}
|
mit
|
85b3725521f1d40bf3730334550c22e5
| 24.6 | 131 | 0.611979 | 4.820084 | false | false | false | false |
LeeMZC/MZCWB
|
MZCWB/MZCWB/Classes/Home-首页/View/MZCHomeTitleButton.swift
|
1
|
2135
|
//
// MZCHomeTitleButton.swift
// MZCWB
//
// Created by 马纵驰 on 16/7/21.
// Copyright © 2016年 马纵驰. All rights reserved.
//
import UIKit
import QorumLogs
class MZCHomeTitleButton: UIButton {
private let spacing = 20
override init(frame: CGRect) {
super.init(frame: frame)
setupNotificationCenter()
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setupNotificationCenter(){
// 3.注册通知
NSNotificationCenter.defaultCenter().addObserver(self, selector : #selector(MZCHomeTitleButton.titleChange), name: MZCHomeTitleButtonDidChange, object: nil)
}
private func setupUI(){
assert(accountTokenMode != nil, "用户信息无法获取")
self.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Normal)
self.setTitle(accountTokenMode!.user?.screen_name, forState: UIControlState.Normal)
self.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
self.sizeToFit()
self.frame.size.width += (CGFloat)(spacing)
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel?.frame.origin.x = 0.0
imageView?.frame.origin.x = (titleLabel?.frame.size.width )! + (CGFloat)(spacing / 2)
}
func imgAnimation(){
guard let tempImgView = imageView else{
return
}
selected = !selected
let timer = 0.5
if selected {
UIView.animateWithDuration(timer, animations: {
tempImgView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
})
}else{
UIView.animateWithDuration(timer, animations: {
tempImgView.transform = CGAffineTransformIdentity
})
}
}
func titleChange(){
imgAnimation()
}
deinit{
// 移除通知
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
artistic-2.0
|
a5c4858f3b91badbecf841630a247923
| 25.43038 | 164 | 0.598659 | 4.8 | false | false | false | false |
seancatkinson/SCAStateMachine
|
Tests/StateChangeActionTests.swift
|
1
|
8370
|
// StateChangeActionTests.swift
// SCAStateMachine
//
// Copyright (c) 2015 SeanCAtkinson (http://seancatkinson.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import Foundation
@testable import SCAStateMachine
class StateChangeActionTests: SCAStateMachineBaseTests {
func testCanSetActions() {
stateMachine = addTestStateRulesToTestStateMachine(stateMachine)
let expectation = self.expectation(description: "Should be performed")
stateMachine.performAfterChangingTo([.Testing]) { (destinationState, startingState, userInfo) -> () in
expectation.fulfill()
}
do {
try stateMachine.changeTo(.Testing)
}
catch {
XCTFail("Couldn't change state")
return
}
self.waitForExpectations(timeout: 0.5, handler: nil)
}
func testActionsAreNotAddedWhenNoStatesProvided() {
stateMachine.allowChangingFrom(.Pending, to: [])
stateMachine.allowChangingTo(.Testing, from: [])
stateMachine.addStateTransition(named: "Test", from: [], to: .Testing)
do { try stateMachine.canPerformTransition(named: "Test") }
catch StateMachineError.noTransitionMatchingName(let name) {
XCTAssertEqual(name, "Test")
}
catch {
XCTFail("Should have been caught earlier")
}
stateMachine.performAfterChangingTo([]) { _,_,_ in }
stateMachine.performAfterChangingFrom([]) { _,_,_ in }
stateMachine.checkConditionBeforeChangingTo([]) { _,_,_ in }
stateMachine.checkConditionBeforeChangingFrom([]) { _,_,_ in }
}
func testActionsFireInTheCorrectOrder() {
stateMachine = addTestStateRulesToTestStateMachine(stateMachine)
var myNumber:Int = 0
let expectation1 = self.expectation(description: "Should be performed")
let expectation2 = self.expectation(description: "Should be performed")
let expectation3 = self.expectation(description: "Should be performed")
stateMachine.performAfterChangingTo([.Testing]) { (destinationState, startingState, userInfo) -> () in
myNumber += 1
XCTAssertEqual(myNumber, 1, "myNumber should equal 1")
expectation1.fulfill()
}
stateMachine.performAfterChangingFrom([.Pending]) { (destinationState, startingState, userInfo) -> () in
myNumber += 10
XCTAssertEqual(myNumber, 11, "myNumber should equal 11")
expectation2.fulfill()
}
stateMachine.performAfterChanging { (destinationState, startingState, userInfo) -> () in
myNumber += 100
XCTAssertEqual(myNumber, 111, "myNumber should equal 111")
expectation3.fulfill()
}
do {
try stateMachine.changeTo(.Testing, userInfo: nil)
}
catch {
XCTFail("Couldn't change to state .Testing")
return
}
self.waitForExpectations(timeout: 0.5, handler: nil)
}
func testCorrectStatesArePassedDuringStateChange() {
stateMachine = addTestStateRulesToTestStateMachine(stateMachine)
let myNumber:Int = 8000
stateMachine.performAfterChangingTo([.Testing]) { (destinationState, startingState, userInfo) -> () in
XCTAssertTrue(destinationState == TestState.Testing, "destinationState should equal .Testing but instead equals: \(destinationState)")
XCTAssertTrue(startingState == TestState.Pending, "startingState should equal .Pending but instead equals: \(startingState)")
if let userInfo = userInfo, userInfo is Int {
let passedNumber = userInfo as! Int
XCTAssertTrue(passedNumber == myNumber, "userInfo should equal what is passed")
} else {
XCTFail("userInfo isn't valid")
}
}
stateMachine.performAfterChangingFrom([.Pending]) { (destinationState, startingState, userInfo) -> () in
XCTAssertTrue(destinationState == TestState.Testing, "destinationState should equal .Testing but instead equals: \(destinationState)")
XCTAssertTrue(startingState == TestState.Pending, "startingState should equal .Pending but instead equals: \(startingState)")
if let userInfo = userInfo, userInfo is Int {
let passedNumber = userInfo as! Int
XCTAssertTrue(passedNumber == myNumber, "userInfo should equal what is passed")
} else {
XCTFail("userInfo isn't valid")
}
}
stateMachine.performAfterChanging { (destinationState, startingState, userInfo) -> () in
XCTAssertTrue(destinationState == TestState.Testing, "destinationState should equal .Testing but instead equals: \(destinationState)")
XCTAssertTrue(startingState == TestState.Pending, "startingState should equal .Pending but instead equals: \(startingState)")
if let userInfo = userInfo, userInfo is Int {
let passedNumber = userInfo as! Int
XCTAssertTrue(passedNumber == myNumber, "userInfo should equal what is passed")
} else {
XCTFail("userInfo isn't valid")
}
}
do {
try stateMachine.changeTo(.Testing, userInfo: myNumber)
}
catch {
XCTFail("Couldn't change to state .Testing")
return
}
}
func testCannotChangeToStateWhenAlreadyInRequestedState() {
do {
try stateMachine.changeTo(.Pending)
}
catch {
return
}
XCTFail("Error should have thrown")
}
func testCanAutomaticallyChangeTo3rdStateAfterChangingTo2ndState() {
let expectation1 = self.expectation(description: "Should be performed")
stateMachine.performAfterChangingTo([.Failed]) { [weak stateMachine] (destinationState, startingState, userInfo) -> () in
XCTAssertEqual(stateMachine!.currentState, TestState.Failed)
do {
try stateMachine?.changeTo(.Pending)
}
catch {
XCTFail("\(error)")
}
expectation1.fulfill()
}
let expectation2 = self.expectation(description: "Should be performed")
stateMachine.performAfterChangingTo([.Pending]) { (destinationState, startingState, userInfo) -> () in
expectation2.fulfill()
}
do {
try stateMachine.changeTo(.Testing)
try stateMachine.changeTo(.Failed)
}
catch {
XCTFail("\(error)")
}
self.waitForExpectations(timeout: 0.5) { errorOptional in
XCTAssertEqual(self.stateMachine.currentState, TestState.Pending)
}
}
}
|
mit
|
0b367fd4063a25f538690d7c47a49dca
| 32.88664 | 146 | 0.607885 | 5.334608 | false | true | false | false |
nyin005/Forecast-App
|
Forecast/Forecast/Class/Summary/CustomView/SummaryTableView.swift
|
1
|
2645
|
//
// SummaryTableView.swift
// Forecast
//
// Created by appledev110 on 11/22/16.
// Copyright © 2016 appledev110. All rights reserved.
//
import UIKit
class SummaryTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var reports = [SummaryTimeModel]()
var cellClickedHandler: ButtonTouchUpWithParmBlock?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame,style: style)
self.delegate = self
self.dataSource = self
self.register(UINib(nibName: "SummaryTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return reports.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: SummaryTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SummaryTableViewCell
cell.initDetailUI(listModel: reports[indexPath.row])
cell.onBenchClickedHandler = {
// print(indexPath.row)
if self.cellClickedHandler != nil {
self.cellClickedHandler!(indexPath.row as AnyObject)
}
}
return cell
}
// func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// return 10.0
// }
//
// func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// return reports[section].date
// }
// func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//// let placeholderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 10))
// let placeholderView = UIView()
// placeholderView.backgroundColor = .clear
// return placeholderView
// }
// func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// return 10.0
// }
//
// func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// let placeholderView = UIView()
// placeholderView.backgroundColor = .clear
// return placeholderView
// }
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 178
}
}
|
gpl-3.0
|
76c2fcb8c10c996a85023af2a2cba6dd
| 32.05 | 135 | 0.639939 | 4.781193 | false | false | false | false |
natecook1000/swift
|
test/Frontend/supplementary-output-support.swift
|
2
|
2903
|
// Checks what happens when trying to emit various supplementary outputs from
// modes that don't support them. This isn't critical because the driver should
// never ask the frontend to do this, but it's nice for people writing tests.
// RUN: not %target-swift-frontend -typecheck -emit-module %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_MODULE %s
// PARSE_NO_MODULE: error: this mode does not support emitting modules{{$}}
// RUN: not %target-swift-frontend -parse -emit-dependencies %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_DEPS %s
// PARSE_NO_DEPS: error: this mode does not support emitting dependency files{{$}}
// RUN: not %target-swift-frontend -dump-ast -emit-dependencies %s 2>&1 | %FileCheck -check-prefix=DUMP_NO_DEPS %s
// DUMP_NO_DEPS: error: this mode does not support emitting dependency files{{$}}
// RUN: not %target-swift-frontend -parse -emit-reference-dependencies %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_REFERENCE_DEPS %s
// PARSE_NO_REFERENCE_DEPS: error: this mode does not support emitting reference dependency files{{$}}
// RUN: not %target-swift-frontend -dump-ast -emit-reference-dependencies %s 2>&1 | %FileCheck -check-prefix=DUMP_NO_REFERENCE_DEPS %s
// DUMP_NO_REFERENCE_DEPS: error: this mode does not support emitting reference dependency files{{$}}
// RUN: not %target-swift-frontend -resolve-imports -emit-reference-dependencies %s 2>&1 | %FileCheck -check-prefix=RESOLVE_IMPORTS_NO_REFERENCE_DEPS %s
// RESOLVE_IMPORTS_NO_REFERENCE_DEPS: error: this mode does not support emitting reference dependency files{{$}}
// RUN: not %target-swift-frontend -parse -emit-objc-header %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_OBJC_HEADER %s
// PARSE_NO_OBJC_HEADER: error: this mode does not support emitting Objective-C headers{{$}}
// RUN: not %target-swift-frontend -dump-ast -emit-objc-header %s 2>&1 | %FileCheck -check-prefix=DUMP_NO_OBJC_HEADER %s
// DUMP_NO_OBJC_HEADER: error: this mode does not support emitting Objective-C headers{{$}}
// RUN: not %target-swift-frontend -resolve-imports -emit-objc-header %s 2>&1 | %FileCheck -check-prefix=RESOLVE_IMPORTS_NO_OBJC_HEADER %s
// RESOLVE_IMPORTS_NO_OBJC_HEADER: error: this mode does not support emitting Objective-C headers{{$}}
// RUN: not %target-swift-frontend -parse -emit-interface-path %t %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_INTERFACE %s
// PARSE_NO_INTERFACE: error: this mode does not support emitting textual interface files{{$}}
// RUN: not %target-swift-frontend -typecheck -emit-interface-path %t %s 2>&1 | %FileCheck -check-prefix=TYPECHECK_NO_INTERFACE %s
// TYPECHECK_NO_INTERFACE: error: this mode does not support emitting textual interface files{{$}}
// RUN: not %target-swift-frontend -emit-silgen -emit-interface-path %t %s 2>&1 | %FileCheck -check-prefix=SILGEN_NO_INTERFACE %s
// SILGEN_NO_INTERFACE: error: this mode does not support emitting textual interface files{{$}}
|
apache-2.0
|
c437ecb384f01b559cfdf7c771abf0c1
| 89.71875 | 152 | 0.741647 | 3.561963 | false | false | false | false |
guowilling/iOSExamples
|
Swift/AudioAndVideo/SampleCodeCaptureAudioAndVideo/SampleCodeCaptureAudioAndVideo/ViewController.swift
|
2
|
6098
|
//
// ViewController.swift
// SampleCodeCaptureAudioAndVideo
//
// Created by 郭伟林 on 2017/9/12.
// Copyright © 2017年 SR. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
fileprivate var videoInput: AVCaptureDeviceInput?
fileprivate var videoDataOutput: AVCaptureVideoDataOutput?
fileprivate var videoPreviewLayer: AVCaptureVideoPreviewLayer?
fileprivate lazy var captureSession: AVCaptureSession = AVCaptureSession()
fileprivate lazy var movieFileOutput: AVCaptureMovieFileOutput = {
let movieFileOutput = AVCaptureMovieFileOutput()
self.captureSession.beginConfiguration()
if self.captureSession.canAddOutput(movieFileOutput) {
self.captureSession.addOutput(movieFileOutput)
}
self.captureSession.commitConfiguration()
let connection = movieFileOutput.connection(withMediaType: AVMediaTypeVideo)
connection?.automaticallyAdjustsVideoMirroring = true
return movieFileOutput
}()
fileprivate var videoFileURL: URL? {
let filePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + "/capture_video.mp4"
return URL(fileURLWithPath: filePath)
}
override func viewDidLoad() {
super.viewDidLoad()
// 初始化视频的输入&输出
setupVideoInputOutput()
// 初始化音频的输入&输出
setupAudioInputOutput()
}
private func setupVideoInputOutput() {
// 视频输入
guard let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] else { return }
guard let device = devices.filter({ $0.position == .front }).first else { return }
guard let input = try? AVCaptureDeviceInput(device: device) else { return }
self.videoInput = input
// 视频输出
let output = AVCaptureVideoDataOutput()
let queue = DispatchQueue.global()
output.setSampleBufferDelegate(self, queue: queue)
self.videoDataOutput = output
addInputOutputToSesssion(input, output)
}
private func setupAudioInputOutput() {
// 音频输入
guard let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio) else { return }
guard let input = try? AVCaptureDeviceInput(device: device) else { return }
// 音频输出
let output = AVCaptureAudioDataOutput()
let queue = DispatchQueue.global()
output.setSampleBufferDelegate(self, queue: queue)
addInputOutputToSesssion(input, output)
}
private func addInputOutputToSesssion(_ input: AVCaptureInput, _ output: AVCaptureOutput) {
captureSession.beginConfiguration()
if captureSession.canAddInput(input) {
captureSession.addInput(input)
}
if captureSession.canAddOutput(output) {
captureSession.addOutput(output)
}
captureSession.commitConfiguration()
}
}
extension ViewController {
@IBAction func startCapture() {
// 开始采集
captureSession.startRunning()
// 初始化预览图层
setupPreviewLayer()
// 写入文件(注意: 此时不会回调 captureOutput:didOutputSampleBuffer:fromConnection: 代理方法)
// if let fileURL = videoFileURL {
// movieFileOutput.startRecording(toOutputFileURL: fileURL, recordingDelegate: self)
// }
}
@IBAction func stopCapturing() {
// movieFileOutput?.stopRecording()
captureSession.stopRunning()
videoPreviewLayer?.removeFromSuperlayer()
}
@IBAction func rotateCamera() {
guard let videoInput = self.videoInput else {
return
}
let postion: AVCaptureDevicePosition = videoInput.device.position == .front ? .back : .front
guard let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] else { return }
guard let device = devices.filter({ $0.position == postion }).first else { return }
guard let newVideoInput = try? AVCaptureDeviceInput(device: device) else { return }
captureSession.beginConfiguration()
captureSession.removeInput(videoInput)
if captureSession.canAddInput(newVideoInput) {
captureSession.addInput(newVideoInput)
}
captureSession.commitConfiguration()
self.videoInput = newVideoInput
}
}
extension ViewController {
fileprivate func setupPreviewLayer() {
guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else { return }
previewLayer.frame = view.bounds
view.layer.insertSublayer(previewLayer, at: 0)
self.videoPreviewLayer = previewLayer
}
}
extension ViewController : AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
if videoDataOutput?.connection(withMediaType: AVMediaTypeVideo) == connection {
// print("采集到视频数据 sampleBuffer: \(sampleBuffer)")
print("采集到视频数据")
} else {
// print("采集到音频数据 sampleBuffer: \(sampleBuffer)")
print("采集到音频数据")
}
}
}
extension ViewController : AVCaptureFileOutputRecordingDelegate {
func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) {
print("didStartRecordingToOutputFileAt")
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
print("didFinishRecordingToOutputFileAt")
}
}
|
mit
|
dfa2a1e5a9fd5d2ad725ae222ddbdc60
| 34.160714 | 163 | 0.665651 | 5.674352 | false | false | false | false |
mihaicris/digi-cloud
|
Digi Cloud/Models/Node.swift
|
1
|
2136
|
//
// Node.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 19/09/16.
// Copyright © 2016 Mihai Cristescu. All rights reserved.
//
import Foundation
struct Node {
// MARK: - Properties
var name: String
let type: String
let modified: TimeInterval
let size: Int64
let contentType: String
let hash: String?
var mount: Mount?
let mountPath: String?
var link: DownloadLink?
var receiver: UploadLink?
var bookmark: Bookmark?
}
extension Node {
init?(object: Any?) {
guard
let jsonDictionary = object as? [String: Any],
let name = jsonDictionary["name"] as? String,
let type = jsonDictionary["type"] as? String,
let modified = jsonDictionary["modified"] as? TimeInterval,
let size = jsonDictionary["size"] as? Int64,
let contentType = jsonDictionary["contentType"] as? String
else { return nil }
self.name = name
self.type = type
self.modified = modified
self.size = size
self.contentType = contentType
self.hash = jsonDictionary["hash"] as? String
self.mount = Mount(object: jsonDictionary["mount"])
self.mountPath = jsonDictionary["mountPath"] as? String
self.link = DownloadLink(object: jsonDictionary["link"])
self.receiver = UploadLink(object: jsonDictionary["receiver"])
self.bookmark = Bookmark(object: jsonDictionary["bookmark"])
}
}
extension Node {
// Extension of the node name (otherwise "")
var ext: String {
return (name as NSString).pathExtension
}
// Location in given Mount
func location(in parentLocation: Location) -> Location {
var path = parentLocation.path + name
if type == "dir" {
path += "/"
}
return Location(mount: parentLocation.mount, path: path )
}
}
extension Node: Hashable {
var hashValue: Int {
return self.hash?.hashValue ?? 0
}
}
extension Node: Equatable {
static func == (lhs: Node, rhs: Node) -> Bool {
return lhs.name == rhs.name
}
}
|
mit
|
64021312bb9326492899ed145c2cd80d
| 25.036585 | 71 | 0.608431 | 4.375 | false | false | false | false |
ps2/rileylink_ios
|
MinimedKit/PumpEvents/BGReceivedPumpEvent.swift
|
1
|
1107
|
//
// BGReceived.swift
// RileyLink
//
// Created by Pete Schwamb on 3/8/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct BGReceivedPumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public let amount: Int
public let meter: String
public init?(availableData: Data, pumpModel: PumpModel) {
length = 10
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
func d(_ idx: Int) -> Int {
return Int(availableData[idx])
}
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
amount = (d(1) << 3) + (d(4) >> 5)
meter = availableData.subdata(in: 7..<10).hexadecimalString
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "BGReceivedPumpEvent",
"amount": amount,
"meter": meter,
]
}
}
|
mit
|
b2e3821501375da0824171119e0e2564
| 24.72093 | 75 | 0.582278 | 4.495935 | false | false | false | false |
gerardogrisolini/Webretail
|
Sources/Webretail/HTTPTurnstile.swift
|
1
|
2966
|
//
// HTTPTurnstile.swift
// Webretail
//
// Created by Gerardo Grisolini on 26/02/17.
//
//
import PerfectHTTP
import PerfectLogger
import Turnstile
import Foundation
extension HTTPResponse {
/// Extends the HTTPRequest with redirect.
public func redirect(path: String) {
self.status = .found
self.addHeader(.location, value: path)
self.completed()
}
public func badRequest(error: String) {
LogFile.error(error)
self.status = .badRequest
self.setHeader(.contentType, value: "text/html")
self.appendBody(string: error)
self.completed()
}
public func setJson<T>(_ json: T) throws where T:Codable {
let encoder = JSONEncoder()
let data = try! encoder.encode(json)
self.setHeader(.contentType, value: "application/json")
self.appendBody(string: String(data: data, encoding: .utf8)!)
}
}
public extension HTTPRequest {
/// Extends the HTTPRequest with a user object.
internal(set) public var user: Subject {
get {
return scratchPad["TurnstileSubject"] as! Subject
}
set {
scratchPad["TurnstileSubject"] = newValue
}
}
public func getJson<T:Codable>() -> T? {
let decoder = JSONDecoder()
let jsonData = self.postBodyString?.data(using: .utf8)
//LogFile.debug(self.postBodyString!)
return try? decoder.decode(T.self, from: jsonData!)
}
}
/// Container for an auth header object
struct AuthorizationHeader {
let headerValue: String
init?(value: String?) {
guard let value = value else { return nil }
headerValue = value
}
/// Enables auth checking via an API Key
var basic: APIKey? {
guard let range = headerValue.range(of: "Basic ") else { return nil }
let token = String(headerValue[range.upperBound...])
guard let separatorRange = token.range(of: "#") else {
return nil
}
let apiKeyID = token[..<separatorRange.lowerBound]
let apiKeySecret = token[separatorRange.upperBound...]
return APIKey(id: String(apiKeyID), secret: String(apiKeySecret))
}
/// Enables auth checking via a Bearer Token
var bearer: AccessToken? {
guard let range = headerValue.range(of: "Bearer ") else { return nil }
let token = headerValue[range.upperBound...]
return AccessToken(string: String(token))
}
}
extension HTTPRequest {
/// Extends the HTTPrequest object with an auth vriable.
var auth: AuthorizationHeader? {
return AuthorizationHeader(value: self.header(.authorization))
}
}
extension HTTPRequest {
/// Extends the HTTPReques object with a Cookie retrieval method
func getCookie(name: String) -> String? {
for (cookieName, payload) in self.cookies {
if name == cookieName {
return payload
}
}
return nil
}
}
|
apache-2.0
|
59b65a5095243fa3760b5cb5af8153e7
| 26.981132 | 78 | 0.627782 | 4.311047 | false | false | false | false |
matsprea/omim
|
iphone/Maps/Core/Theme/Components/IColors.swift
|
1
|
3183
|
let alpha04: CGFloat = 0.04
let alpha12: CGFloat = 0.12
let alpha20: CGFloat = 0.20
let alpha26: CGFloat = 0.26
let alpha30: CGFloat = 0.3
let alpha32: CGFloat = 0.32
let alpha36: CGFloat = 0.36
let alpha40: CGFloat = 0.4
let alpha54: CGFloat = 0.54
let alpha70: CGFloat = 0.7
let alpha80: CGFloat = 0.8
let alpha87: CGFloat = 0.87
let alpha90: CGFloat = 0.9
let alpha100: CGFloat = 1.0
@objc protocol IColors {
var clear: UIColor { get }
var primaryDark: UIColor { get }
var primary: UIColor { get }
var secondary: UIColor { get }
var primaryLight: UIColor { get }
var menuBackground: UIColor { get }
var downloadBadgeBackground: UIColor { get }
var pressBackground: UIColor { get }
var red: UIColor { get }
var errorPink: UIColor { get }
var orange: UIColor { get }
var linkBlue: UIColor { get }
var linkBlueHighlighted: UIColor { get }
var linkBlueDark: UIColor { get }
var buttonRed: UIColor { get }
var buttonRedHighlighted: UIColor { get }
var blackPrimaryText: UIColor { get }
var blackSecondaryText: UIColor { get }
var blackHintText: UIColor { get }
var blackDividers: UIColor { get }
var solidDividers: UIColor { get }
var white: UIColor { get }
var whitePrimaryText: UIColor { get }
var whitePrimaryTextHighlighted: UIColor { get }
var whiteSecondaryText: UIColor { get }
var whiteHintText: UIColor { get }
var buttonDisabledBlueText: UIColor { get }
var alertBackground: UIColor { get }
var blackOpaque: UIColor { get }
var toastBackground: UIColor { get }
var statusBarBackground: UIColor { get }
var bannerBackground: UIColor { get }
var searchPromoBackground: UIColor { get }
var border: UIColor { get }
var discountBackground: UIColor { get }
var discountText: UIColor { get }
var bookmarkSubscriptionBackground: UIColor { get }
var bookmarkSubscriptionScrollBackground: UIColor { get }
var bookmarkSubscriptionFooterBackground: UIColor { get }
var bookingBackground: UIColor { get }
var opentableBackground: UIColor { get }
var transparentGreen: UIColor { get }
var ratingRed: UIColor { get }
var ratingOrange: UIColor { get }
var ratingYellow: UIColor { get }
var ratingLightGreen: UIColor { get }
var ratingGreen: UIColor { get }
var bannerButtonBackground: UIColor { get }
var facebookButtonBackground: UIColor { get }
var facebookButtonBackgroundDisabled: UIColor { get }
var allPassSubscriptionTitle: UIColor { get }
var allPassSubscriptionSubTitle: UIColor { get }
var allPassSubscriptionDescription: UIColor { get }
var allPassSubscriptionMonthlyBackground: UIColor { get }
var allPassSubscriptionYearlyBackground: UIColor { get }
var allPassSubscriptionMonthlyTitle: UIColor { get }
var allPassSubscriptionDiscountBackground: UIColor { get }
var allPassSubscriptionTermsTitle: UIColor { get }
var fadeBackground: UIColor { get }
var blackStatusBarBackground: UIColor { get }
var elevationPreviewSelector: UIColor { get }
var elevationPreviewTint: UIColor { get }
var shadow: UIColor { get }
var chartLine: UIColor { get }
var chartShadow: UIColor { get }
var cityColor: UIColor { get }
var outdoorColor: UIColor { get }
}
|
apache-2.0
|
28fe96f9d10d63c1ae0d9bd9e484bbdf
| 36.892857 | 60 | 0.730129 | 4.171691 | false | false | false | false |
vakoc/particle-swift
|
Sources/Logging.swift
|
1
|
9718
|
// This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016, 2018 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
public var globalLogLevel: LogLevel = .trace
public enum LogLevel: Int, Codable {
case trace,
debug,
info,
warning,
error,
off
}
extension String {
func indentedLines(_ indent: String = " ", separatedBy: String = "\n") -> String {
return self.components(separatedBy: separatedBy)
.map { return "\(indent)\($0)" }
.joined(separator: separatedBy)
}
}
extension Thread {
class func indentedCallStackSymbols() -> String {
return self.callStackSymbols.map { return " " + $0 }.joined(separator: "\n")
}
}
extension LogLevel : CustomStringConvertible {
public var description: String {
get {
switch(self) {
case .trace:
return "TRACE"
case .debug:
return "DEBUG"
case .info:
return "INFO"
case .warning:
return "WARN"
case .error:
return "ERROR"
case .off:
return ""
}
}
}
var paddedDescription: String {
get {
switch(self) {
case .trace:
return " TRACE"
case .debug:
return " DEBUG"
case .info:
return " INFO"
case .warning:
return "⚠ WARN"
case .error:
return "☣ ERROR"
case .off:
return ""
}
}
}
}
/**
logs a message using the specified level
:param: message the message to log, must return a string
:param: level the log level of the message
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
func log( _ message: @autoclosure() -> String, level: LogLevel = .debug, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
if level.rawValue >= globalLogLevel.rawValue {
let message = message()
let f = URL(fileURLWithPath: file).lastPathComponent
if callstack {
print("[\(level.paddedDescription)] \(f):\(line) • \(function) - \(message)\nCallstack:\n\(Thread.indentedCallStackSymbols())")
} else {
print("[\(level.paddedDescription)] \(f):\(line) • \(function) - \(message)")
}
}
}
/**
logs a error message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
func error( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .error, function: function, file: file, line: line, callstack: callstack)
}
/**
logs a warning message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
func warn( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .warning, function: function, file: file, line: line, callstack: callstack)
}
/**
logs a debug (trace) message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
func debug( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .debug, function: function, file: file, line: line, callstack: callstack)
}
/**
logs an informative message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
func info( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .info, function: function, file: file, line: line, callstack: callstack)
}
/**
logs a trace (finer than debug) message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
func trace( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .trace, function: function, file: file, line: line, callstack: callstack)
}
/**
logs a http request and reponse
*/
@inline(__always)
func trace(_ description: String, request: URLRequest, data: Data?, response: URLResponse?, error: Error?, function: String = #function, file: String = #file, line: Int = #line) -> Void {
guard globalLogLevel.rawValue <= LogLevel.trace.rawValue else {
return
}
var components = [description, "with \(request.httpMethod ?? "GET") request"]
components.append("\(request)")
if let headers = request.allHTTPHeaderFields {
components.append("headers")
components.append("\(headers)")
}
if let body = request.httpBody, let bodyString = String(data: body, encoding: String.Encoding.utf8) {
components.append("request body")
components.append(bodyString)
}
if let response = response {
components.append("returned")
components.append("\(response)")
}
#if os(Linux) && swift(>=3.1)
if let response = response as? HTTPURLResponse, let contentType = response.allHeaderFields["Content-Type"] as? String , contentType.contains("application/json"), let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) {
components.append("with response")
components.append("\(json)")
} else if let data = data, let body = String(data: data, encoding: String.Encoding.utf8) {
components.append("with response")
components.append(body)
}
#elseif os(Linux)
// swift < 3.1 on Linux defines allHeaderFields as [String : String] rather than [String : Any]
if let response = response as? HTTPURLResponse, let contentType = response.allHeaderFields["Content-Type"], contentType.contains("application/json"), let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) {
components.append("with response")
components.append("\(json)")
} else if let data = data, let body = String(data: data, encoding: String.Encoding.utf8) {
components.append("with response")
components.append(body)
}
#else
if let response = response as? HTTPURLResponse, let contentType = response.allHeaderFields["Content-Type"] as? String , contentType.contains("application/json"), let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) {
components.append("with response")
components.append("\(json)")
} else if let data = data, let body = String(data: data, encoding: String.Encoding.utf8) {
components.append("with response")
components.append(body)
}
#endif
if let error = error {
components.append("error:")
components.append("\(error)")
}
trace(components.joined(separator: "\n"), function: function, file: file, line: line)
}
/**
logs a http request download request
*/
@inline(__always)
func trace(_ description: String, request: URLRequest, url: URL?, response: URLResponse?, error: Error?, function: String = #function, file: String = #file, line: Int = #line) -> Void {
guard globalLogLevel.rawValue <= LogLevel.trace.rawValue else {
return
}
var components = [description, "with \(request.httpMethod ?? "GET") request"]
components.append("\(request)")
if let headers = request.allHTTPHeaderFields {
components.append("headers")
components.append("\(headers)")
}
if let body = request.httpBody, let bodyString = String(data: body, encoding: String.Encoding.utf8) {
components.append("request body")
components.append(bodyString)
}
if let response = response {
components.append("returned")
components.append("\(response)")
}
if let url = url {
components.append("with url \(url)")
}
if let error = error {
components.append("error:")
components.append("\(error)")
}
trace(components.joined(separator: "\n"), function: function, file: file, line: line)
}
|
apache-2.0
|
c140cfdea3a16189b84f522d14a67fee
| 33.551601 | 255 | 0.634772 | 4.190332 | false | false | false | false |
m-alani/contests
|
hackerrank/SparseArrays.swift
|
1
|
792
|
//
// SparseArrays.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/sparse-arrays
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
import Foundation
// Read N
let n = Int(readLine()!)!
// Generate our dictionary
var stringsDB = [String:Int]()
for _ in 1...n {
let word = String(readLine()!)!
let count = stringsDB[word] ?? 0
stringsDB[word] = count + 1
}
// Read Q
let q = Int(readLine()!)!
// Search and generate output
var output = [Int]()
for _ in 1...q {
let word = String(readLine()!)!
output.append(stringsDB[word] ?? 0)
}
// Print the output
for count in output {
print(count)
}
|
mit
|
3975868a9cce330d535ddf8fe8219984
| 21 | 118 | 0.65404 | 3.384615 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS
|
SmartReceipts/Common/Constants/Global.swift
|
2
|
1493
|
//
// Constants.swift
// SmartReceipts
//
// Created by Jaanus Siim on 16/05/16.
// Copyright © 2016 Will Baumann. All rights reserved.
//
import Foundation
let MIGRATION_VERSION = 2
let TOUCH_AREA: CGFloat = 44
let UI_MARGIN_8: CGFloat = 8
let UI_MARGIN_16: CGFloat = 16
let DEFAULT_ANIMATION_DURATION = 0.3
let VIEW_CONTROLLER_TRANSITION_DELAY = 0.6
func onMainThread(_ closure: @escaping VoidBlock) {
DispatchQueue.main.async(execute: closure)
}
func timeMeasured(_ desc: String = "", closure: () -> ()) {
let start = CACurrentMediaTime()
closure()
Logger.debug(String(format: "%@ - time: %f", desc, CACurrentMediaTime() - start))
}
func delayedExecution(_ afterSecons: TimeInterval, closure: @escaping () -> ()) {
let delayTime = DispatchTime.now() + Double(Int64(afterSecons * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime, execute: closure)
}
func LocalizedString(_ key: String, comment: String = "") -> String {
typealias OBJC_LocalizedString = LocalizedString
return OBJC_LocalizedString.from(key, comment: comment)
}
func MainStoryboard() -> UIStoryboard {
return UIStoryboard(name: "MainStoryboard_iPhone", bundle: nil)
}
func screenScaled(_ value: CGFloat) -> CGFloat {
return value * ((1.0/667.0) * UIScreen.main.bounds.height)
}
enum ReceiptAttachmentType {
case image
case pdf
case none
}
func ABSTRACT_METHOD() {
preconditionFailure("ABSTRACT_METHOD")
}
|
agpl-3.0
|
8a8a7089aedf603623cbb333d3237b48
| 25.642857 | 113 | 0.699732 | 3.63017 | false | false | false | false |
natebird/AdventofCode2015
|
Sources/NBFileManager.swift
|
1
|
692
|
import XCPlayground
import Foundation
public class NBFileManager: NSObject {
private struct Constants {
static let sharedInstance = NBFileManager()
}
public class var shared: NBFileManager {
return Constants.sharedInstance
}
public func loadStringInputFromResource(fileName: String) -> String {
var content = ""
if let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "txt"),
let data = NSFileManager.defaultManager().contentsAtPath(path),
let encoded = String(data: data, encoding: NSUTF8StringEncoding) {
content = encoded
}
return content
}
}
|
mit
|
79869fded0aea8c0253e36073acff8b6
| 27.833333 | 85 | 0.640173 | 5.536 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/UserInterface/Collections/TextSearch/TextSearchResultsView.swift
|
1
|
2523
|
//
// Wire
// Copyright (C) 2017 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 Foundation
import UIKit
final class TextSearchResultsView: UIView {
let tableView = UITableView()
let noResultsView = NoResultsView()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
createConstraints()
backgroundColor = .from(scheme: .contentBackground)
}
private func setupViews() {
tableView.register(TextSearchResultCell.self, forCellReuseIdentifier: TextSearchResultCell.reuseIdentifier)
tableView.estimatedRowHeight = 44
tableView.separatorStyle = .none
tableView.keyboardDismissMode = .interactive
tableView.backgroundColor = .clear
addSubview(tableView)
noResultsView.label.accessibilityLabel = "no text messages"
noResultsView.label.text = "collections.search.no_items".localized(uppercased: true)
noResultsView.icon = .search
addSubview(noResultsView)
}
private func createConstraints() {
[tableView, noResultsView].prepareForLayout()
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: topAnchor),
tableView.bottomAnchor.constraint(equalTo: bottomAnchor),
tableView.leftAnchor.constraint(equalTo: leftAnchor),
tableView.rightAnchor.constraint(equalTo: rightAnchor),
noResultsView.topAnchor.constraint(greaterThanOrEqualTo: topAnchor, constant: 12),
noResultsView.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -12),
noResultsView.centerXAnchor.constraint(equalTo: centerXAnchor),
noResultsView.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
5196e963698688fce40fd5bdbde19088
| 36.656716 | 115 | 0.713436 | 5.180698 | false | false | false | false |
cornerstonecollege/401
|
olderFiles/401_2016_2/swift_examples/Closures/Closures/main.swift
|
1
|
1690
|
//
// main.swift
// Closures
//
// Created by Luiz on 2016-09-27.
// Copyright © 2016 Ideia do Luiz. All rights reserved.
//
import Foundation
// create an alias to a new type called MyClosureType
typealias MyClosureType = () -> Void
// Example 1
// AutoClosures
var x = 1
var myAutoClosure = { // define an autoclosure (it cannot take params)
x += 1
}
myAutoClosure = { // redefine the autoclosure because it is var
x += 2
}
print(x)
myAutoClosure()
print(x) // x will be equal to 3 here
// Example 2
// Closures as last params
func sayHelloWorldAndAnotherThing(x:Int, anotherThing: MyClosureType)
{
print("Hello World \(x)")
anotherThing()
}
sayHelloWorldAndAnotherThing(x: 1) {
print("Hello World 2")
}
sayHelloWorldAndAnotherThing(x: 3, anotherThing: {
print("As a real param")
})
func anyFunction()
{
print("This function as a name")
}
sayHelloWorldAndAnotherThing(x: 5, anotherThing: anyFunction) // any function is a function
// Example 3
// Passing function as params
var fruits = ["Apple", "Orange", "Watermelon", "Tomato", "Banana"]
fruits += ["Lemon"]
print(fruits)
func mySortFunction(leftString: String, rightString:String) -> Bool
{
return leftString > rightString
}
fruits.sort(by: mySortFunction) // first way is good for practice
print(fruits)
fruits.sort (by:{ (str1:String, str2: String) -> Bool in // good for practice
return str1 < str2
})
fruits.sort() {(str1:String, str2: String) -> Bool in // not good for practice
return false;
}
fruits.sort{(str1:String, str2: String) -> Bool in // not good for practice
return true;
}
fruits.sort(by:{$0 > $1}) // good practice
fruits.sort(by: <) // good practice
|
gpl-3.0
|
fd777e05f82a1d227636bc2cc6fa3b57
| 19.597561 | 91 | 0.687389 | 3.279612 | false | false | false | false |
marklin2012/JDUtil
|
JDUtilDemo/JDUtilDemo/JDUtil/JDUIButton.swift
|
3
|
1296
|
//
// JDUIButton.swift
// JDUtilDemo
//
// Created by O2.LinYi on 15/12/24.
// Copyright © 2015年 jd.com. All rights reserved.
//
import UIKit
public extension UIButton {
public func centerVerticallyWithPadding(padding: CGFloat) {
if imageView == nil || titleLabel == nil {
return
}
let imageSize = imageView!.frame.size
let titleSize = titleLabel!.frame.size
let totalHeight = (imageSize.height + titleSize.height + padding)
self.imageEdgeInsets = UIEdgeInsetsMake(-(totalHeight - imageSize.height), 0.0, 0.0, -titleSize.width)
self.titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize.width, -(totalHeight - titleSize.height), 0.0)
}
public func centerVertically() {
self.centerVerticallyWithPadding(6.0)
}
public func centerVerticallyWithoutTitleLabel() {
titleLabel?.frame.size = CGSizeZero
titleLabel?.removeFromSuperview()
let imageSize = imageView!.frame.size
let width : CGFloat = (self.frame.width - imageSize.width) / 2
let height : CGFloat = (self.frame.height - imageSize.height) / 2
self.imageEdgeInsets = UIEdgeInsetsMake(height,
width, height, width)
}
}
|
mit
|
55a053c216ab1fdc2895230cb0fe65db
| 29.785714 | 110 | 0.627224 | 4.568905 | false | false | false | false |
anilkumarbp/ringcentral-swift-NEW
|
ringcentral-swift-develop-anilkumarbp/lib/http/Response.swift
|
2
|
1483
|
import Foundation
class Response: Headers {
var status: Int!
var statusText: String!
var body: String?
var data: NSData?
var response: NSURLResponse?
var error: NSError?
init(data: NSData?, response: NSURLResponse, error: NSError?) {
if let check = error {
super.init()
} else {
let feedback = (response as! NSHTTPURLResponse)
super.init(options: feedback.allHeaderFields)
status = feedback.statusCode
}
statusText = ""
if let check = data {
body = NSString(data: check, encoding: NSUTF8StringEncoding)! as String
}
}
func checkStatus() -> Bool {
return status >= 200 && status < 300
}
func getBody() -> String? {
return body
}
func getResponse() -> NSURLResponse? {
return response
}
func getData() -> NSData? {
return data
}
func getData() -> String? {
return body
}
// func getJson()
// func getResponses()
func getStatus() -> Int {
return status
}
func getStatusText() -> String {
return statusText
}
func getError() -> String {
if let x = error {
return x.description
} else {
return ""
}
}
func getError() -> NSError? {
return error
}
}
|
mit
|
e3d8435bb81c59fb6c0ffdbbfa9b03c6
| 19.054054 | 83 | 0.496291 | 4.97651 | false | false | false | false |
leannenorthrop/markdown-swift
|
MarkdownTests/WylieIntegrationTests.swift
|
1
|
3649
|
//
// ModuleUnitTests.swift
// Markdown
//
// Created by Leanne Northrop on 18/06/2015.
// Copyright (c) 2015 Leanne Northrop. All rights reserved.
//
import XCTest
import Markdown
class WylieIntegrationTests : XCTestCase {
let bundle = NSBundle(forClass: WylieIntegrationTests.self)
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testHeaders() {
runTests("headers", runXML: true, runHTML: true)
}
func testCode() {
runTests("code", runXML: true, runHTML: true)
}
func testWylie() {
runTests("wylie", runXML: true, runHTML: true)
}
func testHorizontalRules() {
runTests("horizontal_rules", runXML: true, runHTML: true)
}
func testLinks() {
runTests("links", runXML: true, runHTML: true)
}
func testBlockQuotes() {
runTests("blockquotes", runXML: true, runHTML: false)
}
func runTests(subDir : String, runXML : Bool, runHTML: Bool) -> () {
let tests : [String:String] = getFilenames(subDir)
for (test,file) in tests {
let testName = test
let mdInputFile = file
let mdOutputFile = file.replace(".text", replacement: ".xml")
let markdown = readFile(mdInputFile, type: "text")
if !markdown.isBlank() {
println("-------------------------------------------------------------------------------")
println(" Running " + testName)
let md : Markdown = Markdown()
let result : [AnyObject] = md.parse(markdown)
XCTAssertNotNil(result, testName + " failed to yield a result.")
if runXML {
let expected = readFile(mdOutputFile, type: "xml")
if !expected.isBlank() {
println("")
let xml = XmlRenderer().toXML(result, includeRoot: true)
XCTAssertEqual(expected, xml, testName + " test failed")
println("")
}
}
if runHTML {
let expectedHTML = readFile(file.replace(".text", replacement: ".html"), type: "html")
if !expectedHTML.isBlank() {
println("")
let html = HtmlRenderer().toHTML(result)
XCTAssertEqual(expectedHTML, html, testName + " HTML test failed")
println("")
}
}
}
}
}
func getFilenames(subDir:String) -> [String:String] {
let resourcePath : String = bundle.resourcePath!
let bundlePath = resourcePath + "/assets/" + subDir
let fm = NSFileManager.defaultManager()
let contents : [AnyObject]? = fm.contentsOfDirectoryAtPath(bundlePath, error: nil)
if contents != nil {
var files : [String:String] = [:]
for var i = 0; i < contents!.count; i++ {
var filename : String = contents![i] as! String
if filename.isMatch("text$") {
let path : String = resourcePath + "/assets/" + subDir + "/" + filename
files[filename.replace(".text", replacement:"")] = path
}
}
return files
}
return [:]
}
func readFile(path:String, type:String) -> String {
let content = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)!
return content
}
}
|
gpl-2.0
|
7a99f57eea9b3cf3be1b430bd17742b5
| 33.752381 | 106 | 0.508907 | 4.795007 | false | true | false | false |
loganSims/wsdot-ios-app
|
wsdot/BorderWaitsViewController.swift
|
1
|
8070
|
//
// BorderWaitViewController.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// 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 GoogleMobileAds
class BorderWaitsViewController: RefreshViewController, UITableViewDelegate, UITableViewDataSource, GADBannerViewDelegate {
let cellIdentifier = "borderwaitcell"
@IBOutlet weak var bannerView: DFPBannerView!
@IBOutlet weak var segmentedControlView: UISegmentedControl!
@IBOutlet weak var tableView: UITableView!
var displayedWaits = [BorderWaitItem]()
var northboundWaits = [BorderWaitItem]()
var southboundWaits = [BorderWaitItem]()
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
displayedWaits = northboundWaits
// refresh controller
refreshControl.addTarget(self, action: #selector(BorderWaitsViewController.refreshAction(_:)), for: .valueChanged)
tableView.addSubview(refreshControl)
showOverlay(self.view)
// remove southbound wait times until we can get more accurate times.
self.northboundWaits = BorderWaitStore.getNorthboundWaits()
//self.southboundWaits = BorderWaitStore.getSouthboundWaits()
self.tableView.reloadData()
refresh(false)
tableView.rowHeight = UITableView.automaticDimension
// Ad Banner
bannerView.adUnitID = ApiKeys.getAdId()
bannerView.rootViewController = self
bannerView.adSize = getFullWidthAdaptiveAdSize()
let request = DFPRequest()
request.customTargeting = ["wsdotapp":"border"]
bannerView.load(request)
bannerView.delegate = self
}
func adViewDidReceiveAd(_ bannerView: GADBannerView) {
bannerView.isAccessibilityElement = true
bannerView.accessibilityLabel = "advertisement banner."
}
@objc func refreshAction(_ refreshControl: UIRefreshControl) {
refresh(true)
}
func refresh(_ force: Bool){
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { [weak self] in
BorderWaitStore.updateWaits(force, completion: { error in
if (error == nil) {
// Reload tableview on UI thread
DispatchQueue.main.async { [weak self] in
if let selfValue = self{
selfValue.northboundWaits = BorderWaitStore.getNorthboundWaits()
selfValue.southboundWaits = BorderWaitStore.getSouthboundWaits()
if (selfValue.segmentedControlView.selectedSegmentIndex == 0){
selfValue.displayedWaits = selfValue.northboundWaits
} else {
selfValue.displayedWaits = selfValue.southboundWaits
}
selfValue.tableView.reloadData()
selfValue.hideOverlayView()
selfValue.refreshControl.endRefreshing()
}
}
} else {
DispatchQueue.main.async { [weak self] in
if let selfValue = self{
selfValue.hideOverlayView()
selfValue.refreshControl.endRefreshing()
AlertMessages.getConnectionAlert(backupURL: WsdotURLS.borderWaits, message: WSDOTErrorStrings.borderWaits)
}
}
}
})
}
}
// MARK: Table View Data Source Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayedWaits.count
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! BorderWaitCell
let wait = displayedWaits[indexPath.row]
cell.nameLabel.text = wait.name + " (" + wait.lane + ")"
do {
let updated = try TimeUtils.timeAgoSinceDate(date: TimeUtils.formatTimeStamp(wait.updated), numericDates: false)
cell.updatedLabel.text = updated
} catch TimeUtils.TimeUtilsError.invalidTimeString {
cell.updatedLabel.text = "N/A"
} catch {
cell.updatedLabel.text = "N/A"
}
if wait.waitTime == -1 {
cell.waitTimeLabel.text = "N/A"
}else if wait.waitTime < 5 {
cell.waitTimeLabel.text = "< 5 min"
}else{
cell.waitTimeLabel.text = String(wait.waitTime) + " min"
}
// set up favorite button
cell.favoriteButton.setImage(wait.selected ? UIImage(named: "icStarSmallFilled") : UIImage(named: "icStarSmall"), for: .normal)
cell.favoriteButton.tintColor = ThemeManager.currentTheme().darkColor
cell.favoriteButton.tag = indexPath.row
cell.favoriteButton.addTarget(self, action: #selector(favoriteAction(_:)), for: .touchUpInside)
cell.RouteImage.image = UIHelpers.getRouteIconFor(borderWait: wait)
return cell
}
// Remove and add hairline for nav bar
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let img = UIImage()
self.navigationController?.navigationBar.shadowImage = img
self.navigationController?.navigationBar.setBackgroundImage(img, for: .default)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MyAnalytics.screenView(screenName: "BorderWaitsNorthbound")
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.navigationBar.shadowImage = nil
self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
}
@IBAction func indexChanged(_ sender: UISegmentedControl) {
switch (sender.selectedSegmentIndex){
case 0:
MyAnalytics.screenView(screenName: "BorderWaitsNorthbound")
displayedWaits = northboundWaits
tableView.reloadData()
break
case 1:
MyAnalytics.screenView(screenName: "BorderWaitsSouthBound")
displayedWaits = southboundWaits
tableView.reloadData()
break
default:
break
}
}
// MARK: Favorite action
@objc func favoriteAction(_ sender: UIButton) {
let index = sender.tag
let wait = displayedWaits[index]
if (wait.selected){
BorderWaitStore.updateFavorite(wait, newValue: false)
sender.setImage(UIImage(named: "icStarSmall"), for: .normal)
}else {
BorderWaitStore.updateFavorite(wait, newValue: true)
sender.setImage(UIImage(named: "icStarSmallFilled"), for: .normal)
}
}
}
|
gpl-3.0
|
3af9e9cc7d66f176b2db4540a32cd137
| 37.066038 | 135 | 0.61834 | 5.219922 | false | false | false | false |
gottesmm/swift
|
test/Constraints/diag_missing_arg.swift
|
5
|
9931
|
// RUN: %target-typecheck-verify-swift
func nonNamedFunc(_ x: Int) {} // expected-note * {{here}}
nonNamedFunc() // expected-error {{missing argument for parameter #1 in call}} {{14-14=<#Int#>}}
func namedFunc(x: Int) {} // expected-note * {{here}}
namedFunc() // expected-error {{missing argument for parameter 'x' in call}} {{11-11=x: <#Int#>}}
func inoutFunc(x: inout Int) {} // expected-note * {{here}}
inoutFunc() // expected-error {{missing argument for parameter 'x' in call}} {{11-11=x: &<#Int#>}}
func autoclosureFunc(x: @autoclosure () -> Int) {} // expected-note * {{here}}
autoclosureFunc() // expected-error {{missing argument for parameter 'x' in call}} {{17-17=x: <#Int#>}}
func attributedFunc(x: @convention(c) () -> Int32) {} // expected-note * {{here}}
attributedFunc() // expected-error {{missing argument for parameter 'x' in call}} {{16-16=x: <#@convention(c) () -> Int32#>}}
func attributedInOutFunc(x: inout @convention(c) () -> Int32) {} // expected-note * {{here}}
attributedInOutFunc() // expected-error {{missing argument for parameter 'x' in call}} {{21-21=x: &<#@convention(c) () -> Int32#>}}
func genericFunc1<T>(x: T) {} // expected-note * {{here}}
genericFunc1() // expected-error {{missing argument for parameter 'x' in call}} {{14-14=x: <#T#>}}
protocol P {}
func genericFunc2<T : P>(x: T) {} // expected-note * {{here}}
genericFunc2() // expected-error {{missing argument for parameter 'x' in call}} {{14-14=x: <#T#>}}
typealias MyInt = Int
func aliasedFunc(x: MyInt) {} // expected-note * {{here}}
aliasedFunc() // expected-error {{missing argument for parameter 'x' in call}} {{13-13=x: <#MyInt#>}}
func trailingClosureSingle1(x: Int, y: () -> Int) {} // expected-note * {{here}}
trailingClosureSingle1 { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{23-23=(x: <#Int#>)}}
trailingClosureSingle1() { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{24-24=x: <#Int#>}}
func trailingClosureSingle2(x: () -> Int, y: Int) {} // expected-note * {{here}}
// FIXME: Bad diagnostics.
trailingClosureSingle2 { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{23-23=(x: <#() -> Int#>)}}
trailingClosureSingle2() { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{24-24=x: <#() -> Int#>}}
func trailingClosureMulti1(x: Int, y: Int, z: () -> Int) {} // expected-note * {{here}}
trailingClosureMulti1(y: 1) { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{23-23=x: <#Int#>, }}
trailingClosureMulti1(x: 1) { 1 } // expected-error {{missing argument for parameter 'y' in call}} {{27-27=, y: <#Int#>}}
trailingClosureMulti1(x: 1, y: 1) // expected-error {{missing argument for parameter 'z' in call}} {{33-33=, z: <#() -> Int#>}}
func trailingClosureMulti2(x: Int, y: () -> Int, z: Int) {} // expected-note * {{here}}
trailingClosureMulti2 { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{22-22=(x: <#Int#>)}}
// FIXME: Bad diagnostics.
trailingClosureMulti2() { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{23-23=x: <#Int#>}}
trailingClosureMulti2(x: 1) { 1 } // expected-error {{missing argument for parameter 'y' in call}} {{27-27=, y: <#() -> Int#>}}
func param2Func(x: Int, y: Int) {} // expected-note * {{here}}
param2Func(x: 1) // expected-error {{missing argument for parameter 'y' in call}} {{16-16=, y: <#Int#>}}
param2Func(y: 1) // expected-error {{missing argument for parameter 'x' in call}} {{12-12=x: <#Int#>, }}
func param2FuncNonNamed1(_ x: Int, y: String) {} // expected-note * {{here}}
param2FuncNonNamed1(1) // expected-error {{missing argument for parameter 'y' in call}} {{22-22=, y: <#String#>}}
param2FuncNonNamed1(y: "foo") // expected-error {{missing argument for parameter #1 in call}} {{21-21=<#Int#>, }}
func param2FuncNonNamed2(x: Int, _ y: String) {} // expected-note * {{here}}
param2FuncNonNamed2(x: 1) // expected-error {{missing argument for parameter #2 in call}} {{25-25=, <#String#>}}
param2FuncNonNamed2("foo") // expected-error {{missing argument for parameter 'x' in call}} {{21-21=x: <#Int#>, }}
func param2FuncNonNamed3(_ x: Int, _ y: String) {} // expected-note * {{here}}
param2FuncNonNamed3(1) // expected-error {{missing argument for parameter #2 in call}} {{22-22=, <#String#>}}
param2FuncNonNamed3("foo") // expected-error {{missing argument for parameter #2 in call}} {{26-26=, <#String#>}}
// FIXME: Bad diagnostic. Could this be #1?
func param3Func(x: Int, y: Int, z: Int) {} // expected-note * {{here}}
param3Func(x: 1, y: 1) // expected-error {{missing argument for parameter 'z' in call}} {{22-22=, z: <#Int#>}}
param3Func(x: 1, z: 1) // expected-error {{missing argument for parameter 'y' in call}} {{16-16=, y: <#Int#>}}
param3Func(y: 1, z: 1) // expected-error {{missing argument for parameter 'x' in call}} {{12-12=x: <#Int#>, }}
func hasDefault1(x: Int, y: Int = 1) {} // expected-note * {{here}}
hasDefault1(x: 1) // ok
hasDefault1(y: 1) // expected-error {{missing argument for parameter 'x' in call}} {{13-13=x: <#Int#>, }}
func hasDefault2(x: Int = 1, y: Int) {} // expected-note * {{here}}
hasDefault2(x: 1) // expected-error {{missing argument for parameter 'y' in call}} {{17-17=, y: <#Int#>}}
hasDefault2(y: 1) // ok
struct S { init(x: Int, y: () -> Int) {} } // expected-note * {{here}}
_ = S(x: 1) // expected-error {{missing argument for parameter 'y' in call}} {{11-11=, y: <#() -> Int#>}}
_ = S(y: { 1 }) // expected-error {{missing argument for parameter 'x' in call}} {{7-7=x: <#Int#>, }}
_ = S { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{6-6=(x: <#Int#>)}}
_ = S() { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{7-7=x: <#Int#>}}
struct S1 {
subscript(x x: Int, y y: () -> Int) -> Int { get { return 1 } set { } } // expected-note * {{here}}
}
var s1 = S1()
_ = s1[x: 1, y: {1}] // Ok.
_ = s1[x: 1] { 1 } // Ok.
_ = s1[x: 1] // expected-error {{missing argument for parameter 'y' in call}} {{12-12=, y: <#() -> Int#>}}
_ = s1[y: { 1 }] // expected-error {{missing argument for parameter 'x' in call}} {{8-8=x: <#Int#>, }}
_ = s1[] { 1 } // expected-error {{cannot convert value of type '() -> Int' to expected argument type '(x: Int, y: () -> Int)'}} {{none}}
_ = s1 { 1 } // expected-error {{cannot call value of non-function type 'S1'}} {{none}}
_ = s1[] // expected-error {{missing argument for parameter 'x' in call}} {{8-8=x: <#Int#>}}
s1[x: 1, y: {1}] = 1 // Ok.
s1[x: 1] { 1 } = 1 // Ok.
s1[x: 1] = 1 // expected-error {{missing argument for parameter 'y' in call}} {{8-8=, y: <#() -> Int#>}}
s1[y: { 1 }] = 1 // expected-error {{missing argument for parameter 'x' in call}} {{4-4=x: <#Int#>, }}
s1[] { 1 } = 1 // expected-error {{cannot convert value of type '() -> Int' to expected argument type '(x: Int, y: () -> Int)'}} {{none}}
struct S2 {
subscript(x: Int, y: () -> Int) -> Int { get { return 1 } set { } } // expected-note * {{here}}
}
var s2 = S2()
_ = s2[1, {1}] // Ok.
_ = s2[1] { 1 } // Ok.
_ = s2[1] // expected-error {{cannot convert value of type 'Int' to expected argument type '(Int, () -> Int)'}} {{none}}
_ = s2[{ 1 }] // expected-error {{cannot convert value of type '() -> Int' to expected argument type '(Int, () -> Int)'}} {{none}}
_ = s2[] { 1 } // expected-error {{cannot convert value of type '() -> Int' to expected argument type '(Int, () -> Int)'}} {{none}}
_ = s2 { 1 } // expected-error {{cannot call value of non-function type 'S2'}} {{none}}
_ = s2[] // expected-error {{missing argument for parameter #1 in call}} {{8-8=<#Int#>}}
s2[1, {1}] = 1 // Ok.
s2[1] { 1 } = 1 // Ok.
s2[1] = 1 // expected-error {{cannot convert value of type 'Int' to expected argument type '(Int, () -> Int)'}} {{none}}
s2[{ 1 }] = 1 // expected-error {{cannot convert value of type '() -> Int' to expected argument type '(Int, () -> Int)'}} {{none}}
s2[] { 1 } = 1 // expected-error {{cannot convert value of type '() -> Int' to expected argument type '(Int, () -> Int)'}} {{none}}
struct S3 {
subscript(x x: Int, y y: Int, z z: (Int) -> Int) -> Int { get { return 1 } set { } } // expected-note * {{here}}
}
var s3 = S3()
_ = s3[y: 1] { 1 } // expected-error {{missing argument for parameter 'x' in call}} {{8-8=x: <#Int#>, }}
_ = s3[x: 1] { 1 } // expected-error {{missing argument for parameter 'y' in call}} {{12-12=, y: <#Int#>}}
_ = s3[x: 1, y: 1] // expected-error {{missing argument for parameter 'z' in call}} {{18-18=, z: <#(Int) -> Int#>}}
s3[y: 1] { 1 } = 1 // expected-error {{missing argument for parameter 'x' in call}} {{4-4=x: <#Int#>, }}
s3[x: 1] { 1 } = 1 // expected-error {{missing argument for parameter 'y' in call}} {{8-8=, y: <#Int#>}}
s3[x: 1, y: 1] = 1 // expected-error {{missing argument for parameter 'z' in call}} {{14-14=, z: <#(Int) -> Int#>}}
struct S4 {
subscript(x: Int, y: Int, z: (Int) -> Int) -> Int { get { return 1 } set { } } // expected-note * {{here}}
}
var s4 = S4()
_ = s4[1] { 1 } // expected-error {{missing argument for parameter #2 in call}} {{9-9=, <#Int#>}}
_ = s4[1, 1] // expected-error {{missing argument for parameter #3 in call}} {{12-12=, <#(Int) -> Int#>}}
s4[1] { 1 } = 1 // expected-error {{missing argument for parameter #2 in call}} {{5-5=, <#Int#>}}
s4[1, 1] = 1 // expected-error {{missing argument for parameter #3 in call}} {{8-8=, <#(Int) -> Int#>}}
func multiLine(x: Int, y: Int, z: Int) {} // expected-note * {{here}}
multiLine(
) // expected-error {{missing argument for parameter 'x' in call}} {{1-1=x: <#Int#>}}
multiLine(
y: 1, // expected-error {{missing argument for parameter 'x' in call}} {{3-3=x: <#Int#>, }}
z: 1
)
multiLine(
x: 1, // expected-error {{missing argument for parameter 'y' in call}} {{7-7=, y: <#Int#>}}
z: 1
)
multiLine(
x: 1,
y: 1 // expected-error {{missing argument for parameter 'z' in call}} {{7-7=, z: <#Int#>}}
)
|
apache-2.0
|
745f185994a79554c4dbb84267055a01
| 62.660256 | 137 | 0.599335 | 3.034219 | false | false | false | false |
Jamol/Nutil
|
Sources/AutoScoket.swift
|
1
|
4959
|
//
// AutoScoket.swift
// Nutil
//
// Created by Jamol Bao on 12/22/16.
// Copyright © 2016 Jamol Bao. All rights reserved.
// Contact: [email protected]
//
import Foundation
class AutoScoket {
fileprivate var tcp: TcpSocket?
fileprivate var ssl: SslSocket?
fileprivate var cbConnect: ErrorCallback?
fileprivate var cbRead: EventCallback?
fileprivate var cbWrite: EventCallback?
fileprivate var cbClose: EventCallback?
fileprivate func initTcpSocket() {
if tcp != nil {
return
}
tcp = TcpSocket()
tcp!
.onConnect { err in
self.cbConnect?(err)
}
.onRead {
self.cbRead?()
}
.onWrite {
self.cbWrite?()
}
.onClose {
self.cbClose?()
}
}
fileprivate func initSslSocket() {
if ssl != nil {
return
}
ssl = SslSocket()
ssl!
.onConnect { err in
self.cbConnect?(err)
}
.onRead {
self.cbRead?()
}
.onWrite {
self.cbWrite?()
}
.onClose {
self.cbClose?()
}
}
func bind(_ addr: String, _ port: Int) -> KMError {
if let s = ssl {
return s.bind(addr, port)
}
initTcpSocket()
return tcp!.bind(addr, port)
}
func connect(_ addr: String, _ port: Int) -> KMError {
if let s = ssl {
return s.connect(addr, port)
}
initTcpSocket()
return tcp!.connect(addr, port)
}
func attachFd(_ fd: Int32) -> KMError {
if let s = ssl {
return s.attachFd(fd)
}
initTcpSocket()
return tcp!.attachFd(fd)
}
func close() {
if let ssl = ssl {
ssl.close()
}
if let tcp = tcp {
tcp.close()
}
}
}
extension AutoScoket {
func read<T>(_ data: UnsafeMutablePointer<T>, _ len: Int) -> Int {
if let ssl = ssl {
return ssl.read(data, len)
}
if let tcp = tcp {
return tcp.read(data, len)
}
return -1
}
func write(_ str: String) -> Int {
if let ssl = ssl {
return ssl.write(str)
}
if let tcp = tcp {
return tcp.write(str)
}
return -1
}
func write<T>(_ data: [T]) -> Int {
if let ssl = ssl {
return ssl.write(data)
}
if let tcp = tcp {
return tcp.write(data)
}
return -1
}
func write<T>(_ data: UnsafePointer<T>, _ len: Int) -> Int {
if let ssl = ssl {
return ssl.write(data, len)
}
if let tcp = tcp {
return tcp.write(data, len)
}
return -1
}
func writev(_ iovs: [iovec]) -> Int {
if let ssl = ssl {
return ssl.writev(iovs)
}
if let tcp = tcp {
return tcp.writev(iovs)
}
return -1
}
}
extension AutoScoket {
func setSslFlags(_ flags: UInt32) {
if flags != SslFlag.none.rawValue {
initSslSocket()
ssl!.setSslFlags(flags)
}
}
func getSslFlags() -> UInt32 {
if let s = ssl {
return s.getSslFlags()
}
return SslFlag.none.rawValue
}
func sslEnabled() -> Bool {
return ssl != nil
}
func setAlpnProtocols(_ alpn: AlpnProtos) {
initSslSocket()
ssl!.setAlpnProtocols(alpn)
}
func getAlpnSelected() -> String? {
if let ssl = ssl {
return ssl.getAlpnSelected()
}
return nil
}
func setServerName(_ name: String) {
initSslSocket()
ssl!.setSslServerName(name)
}
}
extension AutoScoket {
@discardableResult public func onConnect(_ cb: @escaping (KMError) -> Void) -> Self {
cbConnect = cb
return self
}
@discardableResult public func onRead(_ cb: @escaping () -> Void) -> Self {
cbRead = cb
return self
}
@discardableResult public func onWrite(_ cb: @escaping () -> Void) -> Self {
cbWrite = cb
return self
}
@discardableResult public func onClose(_ cb: @escaping () -> Void) -> Self {
cbClose = cb
return self
}
}
extension AutoScoket {
func sync(_ block: (() -> Void)) {
if let ssl = ssl {
ssl.sync(block)
}
if let tcp = tcp {
tcp.sync(block)
}
}
func async(_ block: @escaping (() -> Void)) {
if let ssl = ssl {
ssl.async(block)
}
if let tcp = tcp {
tcp.async(block)
}
}
}
|
mit
|
9862a69ba98d0ec320b89697b7f99be4
| 21.133929 | 89 | 0.463695 | 3.988737 | false | false | false | false |
DaveChambers/SuperCrack
|
SuperCrack!/HoleModel.swift
|
1
|
2064
|
//
// HoleModel.swift
// Pegs in the Head
//
// Created by Dave Chambers on 04/07/2017.
// Copyright © 2017 Dave Chambers. All rights reserved.
//
import Foundation
enum HoleType: Int, CustomStringConvertible {
case unknown = 0, codeHole, paletteHole, playableHole, voidHole
private var holeType: String {
let holeTypes = [
"Code_Hole",
"Palette_Hole",
"Playable_Hole",
"Void_Hole"]
return holeTypes[rawValue - 1]
}
var description: String {
return holeType
}
}
class Hole: CustomStringConvertible {
private var holeType: HoleType
private var column: Int
private var row: Int
private var hidden: Bool
private var staticPeg: Peg? //Can NOT move - just to colour the Hole
private var dynamicPeg: Peg? //Can be dragged
private var paletteColour: PegColour? //Remove?
var description: String {
return "Type of Hole: \(holeType). \t\tStatic Peg in the hole: \(String(describing: staticPeg)) \t\tDynamic Peg in the hole: \(String(describing: dynamicPeg)). \tHole Location:(\(column),\(row))"
}
init(holeType: HoleType, column: Int, row: Int, staticPeg: Peg?, dynamicPeg: Peg?, isHidden: Bool, paletteColour: PegColour) {
self.holeType = holeType
self.column = column
self.row = row
self.staticPeg = staticPeg
self.dynamicPeg = dynamicPeg
self.hidden = isHidden
self.paletteColour = paletteColour
}
func getHoleType() -> HoleType {
return holeType
}
func getColumn() -> Int {
return column
}
func getRow() -> Int {
return row
}
func isHidden() -> Bool {
return hidden
}
func setHidden(isHidden: Bool) {
hidden = isHidden
}
func getStaticPeg() -> Peg? {
return staticPeg
}
func getDynamicPeg() -> Peg? {
return dynamicPeg
}
func getPegPair() -> (staticPeg: Peg?, dynamicPeg: Peg?) {
return (staticPeg, dynamicPeg)
}
func getPaletteColour() -> PegColour? {
return paletteColour
}
}
|
mit
|
79c1e61e38b117d76f7b6958e2538c11
| 21.922222 | 199 | 0.631604 | 3.651327 | false | false | false | false |
dehesa/apple-utilites
|
Sources/Apple/Visuals/Views/AnimatableView.swift
|
2
|
1686
|
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
#if os(iOS) || os(tvOS)
open class AnimatableView<Layer:CALayer>: UIView where Layer:Animatable {
open override static var layerClass : AnyClass {
return Layer.self
}
open override func willMove(toWindow newWindow: UIWindow?) {
guard let screen = newWindow?.screen else { return }
layer.contentsScale = screen.scale
layer.setNeedsLayout()
}
}
#elseif os(macOS)
open class AnimatableView<Layer:CALayer>: NSView where Layer:Animatable {
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.layer = self.makeBackingLayer()
self.wantsLayer = true
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.layer = self.makeBackingLayer()
self.wantsLayer = true
}
open override func makeBackingLayer() -> CALayer {
return Layer()
}
open override func viewDidChangeBackingProperties() {
guard let scale = self.window?.backingScaleFactor,
let layer = self.layer else { return }
layer.contentsScale = scale
layer.setNeedsLayout()
}
}
#endif
#if os(macOS) || os(iOS) || os(tvOS)
extension AnimatableView: Animatable {
public var isAnimating: Bool {
return (self.layer as! Animatable).isAnimating
}
public func startAnimating(withDuration duration: TimeInterval?) {
(self.layer as! Animatable).startAnimating(withDuration: duration)
}
public func stopAnimating() {
(self.layer as! Animatable).stopAnimating()
}
}
#endif
|
mit
|
af3e75aae0223ef870dc9553c43c5bfb
| 26.639344 | 74 | 0.648873 | 4.508021 | false | false | false | false |
VivaReal/Compose
|
Example/Compose_Example/Classes/Modules/MultipleColumnsExample/MultipleColumnViewController.swift
|
1
|
1459
|
//
// MultipleColumnViewController.swift
// Compose_Example
//
// Created by Bruno Bilescky on 25/10/16.
// Copyright © 2016 VivaReal. All rights reserved.
//
import UIKit
import Compose
class MultipleColumnViewController: UIViewController {
@IBOutlet var orientationSegmentedControl: UISegmentedControl!
@IBOutlet var multipleView: MultipleColumnView!
override func viewDidLoad() {
super.viewDidLoad()
let addItem = UIBarButtonItem(title: " + ", style: .plain, target: self, action: #selector(self.addColumn))
let deleteItem = UIBarButtonItem(title: " - ", style: .plain, target: self, action: #selector(self.removeColumn))
self.navigationItem.rightBarButtonItems = [addItem, deleteItem]
multipleView.viewState = MultipleColumnViewState(numberOfItems: 1, vertical: true)
multipleView.updateWith {
return randomColors(maxColors: 35).map { MultipleColumnViewUnits.SingleUnit(color: $0) }
}
}
@IBAction func addColumn() {
multipleView.viewState.numberOfItems = min(multipleView.viewState.numberOfItems + 1, 5)
}
@IBAction func removeColumn() {
multipleView.viewState.numberOfItems = max(multipleView.viewState.numberOfItems - 1, 1)
}
@IBAction func changeOrientation(segmentControl: UISegmentedControl) {
multipleView.viewState.isVertical = segmentControl.selectedSegmentIndex == 0
}
}
|
mit
|
6df3ef08e456892548c7969c948330af
| 33.714286 | 121 | 0.698903 | 4.688103 | false | false | false | false |
ryanipete/AmericanChronicle
|
AmericanChronicle/Code/Modules/USStatePicker/View/USStatePickerViewController.swift
|
1
|
4776
|
import UIKit
// MARK: -
// MARK: USStatePickerUserInterface protocol
protocol USStatePickerUserInterface {
var stateNames: [String] { get set }
func setSelectedStateNames(_ selectedStates: [String])
}
// MARK: -
// MARK: USStatePickerUserInterfaceDelegate protocol
protocol USStatePickerUserInterfaceDelegate: AnyObject {
func userDidTapSave(with selectedStateNames: [String])
func userDidTapCancel()
}
// MARK: -
// MARK: USStatePickerViewController class
final class USStatePickerViewController: UICollectionViewController,
USStatePickerUserInterface,
UICollectionViewDelegateFlowLayout {
// MARK: Properties
weak var delegate: USStatePickerUserInterfaceDelegate?
var stateNames: [String] = []
// MARK: Init methods
func commonInit() {
navigationItem.title = "U.S. States".localized()
navigationItem.setLeftButtonTitle("Cancel".localized(),
target: self,
action: #selector(didTapCancelButton))
navigationItem.setRightButtonTitle("Save".localized(),
target: self,
action: #selector(didTapSaveButton))
}
convenience init() {
self.init(collectionViewLayout: UICollectionViewFlowLayout())
}
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: Internal methods
func setSelectedStateNames(_ selectedStates: [String]) {
for selectedState in selectedStates {
if let idx = stateNames.firstIndex(of: selectedState) {
collectionView?.selectItem(
at: IndexPath(item: idx, section: 0),
animated: false,
scrollPosition: .top)
}
}
}
@objc func didTapCancelButton() {
delegate?.userDidTapCancel()
}
@objc func didTapSaveButton() {
let selectedIndexPaths = collectionView?.indexPathsForSelectedItems ?? []
let selectedStateNames = selectedIndexPaths.map { self.stateNames[($0 as NSIndexPath).item] }
delegate?.userDidTapSave(with: selectedStateNames)
}
// MARK: UICollectionViewDelegateFlowLayout methods
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let columnCount = 1
let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout
let left = flowLayout?.sectionInset.left ?? 0
let right = flowLayout?.sectionInset.right ?? 0
let totalInteritemSpacing = (flowLayout?.minimumInteritemSpacing ?? 0) * CGFloat(columnCount - 1)
let availableWidth = collectionView.bounds.width - (left + totalInteritemSpacing + right)
let columnWidth = availableWidth / CGFloat(columnCount)
return CGSize(width: columnWidth, height: Dimension.buttonHeight)
}
// MARK: UICollectionViewController overrides
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
stateNames.count
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: USStateCell = collectionView.dequeueCellForItemAtIndexPath(indexPath)
cell.label.text = stateNames[(indexPath as NSIndexPath).row]
return cell
}
// MARK: UIViewController overrides
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(USStateCell.self,
forCellWithReuseIdentifier: NSStringFromClass(USStateCell.self))
collectionView?.allowsMultipleSelection = true
collectionView?.backgroundColor = AMCColor.offWhite.withAlphaComponent(0.8)
let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
layout?.sectionInset = UIEdgeInsets(top: Dimension.verticalMargin,
left: Dimension.horizontalMargin,
bottom: Dimension.verticalMargin,
right: Dimension.horizontalMargin)
layout?.minimumInteritemSpacing = 1.0
layout?.minimumLineSpacing = 1.0
}
}
|
mit
|
2b299234d4dbf646db71729e77bc816e
| 36.3125 | 105 | 0.631072 | 6.146718 | false | false | false | false |
ahoppen/swift
|
test/SourceKit/CursorInfo/cursor_opaque_result.swift
|
9
|
1898
|
public protocol P {
associatedtype Assoc
func foo() -> Assoc
}
extension P {
func bar() -> Assoc { fatalError() }
}
public struct MyStruct: P {
public func foo() -> some Comparable { 1 }
}
func test(value: MyStruct) {
value.foo()
value.bar()
}
// RUN: %sourcekitd-test -req=cursor -pos=13:9 %s -- %s -module-name MyModule | %FileCheck --check-prefix=OPAQUE %s
// RUN: %sourcekitd-test -req=cursor -pos=14:9 %s -- %s -module-name MyModule | %FileCheck --check-prefix=ASSOC %s
// OPAQUE: foo()
// OPAQUE-NEXT: s:8MyModule0A6StructV3fooQryF
// OPAQUE-NEXT: source.lang.swift
// OPAQUE-NEXT: (MyStruct) -> () -> some Comparable
// OPAQUE-NEXT: $sQrycD
// OPAQUE-NEXT: <Container>$s8MyModule0A6StructVD</Container>
// OPAQUE-NEXT: MyModule{{$}}
// OPAQUE-NEXT: <Declaration>public func foo() -> some <Type usr="s:SL">Comparable</Type></Declaration>
// OPAQUE-NEXT: <decl.function.method.instance><syntaxtype.keyword>public</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>() -> <decl.function.returntype><syntaxtype.keyword>some</syntaxtype.keyword> <ref.protocol usr="s:SL">Comparable</ref.protocol></decl.function.returntype></decl.function.method.instance>
// ASSOC: bar()
// ASSOC-NEXT: s:8MyModule1PPAAE3bar5AssocQzyF
// ASSOC-NEXT: source.lang.swift
// ASSOC-NEXT: <Self where Self : P> (Self) -> () -> Self.Assoc
// ASSOC-NEXT: $s5AssocQzycD
// ASSOC-NEXT: <Container>$s8MyModule0A6StructVD</Container>
// ASSOC-NEXT: MyModule{{$}}
// ASSOC-NEXT: <Declaration>func bar() -> <Type usr="s:8MyModule0A6StructV5Assoca">Assoc</Type></Declaration>
// ASSOC-NEXT: <decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>bar</decl.name>() -> <decl.function.returntype><ref.typealias usr="s:8MyModule0A6StructV5Assoca">Assoc</ref.typealias></decl.function.returntype></decl.function.method.instance>
|
apache-2.0
|
703a19d77b4bb2a2871f6484eb22efea
| 47.666667 | 357 | 0.718124 | 3.086179 | false | true | false | false |
zhouxj6112/ARKit
|
ARHome/ARHome/ProductsViewController.swift
|
1
|
10865
|
//
// ProductsViewController.swift
// ARHome
//
// Created by MrZhou on 2017/11/24.
// Copyright © 2017年 vipme. All rights reserved.
//
import UIKit
import SwiftyJSON
import ARKit
class ModelTableCell : UITableViewCell {
public var mImageView:UIImageView?
public var mTitleLabel:UILabel?
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//
self.mImageView = UIImageView.init(frame: CGRect.init(x: 10, y: 2, width: 40, height: 40));
self.contentView.addSubview(mImageView!)
self.mTitleLabel = UILabel.init(frame: CGRect.init(x: 60, y: 12, width: 180, height: 20));
self.contentView.addSubview(mTitleLabel!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ProductsViewController: UIViewController {
private var tableView1:UITableView?;
private var tableView2:UITableView?;
private var mSellerList:NSArray = [];
private var mModelList:NSArray = [];
public static func navForProductsViewController() -> UINavigationController {
let vc = ProductsViewController()
let nav = UINavigationController.init(rootViewController: vc)
return nav
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationItem.title = "所有家具"
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "user_setting"), style: .plain, target: self, action: #selector(toSetting))
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "example"), style: .plain, target: self, action: #selector(toExamples))
tableView1 = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: 120, height: self.view.frame.size.height), style: UITableViewStyle.plain)
tableView1?.dataSource = self
tableView1?.delegate = self
self.view.addSubview(tableView1!)
tableView2 = UITableView.init(frame: CGRect.init(x: 120, y: 0, width: self.view.frame.size.width-120, height: self.view.frame.size.height), style: UITableViewStyle.plain)
tableView2?.dataSource = self
tableView2?.delegate = self
self.view.addSubview(tableView2!)
// 注册cell
tableView2?.register(ObjectCell.self, forCellReuseIdentifier: ObjectCell.reuseIdentifier)
//
let preId = UserDefaults.standard.value(forKey: "user_default_seller")
var sId:NSInteger = 0
if preId != nil {
sId = preId as! NSInteger
}
// 获取所有商家列表
NetworkingHelper.get(url: req_sellerlist_url, parameters: nil, callback: { (data:JSON?, error:NSError?) in
if error == nil {
let items = data!["items"]
self.mSellerList = items.rawValue as! NSArray
self.tableView1?.reloadData()
for (index, value) in self.mSellerList.enumerated() {
let item = value as! Dictionary<String, Any?>
let sellerId = item["sellerId"] as! NSInteger
if sellerId == sId {
self.tableView1?.selectRow(at: IndexPath.init(row: index, section: 0), animated: false, scrollPosition: .top)
break;
}
}
} else {
print("接口失败")
}
})
// 默认展示个商家里面的所有模型
NetworkingHelper.get(url: req_modellist_url, parameters: ["sellerId":sId], callback: { (data:JSON?, error:NSError?) in
if error == nil {
let items = data?.rawValue as! NSArray
self.mModelList = items
self.tableView2?.reloadData()
} else {
print("接口失败")
}
})
}
func getModelListForSeller(sId: NSInteger) -> Void {
// 获取某个商家下所有家具模型
NetworkingHelper.get(url: req_modellist_url, parameters: ["sId":sId]) { (data, error) in
//
}
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension ProductsViewController : UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == self.tableView1 {
return 1
} else {
return mModelList.count
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView1 {
return mSellerList.count
} else {
let sData = mModelList.object(at: section)
let data = sData as! Dictionary<String, Any>
let list = data["list"] as! NSArray
return list.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableView1 {
let ident1:String = "cell1"
var cell = tableView.dequeueReusableCell(withIdentifier: ident1)
if cell == nil {
cell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: ident1)
}
let cellData = self.mSellerList.object(at: indexPath.row)
let data = cellData as! Dictionary<String, Any>
let sName = data["sellerName"] as! String
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.textAlignment = .center
cell?.textLabel?.text = sName
return cell!
} else {
let ident2:String = "cell2"
// var cell:ModelTableCell = tableView.dequeueReusableCell(withIdentifier: ident2) as! ModelTableCell
// if cell == nil {
// cell = ModelTableCell.init(style: UITableViewCellStyle.default, reuseIdentifier: ident2)
// }
let cell = ModelTableCell.init(style: UITableViewCellStyle.default, reuseIdentifier: ident2)
let sData = self.mModelList[indexPath.section]
let section = sData as! Dictionary<String, Any>
let list = section["list"] as! NSArray
//
let data = list[indexPath.row] as! Dictionary<String, Any>
let sName = data["modelName"] as! String
cell.mTitleLabel?.text = sName
let sImage = data["compressImage"] as! String
cell.mImageView?.loadImageWithUrl(imageUrl: sImage)
return cell
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if tableView == self.tableView2 {
return 40
}
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == self.tableView1 {
return 60
}
return 44
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if tableView == self.tableView2 {
let sData = self.mModelList.object(at: section)
let data = sData as! Dictionary<String, Any>
let tName = data["typeName"] as! String
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
headerView.backgroundColor = UIColor.lightGray
let label = UILabel.init(frame: CGRect.init(x: 10, y: 0, width: 120, height: 40))
label.text = tName
headerView.addSubview(label)
return headerView
}
return nil
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == self.tableView1 {
let data = self.mSellerList.object(at: indexPath.row) as! NSDictionary
let sId = data.object(forKey: "sellerId") as! NSInteger
//
NetworkingHelper.get(url: req_modellist_url, parameters: ["sellerId":sId], callback: { (data:JSON?, error:NSError?) in
if error == nil {
let items = data?.rawValue as! NSArray
self.mModelList = items
self.tableView2?.reloadData()
} else {
print("接口失败")
}
})
UserDefaults.standard.set(sId, forKey: "user_default_seller")
} else {
let sData = self.mModelList.object(at: indexPath.section) as! Dictionary<String, Any>
let list = sData["list"] as! NSArray
let cellData = list[indexPath.row] as! Dictionary<String, Any>
let modelId = cellData["modelId"] as! String // 模型id
let sId = modelId.components(separatedBy: "_")[0]
self.toAR(sId: sId)
}
}
private func toAR(sId: String) {
if ARWorldTrackingConfiguration.isSupported {
let stroyboard = UIStoryboard.init(name: "Main", bundle: Bundle(identifier: "Main"))
let vc = stroyboard.instantiateInitialViewController() as! ViewController
present(vc, animated: true, completion: {
//
NetworkingHelper.get(url: req_modellist_url, parameters: ["sellerId":sId], callback: { (data:JSON?, error:NSError?) in
if error == nil {
let items = data?.rawValue as! NSArray
vc.resetModelList(array: items)
} else {
print("接口失败")
}
})
})
} else {
// if ReplayKitUtil.isRecording() {
// ReplayKitUtil.stopRecoder();
// } else {
// ReplayKitUtil.startRecoder(self);
// }
}
}
@objc private func toSetting() {
let vc = SettingViewController();
self.navigationController?.pushViewController(vc, animated: true)
}
@objc private func toExamples() {
let vc = HomeViewController();
self.navigationController?.pushViewController(vc, animated: true)
}
}
|
apache-2.0
|
fef2ad4118880778b76b2567965e68d7
| 39.2397 | 178 | 0.589352 | 4.655113 | false | false | false | false |
coreyjv/Emby.ApiClient.Swift
|
Emby.ApiClient/model/apiclient/ServerCredentials.swift
|
1
|
3560
|
//
// ServerCredentials.swift
// Emby.ApiClient
//
import Foundation
public class ServerCredentials: NSObject, NSCoding {
var servers = [ServerInfo]()
var connectUserId: String
var connectAccessToken: String
init(connectAccessToken: String, connectUserId: String, servers: [ServerInfo] = []) {
self.connectAccessToken = connectAccessToken
self.connectUserId = connectUserId
self.servers = servers
}
func addOrUpdateServer(server: ServerInfo!) {
if ( servers.contains(server)) {
let index = servers.indexOf(server)!
let existingServer = servers[index]
if let serverDateLastAccessed = server.dateLastAccessed {
if let existingLastDateAccessed = existingServer.dateLastAccessed {
if ( existingLastDateAccessed.compare(serverDateLastAccessed) == NSComparisonResult.OrderedDescending) {
existingServer.dateLastAccessed = serverDateLastAccessed
}
} else {
existingServer.dateLastAccessed = serverDateLastAccessed
}
}
if let serverUserLinkType = server.userLinkType {
existingServer.userLinkType = serverUserLinkType
}
if ( server.accessToken != nil && !server.accessToken!.isEmpty ) {
existingServer.accessToken = server.accessToken
}
if ( server.userId != nil && !server.userId!.isEmpty ) {
existingServer.userId = server.userId
}
if ( server.exchangeToken != nil ) {
existingServer.exchangeToken = server.exchangeToken
}
if let serverRemoteAddress = server.remoteAddress where !serverRemoteAddress.isEmpty {
existingServer.remoteAddress = serverRemoteAddress
}
if let serverLocalAddress = server.localAddress where !serverLocalAddress.isEmpty {
existingServer.localAddress = serverLocalAddress
}
if let serverManualAddress = server.manualAddress where !serverManualAddress.isEmpty {
existingServer.manualAddress = serverManualAddress
}
if ( !server.name.isEmpty ) {
existingServer.name = server.name
}
if ( server.wakeOnLanInfos.count > 0 ) {
existingServer.wakeOnLanInfos.removeAll()
existingServer.wakeOnLanInfos.appendContentsOf(server.wakeOnLanInfos)
}
} else {
servers.append(server)
}
}
// MARK: NSCoding
public required convenience init?(coder aDecoder: NSCoder) {
guard let connectUserId = aDecoder.decodeObjectForKey("connectUserId") as? String,
let connectAccessToken = aDecoder.decodeObjectForKey("connectAccessToken") as? String,
let servers = aDecoder.decodeObjectForKey("servers") as? [ServerInfo]
else { return nil }
self.init(connectAccessToken: connectAccessToken, connectUserId: connectUserId, servers: servers)
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.connectUserId, forKey: "connectUserId")
aCoder.encodeObject(self.connectAccessToken, forKey: "connectAccessToken")
aCoder.encodeObject(self.servers, forKey: "servers")
}
}
|
mit
|
89081ed3694f0f9b92a6c92c33a22457
| 36.484211 | 124 | 0.605618 | 5.597484 | false | false | false | false |
qiscus/qiscus-sdk-ios
|
Qiscus/Qiscus/Library/QToasterConfig.swift
|
1
|
4839
|
//
// QToasterConfig.swift
// this class is default configuration and helper class and helper for QToasterSwift
// QToasterSwift
//
// Created by Ahmad Athaullah on 7/4/16.
// Copyright © 2016 Ahmad Athaullah. All rights reserved.
//
import UIKit
class QToasterConfig: NSObject {
class var textFont:UIFont{
get{
return UIFont.systemFont(ofSize: 11.0)
}
}
class var titleFont:UIFont{
get{
return UIFont.systemFont(ofSize: 11.0, weight: UIFont.Weight(rawValue: 0.8))
}
}
class var backgroundColor:UIColor{
get{
return UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
}
}
class var textColor:UIColor{
get{
return UIColor.white
}
}
class var iconBackgroundColor:UIColor{
get{
return UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1)
}
}
class var animateDuration:TimeInterval{
get{
return 0.2
}
}
class var delayDuration:TimeInterval{
get{
return 3.0
}
}
class var iconSquareSize:CGFloat{
get{
return 35.0
}
}
class var iconCornerRadius:CGFloat{
get{
return 3.0
}
}
class var screenWidth:CGFloat{
get{
return UIScreen.main.bounds.size.width
}
}
class var statusBarHeight:CGFloat{
get{
return UIApplication.shared.statusBarFrame.size.height
}
}
class func textSize(text: NSString, font: UIFont, maxWidth: CGFloat)->CGSize{
let size = CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)
let rect = text.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil) as CGRect
return rect.size
}
// func imageForUrl
// taken from : ImageLoader.swift
// extension
//
// Created by Nate Lyman on 7/5/14.
// git: https://github.com/natelyman/SwiftImageLoader
// Copyright (c) 2014 NateLyman.com. All rights reserved.
//
class func imageForUrl(urlString: String, header: [String : String] = [String : String](), completionHandler:@escaping (_ image: UIImage?, _ url: String) -> ()) {
DispatchQueue.global(qos: DispatchQoS.background.qosClass).async {
let cache = NSCache<AnyObject,AnyObject>()
let data: Data? = cache.object(forKey: urlString as AnyObject) as? Data
if let goodData = data {
let image = UIImage(data: goodData)
DispatchQueue.main.async(execute: { () -> Void in
completionHandler(image, urlString)
})
return
}
if header.count > 0 {
let url = URL(string: urlString)
var request = URLRequest(url: url!)
for (key,value) in header {
request.setValue(value, forHTTPHeaderField: key)
}
let downloadTask:URLSessionDataTask = URLSession.shared.dataTask(with: request, completionHandler: {(data: Data?, response: URLResponse?, error: Error?) -> Void in
if (error != nil) {
completionHandler(nil, urlString)
return
}
if let data = data {
let image = UIImage(data: data)
cache.setObject(data as AnyObject, forKey: urlString as AnyObject)
DispatchQueue.main.async(execute: { () -> Void in
completionHandler(image, urlString)
})
return
}
})
downloadTask.resume()
}else{
let downloadTask:URLSessionDataTask = URLSession.shared.dataTask(with: URL(string: urlString)!, completionHandler: {(data: Data?, response: URLResponse?, error: Error?) -> Void in
if (error != nil) {
completionHandler(nil, urlString)
return
}
if let data = data {
let image = UIImage(data: data)
cache.setObject(data as AnyObject, forKey: urlString as AnyObject)
DispatchQueue.main.async(execute: { () -> Void in
completionHandler(image, urlString)
})
return
}
})
downloadTask.resume()
}
}
}
}
|
mit
|
4c45ab01ff17e9ca7b1c68dd8b74bdfb
| 32.832168 | 196 | 0.513849 | 5.135881 | false | false | false | false |
aipeople/SimplyLayout
|
SimplyLayout/Core/AttributedDimension.swift
|
1
|
2442
|
//
// AttributedDimension.swift
// SimplyLayout
//
// Created by aipeople on 28/09/2017.
// Copyright © 2017 aipeople. All rights reserved.
//
import UIKit
public struct AttributedDimension {
public let dimension: NSLayoutDimension
public var priority: UILayoutPriority
public var multiplier: CGFloat
public var constant: CGFloat
public var shouldActivate: Bool
init(dimension: NSLayoutDimension,
multiplier: CGFloat,
constant: CGFloat,
priority: UILayoutPriority = SimplyLayout.config.defaultPriority,
shouldActivate: Bool = SimplyLayout.config.defaultActivation) {
self.dimension = dimension
self.multiplier = multiplier
self.constant = constant
self.priority = priority
self.shouldActivate = shouldActivate
}
}
extension AttributedDimension {
public static func +(lhs: AttributedDimension, rhs: CGFloat) -> AttributedDimension {
var dimension = lhs
dimension.constant += rhs
return dimension
}
public static func -(lhs: AttributedDimension, rhs: CGFloat) -> AttributedDimension {
return lhs + -rhs
}
}
extension AttributedDimension {
public static func *(lhs: AttributedDimension, rhs: CGFloat) -> AttributedDimension {
var dimension = lhs
dimension.multiplier *= rhs
return dimension
}
}
extension AttributedDimension {
public static func ~(lhs: AttributedDimension, rhs: Float) -> AttributedDimension {
return lhs ~ UILayoutPriority(rhs)
}
public static func ~(lhs: AttributedDimension, rhs: UILayoutPriority) -> AttributedDimension {
var dimension = lhs
dimension.priority = rhs
return dimension
}
}
extension AttributedDimension {
public static prefix func --(lhs: AttributedDimension) -> AttributedDimension {
guard lhs.shouldActivate else {
return lhs
}
var anchor = lhs
anchor.shouldActivate = false
return anchor
}
public static prefix func ++(lhs: AttributedDimension) -> AttributedDimension {
guard !lhs.shouldActivate else {
return lhs
}
var anchor = lhs
anchor.shouldActivate = true
return anchor
}
}
|
mit
|
77660fcdeed8d0904bdde127c11f8558
| 21.394495 | 98 | 0.621467 | 5.329694 | false | false | false | false |
nervousnet/nervousnet-HUB-iOS
|
Pods/SQLite.swift/SQLite/Helpers.swift
|
3
|
4291
|
//
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif COCOAPODS
import CSQLite
#endif
public typealias Star = (Expression<Binding>?, Expression<Binding>?) -> Expression<Void>
public func *(_: Expression<Binding>?, _: Expression<Binding>?) -> Expression<Void> {
return Expression(literal: "*")
}
public protocol _OptionalType {
associatedtype WrappedType
}
extension Optional : _OptionalType {
public typealias WrappedType = Wrapped
}
// let SQLITE_STATIC = unsafeBitCast(0, sqlite3_destructor_type.self)
let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
extension String {
func quote(_ mark: Character = "\"") -> String {
let escaped = characters.reduce("") { string, character in
string + (character == mark ? "\(mark)\(mark)" : "\(character)")
}
return "\(mark)\(escaped)\(mark)"
}
func join(_ expressions: [Expressible]) -> Expressible {
var (template, bindings) = ([String](), [Binding?]())
for expressible in expressions {
let expression = expressible.expression
template.append(expression.template)
bindings.append(contentsOf: expression.bindings)
}
return Expression<Void>(template.joined(separator: self), bindings)
}
func infix<T>(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression<T> {
let expression = Expression<T>(" \(self) ".join([lhs, rhs]).expression)
guard wrap else {
return expression
}
return "".wrap(expression)
}
func prefix(_ expressions: Expressible) -> Expressible {
return "\(self) ".wrap(expressions) as Expression<Void>
}
func prefix(_ expressions: [Expressible]) -> Expressible {
return "\(self) ".wrap(expressions) as Expression<Void>
}
func wrap<T>(_ expression: Expressible) -> Expression<T> {
return Expression("\(self)(\(expression.expression.template))", expression.expression.bindings)
}
func wrap<T>(_ expressions: [Expressible]) -> Expression<T> {
return wrap(", ".join(expressions))
}
}
func infix<T>(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true, function: String = #function) -> Expression<T> {
return function.infix(lhs, rhs, wrap: wrap)
}
func wrap<T>(_ expression: Expressible, function: String = #function) -> Expression<T> {
return function.wrap(expression)
}
func wrap<T>(_ expressions: [Expressible], function: String = #function) -> Expression<T> {
return function.wrap(", ".join(expressions))
}
func transcode(_ literal: Binding?) -> String {
guard let literal = literal else { return "NULL" }
switch literal {
case let blob as Blob:
return blob.description
case let string as String:
return string.quote("'")
case let binding:
return "\(binding)"
}
}
func value<A: Value>(_ v: Binding) -> A {
return A.fromDatatypeValue(v as! A.Datatype) as! A
}
func value<A: Value>(_ v: Binding?) -> A {
return value(v!)
}
|
gpl-3.0
|
614002eb7df88d9ddc61f7b02652e5db
| 32 | 121 | 0.673893 | 4.29 | false | false | false | false |
nextcloud/ios
|
iOSClient/Main/Collection Common/NCGridCell.swift
|
1
|
9709
|
//
// NCGridCell.swift
// Nextcloud
//
// Created by Marino Faggiana on 08/10/2018.
// Copyright © 2018 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// 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
class NCGridCell: UICollectionViewCell, UIGestureRecognizerDelegate, NCCellProtocol, NCTrashCellProtocol {
@IBOutlet weak var imageItem: UIImageView!
@IBOutlet weak var imageSelect: UIImageView!
@IBOutlet weak var imageStatus: UIImageView!
@IBOutlet weak var imageFavorite: UIImageView!
@IBOutlet weak var imageLocal: UIImageView!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelInfo: UILabel!
@IBOutlet weak var buttonMore: UIButton!
@IBOutlet weak var imageVisualEffect: UIVisualEffectView!
@IBOutlet weak var progressView: UIProgressView!
internal var objectId = ""
private var user = ""
weak var delegate: NCGridCellDelegate?
var namedButtonMore = ""
var fileObjectId: String? {
get { return objectId }
set { objectId = newValue ?? "" }
}
var filePreviewImageView: UIImageView? {
get { return imageItem }
set { imageItem = newValue }
}
var fileUser: String? {
get { return user }
set { user = newValue ?? "" }
}
var fileTitleLabel: UILabel? {
get { return labelTitle }
set { labelTitle = newValue }
}
var fileInfoLabel: UILabel? {
get { return labelInfo }
set { labelInfo = newValue }
}
var fileProgressView: UIProgressView? {
get { return progressView }
set { progressView = newValue }
}
var fileSelectImage: UIImageView? {
get { return imageSelect }
set { imageSelect = newValue }
}
var fileStatusImage: UIImageView? {
get { return imageStatus }
set { imageStatus = newValue }
}
var fileLocalImage: UIImageView? {
get { return imageLocal }
set { imageLocal = newValue }
}
var fileFavoriteImage: UIImageView? {
get { return imageFavorite }
set { imageFavorite = newValue }
}
override func awakeFromNib() {
super.awakeFromNib()
// use entire cell as accessibility element
accessibilityHint = nil
accessibilityLabel = nil
accessibilityValue = nil
isAccessibilityElement = true
imageItem.layer.cornerRadius = 6
imageItem.layer.masksToBounds = true
imageVisualEffect.layer.cornerRadius = 6
imageVisualEffect.clipsToBounds = true
imageVisualEffect.alpha = 0.5
progressView.tintColor = NCBrandColor.shared.brandElement
progressView.transform = CGAffineTransform(scaleX: 1.0, y: 0.5)
progressView.trackTintColor = .clear
let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gestureRecognizer:)))
longPressedGesture.minimumPressDuration = 0.5
longPressedGesture.delegate = self
longPressedGesture.delaysTouchesBegan = true
self.addGestureRecognizer(longPressedGesture)
let longPressedGestureMore = UILongPressGestureRecognizer(target: self, action: #selector(longPressInsideMore(gestureRecognizer:)))
longPressedGestureMore.minimumPressDuration = 0.5
longPressedGestureMore.delegate = self
longPressedGestureMore.delaysTouchesBegan = true
buttonMore.addGestureRecognizer(longPressedGestureMore)
labelTitle.text = ""
labelInfo.text = ""
labelTitle.textColor = .label
labelInfo.textColor = .systemGray
}
override func prepareForReuse() {
super.prepareForReuse()
imageItem.backgroundColor = nil
accessibilityHint = nil
accessibilityLabel = nil
accessibilityValue = nil
}
override func snapshotView(afterScreenUpdates afterUpdates: Bool) -> UIView? {
return nil
}
@IBAction func touchUpInsideMore(_ sender: Any) {
delegate?.tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: imageItem.image, sender: sender)
}
@objc func longPressInsideMore(gestureRecognizer: UILongPressGestureRecognizer) {
delegate?.longPressMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, gestureRecognizer: gestureRecognizer)
}
@objc func longPress(gestureRecognizer: UILongPressGestureRecognizer) {
delegate?.longPressGridItem(with: objectId, gestureRecognizer: gestureRecognizer)
}
fileprivate func setA11yActions() {
let moreName = namedButtonMore == NCGlobal.shared.buttonMoreStop ? "_cancel_" : "_more_"
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(
name: NSLocalizedString(moreName, comment: ""),
target: self,
selector: #selector(touchUpInsideMore))
]
}
func setButtonMore(named: String, image: UIImage) {
namedButtonMore = named
buttonMore.setImage(image, for: .normal)
setA11yActions()
}
func hideButtonMore(_ status: Bool) {
buttonMore.isHidden = status
}
func selectMode(_ status: Bool) {
if status {
imageSelect.isHidden = false
accessibilityCustomActions = nil
} else {
imageSelect.isHidden = true
imageVisualEffect.isHidden = true
setA11yActions()
}
}
func selected(_ status: Bool) {
if status {
if traitCollection.userInterfaceStyle == .dark {
imageVisualEffect.effect = UIBlurEffect(style: .dark)
imageVisualEffect.backgroundColor = .black
} else {
imageVisualEffect.effect = UIBlurEffect(style: .extraLight)
imageVisualEffect.backgroundColor = .lightGray
}
imageSelect.image = NCBrandColor.cacheImages.checkedYes
imageVisualEffect.isHidden = false
} else {
imageSelect.isHidden = true
imageVisualEffect.isHidden = true
}
}
func writeInfoDateSize(date: NSDate, size: Int64) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateFormatter.locale = Locale.current
labelInfo.text = dateFormatter.string(from: date as Date) + " · " + CCUtility.transformedSize(size)
}
func setAccessibility(label: String, value: String) {
accessibilityLabel = label
accessibilityValue = value
}
}
protocol NCGridCellDelegate: AnyObject {
func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any)
func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer)
func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer)
}
// optional func
extension NCGridCellDelegate {
func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {}
func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {}
func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {}
}
// MARK: - Grid Layout
class NCGridLayout: UICollectionViewFlowLayout {
var heightLabelPlusButton: CGFloat = 60
var marginLeftRight: CGFloat = 10
var itemForLine: CGFloat = 3
var itemWidthDefault: CGFloat = 140
// MARK: - View Life Cycle
override init() {
super.init()
sectionHeadersPinToVisibleBounds = false
minimumInteritemSpacing = 1
minimumLineSpacing = marginLeftRight
self.scrollDirection = .vertical
self.sectionInset = UIEdgeInsets(top: 10, left: marginLeftRight, bottom: 0, right: marginLeftRight)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var itemSize: CGSize {
get {
if let collectionView = collectionView {
if collectionView.frame.width < 400 {
itemForLine = 3
} else {
itemForLine = collectionView.frame.width / itemWidthDefault
}
let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
let itemHeight: CGFloat = itemWidth + heightLabelPlusButton
return CGSize(width: itemWidth, height: itemHeight)
}
// Default fallback
return CGSize(width: itemWidthDefault, height: itemWidthDefault)
}
set {
super.itemSize = newValue
}
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return proposedContentOffset
}
}
|
gpl-3.0
|
8df6bfd329afc9c990be5a4e076d5240
| 33.667857 | 143 | 0.665911 | 5.152335 | false | false | false | false |
daniel-beard/Starlight
|
Starlight/Starlight.swift
|
1
|
13798
|
//
// Starlight.swift
// Starlight
//
// Created by Daniel Beard on 9/13/15.
// Copyright © 2015 DanielBeard. All rights reserved.
//
import Foundation
//MARK: Typealiases
public typealias Point = (x: Int, y: Int)
typealias Pair = (first: Double, second: Double)
typealias StateLinkedList = Array<State>
extension Array where Element == State {
mutating func addFirst(_ element: Element) {
guard !self.isEmpty else {
append(element)
return
}
insert(element, at: 0)
}
public var description: String {
return self.reduce("", { $0 + ("\($1)\n") })
}
}
private class PriorityQueue<T: Comparable> {
private var heap = [T]()
func push(item: T) {
heap.append(item)
heap.sort()
}
func pop() -> T {
return heap.removeFirst()
}
func peek() -> T {
return (heap.first)!
}
func isEmpty() -> Bool {
return heap.isEmpty
}
var count: Int {
return heap.count
}
}
struct CellInfo {
var g = 0.0
var rhs = 0.0
var cost = 0.0
}
public class Starlight {
//MARK: Private Properties
private var path = [State]()
private var k_m = 0.0
private var s_start = State()
private var s_goal = State()
private var s_last = State()
private var openList = PriorityQueue<State>()
private var cellHash = [State: CellInfo]()
private var openHash = [State: Double]()
//MARK: Constants
private let maxSteps = 80000
private var C1 = 1.0
init(start: Point, goal: Point) {
s_start.x = start.x
s_start.y = start.y
s_goal.x = goal.x
s_goal.y = goal.y
let goalCellInfo = CellInfo(g: 0.0, rhs: 0.0, cost: C1)
cellHash[s_goal] = goalCellInfo
let startHeuristic = heuristic(s_start, b: s_goal)
let startCellInfo = CellInfo(g: startHeuristic, rhs: startHeuristic, cost: C1)
cellHash[s_start] = startCellInfo
s_start = calculateKey(s_start)
s_last = s_start
}
//MARK: Private Methods
/// CalculateKey - > As per [S. Koenig, 2002]
private func calculateKey(_ u: State) -> State {
let val = min(getRHS(u), getG(u))
let first = (val + heuristic(u, b: s_start) + k_m)
let second = val
return State(x: u.x, y: u.y, k: Pair(first, second))
}
/// Returns the rhs value for the state u
private func getRHS(_ u: State) -> Double {
guard u != s_goal else {
return 0.0
}
guard let cellHashU = cellHash[u] else {
return heuristic(u, b: s_goal)
}
return cellHashU.rhs
}
/// As per [S. Koenig,2002] except for two main modifications:
/// 1. We stop planning after a number of steps, 'maxsteps' we do this
/// because this algorithm can plan forever if the start is surrounded by obstacles
/// 2. We lazily remove states from the open list so we never have to iterate through it.
private func computeShortestPath() -> Int {
if openList.isEmpty() { return 1 }
var k = 0
var s = StateLinkedList()
while !openList.isEmpty() {
// Update start
s_start = calculateKey(s_start)
// Bail if our conditions aren't met
guard (openList.peek() < s_start || getRHS(s_start) != getG(s_start)) else {
break
}
k += 1
if k > maxSteps {
print("At maxsteps")
return -1
}
var u = State()
let test = getRHS(s_start) != getG(s_start)
// Lazy remove
while (true) {
if openList.isEmpty() { return 1 }
u = openList.pop()
if !isValid(u) { continue }
if !(u < s_start) && !test { return 2 }
break
}
openHash[u] = nil
let k_old = State(state: u)
u = calculateKey(u)
if k_old < u { // u is out of date
insert(u)
} else if getG(u) > getRHS(u) { // needs update (got better)
setG(u, g: getRHS(u))
s = getPred(u)
for state in s {
updateVertex(state)
}
} else { // g <= rhs, state has got worse
setG(u, g: Double.infinity)
s = getPred(u)
for state in s {
updateVertex(state)
}
updateVertex(u)
}
s_start = calculateKey(s_start)
}
return 0
}
/// Helper method for generating a list of states around a current state
/// Moves in a clockwise manner
private func generateSuccessorStates(fromState u: State, k: Pair) -> [State] {
return [
State(x: u.x + 1, y: u.y, k: k),
State(x: u.x + 1, y: u.y + 1, k: k),
State(x: u.x, y: u.y + 1, k: k),
State(x: u.x - 1, y: u.y + 1, k: k),
State(x: u.x - 1, y: u.y, k: k),
State(x: u.x - 1, y: u.y - 1, k: k),
State(x: u.x, y: u.y - 1, k: k),
State(x: u.x + 1, y: u.y - 1, k: k),
]
}
/// Returns a list of successor states for state u, since this is an
/// 8-way graph this list contains all of a cells neighbours. Unless
/// the cell is occupied, in which case it has no successors.
private func getSucc(_ u: State) -> StateLinkedList {
var s = StateLinkedList()
if occupied(u) { return s }
// Generating the successors, starting at the immediate right,
// moving in a clockwise manner
// transform to StateLinkedList and return
let successors = generateSuccessorStates(fromState: u, k: (-1.0, -1.0))
successors.forEach { s.addFirst($0) }
return s
}
/// Returns a list of all the predecessor states for state u. Since
/// this is for an 8-way connected graph, the list contains all the
/// neighbours for state u. Occupied neighbours are not added to the list
private func getPred(_ u: State) -> StateLinkedList {
var s = StateLinkedList()
let successors = generateSuccessorStates(fromState: u, k: (-1.0, -1.0))
successors.forEach { if !occupied($0) { s.addFirst($0) }}
return s;
}
/// As per [S. Koenig, 2002]
private func updateVertex(_ u: State) {
var states = StateLinkedList()
if u != s_goal {
states = getSucc(u)
var tmp = Double.infinity
var tmp2 = 0.0
for state in states {
tmp2 = getG(state) + cost(u, b: state)
if tmp2 < tmp { tmp = tmp2 }
}
if !close(getRHS(u), y: tmp) { setRHS(u, rhs: tmp) }
}
if !close(getG(u), y: getRHS(u)) { insert(u) }
}
/// Returns true if state u is on the open list or not by checking if it is in the hash table.
private func isValid(_ u: State) -> Bool {
guard let openHashU = openHash[u] else {
return false
}
if !close(keyHashCode(u), y: openHashU) { return false }
return true
}
/// Returns the value for the state u
private func getG(_ u: State) -> Double {
guard let cellHashU = cellHash[u] else {
return heuristic(u, b: s_goal)
}
return cellHashU.g
}
/// The heuristic we use is the 8-way distance
/// scaled by a constant C1 (should be set to <= min cost
private func heuristic(_ a: State, b: State) -> Double {
return eightCondist(a, b) * C1
}
/// Returns the 8-way distance between state a and state b
private func eightCondist(_ a: State, _ b: State) -> Double {
var min = Double(abs(a.x - b.x))
var max = Double(abs(a.y - b.y))
if min > max {
swap(&min, &max)
}
return (2.squareRoot() - 1.0) * min + max
}
/// Inserts state into openList and openHash
private func insert(_ u: State) {
let u = calculateKey(u)
let csum = keyHashCode(u)
openHash[u] = csum
openList.push(item: u)
}
/// Returns the key hash code for the state u, this is used to compare
/// a state that has been updated
private func keyHashCode(_ u: State) -> Double {
return Double(u.k.first + 1193 * u.k.second)
}
/// Returns true if the cell is occupied (non-traversable), false
/// otherwise. Non-traversable are marked with a cost < 0
private func occupied(_ u: State) -> Bool {
if let cell = cellHash[u] {
return (cell.cost < 0)
}
return false
}
/// Euclidean cost between state a and state b
private func trueDist(_ a: State, b: State) -> Double {
let x = Double(a.x - b.x)
let y = Double(a.y - b.y)
return sqrt(x * x + y * y)
}
/** Returns the cost of moving from state a to state b. This could be
either the cost of moving off state a or onto state b, we went with the
former. This is also the 8-way cost. */
private func cost(_ a: State, b: State) -> Double {
let xd = abs(a.x - b.x)
let yd = abs(a.y - b.y)
var scale = 1.0
if xd + yd > 1 { scale = 2.squareRoot() }
guard let cellHashA = cellHash[a] else {
return scale * C1
}
return scale * cellHashA.cost
}
/// Returns true if x and y are within 10E-5, false otherwise
private func close(_ x: Double, y: Double) -> Bool {
if x == Double.infinity && y == Double.infinity { return true }
return abs(x - y) < 0.00001
}
/// Sets the G value for state u
private func setG(_ u: State, g: Double) {
makeNewCell(u)
cellHash[u]!.g = g
}
/// Sets the rhs value for state u
private func setRHS(_ u: State, rhs: Double) {
makeNewCell(u)
cellHash[u]!.rhs = rhs
}
/// Checks if a cell is in the hash table, if not it adds it in.
private func makeNewCell(_ u: State) {
guard cellHash[u] == nil else { return }
let heuristicValue = heuristic(u, b: s_goal)
let cellInfo = CellInfo(g: heuristicValue, rhs: heuristicValue, cost: C1)
cellHash[u] = cellInfo
}
//MARK: Public Methods
public func replan() -> Bool {
path.removeAll()
let res = computeShortestPath()
if res < 0 {
print("No path to goal")
return false
}
var n = StateLinkedList()
var cur = s_start
if getG(s_start) == Double.infinity {
print("No path to goal")
return false
}
while (cur != s_goal) {
path.append(cur)
n = StateLinkedList()
n = getSucc(cur)
if n.isEmpty {
print("No path to goal")
return false
}
var cmin = Double.infinity
var tmin = 0.0
var smin = State()
for state in n {
var val = cost(cur, b: state)
let val2 = trueDist(state, b: s_goal) + trueDist(s_start, b: state)
val += getG(state)
if close(val, y: cmin) {
if tmin > val2 {
tmin = val2
cmin = val
smin = state
}
} else if val < cmin {
tmin = val2
cmin = val
smin = state
}
}
n.removeAll()
cur = State(state: smin)
}
path.append(s_goal)
return true
}
/// Update the position of the agent/robot.
/// This does not force a replan.
public func updateStart(x: Int, y: Int) {
s_start.x = x
s_start.y = y
k_m += heuristic(s_last, b: s_start)
s_start = calculateKey(s_start)
s_last = s_start
}
public func updateGoal(x: Int, y: Int) {
//TODO: Implement this
fatalError("Not implemented")
}
/// updateCell as per [S. Koenig, 2002]
public func updateCell(x: Int, y: Int, value: Double) {
var u = State()
u.x = x; u.y = y
if u == s_start || u == s_goal {
return
}
makeNewCell(u)
cellHash[u]!.cost = value
updateVertex(u)
}
public func getPath() -> [State] {
return self.path
}
}
public struct State: Hashable, Comparable, CustomStringConvertible {
var x = 0
var y = 0
var k = Pair(0.0, 0.0)
init() { }
init(x: Int, y: Int, k: Pair) {
self.x = x
self.y = y
self.k = k
}
init(state: State) {
x = state.x
y = state.y
k = state.k
}
public var hashValue: Int {
get { return x + 34245 * y }
}
public var description: String {
get { return "x: \(x) y: \(y)\n" }
}
}
public func ==(lhs: State, rhs: State) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public func <(lhs: State, rhs: State) -> Bool {
let delta = 0.000001
if lhs.k.first + delta < rhs.k.first {
return true
} else if lhs.k.first - delta > rhs.k.first {
return false
}
return lhs.k.second < rhs.k.second
}
|
mit
|
393e387c38f79f96f071df3a66536478
| 28.292994 | 98 | 0.505835 | 3.800826 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/CreateWorkspace.swift
|
2
|
4230
|
/**
* Copyright IBM Corporation 2018
*
* 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
/** CreateWorkspace. */
public struct CreateWorkspace: Encodable {
/// The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters.
public var name: String?
/// The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters.
public var description: String?
/// The language of the workspace.
public var language: String?
/// An array of objects defining the intents for the workspace.
public var intents: [CreateIntent]?
/// An array of objects defining the entities for the workspace.
public var entities: [CreateEntity]?
/// An array of objects defining the nodes in the workspace dialog.
public var dialogNodes: [CreateDialogNode]?
/// An array of objects defining input examples that have been marked as irrelevant input.
public var counterexamples: [CreateCounterexample]?
/// Any metadata related to the workspace.
public var metadata: [String: JSON]?
/// Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used.
public var learningOptOut: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case name = "name"
case description = "description"
case language = "language"
case intents = "intents"
case entities = "entities"
case dialogNodes = "dialog_nodes"
case counterexamples = "counterexamples"
case metadata = "metadata"
case learningOptOut = "learning_opt_out"
}
/**
Initialize a `CreateWorkspace` with member variables.
- parameter name: The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters.
- parameter description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters.
- parameter language: The language of the workspace.
- parameter intents: An array of objects defining the intents for the workspace.
- parameter entities: An array of objects defining the entities for the workspace.
- parameter dialogNodes: An array of objects defining the nodes in the workspace dialog.
- parameter counterexamples: An array of objects defining input examples that have been marked as irrelevant input.
- parameter metadata: Any metadata related to the workspace.
- parameter learningOptOut: Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used.
- returns: An initialized `CreateWorkspace`.
*/
public init(name: String? = nil, description: String? = nil, language: String? = nil, intents: [CreateIntent]? = nil, entities: [CreateEntity]? = nil, dialogNodes: [CreateDialogNode]? = nil, counterexamples: [CreateCounterexample]? = nil, metadata: [String: JSON]? = nil, learningOptOut: Bool? = nil) {
self.name = name
self.description = description
self.language = language
self.intents = intents
self.entities = entities
self.dialogNodes = dialogNodes
self.counterexamples = counterexamples
self.metadata = metadata
self.learningOptOut = learningOptOut
}
}
|
mit
|
3180fe232a97766204a54075e51ceaa4
| 46.52809 | 306 | 0.718203 | 4.823261 | false | false | false | false |
KrishMunot/swift
|
test/DebugInfo/generic_arg.swift
|
3
|
999
|
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
import StdlibUnittest
func foo<T>(_ x: T) -> () {
// CHECK: define {{.*}} @_TF11generic_arg3foourFxT_
// CHECK: %[[T:.*]] = alloca %swift.type*
// CHECK: %[[X:.*]] = alloca %swift.opaque*
// CHECK: store %swift.type* %T, %swift.type** %[[T]],
// CHECK: call void @llvm.dbg.declare(metadata %swift.type** %[[T]],
// CHECK-SAME: metadata ![[T1:.*]], metadata ![[EMPTY:.*]])
// CHECK: store %swift.opaque* %0, %swift.opaque** %[[X]],
// CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** %[[X]],
// CHECK-SAME: metadata ![[X1:.*]], metadata ![[EMPTY]])
// CHECK: ![[T1]] = !DILocalVariable(name: "$swift.type.T",
// CHECK-SAME: flags: DIFlagArtificial)
// CHECK: ![[EMPTY]] = !DIExpression()
// CHECK: ![[X1]] = !DILocalVariable(name: "x", arg: 1,
// CHECK-SAME: line: 3, type: !"_TtQq_F11generic_arg3foourFxT_")
_blackHole(x)
}
foo(42)
|
apache-2.0
|
2ac02ebb6990fd1cc0a7fd4aedd850bc
| 46.571429 | 75 | 0.547548 | 3.212219 | false | false | false | false |
KrishMunot/swift
|
stdlib/public/core/Pointer.swift
|
1
|
2805
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A stdlib-internal protocol modeled by the intrinsic pointer types,
/// UnsafeMutablePointer, UnsafePointer, and
/// AutoreleasingUnsafeMutablePointer.
public protocol _Pointer {
/// The underlying raw pointer value.
var _rawValue: Builtin.RawPointer { get }
/// Construct a pointer from a raw value.
init(_ _rawValue: Builtin.RawPointer)
}
/// Derive a pointer argument from a convertible pointer type.
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertPointerToPointerArgument<
FromPointer : _Pointer,
ToPointer : _Pointer
>(_ from: FromPointer) -> ToPointer {
return ToPointer(from._rawValue)
}
/// Derive a pointer argument from the address of an inout parameter.
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertInOutToPointerArgument<
ToPointer : _Pointer
>(_ from: Builtin.RawPointer) -> ToPointer {
return ToPointer(from)
}
/// Derive a pointer argument from an inout array parameter.
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertMutableArrayToPointerArgument<
FromElement,
ToPointer : _Pointer
>(_ a: inout [FromElement]) -> (AnyObject?, ToPointer) {
// TODO: Putting a canary at the end of the array in checked builds might
// be a good idea
// Call reserve to force contiguous storage.
a.reserveCapacity(0)
_debugPrecondition(a._baseAddressIfContiguous != nil || a.isEmpty)
return (a._owner, ToPointer(a._baseAddressIfContiguous._rawValue))
}
/// Derive a pointer argument from a value array parameter.
@_transparent
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertConstArrayToPointerArgument<
FromElement,
ToPointer : _Pointer
>(_ arr: [FromElement]) -> (AnyObject?, ToPointer) {
let (owner, raw) = arr._cPointerArgs()
return (owner, ToPointer(raw))
}
/// Derive a UTF-8 pointer argument from a value string parameter.
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertConstStringToUTF8PointerArgument<
ToPointer : _Pointer
>(_ str: String) -> (AnyObject?, ToPointer) {
// Convert the UTF-8 representation to a null-terminated array.
var utf8 = Array(str.utf8)
utf8.append(0)
// Extract the owner and pointer from the array.
let (owner, raw) = utf8._cPointerArgs()
return (owner, ToPointer(raw))
}
|
apache-2.0
|
cec5c79c593a16a48bb942aefd78beda
| 31.241379 | 80 | 0.697683 | 4.43128 | false | false | false | false |
mikina/SwiftNews
|
SwiftNews/SwiftNews/Modules/Featured/TabCoordinator/FeaturedTabCoordinator.swift
|
1
|
831
|
//
// FeaturedTabCoordinator.swift
// SwiftNews
//
// Created by Mike Mikina on 12/5/16.
// Copyright © 2016 SwiftCookies.com. All rights reserved.
//
import UIKit
class FeaturedTabCoordinator: TabCoordinator {
var rootController: CustomNavigationController
var customTabBarItem = TabBarItem(builder: TabBarItemBuilder { builder in
builder.icon = "featured"
builder.type = .normal
builder.backgroundColor = UIColor.white
builder.iconColor = UIColor(Constants.TabBar.DefaultButtonColor)
builder.selectedIconColor = UIColor(Constants.TabBar.DefaultSelectedButtonColor)
})
init() {
let homeVC = ViewController()
homeVC.title = "Featured"
self.rootController = CustomNavigationController(rootViewController: homeVC)
self.rootController.customTabBarItem = self.customTabBarItem
}
}
|
mit
|
5289e3f8e57461ca269a4fb835bdb610
| 29.740741 | 84 | 0.759036 | 4.585635 | false | false | false | false |
BugMomon/weibo
|
NiceWB/NiceWB/Classes/Compose(发布)/Views/ComposeTitleView.swift
|
1
|
1296
|
//
// ComposeTitleView.swift
// NiceWB
//
// Created by HongWei on 2017/5/15.
// Copyright © 2017年 HongWei. All rights reserved.
//
import UIKit
class ComposeTitleView: UIView {
//懒加载两个label
lazy var title : UILabel = UILabel()
lazy var screenName : UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupLabels()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ComposeTitleView {
func setupLabels() {
addSubview(title)
addSubview(screenName)
title.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.top.equalTo(self)
}
screenName.snp.makeConstraints { (make) in
make.centerX.equalTo(title.snp.centerX)
make.top.equalTo(title.snp.bottom).offset(3)
}
//设置文字
title.font = UIFont.boldSystemFont(ofSize: 15)
screenName.font = UIFont.boldSystemFont(ofSize: 13)
screenName.textColor = UIColor.orange
title.text = "发微博"
screenName.text = UserAccountViewModel.shareInstance.account?.screen_name
}
}
|
apache-2.0
|
5ebb967baf35e31d6c1a023b3524d071
| 22.943396 | 81 | 0.596533 | 4.40625 | false | false | false | false |
turnidge/flutter
|
examples/platform_channel_swift/ios/Runner/AppDelegate.swift
|
1
|
3213
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, FlutterStreamHandler {
private var eventSink: FlutterEventSink?;
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
GeneratedPluginRegistrant.register(with: self);
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController;
let batteryChannel = FlutterMethodChannel.init(name: "samples.flutter.io/battery",
binaryMessenger: controller);
batteryChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: FlutterResult) -> Void in
if ("getBatteryLevel" == call.method) {
self.receiveBatteryLevel(result: result);
} else {
result(FlutterMethodNotImplemented);
}
});
let chargingChannel = FlutterEventChannel.init(name: "samples.flutter.io/charging",
binaryMessenger: controller);
chargingChannel.setStreamHandler(self);
return super.application(application, didFinishLaunchingWithOptions: launchOptions);
}
private func receiveBatteryLevel(result: FlutterResult) {
let device = UIDevice.current;
device.isBatteryMonitoringEnabled = true;
if (device.batteryState == UIDeviceBatteryState.unknown) {
result(FlutterError.init(code: "UNAVAILABLE",
message: "Battery info unavailable",
details: nil));
} else {
result(Int(device.batteryLevel * 100));
}
}
public func onListen(withArguments arguments: Any?,
eventSink: @escaping FlutterEventSink) -> FlutterError? {
self.eventSink = eventSink;
UIDevice.current.isBatteryMonitoringEnabled = true;
self.sendBatteryStateEvent();
NotificationCenter.default.addObserver(
self,
selector: #selector(onBatteryStateDidChange),
name: NSNotification.Name.UIDeviceBatteryStateDidChange,
object: nil)
return nil;
}
@objc private func onBatteryStateDidChange(notification: NSNotification) {
self.sendBatteryStateEvent();
}
private func sendBatteryStateEvent() {
if (eventSink == nil) {
return;
}
let state = UIDevice.current.batteryState;
switch state {
case UIDeviceBatteryState.full:
eventSink!("charging");
break;
case UIDeviceBatteryState.charging:
eventSink!("charging");
break;
case UIDeviceBatteryState.unplugged:
eventSink!("discharging");
break;
default:
eventSink!(FlutterError.init(code: "UNAVAILABLE",
message: "Charging status unavailable",
details: nil));
break;
}
}
public func onCancel(withArguments arguments: Any?) -> FlutterError? {
NotificationCenter.default.removeObserver(self);
eventSink = nil;
return nil;
}
}
|
bsd-3-clause
|
2a71b8d9b9c993130866677adf83799a
| 33.923913 | 98 | 0.665422 | 5.275862 | false | false | false | false |
UrbanCompass/Snail
|
SnailTests/Combine/ReplayAsPublisherTests.swift
|
1
|
944
|
// Copyright © 2021 Compass. All rights reserved.
import Combine
import Foundation
@testable import Snail
import XCTest
@available(iOS 13.0, *)
class ReplayAsPublisherTests: XCTestCase {
private var subject: Replay<String>!
private var subscriptions: Set<AnyCancellable>!
override func setUp() {
super.setUp()
subject = Replay(2)
subscriptions = Set<AnyCancellable>()
}
override func tearDown() {
subject = nil
subscriptions = nil
super.tearDown()
}
func testReplay() {
var strings: [String] = []
subject?.on(.next("1"))
subject?.on(.next("2"))
subject?.on(.done)
subject.asAnyPublisher()
.sink(receiveCompletion: { _ in },
receiveValue: { strings.append($0) })
.store(in: &subscriptions)
XCTAssertEqual(strings[0], "1")
XCTAssertEqual(strings[1], "2")
}
}
|
mit
|
3cff5ab12dfe83d06ff50c0533ad175e
| 23.179487 | 55 | 0.588547 | 4.42723 | false | true | false | false |
jacobwhite/firefox-ios
|
Client/Frontend/Settings/CustomSearchViewController.swift
|
1
|
9972
|
/* 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 Shared
import SnapKit
import Storage
import SDWebImage
import Deferred
private let log = Logger.browserLogger
class CustomSearchError: MaybeErrorType {
enum Reason {
case DuplicateEngine, FormInput
}
var reason: Reason!
internal var description: String {
return "Search Engine Not Added"
}
init(_ reason: Reason) {
self.reason = reason
}
}
class CustomSearchViewController: SettingsTableViewController {
fileprivate var urlString: String?
fileprivate var engineTitle = ""
fileprivate lazy var spinnerView: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.hidesWhenStopped = true
return spinner
}()
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.SettingsAddCustomEngineTitle
view.addSubview(spinnerView)
spinnerView.snp.makeConstraints { make in
make.center.equalTo(self.view.snp.center)
}
}
var successCallback: (() -> Void)?
fileprivate func addSearchEngine(_ searchQuery: String, title: String) {
spinnerView.startAnimating()
let trimmedQuery = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
createEngine(forQuery: trimmedQuery, andName: trimmedTitle).uponQueue(.main) { result in
self.spinnerView.stopAnimating()
guard let engine = result.successValue else {
let alert: UIAlertController
let error = result.failureValue as? CustomSearchError
alert = (error?.reason == .DuplicateEngine) ?
ThirdPartySearchAlerts.duplicateCustomEngine() : ThirdPartySearchAlerts.incorrectCustomEngineForm()
self.navigationItem.rightBarButtonItem?.isEnabled = true
self.present(alert, animated: true, completion: nil)
return
}
self.profile.searchEngines.addSearchEngine(engine)
CATransaction.begin() // Use transaction to call callback after animation has been completed
CATransaction.setCompletionBlock(self.successCallback)
_ = self.navigationController?.popViewController(animated: true)
CATransaction.commit()
}
}
func createEngine(forQuery query: String, andName name: String) -> Deferred<Maybe<OpenSearchEngine>> {
let deferred = Deferred<Maybe<OpenSearchEngine>>()
guard let template = getSearchTemplate(withString: query),
let url = URL(string: template.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!), url.isWebPage() else {
deferred.fill(Maybe(failure: CustomSearchError(.FormInput)))
return deferred
}
// ensure we haven't already stored this template
guard engineExists(name: name, template: template) == false else {
deferred.fill(Maybe(failure: CustomSearchError(.DuplicateEngine)))
return deferred
}
FaviconFetcher.fetchFavImageForURL(forURL: url, profile: profile).uponQueue(.main) { result in
let image = result.successValue ?? FaviconFetcher.getDefaultFavicon(url)
let engine = OpenSearchEngine(engineID: nil, shortName: name, image: image, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true)
//Make sure a valid scheme is used
let url = engine.searchURLForQuery("test")
let maybe = (url == nil) ? Maybe(failure: CustomSearchError(.FormInput)) : Maybe(success: engine)
deferred.fill(maybe)
}
return deferred
}
private func engineExists(name: String, template: String) -> Bool {
return profile.searchEngines.orderedEngines.contains { (engine) -> Bool in
return engine.shortName == name || engine.searchTemplate == template
}
}
func getSearchTemplate(withString query: String) -> String? {
let SearchTermComponent = "%s" //Placeholder in User Entered String
let placeholder = "{searchTerms}" //Placeholder looked for when using Custom Search Engine in OpenSearch.swift
if query.contains(SearchTermComponent) {
return query.replacingOccurrences(of: SearchTermComponent, with: placeholder)
}
return nil
}
override func generateSettings() -> [SettingSection] {
func URLFromString(_ string: String?) -> URL? {
guard let string = string else {
return nil
}
return URL(string: string)
}
let titleField = CustomSearchEngineTextView(placeholder: Strings.SettingsAddCustomEngineTitlePlaceholder, settingIsValid: { text in
return text != nil && text != ""
}, settingDidChange: {fieldText in
guard let title = fieldText else {
return
}
self.engineTitle = title
})
titleField.textField.accessibilityIdentifier = "customEngineTitle"
let urlField = CustomSearchEngineTextView(placeholder: Strings.SettingsAddCustomEngineURLPlaceholder, height: 133, settingIsValid: { text in
//Can check url text text validity here.
return true
}, settingDidChange: {fieldText in
self.urlString = fieldText
})
urlField.textField.autocapitalizationType = .none
urlField.textField.accessibilityIdentifier = "customEngineUrl"
let settings: [SettingSection] = [
SettingSection(title: NSAttributedString(string: Strings.SettingsAddCustomEngineTitleLabel), children: [titleField]),
SettingSection(title: NSAttributedString(string: Strings.SettingsAddCustomEngineURLLabel), footerTitle: NSAttributedString(string: "http://youtube.com/search?q=%s"), children: [urlField])
]
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(self.addCustomSearchEngine))
self.navigationItem.rightBarButtonItem?.accessibilityIdentifier = "customEngineSaveButton"
return settings
}
@objc func addCustomSearchEngine(_ nav: UINavigationController?) {
self.view.endEditing(true)
navigationItem.rightBarButtonItem?.isEnabled = false
if let url = self.urlString {
self.addSearchEngine(url, title: self.engineTitle)
}
}
}
class CustomSearchEngineTextView: Setting, UITextViewDelegate {
fileprivate let Padding: CGFloat = 8
fileprivate let TextLabelHeight: CGFloat = 44
fileprivate var TextFieldHeight: CGFloat = 44
fileprivate let defaultValue: String?
fileprivate let placeholder: String
fileprivate let settingDidChange: ((String?) -> Void)?
fileprivate let settingIsValid: ((String?) -> Bool)?
let textField = UITextView()
let placeholderLabel = UILabel()
init(defaultValue: String? = nil, placeholder: String, height: CGFloat = 44, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
self.defaultValue = defaultValue
self.TextFieldHeight = height
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
textField.addSubview(placeholderLabel)
super.init(cellHeight: TextFieldHeight)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
placeholderLabel.adjustsFontSizeToFitWidth = true
placeholderLabel.textColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
placeholderLabel.text = placeholder
placeholderLabel.frame = CGRect(width: textField.frame.width, height: TextLabelHeight)
textField.font = placeholderLabel.font
textField.textContainer.lineFragmentPadding = 0
textField.keyboardType = .URL
textField.autocorrectionType = .no
textField.delegate = self
cell.isUserInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraitNone
cell.contentView.addSubview(textField)
cell.selectionStyle = .none
textField.snp.makeConstraints { make in
make.height.equalTo(TextFieldHeight)
make.left.right.equalTo(cell.contentView).inset(Padding)
}
}
override func onClick(_ navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
fileprivate func isValid(_ value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
func prepareValidValue(userInput value: String?) -> String? {
return value
}
func textViewDidBeginEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
}
func textViewDidChange(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
settingDidChange?(textView.text)
let color = isValid(textField.text) ? SettingsUX.TableViewRowTextColor : UIConstants.DestructiveRed
textField.textColor = color
}
func textViewDidEndEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
settingDidChange?(textView.text)
}
}
|
mpl-2.0
|
f6dc9d21021c6427a7f6c7c31cfab502
| 38.571429 | 199 | 0.665363 | 5.470104 | false | false | false | false |
WalterCreazyBear/Swifter30
|
iMessageDemo/iMessageExtension/BGSelfDefineViewController.swift
|
1
|
5305
|
//
// BGSelfDefineViewController.swift
// iMessageDemo
//
// Created by Bear on 2017/8/7.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
import Messages
class BGSelfDefineViewController: UIViewController {
//创建消息并插入
func handleSendButtonClick(sender:UIButton) {
//BGConversationManager.shared.appDeleagte这个就是MSMessagesAppViewController的实例。
if let image = createImageForMessage(), let conversation = BGConversationManager.shared.appDeleagte?.activeConversation {
//layout还有很多别的属性值可以设置,详细请查看文档
let layout = MSMessageTemplateLayout()
layout.image = image
layout.caption = "Stepper Value"
let message = MSMessage()
message.layout = layout
message.shouldExpire = true
message.accessibilityLabel = "accessibilityLabel"
message.summaryText = "summaryText"
guard let components = NSURLComponents(string: "data://") else {
fatalError("Invalid base url")
}
let size = URLQueryItem(name: "Size", value: "Large")
let count = URLQueryItem(name: "Topping_Count", value: "2")
let cheese = URLQueryItem(name: "Topping_0", value: "Cheese")
let pepperoni = URLQueryItem(name: "Topping_1", value: "Pepperoni")
components.queryItems = [size, count, cheese, pepperoni]
guard let url = components.url else {
fatalError("Invalid URL components.")
}
message.url = url
//收起页面,以展示插入的消息
BGConversationManager.shared.appDeleagte?.requestPresentationStyle(.compact)
conversation.insert(message, completionHandler: { (error) in
print(error ?? "")
})
// 其它的消息类型
// conversation.insert(<#T##message: MSMessage##MSMessage#>, completionHandler: <#T##((Error?) -> Void)?##((Error?) -> Void)?##(Error?) -> Void#>) //发送自定义消息
// conversation.insertText(<#T##text: String##String#>, completionHandler: <#T##((Error?) -> Void)?##((Error?) -> Void)?##(Error?) -> Void#>) //发送文本消息
// conversation.insert(<#T##sticker: MSSticker##MSSticker#>, completionHandler: <#T##((Error?) -> Void)?##((Error?) -> Void)?##(Error?) -> Void#>) //发送sticker消息
// 发送url: 图片,音频,视频的链接,详细使用请查看文档
// conversation.insertAttachment(<#T##URL: URL##URL#>, withAlternateFilename: <#T##String?#>, completionHandler: <#T##((Error?) -> Void)?##((Error?) -> Void)?##(Error?) -> Void#>)
}
}
//将view转换成图片插入,这不是重点。
func createImageForMessage() -> UIImage? {
let background = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
background.backgroundColor = UIColor.white
let label = UILabel(frame: CGRect(x: 75, y: 75, width: 150, height: 150))
label.font = UIFont.systemFont(ofSize: 56.0)
label.backgroundColor = UIColor.red
label.textColor = UIColor.white
label.text = "1"
label.textAlignment = .center
label.layer.cornerRadius = label.frame.size.width/2.0
label.clipsToBounds = true
background.addSubview(label)
background.frame.origin = CGPoint(x: view.frame.size.width, y: view.frame.size.height)
view.addSubview(background)
UIGraphicsBeginImageContextWithOptions(background.frame.size, false, UIScreen.main.scale)
background.drawHierarchy(in: background.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
background.removeFromSuperview()
return image
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
title = "Self Define"
navigationController?.navigationBar.isHidden = false
view.addSubview(sendButton)
sendButton.widthAnchor.constraint(equalToConstant: 140).isActive = true
sendButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
sendButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
sendButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -25).isActive = true
}
//在界面止添加一个按键,用来触发消息的生成与插入
lazy var sendButton : UIButton = {
let view : UIButton = UIButton()
view.backgroundColor = UIColor.white
view.layer.borderColor = UIColor.gray.cgColor
view.layer.borderWidth = 0.5
view.setTitle("Send", for: .normal)
view.setTitleColor(UIColor.black, for: .normal)
view.addTarget(self, action: #selector(handleSendButtonClick(sender:)), for: .touchUpInside)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
}
|
mit
|
f01422c66e58d6ecf8ffe1e260d3517c
| 39.926829 | 181 | 0.61323 | 4.704673 | false | false | false | false |
WalterCreazyBear/Swifter30
|
PhotoScroll/PhotoScroll/ViewController.swift
|
1
|
2411
|
//
// ViewController.swift
// PhotoScroll
//
// Created by Bear on 2017/6/28.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate let reuseIdentifier = "PhotoCell"
fileprivate let thumbnailSize:CGFloat = 70.0
fileprivate let sectionInsets = UIEdgeInsets(top: 10, left: 5.0, bottom: 10.0, right: 5.0)
fileprivate let photos = ["photo1", "photo2", "photo3", "photo4", "photo5"]
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout.init()
layout.itemSize = CGSize.init(width: self.thumbnailSize, height: self.thumbnailSize)
layout.sectionInset = self.sectionInsets
let collectionView : UICollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.white
collectionView.register(PhotoThumbnailCollectionViewCell.self, forCellWithReuseIdentifier: self.reuseIdentifier)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "PhotoScroll"
view.backgroundColor = UIColor.white
view.addSubview(collectionView)
}
}
extension ViewController:UICollectionViewDelegate,UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier, for: indexPath) as! PhotoThumbnailCollectionViewCell
cell.bindData(imageName: photos[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let pager = PhotoPagerViewController.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pager.currentIndex = indexPath.row
navigationController?.pushViewController(pager, animated: true)
}
}
|
mit
|
f313643f2262e106cedd7428ae395962
| 33.898551 | 149 | 0.70598 | 5.435666 | false | false | false | false |
morbrian/udacity-nano-onthemap
|
OnTheMap/OnTheMapParseService.swift
|
1
|
9393
|
//
// OnTheMapParseWebClient.swift
// OnTheMap
//
// Created by Brian Moriarty on 4/22/15.
// Copyright (c) 2015 Brian Moriarty. All rights reserved.
//
import Foundation
// OnTheMapParseService
// Provides customized methods for accessing the Parse Service to perform operations tailored to the OnTheMap Application.
class OnTheMapParseService {
private var parseClient: ParseClient!
init() {
parseClient = ParseClient(client: WebClient(), applicationId: AppDelegate.ParseApplicationId, restApiKey: AppDelegate.ParseRestApiKey)
}
// fetch a list of StudentInformation objects from the parse service, optionally constrained by several supported attributes.
// limit: maximum number of student objects to return from service.
// skip: number of items to skip before returning the remaining list.
// orderedBy: the sort order of the objects to return.
// olderThan: specifies items with updatedAt attributes older than the specified interval.
// newerThan: specifies items with updatedAt more recent thatn the specified interval.
// completionHandler - studentInformation: array of StudentInformation objects matching the query constraints.
func fetchStudents(limit: Int = 50, skip: Int = 0, orderedBy: String = ParseClient.DefaultSortOrder,
olderThan: NSTimeInterval? = nil, newerThan: NSTimeInterval? = nil,
completionHandler: (studentInformation: [StudentInformation]?, error: NSError?) -> Void) {
func createUpdatedAtQueryWithValue(value: NSTimeInterval?, usingLogic logic: String) -> String? {
if var value = value {
if ParseClient.Logic.GreaterThan == logic {
// increment a little to avoid repeatedly getting the most recent one
value++
}
return "{\"\(ParseClient.ParseJsonKey.UpdatedAt)\":{\"$\(logic)\":\"\(ParseClient.DateFormatter.stringFromDate(NSDate(timeIntervalSince1970: value)))\"}}"
} else {
return nil
}
}
let olderThanQuery = createUpdatedAtQueryWithValue(olderThan, usingLogic: ParseClient.Logic.LessThan)
let newerThanQuery = createUpdatedAtQueryWithValue(newerThan, usingLogic: ParseClient.Logic.GreaterThan)
// fetch items that are older than the last one we retrieved, or newer than the most recent
// for example: {"$or":[{"updatedAt":{"$lt":"2015-03-10T20:23:49.5-07:00"}},{"updatedAt":{"$gt":"2015-05-23T23:55:13.6-07:00"}}]}]
var whereClause: String?
switch (olderThanQuery, newerThanQuery) {
case let (older, nil): whereClause = older
case let (nil, newer): whereClause = newer
case let (older, newer): whereClause = "{\"$or\":[\(older!),\(newer!)]}"
}
parseClient.fetchResultsForClassName(OnTheMapParseService.StudentLocationClassName,
limit: limit, skip: skip, orderedBy: orderedBy, whereClause: whereClause) {
resultsArray, error in
completionHandler(studentInformation: self.parseResults(resultsArray), error: error)
}
}
// fetch the StudentInformation object with the specified Student key.
// key: unique student identity key.
// completionHandler - studentInformation: array of all information objects for the specified key.
func fetchStudentInformationForKey(key: String,
completionHandler: (studentInformation: [StudentInformation]?, error: NSError?) -> Void) {
parseClient.fetchResultsForClassName(OnTheMapParseService.StudentLocationClassName,
whereClause: "{\"\(ParseJsonKey.UniqueKey)\":\"\(key)\"}") { resultsArray, error in
completionHandler(studentInformation: self.parseResults(resultsArray), error: error)
}
}
// create new student information object
// studentInformation: student object with new attribute values to create new object with.
// completion-handler - studentInformation: the studentInformation object with the new objecId, createdAt, and updatedAt properties set.
func createStudentInformation(studentInformation: StudentInformation,
completionHandler: (studentInformation: StudentInformation?, error: NSError?) -> Void) {
parseClient.createObjectOfClassName(OnTheMapParseService.StudentLocationClassName,
withProperties: studentInformation.rawData) { objectId, createdAt, error in
if let objectId = objectId, createdAt = createdAt {
var updatedInfo = studentInformation.rawData
updatedInfo[ParseJsonKey.ObjectId] = objectId
updatedInfo[ParseJsonKey.CreateAt] = createdAt
updatedInfo[ParseJsonKey.UpdatedAt] = createdAt
completionHandler(studentInformation: StudentInformation(parseData: updatedInfo), error: nil)
} else {
completionHandler(studentInformation: nil, error: error)
}
}
}
// update student information object
// studentInformation: student object with new attribute values to update server object with same objectId.
// completion-handler - studentInformation: the studentInformation object with the modified updatedAt property set.
func updateStudentInformation(studentInformation: StudentInformation,
completionHandler: (studentInformation: StudentInformation?, error: NSError?) -> Void) {
parseClient.updateObjectOfClassName(OnTheMapParseService.StudentLocationClassName,
withProperties: studentInformation.rawData, objectId: studentInformation.objectId) { updatedAt, error in
if let updatedAt = updatedAt {
var updatedInfo = studentInformation.rawData
updatedInfo[ParseJsonKey.UpdatedAt] = updatedAt
completionHandler(studentInformation: StudentInformation(parseData: updatedInfo), error: nil)
} else {
completionHandler(studentInformation: nil, error: error)
}
}
}
// delete student information object on server
// studentInformation: object with objectId to delete on server
// completionHandler - studentInformation: copy of object that was just deleted on server.
func deleteStudentInformation(studentInformation: StudentInformation,
completionHandler: (studentInformation: StudentInformation?, error: NSError?) -> Void) {
parseClient.deleteObjectOfClassName(OnTheMapParseService.StudentLocationClassName,
objectId: studentInformation.objectId) { error in
if let error = error {
completionHandler(studentInformation: nil, error: error)
} else {
completionHandler(studentInformation: studentInformation, error: nil)
}
}
}
// MARK: - Data Parsers
// parse teh results array into a list of StudentInformation objects
private func parseResults(resultsArray: [[String:AnyObject]]?) -> [StudentInformation]? {
if let resultsArray = resultsArray {
let optionalStudentLocations = resultsArray.map(){StudentInformation(parseData: $0)}
let filteredStudents = optionalStudentLocations.filter() { $0 != nil }
let students = filteredStudents.map() { $0! as StudentInformation }
return students
} else {
return nil
}
}
}
// MARK: - Constants
extension OnTheMapParseService {
static let StudentLocationClassName = "StudentLocation"
struct ParseJsonKey {
static let ObjectId = ParseClient.ParseJsonKey.ObjectId
static let CreateAt = ParseClient.ParseJsonKey.CreateAt
static let UpdatedAt = ParseClient.ParseJsonKey.UpdatedAt
static let UniqueKey = "uniqueKey"
static let MapString = "mapString"
static let MediaUrl = "mediaURL"
static let Firstname = "firstName"
static let Lastname = "lastName"
static let Latitude = "latitude"
static let Longitude = "longitude"
}
}
// MARK: - Errors
extension OnTheMapParseService {
private static let ErrorDomain = "OnTheMapParseWebClient"
private enum ErrorCode: Int, CustomStringConvertible {
case ResponseContainedNoResultObject = 1, ParseClientApiFailure
var description: String {
switch self {
case ResponseContainedNoResultObject: return "Response data did not provide a results object."
case ParseClientApiFailure: return "Parse Client failed to find data but also failed to provide a valid error object."
}
}
}
// createErrorWithCode
// helper function to simplify creation of error object
private static func errorForCode(code: ErrorCode) -> NSError {
let userInfo = [NSLocalizedDescriptionKey : code.description]
return NSError(domain: OnTheMapParseService.ErrorDomain, code: code.rawValue, userInfo: userInfo)
}
}
|
mit
|
66d42c4b5570b88552a3eee93f44d52f
| 48.962766 | 174 | 0.659321 | 5.541593 | false | false | false | false |
larryhou/swift
|
TexasHoldem/TexasHoldem/PokerHand.swift
|
1
|
5859
|
//
// PokerHand.swift
// TexasHoldem
//
// Created by larryhou on 9/3/2016.
// Copyright © 2016 larryhou. All rights reserved.
//
import Foundation
enum HandPattern: UInt8 {
case highCard = 1, onePair, twoPair, threeOfKind, straight, flush, fullHouse, fourOfKind, straightFlush
var description: String {
switch self {
case .highCard: return "高牌"
case .onePair: return "一对"
case .twoPair: return "两对"
case .threeOfKind: return "三张" //绿色
case .straight: return "顺子" //蓝色
case .flush: return "同花" //紫色
case .fullHouse: return "葫芦" //橙色
case .fourOfKind: return "炸弹" //红色
case .straightFlush:return "花顺" //
}
}
}
class PokerHand {
var givenCards: [PokerCard]
var tableCards: [PokerCard]
var pattern: HandPattern!
var matches: [PokerCard]!
private var _isReady: Bool = false
var isReady: Bool { return _isReady }
init() {
self.givenCards = []
self.tableCards = []
}
init(givenCards: [PokerCard], tableCards: [PokerCard]) {
self.givenCards = givenCards
self.tableCards = tableCards
}
func reset() {
self.givenCards = []
self.tableCards = []
self.matches = nil
self.pattern = nil
}
func checkQualified() {
assert(givenCards.count == 2)
assert(tableCards.count == 5)
}
func recognize() -> HandPattern {
var cards = (givenCards + tableCards).sort()
var colorStats: [PokerColor: Int] = [:]
var maxSameColorCount = 0
var dict: [Int: [PokerCard]] = [:]
for i in 0..<cards.count {
let item = cards[i]
if dict[item.value] == nil {
dict[item.value] = []
}
dict[item.value]?.append(item)
if colorStats[item.color] == nil {
colorStats[item.color] = 0
}
colorStats[item.color]! += 1
maxSameColorCount = max(colorStats[item.color]!, maxSameColorCount)
}
var kindStats: [Int: Int] = [:]
for (_, list) in dict {
if kindStats[list.count] == nil {
kindStats[list.count] = 0
}
kindStats[list.count]! += 1
}
if let v4 = kindStats[4] where v4 >= 1 {
return .fourOfKind
}
if let v3 = kindStats[3], v2 = kindStats[2] where (v3 == 1 && v2 >= 1) || (v3 >= 2) {
return .fullHouse
}
if cards[0].value == 1 {
cards.append(cards[0])
}
var stack = [cards[0]]
for i in 1..<cards.count {
if (cards[i - 1].value - cards[i].value == 1) || (cards[i - 1].value == 1/*A*/ && cards[i].value == 13/*K*/) {
stack.append(cards[i])
} else
if stack.count < 5 {
stack = [cards[i]]
}
}
if stack.count >= 5 {
for i in 0..<stack.count - 5 {
var count = 1
for j in i + 1..<i + 5 {
if stack[j - 1].color != stack[j].color {
break
}
count += 1
}
if count == 5 {
return .straightFlush
}
}
return .straight
}
if maxSameColorCount >= 5 {
return .flush
}
if let v3 = kindStats[3] where v3 == 1 {
return .threeOfKind
}
if let v2 = kindStats[2] {
if v2 >= 2 {
return .twoPair
} else
if v2 == 1 {
return .onePair
}
}
return .highCard
}
func evaluate() {
pattern = recognize()
switch pattern! {
case .highCard:HandV1HighCard.evaluate(self)
case .onePair:HandV2OnePair.evaluate(self)
case .twoPair:HandV3TwoPair.evaluate(self)
case .threeOfKind:HandV4TreeOfKind.evaluate(self)
case .straight:HandV5Straight.evaluate(self)
case .flush:HandV6Flush.evaluate(self)
case .fullHouse:HandV7FullHouse.evaluate(self)
case .fourOfKind:HandV8FourOfKind.evaluate(self)
case .straightFlush:HandV9StraightFlush.evaluate(self)
}
_isReady = true
}
var description: String {
return String(format: "%@ {%@} [%@] [%@]", pattern.description, matches.toString(), givenCards.toString(), tableCards.toString())
}
}
func == (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return false
}
}
return true
}
func != (left: PokerHand, right: PokerHand) -> Bool {
return !(left == right)
}
func > (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return left.matches[i] > right.matches[i]
}
}
return false
}
func >= (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return left.matches[i] > right.matches[i]
}
}
return true
}
func < (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return left.matches[i] < right.matches[i]
}
}
return false
}
func <= (left: PokerHand, right: PokerHand) -> Bool {
for i in 0..<5 {
if left.matches[i] != right.matches[i] {
return left.matches[i] < right.matches[i]
}
}
return true
}
|
mit
|
49c1d9dc0c673e72648d08126f40a088
| 24.447368 | 137 | 0.496553 | 3.757772 | false | false | false | false |
ibm-wearables-sdk-for-mobile/ios
|
IBMMobileEdge/IBMMobileEdge/iOS.swift
|
2
|
3795
|
/*
* © Copyright 2015 IBM Corp.
*
* Licensed under the Mobile Edge iOS Framework License (the "License");
* you may not use this file except in compliance with the License. You may find
* a copy of the license in the license.txt file in this package.
*
* 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 CoreMotion
public class iOS: DeviceConnector{
let manager = CMMotionManager()
public override init(){
super.init()
self.deviceName = "iOS"
//manager.gyroUpdateInterval = 0.016
//manager.accelerometerUpdateInterval = 0.016
//print(manager.gyroUpdateInterval)
//print(manager.accelerometerUpdateInterval)
}
override public func getSupportedSensors() -> [SensorType]{
return [.Accelerometer,.Gyroscope]
}
override public func connect(connectionStatusDelegate:ConnectionStatusDelegate!){
super.connect(connectionStatusDelegate)
updateConnectionStatus(.Connected)
}
override public func disconnect(){
self.manager.stopAccelerometerUpdates()
self.manager.stopGyroUpdates()
updateConnectionStatus(.Disconnected)
}
override public func registerForEvents(systemEvents: SystemEvents){
registerAccelerometerEvents(systemEvents.getSensorEvents(.Accelerometer))
registerGyroscopeEvents(systemEvents.getSensorEvents(.Gyroscope))
}
private func registerAccelerometerEvents(accelerometerEvents:SensorEvents){
//register turn on operation
accelerometerEvents.turnOnCommand.addHandler { () -> () in
if (self.manager.accelerometerAvailable){
self.manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data, error) -> Void in
let accelerometerData = AccelerometerData()
accelerometerData.x = (data?.acceleration.x)!
accelerometerData.y = (data?.acceleration.y)!
accelerometerData.z = (data?.acceleration.z)!
accelerometerEvents.dataEvent.trigger(accelerometerData)
})
}
}
//register turn off operation
accelerometerEvents.turnOffCommand.addHandler { () -> () in
self.manager.stopAccelerometerUpdates()
}
}
private func registerGyroscopeEvents(gyroscopeEvents:SensorEvents){
//register turn on operation
gyroscopeEvents.turnOnCommand.addHandler { () -> () in
if self.manager.gyroAvailable {
self.manager.startGyroUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data, error) -> Void in
let gyroscopeData = GyroscopeData()
//convert from rad to deg
gyroscopeData.x = (data?.rotationRate.x)! * 57.2958
gyroscopeData.y = (data?.rotationRate.y)! * 57.2958
gyroscopeData.z = (data?.rotationRate.z)! * 57.2958
gyroscopeEvents.dataEvent.trigger(gyroscopeData)
})
}
}
//register turn off operation
gyroscopeEvents.turnOffCommand.addHandler { () -> () in
self.manager.stopGyroUpdates()
}
}
}
|
epl-1.0
|
4be187a863eee53f8a0a939824bb69d4
| 35.490385 | 131 | 0.611228 | 5.538686 | false | false | false | false |
ilk33r/IORunner
|
IORunnerBin/AppWorker.swift
|
1
|
11679
|
//
// AppWorker.swift
// IORunner
//
// Created by ilker özcan on 04/07/16.
//
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import Foundation
import IORunnerExtension
typealias maybeCChar = UnsafeMutablePointer<CChar>
internal final class AppWorker {
private var signalHandler: SignalHandler!
private var running = false
private var currentHandlers: [AppHandlers]
private var pidFile: String
private var logger: Logger
private var appArguments: Arguments
private var childProcessPid: Int32 = -1
#if swift(>=3)
enum AppWorkerError: Error {
case StdRedirectFailed
case DaemonizeFailed
case PidFileIsNotWritable
case PidFileExists
}
#elseif swift(>=2.2) && os(OSX)
enum AppWorkerError: ErrorType {
case StdRedirectFailed
case DaemonizeFailed
case PidFileIsNotWritable
case PidFileExists
}
#endif
init(handlers: [AppHandlers], pidFile: String, logger: Logger, appArguments: Arguments) {
self.currentHandlers = handlers
self.pidFile = pidFile
self.logger = logger
self.appArguments = appArguments
childProcessPid = self.checkPid()
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Worker will start with \(currentHandlers.count) handlers!")
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Worker will start with \(currentHandlers.count) handlers!")
#endif
}
func registerSignals() {
signalHandler = SignalHandler()
#if swift(>=3)
signalHandler.register(signal: .Interrupt, handleINT)
signalHandler.register(signal: .Quit, handleQUIT)
signalHandler.register(signal: .Terminate, handleTerminate)
SignalHandler.registerSignals()
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Signals registered")
#elseif swift(>=2.2) && os(OSX)
signalHandler.register(.Interrupt, handleINT)
signalHandler.register(.Quit, handleQUIT)
signalHandler.register(.Terminate, handleTerminate)
SignalHandler.registerSignals()
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Signals registered")
#endif
}
func run(daemonize: Bool, isChildProcess: Bool) throws {
if(isChildProcess) {
registerSignals()
running = true
currentHandlers.forEach { $0.forStart() }
startLoop()
}else{
if daemonize {
var processConfig = ProcessConfigData()
#if swift(>=3)
#if os(Linux)
let arg0 = ProcessInfo.processInfo().arguments[0]
#else
let arg0 = ProcessInfo.processInfo.arguments[0]
#endif
#else
let arg0 = Process.arguments[0]
#endif
processConfig.ProcessArgs = [arg0, "--config", appArguments.config!, "--onlyusearguments", "--signal", "environ"]
processConfig.Environments = [("IO_RUNNER_SN", "child-start")]
var procPid: pid_t! = 0
do {
#if swift(>=3)
procPid = try SpawnCurrentProcess(logger: self.logger, configData: processConfig)
#elseif swift(>=2.2) && os(OSX)
procPid = try SpawnCurrentProcess(self.logger, configData: processConfig)
#endif
} catch _ {
throw AppWorkerError.DaemonizeFailed
}
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Application running with daemonize.")
try setChildProcessPid(pid: procPid)
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Application running with daemonize.")
try setChildProcessPid(procPid)
#endif
}else{
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Application running without daemonize.")
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Application running without daemonize.")
#endif
registerSignals()
running = true
currentHandlers.forEach { $0.forStart() }
startLoop()
}
}
}
func stop(graceful: Bool = true) {
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Stop called! graceful: \(graceful)")
currentHandlers.forEach { $0.forStop() }
if graceful {
killWorkers(signal: SIGTERM)
} else {
killWorkers(signal: SIGQUIT)
}
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Stop called! graceful: \(graceful)")
currentHandlers.forEach { $0.forStop() }
if graceful {
killWorkers(SIGTERM)
} else {
killWorkers(SIGQUIT)
}
#endif
}
// MARK: Handle Signals
func handleINT() {
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Signal INT received")
stop(graceful: false)
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Signal INT received")
stop(false)
#endif
running = false
}
func handleQUIT() {
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Signal QUIT received")
stop(graceful: false)
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Signal QUIT received")
stop(false)
#endif
running = false
}
func handleTerminate() {
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Signal TERMINATE received")
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Signal TERMINATE received")
#endif
currentHandlers.forEach { $0.forStop() }
running = false
}
// MARK: Worker
// Kill all workers with given signal
func killWorkers(signal: Int32) {
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Killing workers with signal: \(signal)")
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Killing workers with signal: \(signal)")
#endif
if(childProcessPid == -1) {
deletePid()
running = false
return
}
if(kill(childProcessPid, signal) == 0) {
childProcessPid = -1
deletePid()
}else{
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.MINIMAL, message: "Process already dead! Removing pid file")
#elseif swift(>=2.2) && os(OSX)
logger.writeLog(Logger.LogLevels.MINIMAL, message: "Process already dead! Removing pid file")
#endif
deletePid()
}
}
// MARK: Pid
func checkPid() -> Int32 {
#if swift(>=3)
let pidFileExists = FileManager.default.fileExists(atPath: pidFile)
if(pidFileExists) {
let pidFileDescriptor = FileHandle(forReadingAtPath: pidFile)
if(pidFileDescriptor == nil) {
return -1
}else{
pidFileDescriptor?.seek(toFileOffset: 0)
if let pidData = pidFileDescriptor?.readDataToEndOfFile() {
let pidStr = String(data: pidData, encoding: String.Encoding.utf8)
pidFileDescriptor?.closeFile()
if let pidVal = Int32(pidStr!) {
return pidVal
}else{
return -1
}
}else{
return -1
}
}
}else{
return -1
}
#elseif swift(>=2.2) && os(OSX)
if(NSFileManager.defaultManager().fileExistsAtPath(pidFile)) {
let pidFileDescriptor = NSFileHandle(forReadingAtPath: pidFile)
if(pidFileDescriptor == nil) {
return -1
}else{
pidFileDescriptor?.seekToFileOffset(0)
if let pidData = pidFileDescriptor?.readDataToEndOfFile() {
let pidStr = String(data: pidData, encoding: NSUTF8StringEncoding)
pidFileDescriptor?.closeFile()
if let pidVal = Int32(pidStr!) {
return pidVal
}else{
return -1
}
}else{
return -1
}
}
}else{
return -1
}
#endif
}
func setChildProcessPid(pid: Int32) throws {
#if swift(>=3)
let pidFileExists = FileManager.default.fileExists(atPath: pidFile)
if(pidFileExists) {
kill(pid, SIGINT)
throw AppWorkerError.PidFileExists
}else{
let createStatus = FileManager.default.createFile(atPath: pidFile, contents: nil, attributes: nil)
if(!createStatus) {
kill(pid, SIGINT)
throw AppWorkerError.PidFileIsNotWritable
}
let pidFileDescriptor = FileHandle(forWritingAtPath: pidFile)
if(pidFileDescriptor == nil) {
kill(pid, SIGINT)
throw AppWorkerError.PidFileIsNotWritable
}else{
logger.writeLog(level: Logger.LogLevels.ERROR, message: "Pid file created")
let pidStr = "\(pid)"
pidFileDescriptor?.write(pidStr.data(using: String.Encoding.utf8)!)
pidFileDescriptor?.closeFile()
childProcessPid = pid
}
}
#elseif swift(>=2.2) && os(OSX)
if(NSFileManager.defaultManager().fileExistsAtPath(pidFile)) {
kill(pid, SIGINT)
throw AppWorkerError.PidFileExists
}else{
let createStatus = NSFileManager.defaultManager().createFileAtPath(pidFile, contents: nil, attributes: nil)
if(!createStatus) {
kill(pid, SIGINT)
throw AppWorkerError.PidFileIsNotWritable
}
let pidFileDescriptor = NSFileHandle(forWritingAtPath: pidFile)
if(pidFileDescriptor == nil) {
kill(pid, SIGINT)
throw AppWorkerError.PidFileIsNotWritable
}else{
logger.writeLog(Logger.LogLevels.ERROR, message: "Pid file created")
let pidStr = "\(pid)"
pidFileDescriptor?.writeData(pidStr.dataUsingEncoding(NSUTF8StringEncoding)!)
pidFileDescriptor?.closeFile()
childProcessPid = pid
}
}
#endif
}
// MARK: Loop
private func startLoop() {
#if swift(>=3)
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Child process will be start \(running)")
#if os(Linux)
let runLoop = RunLoop.current()
repeat {
let _ = signalHandler.process()
currentHandlers.forEach { $0.inLoop() }
usleep(Constants.CpuSleepSec)
let _ = runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: NSDate().addingTimeInterval(-1 * Constants.CpuSleepMsec))
} while (running)
#else
let runLoop = RunLoop.current
repeat {
let _ = signalHandler.process()
currentHandlers.forEach { $0.inLoop() }
usleep(Constants.CpuSleepSec)
} while (running && runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: Date().addingTimeInterval(-1 * Constants.CpuSleepMsec)))
#endif
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Child process will be stop \(running)")
#else
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Child process will be start \(running)")
let runLoop = NSRunLoop.currentRunLoop()
repeat {
let _ = signalHandler.process()
currentHandlers.forEach { $0.inLoop() }
usleep(Constants.CpuSleepSec)
} while (running && runLoop.runMode(NSDefaultRunLoopMode, beforeDate: NSDate().dateByAddingTimeInterval(-1 * Constants.CpuSleepMsec)))
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Child process will be stop \(running)")
#endif
}
func deletePid() {
#if swift(>=3)
if(FileManager.default.fileExists(atPath: pidFile)) {
do {
try FileManager.default.removeItem(atPath: pidFile)
} catch _ {
logger.writeLog(level: Logger.LogLevels.ERROR, message: "Could not delete pid file!")
}
}else{
logger.writeLog(level: Logger.LogLevels.WARNINGS, message: "Pid file does not exists!")
}
#elseif swift(>=2.2) && os(OSX)
if(NSFileManager.defaultManager().fileExistsAtPath(pidFile)) {
do {
try NSFileManager.defaultManager().removeItemAtPath(pidFile)
} catch _ {
logger.writeLog(Logger.LogLevels.ERROR, message: "Could not delete pid file!")
}
}else{
logger.writeLog(Logger.LogLevels.WARNINGS, message: "Pid file does not exists!")
}
#endif
}
func runExtension(extensionName: String) {
for currentHandler in self.currentHandlers {
if(currentHandler.getClassName() == extensionName) {
currentHandler.forAsyncTask()
break
}
}
}
}
|
mit
|
60df77e3d50e4fe3dd8d97696d5fb47f
| 24.113978 | 136 | 0.686248 | 3.419619 | false | false | false | false |
jvesala/teknappi
|
teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/Filter.swift
|
17
|
1665
|
//
// Filter.swift
// Rx
//
// Created by Krunoslav Zaher on 2/17/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class FilterSink<O : ObserverType>: Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = Filter<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
switch event {
case .Next(let value):
do {
let satisfies = try self.parent.predicate(value)
if satisfies {
observer?.on(.Next(value))
}
}
catch let e {
observer?.on(.Error(e))
self.dispose()
}
case .Completed: fallthrough
case .Error:
observer?.on(event)
self.dispose()
}
}
}
class Filter<Element> : Producer<Element> {
typealias Predicate = (Element) throws -> Bool
let source: Observable<Element>
let predicate: Predicate
init(source: Observable<Element>, predicate: Predicate) {
self.source = source
self.predicate = predicate
}
override func run<O: ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = FilterSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return source.subscribeSafe(sink)
}
}
|
gpl-3.0
|
f61133112d2834c61c8261f27de0fd8d
| 26.766667 | 139 | 0.547147 | 4.612188 | false | false | false | false |
Rep2/SimplerNews
|
Sources/App/Controllers/ChannelsController.swift
|
1
|
1316
|
import Vapor
import HTTP
let youtubeAPIKey = "AIzaSyBSsdJSTQ3uvLOH1MgN6joX_cxfs4Tmflw"
final class ChannelsController: ResourceRepresentable {
func index(request: Request) throws -> ResponseRepresentable {
return try JSON(node: Channel.all().makeNode())
}
func create(request: Request) throws -> ResponseRepresentable {
let channelName = try Channel.nameFromRequest(request: request)
var channel = try youtubeAPIGetChannel(for: channelName)
try channel.save()
return channel
}
func show(request: Request, channel: Channel) throws -> ResponseRepresentable {
return channel
}
func delete(request: Request, channel: Channel) throws -> ResponseRepresentable {
try channel.delete()
return ""
}
func youtubeAPIGetChannel(for name: String) throws -> Channel {
let channelResponse = try drop.client.get("https://www.googleapis.com/youtube/v3/channels?part=contentDetails&key=\(youtubeAPIKey)&forUsername=\(name)")
return try Channel.from(youtubeAPIChannelResponse: channelResponse, for: name)
}
func makeResource() -> Resource<Channel> {
return Resource(
index: index,
store: create,
show: show,
destroy: delete
)
}
}
|
mit
|
f4f94b420907a2e9f4d03d5a4f08e351
| 27 | 160 | 0.664894 | 4.537931 | false | false | false | false |
cooliean/CLLKit
|
NSDate-TimeAgo/NSDate+Extension.swift
|
1
|
5477
|
//
// NSDate+Extension.swift
// Tasty
//
// Created by Vitaliy Kuzmenko on 17/10/14.
// http://github.com/vitkuzmenko
// Copyright (c) 2014 Vitaliy Kuz'menko. All rights reserved.
//
import Foundation
func NSDateTimeAgoLocalizedStrings(key: String) -> String {
let resourcePath: String?
if let frameworkBundle = NSBundle(identifier: "com.kevinlawler.NSDateTimeAgo") {
// Load from Framework
resourcePath = frameworkBundle.resourcePath
} else {
// Load from Main Bundle
resourcePath = NSBundle.mainBundle().resourcePath
}
if resourcePath == nil {
return ""
}
let path = NSURL(fileURLWithPath: resourcePath!).URLByAppendingPathComponent("NSDateTimeAgo.bundle")
guard let bundle = NSBundle(URL: path) else {
return ""
}
return NSLocalizedString(key, tableName: "NSDateTimeAgo", bundle: bundle, comment: "")
}
extension NSDate {
// shows 1 or two letter abbreviation for units.
// does not include 'ago' text ... just {value}{unit-abbreviation}
// does not include interim summary options such as 'Just now'
public var timeAgoSimple: String {
let components = self.dateComponents()
if components.year > 0 {
return stringFromFormat("%%d%@yr", withValue: components.year)
}
if components.month > 0 {
return stringFromFormat("%%d%@mo", withValue: components.month)
}
// TODO: localize for other calanders
if components.day >= 7 {
let value = components.day/7
return stringFromFormat("%%d%@w", withValue: value)
}
if components.day > 0 {
return stringFromFormat("%%d%@d", withValue: components.day)
}
if components.hour > 0 {
return stringFromFormat("%%d%@h", withValue: components.hour)
}
if components.minute > 0 {
return stringFromFormat("%%d%@m", withValue: components.minute)
}
if components.second > 0 {
return stringFromFormat("%%d%@s", withValue: components.second )
}
return ""
}
public var timeAgo: String {
let components = self.dateComponents()
if components.year > 0 {
if components.year < 2 {
return NSDateTimeAgoLocalizedStrings("Last year")
} else {
return stringFromFormat("%%d %@years ago", withValue: components.year)
}
}
if components.month > 0 {
if components.month < 2 {
return NSDateTimeAgoLocalizedStrings("Last month")
} else {
return stringFromFormat("%%d %@months ago", withValue: components.month)
}
}
// TODO: localize for other calanders
if components.day >= 7 {
let week = components.day/7
if week < 2 {
return NSDateTimeAgoLocalizedStrings("Last week")
} else {
return stringFromFormat("%%d %@weeks ago", withValue: week)
}
}
if components.day > 0 {
if components.day < 2 {
return NSDateTimeAgoLocalizedStrings("Yesterday")
} else {
return stringFromFormat("%%d %@days ago", withValue: components.day)
}
}
if components.hour > 0 {
if components.hour < 2 {
return NSDateTimeAgoLocalizedStrings("An hour ago")
} else {
return stringFromFormat("%%d %@hours ago", withValue: components.hour)
}
}
if components.minute > 0 {
if components.minute < 2 {
return NSDateTimeAgoLocalizedStrings("A minute ago")
} else {
return stringFromFormat("%%d %@minutes ago", withValue: components.minute)
}
}
if components.second > 0 {
if components.second < 5 {
return NSDateTimeAgoLocalizedStrings("Just now")
} else {
return stringFromFormat("%%d %@seconds ago", withValue: components.second)
}
}
return ""
}
private func dateComponents() -> NSDateComponents {
let calander = NSCalendar.currentCalendar()
return calander.components([.Second, .Minute, .Hour, .Day, .Month, .Year], fromDate: self, toDate: NSDate(), options: [])
}
private func stringFromFormat(format: String, withValue value: Int) -> String {
let localeFormat = String(format: format, getLocaleFormatUnderscoresWithValue(Double(value)))
return String(format: NSDateTimeAgoLocalizedStrings(localeFormat), value)
}
private func getLocaleFormatUnderscoresWithValue(value: Double) -> String {
guard let localeCode = NSLocale.preferredLanguages().first else {
return ""
}
// Russian (ru) and Ukrainian (uk)
if localeCode.hasPrefix("ru") || localeCode.hasPrefix("uk") {
let XY = Int(floor(value)) % 100
let Y = Int(floor(value)) % 10
if Y == 0 || Y > 4 || (XY > 10 && XY < 15) {
return ""
}
if Y > 1 && Y < 5 && (XY < 10 || XY > 20) {
return "_"
}
if Y == 1 && XY != 11 {
return "__"
}
}
return ""
}
}
|
mit
|
2ef9db39a02682a61175718d3c8d91ed
| 29.943503 | 129 | 0.552857 | 4.817062 | false | false | false | false |
crspybits/SyncServerII
|
Sources/Server/Database/Database+Setup.swift
|
1
|
1298
|
//
// Database+Setup.swift
// Server
//
// Created by Christopher G Prince on 6/26/18.
//
import Foundation
extension Database {
typealias Repo = Repository & RepositoryBasics
static let repoTypes:[Repo.Type] = [
SharingGroupRepository.self,
UserRepository.self,
DeviceUUIDRepository.self,
UploadRepository.self,
FileIndexRepository.self,
SharingInvitationRepository.self,
SharingGroupUserRepository.self,
MasterVersionRepository.self
]
static func setup() -> Bool {
let db = Database(showStartupInfo: true)
// The ordering of these table creations is important because of foreign key constraints.
for repoType in repoTypes {
let repo = repoType.init(db)
if case .failure(_) = repo.upcreate() {
return false
}
}
return true
}
#if DEBUG
static func remove() {
// Reversing the order on removal to deal with foreign key constraints.
let reversedRepoTypes = repoTypes.reversed()
let db = Database(showStartupInfo: false)
for repoType in reversedRepoTypes {
let repo = repoType.init(db)
_ = repo.remove()
}
}
#endif
}
|
mit
|
b89934a0326e6b9848b6d4ce3a26b2a4
| 24.45098 | 97 | 0.604006 | 4.669065 | false | false | false | false |
onevcat/CotEditor
|
CotEditor/Sources/String+Normalization.swift
|
1
|
4416
|
//
// String+Normalization.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2015-08-25.
//
// ---------------------------------------------------------------------------
//
// © 2015-2022 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
enum UnicodeNormalizationForm {
case nfd
case nfc
case nfkd
case nfkc
case nfkcCasefold
case modifiedNFD
case modifiedNFC
}
extension StringProtocol {
func normalize(in form: UnicodeNormalizationForm) -> String {
switch form {
case .nfd:
return self.decomposedStringWithCanonicalMapping
case .nfc:
return self.precomposedStringWithCanonicalMapping
case .nfkd:
return self.decomposedStringWithCompatibilityMapping
case .nfkc:
return self.precomposedStringWithCompatibilityMapping
case .nfkcCasefold:
return String(self).precomposedStringWithCompatibilityMappingWithCasefold
case .modifiedNFD:
return String(self).decomposedStringWithHFSPlusMapping
case .modifiedNFC:
return String(self).precomposedStringWithHFSPlusMapping
}
}
}
extension String {
// MARK: Public Properties
/// A string made by normalizing the receiver’s contents using the Unicode Normalization Form KC with Casefold a.k.a. NFKC_Casefold or NFKC_CF.
var precomposedStringWithCompatibilityMappingWithCasefold: String {
let mutable = NSMutableString(string: self) as CFMutableString
CFStringNormalize(mutable, .KC)
CFStringFold(mutable, .compareCaseInsensitive, nil)
return mutable as String
}
/// A string made by normalizing the receiver’s contents using the normalization form adopted by HFS+, a.k.a. Apple Modified NFC.
var precomposedStringWithHFSPlusMapping: String {
let exclusionCharacters = "\\x{0340}\\x{0341}\\x{0343}\\x{0344}\\x{0374}\\x{037E}\\x{0387}\\x{0958}-\\x{095F}\\x{09DC}\\x{09DD}\\x{09DF}\\x{0A33}\\x{0A36}\\x{0A59}-\\x{0A5B}\\x{0A5E}\\x{0B5C}\\x{0B5D}\\x{0F43}\\x{0F4D}\\x{0F52}\\x{0F57}\\x{0F5C}\\x{0F69}\\x{0F73}\\x{0F75}\\x{0F76}\\x{0F78}\\x{0F81}\\x{0F93}\\x{0F9D}\\x{0FA2}\\x{0FA7}\\x{0FAC}\\x{0FB9}\\x{1F71}\\x{1F73}\\x{1F75}\\x{1F77}\\x{1F79}\\x{1F7B}\\x{1F7D}\\x{1FBB}\\x{1FBE}\\x{1FC9}\\x{1FCB}\\x{1FD3}\\x{1FDB}\\x{1FE3}\\x{1FEB}\\x{1FEE}\\x{1FEF}\\x{1FF9}\\x{1FFB}\\x{1FFD}\\x{2000}\\x{2001}\\x{2126}\\x{212A}\\x{212B}\\x{2329}\\x{232A}\\x{2ADC}\\x{F900}-\\x{FA0D}\\x{FA10}\\x{FA12}\\x{FA15}-\\x{FA1E}\\x{FA20}\\x{FA22}\\x{FA25}\\x{FA26}\\x{FA2A}-\\x{FA6D}\\x{FA70}-\\x{FAD9}\\x{FB1D}\\x{FB1F}\\x{FB2A}-\\x{FB36}\\x{FB38}-\\x{FB3C}\\x{FB3E}\\x{FB40}\\x{FB41}\\x{FB43}\\x{FB44}\\x{FB46}-\\x{FB4E}\\x{1D15E}-\\x{1D164}\\x{1D1BB}-\\x{1D1C0}\\x{2F800}-\\x{2FA1D}"
let regex = try! NSRegularExpression(pattern: "[^" + exclusionCharacters + "]+")
let mutable = NSMutableString(string: self)
return regex.matches(in: self, range: self.nsRange)
.map(\.range)
.reversed()
.reduce(into: mutable) { $0.replaceCharacters(in: $1, with: $0.substring(with: $1).precomposedStringWithCanonicalMapping) } as String
}
/// A string made by normalizing the receiver’s contents using the normalization form adopted by HFS+, a.k.a. Apple Modified NFD.
var decomposedStringWithHFSPlusMapping: String {
let length = CFStringGetMaximumSizeOfFileSystemRepresentation(self as CFString)
var buffer = [CChar](repeating: 0, count: length)
guard CFStringGetFileSystemRepresentation(self as CFString, &buffer, length) else { return self }
return String(cString: buffer)
}
}
|
apache-2.0
|
211f589b02099b647259cc91fabf337f
| 40.59434 | 927 | 0.626219 | 3.513147 | false | false | false | false |
twobitlabs/Alamofire
|
Source/SessionManager.swift
|
1
|
34012
|
//
// SessionManager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
open class SessionManager {
// MARK: - Helper Types
/// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
/// associated values.
///
/// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with
/// streaming information.
/// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
/// error.
public enum MultipartFormDataEncodingResult {
case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?)
case failure(Error)
}
// MARK: - Properties
/// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use
/// directly for any ad hoc requests.
open static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
/// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
open static let defaultHTTPHeaders: HTTPHeaders = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joined(separator: ", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`
let userAgent: String = {
if let info = Bundle.main.infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = Bundle(for: SessionManager.self).infoDictionary,
let build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
/// Default memory threshold used when encoding `MultipartFormData` in bytes.
open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000
/// The underlying session.
open let session: URLSession
/// The session delegate handling all the task and session delegate callbacks.
open let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
open var startRequestsImmediately: Bool = true
/// The request adapter called each time a new request is created.
open var adapter: RequestAdapter?
/// The request retrier called each time a request encounters an error to determine whether to retry the request.
open var retrier: RequestRetrier? {
get { return delegate.retrier }
set { delegate.retrier = newValue }
}
/// The background completion handler closure provided by the UIApplicationDelegate
/// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
/// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
/// will automatically call the handler.
///
/// If you need to handle your own events before the handler is called, then you need to override the
/// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
///
/// `nil` by default.
open var backgroundCompletionHandler: (() -> Void)?
let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString)
// MARK: - Lifecycle
/// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter configuration: The configuration used to construct the managed session.
/// `URLSessionConfiguration.default` by default.
/// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
/// default.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance.
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter session: The URL session.
/// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise.
public init?(
session: URLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionManager = self
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Data Request
/// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding`
/// and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
@discardableResult
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return request(encodedURLRequest)
} catch {
return request(failedWith: error)
}
}
/// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `DataRequest`.
open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
do {
let originalRequest = try urlRequest.asURLRequest()
let originalTask = DataRequest.Requestable(urlRequest: originalRequest)
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
let request = DataRequest(session: session, requestTask: .data(originalTask, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return request(failedWith: error)
}
}
// MARK: Private - Request Implementation
private func request(failedWith error: Error) -> DataRequest {
let request = DataRequest(session: session, requestTask: .data(nil, nil), error: error)
if startRequestsImmediately { request.resume() }
return request
}
// MARK: - Download Request
// MARK: URL Request
/// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`,
/// `headers` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return download(encodedURLRequest, to: destination)
} catch {
return download(failedWith: error)
}
}
/// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save
/// them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ urlRequest: URLRequestConvertible,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try urlRequest.asURLRequest()
return download(.request(urlRequest), to: destination)
} catch {
return download(failedWith: error)
}
}
// MARK: Resume Data
/// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve
/// the contents of the original request and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken
/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the
/// data is written incorrectly and will always fail to resume the download. For more information about the bug and
/// possible workarounds, please refer to the following Stack Overflow post:
///
/// - http://stackoverflow.com/a/39347461/1342462
///
/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for
/// additional information.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
resumingWith resumeData: Data,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return download(.resumeData(resumeData), to: destination)
}
// MARK: Private - Download Implementation
private func download(
_ downloadable: DownloadRequest.Downloadable,
to destination: DownloadRequest.DownloadFileDestination?)
-> DownloadRequest
{
do {
let task = try downloadable.task(session: session, adapter: adapter, queue: queue)
let request = DownloadRequest(session: session, requestTask: .download(downloadable, task))
request.downloadDelegate.destination = destination
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return download(failedWith: error)
}
}
private func download(failedWith error: Error) -> DownloadRequest {
let download = DownloadRequest(session: session, requestTask: .download(nil, nil), error: error)
if startRequestsImmediately { download.resume() }
return download
}
// MARK: - Upload Request
// MARK: File
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ fileURL: URL,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(fileURL, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.file(fileURL, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: Data
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(data, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.data(data, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: InputStream
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(stream, with: urlRequest)
} catch {
return upload(failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.stream(stream, urlRequest))
} catch {
return upload(failedWith: error)
}
}
// MARK: MultipartFormData
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
with: urlRequest,
encodingCompletion: encodingCompletion
)
} catch {
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `urlRequest`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter urlRequest: The URL request.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
with urlRequest: URLRequestConvertible,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
DispatchQueue.global(qos: .utility).async {
let formData = MultipartFormData()
multipartFormData(formData)
do {
var urlRequestWithContentType = try urlRequest.asURLRequest()
urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
let isBackgroundSession = self.session.configuration.identifier != nil
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
let data = try formData.encode()
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(data, with: urlRequestWithContentType),
streamingFromDisk: false,
streamFileURL: nil
)
DispatchQueue.main.async { encodingCompletion?(encodingResult) }
} else {
let fileManager = FileManager.default
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
var directoryError: Error?
// Create directory inside serial queue to ensure two threads don't do this in parallel
self.queue.sync {
do {
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
directoryError = error
}
}
if let directoryError = directoryError { throw directoryError }
try formData.writeEncodedData(to: fileURL)
DispatchQueue.main.async {
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(fileURL, with: urlRequestWithContentType),
streamingFromDisk: true,
streamFileURL: fileURL
)
encodingCompletion?(encodingResult)
}
}
} catch {
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
}
// MARK: Private - Upload Implementation
private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest {
do {
let task = try uploadable.task(session: session, adapter: adapter, queue: queue)
let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task))
if case let .stream(inputStream, _) = uploadable {
upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream }
}
delegate[task] = upload
if startRequestsImmediately { upload.resume() }
return upload
} catch {
return upload(failedWith: error)
}
}
private func upload(failedWith error: Error) -> UploadRequest {
let upload = UploadRequest(session: session, requestTask: .upload(nil, nil), error: error)
if startRequestsImmediately { upload.resume() }
return upload
}
#if !os(watchOS)
// MARK: - Stream Request
// MARK: Hostname and Port
/// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter hostName: The hostname of the server to connect to.
/// - parameter port: The port of the server to connect to.
///
/// - returns: The created `StreamRequest`.
@discardableResult
open func stream(withHostName hostName: String, port: Int) -> StreamRequest {
return stream(.stream(hostName: hostName, port: port))
}
// MARK: NetService
/// Creates a `StreamRequest` for bidirectional streaming using the `netService`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter netService: The net service used to identify the endpoint.
///
/// - returns: The created `StreamRequest`.
@discardableResult
open func stream(with netService: NetService) -> StreamRequest {
return stream(.netService(netService))
}
// MARK: Private - Stream Implementation
private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest {
do {
let task = try streamable.task(session: session, adapter: adapter, queue: queue)
let request = StreamRequest(session: session, requestTask: .stream(streamable, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return stream(failedWith: error)
}
}
private func stream(failedWith error: Error) -> StreamRequest {
let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error)
if startRequestsImmediately { stream.resume() }
return stream
}
#endif
// MARK: - Internal - Retry Request
func retry(_ request: Request) -> Bool {
guard let originalTask = request.originalTask else { return false }
do {
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
request.delegate.task = task // resets all task delegate data
request.startTime = CFAbsoluteTimeGetCurrent()
request.endTime = nil
task.resume()
return true
} catch {
request.delegate.error = error
return false
}
}
}
|
mit
|
745280955391bc180d6afc35a69eaf7b
| 42.438059 | 129 | 0.632306 | 5.374842 | false | false | false | false |
VincentPuget/PhoneList
|
PhoneList/class/AppDelegate.swift
|
1
|
9193
|
//
// AppDelegate.swift
// PhoneList
//
// Created by Vincent PUGET on 16/09/2016.
// Copyright © 2016 Vincent PUGET. All rights reserved.
//
import Cocoa
import ServiceManagement
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem!
let popover: NSPopover! = NSPopover()
var popoverEvent: Any! = nil
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
// find . -type f -name '*.png' -exec xattr -c {} \;
// find . | xargs -0 xattr -c
//menuItem
self.statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
if let button = self.statusItem.button {
let icon: NSImage! = NSImage(named: "[email protected]")
icon.isTemplate = true
button.image = icon
button.alternateImage = icon;
button.action = #selector(self.tooglePopOver(sender:))
}
let storyboard:NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let listViewController: ListViewController = storyboard.instantiateController(withIdentifier: "ListViewController") as! ListViewController
self.popover.contentViewController = listViewController
}
func tooglePopOver(sender: AnyObject){
if(self.popover.isShown){
self.closePopover(sender: sender)
}
else{
self.showPopover(sender: sender)
}
}
func closePopover(sender: AnyObject?) {
popover.performClose(sender)
}
func showPopover(sender: AnyObject?) {
if let button = statusItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
if(self.popoverEvent == nil){
self.popoverEvent = NSEvent.addGlobalMonitorForEvents(matching: NSEventMask.leftMouseUp, handler: {(event: NSEvent) in
self.closePopover(sender: self)
})
}
}
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
//qui l'app si la dernière fenetre active est fermée
// func applicationShouldTerminateAfterLastWindowClosed(_ theApplication: NSApplication) -> Bool
// {
// return true;
// }
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: Foundation.URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.apple.toolsQA.CocoaApp_CD" in the user's Application Support directory.
let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
let appSupportURL = urls[urls.count - 1]
return appSupportURL.appendingPathComponent("com.apple.toolsQA.CocoaApp_CD")
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "PhoneList", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
let fileManager = FileManager.default
var failError: NSError? = nil
var shouldFail = false
var failureReason = "There was an error creating or loading the application's saved data."
// Make sure the application files directory is there
do {
let properties = try self.applicationDocumentsDirectory.resourceValues(forKeys: [URLResourceKey.isDirectoryKey])
if !properties.isDirectory! {
failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)."
shouldFail = true
}
} catch {
let nserror = error as NSError
if nserror.code == NSFileReadNoSuchFileError {
do {
try fileManager.createDirectory(atPath: self.applicationDocumentsDirectory.path, withIntermediateDirectories: true, attributes: nil)
} catch {
failError = nserror
}
} else {
failError = nserror
}
}
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = nil
if failError == nil {
coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("PhoneList.storedata")
do {
let options = [ NSInferMappingModelAutomaticallyOption : true,
NSMigratePersistentStoresAutomaticallyOption : true]
try coordinator!.addPersistentStore(ofType: NSXMLStoreType, configurationName: nil, at: url, options: options)
} catch {
// Replace this implementation with code to handle the error appropriately.
/*
Typical reasons for an error here include:
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
failError = error as NSError
}
}
if shouldFail || (failError != nil) {
// Report any error we got.
if let error = failError {
NSApplication.shared().presentError(error)
fatalError("Unresolved error: \(error), \(error.userInfo)")
}
fatalError("Unsresolved error: \(failureReason)")
} else {
return coordinator!
}
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving and Undo support
@IBAction func saveAction(_ sender: AnyObject?) {
// Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
if !managedObjectContext.commitEditing() {
NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing before saving")
}
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
NSApplication.shared().presentError(nserror)
}
}
}
func windowWillReturnUndoManager(window: NSWindow) -> UndoManager? {
// Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
return managedObjectContext.undoManager
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplicationTerminateReply {
// Save changes in the application's managed object context before the application terminates.
if !managedObjectContext.commitEditing() {
NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing to terminate")
return .terminateCancel
}
if !managedObjectContext.hasChanges {
return .terminateNow
}
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
// Customize this code block to include application-specific recovery steps.
let result = sender.presentError(nserror)
if (result) {
return .terminateCancel
}
let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message")
let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info");
let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title")
let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title")
let alert = NSAlert()
alert.messageText = question
alert.informativeText = info
alert.addButton(withTitle: quitButton)
alert.addButton(withTitle: cancelButton)
let answer = alert.runModal()
if answer == NSAlertSecondButtonReturn {
return .terminateCancel
}
}
// If we got here, it is time to quit.
return .terminateNow
}
}
|
mit
|
20cf0e5faf08df252f5f5e1413edb1ad
| 38.956522 | 343 | 0.701306 | 5.230507 | false | false | false | false |
cfilipov/MuscleBook
|
MuscleBook/AllWorkoutsViewController.swift
|
1
|
3818
|
/*
Muscle Book
Copyright (C) 2016 Cristian Filipov
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 Eureka
class AllWorkoutsViewController: FormViewController {
private let db = DB.sharedInstance
let weightFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = 0
return formatter
}()
let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd EEE"
return formatter
}()
let timeFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"
return formatter
}()
let monthFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMMM, yyyy"
return formatter
}()
let filterControl: UISegmentedControl = {
let v = UISegmentedControl(items: [])
return v
}()
let restDaySwitch: UISwitch = {
let v = UISwitch()
return v
}()
let cal = NSCalendar.currentCalendar()
init() {
super.init(style: .Grouped)
hidesBottomBarWhenPushed = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Workouts"
rebuildForm()
}
private func rebuildForm() {
form.removeAll()
let allWorkouts = try! db.all(Workout)
var curMonth: String? = nil
var curSection: Section? = nil
for w in allWorkouts {
let month = monthFormatter.stringFromDate(w.startTime)
if month != curMonth {
curMonth = month
let section = Section(month)
form +++ section
curSection = section
}
if let curSection = curSection {
curSection <<< workoutToRow(w)
}
}
}
private func workoutToRow(workout: Workout) -> BaseRow {
let row = activeDayRow(workout)
//let row = workout.reps > 0 ? activeDayRow(workout) : restDayRow(workout)
return row
}
private func restDayRow(workout: Workout) -> BaseRow {
let row = LabelRow()
row.value = "Rest"
row.hidden = "$show_rest_days == false"
row.title = dateFormatter.stringFromDate(workout.startTime)
return row
}
private func activeDayRow(workout: Workout) -> BaseRow {
let row = LabelRow()
row.title = dateFormatter.stringFromDate(workout.startTime)
row.cellSetup { cell, row in
cell.detailTextLabel?.textColor = UIColor.blackColor()
cell.accessoryType = .DisclosureIndicator
}
row.cellUpdate { cell, row in
cell.detailTextLabel?.text = self.timeFormatter.stringFromDate(workout.startTime)
}
row.onCellSelection { cell, row in
let vc = WorkoutSummaryViewController(workout: workout)
self.showViewController(vc, sender: nil)
}
return row
}
}
|
gpl-3.0
|
214831cde17f12fcde3fd1d30345e4bb
| 29.062992 | 93 | 0.626244 | 4.95201 | false | false | false | false |
googlearchive/science-journal-ios
|
ScienceJournalTests/UI/ExperimentListDataSourceTest.swift
|
1
|
11902
|
/*
* Copyright 2019 Google LLC. 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 XCTest
@testable import third_party_sciencejournal_ios_ScienceJournalOpen
class ExperimentListDataSourceTest: XCTestCase {
var dataSource: ExperimentsListDataSource!
var metadataManager: MetadataManager!
override func setUp() {
super.setUp()
metadataManager = createMetadataManager()
dataSource = ExperimentsListDataSource(
includeArchived: false,
metadataManager: metadataManager)
}
func testInsertOverviewAtBeginning() {
// Insert four overviews at the beginning that will create two separate sections.
let overview1 = ExperimentOverview(experimentID: "experiment1")
overview1.lastUsedDate = dateWithFormat("20170920")
dataSource.insertOverview(overview1, atBeginning: true)
let overview2 = ExperimentOverview(experimentID: "experiment2")
overview2.lastUsedDate = dateWithFormat("20170921")
dataSource.insertOverview(overview2, atBeginning: true)
let overview3 = ExperimentOverview(experimentID: "experiment3")
overview3.lastUsedDate = dateWithFormat("20171001")
dataSource.insertOverview(overview3, atBeginning: true)
let overview4 = ExperimentOverview(experimentID: "experiment4")
overview4.lastUsedDate = dateWithFormat("20171002")
dataSource.insertOverview(overview4, atBeginning: true)
XCTAssertEqual(dataSource.numberOfSections, 3, "There should be three sections.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 1))!.experimentID,
overview4.experimentID,
"experiment4 should be the first item in the first section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 1, section: 1))!.experimentID,
overview3.experimentID,
"experiment3 should be the second item in the first section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 2))!.experimentID,
overview2.experimentID,
"experiment2 should be the first item in the second section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 1, section: 2))!.experimentID,
overview1.experimentID,
"experiment1 should be the second item in the second section.")
// Insert a final overview that will go into the initial section.
let overview5 = ExperimentOverview(experimentID: "experiment5")
overview5.lastUsedDate = dateWithFormat("20170927")
dataSource.insertOverview(overview5, atBeginning: true)
XCTAssertEqual(dataSource.numberOfSections, 3, "There should be three sections.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 1))!.experimentID,
overview4.experimentID,
"experiment4 should be the first item in the first section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 1, section: 1))!.experimentID,
overview3.experimentID,
"experiment3 should be the second item in the first section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 2))!.experimentID,
overview5.experimentID,
"experiment5 should be the first item in the second section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 1, section: 2))!.experimentID,
overview2.experimentID,
"experiment2 should be the second item in the second section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 2, section: 2))!.experimentID,
overview1.experimentID,
"experiment1 should be the third item in the second section.")
}
func testInsertOverviewIntoNewSections() {
// Insert three overviews that will create three separate sections.
let overview1 = ExperimentOverview(experimentID: "experiment1")
overview1.lastUsedDate = dateWithFormat("20170720")
dataSource.insertOverview(overview1)
let overview2 = ExperimentOverview(experimentID: "experiment2")
overview2.lastUsedDate = dateWithFormat("20170901")
dataSource.insertOverview(overview2)
let overview3 = ExperimentOverview(experimentID: "experiment3")
overview3.lastUsedDate = dateWithFormat("20171001")
dataSource.insertOverview(overview3)
XCTAssertEqual(dataSource.numberOfSections, 4, "There should be four sections.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 1))!.experimentID,
overview3.experimentID,
"experiment3 should be the first item in the first section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 2))!.experimentID,
overview2.experimentID,
"experiment2 should be the first item in the second section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 3))!.experimentID,
overview1.experimentID,
"experiment1 should be the first item in the third section.")
// Insert an overview that will go into a section between the existing ones.
let overview4 = ExperimentOverview(experimentID: "experiment4")
overview4.lastUsedDate = dateWithFormat("20170802")
dataSource.insertOverview(overview4)
XCTAssertEqual(dataSource.numberOfSections, 5, "There should be five sections.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 1))!.experimentID,
overview3.experimentID,
"experiment3 should be the first item in the first section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 2))!.experimentID,
overview2.experimentID,
"experiment2 should be the first item in the second section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 3))!.experimentID,
overview4.experimentID,
"experiment4 should be the first item in the third section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 4))!.experimentID,
overview1.experimentID,
"experiment1 should be the first item in the fourth section.")
// Insert a final overview that will go into a section after all of the existing ones.
let overview5 = ExperimentOverview(experimentID: "experiment5")
overview5.lastUsedDate = dateWithFormat("20170602")
dataSource.insertOverview(overview5)
XCTAssertEqual(dataSource.numberOfSections, 6, "There should be six sections.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 1))!.experimentID,
overview3.experimentID,
"experiment3 should be the first item in the first section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 2))!.experimentID,
overview2.experimentID,
"experiment2 should be the first item in the second section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 3))!.experimentID,
overview4.experimentID,
"experiment4 should be the first item in the third section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 4))!.experimentID,
overview1.experimentID,
"experiment1 should be the first item in the fourth section.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 5))!.experimentID,
overview5.experimentID,
"experiment5 should be the first item in the fifth section.")
}
func testInsertOverviewIntoExistingSection() {
// Insert three overviews that will go into a single section.
let overview1 = ExperimentOverview(experimentID: "experiment1")
overview1.lastUsedDate = dateWithFormat("20171005")
dataSource.insertOverview(overview1)
let overview2 = ExperimentOverview(experimentID: "experiment2")
overview2.lastUsedDate = dateWithFormat("20171010")
dataSource.insertOverview(overview2)
let overview3 = ExperimentOverview(experimentID: "experiment3")
overview3.lastUsedDate = dateWithFormat("20171015")
dataSource.insertOverview(overview3)
XCTAssertEqual(dataSource.numberOfSections, 2, "There should be two sections.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 1))!.experimentID,
overview3.experimentID,
"experiment3 should be the first item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 1, section: 1))!.experimentID,
overview2.experimentID,
"experiment2 should be the second item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 2, section: 1))!.experimentID,
overview1.experimentID,
"experiment1 should be the third item.")
// Insert an overview that will go between the existing ones.
let overview4 = ExperimentOverview(experimentID: "experiment4")
overview4.lastUsedDate = dateWithFormat("20171012")
dataSource.insertOverview(overview4)
XCTAssertEqual(dataSource.numberOfSections, 2, "There should be two sections.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 1))!.experimentID,
overview3.experimentID,
"experiment3 should be the first item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 1, section: 1))!.experimentID,
overview4.experimentID,
"experiment4 should be the second item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 2, section: 1))!.experimentID,
overview2.experimentID,
"experiment2 should be the third item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 3, section: 1))!.experimentID,
overview1.experimentID,
"experiment1 should be the fourth item.")
// Insert a final overview that will go after all of the existing ones.
let overview5 = ExperimentOverview(experimentID: "experiment5")
overview5.lastUsedDate = dateWithFormat("20171001")
dataSource.insertOverview(overview5)
XCTAssertEqual(dataSource.numberOfSections, 2, "There should be two sections.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 0, section: 1))!.experimentID,
overview3.experimentID,
"experiment3 should be the first item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 1, section: 1))!.experimentID,
overview4.experimentID,
"experiment4 should be the second item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 2, section: 1))!.experimentID,
overview2.experimentID,
"experiment3 should be the third item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 3, section: 1))!.experimentID,
overview1.experimentID,
"experiment2 should be the fourth item.")
XCTAssertEqual(dataSource.itemAt(IndexPath(item: 4, section: 1))!.experimentID,
overview5.experimentID,
"experiment5 should be the fifth item.")
}
// MARK: - Helpers
func dateWithFormat(_ format: String) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
return formatter.date(from: format)!
}
}
|
apache-2.0
|
496a9be32483e75ea61caedcb3a01960
| 51.897778 | 90 | 0.69022 | 5.011368 | false | false | false | false |
moosichu/hac-website
|
Sources/HaCWebsiteLib/Views/PostCard.swift
|
1
|
1188
|
import HaCTML
struct PostCard: Nodeable {
enum PostCategory: String {
case workshop = "Workshop"
case video = "Video"
case hackathon = "Hackathon"
case general = "General Event"
}
let title: String
let category: PostCategory
let description: String
let backgroundColor: String?
let imageURL: String?
var node: Node {
return El.Div[Attr.className => "PostCard", Attr.style => ["background-color": backgroundColor]].containing(
El.Div[
Attr.className => "PostCard__photoBackground",
Attr.style => ["background-image": imageURL.map { "url('\($0)')" }]
],
El.Div[Attr.className => "PostCard__content"].containing(
El.Span[Attr.className => "PostCard__categoryLabel"].containing(category.rawValue),
El.Div[Attr.className => "PostCard__title"].containing(title),
El.Div[Attr.className => "PostCard__description"].containing(description)
),
El.Div[Attr.className => "PostCard__footer"].containing(
El.Div[Attr.className => "PostCard__bottomAction"].containing("Find out more")
)
)
}
}
protocol PostCardRepresentable {
var postCardRepresentation : PostCard {get}
}
|
mit
|
3e4d9fc431d6cfb074514afd2d97fa7a
| 31.135135 | 112 | 0.659933 | 4.027119 | false | false | false | false |
skylib/SnapOnboarding-iOS
|
SnapOnboarding-iOS/SnapOnboarding-iOS/HasSparklingStars.swift
|
2
|
1624
|
import UIKit
protocol HasSparklingStars: class {
var sparklingStars: [UIImageView]? { get }
}
extension HasSparklingStars {
func animateSparklingStarsWithCycleDuration(_ duration: TimeInterval) {
guard let sparklingStars = sparklingStars else {
return
}
let variation = duration < 1 ? 0 : 0.4
for star in sparklingStars where star.layer.animationKeys() == nil {
let delay: TimeInterval = Double(arc4random_uniform(UInt32(duration * 100))) / 100 // 0 ... duration
let duration: TimeInterval = (duration - variation / 2) + Double(arc4random_uniform(UInt32(variation * 100))) / 100 // (duration - variation / 2) ... (duration + variation / 2)
animateSparklingStarWithDuration(duration, delay: delay, star: star)
}
}
func stopAnimatingSparklingStars() {
sparklingStars?.forEach { $0.layer.removeAllAnimations() }
}
fileprivate func animateSparklingStarWithDuration(_ duration: TimeInterval, delay: TimeInterval, star: UIImageView) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions(), animations: {
star.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}, completion: { finished in
guard finished else { return }
UIView.animate(withDuration: duration, delay: 0, options: [.autoreverse, .repeat], animations: {
star.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}, completion: nil)
})
}
}
|
bsd-3-clause
|
ae3e6de02362bf462a2f9633f34bd82a
| 36.767442 | 188 | 0.617611 | 4.653295 | false | false | false | false |
pcperini/Thrust
|
Thrust/Source/Random.swift
|
1
|
3801
|
//
// Random.swift
// Thrust
//
// Created by Patrick Perini on 7/22/14.
// Copyright (c) 2014 pcperini. All rights reserved.
//
import Foundation
// MARK: Random Primitives
extension Int {
// MARK: Class Accessors
/// Returns a uniformly-distributed random integer between Int.min and Int.max, inclusive.
static func random() -> Int {
return self.random(Int.min ..< Int.max)
}
/// Returns a uniformly-distributed random integer in the given range.
static func random(r: Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(r.endIndex)) + UInt32(r.startIndex))
}
}
extension Double {
// MARK: Class Accessors
/// Returns a uniformly-distributed random double between 0.0 and 1.0, inclusive.
static func random() -> Double {
return Double(Int.random(0 ... 100)) / 100.0
}
/**
Returns a normally-distributed random double.
:param: sigma The standard deviation sigma for the distribution.
:param: mean The average value for the distribution.
:returns: A normally-distributed random double.
*/
static func normalized(#sigma: Double, mean: Double) -> Double {
return sqrt(-2.0 * log(Double.random() + DBL_EPSILON)) * cos(2.0 * M_PI * Double.random()) * sigma + mean
}
}
extension String {
// MARK: Class Accessors
/**
Returns a randomly-built string.
:param: length The length of the random string. Defaults to a random integer.
:param: alphabet The alphabet from which to construct the string. Defaults to alphanumeric characters.
:returns: A randomly-built string.
*/
static func random(length: Int? = nil, alphabet: String? = nil) -> String {
let chars: String = alphabet ?? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var string: String = ""
for _ in 0 ..< (length ?? Int.random()) {
let character: String = chars[Int.random(0 ..< chars.length)]
string += character
}
return string
}
}
// MARK: Random Selections
protocol Random {
typealias ValueType
// MARK: Accessors
/// Returns a random value from the collection.
var any: ValueType? { get }
// MARK: Mutators
/// Randomizes the values' positions in the collection. Not guaranteed to be different across shuffles.
mutating func shuffle()
}
extension Array: Random {
// MARK: Properties
var any: T? {
return (self.count == 0) ? nil : self[Int.random(0 ..< self.count)]
}
// MARK: Mutators
mutating func shuffle() {
for var i = self.count - 1; i > 0; i-- {
let j = Int.random(0 ..< i)
swap(&self[i], &self[j])
}
}
}
extension Dictionary: Random {
// MARK: Properties
var any: Key? {
return self.keys.array.any
}
// MARK: Mutators
mutating func shuffle() {
// Since order is not guaranteed,
// do nothing.
}
}
extension Dictionary {
// MARK: Accessors
/// From a [Key: Int] dictionary, returns a random Key, weighted by the key's value.
var anyByWeight: Key? {
get {
let keys: [Key] = self.keys.array
var weightedIndices: [Int] = []
for (index, key) in enumerate(keys) {
var value: Value? = self[key]
if let count = value as? Int {
for _ in 0 ..< count {
weightedIndices.append(index)
}
}
}
if let weightedIndex: Int = weightedIndices.any {
return keys[weightedIndex]
} else {
return nil
}
}
}
}
|
mit
|
aa35a3a90df824547a80925db1c83395
| 26.751825 | 113 | 0.574849 | 4.290068 | false | false | false | false |
chrisjmendez/swift-exercises
|
Animation/Flicker/flicker/ViewController.swift
|
1
|
1975
|
//
// ViewController.swift
// flicker
//
// Created by Tommy Trojan on 2/1/17.
// Copyright © 2017 Chris Mendez. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var timer:Timer = Timer()
var counter = 0.2
@IBOutlet weak var myView: UIView!
@IBOutlet weak var myButton: UIButton!
@IBAction func onTap(_ sender: Any) {
print("onTap")
startTimer()
blinkingStart()
}
func blinkingStart(){
UIView.animate(withDuration: 0.1, delay: 0.0, options: [
.curveEaseInOut,
.repeat,
.autoreverse,
.allowUserInteraction
],
animations: {() -> Void in
self.myView.alpha = 0.0
}, completion: {(_ finished: Bool) -> Void in
print("animation compelted")
})
}
func blinkingStop(){
UIView.animate(withDuration: 0.12, delay: 0.0, options: [.curveEaseInOut, .beginFromCurrentState], animations: {() -> Void in
self.myView.alpha = 1
}, completion: {(_ finished: Bool) -> Void in
// Do nothing
})
myView.layer.removeAllAnimations()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func startTimer(){
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.counterUpdater), userInfo: nil, repeats: true)
}
func stopTimer(){
timer.invalidate()
blinkingStop()
}
func resetTimer() {
timer.invalidate()
startTimer()
}
func counterUpdater(){
counter -= counter
print("counterUpdater", counter)
if( counter == 0 ){
stopTimer()
}
}
}
|
mit
|
3c933819aaa9a69dd0c37982b329332d
| 23.675 | 149 | 0.566363 | 4.733813 | false | false | false | false |
jasnig/UsefulPickerView
|
UsefulPickerView/Source/SelectionTextField.swift
|
1
|
11166
|
//
// SelectionTextField.swift
// UsefulPickerVIew
//
// Created by jasnig on 16/4/16.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// 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
open class SelectionTextField: UITextField {
public typealias BtnAction = () -> Void
public typealias SingleDoneAction = (_ textField: UITextField, _ selectedIndex: Int, _ selectedValue: String) -> Void
public typealias MultipleDoneAction = (_ textField: UITextField, _ selectedIndexs: [Int], _ selectedValues: [String]) -> Void
public typealias DateDoneAction = (_ textField: UITextField, _ selectedDate: Date) -> Void
public typealias MultipleAssociatedDataType = [[[String: [String]?]]]
/// 保存pickerView的初始化
fileprivate var setUpPickerClosure:(() -> PickerView)?
/// 如果设置了autoSetSelectedText为true 将自动设置text的值, 默认以空格分开多列选择, 但你仍然可以在响应完成的closure中修改text的值
fileprivate var autoSetSelectedText = false
//MARK: 初始化
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
// 从xib或storyboard中初始化时候调用
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
deinit {
NotificationCenter.default.removeObserver(self)
print("\(self.debugDescription) --- 销毁")
}
}
// MARK: - 监听通知
extension SelectionTextField {
fileprivate func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(self.didBeginEdit), name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: self)
NotificationCenter.default.addObserver(self, selector: #selector(self.didEndEdit), name: NSNotification.Name.UITextFieldTextDidEndEditing, object: self)
}
// 开始编辑添加pickerView
func didBeginEdit() {
let pickerView = setUpPickerClosure?()
pickerView?.delegate = self
inputView = pickerView
}
// 编辑完成销毁pickerView
func didEndEdit() {
inputView = nil
}
override open func caretRect(for position: UITextPosition) -> CGRect {
return CGRect.zero
}
}
// MARK: - 使用方法
extension SelectionTextField {
/// 单列选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter data: 数据
/// - parameter defaultSeletedIndex: 默认选中的行数
/// - parameter autoSetSelectedText: 设置为true的时候, 将按默认的格式自动设置textField的值
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public func showSingleColPicker(_ toolBarTitle: String, data: [String], defaultSelectedIndex: Int?,autoSetSelectedText: Bool, doneAction: SingleDoneAction?) {
self.autoSetSelectedText = autoSetSelectedText
// 保存在这个closure中, 在开始编辑的时候在执行, 避免像之前在这里直接初始化pickerView, 每个SelectionTextField在调用这个方法的时候就初始化pickerView,当有多个pickerView的时候就很消耗内存
setUpPickerClosure = {() -> PickerView in
return PickerView.singleColPicker(toolBarTitle, singleColData: data, defaultIndex: defaultSelectedIndex, cancelAction: {[unowned self] in
self.endEditing(true)
}, doneAction: {[unowned self] (selectedIndex: Int, selectedValue: String) -> Void in
doneAction?(self, selectedIndex, selectedValue)
self.endEditing(true)
})
}
}
/// 多列不关联选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter data: 数据
/// - parameter defaultSeletedIndexs: 默认选中的每一列的行数
/// - parameter autoSetSelectedText: 设置为true的时候, 将俺默认的格式自动设置textField的值
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public func showMultipleColsPicker(_ toolBarTitle: String, data: [[String]], defaultSelectedIndexs: [Int]?, autoSetSelectedText: Bool, doneAction: MultipleDoneAction?) {
self.autoSetSelectedText = autoSetSelectedText
setUpPickerClosure = {() -> PickerView in
return PickerView.multipleCosPicker(toolBarTitle, multipleColsData: data, defaultSelectedIndexs: defaultSelectedIndexs, cancelAction: { [unowned self] in
self.endEditing(true)
}, doneAction:{[unowned self] (selectedIndexs: [Int], selectedValues: [String]) -> Void in
doneAction?(self, selectedIndexs, selectedValues)
self.endEditing(true)
})
}
}
/// 多列关联选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter data: 数据, 数据的格式参照示例
/// - parameter defaultSeletedIndexs: 默认选中的每一列的行数
/// - parameter autoSetSelectedText: 设置为true的时候, 将按默认的格式自动设置textField的值
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public func showMultipleAssociatedColsPicker(_ toolBarTitle: String, data: MultipleAssociatedDataType, defaultSelectedValues: [String]?,autoSetSelectedText: Bool, doneAction: MultipleDoneAction?) {
self.autoSetSelectedText = autoSetSelectedText
setUpPickerClosure = {() -> PickerView in
return PickerView.multipleAssociatedCosPicker(toolBarTitle, multipleAssociatedColsData: data, defaultSelectedValues: defaultSelectedValues,cancelAction: { [unowned self] in
self.endEditing(true)
}, doneAction:{[unowned self] (selectedIndexs: [Int], selectedValues: [String]) -> Void in
doneAction?(self, selectedIndexs, selectedValues)
self.endEditing(true)
})
}
}
/// 城市选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter defaultSeletedValues: 默认选中的每一列的值, 注意不是行数
/// - parameter autoSetSelectedText: 设置为true的时候, 将按默认的格式自动设置textField的值
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public func showCitiesPicker(_ toolBarTitle: String, defaultSelectedValues: [String]?,autoSetSelectedText: Bool, doneAction: MultipleDoneAction?) {
self.autoSetSelectedText = autoSetSelectedText
setUpPickerClosure = {() -> PickerView in
return PickerView.citiesPicker(toolBarTitle, defaultSelectedValues: defaultSelectedValues, cancelAction: { [unowned self] in
self.endEditing(true)
}, doneAction:{[unowned self] (selectedIndexs: [Int], selectedValues: [String]) -> Void in
doneAction?(self,selectedIndexs, selectedValues)
self.endEditing(true)
})
}
}
/// 日期选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter datePickerSetting: 可配置UIDatePicker的样式
/// - parameter autoSetSelectedText: 设置为true的时候, 将按默认的格式自动设置textField的值
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public func showDatePicker(_ toolBarTitle: String, datePickerSetting: DatePickerSetting = DatePickerSetting(), autoSetSelectedText: Bool, doneAction: DateDoneAction?) {
self.autoSetSelectedText = autoSetSelectedText
setUpPickerClosure = {() -> PickerView in
return PickerView.datePicker(toolBarTitle, datePickerSetting: datePickerSetting, cancelAction: { [unowned self] in
self.endEditing(true)
}, doneAction: {[unowned self] (selectedDate) in
doneAction?(self, selectedDate)
self.endEditing(true)
})
}
}
}
// MARK: - PickerViewDelegate -- 如果设置了autoSetSelectedText为true 这些代理方法中将以默认的格式自动设置textField的值
extension SelectionTextField: PickerViewDelegate {
public func singleColDidSelecte(_ selectedIndex: Int, selectedValue: String) {
if autoSetSelectedText {
text = " " + selectedValue
}
}
public func multipleColsDidSelecte(_ selectedIndexs: [Int], selectedValues: [String]) {
if autoSetSelectedText {
text = selectedValues.reduce("", { (result, selectedValue) -> String in
result + " " + selectedValue
})
}
}
public func dateDidSelecte(_ selectedDate: Date) {
if autoSetSelectedText {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let string = formatter.string(from: selectedDate)
text = " " + string
}
}
}
|
mit
|
a56057e407b196a966f748d739715a1b
| 38.896154 | 201 | 0.609756 | 4.762626 | false | false | false | false |
MrAlek/JSQDataSourcesKit
|
Example/Example/FetchedTableViewController.swift
|
1
|
4012
|
//
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
import CoreData
import JSQDataSourcesKit
class FetchedTableViewController: UITableViewController {
// MARK: Properties
let stack = CoreDataStack()
typealias TableCellFactory = CellFactory<Thing, UITableViewCell>
var dataSourceProvider: TableViewFetchedResultsDataSourceProvider<TableCellFactory>?
var delegateProvider: TableViewFetchedResultsDelegateProvider<TableCellFactory>?
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// 1. create factory
let factory = CellFactory(reuseIdentifier: CellId) { (cell, model: Thing, tableView, indexPath) -> UITableViewCell in
cell.textLabel?.text = model.displayName
cell.textLabel?.textColor = model.displayColor
cell.detailTextLabel?.text = "\(indexPath.section), \(indexPath.row)"
return cell
}
// 2. create fetched results controller
let frc = thingFRCinContext(stack.context)
// 3. create delegate provider
delegateProvider = TableViewFetchedResultsDelegateProvider(tableView: tableView,
cellFactory: factory,
fetchedResultsController: frc)
// 4. create data source provider
dataSourceProvider = TableViewFetchedResultsDataSourceProvider(fetchedResultsController: frc,
cellFactory: factory,
tableView: tableView)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
fetchData()
}
// MARK: Helpers
func fetchData() {
do {
try dataSourceProvider?.fetchedResultsController.performFetch()
} catch {
print("Fetch error = \(error)")
}
}
// MARK: Actions
@IBAction func didTapActionButton(sender: UIBarButtonItem) {
UIAlertController.showActionAlert(self, addNewAction: {
self.addNewThing()
}, deleteAction: {
self.deleteSelected()
}, changeNameAction: {
self.changeNameSelected()
}, changeColorAction: {
self.changeColorSelected()
}, changeAllAction: {
self.changeAllSelected()
})
}
func addNewThing() {
tableView.deselectAllRows()
let newThing = Thing.newThing(stack.context)
stack.saveAndWait()
fetchData()
if let indexPath = dataSourceProvider?.fetchedResultsController.indexPathForObject(newThing) {
tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .Middle)
}
}
func deleteSelected() {
dataSourceProvider?.fetchedResultsController.deleteThingsAtIndexPaths(tableView.indexPathsForSelectedRows)
stack.saveAndWait()
fetchData()
}
func changeNameSelected() {
dataSourceProvider?.fetchedResultsController.changeThingNamesAtIndexPaths(tableView.indexPathsForSelectedRows)
stack.saveAndWait()
fetchData()
}
func changeColorSelected() {
dataSourceProvider?.fetchedResultsController.changeThingColorsAtIndexPaths(tableView.indexPathsForSelectedRows)
stack.saveAndWait()
fetchData()
}
func changeAllSelected() {
dataSourceProvider?.fetchedResultsController.changeThingsAtIndexPaths(tableView.indexPathsForSelectedRows)
stack.saveAndWait()
fetchData()
}
}
|
mit
|
c008e0115dcc7a2d934df56ea05128cd
| 29.157895 | 125 | 0.626527 | 5.846939 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Examples/SciChartDemo/ShareChartSwiftExample/ShareChartSwiftExample/SCSBrownianMotionGenerator.swift
|
1
|
2034
|
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// SCSBrownianMotionGenerator.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
import Foundation
class SCSBrownianMotionGenerator: NSObject {
private var xmax: Double = 0.0
private var xmin: Double = 0.0
private var xyData: [[Double]]!
func getXyData(_ count: Int, min: Double, max: Double) -> [[Double]] {
xmin = min
xmax = max
initXyData(count, min: min, max: max)
return xyData
}
func initXyData(_ count: Int, min: Double, max: Double) {
xyData = [[Double]]()
let xValues = [Double]() /* capacity: count */
let yValues = [Double]() /* capacity: count */
xyData.append(xValues)
xyData.append(yValues)
// Generate a slightly positive biased random walk
// y[i] = y[i-1] + random,
// where random is in the range min, max
for i in 0..<count {
xyData[0].append(Double(i))
xyData[1].append(SCSDataManager.randomize(min, max: max))
}
}
func mapX(_ v1: Double, _ v2: Double) -> Double {
return xmin + (xmax - xmin) * v1
}
func getRandomPoints() -> Double {
let v1: Double = SCSDataManager.randomize(0.0, max: 1.0)
let v2: Double = SCSDataManager.randomize(0.0, max: 1.0)
return mapX(v1, v2)
}
}
|
mit
|
1e1fc9bb838769651a00986744ea9c6c
| 34.017241 | 99 | 0.570162 | 4.062 | false | false | false | false |
kesun421/firefox-ios
|
Client/Frontend/Browser/TabPeekViewController.swift
|
1
|
7843
|
/* 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 Shared
import Storage
import ReadingList
import WebKit
protocol TabPeekDelegate: class {
func tabPeekDidAddBookmark(_ tab: Tab)
@discardableResult func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord?
func tabPeekRequestsPresentationOf(_ viewController: UIViewController)
func tabPeekDidCloseTab(_ tab: Tab)
}
class TabPeekViewController: UIViewController, WKNavigationDelegate {
fileprivate static let PreviewActionAddToBookmarks = NSLocalizedString("Add to Bookmarks", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Bookmarks")
fileprivate static let PreviewActionAddToReadingList = NSLocalizedString("Add to Reading List", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to add current tab to Reading List")
fileprivate static let PreviewActionCopyURL = NSLocalizedString("Copy URL", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to copy the URL of the current tab to clipboard")
fileprivate static let PreviewActionCloseTab = NSLocalizedString("Close Tab", tableName: "3DTouchActions", comment: "Label for preview action on Tab Tray Tab to close the current tab")
weak var tab: Tab?
fileprivate weak var delegate: TabPeekDelegate?
fileprivate var clientPicker: UINavigationController?
fileprivate var isBookmarked: Bool = false
fileprivate var isInReadingList: Bool = false
fileprivate var hasRemoteClients: Bool = false
fileprivate var ignoreURL: Bool = false
fileprivate var screenShot: UIImageView?
fileprivate var previewAccessibilityLabel: String!
// Preview action items.
lazy var previewActions: [UIPreviewActionItem] = {
var actions = [UIPreviewActionItem]()
let urlIsTooLongToSave = self.tab?.urlIsTooLong ?? false
if !self.ignoreURL && !urlIsTooLongToSave {
if !self.isInReadingList {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToReadingList, style: .default) { previewAction, viewController in
guard let tab = self.tab else { return }
_ = self.delegate?.tabPeekDidAddToReadingList(tab)
})
}
if !self.isBookmarked {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionAddToBookmarks, style: .default) { previewAction, viewController in
guard let tab = self.tab else { return }
self.delegate?.tabPeekDidAddBookmark(tab)
})
}
if self.hasRemoteClients {
actions.append(UIPreviewAction(title: Strings.SendToDeviceTitle, style: .default) { previewAction, viewController in
guard let clientPicker = self.clientPicker else { return }
self.delegate?.tabPeekRequestsPresentationOf(clientPicker)
})
}
// only add the copy URL action if we don't already have 3 items in our list
// as we are only allowed 4 in total and we always want to display close tab
if actions.count < 3 {
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCopyURL, style: .default) { previewAction, viewController in
guard let url = self.tab?.canonicalURL else { return }
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: self.view)
})
}
}
actions.append(UIPreviewAction(title: TabPeekViewController.PreviewActionCloseTab, style: .destructive) { previewAction, viewController in
guard let tab = self.tab else { return }
self.delegate?.tabPeekDidCloseTab(tab)
})
return actions
}()
init(tab: Tab, delegate: TabPeekDelegate?) {
self.tab = tab
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if let webViewAccessibilityLabel = tab?.webView?.accessibilityLabel {
previewAccessibilityLabel = String(format: NSLocalizedString("Preview of %@", tableName: "3DTouchActions", comment: "Accessibility label, associated to the 3D Touch action on the current tab in the tab tray, used to display a larger preview of the tab."), webViewAccessibilityLabel)
}
// if there is no screenshot, load the URL in a web page
// otherwise just show the screenshot
setupWebView(tab?.webView)
guard let screenshot = tab?.screenshot else { return }
setupWithScreenshot(screenshot)
}
fileprivate func setupWithScreenshot(_ screenshot: UIImage) {
let imageView = UIImageView(image: screenshot)
self.view.addSubview(imageView)
imageView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
screenShot = imageView
screenShot?.accessibilityLabel = previewAccessibilityLabel
}
fileprivate func setupWebView(_ webView: WKWebView?) {
guard let webView = webView, let url = webView.url, !isIgnoredURL(url) else { return }
let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration)
clonedWebView.allowsLinkPreview = false
webView.accessibilityLabel = previewAccessibilityLabel
self.view.addSubview(clonedWebView)
clonedWebView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
clonedWebView.navigationDelegate = self
clonedWebView.load(URLRequest(url: url))
}
func setState(withProfile browserProfile: BrowserProfile, clientPickerDelegate: ClientPickerViewControllerDelegate) {
assert(Thread.current.isMainThread)
guard let tab = self.tab else {
return
}
guard let displayURL = tab.url?.absoluteString, displayURL.characters.count > 0 else {
return
}
let mainQueue = DispatchQueue.main
browserProfile.bookmarks.modelFactory >>== {
$0.isBookmarked(displayURL).uponQueue(mainQueue) {
self.isBookmarked = $0.successValue ?? false
}
}
browserProfile.remoteClientsAndTabs.getClientGUIDs().uponQueue(mainQueue) {
guard let clientGUIDs = $0.successValue else {
return
}
self.hasRemoteClients = !clientGUIDs.isEmpty
let clientPickerController = ClientPickerViewController()
clientPickerController.clientPickerDelegate = clientPickerDelegate
clientPickerController.profile = browserProfile
if let url = tab.url?.absoluteString {
clientPickerController.shareItem = ShareItem(url: url, title: tab.title, favicon: nil)
}
self.clientPicker = UINavigationController(rootViewController: clientPickerController)
}
let result = browserProfile.readingList?.getRecordWithURL(displayURL).successValue!
self.isInReadingList = (result?.url.characters.count ?? 0) > 0
self.ignoreURL = isIgnoredURL(displayURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
screenShot?.removeFromSuperview()
screenShot = nil
}
}
|
mpl-2.0
|
3d9b3ad17f4ec11a23cbf34e127ad870
| 44.074713 | 294 | 0.675252 | 5.50386 | false | false | false | false |
cpuu/OTT
|
BlueCapKit/Peripheral/BCMutableService.swift
|
1
|
2308
|
//
// BCMutableService.swift
// BlueCap
//
// Created by Troy Stribling on 8/9/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import CoreBluetooth
// MARK: - BCMutableService -
public class BCMutableService : NSObject {
static let ioQueue = Queue("us.gnos.blueCap.mutable-service")
private var _characteristics = BCSerialIOArray<BCMutableCharacteristic>(BCMutableService.ioQueue)
internal let profile: BCServiceProfile
internal weak var peripheralManager: BCPeripheralManager?
internal let cbMutableService: CBMutableServiceInjectable
public var UUID: CBUUID {
return self.profile.UUID
}
public var name: String {
return self.profile.name
}
public var characteristics: [BCMutableCharacteristic] {
get {
return self._characteristics.data
}
set {
self._characteristics.data = newValue
let cbCharacteristics = self._characteristics.map { characteristic -> CBCharacteristicInjectable in
characteristic._service = self
return characteristic.cbMutableChracteristic
}
self.cbMutableService.setCharacteristics(cbCharacteristics)
}
}
public convenience init(profile: BCServiceProfile) {
self.init(cbMutableService: CBMutableService(type: profile.UUID, primary: true), profile: profile)
}
public convenience init(UUID: String) {
self.init(profile: BCServiceProfile(UUID: UUID))
}
internal init(cbMutableService: CBMutableServiceInjectable, profile: BCServiceProfile) {
self.cbMutableService = cbMutableService
self.profile = profile
super.init()
}
internal init(cbMutableService: CBMutableServiceInjectable) {
self.cbMutableService = cbMutableService
let uuid = cbMutableService.UUID
if let profile = BCProfileManager.sharedInstance.services[uuid] {
self.profile = profile
} else {
self.profile = BCServiceProfile(UUID: uuid.UUIDString)
}
super.init()
}
public func characteristicsFromProfiles() {
self.characteristics = self.profile.characteristics.map { BCMutableCharacteristic(profile: $0) }
}
}
|
mit
|
23d5018290ceb56897b555dd9f5a8185
| 28.987013 | 111 | 0.67461 | 4.869198 | false | false | false | false |
ello/ello-ios
|
Sources/Views/NewPostsButton.swift
|
1
|
1881
|
////
/// NewPostsButton.swift
//
import SnapKit
class NewPostsButton: Control {
struct Size {
static let top: CGFloat = 45
static let sideMargin: CGFloat = 15
static let innerMargin: CGFloat = 7
static let height: CGFloat = 35
}
private let bg = UIImageView()
private let arrow = UIImageView()
private let label = UILabel()
override var intrinsicContentSize: CGSize {
guard
arrow.intrinsicContentSize.width != UIView.noIntrinsicMetric,
label.intrinsicContentSize.width != UIView.noIntrinsicMetric
else { return super.intrinsicContentSize }
var width = 2 * Size.sideMargin + Size.innerMargin
width += arrow.intrinsicContentSize.width
width += label.intrinsicContentSize.width
return CGSize(width: width, height: Size.height)
}
override func setText() {
arrow.setInterfaceImage(.arrowUp, style: .white)
label.text = InterfaceString.Following.NewPosts
}
override func style() {
label.font = .defaultFont(16)
label.textColor = .white
bg.alpha = 0.8
bg.backgroundColor = .black
bg.clipsToBounds = true
}
override func arrange() {
addSubview(bg)
addSubview(arrow)
addSubview(label)
bg.snp.makeConstraints { make in
make.edges.equalTo(self)
}
arrow.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.leading.equalTo(self.snp.leading).offset(Size.sideMargin)
}
label.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.leading.equalTo(arrow.snp.trailing).offset(Size.innerMargin)
}
}
override func layoutSubviews() {
super.layoutSubviews()
bg.layer.cornerRadius = Size.height / 2
}
}
|
mit
|
03dfe5fbd21f46eaf8b375990bf69d6f
| 25.492958 | 77 | 0.620415 | 4.726131 | false | false | false | false |
Hejki/SwiftExtLib
|
src/StreamReader.swift
|
1
|
3888
|
//
// HejkiSwiftCore
//
// Copyright (c) 2015-2016 Hejki
//
// 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
open class StreamReader {
let encoding: String.Encoding
let chunkSize: Int
var fileHandle: FileHandle!
let buffer: NSMutableData!
let delimData: Data!
var atEof: Bool = false
public init(url: URL, delimiter: String = "\n", encoding: String.Encoding = .utf8, chunkSize: Int = 4096) throws {
self.chunkSize = chunkSize
self.encoding = encoding
do {
let fileHandle = try FileHandle(forReadingFrom: url)
if let delimData = delimiter.data(using: encoding),
let buffer = NSMutableData(capacity: chunkSize) {
self.fileHandle = fileHandle
self.delimData = delimData
self.buffer = buffer
} else {
throw HSCAppError.cannotReadFile(url: url).nsError
}
}
}
deinit {
self.close()
}
/// Return next line, or nil on EOF.
open func nextLine() -> String? {
precondition(fileHandle != nil, "Attempt to read from closed file")
if atEof {
return nil
}
// Read data chunks from file until a line delimiter is found:
var range = buffer.range(of: delimData, options: [], in: NSMakeRange(0, buffer.length))
while range.location == NSNotFound {
let tmpData = fileHandle.readData(ofLength: chunkSize)
if tmpData.count == 0 {
// EOF or read error.
atEof = true
if buffer.length > 0 {
// Buffer contains last line in file (not terminated by delimiter).
let line = String(data: buffer as Data, encoding: encoding)
buffer.length = 0
return line
}
// No more lines.
return nil
}
buffer.append(tmpData)
range = buffer.range(of: delimData, options: [], in: NSMakeRange(0, buffer.length))
}
// Convert complete line (excluding the delimiter) to a string:
let line = String(data: buffer.subdata(with: NSMakeRange(0, range.location)),
encoding: encoding)
// Remove line (and the delimiter) from the buffer:
buffer.replaceBytes(in: NSMakeRange(0, range.location + range.length), withBytes: nil, length: 0)
return line
}
/// Start reading from the beginning of file.
open func rewind() -> Void {
fileHandle.seek(toFileOffset: 0)
buffer.length = 0
atEof = false
}
/// Close the underlying file. No reading must be done after calling this method.
open func close() -> Void {
fileHandle?.closeFile()
fileHandle = nil
}
}
|
mit
|
87a8b216363efcaf530d1120494b6acd
| 35 | 118 | 0.622171 | 4.70133 | false | false | false | false |
LucianoPAlmeida/SwifterSwift
|
Sources/Extensions/UIKit/UILabelExtensions.swift
|
1
|
763
|
//
// UILabelExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 9/23/16.
// Copyright © 2016 SwifterSwift
//
#if os(iOS) || os(tvOS)
import UIKit
// MARK: - Methods
public extension UILabel {
/// SwifterSwift: Initialize a UILabel with text
public convenience init(text: String?) {
self.init()
self.text = text
}
/// SwifterSwift: Required height for a label
public var requiredHeight: CGFloat {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.attributedText = attributedText
label.sizeToFit()
return label.frame.height
}
}
#endif
|
mit
|
a93b19f595d6e60328525822685a358e
| 21.411765 | 109 | 0.712598 | 3.577465 | false | false | false | false |
luizlopezm/ios-Luis-Trucking
|
Pods/Eureka/Source/Rows/ImageRow.swift
|
1
|
7164
|
//
// ImageRow.swift
// Eureka
//
// Created by Martin Barreto on 2/23/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
public struct ImageRowSourceTypes : OptionSetType {
public let rawValue: Int
public var imagePickerControllerSourceTypeRawValue: Int { return self.rawValue >> 1 }
public init(rawValue: Int) { self.rawValue = rawValue }
private init(_ sourceType: UIImagePickerControllerSourceType) { self.init(rawValue: 1 << sourceType.rawValue) }
public static let PhotoLibrary = ImageRowSourceTypes(.PhotoLibrary)
public static let Camera = ImageRowSourceTypes(.Camera)
public static let SavedPhotosAlbum = ImageRowSourceTypes(.SavedPhotosAlbum)
public static let All: ImageRowSourceTypes = [Camera, PhotoLibrary, SavedPhotosAlbum]
}
public enum ImageClearAction {
case No
case Yes(style: UIAlertActionStyle)
}
//MARK: Row
public class _ImageRow<Cell: CellType where Cell: BaseCell, Cell: TypedCellType, Cell.Value == UIImage>: SelectorRow<UIImage, Cell, ImagePickerController> {
public var sourceTypes: ImageRowSourceTypes
public internal(set) var imageURL: NSURL?
public var clearAction = ImageClearAction.Yes(style: .Destructive)
private var _sourceType: UIImagePickerControllerSourceType = .Camera
public required init(tag: String?) {
sourceTypes = .All
super.init(tag: tag)
presentationMode = .PresentModally(controllerProvider: ControllerProvider.Callback { return ImagePickerController() }, completionCallback: { [weak self] vc in
self?.select()
vc.dismissViewControllerAnimated(true, completion: nil)
})
self.displayValueFor = nil
}
// copy over the existing logic from the SelectorRow
private func displayImagePickerController(sourceType: UIImagePickerControllerSourceType) {
if let presentationMode = presentationMode where !isDisabled {
if let controller = presentationMode.createController(){
controller.row = self
controller.sourceType = sourceType
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.presentViewController(controller, row: self, presentingViewController: cell.formViewController()!)
}
else{
_sourceType = sourceType
presentationMode.presentViewController(nil, row: self, presentingViewController: cell.formViewController()!)
}
}
}
public override func customDidSelect() {
guard !isDisabled else {
super.customDidSelect()
return
}
deselect()
var availableSources: ImageRowSourceTypes = []
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
availableSources.insert(.PhotoLibrary)
}
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
availableSources.insert(.Camera)
}
if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
availableSources.insert(.SavedPhotosAlbum)
}
sourceTypes.intersectInPlace(availableSources)
if sourceTypes.isEmpty {
super.customDidSelect()
return
}
// now that we know the number of actions aren't empty
let sourceActionSheet = UIAlertController(title: nil, message: selectorTitle, preferredStyle: .ActionSheet)
guard let tableView = cell.formViewController()?.tableView else { fatalError() }
if let popView = sourceActionSheet.popoverPresentationController {
popView.sourceView = tableView
popView.sourceRect = tableView.convertRect(cell.accessoryView?.frame ?? cell.contentView.frame, fromView: cell)
}
if sourceTypes.contains(.Camera) {
let cameraOption = UIAlertAction(title: NSLocalizedString("Take Photo", comment: ""), style: .Default, handler: { [weak self] _ in
self?.displayImagePickerController(.Camera)
})
sourceActionSheet.addAction(cameraOption)
}
if sourceTypes.contains(.PhotoLibrary) {
let photoLibraryOption = UIAlertAction(title: NSLocalizedString("Photo Library", comment: ""), style: .Default, handler: { [weak self] _ in
self?.displayImagePickerController(.PhotoLibrary)
})
sourceActionSheet.addAction(photoLibraryOption)
}
if sourceTypes.contains(.SavedPhotosAlbum) {
let savedPhotosOption = UIAlertAction(title: NSLocalizedString("Saved Photos", comment: ""), style: .Default, handler: { [weak self] _ in
self?.displayImagePickerController(.SavedPhotosAlbum)
})
sourceActionSheet.addAction(savedPhotosOption)
}
switch clearAction {
case .Yes(let style):
if let _ = value {
let clearPhotoOption = UIAlertAction(title: NSLocalizedString("Clear Photo", comment: ""), style: style, handler: { [weak self] _ in
self?.value = nil
self?.updateCell()
})
sourceActionSheet.addAction(clearPhotoOption)
}
case .No:
break
}
// check if we have only one source type given
if sourceActionSheet.actions.count == 1 {
if let imagePickerSourceType = UIImagePickerControllerSourceType(rawValue: sourceTypes.imagePickerControllerSourceTypeRawValue) {
displayImagePickerController(imagePickerSourceType)
}
} else {
let cancelOption = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel, handler:nil)
sourceActionSheet.addAction(cancelOption)
if let presentingViewController = cell.formViewController() {
presentingViewController.presentViewController(sourceActionSheet, animated: true, completion:nil)
}
}
}
public override func prepareForSegue(segue: UIStoryboardSegue) {
super.prepareForSegue(segue)
guard let rowVC = segue.destinationViewController as? ImagePickerController else {
return
}
rowVC.sourceType = _sourceType
}
public override func customUpdateCell() {
super.customUpdateCell()
cell.accessoryType = .None
if let image = self.value {
let imageView = UIImageView(frame: CGRectMake(0, 0, 44, 44))
imageView.contentMode = .ScaleAspectFill
imageView.image = image
imageView.clipsToBounds = true
cell.accessoryView = imageView
}
else{
cell.accessoryView = nil
}
}
}
/// A selector row where the user can pick an image
public final class ImageRow : _ImageRow<PushSelectorCell<UIImage>>, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
|
mit
|
979f49dfb3b87fd1a31a3da1742c1996
| 39.241573 | 166 | 0.642747 | 5.871311 | false | false | false | false |
everald/JetPack
|
Sources/Measures/Length.swift
|
2
|
3613
|
private let metersPerCentimeter = 0.01
private let metersPerFoot = 0.3048
private let metersPerInch = 0.0254
private let metersPerKilometer = 1000.0
private let metersPerMile = 1609.344
private let centimetersPerMeter = 1.0 / metersPerCentimeter
private let feetPerMeter = 1.0 / metersPerFoot
private let inchesPerMeter = 1.0 / metersPerInch
private let kilometersPerMeter = 1.0 / metersPerKilometer
private let milesPerMeter = 1.0 / metersPerMile
public struct Length: Measure {
public static let name = MeasuresStrings.Measure.length
public static let rawUnit = LengthUnit.meters
public var rawValue: Double
public init(_ value: Double, unit: LengthUnit) {
precondition(!value.isNaN, "Value must not be NaN.")
switch unit {
case .centimeters: rawValue = value * metersPerCentimeter
case .feet: rawValue = value * metersPerFoot
case .inches: rawValue = value * metersPerInch
case .kilometers: rawValue = value * metersPerKilometer
case .meters: rawValue = value
case .miles: rawValue = value * metersPerMile
}
}
public init(centimeters: Double) {
self.init(centimeters, unit: .centimeters)
}
public init(feet: Double) {
self.init(feet, unit: .feet)
}
public init(inches: Double) {
self.init(inches, unit: .inches)
}
public init(kilometers: Double) {
self.init(kilometers, unit: .kilometers)
}
public init(meters: Double) {
self.init(meters, unit: .meters)
}
public init(miles: Double) {
self.init(miles, unit: .miles)
}
public init(rawValue: Double) {
self.rawValue = rawValue
}
public var centimeters: Double {
return meters * centimetersPerMeter
}
public var feet: Double {
return meters * feetPerMeter
}
public var inches: Double {
return meters * inchesPerMeter
}
public var kilometers: Double {
return meters * kilometersPerMeter
}
public var meters: Double {
return rawValue
}
public var miles: Double {
return meters * milesPerMeter
}
public func valueInUnit(_ unit: LengthUnit) -> Double {
switch unit {
case .centimeters: return centimeters
case .feet: return feet
case .inches: return inches
case .kilometers: return kilometers
case .meters: return meters
case .miles: return miles
}
}
}
public enum LengthUnit: Unit {
case centimeters
case feet
case inches
case kilometers
case meters
case miles
}
extension LengthUnit {
public var abbreviation: String {
switch self {
case .centimeters: return MeasuresStrings.Unit.Centimeter.abbreviation
case .feet: return MeasuresStrings.Unit.Foot.abbreviation
case .inches: return MeasuresStrings.Unit.Inch.abbreviation
case .kilometers: return MeasuresStrings.Unit.Kilometer.abbreviation
case .meters: return MeasuresStrings.Unit.Meter.abbreviation
case .miles: return MeasuresStrings.Unit.Mile.abbreviation
}
}
public var name: PluralizedString {
switch self {
case .centimeters: return MeasuresStrings.Unit.Centimeter.name
case .feet: return MeasuresStrings.Unit.Foot.name
case .inches: return MeasuresStrings.Unit.Inch.name
case .kilometers: return MeasuresStrings.Unit.Kilometer.name
case .meters: return MeasuresStrings.Unit.Meter.name
case .miles: return MeasuresStrings.Unit.Mile.name
}
}
public var symbol: String? {
switch self {
case .centimeters: return nil
case .feet: return "′"
case .inches: return "″"
case .kilometers: return nil
case .meters: return nil
case .miles: return nil
}
}
}
|
mit
|
9e201b534d714285e5da456e1ac3ddcf
| 21.416149 | 72 | 0.705181 | 3.524414 | false | false | false | false |
stefanoa/Spectrogram
|
Spectogram/SpectogramContainerView.swift
|
1
|
4075
|
//
// SpectogramContainerView.swift
// Spectogram
//
// Created by Stefano on 30/07/2017.
// Copyright © 2017 SA. All rights reserved.
//
import UIKit
protocol SpectogramDataSource {
func numberOfSlices() -> Int
func sliceAtIndex(_ index:Int)->[Float]
}
protocol SpectogramDelegate {
func selectedSliceAtIndex(_ index:Int, slice:[Float])
}
class SpectogramContainerView:UIView{
var dataSource:SpectogramDataSource!
var delegate:SpectogramDelegate?
var pixelPerSlice:CGFloat = 4
var pixelDeltaNote:CGFloat = 10
let cutOff = 0
var rate:Float = 41100
var longPressRecognizer:UILongPressGestureRecognizer!
func longPressed(recognizer:UILongPressGestureRecognizer){
if let delegate = delegate , recognizer.state == .began{
let position = recognizer.location(in: recognizer.view)
let index = Int(position.x/pixelPerSlice)
if index < dataSource.numberOfSlices(){
let slice = dataSource.sliceAtIndex(index)
delegate.selectedSliceAtIndex(index, slice: slice)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(recognizer:)))
longPressRecognizer.minimumPressDuration = 0.5
self.addGestureRecognizer(longPressRecognizer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(recognizer:)))
longPressRecognizer.minimumPressDuration = 0.5
self.addGestureRecognizer(longPressRecognizer)
}
override func draw(_ rect: CGRect) {
if dataSource.numberOfSlices()>0 {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
let width = pixelPerSlice
let yStart = yAtIndex(index: cutOff)
for index in 0...dataSource.numberOfSlices()-1{
let slice = dataSource.sliceAtIndex(index)
var y0:CGFloat = yStart
for j in cutOff...slice.count-1{
let v = slice[j]
let y = yAtIndex(index: j)
let rect = CGRect(x: CGFloat(index)*width, y:y0-yStart, width: width, height: y-y0)
//let color = UIColor(red: 1-CGFloat(v),green:CGFloat(v),blue:0.0, alpha: 1.0)
let color = UIColor(white: 1-CGFloat(v), alpha: 1.0)
color.setFill()
ctx.fill(rect)
y0 = y
}
}
/*
let slice = dataSource.sliceAtIndex(0)
let sliceSize = Float(slice.count)
var ci:Float = 55
UIColor.darkGray.setStroke()
let size = getSize()
for _ in 1...7 {
let kf = ci*sliceSize/rate
let k = Int(kf)
let y = yAtIndex(index: k)-yStart
let line = UIBezierPath()
line.move(to: CGPoint(x: 0, y: y))
line.addLine(to: CGPoint(x: size.width, y: y))
line.stroke()
ci*=2
}*/
}
}
func getSize()-> CGSize{
if dataSource.numberOfSlices() > 0{
let slice = dataSource.sliceAtIndex(0)
let n = slice.count
let numberOfSlices = dataSource.numberOfSlices()
return CGSize(width:pixelPerSlice*CGFloat(numberOfSlices), height: yAtIndex(index: n-1))
}else{
return CGSize.zero
}
}
func yAtIndex(index:Int)->CGFloat{
let indexF = CGFloat(index)
return round((log(indexF+1)/log(CGFloat(Spectogram.noteSeparation)))*pixelDeltaNote)
}
func reloadData(){
let size:CGSize = getSize()
self.frame.size = size
self.setNeedsDisplay()
}
}
|
mit
|
160f5c45c57c665076edaf7f130ef91e
| 34.12069 | 117 | 0.572165 | 4.666667 | false | false | false | false |
arbitur/Func
|
source/UI/RadialGradientView.swift
|
1
|
1940
|
//
// RadialGradientView.swift
// Pods
//
// Created by Philip Fryklund on 21/Feb/17.
//
//
import UIKit
public class RadialGradientView: UIView {
public override class var layerClass: AnyClass { return RadialGradientLayer.self }
private var gradientLayer: RadialGradientLayer { return self.layer as! RadialGradientLayer }
public var colorComponents: [(color: UIColor, location: CGFloat)]? {
get { return gradientLayer.colorComponents }
set { gradientLayer.colorComponents = newValue }
}
}
open class RadialGradientLayer: CALayer {
public var colorComponents: [(color: UIColor, location: CGFloat)]? {
didSet { self.setNeedsDisplay() }
}
open override func animation(forKey key: String) -> CAAnimation? {
switch key {
case "frame": fallthrough
case "bounds": return nil
default: return super.animation(forKey: key)
}
}
public override init() {
super.init()
self.needsDisplayOnBoundsChange = true
}
public override init(layer: Any) {
super.init(layer: layer)
self.needsDisplayOnBoundsChange = true
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.needsDisplayOnBoundsChange = true
}
open override func draw(in ctx: CGContext) {
guard let components = colorComponents, !components.isEmpty else {
return super.draw(in: ctx)
}
let colors = components.map { $0.color.cgColor } as CFArray
let locations = components.map { $0.location }
ctx.saveGState()
let colorspace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: colorspace, colors: colors, locations: locations)!
let center = self.bounds.center
let radius = center.magnitude//Math.hypotenusa(point: center) //TODO: Check still works as intended
ctx.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: radius, options: .drawsAfterEndLocation)
}
}
|
mit
|
6ef01f1ce0d80a4ccbfd0890f1a8dce6
| 18.4 | 142 | 0.715979 | 3.97541 | false | false | false | false |
WWITDC/Underchess
|
underchess/UCiOSArenaViewController.swift
|
1
|
2019
|
//
// UCiOSArenaViewController.swift
// Underchess
//
// Created by Apollonian on 6/16/16.
// Copyright © 2016 WWITDC. All rights reserved.
//
import UIKit
class UCiOSArenaViewController: UCArenaViewController, UCArenaViewControllerDelegate {
var base: AnyObject?
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
base = UIApplication.shared.keyWindow
}
func endGame() {
let dialog = LLDialog()
dialog.title = currentPlayer ? ("Player Green Won") : ("Player Red Won")
dialog.message = "Congratulations. Do you want to play again? \n P.S. If you choose `No`, you can always shake your device and play again."
dialog.setPositiveButton(withTitle: "Yes", target: self, action: #selector(startNew))
dialog.setNegativeButton(withTitle: "No")
dialog.show()
newUCArenaViewController = UCiOSArenaViewController()
}
override func get(error: UCUserInputError) {
super.get(error: error)
let dialog = LLDialog()
dialog.title = "Permission denied"
dialog.message = error.description
dialog.setPositiveButton(withTitle: "OK")
dialog.setNegativeButton()
dialog.show()
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
super.motionEnded(motion, with: event)
if motion == UIEventSubtype.motionShake{
switch gamingStatus {
case .notStarted:
currentPlayer = !currentPlayer
case .ended:
startNew()
case .playing:
let dialog = LLDialog()
dialog.title = "Restart the game?"
dialog.message = "The game is not finished. Do you want to restart the game?"
dialog.setPositiveButton(withTitle: "YES", target: self, action: #selector(startNew))
dialog.setNegativeButton(withTitle: "No")
dialog.show()
}
}
}
}
|
unlicense
|
4594e4e33ecbddf2ed913832b71a2fa9
| 33.20339 | 147 | 0.616452 | 4.514541 | false | false | false | false |
drewag/Swiftlier
|
Sources/Swiftlier/Model/Observable/ObservableDictionary.swift
|
1
|
3850
|
//
// ObservableDictionary.swift
// Swiftlier
//
// Created by Andrew J Wagner on 8/2/16.
// Copyright © 2016 Drewag LLC. All rights reserved.
//
public final class ObservableDictionary<Key: Hashable, Value> {
public typealias DidChange = (_ oldValue: Value, _ newValue: Value, _ at: Key) -> ()
public typealias DidInsert = (Value, _ at: Key) -> ()
public typealias DidRemove = (Value, _ at: Key) -> ()
public typealias DidRemoveAll = (_ oldValues: [Key:Value]) -> ()
public typealias ObservationHandlers = (changed: DidChange?, insert: DidInsert?, remove: DidRemove?, removeAll: DidRemoveAll?)
fileprivate var observers: [(observer: WeakWrapper<AnyObject>, handlers: [ObservationHandlers])] = []
private var onHasObserversChanged: ((Bool) -> ())?
public private(set) var values: [Key:Value]
public init(_ values: [Key:Value], onHasObserversChanged: ((Bool) -> ())? = nil) {
self.values = values
self.onHasObserversChanged = onHasObserversChanged
}
public func add(
observer: AnyObject,
onDidChange: DidChange? = nil,
onDidInsert: DidInsert? = nil,
onDidRemove: DidRemove? = nil,
onDidRemoveAll: DidRemoveAll? = nil
)
{
guard onDidInsert != nil || onDidRemove != nil || onDidRemoveAll != nil else {
return
}
let handlers: ObservationHandlers = (changed: onDidChange, insert: onDidInsert, remove: onDidRemove, removeAll: onDidRemoveAll)
if let index = self.index(ofObserver: observer) {
self.observers[index].handlers.append(handlers)
}
else {
let oldCount = self.observers.count
self.observers.append((observer: WeakWrapper(observer), handlers: [handlers]))
if oldCount == 0 {
self.onHasObserversChanged?(true)
}
}
}
public func remove(observer: AnyObject) {
if let index = self.index(ofObserver: observer) {
self.observers.remove(at: index)
if self.observers.count == 0 {
self.onHasObserversChanged?(false)
}
}
}
public subscript(key: Key) -> Value? {
get {
return self.values[key]
}
set {
if let oldValue = self.values[key] {
self.values[key] = newValue
if let newValue = newValue {
self.executeWithAllHandlers { handler in
handler.changed?(oldValue, newValue, key)
}
}
else {
self.executeWithAllHandlers { handler in
handler.remove?(oldValue, key)
}
}
}
else {
self.values[key] = newValue
if let newValue = newValue {
self.executeWithAllHandlers { handler in
handler.insert?(newValue, key)
}
}
}
}
}
public func removeAll() {
let oldValues = self.values
self.values.removeAll()
self.executeWithAllHandlers { handler in
handler.removeAll?(oldValues)
}
}
}
private extension ObservableDictionary {
func index(ofObserver observer: AnyObject) -> Int? {
var index: Int = 0
for (possibleObserver, _) in self.observers {
if possibleObserver.value === observer {
return index
}
index += 1
}
return nil
}
func executeWithAllHandlers(callback: (_ handlers: ObservationHandlers) -> ()) {
for (_, handlers) in self.observers {
for handler in handlers {
callback(handler)
}
}
}
}
|
mit
|
6434a2481e58f04d9fac963bb80f1e52
| 31.897436 | 135 | 0.547675 | 4.787313 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift
|
26
|
8716
|
//
// RxCocoaObjCRuntimeError+Extensions.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 10/9/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux)
import RxCocoaRuntime
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
/// RxCocoa ObjC runtime interception mechanism.
public enum RxCocoaInterceptionMechanism {
/// Unknown message interception mechanism.
case unknown
/// Key value observing interception mechanism.
case kvo
}
/// RxCocoa ObjC runtime modification errors.
public enum RxCocoaObjCRuntimeError
: Swift.Error
, CustomDebugStringConvertible {
/// Unknown error has occurred.
case unknown(target: AnyObject)
/**
If the object is reporting a different class then it's real class, that means that there is probably
already some interception mechanism in place or something weird is happening.
The most common case when this would happen is when using a combination of KVO (`observe`) and `sentMessage`.
This error is easily resolved by just using `sentMessage` observing before `observe`.
The reason why the other way around could create issues is because KVO will unregister it's interceptor
class and restore original class. Unfortunately that will happen no matter was there another interceptor
subclass registered in hierarchy or not.
Failure scenario:
* KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`)
* `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`)
* then unobserving with KVO will restore class to be `OriginalClass` -> failure point (possibly a bug in KVO)
The reason why changing order of observing works is because any interception method on unregistration
should return object's original real class (if that doesn't happen then it's really easy to argue that's a bug
in that interception mechanism).
This library won't remove registered interceptor even if there aren't any observers left because
it's highly unlikely it would have any benefit in real world use cases, and it's even more
dangerous.
*/
case objectMessagesAlreadyBeingIntercepted(target: AnyObject, interceptionMechanism: RxCocoaInterceptionMechanism)
/// Trying to observe messages for selector that isn't implemented.
case selectorNotImplemented(target: AnyObject)
/// Core Foundation classes are usually toll free bridged. Those classes crash the program in case
/// `object_setClass` is performed on them.
///
/// There is a possibility to just swizzle methods on original object, but since those won't be usual use
/// cases for this library, then an error will just be reported for now.
case cantInterceptCoreFoundationTollFreeBridgedObjects(target: AnyObject)
/// Two libraries have simultaneously tried to modify ObjC runtime and that was detected. This can only
/// happen in scenarios where multiple interception libraries are used.
///
/// To synchronize other libraries intercepting messages for an object, use `synchronized` on target object and
/// it's meta-class.
case threadingCollisionWithOtherInterceptionMechanism(target: AnyObject)
/// For some reason saving original method implementation under RX namespace failed.
case savingOriginalForwardingMethodFailed(target: AnyObject)
/// Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.
case replacingMethodWithForwardingImplementation(target: AnyObject)
/// Attempt to intercept one of the performance sensitive methods:
/// * class
/// * respondsToSelector:
/// * methodSignatureForSelector:
/// * forwardingTargetForSelector:
case observingPerformanceSensitiveMessages(target: AnyObject)
/// Message implementation has unsupported return type (for example large struct). The reason why this is a error
/// is because in some cases intercepting sent messages requires replacing implementation with `_objc_msgForward_stret`
/// instead of `_objc_msgForward`.
///
/// The unsupported cases should be fairly uncommon.
case observingMessagesWithUnsupportedReturnType(target: AnyObject)
}
extension RxCocoaObjCRuntimeError {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case let .unknown(target):
return "Unknown error occurred.\nTarget: `\(target)`"
case let .objectMessagesAlreadyBeingIntercepted(target, interceptionMechanism):
let interceptionMechanismDescription = interceptionMechanism == .kvo ? "KVO" : "other interception mechanism"
return "Collision between RxCocoa interception mechanism and \(interceptionMechanismDescription)."
+ " To resolve this conflict please use this interception mechanism first.\nTarget: \(target)"
case let .selectorNotImplemented(target):
return "Trying to observe messages for selector that isn't implemented.\nTarget: \(target)"
case let .cantInterceptCoreFoundationTollFreeBridgedObjects(target):
return "Interception of messages sent to Core Foundation isn't supported.\nTarget: \(target)"
case let .threadingCollisionWithOtherInterceptionMechanism(target):
return "Detected a conflict while modifying ObjC runtime.\nTarget: \(target)"
case let .savingOriginalForwardingMethodFailed(target):
return "Saving original method implementation failed.\nTarget: \(target)"
case let .replacingMethodWithForwardingImplementation(target):
return "Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.\nTarget: \(target)"
case let .observingPerformanceSensitiveMessages(target):
return "Attempt to intercept one of the performance sensitive methods. \nTarget: \(target)"
case let .observingMessagesWithUnsupportedReturnType(target):
return "Attempt to intercept a method with unsupported return type. \nTarget: \(target)"
}
}
}
// MARK: Conversions `NSError` > `RxCocoaObjCRuntimeError`
extension Error {
func rxCocoaErrorForTarget(_ target: AnyObject) -> RxCocoaObjCRuntimeError {
let error = self as NSError
if error.domain == RXObjCRuntimeErrorDomain {
let errorCode = RXObjCRuntimeError(rawValue: error.code) ?? .unknown
switch errorCode {
case .unknown:
return .unknown(target: target)
case .objectMessagesAlreadyBeingIntercepted:
let isKVO = (error.userInfo[RXObjCRuntimeErrorIsKVOKey] as? NSNumber)?.boolValue ?? false
return .objectMessagesAlreadyBeingIntercepted(target: target, interceptionMechanism: isKVO ? .kvo : .unknown)
case .selectorNotImplemented:
return .selectorNotImplemented(target: target)
case .cantInterceptCoreFoundationTollFreeBridgedObjects:
return .cantInterceptCoreFoundationTollFreeBridgedObjects(target: target)
case .threadingCollisionWithOtherInterceptionMechanism:
return .threadingCollisionWithOtherInterceptionMechanism(target: target)
case .savingOriginalForwardingMethodFailed:
return .savingOriginalForwardingMethodFailed(target: target)
case .replacingMethodWithForwardingImplementation:
return .replacingMethodWithForwardingImplementation(target: target)
case .observingPerformanceSensitiveMessages:
return .observingPerformanceSensitiveMessages(target: target)
case .observingMessagesWithUnsupportedReturnType:
return .observingMessagesWithUnsupportedReturnType(target: target)
@unknown default:
fatalError("Unhandled Objective C Runtime Error")
}
}
return RxCocoaObjCRuntimeError.unknown(target: target)
}
}
#endif
|
mit
|
a408c1080ce49f7365c486de800454f3
| 53.130435 | 156 | 0.680092 | 5.651751 | false | false | false | false |
hjw6160602/JourneyNotes
|
Pods/Himotoki/Sources/Extractor.swift
|
2
|
3717
|
//
// Extractor.swift
// Himotoki
//
// Created by Syo Ikeda on 5/2/15.
// Copyright (c) 2015 Syo Ikeda. All rights reserved.
//
import class Foundation.NSNull
public struct Extractor {
public let rawValue: Any
private let isDictionary: Bool
internal init(_ rawValue: Any) {
self.rawValue = rawValue
self.isDictionary = rawValue is [String: Any]
}
// If we use `rawValue` here, that would conflict with `let rawValue: Any`
// on Linux. This naming is avoiding the weird case.
private func _rawValue(_ keyPath: KeyPath) throws -> Any? {
guard isDictionary else {
throw typeMismatch("Dictionary", actual: rawValue, keyPath: keyPath)
}
let components = ArraySlice(keyPath.components)
return valueFor(components, rawValue)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func value<T: Decodable>(_ keyPath: KeyPath) throws -> T {
guard let value: T = try valueOptional(keyPath) else {
throw DecodeError.missingKeyPath(keyPath)
}
return value
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func valueOptional<T: Decodable>(_ keyPath: KeyPath) throws -> T? {
guard let rawValue = try _rawValue(keyPath) else {
return nil
}
do {
return try T.decodeValue(rawValue)
} catch let DecodeError.missingKeyPath(missing) {
throw DecodeError.missingKeyPath(keyPath + missing)
} catch let DecodeError.typeMismatch(expected, actual, mismatched) {
throw DecodeError.typeMismatch(expected: expected, actual: actual, keyPath: keyPath + mismatched)
}
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func array<T: Decodable>(_ keyPath: KeyPath) throws -> [T] {
guard let array: [T] = try arrayOptional(keyPath) else {
throw DecodeError.missingKeyPath(keyPath)
}
return array
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func arrayOptional<T: Decodable>(_ keyPath: KeyPath) throws -> [T]? {
return try _rawValue(keyPath).map([T].decode)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func dictionary<T: Decodable>(_ keyPath: KeyPath) throws -> [String: T] {
guard let dictionary: [String: T] = try dictionaryOptional(keyPath) else {
throw DecodeError.missingKeyPath(keyPath)
}
return dictionary
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func dictionaryOptional<T: Decodable>(_ keyPath: KeyPath) throws -> [String: T]? {
return try _rawValue(keyPath).map([String: T].decode)
}
}
extension Extractor: Decodable {
public static func decode(_ e: Extractor) throws -> Extractor {
return e
}
}
extension Extractor: CustomStringConvertible {
public var description: String {
return "Extractor(\(rawValue))"
}
}
// Implement it as a tail recursive function.
//
// `ArraySlice` is used for performance optimization.
// See https://gist.github.com/norio-nomura/d9ec7212f2cfde3fb662.
private func valueFor<C: Collection>(_ keyPathComponents: C, _ JSON: Any) -> Any? where C.Iterator.Element == String, C.SubSequence == C {
guard
let first = keyPathComponents.first,
let nativeDict = JSON as? [String: Any],
case let nested? = nativeDict[first],
!(nested is NSNull) else // swiftlint:disable:this opening_brace
{
return nil
}
if keyPathComponents.count == 1 {
return nested
}
let tail = keyPathComponents.dropFirst()
return valueFor(tail, nested)
}
|
mit
|
a89cac1d58fc0611843afc88cea39cb7
| 31.043103 | 138 | 0.644606 | 4.472924 | false | false | false | false |
RenanMatias/MeLevaRio
|
MeLevaRio/MeLevaRioRequest.swift
|
1
|
2305
|
//
// MeLevaRioRequest.swift
// MeLevaRio
//
// Created by Renan Matias on 27/06/17.
// Copyright © 2017 Renan Matias. All rights reserved.
//
import Foundation
import ObjectMapper
public typealias JSONDictionary = [String: Any]
typealias ModelRemoteServiceCompletion = (_ objects: [lugares]?, _ error: Error?) -> Void
class LugaresRequest {
required init() { }
func downloadObjects(_ completion: @escaping ModelRemoteServiceCompletion) {
DispatchQueue.global().async {
// REQUEST
self.getJSON({ lugares in
completion(lugares, nil)
})
}
}
func mockJSON() -> [lugares] {
let path = Bundle.main.path(forResource: "me-leva-rio-export", ofType: "json")
let data = try! Data(contentsOf: URL(fileURLWithPath: path!))
let jsonResult = try! JSONSerialization.jsonObject(with: data, options: []) as! [JSONDictionary]
let lugaresResult = jsonResult.flatMap { lugares(map: Map(mappingType: .fromJSON, JSON: $0)) }
return lugaresResult
}
func getJSON(_ completion: @escaping (_ lugares: [lugares]) -> Void) {
let url = URL(string: "https://me-leva-rio.firebaseio.com/.json")
DispatchQueue.global().async {
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
if let data = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: [])
if let jsonArray = jsonResult as? [JSONDictionary] {
let lugaresResult = jsonArray.flatMap { lugares(map: Map(mappingType: .fromJSON, JSON: $0)) }
completion(lugaresResult)
}
} catch { print("Erro no retorno") }
}
} else { return () }
}
task.resume()
}
}
}
|
mit
|
0d9c23752a055f59bd3862abdefe0736
| 31.914286 | 125 | 0.486111 | 5.086093 | false | false | false | false |
vermont42/Conjugar
|
Conjugar/ConjugationCell.swift
|
1
|
1937
|
//
// ConjugationCell.swift
// Conjugar
//
// Created by Joshua Adams on 5/7/17.
// Copyright © 2017 Josh Adams. All rights reserved.
//
import UIKit
class ConjugationCell: UITableViewCell {
static let identifier = "ConjugationCell"
@UsesAutoLayout
var conjugation: UILabel = {
let label = UILabel()
label.textColor = Colors.yellow
label.font = Fonts.smallCell
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
return label
}()
required init?(coder aDecoder: NSCoder) {
NSCoder.fatalErrorNotImplemented()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ConjugationCell.tap(_:))))
selectionStyle = .none
backgroundColor = Colors.black
addSubview(conjugation)
NSLayoutConstraint.activate([
conjugation.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Layout.defaultSpacing),
conjugation.trailingAnchor.constraint(equalTo: trailingAnchor, constant: Layout.defaultSpacing * -1.0),
conjugation.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
func configure(tense: Tense, personNumber: PersonNumber, conjugation: String) {
var conjugation = conjugation
if conjugation == Conjugator.defective {
self.conjugation.text = ""
} else {
if tense == .imperativoPositivo || tense == .imperativoNegativo {
conjugation = "¡" + conjugation + "!"
} else {
conjugation = personNumber.pronoun + " " + conjugation
}
self.conjugation.attributedText = conjugation.conjugatedString
self.conjugation.setAccessibilityLabelInSpanish(conjugation)
}
}
@objc func tap(_ sender: UITapGestureRecognizer) {
Utterer.utter(conjugation.attributedText?.string ?? conjugation.text ?? "")
}
}
|
agpl-3.0
|
0d7bb4065ce8302e6a7f26e3553dc5db
| 31.25 | 109 | 0.713178 | 4.731051 | false | false | false | false |
turekj/ReactiveTODO
|
ReactiveTODOTests/Classes/Models/TODONoteSpec.swift
|
1
|
1412
|
@testable import ReactiveTODOFramework
import Foundation
import Nimble
import Quick
class TODONoteSpec: QuickSpec {
override func spec() {
describe("TODONote") {
it("Should have guid property") {
let sut = TODONote()
expect(sut.guid).to(equal(""))
}
it("Should have note property") {
let sut = TODONote()
expect(sut.note).to(equal(""))
}
it("Should have date property") {
let sut = TODONote()
expect(sut.date).to(equal(NSDate(timeIntervalSince1970: 1)))
}
it("Should have priority property") {
let urgentNote = TODONote()
urgentNote.priority = .Urgent
let notImportantNote = TODONote()
notImportantNote.priority = .Low
expect(urgentNote.priority).to(equal(Priority.Urgent))
expect(notImportantNote.priority).to(equal(Priority.Low))
}
it("Should have primary key set") {
let primaryKey = TODONote.primaryKey()
expect(primaryKey).toNot(beNil())
expect(primaryKey).to(equal("guid"))
}
}
}
}
|
mit
|
6e3935a1dfd052ecf502e4ef59a0384c
| 29.042553 | 76 | 0.469547 | 5.670683 | false | false | false | false |
gs01md/ColorfulWoodUIUser
|
TestUI/Pods/LoginKit/LoginKit/RegistrationController.swift
|
1
|
3905
|
/**
The RegistrationController displays a configurable screen for users to register
for a new account that is used by the rest of the library.
*/
public class RegistrationController: UIViewController {
var newUsername: UITextField = UITextField()
var newPassword: UITextField = UITextField()
var newPasswordConfirm: UITextField = UITextField()
var centerCoords: CGFloat {
return (self.view.frame.size.width/2) - (235/2)
}
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Appearance.backgroundColor
self.newUsername = buildField("Username", top: 50)
self.newPassword = buildField("Password", top: 120)
self.newPasswordConfirm = buildField("Password Confirmation", top: 190)
self.view.addSubview(self.newUsername)
self.view.addSubview(self.newPassword)
self.view.addSubview(self.newPasswordConfirm)
let register = UIButton(type: UIButtonType.System)
register.setTitle("Register", forState: UIControlState.Normal)
register.titleLabel?.font = UIFont.boldSystemFontOfSize(17)
register.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
register.clipsToBounds = true
register.layer.cornerRadius = 5
register.sizeToFit()
register.layer.borderColor = Appearance.buttonBorderColor.CGColor
register.layer.borderWidth = 1.0
register.backgroundColor = Appearance.buttonColor
register.addTarget(self,
action: #selector(RegistrationController.performRegistration(_:)),
forControlEvents: UIControlEvents.TouchUpInside)
register.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin]
register.frame = CGRectMake(centerCoords, self.newPasswordConfirm.frame.maxY + 20, 235, 50)
self.view.addSubview(register)
}
override public func shouldAutorotate() -> Bool {
return true
}
override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
func buildField(name: String, top: CGFloat) -> UITextField {
let field = UITextField()
field.sizeToFit()
let placeholderText = name
let attrs = [NSForegroundColorAttributeName: UIColor.grayColor()]
let placeholderString = NSMutableAttributedString(string: placeholderText, attributes: attrs)
field.attributedPlaceholder = placeholderString
let cord: CGFloat = 235
let width: CGFloat = 50
field.frame = CGRectMake(centerCoords, top, cord, width)
field.borderStyle = UITextBorderStyle.RoundedRect
// Enhancements
field.autocorrectionType = UITextAutocorrectionType.No
field.autocapitalizationType = UITextAutocapitalizationType.None
field.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin]
return field
}
func performRegistration(sender: UIButton!) {
if let username = self.newUsername.text, let password = self.newPassword.text
where username.characters.count > 0 && password.characters.count > 0 {
//TODO:
// * Send username and password to server
// * Check for password that is not the same (validation)
// * Check for password length
// * Check for password strength
} else {
let alert = UIAlertController(title: nil, message: "Please enter a username and password.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
|
mit
|
3727a6834676b0d0be89de08ce4c01f9
| 39.677083 | 127 | 0.660691 | 5.578571 | false | false | false | false |
jessesquires/Cartography
|
CartographyTests/PointSpec.swift
|
15
|
2056
|
import Cartography
import Nimble
import Quick
class PointSpec: QuickSpec {
override func spec() {
var superview: View!
var view: View!
beforeEach {
superview = TestView(frame: CGRectMake(0, 0, 400, 400))
view = TestView(frame: CGRectZero)
superview.addSubview(view)
constrain(view) { view in
view.width == 200
view.height == 200
}
}
describe("LayoutProxy.center") {
it("should support relative equalities") {
layout(view) { view in
view.center == view.superview!.center
}
expect(view.frame).to(equal(CGRectMake(100, 100, 200, 200)))
}
it("should support relative inequalities") {
layout(view) { view in
view.center <= view.superview!.center
view.center >= view.superview!.center
}
expect(view.frame).to(equal(CGRectMake(100, 100, 200, 200)))
}
}
#if os(iOS)
describe("on iOS only") {
beforeEach {
view.layoutMargins = UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)
}
describe("LayoutProxy.centerWithinMargins") {
it("should support relative equalities") {
layout(view) { view in
view.centerWithinMargins == view.superview!.center
}
expect(view.frame).to(equal(CGRectMake(110, 110, 200, 200)))
}
it("should support relative inequalities") {
layout(view) { view in
view.centerWithinMargins <= view.superview!.center
view.centerWithinMargins >= view.superview!.center
}
expect(view.frame).to(equal(CGRectMake(110, 110, 200, 200)))
}
}
}
#endif
}
}
|
mit
|
561fcd710d7b3d9747a150ff9e6e9242
| 28.797101 | 91 | 0.484436 | 5.165829 | false | false | false | false |
frootloops/swift
|
test/ClangImporter/macros_redef.swift
|
5
|
1736
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -import-objc-header %S/Inputs/macros_redef.h -emit-silgen %s | %FileCheck -check-prefix=NEGATIVE %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -import-objc-header %S/Inputs/macros_redef.h -DCONFLICT -typecheck -verify %s
// NEGATIVE-NOT: OLDTAG
import MacrosRedefA
import MacrosRedefB
import MacrosDeliberateRedefA
import MacrosDeliberateRedefB
#if CONFLICT
import MacrosRedefWithSubmodules
import MacrosRedefWithSubmodules.TheSubmodule
import MacrosRedefWithParallelSubmodules.A
import MacrosRedefWithParallelSubmodules.B
#else
import MacrosRedefWithSubmodules.TheSubmodule
import MacrosRedefWithParallelSubmodules.A
#endif
func testFrameworkRedef() {
var s: String
s = REDEF_1
#if CONFLICT
s = REDEF_2 // expected-error{{ambiguous use of 'REDEF_2'}}
#endif
}
func testBridgingHeaderRedef() {
var s: String
s = BRIDGING_HEADER_1
s = BRIDGING_HEADER_2
_ = s
}
func testSubmodules() {
var s: String
s = MRWS_REDEF_1
s = MRWS_REDEF_2
_ = s
}
func testParallelSubmodules() {
var s: String
s = MRWPS_REDEF_1
s = MRWPS_REDEF_2 // expected-error{{ambiguous use of 'MRWPS_REDEF_2'}}
_ = s
}
func testDeliberateRedef() {
var s: String
s = MacrosDeliberateRedefA.MDR_REDEF_1
s = MacrosDeliberateRedefB.MDR_REDEF_1
s = MDR_REDEF_1
#if CONFLICT
// The first two lines ought to work even when SILGen-ing, but the two
// definitions of MDR_REDEF_2 end up getting the same mangled name.
s = MacrosDeliberateRedefA.MDR_REDEF_2 // ok
s = MacrosDeliberateRedefB.MDR_REDEF_2 // ok
s = MDR_REDEF_2 // expected-error{{ambiguous use of 'MDR_REDEF_2'}}
#endif
}
|
apache-2.0
|
b4ce43f9c1f57ac50a2bfa55b9e4632e
| 25.707692 | 189 | 0.741359 | 2.786517 | false | true | false | false |
mmick66/kinieta
|
Kinieta/Sequence.swift
|
1
|
2651
|
/*
* Sequence.swift
* Created by Michael Michailidis on 16/10/2017.
* http://blog.karmadust.com/
*
* 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
class Sequence: Collection, Action {
let complete: Block?
init(_ types: [ActionType] = [], complete: Block? = nil) {
self.complete = complete
super.init(types)
}
func popLast() -> ActionType? {
return super.pop()
}
func popFirst() -> ActionType? {
guard let first = self.types.first else { return nil }
self.types.removeFirst()
return first
}
func popAllUnGrouped() -> [ActionType] {
var actions = [ActionType]()
pop: while let last = self.popLast() {
switch last {
case .Group:
self.add(last) // put back
break pop
default:
actions.append(last)
}
}
return actions
}
private var currentAction: Action?
func update(_ frame: Engine.Frame) -> ActionResult {
if let currentAction = self.currentAction {
switch currentAction.update(frame) {
case .Running:
return .Running
case .Finished:
self.currentAction = nil
return self.types.count > 0 ? .Running : .Finished
}
}
else if let nextAction = self.popFirstAction() {
self.currentAction = nextAction
return update(frame)
}
self.complete?()
return .Finished
}
}
|
apache-2.0
|
af61138fad101bbe26ae881159082ceb
| 31.329268 | 80 | 0.617503 | 4.683746 | false | false | false | false |
lucascarletti/Pruuu
|
Pods/StatefulViewController/StatefulViewController/StatefulViewControllerImplementation.swift
|
1
|
4336
|
import UIKit
// MARK: Default Implementation BackingViewProvider
extension BackingViewProvider where Self: UIViewController {
public var backingView: UIView {
return view
}
}
extension BackingViewProvider where Self: UIView {
public var backingView: UIView {
return self
}
}
// MARK: Default Implementation StatefulViewController
/// Default implementation of StatefulViewController for UIViewController
extension StatefulViewController {
public var stateMachine: ViewStateMachine {
return associatedObject(self, key: &stateMachineKey) { [unowned self] in
return ViewStateMachine(view: self.backingView)
}
}
public var currentState: StatefulViewControllerState {
switch stateMachine.currentState {
case .none: return .Content
case .view(let viewKey): return StatefulViewControllerState(rawValue: viewKey)!
}
}
public var lastState: StatefulViewControllerState {
switch stateMachine.lastState {
case .none: return .Content
case .view(let viewKey): return StatefulViewControllerState(rawValue: viewKey)!
}
}
// MARK: Views
public var loadingView: UIView? {
get { return placeholderView(.Loading) }
set { setPlaceholderView(newValue, forState: .Loading) }
}
public var errorView: UIView? {
get { return placeholderView(.Error) }
set { setPlaceholderView(newValue, forState: .Error) }
}
public var emptyView: UIView? {
get { return placeholderView(.Empty) }
set { setPlaceholderView(newValue, forState: .Empty) }
}
// MARK: Transitions
public func setupInitialViewState(_ completion: (() -> Void)? = nil) {
let isLoading = (lastState == .Loading)
let error: NSError? = (lastState == .Error) ? NSError(domain: "com.aschuch.StatefulViewController.ErrorDomain", code: -1, userInfo: nil) : nil
transitionViewStates(loading: isLoading, error: error, animated: false, completion: completion)
}
public func startLoading(animated: Bool = false, completion: (() -> Void)? = nil) {
transitionViewStates(loading: true, animated: animated, completion: completion)
}
public func endLoading(animated: Bool = true, error: Error? = nil, completion: (() -> Void)? = nil) {
transitionViewStates(loading: false, error: error, animated: animated, completion: completion)
}
public func transitionViewStates(loading: Bool = false, error: Error? = nil, animated: Bool = true, completion: (() -> Void)? = nil) {
// Update view for content (i.e. hide all placeholder views)
if hasContent() {
if let e = error {
// show unobstrusive error
handleErrorWhenContentAvailable(e)
}
self.stateMachine.transitionToState(.none, animated: animated, completion: completion)
return
}
// Update view for placeholder
var newState: StatefulViewControllerState = .Empty
if loading {
newState = .Loading
} else if let _ = error {
newState = .Error
}
self.stateMachine.transitionToState(.view(newState.rawValue), animated: animated, completion: completion)
}
// MARK: Content and error handling
public func hasContent() -> Bool {
return true
}
public func handleErrorWhenContentAvailable(_ error: Error) {
// Default implementation does nothing.
}
// MARK: Helper
fileprivate func placeholderView(_ state: StatefulViewControllerState) -> UIView? {
return stateMachine[state.rawValue]
}
fileprivate func setPlaceholderView(_ view: UIView?, forState state: StatefulViewControllerState) {
stateMachine[state.rawValue] = view
}
}
// MARK: Association
private var stateMachineKey: UInt8 = 0
private func associatedObject<T: AnyObject>(_ host: AnyObject, key: UnsafeRawPointer, initial: () -> T) -> T {
var value = objc_getAssociatedObject(host, key) as? T
if value == nil {
value = initial()
objc_setAssociatedObject(host, key, value, .OBJC_ASSOCIATION_RETAIN)
}
return value!
}
|
mit
|
e9807e0589b87d69bb4a3ff9fad73abf
| 31.118519 | 150 | 0.641836 | 5.065421 | false | false | false | false |
josherick/DailySpend
|
DailySpend/AppDelegate.swift
|
1
|
13097
|
//
// AppDelegate.swift
// DailySpend
//
// Created by Josh Sherick on 3/6/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var spendIndicationColor: UIColor? {
didSet {
let nc = NotificationCenter.default
nc.post(name: NSNotification.Name.init("ChangedSpendIndicationColor"),
object: UIApplication.shared)
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Logger.printAllCoreData()
return true
}
func application(_ app: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
guard url.pathExtension == "dailyspend" || url.pathExtension == "zip" else {
return false
}
let rootVC = window?.rootViewController
var visibleVC = getVisibleViewController(rootVC)
let importHandler: (UIAlertAction) -> Void = { _ in
// Initialize import feedback message.
var title = "Success"
var message = "The import has succeeded. Your data file has been " +
"loaded into the app."
do {
// Attempt to import.
try Importer.importURL(url)
// Success, load the main screen.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialVC = storyboard.instantiateInitialViewController()
self.window?.rootViewController = initialVC
visibleVC = initialVC
} catch ExportError.recoveredFromPersistentStoreProblem {
// Recovered from failure due to an error moving or accessing the
// persistent store.
title = "Failed"
message = "Import failed. Please check that your device isn't " +
"running low on space. Your data has been restored " +
"to the state before the import."
} catch ExportError.recoveredFromBadFormat {
// Recovered from failure due to an error parsing the import file.
title = "Failed"
message = "Import failed. Please check that the file you " +
"are trying to import is valid. Your data has been " +
"restored to the state before the import."
} catch ExportError.unrecoverableDatabaseInBadState {
// Could not recover due to being unable to promote the backup
// persistent store to the primary persistent store.
title = "Failed"
message = "Import failed. Unfortunately, we were not able " +
"to recover to the state before import, possibly " +
"due to a number of factors, one of which could be " +
"low space on your device. Check that the imported " +
"file is in a correct format and that your device " +
"has sufficient space and try again. Sorry for " +
"this inconvenience. If you need help, please " +
"contact support."
} catch ExportError.recoveredFromBadFormatWithContextChange {
// The context has changed. Any ManagedObjects stored in memory
// will be invalidated and cause errors if used.
// To ensure they aren't, we'll instantiate a new
// TodayViewController and set it as the window's root VC.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialVC = storyboard.instantiateInitialViewController()
self.window?.rootViewController = initialVC
visibleVC = initialVC
title = "Failed"
message = "Import failed. Please check that the file you " +
"are trying to import is valid. Your data has been restored " +
"to the state before the import."
} catch ExportError.recoveredFromFilesystemError {
// Recovered from failure due to filesystem operations.
title = "Failed"
message = "Import failed. Please check that your device isn't " +
"running low on space. Your data has been restored " +
"to the state before the import."
} catch ExportError.unrecoverableFilesystemError {
// Could not recover from a failure due to filesystem operations.
title = "Failed"
message = "Import failed. Unfortunately, we were not able " +
"to recover to the state before import, possibly " +
"due to a number of factors, one of which could be " +
"low space on your device. Check that the imported " +
"file is in a correct format and that your device " +
"has sufficient space and try again. Sorry for " +
"this inconvenience. If you need help, please " +
"contact support."
} catch {
// Catch-all to satisfy function type requirements.
title = "Failed"
message = "There was an unknown error."
Logger.debug("\(error)")
}
// Create and present alert.
let alert = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
let okay = UIAlertAction(title: "Okay", style: .default, handler: nil)
alert.addAction(okay)
visibleVC?.present(alert, animated: true, completion: nil)
}
// Prompt user as to whether they would like to import.
let title = "Import"
let message = "Would you like to import this data file to your app? " +
"This will overwrite any existing data. If you haven't " +
"made a backup of your existing data, tap cancel, go to " +
"the Settings menu, export your data, and make a copy " +
"somewhere safe."
let alert = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
let cancel = UIAlertAction(title: "Cancel",
style: .cancel,
handler: nil)
let delete = UIAlertAction(title: "Overwrite and Import",
style: .destructive,
handler: importHandler)
alert.addAction(cancel)
alert.addAction(delete)
visibleVC?.present(alert, animated: true, completion: nil)
return true
}
func getVisibleViewController(_ rootViewController: UIViewController?) -> UIViewController? {
var rootVC = rootViewController
if rootVC == nil {
rootVC = UIApplication.shared.keyWindow?.rootViewController
}
if rootVC?.presentedViewController == nil {
return rootVC
}
if let presented = rootVC?.presentedViewController {
if presented.isKind(of: UINavigationController.self) {
let navigationController = presented as! UINavigationController
return navigationController.viewControllers.last!
}
if presented.isKind(of: UITabBarController.self) {
let tabBarController = presented as! UITabBarController
return tabBarController.selectedViewController!
}
return getVisibleViewController(presented)
}
return nil
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
//NotificationCenter.default.removeObserver(self, name: Notification.Name.NSCalendarDayChanged, object: nil)
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//NotificationCenter.default.addObserver(self, selector: #selector(createUpToToday), name: Notification.Name.NSCalendarDayChanged, object: nil)
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
var _persistentContainer: NSPersistentContainer? = nil
var persistentContainer: NSPersistentContainer! {
get {
if let pc = _persistentContainer {
return pc
}
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "DailySpend")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
_persistentContainer = container
return _persistentContainer
}
set {
_persistentContainer = newValue
}
}
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
d01675129e7c11666fe71ef013080ce3
| 48.233083 | 285 | 0.584911 | 5.988112 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.