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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
WhisperSystems/Signal-iOS | SignalServiceKit/src/Storage/Jobs/SSKJobRecord+SDS.swift | 1 | 28392 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import GRDB
import SignalCoreKit
// NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py.
// Do not manually edit it, instead run `sds_codegen.sh`.
// MARK: - Record
public struct JobRecordRecord: SDSRecord {
public var tableMetadata: SDSTableMetadata {
return SSKJobRecordSerializer.table
}
public static let databaseTableName: String = SSKJobRecordSerializer.table.tableName
public var id: Int64?
// This defines all of the columns used in the table
// where this model (and any subclasses) are persisted.
public let recordType: SDSRecordType
public let uniqueId: String
// Base class properties
public let failureCount: UInt
public let label: String
public let status: SSKJobRecordStatus
// Subclass properties
public let attachmentIdMap: Data?
public let contactThreadId: String?
public let envelopeData: Data?
public let invisibleMessage: Data?
public let messageId: String?
public let removeMessageAfterSending: Bool?
public let threadId: String?
public enum CodingKeys: String, CodingKey, ColumnExpression, CaseIterable {
case id
case recordType
case uniqueId
case failureCount
case label
case status
case attachmentIdMap
case contactThreadId
case envelopeData
case invisibleMessage
case messageId
case removeMessageAfterSending
case threadId
}
public static func columnName(_ column: JobRecordRecord.CodingKeys, fullyQualified: Bool = false) -> String {
return fullyQualified ? "\(databaseTableName).\(column.rawValue)" : column.rawValue
}
}
// MARK: - Row Initializer
public extension JobRecordRecord {
static var databaseSelection: [SQLSelectable] {
return CodingKeys.allCases
}
init(row: Row) {
id = row[0]
recordType = row[1]
uniqueId = row[2]
failureCount = row[3]
label = row[4]
status = row[5]
attachmentIdMap = row[6]
contactThreadId = row[7]
envelopeData = row[8]
invisibleMessage = row[9]
messageId = row[10]
removeMessageAfterSending = row[11]
threadId = row[12]
}
}
// MARK: - StringInterpolation
public extension String.StringInterpolation {
mutating func appendInterpolation(jobRecordColumn column: JobRecordRecord.CodingKeys) {
appendLiteral(JobRecordRecord.columnName(column))
}
mutating func appendInterpolation(jobRecordColumnFullyQualified column: JobRecordRecord.CodingKeys) {
appendLiteral(JobRecordRecord.columnName(column, fullyQualified: true))
}
}
// MARK: - Deserialization
// TODO: Rework metadata to not include, for example, columns, column indices.
extension SSKJobRecord {
// This method defines how to deserialize a model, given a
// database row. The recordType column is used to determine
// the corresponding model class.
class func fromRecord(_ record: JobRecordRecord) throws -> SSKJobRecord {
guard let recordId = record.id else {
throw SDSError.invalidValue
}
switch record.recordType {
case .broadcastMediaMessageJobRecord:
let uniqueId: String = record.uniqueId
let failureCount: UInt = record.failureCount
let label: String = record.label
let sortId: UInt64 = UInt64(recordId)
let status: SSKJobRecordStatus = record.status
let attachmentIdMapSerialized: Data? = record.attachmentIdMap
let attachmentIdMap: [String: [String]] = try SDSDeserialization.unarchive(attachmentIdMapSerialized, name: "attachmentIdMap")
return OWSBroadcastMediaMessageJobRecord(uniqueId: uniqueId,
failureCount: failureCount,
label: label,
sortId: sortId,
status: status,
attachmentIdMap: attachmentIdMap)
case .sessionResetJobRecord:
let uniqueId: String = record.uniqueId
let failureCount: UInt = record.failureCount
let label: String = record.label
let sortId: UInt64 = UInt64(recordId)
let status: SSKJobRecordStatus = record.status
let contactThreadId: String = try SDSDeserialization.required(record.contactThreadId, name: "contactThreadId")
return OWSSessionResetJobRecord(uniqueId: uniqueId,
failureCount: failureCount,
label: label,
sortId: sortId,
status: status,
contactThreadId: contactThreadId)
case .jobRecord:
let uniqueId: String = record.uniqueId
let failureCount: UInt = record.failureCount
let label: String = record.label
let sortId: UInt64 = UInt64(recordId)
let status: SSKJobRecordStatus = record.status
return SSKJobRecord(uniqueId: uniqueId,
failureCount: failureCount,
label: label,
sortId: sortId,
status: status)
case .messageDecryptJobRecord:
let uniqueId: String = record.uniqueId
let failureCount: UInt = record.failureCount
let label: String = record.label
let sortId: UInt64 = UInt64(recordId)
let status: SSKJobRecordStatus = record.status
let envelopeData: Data? = SDSDeserialization.optionalData(record.envelopeData, name: "envelopeData")
return SSKMessageDecryptJobRecord(uniqueId: uniqueId,
failureCount: failureCount,
label: label,
sortId: sortId,
status: status,
envelopeData: envelopeData)
case .messageSenderJobRecord:
let uniqueId: String = record.uniqueId
let failureCount: UInt = record.failureCount
let label: String = record.label
let sortId: UInt64 = UInt64(recordId)
let status: SSKJobRecordStatus = record.status
let invisibleMessageSerialized: Data? = record.invisibleMessage
let invisibleMessage: TSOutgoingMessage? = try SDSDeserialization.optionalUnarchive(invisibleMessageSerialized, name: "invisibleMessage")
let messageId: String? = record.messageId
let removeMessageAfterSending: Bool = try SDSDeserialization.required(record.removeMessageAfterSending, name: "removeMessageAfterSending")
let threadId: String? = record.threadId
return SSKMessageSenderJobRecord(uniqueId: uniqueId,
failureCount: failureCount,
label: label,
sortId: sortId,
status: status,
invisibleMessage: invisibleMessage,
messageId: messageId,
removeMessageAfterSending: removeMessageAfterSending,
threadId: threadId)
default:
owsFailDebug("Unexpected record type: \(record.recordType)")
throw SDSError.invalidValue
}
}
}
// MARK: - SDSModel
extension SSKJobRecord: SDSModel {
public var serializer: SDSSerializer {
// Any subclass can be cast to it's superclass,
// so the order of this switch statement matters.
// We need to do a "depth first" search by type.
switch self {
case let model as SSKMessageSenderJobRecord:
assert(type(of: model) == SSKMessageSenderJobRecord.self)
return SSKMessageSenderJobRecordSerializer(model: model)
case let model as SSKMessageDecryptJobRecord:
assert(type(of: model) == SSKMessageDecryptJobRecord.self)
return SSKMessageDecryptJobRecordSerializer(model: model)
case let model as OWSSessionResetJobRecord:
assert(type(of: model) == OWSSessionResetJobRecord.self)
return OWSSessionResetJobRecordSerializer(model: model)
case let model as OWSBroadcastMediaMessageJobRecord:
assert(type(of: model) == OWSBroadcastMediaMessageJobRecord.self)
return OWSBroadcastMediaMessageJobRecordSerializer(model: model)
default:
return SSKJobRecordSerializer(model: self)
}
}
public func asRecord() throws -> SDSRecord {
return try serializer.asRecord()
}
public var sdsTableName: String {
return JobRecordRecord.databaseTableName
}
public static var table: SDSTableMetadata {
return SSKJobRecordSerializer.table
}
}
// MARK: - Table Metadata
extension SSKJobRecordSerializer {
// This defines all of the columns used in the table
// where this model (and any subclasses) are persisted.
static let idColumn = SDSColumnMetadata(columnName: "id", columnType: .primaryKey, columnIndex: 0)
static let recordTypeColumn = SDSColumnMetadata(columnName: "recordType", columnType: .int64, columnIndex: 1)
static let uniqueIdColumn = SDSColumnMetadata(columnName: "uniqueId", columnType: .unicodeString, isUnique: true, columnIndex: 2)
// Base class properties
static let failureCountColumn = SDSColumnMetadata(columnName: "failureCount", columnType: .int64, columnIndex: 3)
static let labelColumn = SDSColumnMetadata(columnName: "label", columnType: .unicodeString, columnIndex: 4)
static let statusColumn = SDSColumnMetadata(columnName: "status", columnType: .int, columnIndex: 5)
// Subclass properties
static let attachmentIdMapColumn = SDSColumnMetadata(columnName: "attachmentIdMap", columnType: .blob, isOptional: true, columnIndex: 6)
static let contactThreadIdColumn = SDSColumnMetadata(columnName: "contactThreadId", columnType: .unicodeString, isOptional: true, columnIndex: 7)
static let envelopeDataColumn = SDSColumnMetadata(columnName: "envelopeData", columnType: .blob, isOptional: true, columnIndex: 8)
static let invisibleMessageColumn = SDSColumnMetadata(columnName: "invisibleMessage", columnType: .blob, isOptional: true, columnIndex: 9)
static let messageIdColumn = SDSColumnMetadata(columnName: "messageId", columnType: .unicodeString, isOptional: true, columnIndex: 10)
static let removeMessageAfterSendingColumn = SDSColumnMetadata(columnName: "removeMessageAfterSending", columnType: .int, isOptional: true, columnIndex: 11)
static let threadIdColumn = SDSColumnMetadata(columnName: "threadId", columnType: .unicodeString, isOptional: true, columnIndex: 12)
// TODO: We should decide on a naming convention for
// tables that store models.
public static let table = SDSTableMetadata(collection: SSKJobRecord.collection(),
tableName: "model_SSKJobRecord",
columns: [
idColumn,
recordTypeColumn,
uniqueIdColumn,
failureCountColumn,
labelColumn,
statusColumn,
attachmentIdMapColumn,
contactThreadIdColumn,
envelopeDataColumn,
invisibleMessageColumn,
messageIdColumn,
removeMessageAfterSendingColumn,
threadIdColumn
])
}
// MARK: - Save/Remove/Update
@objc
public extension SSKJobRecord {
func anyInsert(transaction: SDSAnyWriteTransaction) {
sdsSave(saveMode: .insert, transaction: transaction)
}
// This method is private; we should never use it directly.
// Instead, use anyUpdate(transaction:block:), so that we
// use the "update with" pattern.
private func anyUpdate(transaction: SDSAnyWriteTransaction) {
sdsSave(saveMode: .update, transaction: transaction)
}
@available(*, deprecated, message: "Use anyInsert() or anyUpdate() instead.")
func anyUpsert(transaction: SDSAnyWriteTransaction) {
let isInserting: Bool
if SSKJobRecord.anyFetch(uniqueId: uniqueId, transaction: transaction) != nil {
isInserting = false
} else {
isInserting = true
}
sdsSave(saveMode: isInserting ? .insert : .update, transaction: transaction)
}
// This method is used by "updateWith..." methods.
//
// This model may be updated from many threads. We don't want to save
// our local copy (this instance) since it may be out of date. We also
// want to avoid re-saving a model that has been deleted. Therefore, we
// use "updateWith..." methods to:
//
// a) Update a property of this instance.
// b) If a copy of this model exists in the database, load an up-to-date copy,
// and update and save that copy.
// b) If a copy of this model _DOES NOT_ exist in the database, do _NOT_ save
// this local instance.
//
// After "updateWith...":
//
// a) Any copy of this model in the database will have been updated.
// b) The local property on this instance will always have been updated.
// c) Other properties on this instance may be out of date.
//
// All mutable properties of this class have been made read-only to
// prevent accidentally modifying them directly.
//
// This isn't a perfect arrangement, but in practice this will prevent
// data loss and will resolve all known issues.
func anyUpdate(transaction: SDSAnyWriteTransaction, block: (SSKJobRecord) -> Void) {
block(self)
guard let dbCopy = type(of: self).anyFetch(uniqueId: uniqueId,
transaction: transaction) else {
return
}
// Don't apply the block twice to the same instance.
// It's at least unnecessary and actually wrong for some blocks.
// e.g. `block: { $0 in $0.someField++ }`
if dbCopy !== self {
block(dbCopy)
}
dbCopy.anyUpdate(transaction: transaction)
}
func anyRemove(transaction: SDSAnyWriteTransaction) {
sdsRemove(transaction: transaction)
}
func anyReload(transaction: SDSAnyReadTransaction) {
anyReload(transaction: transaction, ignoreMissing: false)
}
func anyReload(transaction: SDSAnyReadTransaction, ignoreMissing: Bool) {
guard let latestVersion = type(of: self).anyFetch(uniqueId: uniqueId, transaction: transaction) else {
if !ignoreMissing {
owsFailDebug("`latest` was unexpectedly nil")
}
return
}
setValuesForKeys(latestVersion.dictionaryValue)
}
}
// MARK: - SSKJobRecordCursor
@objc
public class SSKJobRecordCursor: NSObject {
private let cursor: RecordCursor<JobRecordRecord>?
init(cursor: RecordCursor<JobRecordRecord>?) {
self.cursor = cursor
}
public func next() throws -> SSKJobRecord? {
guard let cursor = cursor else {
return nil
}
guard let record = try cursor.next() else {
return nil
}
return try SSKJobRecord.fromRecord(record)
}
public func all() throws -> [SSKJobRecord] {
var result = [SSKJobRecord]()
while true {
guard let model = try next() else {
break
}
result.append(model)
}
return result
}
}
// MARK: - Obj-C Fetch
// TODO: We may eventually want to define some combination of:
//
// * fetchCursor, fetchOne, fetchAll, etc. (ala GRDB)
// * Optional "where clause" parameters for filtering.
// * Async flavors with completions.
//
// TODO: I've defined flavors that take a read transaction.
// Or we might take a "connection" if we end up having that class.
@objc
public extension SSKJobRecord {
class func grdbFetchCursor(transaction: GRDBReadTransaction) -> SSKJobRecordCursor {
let database = transaction.database
do {
let cursor = try JobRecordRecord.fetchCursor(database)
return SSKJobRecordCursor(cursor: cursor)
} catch {
owsFailDebug("Read failed: \(error)")
return SSKJobRecordCursor(cursor: nil)
}
}
// Fetches a single model by "unique id".
class func anyFetch(uniqueId: String,
transaction: SDSAnyReadTransaction) -> SSKJobRecord? {
assert(uniqueId.count > 0)
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return SSKJobRecord.ydb_fetch(uniqueId: uniqueId, transaction: ydbTransaction)
case .grdbRead(let grdbTransaction):
let sql = "SELECT * FROM \(JobRecordRecord.databaseTableName) WHERE \(jobRecordColumn: .uniqueId) = ?"
return grdbFetchOne(sql: sql, arguments: [uniqueId], transaction: grdbTransaction)
}
}
// Traverses all records.
// Records are not visited in any particular order.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
block: @escaping (SSKJobRecord, UnsafeMutablePointer<ObjCBool>) -> Void) {
anyEnumerate(transaction: transaction, batched: false, block: block)
}
// Traverses all records.
// Records are not visited in any particular order.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
batched: Bool = false,
block: @escaping (SSKJobRecord, UnsafeMutablePointer<ObjCBool>) -> Void) {
let batchSize = batched ? Batching.kDefaultBatchSize : 0
anyEnumerate(transaction: transaction, batchSize: batchSize, block: block)
}
// Traverses all records.
// Records are not visited in any particular order.
//
// If batchSize > 0, the enumeration is performed in autoreleased batches.
class func anyEnumerate(transaction: SDSAnyReadTransaction,
batchSize: UInt,
block: @escaping (SSKJobRecord, UnsafeMutablePointer<ObjCBool>) -> Void) {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
SSKJobRecord.ydb_enumerateCollectionObjects(with: ydbTransaction) { (object, stop) in
guard let value = object as? SSKJobRecord else {
owsFailDebug("unexpected object: \(type(of: object))")
return
}
block(value, stop)
}
case .grdbRead(let grdbTransaction):
do {
let cursor = SSKJobRecord.grdbFetchCursor(transaction: grdbTransaction)
try Batching.loop(batchSize: batchSize,
loopBlock: { stop in
guard let value = try cursor.next() else {
stop.pointee = true
return
}
block(value, stop)
})
} catch let error {
owsFailDebug("Couldn't fetch models: \(error)")
}
}
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
anyEnumerateUniqueIds(transaction: transaction, batched: false, block: block)
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
batched: Bool = false,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
let batchSize = batched ? Batching.kDefaultBatchSize : 0
anyEnumerateUniqueIds(transaction: transaction, batchSize: batchSize, block: block)
}
// Traverses all records' unique ids.
// Records are not visited in any particular order.
//
// If batchSize > 0, the enumeration is performed in autoreleased batches.
class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction,
batchSize: UInt,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
ydbTransaction.enumerateKeys(inCollection: SSKJobRecord.collection()) { (uniqueId, stop) in
block(uniqueId, stop)
}
case .grdbRead(let grdbTransaction):
grdbEnumerateUniqueIds(transaction: grdbTransaction,
sql: """
SELECT \(jobRecordColumn: .uniqueId)
FROM \(JobRecordRecord.databaseTableName)
""",
batchSize: batchSize,
block: block)
}
}
// Does not order the results.
class func anyFetchAll(transaction: SDSAnyReadTransaction) -> [SSKJobRecord] {
var result = [SSKJobRecord]()
anyEnumerate(transaction: transaction) { (model, _) in
result.append(model)
}
return result
}
// Does not order the results.
class func anyAllUniqueIds(transaction: SDSAnyReadTransaction) -> [String] {
var result = [String]()
anyEnumerateUniqueIds(transaction: transaction) { (uniqueId, _) in
result.append(uniqueId)
}
return result
}
class func anyCount(transaction: SDSAnyReadTransaction) -> UInt {
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return ydbTransaction.numberOfKeys(inCollection: SSKJobRecord.collection())
case .grdbRead(let grdbTransaction):
return JobRecordRecord.ows_fetchCount(grdbTransaction.database)
}
}
// WARNING: Do not use this method for any models which do cleanup
// in their anyWillRemove(), anyDidRemove() methods.
class func anyRemoveAllWithoutInstantation(transaction: SDSAnyWriteTransaction) {
switch transaction.writeTransaction {
case .yapWrite(let ydbTransaction):
ydbTransaction.removeAllObjects(inCollection: SSKJobRecord.collection())
case .grdbWrite(let grdbTransaction):
do {
try JobRecordRecord.deleteAll(grdbTransaction.database)
} catch {
owsFailDebug("deleteAll() failed: \(error)")
}
}
if shouldBeIndexedForFTS {
FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction)
}
}
class func anyRemoveAllWithInstantation(transaction: SDSAnyWriteTransaction) {
// To avoid mutationDuringEnumerationException, we need
// to remove the instances outside the enumeration.
let uniqueIds = anyAllUniqueIds(transaction: transaction)
var index: Int = 0
do {
try Batching.loop(batchSize: Batching.kDefaultBatchSize,
loopBlock: { stop in
guard index < uniqueIds.count else {
stop.pointee = true
return
}
let uniqueId = uniqueIds[index]
index = index + 1
guard let instance = anyFetch(uniqueId: uniqueId, transaction: transaction) else {
owsFailDebug("Missing instance.")
return
}
instance.anyRemove(transaction: transaction)
})
} catch {
owsFailDebug("Error: \(error)")
}
if shouldBeIndexedForFTS {
FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction)
}
}
class func anyExists(uniqueId: String,
transaction: SDSAnyReadTransaction) -> Bool {
assert(uniqueId.count > 0)
switch transaction.readTransaction {
case .yapRead(let ydbTransaction):
return ydbTransaction.hasObject(forKey: uniqueId, inCollection: SSKJobRecord.collection())
case .grdbRead(let grdbTransaction):
let sql = "SELECT EXISTS ( SELECT 1 FROM \(JobRecordRecord.databaseTableName) WHERE \(jobRecordColumn: .uniqueId) = ? )"
let arguments: StatementArguments = [uniqueId]
return try! Bool.fetchOne(grdbTransaction.database, sql: sql, arguments: arguments) ?? false
}
}
}
// MARK: - Swift Fetch
public extension SSKJobRecord {
class func grdbFetchCursor(sql: String,
arguments: StatementArguments = StatementArguments(),
transaction: GRDBReadTransaction) -> SSKJobRecordCursor {
do {
let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true)
let cursor = try JobRecordRecord.fetchCursor(transaction.database, sqlRequest)
return SSKJobRecordCursor(cursor: cursor)
} catch {
Logger.error("sql: \(sql)")
owsFailDebug("Read failed: \(error)")
return SSKJobRecordCursor(cursor: nil)
}
}
class func grdbFetchOne(sql: String,
arguments: StatementArguments = StatementArguments(),
transaction: GRDBReadTransaction) -> SSKJobRecord? {
assert(sql.count > 0)
do {
let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true)
guard let record = try JobRecordRecord.fetchOne(transaction.database, sqlRequest) else {
return nil
}
return try SSKJobRecord.fromRecord(record)
} catch {
owsFailDebug("error: \(error)")
return nil
}
}
}
// MARK: - SDSSerializer
// The SDSSerializer protocol specifies how to insert and update the
// row that corresponds to this model.
class SSKJobRecordSerializer: SDSSerializer {
private let model: SSKJobRecord
public required init(model: SSKJobRecord) {
self.model = model
}
// MARK: - Record
func asRecord() throws -> SDSRecord {
let id: Int64? = model.sortId > 0 ? Int64(model.sortId) : nil
let recordType: SDSRecordType = .jobRecord
let uniqueId: String = model.uniqueId
// Base class properties
let failureCount: UInt = model.failureCount
let label: String = model.label
let status: SSKJobRecordStatus = model.status
// Subclass properties
let attachmentIdMap: Data? = nil
let contactThreadId: String? = nil
let envelopeData: Data? = nil
let invisibleMessage: Data? = nil
let messageId: String? = nil
let removeMessageAfterSending: Bool? = nil
let threadId: String? = nil
return JobRecordRecord(id: id, recordType: recordType, uniqueId: uniqueId, failureCount: failureCount, label: label, status: status, attachmentIdMap: attachmentIdMap, contactThreadId: contactThreadId, envelopeData: envelopeData, invisibleMessage: invisibleMessage, messageId: messageId, removeMessageAfterSending: removeMessageAfterSending, threadId: threadId)
}
}
| gpl-3.0 | 808f5e9741c746351c948d94a2268180 | 39.910663 | 368 | 0.613377 | 5.408 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Wallet/Views/PassphraseView.swift | 1 | 2747 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import UIKit
final class PassphraseView: UIView {
lazy var layout: UICollectionViewLayout = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 8
layout.minimumInteritemSpacing = 8
layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
layout.sectionInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
return layout
}()
lazy var collectionView: DynamicCollectionView = {
let collectionView = DynamicCollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.isScrollEnabled = false
return collectionView
}()
var words: [String] = [] {
didSet {
collectionView.reloadData()
}
}
var isEditable: Bool = false
var didDeleteItem: ((String) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(R.nib.wordCollectionViewCell)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: topAnchor),
collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PassphraseView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return words.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: R.nib.wordCollectionViewCell.identifier, for: indexPath) as! WordCollectionViewCell
cell.wordLabel.text = words[indexPath.row]
return cell
}
}
extension PassphraseView: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard isEditable else { return }
let item = words[indexPath.row]
words.remove(at: indexPath.row)
collectionView.reloadData()
didDeleteItem?(item)
}
}
| gpl-3.0 | 33d2be52baf890c4b6d3cdd4e5152c41 | 33.772152 | 158 | 0.698216 | 5.722917 | false | false | false | false |
nmdias/FeedKit | Sources/FeedKit/Models/Atom/AtomFeedGenerator.swift | 2 | 3883 | //
// AtomFeedGenerator.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// The "atom:generator" element's content identifies the agent used to
/// generate a feed, for debugging and other purposes.
///
/// The content of this element, when present, MUST be a string that is a
/// human-readable name for the generating agent. Entities such as
/// "&" and "<" represent their corresponding characters ("&" and
/// "<" respectively), not markup.
///
/// The atom:generator element MAY have a "uri" attribute whose value
/// MUST be an IRI reference [RFC3987]. When dereferenced, the resulting
/// URI (mapped from an IRI, if necessary) SHOULD produce a
/// representation that is relevant to that agent.
///
/// The atom:generator element MAY have a "version" attribute that
/// indicates the version of the generating agent.
public class AtomFeedGenerator {
/// The element's attributes.
public class Attributes {
/// The atom:generator element MAY have a "uri" attribute whose value
/// MUST be an IRI reference [RFC3987]. When dereferenced, the resulting
/// URI (mapped from an IRI, if necessary) SHOULD produce a
/// representation that is relevant to that agent.
public var uri: String?
/// The atom:generator element MAY have a "version" attribute that
/// indicates the version of the generating agent.
public var version: String?
}
/// The element's attributes.
public var attributes: Attributes?
/// The element's value.
public var value: String?
public init() { }
}
// MARK: - Initializers
extension AtomFeedGenerator {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = AtomFeedGenerator.Attributes(attributes: attributeDict)
}
}
extension AtomFeedGenerator.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.uri = attributeDict["uri"]
self.version = attributeDict["version"]
}
}
// MARK: - Equatable
extension AtomFeedGenerator: Equatable {
public static func ==(lhs: AtomFeedGenerator, rhs: AtomFeedGenerator) -> Bool {
return
lhs.attributes == rhs.attributes &&
lhs.value == rhs.value
}
}
extension AtomFeedGenerator.Attributes: Equatable {
public static func ==(lhs: AtomFeedGenerator.Attributes, rhs: AtomFeedGenerator.Attributes) -> Bool {
return
lhs.uri == rhs.uri &&
lhs.version == rhs.version
}
}
| mit | c81458bbbd257ec8fbcd3a46f22b2826 | 32.188034 | 105 | 0.668298 | 4.672684 | false | false | false | false |
qzephyrmor/antavo-sdk-swift | AntavoLoyaltySDK/Classes/ANTCustomer.swift | 1 | 2223 | //
// Customer.swift
// AntavoSDK
//
// Copyright © 2017 Antavo Ltd. All rights reserved.
//
// MARK: Base Antavo Customer object.
open class ANTCustomer: NSObject {
/**
Customer's unique identifier specified as string.
*/
open var id: String?
/**
Customer's first name specified as string.
*/
open var firstName: String?
/**
Customer's last name specified as string.
*/
open var lastName: String?
/**
Customer's handler specified as string.
*/
open var handler: String?
/**
Customer's email specified as string.
*/
open var email: String?
/**
Customer's status specified as string.
*/
open var status: String?
/**
Customer's score specified as integer.
*/
open var score: Int = 0
/**
Customer's spent specified as integer.
*/
open var spent: Int = 0
/**
Creates a new instance of Customer, and assigns the given properties to it.
- Parameter data: Properties to assign as NSDictionary object.
*/
open func assign(data: NSDictionary) -> ANTCustomer {
let customer = ANTCustomer()
if let id = data.object(forKey: "id") {
customer.id = id as? String
}
if let firstName = data.object(forKey: "first_name") {
customer.firstName = firstName as? String
}
if let lastName = data.object(forKey: "last_name") {
customer.lastName = lastName as? String
}
if let handler = data.object(forKey: "handler") {
customer.handler = handler as? String
}
if let email = data.object(forKey: "email") {
customer.email = email as? String
}
if let score = data.object(forKey: "score") {
customer.score = score as! Int
}
if let spent = data.object(forKey: "spent") {
customer.spent = spent as! Int
}
if let status = data.object(forKey: "status") {
customer.status = status as? String
}
return customer
}
}
| mit | e671ef1bffd163889b013f9fbed61271 | 23.152174 | 80 | 0.540954 | 4.609959 | false | false | false | false |
IngmarStein/swift | test/Interpreter/generic_class_empty_field.swift | 17 | 763 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
class Outer {
class Foo {
var zim = Bar()
var bas = Outer()
}
class Boo {
var bas = Outer()
var zim = Bar()
}
required init() {}
}
protocol Initable { init() }
extension Outer: Initable {}
class GFoo<T: Initable> {
var zim = Bar()
var bas = T()
}
class GBoo<T: Initable> {
var bas = T()
var zim = Bar()
}
class GFos<T: Initable> {
var bar = T()
var zim = Bar()
var bas = T()
}
struct Bar { }
do {
let a = Outer.Foo()
let b = Outer.Boo()
let c = GFoo<Outer>()
let d = GBoo<Outer>()
let e = GFos<Outer>()
}
// CHECK: Job's finished
print("Job's finished")
| apache-2.0 | c41e9c8e602afdaa93b2ee12e7ff7ec5 | 15.234043 | 44 | 0.559633 | 2.764493 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/Schedule/ScheduleCoordinator.swift | 1 | 851 | //
// ScheduleCoordinator.swift
// HTWDD
//
// Created by Benjamin Herzog on 29.10.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
class ScheduleCoordinator: Coordinator {
// MARK: Properties
let context: HasSchedule
var rootViewController: UIViewController { return self.scheduleMainViewController }
var childCoordinators: [Coordinator] = []
private lazy var scheduleMainViewController = ScheduleMainVC(context: self.context)
var auth: ScheduleService.Auth? {
didSet {
self.scheduleMainViewController.auth = self.auth
}
}
// MARK: Lifecycle
init(context: HasSchedule) {
self.context = context
}
func jumpToToday(animated: Bool = true) {
self.scheduleMainViewController.jumpToToday(animated: animated)
}
}
| gpl-2.0 | dc19144e0b8da93a1c1b7da85599da85 | 24.757576 | 87 | 0.672941 | 4.644809 | false | false | false | false |
WSDOT/wsdot-ios-app | wsdot/AlertInAreaViewController.swift | 1 | 7641 | //
// AlertInAreaViewController.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 Foundation
import UIKit
import SafariServices
class AlertsInAreaViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, INDLinkLabelDelegate {
let cellIdentifier = "AlertCell"
let SegueHighwayAlertViewController = "HighwayAlertViewController"
var alerts = [HighwayAlertItem]()
var trafficAlerts = [HighwayAlertItem]()
var constructionAlerts = [HighwayAlertItem]()
var specialEvents = [HighwayAlertItem]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
for alert in alerts{
if alert.eventCategory.lowercased() == "special event"{
specialEvents.append(alert)
} else if alert.headlineDesc.lowercased().contains("construction") || alert.eventCategory.lowercased().contains("construction") {
constructionAlerts.append(alert)
}else {
trafficAlerts.append(alert)
}
}
trafficAlerts = trafficAlerts.sorted(by: {$0.lastUpdatedTime.timeIntervalSince1970 > $1.lastUpdatedTime.timeIntervalSince1970})
constructionAlerts = constructionAlerts.sorted(by: {$0.lastUpdatedTime.timeIntervalSince1970 > $1.lastUpdatedTime.timeIntervalSince1970})
specialEvents = specialEvents.sorted(by: {$0.lastUpdatedTime.timeIntervalSince1970 > $1.lastUpdatedTime.timeIntervalSince1970})
tableView.rowHeight = UITableView.automaticDimension
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MyAnalytics.screenView(screenName: "AreaAlerts")
}
// MARK: Table View Data Source Methods
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch(section){
case 0:
return "Traffic Incidents" + (self.title != "Alert" && (trafficAlerts.count == 0) ? " - None Reported": "")
case 1:
return "Construction" + (self.title != "Alert" && (constructionAlerts.count == 0) ? " - None Reported": "")
case 2:
return "Special Events" + (self.title != "Alert" && (specialEvents.count == 0) ? " - None Reported": "")
default:
return nil
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch(section){
case 0:
return trafficAlerts.count
case 1:
return constructionAlerts.count
case 2:
return specialEvents.count
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! LinkCell
let htmlStyleString = "<style>body{font-family: '-apple-system'; font-size:\(cell.linkLabel.font.pointSize)px;}</style>"
var htmlString = ""
switch indexPath.section{
case 0:
cell.updateTime.text = TimeUtils.timeAgoSinceDate(date: trafficAlerts[indexPath.row].lastUpdatedTime, numericDates: false)
htmlString = htmlStyleString + trafficAlerts[indexPath.row].headlineDesc
break
case 1:
cell.updateTime.text = TimeUtils.timeAgoSinceDate(date: constructionAlerts[indexPath.row].lastUpdatedTime, numericDates: false)
htmlString = htmlStyleString + constructionAlerts[indexPath.row].headlineDesc
break
case 2:
cell.updateTime.text = TimeUtils.timeAgoSinceDate(date: specialEvents[indexPath.row].lastUpdatedTime, numericDates: false)
htmlString = htmlStyleString + specialEvents[indexPath.row].headlineDesc
break
default:
break
}
let attrStr = try! NSMutableAttributedString(
data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: false)!,
options: [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil)
cell.linkLabel.attributedText = attrStr
cell.linkLabel.delegate = self
if #available(iOS 13, *){
cell.linkLabel.textColor = UIColor.label
}
return cell
}
// MARK: Table View Delegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch(indexPath.section){
case 0:
performSegue(withIdentifier: SegueHighwayAlertViewController, sender: trafficAlerts[indexPath.row])
break
case 1:
performSegue(withIdentifier: SegueHighwayAlertViewController, sender: constructionAlerts[indexPath.row])
break
case 2:
performSegue(withIdentifier: SegueHighwayAlertViewController, sender: specialEvents[indexPath.row])
break
default: break
}
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: Naviagtion
// Get refrence to child VC
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SegueHighwayAlertViewController {
let alertItem = (sender as! HighwayAlertItem)
let destinationViewController = segue.destination as! HighwayAlertViewController
destinationViewController.alertId = alertItem.alertId
}
}
// MARK: INDLinkLabelDelegate
func linkLabel(_ label: INDLinkLabel, didLongPressLinkWithURL URL: Foundation.URL) {
let activityController = UIActivityViewController(activityItems: [URL], applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
}
func linkLabel(_ label: INDLinkLabel, didTapLinkWithURL URL: Foundation.URL) {
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = false
let svc = SFSafariViewController(url: URL, configuration: config)
if #available(iOS 10.0, *) {
svc.preferredControlTintColor = ThemeManager.currentTheme().secondaryColor
svc.preferredBarTintColor = ThemeManager.currentTheme().mainColor
} else {
svc.view.tintColor = ThemeManager.currentTheme().mainColor
}
self.present(svc, animated: true, completion: nil)
}
}
| gpl-3.0 | b837eefbb2b01783adf63905bc38f337 | 38.590674 | 146 | 0.657636 | 5.251546 | false | false | false | false |
mbrandonw/swift-fp | swift-fp/Tree.swift | 1 | 2786 | import Foundation
enum Tree <A> {
case Empty
case Leaf(@autoclosure () -> A)
case Node(
@autoclosure () -> Tree<A>,
@autoclosure () -> A,
@autoclosure () -> Tree<A>
)
init () {
self = .Empty
}
}
/**
Helper accessors
*/
func empty <A> (tree: Tree<A>) -> Bool {
switch tree {
case .Empty: return true
case .Leaf, .Node: return false
}
}
/**
Printable
*/
extension Tree : Printable {
var description: String {
get {
return _description("")
}
}
private func _description(indent: String) -> String {
switch self {
case .Empty:
return "\(indent)(empty)"
case let .Leaf(value):
return "\(indent)\(value())"
case let .Node(left, value, right):
let leftDescription = left()._description(indent + "|--")
let rightDescription = right()._description(indent + "|--")
return "\(indent)\(value())\n\(leftDescription)\n\(rightDescription)"
}
}
}
/**
Functor
*/
func fmap <A, B> (f: A -> B) -> Tree<A> -> Tree<B> {
return {tree in
switch tree {
case .Empty:
return .Empty
case let .Leaf(value):
return Tree<B>.Leaf(f(value()))
case let .Node(left, value, right):
return Tree<B>.Node(
fmap(f)(left()),
f(value()),
fmap(f)(right())
)
}
}
}
/**
Monad
*/
// Can't do it in any natural way!
//func bind <A, B> (tree: Tree<A>, f: A -> Tree<B>) -> Tree<B> {
// switch tree {
// case .Empty:
// return .Empty
// case let .Leaf(value):
// return .Leaf(f(value()))
// case let .Node(left, value, right):
// return .Node(bind(left(), f), ?????, bind(right(), f))
// }
//}
/**
Applicative
*/
func ap <A, B> (fs: Tree<A -> B>) -> Tree<A> -> Tree<B> {
return {tree in
switch (fs, tree) {
case (.Empty, .Empty), (.Leaf, .Empty), (.Node, .Empty), (.Empty, .Leaf), (.Empty, .Node):
return .Empty
case let (.Leaf(f), .Leaf(value)):
return .Leaf(f()(value()))
case let (.Leaf(f), .Node(left, value, right)):
return .Leaf(f()(value()))
case let (.Node(leftfs, f, rightfs), .Leaf(value)):
return .Leaf(f()(value()))
case let (.Node(leftfs, f, rightfs), .Node(left, value, right)):
return .Node(
ap(leftfs())(left()),
f()(value()),
ap(rightfs())(right())
)
}
}
}
/**
Foldable
*/
func foldl <A, B> (f: A -> B -> A) -> A -> Tree<B> -> A {
return {initial in
return {tree in
switch tree {
case .Empty:
return initial
case let .Leaf(value):
return f(initial)(value())
case let .Node(left, value, right):
let leftAccum = foldl(f)(initial)(left())
let rightAccum = foldl(f)(leftAccum)(right())
return f(rightAccum)(value())
}
}
}
}
| mit | 8833ca0734de92b613aaf39254c7d52f | 19.335766 | 94 | 0.526202 | 3.273796 | false | false | false | false |
shubham01/StyleGuide | StyleGuide/Classes/View Themes/SliderTheme.swift | 2 | 1087 | //
// File.swift
// StyleGuide
//
// Created by Shubham Agrawal on 28/10/17.
//
import Foundation
import SwiftyJSON
extension StyleGuide {
public class SliderTheme: ViewTheme {
let alternateTintColor: UIColor?
let thumbTintColor: UIColor?
override init(fromJSON json: JSON) {
self.thumbTintColor = StyleGuide.getColor(forString: json["thumbTintColor"].string)
self.alternateTintColor = StyleGuide.getColor(forString: json["alternateTintColor"].string)
super.init(fromJSON: json)
}
}
}
extension UISlider {
override public func apply(theme: String) {
if let values: StyleGuide.SliderTheme = StyleGuide.shared.sliderTheme[theme] {
self.apply(sliderThemeValues: values)
}
}
public func apply(sliderThemeValues values: StyleGuide.SliderTheme) {
self.apply(viewThemeValues: values)
self.maximumTrackTintColor = values.alternateTintColor ?? self.maximumTrackTintColor
self.thumbTintColor = values.thumbTintColor ?? self.thumbTintColor
}
}
| mit | bb9ee310619ad0115d7cbb6609c9004b | 27.605263 | 103 | 0.685373 | 4.454918 | false | false | false | false |
Daniel-Lopez/EZSwiftExtensions | Sources/UITextViewExtensions.swift | 1 | 1349 | //
// UITextViewExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension UITextView {
/// EZSwiftExtensions: Automatically sets these values: backgroundColor = clearColor, textColor = ThemeNicknameColor, clipsToBounds = true,
/// textAlignment = Left, userInteractionEnabled = true, editable = false, scrollEnabled = false, font = ThemeFontName, fontsize = 17
public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
self.init(x: x, y: y, w: w, h: h, fontSize: 17)
}
/// EZSwiftExtensions: Automatically sets these values: backgroundColor = clearColor, textColor = ThemeNicknameColor, clipsToBounds = true,
/// textAlignment = Left, userInteractionEnabled = true, editable = false, scrollEnabled = false, font = ThemeFontName
public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, fontSize: CGFloat) {
self.init(frame: CGRect(x: x, y: y, width: w, height: h))
font = UIFont.HelveticaNeue(type: FontType.None, size: fontSize)
backgroundColor = UIColor.clearColor()
clipsToBounds = true
textAlignment = NSTextAlignment.Left
userInteractionEnabled = true
editable = false
scrollEnabled = false
}
}
| mit | 90913d6587154ff4894b8d334c3aca0b | 43.966667 | 143 | 0.693847 | 4.496667 | false | false | false | false |
hejunbinlan/actor-platform | actor-apps/app-ios/Actor/Controllers/Group/AddParticipantViewController.swift | 55 | 2649 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import UIKit
class AddParticipantViewController: ContactsBaseViewController {
var tableView: UITableView!
let gid: Int
init (gid: Int) {
self.gid = gid
super.init(contentSection: 1)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
title = NSLocalizedString("GroupAddParticipantTitle", comment: "Participant Title")
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("NavigationCancel", comment: "Cancel"),
style: UIBarButtonItemStyle.Plain,
target: self, action: Selector("dismiss"))
tableView = UITableView(frame: view.bounds, style: UITableViewStyle.Plain)
tableView.backgroundColor = UIColor.whiteColor()
view = tableView
bindTable(tableView, fade: true);
super.viewDidLoad();
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return 1
} else {
return super.tableView(tableView, numberOfRowsInSection: section)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
let reuseId = "cell_invite";
var res = ContactActionCell(reuseIdentifier: reuseId)
res.bind("ic_invite_user",
actionTitle: NSLocalizedString("GroupAddParticipantUrl", comment: "Action Title"),
isLast: false)
return res
} else {
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == 0 {
navigateNext(InviteLinkViewController(gid: gid), removeCurrent: false)
} else {
var contact = objectAtIndexPath(indexPath) as! AMContact;
execute(MSG.inviteMemberCommandWithGid(jint(gid), withUid: contact.getUid()), successBlock: { (val) -> () in
self.dismiss()
}, failureBlock: { (val) -> () in
self.dismiss()
})
}
}
}
| mit | 6326ff21e3caaeecf5dff54c48bab6c8 | 32.961538 | 120 | 0.604379 | 5.373225 | false | false | false | false |
afaan5556/toolbelt | xcode-toolbelt/ToolBelt/Pods/Alamofire/Source/Upload.swift | 236 | 15977 | //
// Upload.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
extension Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Request {
var uploadTask: NSURLSessionUploadTask!
var HTTPBodyStream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
dispatch_sync(queue) {
uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
}
case .File(let request, let fileURL):
dispatch_sync(queue) {
uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
}
case .Stream(let request, let stream):
dispatch_sync(queue) {
uploadTask = self.session.uploadTaskWithStreamedRequest(request)
}
HTTPBodyStream = stream
}
let request = Request(session: session, task: uploadTask)
if HTTPBodyStream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return HTTPBodyStream
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: File
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- parameter file: The file to upload
- returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return upload(.File(URLRequest.URLRequest, file))
}
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter file: The file to upload
- returns: The created upload request.
*/
public func upload(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
file: NSURL)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return upload(mutableURLRequest, file: file)
}
// MARK: Data
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request.
- parameter data: The data to upload.
- returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return upload(.Data(URLRequest.URLRequest, data))
}
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter data: The data to upload
- returns: The created upload request.
*/
public func upload(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
data: NSData)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return upload(mutableURLRequest, data: data)
}
// MARK: Stream
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request.
- parameter stream: The stream to upload.
- returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return upload(.Stream(URLRequest.URLRequest, stream))
}
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter stream: The stream to upload.
- returns: The created upload request.
*/
public func upload(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
stream: NSInputStream)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return upload(mutableURLRequest, stream: stream)
}
// MARK: MultipartFormData
/// Default memory threshold used when encoding `MultipartFormData`.
public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024
/**
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 `Request` 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: Request, streamingFromDisk: Bool, streamFileURL: NSURL?)
case Failure(ErrorType)
}
/**
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
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 method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
`MultipartFormDataEncodingMemoryThreshold` by default.
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
*/
public func upload(
method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
multipartFormData: MultipartFormData -> Void,
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: (MultipartFormDataEncodingResult -> Void)?)
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return upload(
mutableURLRequest,
multipartFormData: multipartFormData,
encodingMemoryThreshold: encodingMemoryThreshold,
encodingCompletion: encodingCompletion
)
}
/**
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
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 URLRequest: The URL request.
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
`MultipartFormDataEncodingMemoryThreshold` by default.
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
*/
public func upload(
URLRequest: URLRequestConvertible,
multipartFormData: MultipartFormData -> Void,
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: (MultipartFormDataEncodingResult -> Void)?)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let formData = MultipartFormData()
multipartFormData(formData)
let URLRequestWithContentType = URLRequest.URLRequest
URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
let isBackgroundSession = self.session.configuration.identifier != nil
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
do {
let data = try formData.encode()
let encodingResult = MultipartFormDataEncodingResult.Success(
request: self.upload(URLRequestWithContentType, data: data),
streamingFromDisk: false,
streamFileURL: nil
)
dispatch_async(dispatch_get_main_queue()) {
encodingCompletion?(encodingResult)
}
} catch {
dispatch_async(dispatch_get_main_queue()) {
encodingCompletion?(.Failure(error as NSError))
}
}
} else {
let fileManager = NSFileManager.defaultManager()
let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data")
let fileName = NSUUID().UUIDString
let fileURL = directoryURL.URLByAppendingPathComponent(fileName)
do {
try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil)
try formData.writeEncodedDataToDisk(fileURL)
dispatch_async(dispatch_get_main_queue()) {
let encodingResult = MultipartFormDataEncodingResult.Success(
request: self.upload(URLRequestWithContentType, file: fileURL),
streamingFromDisk: true,
streamFileURL: fileURL
)
encodingCompletion?(encodingResult)
}
} catch {
dispatch_async(dispatch_get_main_queue()) {
encodingCompletion?(.Failure(error as NSError))
}
}
}
}
}
}
// MARK: -
extension Request {
// MARK: - UploadTaskDelegate
class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
// MARK: Delegate Methods
func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
progress.totalUnitCount = totalBytesExpectedToSend
progress.completedUnitCount = totalBytesSent
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
}
}
| mit | 9cdc3fdc6a8d71c89ef791b7cb2ffef9 | 41.492021 | 124 | 0.649121 | 5.728577 | false | false | false | false |
xeo-it/poggy | Pods/OAuthSwift/OAuthSwift/OAuthSwiftClient.swift | 1 | 10533 | //
// OAuthSwiftClient.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
var OAuthSwiftDataEncoding: NSStringEncoding = NSUTF8StringEncoding
public protocol OAuthSwiftRequestHandle {
func cancel()
}
public class OAuthSwiftClient: NSObject {
private(set) public var credential: OAuthSwiftCredential
public var paramsLocation: OAuthSwiftHTTPRequest.ParamsLocation = .AuthorizationHeader
static let separator: String = "\r\n"
static var separatorData: NSData = {
return OAuthSwiftClient.separator.dataUsingEncoding(OAuthSwiftDataEncoding)!
}()
// MARK: init
public init(consumerKey: String, consumerSecret: String) {
self.credential = OAuthSwiftCredential(consumer_key: consumerKey, consumer_secret: consumerSecret)
}
public init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.credential = OAuthSwiftCredential(oauth_token: accessToken, oauth_token_secret: accessTokenSecret)
self.credential.consumer_key = consumerKey
self.credential.consumer_secret = consumerSecret
}
public init(credential: OAuthSwiftCredential) {
self.credential = credential
}
// MARK: client methods
public func get(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .GET, parameters: parameters, headers: headers, success: success, failure: failure)
}
public func post(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .POST, parameters: parameters, headers: headers, success: success, failure: failure)
}
public func put(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, body: NSData? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .PUT, parameters: parameters, headers: headers, body: body, success: success, failure: failure)
}
public func delete(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .DELETE, parameters: parameters, headers: headers,success: success, failure: failure)
}
public func patch(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.request(urlString, method: .PATCH, parameters: parameters, headers: headers,success: success, failure: failure)
}
public func request(urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, body: NSData? = nil, checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {
if checkTokenExpiration && self.credential.isTokenExpired() {
let errorInfo = [NSLocalizedDescriptionKey: NSLocalizedString("The provided token is expired.", comment:"Token expired, retrieve new token by using the refresh token")]
if let failureHandler = failure {
failureHandler(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.TokenExpiredError.rawValue, userInfo: errorInfo))
}
return nil
}
guard let _ = NSURL(string: urlString) else {
failure?(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.RequestCreationError.rawValue, userInfo: nil))
return nil
}
if let request = makeRequest(urlString, method: method, parameters: parameters, headers: headers, body: body) {
request.successHandler = success
request.failureHandler = failure
request.start()
return request
}
return nil
}
public func makeRequest(request: NSURLRequest) -> OAuthSwiftHTTPRequest {
let request = OAuthSwiftHTTPRequest(request: request, paramsLocation: self.paramsLocation)
request.makeOAuthSwiftHTTPRequest(self.credential)
return request
}
public func makeRequest(urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, body: NSData? = nil) -> OAuthSwiftHTTPRequest? {
guard let url = NSURL(string: urlString) else {
return nil
}
let request = OAuthSwiftHTTPRequest(URL: url, method: method, parameters: parameters, paramsLocation: self.paramsLocation, HTTPBody: body, headers: headers ?? [:])
request.makeOAuthSwiftHTTPRequest(self.credential)
return request
}
@available(*, deprecated=0.6.0, message="This method will be removed to make OAuthSwiftHTTPRequest.Config not mutable")
public func makeOAuthSwiftHTTPRequest(request: OAuthSwiftHTTPRequest) -> OAuthSwiftHTTPRequest {
request.makeOAuthSwiftHTTPRequest(self.credential)
return request
}
public func postImage(urlString: String, parameters: [String:AnyObject], image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {
return self.multiPartRequest(urlString, method: .POST, parameters: parameters, image: image, success: success, failure: failure)
}
func multiPartRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String:AnyObject], image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? {
let paramImage: [String: AnyObject] = ["media": image]
let boundary = "AS-boundary-\(arc4random())-\(arc4random())"
let type = "multipart/form-data; boundary=\(boundary)"
let body = self.multiPartBodyFromParams(paramImage, boundary: boundary)
let headers = [kHTTPHeaderContentType: type]
if let request = makeRequest(url, method: method, parameters: parameters, headers: headers, body: body) { // TODO check if headers do not override others...
request.successHandler = success
request.failureHandler = failure
request.start()
return request
}
return nil
}
public func multiPartBodyFromParams(parameters: [String: AnyObject], boundary: String) -> NSData {
let data = NSMutableData()
let prefixString = "--\(boundary)\r\n"
let prefixData = prefixString.dataUsingEncoding(OAuthSwiftDataEncoding)!
for (key, value) in parameters {
var sectionData: NSData
var sectionType: String?
var sectionFilename: String?
if let multiData = value as? NSData where key == "media" {
sectionData = multiData
sectionType = "image/jpeg"
sectionFilename = "file"
} else {
sectionData = "\(value)".dataUsingEncoding(OAuthSwiftDataEncoding)!
}
data.appendData(prefixData)
let multipartData = OAuthSwiftMultipartData(name: key, data: sectionData, fileName: sectionFilename, mimeType: sectionType)
data.appendMultipartData(multipartData, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData)
}
let endingString = "--\(boundary)--\r\n"
let endingData = endingString.dataUsingEncoding(OAuthSwiftDataEncoding)!
data.appendData(endingData)
return data
}
public func postMultiPartRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String:AnyObject], headers: [String: String]? = nil, multiparts: Array<OAuthSwiftMultipartData> = [], checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
let boundary = "POST-boundary-\(arc4random())-\(arc4random())"
let type = "multipart/form-data; boundary=\(boundary)"
let body = self.multiDataFromObject(parameters, multiparts: multiparts, boundary: boundary)
var finalHeaders = [kHTTPHeaderContentType: type]
finalHeaders += headers ?? [:]
if let request = makeRequest(url, method: method, parameters: parameters, headers: finalHeaders, body: body) { // TODO check if headers do not override
request.successHandler = success
request.failureHandler = failure
request.start()
}
}
func multiDataFromObject(object: [String:AnyObject], multiparts: Array<OAuthSwiftMultipartData>, boundary: String) -> NSData? {
let data = NSMutableData()
let prefixString = "--\(boundary)\r\n"
let prefixData = prefixString.dataUsingEncoding(OAuthSwiftDataEncoding)!
for (key, value) in object {
guard let valueData = "\(value)".dataUsingEncoding(OAuthSwiftDataEncoding) else {
continue
}
data.appendData(prefixData)
let multipartData = OAuthSwiftMultipartData(name: key, data: valueData, fileName: nil, mimeType: nil)
data.appendMultipartData(multipartData, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData)
}
for multipart in multiparts {
data.appendData(prefixData)
data.appendMultipartData(multipart, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData)
}
let endingString = "--\(boundary)--\r\n"
let endingData = endingString.dataUsingEncoding(OAuthSwiftDataEncoding)!
data.appendData(endingData)
return data
}
}
| apache-2.0 | 606e2ebff8b87318d9dc5785009617d7 | 50.131068 | 335 | 0.693535 | 5.196349 | false | false | false | false |
thombles/Flyweight | Flyweight/Client/Events.swift | 1 | 2606 | // Flyweight - iOS client for GNU social
// Copyright 2017 Thomas Karpiniec
//
// 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
fileprivate class EventIdGenerator {
static let lock = NSLock()
static var currentId: Int64 = 1
static func getNextId() -> Int64 {
lock.lock()
let ret = currentId
currentId += 1
lock.unlock()
return ret
}
}
class EventListenerToken<T> {
let id: Int64 = EventIdGenerator.getNextId()
let source: EventSource<T>
init(source: EventSource<T>) {
self.source = source
}
func unsubscribe() {
source.unsubscribe(id: id)
}
deinit {
unsubscribe()
}
}
class EventSource<T> {
let lock = NSLock()
var noParamHandlers: [Int64: () -> Void] = [:]
var paramHandlers: [Int64: (T) -> Void] = [:]
func subscribe(handler: @escaping () -> Void) -> EventListenerToken<T> {
let token = EventListenerToken(source: self)
lock.lock()
noParamHandlers[token.id] = handler
lock.unlock()
return token
}
func subscribeValue(handler: @escaping (T) -> Void) -> EventListenerToken<T> {
let token = EventListenerToken(source: self)
lock.lock()
paramHandlers[token.id] = handler
lock.unlock()
return token
}
func dispatch() {
lock.lock()
let handlers = Array(noParamHandlers.values)
lock.unlock()
for h in handlers {
h()
}
}
func dispatchValue(value: T) {
lock.lock()
let handlers1 = Array(noParamHandlers.values)
let handlers2 = Array(paramHandlers.values)
lock.unlock()
for h in handlers1 {
h()
}
for h in handlers2 {
h(value)
}
}
func unsubscribe(id: Int64) {
lock.lock()
noParamHandlers.removeValue(forKey: id)
paramHandlers.removeValue(forKey: id)
lock.unlock()
}
}
| apache-2.0 | 14e2c8cc0784bd751b1323a3749384c2 | 23.819048 | 82 | 0.586723 | 4.265139 | false | false | false | false |
ThatBerryKid/Code2 | Pong_App/Pong/Pong/menu.swift | 1 | 960 | //
// menu.swift
// Pong
//
// Created by James Berry on 3/3/17.
// Copyright © 2017 James Berry. All rights reserved.
//
import SpriteKit
import GameplayKit
class menu: SKScene {
var label: SKLabelNode?
var labe2: SKLabelNode?
var score = 0
var highScore = 0;
override func didMove(to view: SKView) {
label = self.childNode(withName: "LabelLastScore") as! SKLabelNode?
labe2 = self.childNode(withName: "LabelHighScore") as! SKLabelNode?
label?.text = "Last Score: \(score)"
labe2?.text = "High Score: \(highScore)"
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let scene = SKScene(fileNamed: "GameScene")
// Set the scale mode to scale to fit the window
scene?.scaleMode = .aspectFill
// Present the scene
view?.presentScene(scene)
}
}
| mit | 4c8793599de58cbf49bc44acd269ce03 | 21.302326 | 79 | 0.582899 | 4.20614 | false | false | false | false |
LINAICAI/NCLoadingView | source/NCLoadingAnimatedView.swift | 1 | 2636 | //
// NCLoadingAnimatedView.swift
// NCLoadingView
//
// Created by LINAICAI on 2017/3/18.
// Copyright © 2017年 LINAICAI. All rights reserved.
//
import UIKit
class NCLoadingAnimatedView: UIView {
var maskLayer:CALayer = {
let layer = CALayer()
return layer
}()
var foregroundLayer:CAShapeLayer = {
let layer = CAShapeLayer()
layer.lineWidth = 2.0
layer.strokeColor = NCLoadingView.tintColor.cgColor
layer.fillColor = nil
layer.lineCap = kCALineCapButt
layer.strokeEnd = 0.15;
return layer
}()
var backgroundLayer:CAShapeLayer = {
let layer = CAShapeLayer()
layer.lineWidth = 2.0
layer.strokeColor = UIColor(red: 239.0/255.0, green: 239.0/255.0, blue: 239.0/255.0, alpha: 1.0).cgColor
layer.fillColor = nil
layer.lineCap = kCALineCapButt
layer.strokeEnd = 1.0;
return layer
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.foregroundLayer.position = self.center
self.backgroundLayer.position = self.center
self.foregroundLayer.frame = bounds
self.backgroundLayer.frame = bounds
self.maskLayer.frame = bounds
self.maskLayer.mask = self.backgroundLayer
let path:UIBezierPath = UIBezierPath(ovalIn: bounds.insetBy(dx: 2, dy: 2))
self.foregroundLayer.path = path.cgPath
self.backgroundLayer.path = path.cgPath
self.layer.addSublayer(self.backgroundLayer)
self.layer.addSublayer(self.foregroundLayer)
self.rotate()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
func rotate() -> Void{
let animation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation")
animation.toValue = NSNumber(floatLiteral: Double.pi)
animation.duration = 0.5
animation.isCumulative = true
animation.repeatCount = Float(Int.max)
animation.autoreverses = false
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
self.foregroundLayer.add(animation, forKey: "animation")
}
}
| mit | bc248ca76272c86688ac25b9bcdc8925 | 31.9125 | 112 | 0.642993 | 4.701786 | false | false | false | false |
Ifinity/ifinity-swift-example | IfinitySDK-swift/FloorsViewController.swift | 1 | 2730 | //
// FloorsViewController.swift
// IfinitySDK-swift
//
// Created by Ifinity on 14.12.2015.
// Copyright © 2015 getifinity.com. All rights reserved.
//
import UIKit
import ifinitySDK
class FloorsViewController: UITableViewController {
var venue : IFMVenue?
var floors : [AnyObject] = []
override func viewDidLoad() {
super.viewDidLoad()
NSLog("Venue: %@ name: %@", self.venue!.remote_id, self.venue!.name)
self.title = "\(self.venue!.name) - Floors"
self.fetchFloors()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - IfinitySDK Calls
func fetchFloors() {
IFDataManager.sharedManager().fetchFloorsFromCacheForVenueId(self.venue!.remote_id, block: {floors in
NSLog("Fetch floors success with count: \(floors.count)")
self.floors = floors
if (self.refreshControl != nil) {
let formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "MMM d, h:mm a"
let lastUpdated: String = "Last updated on \(formatter.stringFromDate(NSDate()))"
self.refreshControl!.attributedTitle = NSAttributedString(string: lastUpdated)
self.refreshControl!.endRefreshing()
}
self.tableView.reloadData()
})
}
//MARK: - UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.floors.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath)
let floor: IFMFloorplan = self.floors[indexPath.row] as! IFMFloorplan
cell.textLabel!.text = "floor \(floor.label)"
return cell
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.destinationViewController is ContentViewController {
let url = NSURL(string: self.venue!.content.getContentURL())
let destinationVC = segue.destinationViewController as! ContentViewController
destinationVC.url = url
}
else if segue.destinationViewController is FloorplanChild && sender is UITableViewCell {
let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell)
let destinationVC = segue.destinationViewController as! FloorplanChild
destinationVC.floor = self.floors[indexPath!.row] as? IFMFloorplan
}
}
}
| mit | 9fc37caef50f78dd060dde7e01b29a58 | 34.441558 | 118 | 0.649689 | 4.961818 | false | false | false | false |
natestedman/ArrayLoader | ArrayLoaderTests/PageStateTests.swift | 1 | 2321 | // ArrayLoader
// Written in 2015 by Nate Stedman <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
import ArrayLoader
import XCTest
class PageStateTests: XCTestCase
{
func testHasMore()
{
XCTAssertTrue(PageState<NSError>.HasMore.isHasMore)
XCTAssertFalse(PageState<NSError>.HasMore.isCompleted)
XCTAssertFalse(PageState<NSError>.HasMore.isLoading)
XCTAssertNil(PageState<NSError>.HasMore.error)
}
func testCompleted()
{
XCTAssertTrue(PageState<NSError>.Completed.isCompleted)
XCTAssertFalse(PageState<NSError>.Completed.isHasMore)
XCTAssertFalse(PageState<NSError>.Completed.isLoading)
XCTAssertNil(PageState<NSError>.Completed.error)
}
func testLoading()
{
XCTAssertTrue(PageState<NSError>.Loading.isLoading)
XCTAssertFalse(PageState<NSError>.Loading.isCompleted)
XCTAssertFalse(PageState<NSError>.Loading.isHasMore)
XCTAssertNil(PageState<NSError>.Loading.error)
}
func testFailure()
{
let testError = NSError(domain: "test", code: 0, userInfo: nil)
let state = PageState.Failed(testError)
XCTAssertFalse(state.isLoading)
XCTAssertFalse(state.isCompleted)
XCTAssertFalse(state.isLoading)
XCTAssertNotNil(state.error)
XCTAssertEqual(state.error, testError)
}
func testEquatable()
{
XCTAssertEqual(PageState<NSError>.Loading, PageState.Loading)
XCTAssertEqual(PageState<NSError>.Completed, PageState.Completed)
XCTAssertEqual(PageState<NSError>.HasMore, PageState.HasMore)
let testError = NSError(domain: "test", code: 0, userInfo: nil)
let state = PageState.Failed(testError)
XCTAssertEqual(state, state)
let otherError = NSError(domain: "test", code: 1, userInfo: nil)
XCTAssertNotEqual(state, PageState.Failed(otherError))
}
}
| cc0-1.0 | e646111ce2bea94d4f1b72582d0b0c2f | 34.707692 | 83 | 0.695821 | 4.660643 | false | true | false | false |
roseleaf/tipCalcExample | tips/ViewController.swift | 1 | 1634 | //
// ViewController.swift
// tips
//
// Created by Rose Trujillo on 1/28/15.
// Copyright (c) 2015 Rose Trujillo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var totalField: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
var tipPercentages: [Int]!
override func viewDidLoad() {
super.viewDidLoad()
tipLabel.text = "$0.00"
totalField.text = "$0.00"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onEditingChanged(sender: AnyObject) {
var billAmount = NSString(string: billField.text).doubleValue
var tipPercentages = [0.15, 0.18, 0.20]
var tipPercentage = tipPercentages[tipControl.selectedSegmentIndex]
var tip = billAmount * tipPercentage
var total = billAmount + tip
tipLabel.text = String(format: "$%.2f", tip)
totalField.text = String(format: "$%.2f", total) }
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let defaults = NSUserDefaults.standardUserDefaults()
let percentSetting = defaults.integerForKey("tip_percent")
tipControl.selectedSegmentIndex = percentSetting
self.onEditingChanged(self)
}
}
| mit | 519b30d28ad2d8aa4e8052cdfa7702ae | 29.259259 | 75 | 0.656671 | 4.777778 | false | false | false | false |
knorrium/PitchPerfect | Pitch Perfect/PlaySoundsViewController.swift | 1 | 3350 | //
// PlaySoundsViewController.swift
// Pitch Perfect
//
// Created by Felipe Kuhn on 8/6/15.
// Copyright (c) 2015 Knorrium. All rights reserved.
//
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var audioPlayer:AVAudioPlayer!
var receivedAudio:RecordedAudio!
var audioEngine: AVAudioEngine!
var audioFile:AVAudioFile!
@IBOutlet weak var btnStop: UIButton!
@IBOutlet weak var btnPlayFast: UIButton!
@IBOutlet weak var btnSnail: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
audioEngine = AVAudioEngine()
audioFile = AVAudioFile(forReading: receivedAudio.filePathUrl, error: nil)
audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filePathUrl, error: nil)
audioPlayer.enableRate = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func resetPlayer() {
audioPlayer.stop()
audioEngine.stop()
audioPlayer.currentTime = 0.0
audioPlayer.rate = 1.0
audioEngine.reset()
}
@IBAction func stopAudio(sender: UIButton) {
resetPlayer()
}
@IBAction func playFastAudio(sender: UIButton) {
playAudioWithVariableRate(2.0)
}
@IBAction func playSlowAudio(sender: UIButton) {
playAudioWithVariableRate(0.5)
}
@IBAction func playDarthVader(sender: AnyObject) {
playAudioWithVariablePitch(-1000)
}
@IBAction func playChipmunk(sender: UIButton) {
playAudioWithVariablePitch(1000)
}
@IBAction func playEcho(sender: AnyObject) {
playAudioWithDelay(0.2)
}
func playAudioWithDelay(delay: Float) {
resetPlayer()
var audioPlayerNode = AVAudioPlayerNode()
audioEngine.attachNode(audioPlayerNode)
var addDelayEffect = AVAudioUnitDelay()
addDelayEffect.delayTime = NSTimeInterval(delay)
audioEngine.attachNode(addDelayEffect)
audioEngine.connect(audioPlayerNode, to: addDelayEffect, format: nil)
audioEngine.connect(addDelayEffect, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(nil)
audioPlayerNode.play()
}
func playAudioWithVariableRate(rate: Float) {
resetPlayer()
audioPlayer.rate = rate
audioPlayer.play()
}
func playAudioWithVariablePitch(pitch: Float){
resetPlayer()
var audioPlayerNode = AVAudioPlayerNode()
audioEngine.attachNode(audioPlayerNode)
var changePitchEffect = AVAudioUnitTimePitch()
changePitchEffect.pitch = pitch
audioEngine.attachNode(changePitchEffect)
audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil)
audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(nil)
audioPlayerNode.play()
}
}
| mit | 66a6e3aaf1b79f4ade1e8b260ebbd473 | 28.646018 | 89 | 0.666269 | 5.122324 | false | false | false | false |
amitburst/Palettes | Palettes/ColorConverter.swift | 1 | 3600 | //
// ColorConverter.swift
// Palettes
//
// Created by Amit Burstein on 12/3/14.
// Copyright (c) 2014 Amit Burstein. All rights reserved.
//
class ColorConverter: NSObject {
// MARK: Enumerations
enum CopyType: Int {
case HEX = 0, RGB = 1, RGBA = 2, HSL = 3, HSLA = 4, NSColorSwift = 5, NSColorObjC = 6, UIColorSwift = 7, UIColorObjC = 8
}
// MARK: Functions
class func getColorString(#index: Int, rawHex: String) -> String {
let hex = "0x\(rawHex)".withCString { strtoul($0, nil, 16) }
var red = (hex & 0xFF0000) >> 16
var green = (hex & 0x00FF00) >> 8
var blue = (hex & 0x0000FF)
switch index {
case CopyType.HEX.rawValue:
return "#\(rawHex.lowercaseString)"
case CopyType.RGB.rawValue:
return "rgb(\(red), \(green), \(blue))"
case CopyType.RGBA.rawValue:
return "rgba(\(red), \(green), \(blue), 1)"
case CopyType.HSL.rawValue:
let (h, s, l) = getHSLFromRGB(red: red, green: green, blue: blue)
return "hsl(\(h), \(s)%, \(l)%)"
case CopyType.HSLA.rawValue:
let (h, s, l) = getHSLFromRGB(red: red, green: green, blue: blue)
return "hsla(\(h), \(s)%, \(l)%, 1)"
case CopyType.NSColorSwift.rawValue:
let r = String(format: "%.3f", Float(red) / 255)
let g = String(format: "%.3f", Float(green) / 255)
let b = String(format: "%.3f", Float(blue) / 255)
return "NSColor(red: \(r), green: \(g), blue: \(b), alpha: 1)"
case CopyType.NSColorObjC.rawValue:
let r = String(format: "%.3f", Float(red) / 255)
let g = String(format: "%.3f", Float(green) / 255)
let b = String(format: "%.3f", Float(blue) / 255)
return "[NSColor colorWithRed:\(r) green:\(g) blue:\(b) alpha:1]"
case CopyType.UIColorSwift.rawValue:
let r = String(format: "%.3f", Float(red) / 255)
let g = String(format: "%.3f", Float(green) / 255)
let b = String(format: "%.3f", Float(blue) / 255)
return "UIColor(red: \(r), green: \(g), blue: \(b), alpha: 1)"
case CopyType.UIColorObjC.rawValue:
let r = String(format: "%.3f", Float(red) / 255)
let g = String(format: "%.3f", Float(green) / 255)
let b = String(format: "%.3f", Float(blue) / 255)
return "[UIColor colorWithRed:\(r) green:\(g) blue:\(b) alpha:1]"
default:
println("New color type added?")
return ""
}
}
class func getHSLFromRGB(#red: UInt, green: UInt, blue: UInt) -> (h: Int, s: Int, l: Int) {
var r = CGFloat(red) / 255
var g = CGFloat(green) / 255
var b = CGFloat(blue) / 255
let maxRGB = max(r, g, b)
let minRGB = min(r, g, b)
var h = (maxRGB + minRGB) / 2
var s = h
var l = h
if minRGB == maxRGB {
h = 0
s = 0
} else {
let d = maxRGB - minRGB
s = l > 0.5 ? d / (2 - maxRGB - minRGB) : d / (maxRGB + minRGB)
switch maxRGB {
case r:
h = (g - b) / d + (g < b ? 6 : 0)
case g:
h = (b - r) / d + 2
case b:
h = (r - g) / d + 4
default:
println("Something bad happened...")
}
h /= 6
}
return (Int(round(h * 360)), Int(round(s * 100)), Int(round(l * 100)))
}
}
| mit | f2fb0bbec89afd7301e5066c28120ce2 | 36.5 | 128 | 0.482778 | 3.501946 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Pods/Nuke/Sources/ImageProcessing.swift | 1 | 7227 | // The MIT License (MIT)
//
// Copyright (c) 2015-2019 Alexander Grebenyuk (github.com/kean).
import Foundation
/// Performs image processing.
public protocol ImageProcessing: Equatable {
/// Returns processed image.
func process(image: Image, context: ImageProcessingContext) -> Image?
}
/// Image processing context used when selecting which processor to use.
public struct ImageProcessingContext {
public let request: ImageRequest
public let isFinal: Bool
public let scanNumber: Int? // need a more general purpose way to implement this
}
/// Composes multiple processors.
internal struct ImageProcessorComposition: ImageProcessing {
private let processors: [AnyImageProcessor]
/// Composes multiple processors.
public init(_ processors: [AnyImageProcessor]) {
self.processors = processors
}
/// Processes the given image by applying each processor in an order in
/// which they were added. If one of the processors fails to produce
/// an image the processing stops and `nil` is returned.
func process(image: Image, context: ImageProcessingContext) -> Image? {
return processors.reduce(image) { image, processor in
return autoreleasepool {
image.flatMap { processor.process(image: $0, context: context) }
}
}
}
/// Returns true if the underlying processors are pairwise-equivalent.
public static func == (lhs: ImageProcessorComposition, rhs: ImageProcessorComposition) -> Bool {
return lhs.processors == rhs.processors
}
}
/// Type-erased image processor.
public struct AnyImageProcessor: ImageProcessing {
private let _process: (Image, ImageProcessingContext) -> Image?
private let _processor: Any
private let _equals: (AnyImageProcessor) -> Bool
public init<P: ImageProcessing>(_ processor: P) {
self._process = { processor.process(image: $0, context: $1) }
self._processor = processor
self._equals = { ($0._processor as? P) == processor }
}
public func process(image: Image, context: ImageProcessingContext) -> Image? {
return self._process(image, context)
}
public static func == (lhs: AnyImageProcessor, rhs: AnyImageProcessor) -> Bool {
return lhs._equals(rhs)
}
}
internal struct AnonymousImageProcessor<Key: Hashable>: ImageProcessing {
private let _key: Key
private let _closure: (Image) -> Image?
init(_ key: Key, _ closure: @escaping (Image) -> Image?) {
self._key = key; self._closure = closure
}
func process(image: Image, context: ImageProcessingContext) -> Image? {
return self._closure(image)
}
static func == (lhs: AnonymousImageProcessor, rhs: AnonymousImageProcessor) -> Bool {
return lhs._key == rhs._key
}
}
extension ImageProcessing {
func process(image: ImageContainer, request: ImageRequest) -> Image? {
let context = ImageProcessingContext(request: request, isFinal: image.isFinal, scanNumber: image.scanNumber)
return process(image: image.image, context: context)
}
}
#if !os(macOS)
import UIKit
/// Decompresses and (optionally) scales down input images. Maintains
/// original aspect ratio.
///
/// Decompressing compressed image formats (such as JPEG) can significantly
/// improve drawing performance as it allows a bitmap representation to be
/// created in a background rather than on the main thread.
public struct ImageDecompressor: ImageProcessing {
/// An option for how to resize the image.
public enum ContentMode {
/// Scales the image so that it completely fills the target size.
/// Doesn't clip images.
case aspectFill
/// Scales the image so that it fits the target size.
case aspectFit
}
/// Size to pass to disable resizing.
public static let MaximumSize = CGSize(
width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude
)
private let targetSize: CGSize
private let contentMode: ContentMode
private let upscale: Bool
/// Initializes `Decompressor` with the given parameters.
/// - parameter targetSize: Size in pixels. `MaximumSize` by default.
/// - parameter contentMode: An option for how to resize the image
/// to the target size. `.aspectFill` by default.
public init(targetSize: CGSize = MaximumSize, contentMode: ContentMode = .aspectFill, upscale: Bool = false) {
self.targetSize = targetSize
self.contentMode = contentMode
self.upscale = upscale
}
/// Decompresses and scales the image.
public func process(image: Image, context: ImageProcessingContext) -> Image? {
return decompress(image, targetSize: targetSize, contentMode: contentMode, upscale: upscale)
}
/// Returns true if both have the same `targetSize` and `contentMode`.
public static func == (lhs: ImageDecompressor, rhs: ImageDecompressor) -> Bool {
return lhs.targetSize == rhs.targetSize && lhs.contentMode == rhs.contentMode
}
#if !os(watchOS)
/// Returns target size in pixels for the given view. Takes main screen
/// scale into the account.
public static func targetSize(for view: UIView) -> CGSize { // in pixels
let scale = UIScreen.main.scale
let size = view.bounds.size
return CGSize(width: size.width * scale, height: size.height * scale)
}
#endif
}
internal func decompress(_ image: UIImage, targetSize: CGSize, contentMode: ImageDecompressor.ContentMode, upscale: Bool) -> UIImage {
guard let cgImage = image.cgImage else { return image }
let bitmapSize = CGSize(width: cgImage.width, height: cgImage.height)
let scaleHor = targetSize.width / bitmapSize.width
let scaleVert = targetSize.height / bitmapSize.height
let scale = contentMode == .aspectFill ? max(scaleHor, scaleVert) : min(scaleHor, scaleVert)
return decompress(image, scale: CGFloat(upscale ? scale : min(scale, 1)))
}
internal func decompress(_ image: UIImage, scale: CGFloat) -> UIImage {
guard let cgImage = image.cgImage else { return image }
let size = CGSize(
width: round(scale * CGFloat(cgImage.width)),
height: round(scale * CGFloat(cgImage.height))
)
// For more info see:
// - Quartz 2D Programming Guide
// - https://github.com/kean/Nuke/issues/35
// - https://github.com/kean/Nuke/issues/57
let alphaInfo: CGImageAlphaInfo = isOpaque(cgImage) ? .noneSkipLast : .premultipliedLast
guard let ctx = CGContext(
data: nil,
width: Int(size.width), height: Int(size.height),
bitsPerComponent: 8, bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: alphaInfo.rawValue) else {
return image
}
ctx.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: size))
guard let decompressed = ctx.makeImage() else { return image }
return UIImage(cgImage: decompressed, scale: image.scale, orientation: image.imageOrientation)
}
private func isOpaque(_ image: CGImage) -> Bool {
let alpha = image.alphaInfo
return alpha == .none || alpha == .noneSkipFirst || alpha == .noneSkipLast
}
#endif
| mit | dbe3fd7f6d91126e2290042092fbf06c | 36.445596 | 134 | 0.683686 | 4.545283 | false | false | false | false |
macemmi/HBCI4Swift | HBCI4Swift/HBCI4Swift/Source/Syntax/HBCISegmentVersions.swift | 1 | 3640 | //
// HBCISegmentVersions.swift
// HBCIBackend
//
// Created by Frank Emminghaus on 27.12.14.
// Copyright (c) 2014 Frank Emminghaus. All rights reserved.
//
import Foundation
class HBCISegmentVersions {
let identifier:String!
var code: String! // todo: replace with let after Xcode bug fixed
var syntaxElement: XMLElement;
var versions = Dictionary<Int, HBCISegmentDescription>();
var versionNumbers = Array<Int>();
init(syntax: HBCISyntax, element: XMLElement) throws {
self.syntaxElement = element;
self.identifier = element.valueForAttribute("id");
if self.identifier == nil {
// error
logInfo("Syntax file error: attribute ID is missing for element \(element)");
throw HBCIError.syntaxFileError;
}
self.code = element.valueForAttribute("code");
if self.code == nil {
// error
logInfo("Syntax file error: attribute CODE is missing for element \(element)");
throw HBCIError.syntaxFileError;
}
let all_vers = element.elements(forName: "SEGVersion") ;
for segv in all_vers {
if let versionString = segv.valueForAttribute("id") {
if let version = Int(versionString) {
// HBCISegmentDescription
let segment = try HBCISegmentDescription(syntax: syntax, element: segv, code: code, version: version);
segment.type = identifier;
segment.syntaxElement = segv;
segment.values["SegHead.version"] = version;
segment.values["SegHead.code"] = code;
versions[version] = segment;
// next version
continue;
} else {
logInfo("Syntax file error: ID \(versionString) cannot be converted to a number");
throw HBCIError.syntaxFileError;
}
} else {
logInfo("Syntax file error: attribute ID is missing for element \(segv)");
throw HBCIError.syntaxFileError;
}
}
// get and sort version codes
self.versionNumbers = Array(versions.keys);
if self.versionNumbers.count > 0 {
self.versionNumbers.sort(by: {$0 < $1})
} else {
// error
logInfo("Syntax file error: segment \(element) has no versions");
throw HBCIError.syntaxFileError;
}
// values
let all_values = element.elements(forName: "value") ;
for elem in all_values {
if let path = elem.valueForAttribute("path") {
if let value = elem.stringValue {
// now set value for all versions
for segv in versions.values {
segv.values[path] = value;
}
// next value
continue;
}
}
// error occured
logInfo("Syntax file error: value element \(elem) could not be parsed");
throw HBCIError.syntaxFileError;
}
}
func latestVersion() ->HBCISegmentDescription {
return self.versions[self.versionNumbers.last!]!;
}
func isVersionSupported(_ version:Int) ->Bool {
return versionNumbers.firstIndex(of: version) != nil;
}
func segmentWithVersion(_ version:Int) -> HBCISegmentDescription? {
return versions[version];
}
}
| gpl-2.0 | 4b6c84ce350797753bb6fb15672ab934 | 35.4 | 122 | 0.541758 | 5.2149 | false | false | false | false |
adrfer/swift | test/Constraints/members.swift | 1 | 14333 | // RUN: %target-parse-verify-swift
import Swift
////
// Members of structs
////
struct X {
func f0(i: Int) -> X { }
func f1(i: Int) { }
mutating func f1(f: Float) { }
func f2<T>(x: T) -> T { }
}
struct Y<T> {
func f0(_: T) -> T {}
func f1<U>(x: U, y: T) -> (T, U) {}
}
var i : Int
var x : X
var yf : Y<Float>
func g0(_: (inout X) -> (Float) -> ()) {}
x.f0(i)
x.f0(i).f1(i)
g0(X.f1)
x.f0(x.f2(1))
x.f0(1).f2(i)
yf.f0(1)
yf.f1(i, y: 1)
// Members referenced from inside the struct
struct Z {
var i : Int
func getI() -> Int { return i }
mutating func incI() {}
func curried(x: Int) -> (Int) -> Int { return { y in x + y } }
subscript (k : Int) -> Int {
get {
return i + k
}
mutating
set {
i -= k
}
}
}
struct GZ<T> {
var i : T
func getI() -> T { return i }
func f1<U>(a: T, b: U) -> (T, U) {
return (a, b)
}
func f2() {
var f : Float
var t = f1(i, b: f)
f = t.1
var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}}
var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}}
}
}
var z = Z(i: 0)
var getI = z.getI
var incI = z.incI // expected-error{{partial application of 'mutating'}}
var zi = z.getI()
var zcurried1 = z.curried
var zcurried2 = z.curried(0)
var zcurriedFull = z.curried(0)(1)
////
// Members of modules
////
// Module
Swift.print(3, terminator: "")
var format : String
format._splitFirstIf({ $0.isASCII() })
////
// Unqualified references
////
////
// Members of literals
////
// FIXME: Crappy diagnostic
"foo".lower() // expected-error{{value of type 'String' has no member 'lower'}}
var tmp = "foo".debugDescription
////
// Members of enums
////
enum W {
case Omega
func foo(x: Int) {}
func curried(x: Int) -> (Int) -> () {}
}
var w = W.Omega
var foo = w.foo
var fooFull : () = w.foo(0)
var wcurried1 = w.curried
var wcurried2 = w.curried(0)
var wcurriedFull : () = w.curried(0)(1)
// Member of enum Type
func enumMetatypeMember(opt: Int?) {
opt.None // expected-error{{static member 'None' cannot be used on instance of type 'Int?'}}
}
////
// Nested types
////
// Reference a Type member. <rdar://problem/15034920>
class G<T> {
class In { // expected-error{{nested in generic type}}
class func foo() {}
}
}
func goo() {
G<Int>.In.foo()
}
////
// Members of archetypes
////
func id<T>(t: T) -> T { return t }
func doGetLogicValue<T : BooleanType>(t: T) {
t.boolValue
}
protocol P {
init()
func bar(x: Int)
mutating func mut(x: Int)
static func tum()
}
extension P {
func returnSelfInstance() -> Self {
return self
}
func returnSelfOptionalInstance(b: Bool) -> Self? {
return b ? self : nil
}
func returnSelfIUOInstance(b: Bool) -> Self! {
return b ? self : nil
}
static func returnSelfStatic() -> Self {
return Self()
}
static func returnSelfOptionalStatic(b: Bool) -> Self? {
return b ? Self() : nil
}
static func returnSelfIUOStatic(b: Bool) -> Self! {
return b ? Self() : nil
}
}
protocol ClassP : class {
func bas(x: Int)
}
func generic<T: P>(t: T) {
var t = t
// Instance member of archetype
let _: Int -> () = id(t.bar)
let _: () = id(t.bar(0))
// Static member of archetype metatype
let _: () -> () = id(T.tum)
// Instance member of archetype metatype
let _: T -> Int -> () = id(T.bar)
let _: Int -> () = id(T.bar(t))
_ = t.mut // expected-error{{partial application of 'mutating' method is not allowed}}
_ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}}
// Instance member of extension returning Self)
let _: T -> () -> T = id(T.returnSelfInstance)
let _: () -> T = id(T.returnSelfInstance(t))
let _: T = id(T.returnSelfInstance(t)())
let _: () -> T = id(t.returnSelfInstance)
let _: T = id(t.returnSelfInstance())
let _: T -> Bool -> T? = id(T.returnSelfOptionalInstance)
let _: Bool -> T? = id(T.returnSelfOptionalInstance(t))
let _: T? = id(T.returnSelfOptionalInstance(t)(false))
let _: Bool -> T? = id(t.returnSelfOptionalInstance)
let _: T? = id(t.returnSelfOptionalInstance(true))
let _: T -> Bool -> T! = id(T.returnSelfIUOInstance)
let _: Bool -> T! = id(T.returnSelfIUOInstance(t))
let _: T! = id(T.returnSelfIUOInstance(t)(true))
let _: Bool -> T! = id(t.returnSelfIUOInstance)
let _: T! = id(t.returnSelfIUOInstance(true))
// Static member of extension returning Self)
let _: () -> T = id(T.returnSelfStatic)
let _: T = id(T.returnSelfStatic())
let _: Bool -> T? = id(T.returnSelfOptionalStatic)
let _: T? = id(T.returnSelfOptionalStatic(false))
let _: Bool -> T! = id(T.returnSelfIUOStatic)
let _: T! = id(T.returnSelfIUOStatic(true))
}
func genericClassP<T: ClassP>(t: T) {
// Instance member of archetype)
let _: Int -> () = id(t.bas)
let _: () = id(t.bas(0))
// Instance member of archetype metatype)
let _: T -> Int -> () = id(T.bas)
let _: Int -> () = id(T.bas(t))
let _: () = id(T.bas(t)(1))
}
////
// Members of existentials
////
func existential(p: P) {
var p = p
// Fully applied mutating method
p.mut(1)
_ = p.mut // expected-error{{partial application of 'mutating' method is not allowed}}
// Instance member of existential)
let _: Int -> () = id(p.bar)
let _: () = id(p.bar(0))
// Static member of existential metatype)
let _: () -> () = id(p.dynamicType.tum)
// Instance member of extension returning Self
let _: () -> P = id(p.returnSelfInstance)
let _: P = id(p.returnSelfInstance())
let _: P? = id(p.returnSelfOptionalInstance(true))
let _: P! = id(p.returnSelfIUOInstance(true))
}
func staticExistential(p: P.Type, pp: P.Protocol) {
let ppp: P = p.init()
_ = pp.init() // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = P() // expected-error{{protocol type 'P' cannot be instantiated}}
// Instance member of metatype
let _: P -> Int -> () = P.bar
let _: Int -> () = P.bar(ppp)
P.bar(ppp)(5)
// Instance member of metatype value
let _: P -> Int -> () = pp.bar
let _: Int -> () = pp.bar(ppp)
pp.bar(ppp)(5)
// Static member of existential metatype value
let _: () -> () = p.tum
// Instance member of existential metatype -- not allowed
_ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}}
_ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}}
// Static member of metatype -- not allowed
_ = pp.tum // expected-error{{static member 'tum' cannot be used on instance of type 'P.Protocol'}}
_ = P.tum // expected-error{{static member 'tum' cannot be used on instance of type 'P.Protocol'}}
// Static member of extension returning Self)
let _: () -> P = id(p.returnSelfStatic)
let _: P = id(p.returnSelfStatic())
let _: Bool -> P? = id(p.returnSelfOptionalStatic)
let _: P? = id(p.returnSelfOptionalStatic(false))
let _: Bool -> P! = id(p.returnSelfIUOStatic)
let _: P! = id(p.returnSelfIUOStatic(true))
}
func existentialClassP(p: ClassP) {
// Instance member of existential)
let _: Int -> () = id(p.bas)
let _: () = id(p.bas(0))
// Instance member of existential metatype)
let _: ClassP -> Int -> () = id(ClassP.bas)
let _: Int -> () = id(ClassP.bas(p))
let _: () = id(ClassP.bas(p)(1))
}
// Partial application of curried protocol methods
protocol Scalar {}
protocol Vector {
func scale(c: Scalar) -> Self
}
protocol Functional {
func apply(v: Vector) -> Scalar
}
protocol Coalgebra {
func coproduct(f: Functional) -> (v1: Vector, v2: Vector) -> Scalar
}
// Make sure existential is closed early when we partially apply
func wrap<T>(t: T) -> T {
return t
}
func exercise(c: Coalgebra, f: Functional, v: Vector) {
let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f))
let _: Scalar -> Vector = v.scale
}
// Make sure existential isn't closed too late
protocol Copyable {
func copy() -> Self
}
func copyTwice(c: Copyable) -> Copyable {
return c.copy().copy()
}
////
// Misc ambiguities
////
// <rdar://problem/15537772>
struct DefaultArgs {
static func f(a: Int = 0) -> DefaultArgs {
return DefaultArgs()
}
init() {
self = .f()
}
}
class InstanceOrClassMethod {
func method() -> Bool { return true }
class func method(other: InstanceOrClassMethod) -> Bool { return false }
}
func testPreferClassMethodToCurriedInstanceMethod(obj: InstanceOrClassMethod) {
let result = InstanceOrClassMethod.method(obj)
let _: Bool = result // no-warning
let _: () -> Bool = InstanceOrClassMethod.method(obj)
}
protocol Numeric {
func +(x: Self, y: Self) -> Self
}
func acceptBinaryFunc<T>(x: T, _ fn: (T, T) -> T) { }
func testNumeric<T : Numeric>(x: T) {
acceptBinaryFunc(x, +)
}
/* FIXME: We can't check this directly, but it can happen with
multiple modules.
class PropertyOrMethod {
func member() -> Int { return 0 }
let member = false
class func methodOnClass(obj: PropertyOrMethod) -> Int { return 0 }
let methodOnClass = false
}
func testPreferPropertyToMethod(obj: PropertyOrMethod) {
let result = obj.member
let resultChecked: Bool = result
let called = obj.member()
let calledChecked: Int = called
let curried = obj.member as () -> Int
let methodOnClass = PropertyOrMethod.methodOnClass
let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass
}
*/
struct Foo { var foo: Int }
protocol ExtendedWithMutatingMethods { }
extension ExtendedWithMutatingMethods {
mutating func mutatingMethod() {}
var mutableProperty: Foo {
get { }
set { }
}
var nonmutatingProperty: Foo {
get { }
nonmutating set { }
}
var mutatingGetProperty: Foo {
mutating get { }
set { }
}
}
class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {}
class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {}
func testClassExtendedWithMutatingMethods(c: ClassExtendedWithMutatingMethods, // expected-note* {{}}
sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}}
c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}}
c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
c.nonmutatingProperty = Foo(foo: 0)
c.nonmutatingProperty.foo = 0
c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = c.mutableProperty
_ = c.mutableProperty.foo
_ = c.nonmutatingProperty
_ = c.nonmutatingProperty.foo
// FIXME: diagnostic nondeterministically says "member" or "getter"
_ = c.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}}
sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
sub.nonmutatingProperty = Foo(foo: 0)
sub.nonmutatingProperty.foo = 0
sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = sub.mutableProperty
_ = sub.mutableProperty.foo
_ = sub.nonmutatingProperty
_ = sub.nonmutatingProperty.foo
_ = sub.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
var mutableC = c
mutableC.mutatingMethod()
mutableC.mutableProperty = Foo(foo: 0)
mutableC.mutableProperty.foo = 0
mutableC.nonmutatingProperty = Foo(foo: 0)
mutableC.nonmutatingProperty.foo = 0
mutableC.mutatingGetProperty = Foo(foo: 0)
mutableC.mutatingGetProperty.foo = 0
_ = mutableC.mutableProperty
_ = mutableC.mutableProperty.foo
_ = mutableC.nonmutatingProperty
_ = mutableC.nonmutatingProperty.foo
_ = mutableC.mutatingGetProperty
_ = mutableC.mutatingGetProperty.foo
var mutableSub = sub
mutableSub.mutatingMethod()
mutableSub.mutableProperty = Foo(foo: 0)
mutableSub.mutableProperty.foo = 0
mutableSub.nonmutatingProperty = Foo(foo: 0)
mutableSub.nonmutatingProperty.foo = 0
_ = mutableSub.mutableProperty
_ = mutableSub.mutableProperty.foo
_ = mutableSub.nonmutatingProperty
_ = mutableSub.nonmutatingProperty.foo
_ = mutableSub.mutatingGetProperty
_ = mutableSub.mutatingGetProperty.foo
}
// <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad.
enum LedModules: Int {
case WS2811_1x_5V
}
extension LedModules {
static var watts: Double {
return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}}
}
}
// <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic
class r15117741S {
static func g() {}
}
func test15117741(s: r15117741S) {
s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}}
}
// <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous
struct UnavailMember {
@available(*, unavailable)
static var XYZ : X { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}}
}
let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}}
let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}}
// <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines a Generator type alias
struct S22490787 {
typealias Generator = AnyGenerator<Int>
}
func f22490787() {
var path: S22490787 = S22490787()
for p in path { // expected-error {{type 'S22490787' does not conform to protocol 'SequenceType'}}
}
}
// <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor
enum r23942743 {
case Tomato(cloud: String)
}
let _ = .Tomato(cloud: .None) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}}
| apache-2.0 | 971661627dfc2efd1ad43e66f071c089 | 25.444649 | 135 | 0.653527 | 3.540761 | false | false | false | false |
tokenlab/TKSequenceTextField | TKSequenceTextField/Classes/TKSequenceTextField.swift | 1 | 5456 | //
// TKSequenceTextField.swift
// Pods
//
// Created by Domene on 05/04/17.
//
//
import Foundation
import UIKit
import TLCustomMask
/*
* CustomMaskTextField can be used with a list of masks.
* e.g:
* customMaskTextField.setMaskSequence(['**.**', '***-***', '$$-$$$'])
*
* Use $ for digits ($$-$$$$)
* Use * for characters [a-zA-Z] (**-****)
*
* This custom TextField will reorder its maskSequence by mask length (smaller to bigger)
*/
public class TKSequenceTextField: UITextField, UITextFieldDelegate{
private var customMask = TLCustomMask()
private var currentMaskIndex : Int = 0
private var maskSequence : [String] = []
private var _text : String?
public var cleanText : String?
public override var text : String? {
get{
return self._text ?? ""
}
set {
if !maskSequence.indices.contains(currentMaskIndex){
self._text = newValue ?? ""
super.text = self._text
return
}
//currentMaskIndex = maskSequence.count-1
customMask.formattingPattern = maskSequence[currentMaskIndex]
var newText = customMask.formatString(string: newValue ?? "")
// if "12.34" < "$$.$$$"
if newText.characters.count < maskSequence[currentMaskIndex].characters.count {
//if not first AND "12.34" >= "$$.$"
let previousPatternIndex = currentMaskIndex - 1
if maskSequence.indices.contains(previousPatternIndex)
&& (newText.characters.count >= maskSequence[previousPatternIndex].characters.count) {
customMask.formattingPattern = maskSequence[currentMaskIndex]
newText = customMask.formatString(string: newValue ?? "")
}
}
self._text = newText
super.text = self._text
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
super.delegate = self
}
public override init(frame: CGRect) {
super.init(frame: frame)
super.delegate = self
}
public func setMaskSequence(maskSequence: [String]){
if(maskSequence.isEmpty || (maskSequence.count > 0 && (maskSequence.first?.isEmpty ?? true))){
customMask.formattingPattern = ""
self.maskSequence = [""]
return
}
self.maskSequence = sortArrayByLength(array: maskSequence);
currentMaskIndex = 0
customMask.formattingPattern = self.maskSequence[currentMaskIndex];
self.text = customMask.formatString(string: self.text!)
}
private func sortArrayByLength(array: [String]) -> Array<String>{
let sorted = array.sorted(by: {x, y -> Bool in x.characters.count < y.characters.count })
return sorted;
}
// MARK : UITextFieldDelegate
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return shouldChangeCharactersInRange(range: range, replacementString: string)
}
func shouldChangeCharactersInRange(range: NSRange, replacementString string: String) -> Bool {
//Check if backspace was pressed
//Detect backspace
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92 || range.length == 1) { //Backspace was pressed
if(currentMaskIndex > 0){
if((self.text!.characters.count-1) <= maskSequence[currentMaskIndex-1].characters.count){
currentMaskIndex -= 1
}
}else{
currentMaskIndex = 0
}
if self.maskSequence.indices.contains(currentMaskIndex){
self.customMask.formattingPattern = self.maskSequence[currentMaskIndex]
}else{
self.customMask.formattingPattern = ""
}
//remove last char
if let text = self.text, (self.text!.endIndex > self.text!.startIndex){
self.text = text.substring(to: text.index(before: text.endIndex))
}
self.text = customMask.formatString(string: self.text!)
}else{
//If mask is specified ( not maskSequence = [] or [""] )
if maskSequence.count > 0 && !maskSequence.first!.isEmpty{
//if text length is greater than currentMask length
//eg: "1234" > "$$$"
if((self.text!.characters.count+1) > maskSequence[currentMaskIndex].characters.count){
//if currentMask is not the last
if(currentMaskIndex < maskSequence.count-1){
currentMaskIndex += 1
self.customMask.formattingPattern = self.maskSequence[currentMaskIndex]
self.text = customMask.formatString(string: self.text!+string)
}
}
else{
self.text = customMask.formatStringWithRange(range: range, string: string)
}
}
//There is a mask
else{
self.text = self.text!.appending(string)
}
}
return false
}
}
| mit | 59245fbb05595444cf73e4c3424de613 | 37.153846 | 136 | 0.566532 | 4.691316 | false | false | false | false |
seuzl/iHerald | Herald/LibNavViewController.swift | 1 | 1121 | //
// LibNavViewController.swift
// 先声
//
// Created by Wangshuo on 14-9-5.
// Copyright (c) 2014年 WangShuo. All rights reserved.
//
import UIKit
class LibNavViewController: UIViewController {
@IBOutlet var jlhButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationItem.title = "本馆导航"
let color = UIColor(red: 96/255, green: 199/255, blue: 222/255, alpha: 1)
self.navigationController?.navigationBar.barTintColor = color
}
@IBAction func clickJLHButton(sender: AnyObject) {
let LibJLHNavVC = LibJLHNavViewController(nibName: "LibJLHNavViewController", bundle: nil)
self.navigationController!.pushViewController(LibJLHNavVC, animated: true)
}
@IBAction func clickSPLButton(sender: AnyObject) {
let LibSPLNavVC = LibSPLNavViewController(nibName: "LibSPLNavViewController", bundle: nil)
self.navigationController!.pushViewController(LibSPLNavVC, animated: true)
}
}
| mit | c16c374715ef5bf84bfc2fff6802e8a2 | 24.744186 | 98 | 0.671183 | 4.225191 | false | false | false | false |
mapsme/omim | iphone/Chart/Chart/ChartData/ChartPresentationData.swift | 5 | 7090 | import UIKit
public class ChartPresentationData {
private let chartData: IChartData
private var presentationLines: [ChartPresentationLine]
private let pathBuilder = ChartPathBuilder()
private let useFilter: Bool
let formatter: IFormatter
public init(_ chartData: IChartData, formatter: IFormatter, useFilter: Bool = false) {
self.chartData = chartData
self.useFilter = useFilter
self.formatter = formatter
presentationLines = chartData.lines.map { ChartPresentationLine($0, useFilter: useFilter) }
labels = chartData.xAxisValues.map { formatter.distanceString(from: $0) }
recalcBounds()
}
var linesCount: Int { chartData.lines.count }
var pointsCount: Int { chartData.xAxisValues.count }
var xAxisValues: [Double] { chartData.xAxisValues }
var type: ChartType { chartData.type }
var labels: [String]
var lower = CGFloat(Int.max)
var upper = CGFloat(Int.min)
func labelAt(_ point: CGFloat) -> String {
formatter.distanceString(from: xAxisValueAt(point))
}
func xAxisValueAt(_ point: CGFloat) -> Double {
let p1 = Int(floor(point))
let p2 = Int(ceil(point))
let v1 = chartData.xAxisValues[p1]
let v2 = chartData.xAxisValues[p2]
return v1 + (v2 - v1) * Double(point.truncatingRemainder(dividingBy: 1))
}
func lineAt(_ index: Int) -> ChartPresentationLine {
presentationLines[index]
}
private func recalcBounds() {
presentationLines.forEach { $0.aggregatedValues = [] }
pathBuilder.build(presentationLines, type: type)
var l = CGFloat(Int.max)
var u = CGFloat(Int.min)
presentationLines.forEach {
l = min($0.minY, l)
u = max($0.maxY, u)
}
lower = l
upper = u
}
}
class ChartPresentationLine {
private let chartLine: IChartLine
private let useFilter: Bool
var aggregatedValues: [CGFloat] = []
var minY: CGFloat = CGFloat(Int.max)
var maxY: CGFloat = CGFloat(Int.min)
var path = UIBezierPath()
var previewPath = UIBezierPath()
var values: [CGFloat]
var originalValues: [Int] { return chartLine.values }
var color: UIColor { return chartLine.color }
var name: String { return chartLine.name }
var type: ChartLineType { return chartLine.type }
init(_ chartLine: IChartLine, useFilter: Bool = false) {
self.chartLine = chartLine
self.useFilter = useFilter
if useFilter {
var filter = LowPassFilter(value: CGFloat(chartLine.values[0]), filterFactor: 0.8)
values = chartLine.values.map {
filter.update(newValue: CGFloat($0))
return filter.value
}
} else {
values = chartLine.values.map { CGFloat($0) }
}
}
}
protocol IChartPathBuilder {
func build(_ lines: [ChartPresentationLine])
func makeLinePath(line: ChartPresentationLine) -> UIBezierPath
func makePercentLinePath(line: ChartPresentationLine, bottomLine: ChartPresentationLine?) -> UIBezierPath
}
extension IChartPathBuilder {
func makeLinePreviewPath(line: ChartPresentationLine) -> UIBezierPath {
var filter = LowPassFilter(value: 0, filterFactor: 0.3)
let path = UIBezierPath()
let step = 5
let values = line.values.enumerated().compactMap { $0 % step == 0 ? $1 : nil }
for i in 0..<values.count {
let x = CGFloat(i * step)
let y = CGFloat(values[i] - line.minY)
if i == 0 {
filter.value = y
path.move(to: CGPoint(x: x, y: y))
} else {
filter.update(newValue: y)
path.addLine(to: CGPoint(x: x, y: filter.value))
}
}
return path
}
func makeLinePath(line: ChartPresentationLine) -> UIBezierPath {
let path = UIBezierPath()
let values = line.values
for i in 0..<values.count {
let x = CGFloat(i)
let y = CGFloat(values[i] - line.minY)
if i == 0 {
path.move(to: CGPoint(x: x, y: y))
} else {
path.addLine(to: CGPoint(x: x, y: y))
}
}
return path
}
func makePercentLinePreviewPath(line: ChartPresentationLine, bottomLine: ChartPresentationLine?) -> UIBezierPath {
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
var filter = LowPassFilter(value: 0, filterFactor: 0.3)
let step = 5
let aggregatedValues = line.aggregatedValues.enumerated().compactMap { $0 % step == 0 ? $1 : nil }
for i in 0..<aggregatedValues.count {
let x = CGFloat(i * step)
let y = aggregatedValues[i] - CGFloat(line.minY)
if i == 0 { filter.value = y } else { filter.update(newValue: y) }
path.addLine(to: CGPoint(x: x, y: filter.value))
}
path.addLine(to: CGPoint(x: aggregatedValues.count * step, y: 0))
path.close()
return path
}
func makePercentLinePath(line: ChartPresentationLine, bottomLine: ChartPresentationLine?) -> UIBezierPath {
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
let aggregatedValues = line.aggregatedValues
for i in 0..<aggregatedValues.count {
let x = CGFloat(i)
let y = aggregatedValues[i] - CGFloat(line.minY)
path.addLine(to: CGPoint(x: x, y: y))
}
path.addLine(to: CGPoint(x: aggregatedValues.count, y: 0))
path.close()
return path
}
}
struct LowPassFilter {
var value: CGFloat
let filterFactor: CGFloat
mutating func update(newValue: CGFloat) {
value = filterFactor * value + (1.0 - filterFactor) * newValue
}
}
class ChartPathBuilder {
private let builders: [ChartType: IChartPathBuilder] = [
.regular : LinePathBuilder(),
.percentage : PercentagePathBuilder()
]
func build(_ lines: [ChartPresentationLine], type: ChartType) {
builders[type]?.build(lines)
}
}
class LinePathBuilder: IChartPathBuilder {
func build(_ lines: [ChartPresentationLine]) {
lines.forEach {
$0.aggregatedValues = $0.values.map { CGFloat($0) }
if $0.type == .lineArea {
$0.minY = 0
for val in $0.values {
$0.maxY = max(val, $0.maxY)
}
$0.path = makePercentLinePath(line: $0, bottomLine: nil)
$0.previewPath = makePercentLinePreviewPath(line: $0, bottomLine: nil)
} else {
for val in $0.values {
$0.minY = min(val, $0.minY)
$0.maxY = max(val, $0.maxY)
}
$0.path = makeLinePath(line: $0)
$0.previewPath = makeLinePreviewPath(line: $0)
}
}
}
}
class PercentagePathBuilder: IChartPathBuilder {
func build(_ lines: [ChartPresentationLine]) {
lines.forEach {
$0.minY = 0
$0.maxY = CGFloat(Int.min)
}
for i in 0..<lines[0].values.count {
let sum = CGFloat(lines.reduce(0) { (r, l) in r + l.values[i] })
var aggrPercentage: CGFloat = 0
lines.forEach {
aggrPercentage += CGFloat($0.values[i]) / sum * 100
$0.aggregatedValues.append(aggrPercentage)
$0.maxY = max(round(aggrPercentage), CGFloat($0.maxY))
}
}
var prevLine: ChartPresentationLine? = nil
lines.forEach {
$0.path = makePercentLinePath(line: $0, bottomLine: prevLine)
$0.previewPath = makePercentLinePreviewPath(line: $0, bottomLine: prevLine)
prevLine = $0
}
}
}
| apache-2.0 | 453ab739466d7c0338b67f287a27c092 | 29.692641 | 116 | 0.64866 | 3.600813 | false | false | false | false |
CoderXiaoming/Ronaldo | SaleManager/SaleManager/Car/Controller/SAMShoppingCarController.swift | 1 | 31386 | //
// SAMShoppingCarController.swift
// SaleManager
//
// Created by apple on 16/11/9.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
import MJRefresh
///购物车CELL重用标识符
private let SAMShoppingCarListCellReuseIdentifier = "SAMShoppingCarListCellReuseIdentifier"
///购物车CELL标志正常图片
let SAMShoppingCarCellIndicaterNormalImage = UIImage(named: "shoppingCarSelectedButton_normal")
///购物车CELL标志选中图片
let SAMShoppingCarCellIndicaterSelectedImage = UIImage(named: "shoppingCarSelectedButton_selected")
class SAMShoppingCarController: UIViewController {
///单例
fileprivate static let carViewVC: SAMShoppingCarController = SAMShoppingCarController()
//MARK: - 对外提供的主单例单例方法
class func sharedInstanceMain() -> SAMShoppingCarController {
return carViewVC
}
//MARK: - viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
//初始化UI
setupUI()
//设置tableView
setupTableView()
}
//MARK: - 初始化UI
fileprivate func setupUI() {
//设置标题
navigationItem.title = "购物车"
//设置搜索框
searchBar.showsCancelButton = false
searchBar.placeholder = "产品名称\\备注内容"
//监听键盘弹出通知
NotificationCenter.default.addObserver(self, selector: #selector(SAMShoppingCarController.keyboardWillChangeFrame(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
//MARK: - 初始化tableView
fileprivate func setupTableView() {
//注册CELL
tableView.register(UINib.init(nibName: "SAMShoppingCarListCell", bundle: nil), forCellReuseIdentifier: SAMShoppingCarListCellReuseIdentifier)
//设置下拉
tableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(SAMShoppingCarController.loadNewInfo))
//设置行高
tableView.rowHeight = 74
}
//MARK: - viewDidAppear
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//刷新界面数据
tableView.mj_header.beginRefreshing()
}
//MARK: - 加载新数据
func loadNewInfo() {
//处理搜索框的状态
if searchBar.showsCancelButton {
searchBarCancelButtonClicked(searchBar)
}
//创建请求参数
let userIDStr = SAMUserAuth.shareUser()!.id!
let parameters = ["userID": userIDStr, "productIDName": ""]
//发送请求
SAMNetWorker.sharedNetWorker().get("getCartList.ashx", parameters: parameters, progress: nil, success: {[weak self] (Task, json) in
//设置全选,减样按钮不选中
self!.daHuoButton.isSelected = false
self!.jianYangButton.isSelected = false
//清空原先数据
self!.clearExpiredInfo()
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let count = dictArr?.count ?? 0
if count == 0 { //没有模型数据
//提示用户
let _ = SAMHUD.showMessage("暂无数据", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}else { //有数据模型
let arr = SAMShoppingCarListModel.mj_objectArray(withKeyValuesArray: dictArr)!
self!.listModels.addObjects(from: arr as [AnyObject])
}
//回到主线程
DispatchQueue.main.async(execute: {
//结束上拉
self!.tableView.mj_header.endRefreshing()
//刷新数据
self!.tableView.reloadData()
})
}) {[weak self] (Task, Error) in
//处理上拉
self!.tableView.mj_header.endRefreshing()
//提示用户
let _ = SAMHUD.showMessage("请检查网络", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
}
//MARK: - 清除过期数据
fileprivate func clearExpiredInfo() {
listModels.removeAllObjects()
selectedModels.removeAllObjects()
}
//MARK: - 对外提供的设置购物车数量的方法
func addOrMinusProductCountOne(_ add: Bool) {
//改变计数
var count = badgeCount
count = add ? count + 1 : count - 1
//判断计数
count = count > 0 ? count : 0
//记录数量
badgeCount = count
}
//MARK: - 修改结算,删除按钮的文字
fileprivate func checkAllButtonsState() {
//获取数组数量
let selectedCount = selectedModels.count
//设置按钮文字
let deleateStr = String(format: "删除(%d)", selectedCount)
let orderStr = String(format: "下单(%d)", selectedCount)
deleateButton.setTitle(deleateStr, for: UIControlState())
orderButton.setTitle(orderStr, for: UIControlState())
//根据 选中数量 和 是否在搜索状态 设置按钮状态
if selectedCount != 0 && !isSearch {
deleateButton.isEnabled = true
orderButton.isEnabled = true
}else {
deleateButton.isEnabled = false
orderButton.isEnabled = false
}
//根据源数组总数设置全选按钮状态
let allCount = listModels.count
if allCount != 0 && !isSearch {
daHuoButton.isEnabled = true
jianYangButton.isEnabled = true
}else {
daHuoButton.isEnabled = false
jianYangButton.isEnabled = false
}
}
//MARK: - 键盘弹出调用的方法
func keyboardWillChangeFrame(_ notification: Notification) {
//获取动画时长
let animDuration = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
//键盘终点frame
let endKeyboardFrameStr = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"]
let endKeyboardEndFrame = (endKeyboardFrameStr! as AnyObject).cgRectValue
let endKeyboardEndY = endKeyboardEndFrame?.origin.y
if endKeyboardEndY == ScreenH { //键盘即将隐藏
UIView.animate(withDuration: animDuration, animations: {
self.bottomToolBar.transform = CGAffineTransform.identity
}, completion: { (_) in
})
}else { //键盘即将展示
//计算形变
let transformY = tabBarController!.tabBar.bounds.height - (endKeyboardEndFrame?.height)!
UIView.animate(withDuration: animDuration, animations: {
self.bottomToolBar.transform = CGAffineTransform(translationX: 0, y: transformY)
}, completion: { (_) in
})
}
}
//MARK: - 属性懒加载
/// tabbar右上角数字
fileprivate var badgeCount: Int = 0 {
didSet{
//设置badgeValue
let tabbarItem = tabBarController!.tabBar.items![3] as UITabBarItem
if badgeCount == 0 {
tabbarItem.badgeValue = nil
}else {
tabbarItem.badgeValue = String(format: "%d", badgeCount)
}
}
}
///源模型数组
fileprivate let listModels = NSMutableArray()
///选中的模型数组
fileprivate let selectedModels = NSMutableArray()
///记录当前是否在搜索
fileprivate var isSearch: Bool = false {
didSet{
self.daHuoButton.isEnabled = !isSearch
self.jianYangButton.isEnabled = !isSearch
}
}
///符合搜索结果模型数组
fileprivate let searchResultModels = NSMutableArray()
///添加产品的动画layer数组
fileprivate lazy var addProductAnimLayers = [CALayer]()
///购物车选择控件
fileprivate var productOperationView: SAMProductOperationView?
///展示购物车时,主界面添加的蒙版
fileprivate lazy var productOperationMaskView: UIView = {
let maskView = UIView(frame: UIScreen.main.bounds)
maskView.backgroundColor = UIColor.black
maskView.alpha = 0.0
//添加手势
let tap = UITapGestureRecognizer(target: self, action: #selector(SAMShoppingCarController.hideProductOperationViewWhenMaskViewDidClick))
maskView.addGestureRecognizer(tap)
return maskView
}()
//MARK: - XIB链接点击事件处理
@IBAction func daHuoBtnClick(_ sender: UIButton) {
//获取更改后的选中状态
let selected = !sender.isSelected
//改变按钮状态
sender.isSelected = selected
listModels.enumerateObjects({ (obj, index, _) in
let model = obj as! SAMShoppingCarListModel
if model.countP != 0 {
model.selected = selected
if selected {
if !selectedModels.contains(model) {
selectedModels.add(model)
}
}else {
selectedModels.remove(model)
}
}
})
//更新tableView
tableView.reloadData()
}
@IBAction func jianYangBtnClick(_ sender: UIButton) {
//获取更改后的选中状态
let selected = !sender.isSelected
//改变按钮状态
sender.isSelected = selected
listModels.enumerateObjects({ (obj, index, _) in
let model = obj as! SAMShoppingCarListModel
if model.countP == 0 {
model.selected = selected
if selected {
if !selectedModels.contains(model) {
selectedModels.add(model)
}
}else {
selectedModels.remove(model)
}
}
})
//更新tableView
tableView.reloadData()
}
@IBAction func deleteBtnClick(_ sender: UIButton) {
//创建 UIAlertController
let totalCount = listModels.count
let deleateCount = selectedModels.count
var alertMessage: String
if deleateCount == totalCount {
alertMessage = "是否清空购物车?"
}else {
alertMessage = String(format: "是否删除这%d条?", deleateCount)
}
let alertVC = UIAlertController(title: alertMessage, message: nil, preferredStyle: .alert)
//添加两个按钮
alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
}))
alertVC.addAction(UIAlertAction(title: "确定", style: .destructive, handler: { (_) in
//设置全选按钮状态
self.daHuoButton.isSelected = false
self.jianYangButton.isSelected = false
let deleateArr = self.selectedModels.mutableCopy()
//从 源模型数组 和 选中数组 中删除选中模型
self.selectedModels.removeAllObjects()
//遍历删除数组
(deleateArr as AnyObject).enumerateObjects { (obj, index, _) in
//获取模型 和 源数组中对应的编号
let model = obj as! SAMShoppingCarListModel
let orignalIndex = self.listModels.index(of: model)
//从源数组中删除对应模型
self.listModels.removeObject(at: orignalIndex)
//动画删除对应组
self.tableView.deleteSections(IndexSet.init(integer: orignalIndex), with: .left)
//异步发送删除请求
let parameters = ["id": model.id]
SAMNetWorker.sharedNetWorker().post("CartDelete.ashx", parameters: parameters, progress: nil, success: { (task, Json) in
}, failure: { (task, error) in
})
}
}))
//展示控制器
present(alertVC, animated: true, completion: nil)
}
@IBAction func orderBtnClick(_ sender: UIButton) {
///创建需要的模型数组
var models = [SAMShoppingCarListModel]()
selectedModels.enumerateObjects({ (obj, index, _) in
let model = obj as! SAMShoppingCarListModel
models.append(model)
})
let buildOrderVC = SAMOrderOwedOperationController.buildOrder(productModels: models, type: .buildOrder)
//判断当前导航栏是否隐藏
if navigationController!.isNavigationBarHidden { //如果当前导航栏隐藏,直接复制取消按钮点击代码
//结束搜索框编辑状态
searchBar.text = ""
searchBar.resignFirstResponder()
//执行结束动画
UIView.animate(withDuration: 0.3, animations: {
self.navigationController!.setNavigationBarHidden(false, animated: false)
self.searchBar.transform = CGAffineTransform.identity
self.tableView.transform = CGAffineTransform.identity
self.searchBar.showsCancelButton = false
}, completion: { (_) in
self.isSearch = false
self.deleateButton.isEnabled = true
self.orderButton.isEnabled = true
self.tableView.reloadData()
self.navigationController!.pushViewController(buildOrderVC, animated: true)
})
}else {
navigationController!.pushViewController(buildOrderVC, animated: true)
}
}
//MARK: - XIB链接属性
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var bottomToolBar: UIView!
@IBOutlet weak var daHuoButton: UIButton!
@IBOutlet weak var jianYangButton: UIButton!
@IBOutlet weak var orderButton: UIButton!
@IBOutlet weak var deleateButton: UIButton!
//MARK: - 其他方法
fileprivate init() {
super.init(nibName: nil, bundle: nil)
}
fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func loadView() {
view = Bundle.main.loadNibNamed("SAMShoppingCarController", owner: self, options: nil)![0] as! UIView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
//MARK: - tableView数据源方法 UITableViewDataSource
extension SAMShoppingCarController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
//检查所有按钮的状态
checkAllButtonsState()
//获取总数组数值,赋值badgeValue
let count = listModels.count
badgeCount = count
//根据是否是搜索状态返回不同的数据
let sourceArr = isSearch ? searchResultModels : listModels
return sourceArr.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//获取重用Cell
let cell = tableView.dequeueReusableCell(withIdentifier: SAMShoppingCarListCellReuseIdentifier) as! SAMShoppingCarListCell
//根据是否是搜索状态返回不同的数据
let sourceArr = isSearch ? searchResultModels : listModels
cell.listModel = sourceArr[indexPath.section] as? SAMShoppingCarListModel
return cell
}
}
//MARK: - tableView代理 UITableViewDelegate
extension SAMShoppingCarController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//调用下面方法
tableViewSelectOrDeselectCellAt(indexPath)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
//调用下面方法
tableViewSelectOrDeselectCellAt(indexPath)
}
//选中cell或取消选中cell集中调用
fileprivate func tableViewSelectOrDeselectCellAt(_ indexPath: IndexPath) {
//结束搜索框编辑状态
searchBar.endEditing(true)
//取出cell
let cell = tableView.cellForRow(at: indexPath) as! SAMShoppingCarListCell
//取出模型
let model = cell.listModel!
//更改模型记录数据
model.selected = !model.selected
if model.selected { //添加数据模型的情况下
//添加到选中数组中
selectedModels.add(model)
//执行添加动画
let productImageViewConvertFrame = cell.convert(cell.productImageView.frame, to: view)
addProductAnim(cell.productImageView.image!, ImageFrame: productImageViewConvertFrame)
}else { //删除数据模型的情况下
//从选中数组中删除
selectedModels.remove(model)
}
//刷新数据
tableView.reloadData()
}
//添加产品时的动画
fileprivate func addProductAnim(_ productImage: UIImage, ImageFrame: CGRect) {
/****************** layer路线动画 ******************/
let pathAnimation = CAKeyframeAnimation(keyPath: "position")
let path = UIBezierPath()
//计算各点
let imageViewCenterX = ImageFrame.origin.x + ImageFrame.width * 0.5
let imageViewCenterY = ImageFrame.origin.y + ImageFrame.height * 0.5
let orderButtonConvertFrame = bottomToolBar.convert(orderButton.frame, to: view)
let startPoint = CGPoint(x: imageViewCenterX, y: imageViewCenterY)
var endPoint = orderButtonConvertFrame.origin
endPoint.x = endPoint.x + 20
let controlPoint = CGPoint(x: (endPoint.x - startPoint.x) * 0.5 + 100, y: startPoint.y - 50)
//连线
path.move(to: startPoint)
path.addQuadCurve(to: endPoint, controlPoint: controlPoint)
pathAnimation.path = path.cgPath
pathAnimation.rotationMode = kCAAnimationRotateAuto
/****************** layer缩小动画 ******************/
let narrowAnimation = CABasicAnimation(keyPath: "transform.scale")
narrowAnimation.fromValue = 1
narrowAnimation.toValue = 0.4
narrowAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
//组合成组动画
let group = CAAnimationGroup()
group.animations = [pathAnimation, narrowAnimation]
group.duration = 0.5
group.isRemovedOnCompletion = false
group.fillMode = kCAFillModeForwards
group.delegate = self
//设置动画layer
let layer = CALayer()
layer.contentsGravity = kCAGravityResizeAspectFill
layer.cornerRadius = 15
layer.masksToBounds = true
layer.frame = ImageFrame
layer.contents = productImage.cgImage
view.layer.addSublayer(layer)
layer.add(group, forKey: "group")
addProductAnimLayers.append(layer)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//结束搜索框编辑状态
searchBar.endEditing(true)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 10
}else {
return 5
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == (listModels.count - 1) {
return 10
}else {
return 5
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//取出cell
let cell = tableView.cellForRow(at: indexPath) as! SAMShoppingCarListCell
//取出对应模型
let model = cell.listModel!
/******************* 查询按钮 ********************/
let equiryAction = UITableViewRowAction(style: .normal, title: "查询") { (action, indexPath) in
let stockVC = SAMStockViewController.instance(shoppingCarListModel: model, QRCodeScanStr: nil, type: .requestStock)
self.navigationController?.pushViewController(stockVC, animated: true)
}
equiryAction.backgroundColor = UIColor(red: 0, green: 255 / 255.0, blue: 127 / 255.0, alpha: 1.0)
/******************* 编辑按钮 ********************/
let editAction = UITableViewRowAction(style: .default, title: "编辑") { (action, indexPath) in
self.showShoppingCar(editModel: model)
}
editAction.backgroundColor = customBlueColor
//操作数组
return[editAction, equiryAction]
}
}
//MARK: - 搜索框代理UISearchBarDelegate
extension SAMShoppingCarController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//取消全选,减样按钮选中状态
daHuoButton.isSelected = false
jianYangButton.isSelected = false
//清空搜索结果数组,并赋值
searchResultModels.removeAllObjects()
searchResultModels.addObjects(from: listModels as [AnyObject])
//获取搜索字符串
let searchStr = NSString(string: searchText.lxm_stringByTrimmingWhitespace()!)
if searchStr.length > 0 {
//记录正在搜索
isSearch = true
//获取搜索字符串数组
let searchItems = searchStr.components(separatedBy: " ")
var andMatchPredicates = [NSPredicate]()
for item in searchItems {
let searchString = item as NSString
//productIDName搜索谓语
var lhs = NSExpression(forKeyPath: "productIDName")
let rhs = NSExpression(forConstantValue: searchString)
let firstPredicate = NSComparisonPredicate(leftExpression: lhs, rightExpression: rhs, modifier: .direct, type:
.contains, options: .caseInsensitive)
//memoInfo搜索谓语
lhs = NSExpression(forKeyPath: "memoInfo")
let secondPredicate = NSComparisonPredicate(leftExpression: lhs, rightExpression: rhs, modifier: .direct, type:
.contains, options: .caseInsensitive)
let orMatchPredicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: [firstPredicate, secondPredicate])
andMatchPredicates.append(orMatchPredicate)
}
let finalCompoundPredicate = NSCompoundPredicate.init(andPredicateWithSubpredicates: andMatchPredicates)
//存储搜索结果
let arr = searchResultModels.filtered(using: finalCompoundPredicate)
searchResultModels.removeAllObjects()
searchResultModels.addObjects(from: arr)
}else {
//记录没有搜索
isSearch = false
}
//刷新tableView
tableView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
//取消全选,减样按钮选中状态
daHuoButton.isSelected = false
jianYangButton.isSelected = false
//设置删除,下单按钮不可用
deleateButton.isEnabled = false
orderButton.isEnabled = false
//执行准备动画
UIView.animate(withDuration: 0.3, animations: {
self.navigationController!.setNavigationBarHidden(true, animated: true)
}, completion: { (_) in
UIView.animate(withDuration: 0.2, animations: {
searchBar.transform = CGAffineTransform(translationX: 0, y: 20)
self.tableView.transform = CGAffineTransform(translationX: 0, y: 20)
searchBar.showsCancelButton = true
})
})
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
//结束搜索框编辑状态
searchBar.text = ""
searchBar.resignFirstResponder()
//执行结束动画
UIView.animate(withDuration: 0.3, animations: {
self.navigationController!.setNavigationBarHidden(false, animated: false)
searchBar.transform = CGAffineTransform.identity
self.tableView.transform = CGAffineTransform.identity
searchBar.showsCancelButton = false
}, completion: { (_) in
//结束搜索状态
self.isSearch = false
//设置删除,下单按钮可用
self.deleateButton.isEnabled = true
self.orderButton.isEnabled = true
//刷新数据
self.tableView.reloadData()
})
}
//MARK: - 点击键盘搜索按钮调用
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBarCancelButtonClicked(searchBar)
}
}
//MARK: - 动画代理CAAnimationDelegate
extension SAMShoppingCarController: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
let layer = addProductAnimLayers[0]
if anim == layer.animation(forKey: "group") {
//移除动画
layer.removeAllAnimations()
//移除动画图层
layer.removeFromSuperlayer()
//从图层数组中移除
addProductAnimLayers.remove(at: 0)
}
}
}
//MARK: - 购物车代理SAMProductOperationViewDelegate
extension SAMShoppingCarController: SAMProductOperationViewDelegate {
func operationViewDidClickDismissButton() {
//隐藏购物车
hideProductOperationView(false)
}
func operationViewAddOrEditProductSuccess(_ productImage: UIImage, postShoppingCarListModelSuccess: Bool) {
//隐藏购物车
hideProductOperationView(true)
}
}
//MARK: - 购物车相关方法
extension SAMShoppingCarController {
//view的第一步动画
fileprivate func firstTran() -> CATransform3D {
var transform = CATransform3DIdentity
transform.m24 = -1/2000
transform = CATransform3DScale(transform, 0.9, 0.9, 1)
return transform
}
//view的第二步动画
fileprivate func secondTran() -> CATransform3D {
var transform = CATransform3DIdentity
transform = CATransform3DTranslate(transform, 0, self.view.frame.size.height * (-0.08), 0)
transform = CATransform3DScale(transform, 0.8, 0.8, 1)
return transform
}
//点击maskView隐藏购物车控件
func hideProductOperationViewWhenMaskViewDidClick() {
hideProductOperationView(false)
}
//展示购物车
func showShoppingCar(editModel: SAMShoppingCarListModel) {
//设置购物车控件的目标frame
self.productOperationView = SAMProductOperationView.operationViewWillShow(nil, editProductModel: editModel, isFromeCheckOrder: false, postModelAfterOperationSuccess: false)
self.productOperationView!.delegate = self
self.productOperationView!.frame = CGRect(x: 0, y: ScreenH, width: ScreenW, height: 350)
var rect = self.productOperationView!.frame
rect.origin.y = ScreenH - rect.size.height
//添加背景View
self.tabBarController!.view.addSubview(self.productOperationMaskView)
KeyWindow?.addSubview(self.productOperationView!)
//动画展示购物车控件
UIView.animate(withDuration: 0.5, animations: {
self.productOperationView!.frame = rect
})
//动画移动背景View
UIView.animate(withDuration: 0.25, animations: {
//执行第一步动画
self.productOperationMaskView.alpha = 0.5
self.tabBarController!.view.layer.transform = self.firstTran()
}, completion: { (_) in
//执行第二步动画
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = self.secondTran()
}, completion: { (_) in
})
})
}
//隐藏购物车控件
func hideProductOperationView(_ editSuccess: Bool) {
//结束 tableView 编辑状态
self.tableView.isEditing = false
//设置购物车目标frame
var rect = self.productOperationView!.frame
rect.origin.y = ScreenH
//动画隐藏购物车控件
UIView.animate(withDuration: 0.5, animations: {
self.productOperationView!.frame = rect
})
//动画展示主View
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = self.firstTran()
self.productOperationMaskView.alpha = 0.0
}, completion: { (_) in
//移除蒙板
self.productOperationMaskView.removeFromSuperview()
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = CATransform3DIdentity
}, completion: { (_) in
//移除购物车
self.productOperationView!.removeFromSuperview()
//调用成功添加购物车的动画
if editSuccess {
self.tableView.mj_header.beginRefreshing()
}
})
})
}
}
| apache-2.0 | 24092a6691c3bec58fba2df7b5f56202 | 33.066745 | 193 | 0.580586 | 5.173929 | false | false | false | false |
oursky/Redux | Pod/Classes/types.swift | 1 | 2225 | //
// types.swift
// Redux.swift
//
// Created by Mark Wise on 11/6/15.
// Copyright © 2015 InstaJams. All rights reserved.
//
import Foundation
public typealias ActionCreator = (_ args: Any...) -> ReduxAction
public typealias ActionType = String
public typealias ReduxAppState = KeyValueEqutable
public typealias DispatchFunction = (_ action: ReduxAction) -> Void
public typealias FunctionWithArgs = (_ args: Any...) -> Void
public typealias Listener = () -> Void
public typealias Reducer = (_ previousState: Any, _ action: ReduxAction) -> Any
public typealias ReduxState = AnyEquatable
public protocol AnyEquatable {
func equals(_ otherObject: AnyEquatable) -> Bool
}
public extension AnyEquatable where Self: Equatable {
// otherObject could also be 'Any'
func equals(_ otherObject: AnyEquatable) -> Bool {
if let otherAsSelf = otherObject as? Self {
return otherAsSelf == self
}
return false
}
}
public protocol KeyValueEqutable {
func get(_ key: String) -> AnyEquatable?
mutating func set(_ key: String, value: AnyEquatable)
}
public enum ActionTypes: ReduxActionType {
case `init`
}
public protocol ReduxActionType {}
public struct ReduxAction {
public var payload: ReduxActionType
public init(payload: ReduxActionType) {
self.payload = payload
}
}
open class ReduxStore {
open let dispatch: DispatchFunction
open let getState: () -> ReduxState
open let replaceReducer: (_ nextReducer: @escaping Reducer) -> Void
open let subscribe: (_ listener: @escaping Listener) -> () -> Void
public init(
dispatch: @escaping DispatchFunction,
getState: @escaping () -> ReduxState,
replaceReducer: @escaping (_ nextReducer: @escaping Reducer) -> Void,
subscribe: @escaping (_ listener: @escaping Listener) -> () -> Void
) {
self.dispatch = dispatch
self.getState = getState
self.replaceReducer = replaceReducer
self.subscribe = subscribe
}
}
public extension ReduxStore {
func getAppState() -> ReduxAppState? {
return getState() as? ReduxAppState
}
}
public enum ReduxSwiftError: Error {
case reducerDispatchError
}
| mit | c60859c59455c3e0fea6114bb199693b | 26.121951 | 79 | 0.679856 | 4.412698 | false | false | false | false |
mohsinalimat/SpringIndicator | SpringIndicator/SpringIndicator.swift | 1 | 19919 | //
// SpringIndicator.swift
// SpringIndicator
//
// Created by Kyohei Ito on 2015/03/06.
// Copyright (c) 2015年 kyohei_ito. All rights reserved.
//
import UIKit
@IBDesignable
public class SpringIndicator: UIView {
private typealias Me = SpringIndicator
private static let LotateAnimationKey = "rotateAnimation"
private static let ExpandAnimationKey = "expandAnimation"
private static let ContractAnimationKey = "contractAnimation"
private static let GroupAnimationKey = "groupAnimation"
private static let StrokeTiming = [0, 0.3, 0.5, 0.7, 1]
private static let StrokeValues = [0, 0.1, 0.5, 0.9, 1]
private static let DispatchQueueLabelTimer = "SpringIndicator.Timer.Thread"
private static let timerQueue = dispatch_queue_create(DispatchQueueLabelTimer, DISPATCH_QUEUE_CONCURRENT)
private static let timerRunLoop = NSRunLoop.currentRunLoop()
private static let timerPort = NSPort()
public override class func initialize() {
super.initialize()
dispatch_async(timerQueue) {
self.timerRunLoop.addPort(self.timerPort, forMode: NSRunLoopCommonModes)
self.timerRunLoop.run()
}
}
public override class func finalize() {
super.finalize()
timerPort.invalidate()
}
private var strokeTimer: NSTimer? {
didSet {
oldValue?.invalidate()
}
}
private var rotateThreshold = (M_PI / M_PI_2 * 2) - 1
private var indicatorView: UIView
private var animationCount: Double = 0
private var pathLayer: CAShapeLayer? {
didSet {
oldValue?.removeAllAnimations()
oldValue?.removeFromSuperlayer()
}
}
/// Start the animation automatically in drawRect.
@IBInspectable public var animating: Bool = false
/// Line thickness.
@IBInspectable public var lineWidth: CGFloat = 3
/// Line Color. Default is gray.
@IBInspectable public var lineColor: UIColor = UIColor.grayColor()
/// Cap style. Options are `round' and `square'. true is `round`. Default is false
@IBInspectable public var lineCap: Bool = false
/// Rotation duration. Default is 1.5
@IBInspectable public var lotateDuration: Double = 1.5
/// Stroke duration. Default is 0.7
@IBInspectable public var strokeDuration: Double = 0.7
/// It is called when finished stroke. from subthread.
public var intervalAnimationsHandler: ((SpringIndicator) -> Void)?
private var stopAnimationsHandler: ((SpringIndicator) -> Void)?
public override init(frame: CGRect) {
indicatorView = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
super.init(frame: frame)
indicatorView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
addSubview(indicatorView)
backgroundColor = UIColor.clearColor()
}
public required init(coder aDecoder: NSCoder) {
indicatorView = UIView()
super.init(coder: aDecoder)
indicatorView.frame = bounds
indicatorView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
addSubview(indicatorView)
}
public override func drawRect(rect: CGRect) {
super.drawRect(rect)
if animating {
startAnimation()
}
}
/// During stroke animation is true.
public func isSpinning() -> Bool {
return pathLayer?.animationForKey(Me.ContractAnimationKey) != nil || pathLayer?.animationForKey(Me.GroupAnimationKey) != nil
}
private func incrementAnimationCount() -> Double {
animationCount++
if animationCount > rotateThreshold {
animationCount = 0
}
return animationCount
}
private func nextRotatePath(count: Double) -> UIBezierPath {
animationCount = count
let start = CGFloat(M_PI_2 * (0 - count))
let end = CGFloat(M_PI_2 * (rotateThreshold - count))
let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let radius = max(bounds.width, bounds.height) / 2
var arc = UIBezierPath(arcCenter: center, radius: radius, startAngle: start, endAngle: end, clockwise: true)
arc.lineWidth = 0
return arc
}
private func rotateLayer() -> CAShapeLayer {
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = lineColor.CGColor
shapeLayer.fillColor = nil
shapeLayer.lineWidth = lineWidth
shapeLayer.lineCap = lineCap ? kCALineCapRound : kCALineCapSquare
return shapeLayer
}
private func nextStrokeLayer(count: Double) -> CAShapeLayer {
let shapeLayer = rotateLayer()
shapeLayer.path = nextRotatePath(count).CGPath
return shapeLayer
}
}
// MARK: - Animation
public extension SpringIndicator {
/// If start from a state in spread is True.
public func startAnimation(expand: Bool = false) {
stopAnimationsHandler = nil
if isSpinning() {
return
}
let animation = lotateAnimation(lotateDuration)
indicatorView.layer.addAnimation(animation, forKey: Me.LotateAnimationKey)
strokeTransaction(expand)
let timer = nextStrokeTimer(expand)
setStrokeTimer(timer)
}
/// true is wait for stroke animation.
public func stopAnimation(waitAnimation: Bool, completion: ((SpringIndicator) -> Void)? = nil) {
if waitAnimation {
stopAnimationsHandler = { indicator in
indicator.stopAnimation(false, completion: completion)
}
} else {
strokeTimer = nil
stopAnimationsHandler = nil
indicatorView.layer.removeAllAnimations()
pathLayer?.strokeEnd = 0
pathLayer = nil
if NSThread.currentThread().isMainThread {
completion?(self)
} else {
dispatch_async(dispatch_get_main_queue()) {
completion?(self)
}
}
}
}
private func strokeTransaction(expand: Bool) {
let count = nextAnimationCount(expand)
if let layer = pathLayer {
layer.removeAllAnimations()
layer.path = nextRotatePath(count).CGPath
layer.strokeColor = lineColor.CGColor
layer.lineWidth = lineWidth
} else {
let shapeLayer = nextStrokeLayer(count)
pathLayer = shapeLayer
indicatorView.layer.addSublayer(shapeLayer)
}
let animation = nextStrokeAnimation(expand)
let animationKey = nextAnimationKey(expand)
pathLayer?.addAnimation(animation, forKey: animationKey)
}
// MARK: stroke properties
private func nextStrokeTimer(expand: Bool) -> NSTimer {
let animationKey = nextAnimationKey(expand)
if expand {
return createTimer(timeInterval: strokeDuration, userInfo: animationKey, repeats: false)
} else {
return createTimer(timeInterval: strokeDuration * 2, userInfo: animationKey, repeats: true)
}
}
private func nextAnimationKey(expand: Bool) -> String {
return expand ? Me.ContractAnimationKey : Me.GroupAnimationKey
}
private func nextAnimationCount(expand: Bool) -> Double {
return expand ? 0 : incrementAnimationCount()
}
private func nextStrokeAnimation(expand: Bool) -> CAAnimation {
return expand ? contractAnimation(strokeDuration) : groupAnimation(strokeDuration)
}
// MARK: animations
private func lotateAnimation(duration: CFTimeInterval) -> CAPropertyAnimation {
let anim = CABasicAnimation(keyPath: "transform.rotation.z")
anim.duration = duration
anim.repeatCount = HUGE
anim.fromValue = -(M_PI + M_PI_4)
anim.toValue = M_PI - M_PI_4
return anim
}
private func groupAnimation(duration: CFTimeInterval) -> CAAnimationGroup {
let expand = expandAnimation(duration)
expand.beginTime = 0
let contract = contractAnimation(duration)
contract.beginTime = duration
let group = CAAnimationGroup()
group.animations = [expand, contract]
group.duration = duration * 2
group.fillMode = kCAFillModeForwards
group.removedOnCompletion = false
return group
}
private func contractAnimation(duration: CFTimeInterval) -> CAPropertyAnimation {
let anim = CAKeyframeAnimation(keyPath: "strokeStart")
anim.duration = duration
anim.keyTimes = Me.StrokeTiming
anim.values = Me.StrokeValues
anim.fillMode = kCAFillModeForwards
anim.removedOnCompletion = false
return anim
}
private func expandAnimation(duration: CFTimeInterval) -> CAPropertyAnimation {
let anim = CAKeyframeAnimation(keyPath: "strokeEnd")
anim.duration = duration
anim.keyTimes = Me.StrokeTiming
anim.values = Me.StrokeValues
return anim
}
}
// MARK: - Timer
internal extension SpringIndicator {
private func createTimer(timeInterval ti: NSTimeInterval, userInfo: AnyObject?, repeats yesOrNo: Bool) -> NSTimer {
return NSTimer(timeInterval: ti, target: self, selector: Selector("onStrokeTimer:"), userInfo: userInfo, repeats: yesOrNo)
}
private func setStrokeTimer(timer: NSTimer) {
strokeTimer = timer
Me.timerRunLoop.addTimer(timer, forMode: NSRunLoopCommonModes)
}
func onStrokeTimer(timer: NSTimer!) {
stopAnimationsHandler?(self)
intervalAnimationsHandler?(self)
if isSpinning() == false {
return
}
if (timer?.userInfo as? String) == Me.ContractAnimationKey {
let timer = createTimer(timeInterval: strokeDuration * 2, userInfo: Me.GroupAnimationKey, repeats: true)
setStrokeTimer(timer)
}
strokeTransaction(false)
}
}
// MARK: - Stroke
public extension SpringIndicator {
/// between 0.0 and 1.0.
public func strokeRatio(ratio: CGFloat) {
if ratio <= 0 {
pathLayer = nil
} else if ratio >= 1 {
strokeValue(1)
} else {
strokeValue(ratio)
}
}
private func strokeValue(value: CGFloat) {
if pathLayer == nil {
let shapeLayer = nextStrokeLayer(0)
pathLayer = shapeLayer
indicatorView.layer.addSublayer(shapeLayer)
}
CATransaction.begin()
CATransaction.setDisableActions(true)
pathLayer?.strokeStart = 0
pathLayer?.strokeEnd = value
CATransaction.commit()
}
}
// MARK: - Refresher
public extension SpringIndicator {
public class Refresher: UIControl {
private typealias Me = Refresher
private static let ObserverOffsetKeyPath = "contentOffset"
private static let ScaleAnimationKey = "scaleAnimation"
private static let DefaultContentHeight: CGFloat = 60
private var RefresherContext = ""
private var initialInsetTop: CGFloat = 0
public let indicator = SpringIndicator(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
public private(set) var refreshing: Bool = false
public private(set) var targetView: UIScrollView?
deinit {
indicator.stopAnimation(false)
}
public convenience init() {
self.init(frame: CGRect.zeroRect)
}
override init(var frame: CGRect) {
super.init(frame: frame)
setupIndicator()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupIndicator()
}
public override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = UIColor.clearColor()
userInteractionEnabled = false
autoresizingMask = .FlexibleWidth | .FlexibleBottomMargin
if let superview = superview {
frame.size.height = Me.DefaultContentHeight
frame.size.width = superview.bounds.width
center.x = superview.center.x
if let scrollView = superview as? UIScrollView {
initialInsetTop = scrollView.contentInset.top
}
}
}
public override func willMoveToSuperview(newSuperview: UIView!) {
super.willMoveToSuperview(newSuperview)
targetView = newSuperview as? UIScrollView
addObserver()
}
weak var target: AnyObject?
public override func addTarget(target: AnyObject?, action: Selector, forControlEvents controlEvents: UIControlEvents) {
super.addTarget(target, action: action, forControlEvents: controlEvents)
self.target = target
}
public override func removeTarget(target: AnyObject?, action: Selector, forControlEvents controlEvents: UIControlEvents) {
super.removeTarget(target, action: action, forControlEvents: controlEvents)
self.target = nil
}
public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if let scrollView = object as? UIScrollView {
if target == nil {
removeObserver()
targetView = nil
return
}
if bounds.height <= 0 {
return
}
frame.origin.y = scrollOffset(scrollView)
if indicator.isSpinning() {
return
}
if refreshing && scrollView.dragging == false {
refreshStart(scrollView)
return
}
let ratio = scrollRatio(scrollView)
refreshing = ratio >= 1
indicator.strokeRatio(ratio)
rotateRatio(ratio)
}
}
private func setupIndicator() {
indicator.lineWidth = 2
indicator.lotateDuration = 1
indicator.strokeDuration = 0.5
indicator.center = center
indicator.autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleTopMargin | .FlexibleBottomMargin
addSubview(indicator)
}
private func addObserver() {
targetView?.addObserver(self, forKeyPath: Me.ObserverOffsetKeyPath, options: .New, context: &RefresherContext)
}
private func removeObserver() {
targetView?.removeObserver(self, forKeyPath: Me.ObserverOffsetKeyPath, context: &RefresherContext)
}
private func notObserveBlock(block: (() -> Void)) {
removeObserver()
block()
addObserver()
}
private func scrollOffset(scrollView: UIScrollView) -> CGFloat {
var offsetY = scrollView.contentOffset.y
offsetY += initialInsetTop
return offsetY
}
private func scrollRatio(scrollView: UIScrollView) -> CGFloat {
var offsetY = scrollOffset(scrollView)
offsetY += frame.size.height - indicator.frame.size.height
if offsetY > 0 {
offsetY = 0
}
return abs(offsetY / bounds.height)
}
private func rotateRatio(ratio: CGFloat) {
let value = max(min(ratio, 1), 0)
CATransaction.begin()
CATransaction.setDisableActions(true)
indicator.indicatorView.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI - M_PI_4) * value, 0, 0, 1)
CATransaction.commit()
}
}
}
// MARK: - Refresher start
private extension SpringIndicator.Refresher {
private func refreshStart(scrollView: UIScrollView) {
sendActionsForControlEvents(.ValueChanged)
indicator.layer.addAnimation(refreshStartAnimation(), forKey: Me.ScaleAnimationKey)
indicator.startAnimation(expand: true)
let insetTop = initialInsetTop + bounds.height
notObserveBlock {
scrollView.contentInset.top = insetTop
}
scrollView.contentOffset.y -= insetTop - initialInsetTop
}
private func refreshStartAnimation() -> CAPropertyAnimation {
let anim = CABasicAnimation(keyPath: "transform.scale")
anim.duration = 0.1
anim.repeatCount = 1
anim.autoreverses = true
anim.fromValue = 1
anim.toValue = 1.3
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
return anim
}
}
// MARK: - Refresher end
public extension SpringIndicator.Refresher {
/// Must be explicitly called when the refreshing has completed
public func endRefreshing() {
refreshing = false
if let scrollView = superview as? UIScrollView {
let insetTop: CGFloat
if scrollView.superview?.superview == nil {
insetTop = 0
} else {
insetTop = initialInsetTop
}
if scrollView.contentInset.top > insetTop {
var completionBlock: (() -> Void) = {
scrollView.contentInset.top = insetTop
self.indicator.stopAnimation(false) { indicator in
indicator.layer.removeAnimationForKey(Me.ScaleAnimationKey)
}
}
if scrollView.contentOffset.y < -insetTop {
indicator.layer.addAnimation(refreshEndAnimation(), forKey: Me.ScaleAnimationKey)
UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: .AllowUserInteraction, animations: {
scrollView.setContentOffset(scrollView.contentOffset, animated: false)
scrollView.contentOffset.y = -insetTop
}) { _ in
completionBlock()
}
} else {
CATransaction.begin()
CATransaction.setCompletionBlock(completionBlock)
indicator.layer.addAnimation(refreshEndAnimation(), forKey: Me.ScaleAnimationKey)
CATransaction.commit()
}
return
}
}
indicator.stopAnimation(false)
}
private func refreshEndAnimation() -> CAPropertyAnimation {
let anim = CABasicAnimation(keyPath: "transform.scale")
anim.duration = 0.3
anim.repeatCount = 1
anim.fromValue = 1
anim.toValue = 0
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
anim.fillMode = kCAFillModeForwards
anim.removedOnCompletion = false
return anim
}
}
| mit | ab17b4d43f73d51e2a66be370d6f3c71 | 33.398964 | 167 | 0.589998 | 5.547911 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Swift/Classes/View/CustomPickerCellView.swift | 1 | 1360 | //
// CustomPickerCellView.swift
// Example
//
// Created by Slience on 2021/3/16.
//
import UIKit
import HXPHPicker
class CustomPickerViewCell: PhotoPickerViewCell {
lazy var selectedMaskView: UIView = {
let view = UIView.init()
view.layer.borderWidth = 5
view.layer.borderColor = UIColor(hexString: "#07c160").cgColor
view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
view.addSubview(numberLb)
view.isHidden = true
return view
}()
lazy var numberLb: UILabel = {
let label = UILabel.init()
label.textColor = UIColor(hexString: "#ffffff")
label.textAlignment = .center
label.font = .boldSystemFont(ofSize: 35)
label.adjustsFontSizeToFitWidth = true
return label
}()
override func initView() {
super.initView()
contentView.addSubview(selectedMaskView)
}
override func updateSelectedState(isSelected: Bool, animated: Bool) {
super.updateSelectedState(isSelected: isSelected, animated: animated)
numberLb.text = String(photoAsset.selectIndex + 1)
selectedMaskView.isHidden = !isSelected
}
override func layoutView() {
super.layoutView()
selectedMaskView.frame = bounds
numberLb.frame = selectedMaskView.bounds
}
}
| mit | 1d68352fb20b4a898c07a8c26b0b03be | 27.333333 | 77 | 0.647059 | 4.657534 | false | false | false | false |
kirankunigiri/Apple-Family | Source/Family/Signal/Signal.swift | 2 | 16329 | //
// Signal.swift
//
// Created by Kiran Kunigiri on 1/22/17.
// Copyright © 2017 Kiran. All rights reserved.
//
import Foundation
import MultipeerConnectivity
#if os(iOS)
import UIKit
#endif
// MARK: - Family Protocol
protocol SignalDelegate {
/** Runs when the device has received data from another peer. */
func signal(didReceiveData data: Data, ofType type: UInt32)
/** Runs when a device connects/disconnects to the session */
func signal(connectedDevicesChanged devices: [String])
}
// MARK: - Main Family Class
class Signal: NSObject {
static let instance = Signal()
// MARK: Properties
/** The name of the signal. Limited to one hyphen (-) and 15 characters */
var serviceType: String!
/** The device's name that will appear to others */
var devicePeerID: MCPeerID!
/** The host will use this to advertise its signal */
var serviceAdvertiser: MCNearbyServiceAdvertiser!
/** Devices will use this to look for a hosted session */
var serviceBrowser: MCNearbyServiceBrowser!
/** The amount of time that can be spent connecting with a device before it times out */
var connectionTimeout = 10.0
/** The delegate. Conform to its methods to be informed when certain events occur */
var delegate: SignalDelegate?
/** Whether the device is automatically inviting all devices */
var inviteMode = InviteMode.Auto
/** Whether the device is automatically accepting all invitations */
var acceptMode = InviteMode.Auto
/** Peers available to connect to */
var availablePeers: [Peer] = []
/** Peers connected to */
var connectedPeers: [Peer] = []
/** The names of all devices connected */
var connectedDeviceNames: [String] {
return session.connectedPeers.map({$0.displayName})
}
/** Prints out all errors and status updates */
var debugMode = false
// UI Elements (iOS Only)
#if os(iOS)
private var inviteNavigationController: UINavigationController!
fileprivate var inviteController: InviteTableViewController!
#endif
/** The main object that manages the current connections */
lazy var session: MCSession = {
let session = MCSession(peer: self.devicePeerID, securityIdentity: nil, encryptionPreference: MCEncryptionPreference.none)
session.delegate = self
return session
}()
// MARK: - Initializers
/** Initializes the signal service. Service type is just the name of the signal, and is limited to one hyphen (-) and 15 characters */
func initialize(serviceType: String) {
#if os(iOS)
initialize(serviceType: serviceType, deviceName: UIDevice.current.name)
#elseif os(macOS)
initialize(serviceType: serviceType, deviceName: Host.current().name!)
#endif
}
/** Initializes the signal service. Service type is just the name of the signal, and is limited to one hyphen (-) and 15 characters. The device name is what others will see. */
func initialize(serviceType: String, deviceName: String) {
// Setup device/signal properties
self.serviceType = serviceType
self.devicePeerID = MCPeerID(displayName: deviceName)
// Setup the service advertiser
self.serviceAdvertiser = MCNearbyServiceAdvertiser(peer: self.devicePeerID, discoveryInfo: nil, serviceType: serviceType)
self.serviceAdvertiser.delegate = self
// Setup the service browser
self.serviceBrowser = MCNearbyServiceBrowser(peer: self.devicePeerID, serviceType: serviceType)
self.serviceBrowser.delegate = self
#if os(iOS)
// Setup the invite view controller
let storyboard = UIStoryboard(name: "Signal", bundle: nil)
inviteController = storyboard.instantiateViewController(withIdentifier: "inviteViewController") as! InviteTableViewController
inviteController.delegate = self
inviteNavigationController = UINavigationController(rootViewController: inviteController)
inviteNavigationController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButton))
inviteController.navigationItem.setRightBarButton(doneBarButton, animated: true)
#endif
}
// Stop the advertising and browsing services
deinit {
disconnect()
}
// MARK: - Methods
#if os(iOS)
// NAVIGATION CONTROLLER
@objc private func cancelButton() {
self.disconnect()
inviteNavigationController.dismiss(animated: true, completion: nil)
}
@objc private func doneButton() {
inviteNavigationController.dismiss(animated: true, completion: nil)
}
/** Returns a View Controller that you can present so the user can manually invite certain devices */
func inviteUI() {
self.inviteMode = .UI
self.serviceBrowser.startBrowsingForPeers()
topMostController().present(inviteNavigationController, animated: true, completion: nil)
}
/** Returns the View Controller at the top of the view heirarchy
http://stackoverflow.com/questions/6131205/iphone-how-to-find-topmost-view-controller
*/
fileprivate func topMostController() -> UIViewController {
var topController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
while ((topController?.presentedViewController) != nil) {
topController = topController?.presentedViewController
}
return topController!
}
#endif
// HOST
/** Automatically invites all devices it finds */
func inviteAuto() {
self.inviteMode = .Auto
self.serviceBrowser.startBrowsingForPeers()
}
// JOIN
/** Automatically accepts all invites */
func acceptAuto() {
self.acceptMode = .Auto
self.serviceAdvertiser.startAdvertisingPeer()
}
/** You will now be given a UIAlertController in the protocol method so that the user can accept/decline an invitation */
func acceptUI() {
self.acceptMode = .UI
self.serviceAdvertiser.startAdvertisingPeer()
}
// OTHER
/** Automatically begins to connect all devices with the same service type to each other. It works by running the host and join methods on all devices so that they connect as fast as possible. */
func autoConnect() {
inviteAuto()
acceptAuto()
}
/** Stops the invitation process */
func stopInviting() {
self.serviceBrowser.stopBrowsingForPeers()
}
/** Stops accepting invites and becomes invisible on the network */
func stopAccepting() {
self.serviceAdvertiser.stopAdvertisingPeer()
}
/** Stops all invite/accept services */
func stopSearching() {
self.serviceAdvertiser.stopAdvertisingPeer()
self.serviceBrowser.stopBrowsingForPeers()
}
/** Disconnects from the current session and stops all searching activity */
func disconnect() {
session.disconnect()
connectedPeers.removeAll()
availablePeers.removeAll()
}
/** Shuts down all signal services. Stops inviting/accepting and disconnects from the session */
func shutDown() {
stopSearching()
disconnect()
}
var isConnected: Bool {
return connectedPeers.count >= 1
}
enum InviteMode {
case Auto
case UI
}
enum AcceptMode {
case Auto
case UI
}
/** Sends data to all connected peers. Pass in an object, and the method will convert it into data and send it. You can use the Data extended method, `convertData()` in order to convert it back into an object. */
func sendObject(object: Any, type: UInt32) {
if (session.connectedPeers.count > 0) {
do {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
let container: [Any] = [data, type]
let item = NSKeyedArchiver.archivedData(withRootObject: container)
try session.send(item, toPeers: session.connectedPeers, with: MCSessionSendDataMode.reliable)
} catch let error {
printDebug(error.localizedDescription)
}
}
}
/** Sends data to all connected peers. Pass in an object, and the method will convert it into data and send it. You can use the Data extended method, `convertData()` in order to convert it back into an object. */
func sendData(data: Data, type: UInt32) {
if (session.connectedPeers.count > 0) {
do {
let container: [Any] = [data, type]
let item = NSKeyedArchiver.archivedData(withRootObject: container)
try session.send(item, toPeers: session.connectedPeers, with: MCSessionSendDataMode.reliable)
} catch let error {
printDebug(error.localizedDescription)
}
}
}
/** Prints only if in debug mode */
fileprivate func printDebug(_ string: String) {
if debugMode {
print(string)
}
}
}
// MARK: - Advertiser Delegate
extension Signal: MCNearbyServiceAdvertiserDelegate {
#if os(iOS)
/** Creates a UI Alert given the name of the device */
func alertForInvitation(name: String, completion: @escaping (Bool) -> Void) -> UIAlertController {
let alert = UIAlertController(title: "Invite", message: "You've received an invite from \(name)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Accept", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Decline", style: .destructive, handler: { action in
completion(false)
}))
return alert
}
#endif
// Received invitation
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) {
OperationQueue.main.addOperation {
if self.acceptMode == .Auto {
invitationHandler(true, self.session)
} else if self.acceptMode == .UI {
#if os(iOS)
let alert = UIAlertController(title: "Invite", message: "You've received an invite from \(peerID.displayName)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Accept", style: .default, handler: { action in
debugPrint("Accepted invitation")
invitationHandler(true, self.session)
}))
alert.addAction(UIAlertAction(title: "Decline", style: .destructive, handler: { action in
invitationHandler(false, self.session)
}))
self.topMostController().present(alert, animated: true, completion: nil)
#endif
}
}
}
// Error, could not start advertising
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) {
printDebug("Could not start advertising due to error: \(error)")
}
}
// MARK: - Browser Delegate
extension Signal: MCNearbyServiceBrowserDelegate {
// Found a peer
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
printDebug("Found peer: \(peerID)")
// Update the list and the controller
availablePeers.append(Peer(peerID: peerID, state: .notConnected))
#if os(iOS)
inviteController.update()
#endif
// Invite peer in auto mode
if (inviteMode == .Auto) {
browser.invitePeer(peerID, to: session, withContext: nil, timeout: connectionTimeout)
}
}
// Error, could not start browsing
func browser(_ browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: Error) {
printDebug("Could not start browsing due to error: \(error)")
}
// Lost a peer
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
printDebug("Lost peer: \(peerID)")
// Update the lost peer
availablePeers = availablePeers.filter{ $0.peerID != peerID }
#if os(iOS)
inviteController.update()
#endif
}
}
// MARK: - Session Delegate
extension Signal: MCSessionDelegate {
// Peer changed state
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
printDebug("Peer \(peerID.displayName) changed state to \(state.stringValue)")
// If the new state is connected, then remove it from the available peers
// Otherwise, update the state
if state == .connected {
availablePeers = availablePeers.filter{ $0.peerID != peerID }
} else {
availablePeers.filter{ $0.peerID == peerID }.first?.state = state
}
// Update all connected peers
connectedPeers = session.connectedPeers.map{ Peer(peerID: $0, state: .connected) }
// Send new connection list to delegate
OperationQueue.main.addOperation {
self.delegate?.signal(connectedDevicesChanged: session.connectedPeers.map({$0.displayName}))
}
#if os(iOS)
// Update table view
inviteController.update()
#endif
}
// Received data
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
printDebug("Received data: \(data.count) bytes")
let container = data.convert() as! [Any]
let item = container[0] as! Data
let type = container[1] as! UInt32
OperationQueue.main.addOperation {
self.delegate?.signal(didReceiveData: item, ofType: type)
}
}
// Received stream
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
printDebug("Received stream")
}
// Finished receiving resource
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL, withError error: Error?) {
printDebug("Finished receiving resource with name: \(resourceName)")
}
// Started receiving resource
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
printDebug("Started receiving resource with name: \(resourceName)")
}
}
#if os(iOS)
// MARK: - Invite Tableview Delegate
extension Signal: InviteDelegate {
internal func getAvailablePeers() -> [Peer] {
return availablePeers
}
func getConnectedPeers() -> [Peer] {
return connectedPeers
}
func invitePeer(peer: Peer) {
self.serviceBrowser.invitePeer(peer.peerID, to: session, withContext: nil, timeout: connectionTimeout)
}
}
#endif
// MARK: - Information data
extension MCSessionState {
/** String version of an `MCSessionState` */
var stringValue: String {
switch(self) {
case .notConnected: return "Available"
case .connecting: return "Connecting"
case .connected: return "Connected"
}
}
}
// MARK: - Custom Peer class
// This class is used to contain the peerID along with the state to be presented in a table view
class Peer {
var peerID: MCPeerID
var state: MCSessionState
init(peerID: MCPeerID, state: MCSessionState) {
self.peerID = peerID
self.state = state
}
}
| mit | a1928bf0c428cf193e2aba6510e9e82e | 33.230608 | 216 | 0.63829 | 5.193384 | false | false | false | false |
DanielZakharin/Shelfie | Shelfie/Pods/BarcodeScanner/Sources/HeaderView.swift | 1 | 1873 | import UIKit
protocol HeaderViewDelegate: class {
func headerViewDidPressClose(_ headerView: HeaderView)
}
/**
Header view that simulates a navigation bar.
*/
class HeaderView: UIView {
/// Title label.
lazy var label: UILabel = {
let label = UILabel()
label.text = Title.text
label.font = Title.font
label.textColor = Title.color
label.backgroundColor = Title.backgroundColor
label.numberOfLines = 1
label.textAlignment = .center
return label
}()
/// Close button.
lazy var button: UIButton = {
let button = UIButton(type: .system)
button.setTitle(CloseButton.text, for: UIControlState())
button.titleLabel?.font = CloseButton.font
button.tintColor = CloseButton.color
button.addTarget(self, action: #selector(buttonDidPress), for: .touchUpInside)
return button
}()
/// Header view delegate.
weak var delegate: HeaderViewDelegate?
// MARK: - Initialization
/**
Creates a new instance of `HeaderView`.
- Parameter frame: View frame.
*/
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = Title.backgroundColor
[label, button].forEach {
addSubview($0)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
let padding: CGFloat = 8
let labelHeight: CGFloat = 40
button.sizeToFit()
button.frame.origin = CGPoint(x: 15,
y: ((frame.height - button.frame.height) / 2) + padding)
label.frame = CGRect(
x: 0, y: ((frame.height - labelHeight) / 2) + padding,
width: frame.width, height: labelHeight)
}
// MARK: - Actions
/**
Close button action handler.
*/
@objc func buttonDidPress() {
delegate?.headerViewDidPressClose(self)
}
}
| gpl-3.0 | 8b94f94ba59087b8d734593bc7ef25ec | 21.035294 | 82 | 0.66204 | 4.237557 | false | false | false | false |
khizkhiz/swift | validation-test/Evolution/test_struct_change_size.swift | 2 | 1699 | // RUN: %target-resilience-test
// REQUIRES: executable_test
import StdlibUnittest
import struct_change_size
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
import SwiftPrivatePthreadExtras
#if _runtime(_ObjC)
import ObjectiveC
#endif
var ClassChangeSizeTest = TestSuite("ClassChangeSize")
func increment(c: inout ChangeSize) {
c.version += 1
}
ClassChangeSizeTest.test("ChangeFieldOffsetsOfFixedLayout") {
var t = ChangeFieldOffsetsOfFixedLayout(major: 7, minor: 5, patch: 3)
do {
expectEqual(t.getVersion(), "7.5.3")
}
do {
t.minor.version = 1
t.patch.version = 2
expectEqual(t.getVersion(), "7.1.2")
}
do {
increment(&t.patch)
expectEqual(t.getVersion(), "7.1.3")
}
}
struct ChangeFieldOffsetsOfMyFixedLayout {
init(major: Int32, minor: Int32, patch: Int32) {
self.major = ChangeSize(version: major)
self.minor = ChangeSize(version: minor)
self.patch = ChangeSize(version: patch)
}
var major: ChangeSize
var minor: ChangeSize
var patch: ChangeSize
func getVersion() -> String {
return "\(major.version).\(minor.version).\(patch.version)"
}
}
ClassChangeSizeTest.test("ChangeFieldOffsetsOfMyFixedLayout") {
var t = ChangeFieldOffsetsOfMyFixedLayout(major: 9, minor: 2, patch: 1)
do {
expectEqual(t.getVersion(), "9.2.1")
}
do {
t.major.version = 7
t.minor.version = 6
t.patch.version = 1
expectEqual(t.getVersion(), "7.6.1")
}
do {
increment(&t.patch)
expectEqual(t.getVersion(), "7.6.2")
}
}
runAllTests()
| apache-2.0 | d20461508c6f0b0b98f9942392ed0e8a | 21.064935 | 73 | 0.693349 | 3.439271 | false | true | false | false |
pjcau/LocalNotifications_Over_iOS10 | Pods/SwiftDate/Sources/SwiftDate/DateInRegion+Formatter.swift | 2 | 8642 | // SwiftDate
// Manage Date/Time & Timezone in Swift
//
// Created by: Daniele Margutti
// Email: <[email protected]>
// Web: <http://www.danielemargutti.com>
//
// Licensed under MIT License.
import Foundation
// MARK: - DateInRegion Formatter Support
public extension DateInRegion {
/// Convert a `DateInRegion` to a string according to passed format expressed in region's timezone, locale and calendar.
/// Se Apple's "Date Formatting Guide" to see details about the table of symbols you can use to format each date component.
/// Since iOS7 and macOS 10.9 it's based upon tr35-31 specs (http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns)
///
/// - parameter formatString: format string
///
/// - returns: a string representing given date in format string you have specified
public func string(custom formatString: String) -> String {
return self.string(format: .custom(formatString))
}
/// Convert a `DateInRegion` to a string using ISO8601 format expressed in region's timezone, locale and calendar.
///
/// - parameter opts: optional options for ISO8601 formatter specs (see `ISO8601Parser.Options`). If nil `.withInternetDateTime` will be used instead)
///
/// - returns: a string representing the date in ISO8601 format according to passed options
public func iso8601(opts: ISO8601DateTimeFormatter.Options? = nil) -> String {
return self.string(format: .iso8601(options: opts ?? [.withInternetDateTime]))
}
/// Convert a `DateInRegion` to a string using region's timezone, locale and calendar
///
/// - parameter format: format of the string as defined by `DateFormat`
///
/// - returns: a new string or nil if DateInRegion does not contains any valid date
public func string(format: DateFormat) -> String {
switch format {
case .custom(let format):
return self.formatters.dateFormatter(format: format).string(from: self.absoluteDate)
case .strict(let format):
return self.formatters.dateFormatter(format: format).string(from: self.absoluteDate)
case .iso8601(let options):
let formatter = self.formatters.isoFormatter()
return formatter.string(from: self.absoluteDate, tz: self.region.timeZone, options: options)
case .iso8601Auto:
let formatter = self.formatters.isoFormatter()
return formatter.string(from: self.absoluteDate, tz: self.region.timeZone, options: [.withInternetDateTime])
case .rss(let isAltRSS):
let format = (isAltRSS ? "d MMM yyyy HH:mm:ss ZZZ" : "EEE, d MMM yyyy HH:mm:ss ZZZ")
return self.formatters.dateFormatter(format: format).string(from: self.absoluteDate)
case .extended:
let format = "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz"
return self.formatters.dateFormatter(format: format).string(from: self.absoluteDate)
case .dotNET:
return DOTNETDateTimeFormatter.string(self)
}
}
/// Get the representation of the absolute time interval between `self` date and a given date
///
/// - parameter date: date to compare
/// - parameter dateStyle: style to format the date
/// - parameter timeStyle: style to format the time
///
/// - returns: a new string which represent the interval from given dates
public func intervalString(toDate date: DateInRegion, dateStyle: DateIntervalFormatter.Style = .medium, timeStyle: DateIntervalFormatter.Style = .medium) -> String {
let formatter = self.formatters.intervalFormatter()
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
return formatter.string(from: self.absoluteDate, to: date.absoluteDate)
}
/// Convert a `DateInRegion` date into a string with date & time style specific format style
///
/// - parameter dateStyle: style of the date (if not specified `.medium`)
/// - parameter timeStyle: style of the time (if not specified `.medium`)
///
/// - returns: a new string which represent the date expressed into the current region
public func string(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
let formatter = self.formatters.dateFormatter()
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
return formatter.string(from: self.absoluteDate)
}
/// This method produces a colloquial representation of time elapsed between this `DateInRegion` (`self`) and
/// the current date (`Date()`)
///
/// - parameter style: style of output. If not specified `.full` is used
/// - returns: colloquial string representation
/// - throws: throw an exception is colloquial string cannot be evaluated
@available(*, deprecated: 4.5.0, message: "Deprecated. Use colloquialSinceNow(options:) instead")
public func colloquialSinceNow(style: DateComponentsFormatter.UnitsStyle? = nil) throws -> (colloquial: String, time: String?) {
let now = DateInRegion(absoluteDate: Date(), in: self.region)
return try self.colloquial(toDate: now, style: style)
}
/// This method produces a colloquial representation of time elapsed between this `DateInRegion` and
/// the current date (`Date()`).
///
/// - Parameter options: formatting options, `nil` to use default options
/// - Returns: String, `nil` if formatting fails
public func colloquialSinceNow(options: ColloquialDateFormatter.Options? = nil) -> String? {
let now = DateInRegion(absoluteDate: Date(), in: self.region)
return self.colloquial(toDate: now, options: options)
}
/// This method produces a colloquial representation of time elapsed between this `DateInRegion` (`self`) and
/// another passed date.
///
/// - Parameters:
/// - parameter date: date to compare
/// - parameter style: style of output. If not specified `.full` is used
/// - returns: colloquial string representation
/// - throws: throw an exception is colloquial string cannot be evaluated
@available(*, deprecated: 4.5.0, message: "Deprecated. Use colloquial(toDate:options:) instead")
public func colloquial(toDate date: DateInRegion, style: DateComponentsFormatter.UnitsStyle? = nil) throws -> (colloquial: String, time: String?) {
let formatter = DateInRegionFormatter()
formatter.localization = Localization(locale: self.region.locale)
formatter.unitStyle = style ?? .full
if style == nil || style == .full || style == .spellOut {
return try formatter.colloquial(from: self, to: date)
} else {
return (try formatter.timeComponents(from: self, to: date),nil)
}
}
/// This method produces a colloquial representation of time elapsed between `self` and another reference date.
///
/// - Parameters:
/// - date: reference date
/// - options: formatting options, `nil` to use default options
/// - Returns: String, `nil` if formatting fails
public func colloquial(toDate date: DateInRegion, options: ColloquialDateFormatter.Options? = nil) -> String? {
return ColloquialDateFormatter.colloquial(from: self, to: date, options: options)
}
/// This method produces a string by printing the interval between self and another date and output a string where each
/// calendar component is printed.
///
/// - parameter toDate: date to compare
/// - parameter options: options to format the output. Keep in mind: `.locale` will be overwritten by self's `region.locale`.
///
/// - throws: throw an exception if time components cannot be evaluated
///
/// - returns: string with each time component
public func timeComponents(toDate date: DateInRegion, options: ComponentsFormatterOptions? = nil) throws -> String {
let interval = self.absoluteDate.timeIntervalSince(date.absoluteDate)
var optionsStruct = (options == nil ? ComponentsFormatterOptions() : options!)
optionsStruct.locale = self.region.locale
optionsStruct.allowedUnits = optionsStruct.allowedUnits ?? optionsStruct.bestAllowedUnits(forInterval: interval)
return try interval.string(options: optionsStruct, shared: self.formatters.useSharedFormatters)
}
// This method produces a string by printing the interval between self and current Date and output a string where each
/// calendar component is printed.
///
/// - parameter options: options to format the output. Keep in mind: `.locale` will be overwritten by self's `region.locale`.
///
/// - throws: throw an exception if time components cannot be evaluated
///
/// - returns: string with each time component
public func timeComponentsSinceNow(options: ComponentsFormatterOptions? = nil) throws -> String {
let interval = abs(self.absoluteDate.timeIntervalSinceNow)
var optionsStruct = (options == nil ? ComponentsFormatterOptions() : options!)
optionsStruct.locale = self.region.locale
return try interval.string(options: optionsStruct, shared: self.formatters.useSharedFormatters)
}
}
| mit | 5bef0754ead21fc4c0863769b1e2176a | 47.824859 | 166 | 0.737676 | 4.002779 | false | false | false | false |
idappthat/UTANow-iOS | UTANow/EventListTableViewCell.swift | 1 | 1249 | //
// EventListTableViewCell.swift
// UTANow
//
// Created by Cameron Moreau on 11/7/15.
// Copyright © 2015 Mobi. All rights reserved.
//
import UIKit
import Kingfisher
class EventListTableViewCell: UITableViewCell {
@IBOutlet weak var labelDate: UILabel!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelLocation: UILabel!
@IBOutlet weak var overlay: UIView!
@IBOutlet weak var btnQuickAdd: UIButton!
@IBOutlet weak var btnOpenMap: UIButton!
func setData(event: Event) {
labelTitle.text = event.title
labelDate.text = event.getListingStartTime()
labelLocation.text = event.getListingAddress()
let bgImage = UIImageView()
bgImage.kf_setImageWithURL(NSURL(string: event.imageUrl)!)
self.backgroundView = bgImage
self.backgroundView?.contentMode = .ScaleAspectFill
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
//ANDREW W: to prevent flashing bug when selected
overlay.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
}
}
| mit | ca2c9ef4daf90ad76d9ec76cb15902b3 | 26.733333 | 83 | 0.679487 | 4.605166 | false | false | false | false |
nktn/MalKit | Sample/Sample/ViewController.swift | 1 | 3077 | //
// ViewController.swift
// Sample
//
// Created by nktn on 2017/07/09.
// Copyright © 2017年 nktn. All rights reserved.
//
import UIKit
import SWXMLHash
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var responseArray:NSArray = []
var xml: XMLIndexer? = nil
@IBOutlet weak var tableView: UITableView!
@IBAction func add(_ sender: Any) {
let date = Date()
MalKit().addAnime(20, params: ["status": 1, "date_start": date, "comments":"test"]) { (result, res, err) in
if err == nil {
var str:String = "NG"
if result == true {
str = "OK"
}
let alertController = UIAlertController(title: "response",message: str, preferredStyle: UIAlertControllerStyle.alert)
let cancelButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alertController.addAction(cancelButton)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.present(alertController,animated: true,completion: nil)
}
}else{
let str:String = "Please check user_id/passwd param or already add it"
let alertController = UIAlertController(title: "response",message: str, preferredStyle: UIAlertControllerStyle.alert)
let cancelButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alertController.addAction(cancelButton)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.present(alertController,animated: true,completion: nil)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
MalKit().searchAnime("naruto", completionHandler: { (items, res, err) in
if err == nil {
if items != nil{
DispatchQueue.main.async(execute: {
self.xml = SWXMLHash.parse(items!)
self.tableView.reloadData()
})
}
}
})
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ table: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.xml?["anime"]["entry"].all.count != nil {
return (self.xml?["anime"]["entry"].all.count)!
}else{
return 0
}
}
func tableView(_ table: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = table.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = self.xml?["anime"]["entry"][indexPath.row]["title"].element?.text ?? ""
return cell
}
}
| mit | d4ee25a251e1a6041a2c8170b660d4ac | 36.487805 | 133 | 0.568966 | 4.998374 | false | false | false | false |
prebid/prebid-mobile-ios | EventHandlers/PrebidMobileAdMobAdapters/Sources/PrebidAdMobBannerAdapter.swift | 1 | 4677 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import PrebidMobile
import GoogleMobileAds
@objc(PrebidAdMobBannerAdapter)
public class PrebidAdMobBannerAdapter:
PrebidAdMobMediationBaseAdapter,
GADMediationBannerAd,
DisplayViewLoadingDelegate,
DisplayViewInteractionDelegate {
public var view: UIView {
return displayView ?? UIView()
}
var displayView: PBMDisplayView?
weak var delegate: GADMediationBannerAdEventDelegate?
var adConfiguration: GADMediationBannerAdConfiguration?
var completionHandler: GADMediationBannerLoadCompletionHandler?
public func loadBanner(for adConfiguration: GADMediationBannerAdConfiguration,
completionHandler: @escaping GADMediationBannerLoadCompletionHandler) {
self.adConfiguration = adConfiguration
self.completionHandler = completionHandler
guard let serverParameter = adConfiguration.credentials.settings["parameter"] as? String else {
let error = AdMobAdaptersError.noServerParameter
delegate = completionHandler(nil, error)
return
}
guard let eventExtras = adConfiguration.extras as? GADCustomEventExtras,
let eventExtrasDictionary = eventExtras.extras(forLabel: AdMobConstants.PrebidAdMobEventExtrasLabel),
!eventExtrasDictionary.isEmpty else {
let error = AdMobAdaptersError.emptyCustomEventExtras
delegate = completionHandler(nil, error)
return
}
guard let targetingInfo = eventExtrasDictionary[PBMMediationTargetingInfoKey] as? [String: String] else {
let error = AdMobAdaptersError.noTargetingInfoInEventExtras
delegate = completionHandler(nil, error)
return
}
guard MediationUtils.isServerParameterInTargetingInfoDict(serverParameter, targetingInfo) else {
let error = AdMobAdaptersError.wrongServerParameter
delegate = completionHandler(nil, error)
return
}
guard let bid = eventExtrasDictionary[PBMMediationAdUnitBidKey] as? Bid else {
let error = AdMobAdaptersError.noBidInEventExtras
delegate = completionHandler(nil, error)
return
}
guard let configId = eventExtrasDictionary[PBMMediationConfigIdKey] as? String else {
let error = AdMobAdaptersError.noConfigIDInEventExtras
delegate = completionHandler(nil, error)
return
}
let frame = CGRect(origin: .zero, size: bid.size)
displayView = PBMDisplayView(frame: frame, bid: bid, configId: configId)
displayView?.interactionDelegate = self
displayView?.loadingDelegate = self
displayView?.displayAd()
}
// MARK: - DisplayViewLoadingDelegate
public func displayViewDidLoadAd(_ displayView: PBMDisplayView) {
if let handler = completionHandler {
delegate = handler(self, nil)
}
}
public func displayView(_ displayView: PBMDisplayView, didFailWithError error: Error) {
if let handler = completionHandler {
delegate = handler(nil, error)
}
}
// MARK: - PBMDisplayViewInteractionDelegate
public func trackImpression(forDisplayView: PBMDisplayView) {
delegate?.reportImpression()
}
public func viewControllerForModalPresentation(fromDisplayView: PBMDisplayView) -> UIViewController? {
return adConfiguration?.topViewController ?? UIApplication.shared.windows.first?.rootViewController
}
public func didLeaveApp(from displayView: PBMDisplayView) {
delegate?.reportClick()
}
public func willPresentModal(from displayView: PBMDisplayView) {
delegate?.willPresentFullScreenView()
}
public func didDismissModal(from displayView: PBMDisplayView) {
delegate?.willDismissFullScreenView()
delegate?.didDismissFullScreenView()
}
}
| apache-2.0 | 35dafc9612fe9a1e583078a2f07baa65 | 36.328 | 115 | 0.685598 | 5.302273 | false | true | false | false |
makelove/Developing-iOS-8-Apps-with-Swift | Lession7-Psychologist/Psychologist/Psychologist/HappinessViewController.swift | 1 | 1931 | //
// HappinessViewController.swift
// Happiness
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import UIKit
class HappinessViewController: UIViewController, FaceViewDataSource
{
var happiness: Int = 60 { // 0 = very sad, 100 = ecstatic
didSet {
happiness = min(max(happiness, 0), 100)
print("happiness = \(happiness)")
updateUI()
}
}
func updateUI() {
// in L7, we discovered that we have to be careful here
// we can't just unwrap the implicitly unwrapped optional faceView
// that's because outlets are not set during segue preparation
faceView?.setNeedsDisplay()
// note that this MVC is setting its own title
// often there is no one more suited to set an MVCs title than itself
// but other times another MVC might want to set it (title is public)
title = "\(happiness)"
}
func smilinessForFaceView(sender: FaceView) -> Double? {
return Double(happiness-50)/50
}
@IBOutlet weak var faceView: FaceView! {
didSet {
faceView.dataSource = self
faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: "scale:"))
}
}
private struct Constants {
static let HappinessGestureScale: CGFloat = 4
}
@IBAction func changeHappiness(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .Ended: fallthrough
case .Changed:
let translation = gesture.translationInView(faceView)
let happinessChange = -Int(translation.y / Constants.HappinessGestureScale)
if happinessChange != 0 {
happiness += happinessChange
gesture.setTranslation(CGPointZero, inView: faceView)
}
default: break
}
}
}
| apache-2.0 | 7bcaef7ca66c72e3746922d181dcd818 | 31.183333 | 103 | 0.620404 | 5.108466 | false | false | false | false |
slightair/CA2D | iOS/CA2D/Graphics/Renderer.swift | 1 | 5278 | import Metal
import MetalKit
struct Vertex {
var position: SIMD2<Float>
var color: SIMD3<Float>
}
struct Uniforms {
var viewportSize: SIMD2<Float>
}
final class Renderer: NSObject {
private let device: MTLDevice
private var pipelineState: MTLRenderPipelineState
private let commandQueue: MTLCommandQueue
private var drawableSize: CGSize = .zero
private let world: World
private let cellSize: CGFloat
init?(view: MTKView, world: World, cellSize: CGFloat) {
self.device = view.device!
self.world = world
self.cellSize = cellSize
guard let defaultLibrary = device.makeDefaultLibrary() else {
fatalError()
}
let vertexFunction = defaultLibrary.makeFunction(name: "vertexShader")
let fragmentFunction = defaultLibrary.makeFunction(name: "fragmentShader")
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.label = "World Rendering Pipeline"
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.fragmentFunction = fragmentFunction
pipelineDescriptor.colorAttachments[0].pixelFormat = view.colorPixelFormat
do {
pipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor)
} catch {
fatalError("Failed to create pipeline state: \(error)")
}
commandQueue = device.makeCommandQueue()!
}
private func vertexColor(for condition: Int) -> SIMD3<Float> {
guard world.rule.conditions > 2 else {
return SIMD3(1.0, 1.0, 0.0)
}
let cyan:Float = 0.0
let magenta:Float = 1.0 - (1.0 / Float(world.rule.conditions - 2) * Float(condition - 1))
let yellow:Float = 1.0
let key:Float = 0.0
let red = 1 - min(1.0, cyan * (1.0 - key)) + key
let green = 1 - min(1.0, magenta * (1.0 - key)) + key
let blue = 1 - min(1.0, yellow * (1.0 - key)) + key
return SIMD3(red, green, blue)
}
private func renderWorld(renderEncoder: MTLRenderCommandEncoder) {
let cellSize = Float(self.cellSize)
let basePositionX = Float(-drawableSize.width / 2)
let basePositionY = Float(-drawableSize.height / 2)
var vertices: [Vertex] = []
for y in (0..<world.height) {
for x in (0..<world.width) {
let index = y * world.width + x
let condition = world.cells[index]
if condition == 0 { continue }
let color = vertexColor(for: condition)
let x1 = basePositionX + cellSize * Float(x)
let x2 = basePositionX + cellSize * Float(x + 1)
let y1 = basePositionY + cellSize * Float(y)
let y2 = basePositionY + cellSize * Float(y + 1)
vertices.append(contentsOf: [
Vertex(position: .init(x1, y1), color: color),
Vertex(position: .init(x1, y2), color: color),
Vertex(position: .init(x2, y1), color: color),
Vertex(position: .init(x1, y2), color: color),
Vertex(position: .init(x2, y1), color: color),
Vertex(position: .init(x2, y2), color: color),
])
}
}
let vertexBuffer = device.makeBuffer(bytes: vertices,
length: vertices.count * MemoryLayout<Vertex>.stride,
options: [])!
var uniforms = Uniforms(viewportSize: .init(Float(drawableSize.width), Float(drawableSize.height)))
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
renderEncoder.setVertexBytes(&uniforms,
length: MemoryLayout<Uniforms>.stride,
index: 1)
renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertices.count)
}
}
extension Renderer: MTKViewDelegate {
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
drawableSize = size
}
func draw(in view: MTKView) {
let commandBuffer = commandQueue.makeCommandBuffer()!
commandBuffer.label = "World Command Buffer"
if let renderPassDescriptor = view.currentRenderPassDescriptor,
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) {
renderEncoder.label = "World Render Encoder"
let viewport = MTLViewport(originX: 0,
originY: 0,
width: Double(drawableSize.width),
height: Double(drawableSize.height),
znear: 0,
zfar: 1)
renderEncoder.setViewport(viewport)
renderEncoder.setRenderPipelineState(pipelineState)
renderWorld(renderEncoder: renderEncoder)
renderEncoder.endEncoding()
if let drawable = view.currentDrawable {
commandBuffer.present(drawable)
}
}
commandBuffer.commit()
}
}
| bsd-3-clause | 6c94033a687e6328006fd1ba577f3c5e | 36.7 | 107 | 0.578249 | 4.95122 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/ProjectPage/Views/Cells/ProjectPamphletSubpageCell.swift | 1 | 3279 | import KsApi
import Library
import Prelude
import UIKit
internal final class ProjectPamphletSubpageCell: UITableViewCell, ValueCell {
@IBOutlet private var countContainerView: UIView!
@IBOutlet private var countLabel: UILabel!
@IBOutlet private var rootStackView: UIStackView!
@IBOutlet private var separatorView: UIView!
@IBOutlet private var subpageLabel: UILabel!
@IBOutlet private var topSeparatorView: UIView!
private let viewModel: ProjectPamphletSubpageCellViewModelType = ProjectPamphletSubpageCellViewModel()
internal func configureWith(value subpage: ProjectPamphletSubpage) {
self.viewModel.inputs.configureWith(subpage: subpage)
self.setNeedsLayout()
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
|> ProjectPamphletSubpageCell.lens.accessibilityTraits .~ UIAccessibilityTraits.button
|> ProjectPamphletSubpageCell.lens.contentView.layoutMargins %~~ { _, cell in
cell.traitCollection.isRegularRegular
? .init(topBottom: Styles.gridHalf(5), leftRight: Styles.grid(16))
: .init(topBottom: Styles.gridHalf(5), leftRight: Styles.gridHalf(7))
}
_ = self.countContainerView
|> UIView.lens.layoutMargins .~ .init(topBottom: Styles.grid(1), leftRight: Styles.grid(2))
|> UIView.lens.layer.borderWidth .~ 1
_ = self.countLabel
|> UILabel.lens.font .~ .ksr_headline(size: 13)
|> UIView.lens.contentHuggingPriority(for: .horizontal) .~ UILayoutPriority.required
|> UIView.lens.contentCompressionResistancePriority(for: .horizontal) .~ UILayoutPriority.required
_ = self.rootStackView
|> UIStackView.lens.spacing .~ Styles.grid(1)
|> UIStackView.lens.alignment .~ .center
|> UIStackView.lens.distribution .~ .fill
_ = [self.separatorView, self.topSeparatorView]
||> separatorStyle
_ = self.subpageLabel
|> UILabel.lens.numberOfLines .~ 2
|> UILabel.lens.font .~ .ksr_body(size: 14)
|> UILabel.lens.backgroundColor .~ .ksr_white
|> UIView.lens.contentHuggingPriority(for: .horizontal) .~ UILayoutPriority.defaultLow
|> UIView.lens.contentCompressionResistancePriority(for: .horizontal) .~ UILayoutPriority.defaultLow
self.setNeedsLayout()
}
internal override func bindViewModel() {
super.bindViewModel()
self.countLabel.rac.text = self.viewModel.outputs.countLabelText
self.countLabel.rac.textColor = self.viewModel.outputs.countLabelTextColor
self.countLabel.rac.backgroundColor = self.viewModel.outputs.countLabelBackgroundColor
self.countContainerView.rac.backgroundColor = self.viewModel.outputs.countLabelBackgroundColor
self.viewModel.outputs.countLabelBorderColor
.observeForUI()
.observeValues { [weak self] in
self?.countContainerView.layer.borderColor = $0.cgColor
}
self.topSeparatorView.rac.hidden = self.viewModel.outputs.topSeparatorViewHidden
self.separatorView.rac.hidden = self.viewModel.outputs.separatorViewHidden
self.subpageLabel.rac.text = self.viewModel.outputs.labelText
self.subpageLabel.rac.textColor = self.viewModel.outputs.labelTextColor
}
internal override func layoutSubviews() {
super.layoutSubviews()
}
}
| apache-2.0 | 81f12443816e70bad75bd4a3fb1d909d | 38.035714 | 106 | 0.737725 | 4.690987 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | the-blue-alliance-ios/View Controllers/Teams/Team/Team@Event/TeamStatsViewController.swift | 1 | 4319 | import CoreData
import Foundation
import TBAData
import TBAKit
import UIKit
class TeamStatsViewController: TBATableViewController, Observable {
private let team: Team
private let event: Event
private var teamStat: EventTeamStat? {
didSet {
if let teamStat = teamStat {
contextObserver.observeObject(object: teamStat, state: .updated) { [weak self] (_, _) in
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}
} else {
contextObserver.observeInsertions { [weak self] (teamStats) in
self?.teamStat = teamStats.first
}
}
}
}
// MARK: - Observable
typealias ManagedType = EventTeamStat
lazy var contextObserver: CoreDataContextObserver<EventTeamStat> = {
return CoreDataContextObserver(context: persistentContainer.viewContext)
}()
lazy var observerPredicate: NSPredicate = {
return EventTeamStat.predicate(eventKey: event.key, teamKey: team.key)
}()
// MARK: - Init
init(team: Team, event: Event, dependencies: Dependencies) {
self.team = team
self.event = event
super.init(dependencies: dependencies)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// TODO: Since we leverage didSet, we need to do this *after* initilization
teamStat = EventTeamStat.findOrFetch(in: persistentContainer.viewContext, matching: observerPredicate)
tableView.registerReusableCell(EventTeamStatTableViewCell.self)
}
// MARK: Table View Data Source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if teamStat == nil {
showNoDataView()
return 0
}
removeNoDataView()
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> EventTeamStatTableViewCell {
let cell = tableView.dequeueReusableCell(indexPath: indexPath) as EventTeamStatTableViewCell
cell.selectionStyle = .none
let (statName, statKey): (String, String) = {
switch indexPath.row {
case 0:
return ("OPR", EventTeamStat.oprKeyPath())
case 1:
return ("DPR", EventTeamStat.dprKeyPath())
case 2:
return ("CCWM", EventTeamStat.ccwmKeyPath())
default:
return ("", "")
}
}()
cell.viewModel = EventTeamStatCellViewModel(eventTeamStat: teamStat, statName: statName, statKey: statKey)
return cell
}
}
extension TeamStatsViewController: Refreshable {
var refreshKey: String? {
return "\(event.key)_team_stats"
}
var automaticRefreshInterval: DateComponents? {
return DateComponents(hour: 1)
}
var automaticRefreshEndDate: Date? {
// Automatically refresh team stats until the event is over
return event.endDate?.endOfDay()
}
var isDataSourceEmpty: Bool {
return teamStat == nil
}
@objc func refresh() {
var operation: TBAKitOperation!
operation = tbaKit.fetchEventTeamStats(key: event.key) { [self] (result, notModified) in
guard case .success(let stats) = result, !notModified else {
return
}
let context = persistentContainer.newBackgroundContext()
context.performChangesAndWait({
let event = context.object(with: self.event.objectID) as! Event
event.insert(stats)
}, saved: { [unowned self] in
markTBARefreshSuccessful(self.tbaKit, operation: operation)
}, errorRecorder: errorRecorder)
}
addRefreshOperations([operation])
}
}
extension TeamStatsViewController: Stateful {
var noDataText: String? {
return "No stats for team at event"
}
}
| mit | 1300e112bdfafcbc0cf0a26849d683d5 | 29.202797 | 120 | 0.605696 | 4.975806 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Playback.playground/Pages/Phase-Locked Vocoder.xcplaygroundpage/Contents.swift | 1 | 1162 | //: ## Phase-Locked Vocoder
//: A different kind of time and pitch stretching
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: "guitarloop.wav")
let phaseLockedVocoder = AKPhaseLockedVocoder(file: file)
AudioKit.output = phaseLockedVocoder
AudioKit.start()
phaseLockedVocoder.start()
phaseLockedVocoder.amplitude = 1
phaseLockedVocoder.pitchRatio = 1
var timeStep = 0.1
import AudioKitUI
class LiveView: AKLiveViewController {
// UI Elements we'll need to be able to access
var playingPositionSlider: AKSlider?
override func viewDidLoad() {
addTitle("Phase Locked Vocoder")
playingPositionSlider = AKSlider(property: "Position",
value: phaseLockedVocoder.position,
range: 0 ... 3.428,
format: "%0.2f s"
) { sliderValue in
phaseLockedVocoder.position = sliderValue
}
addView(playingPositionSlider)
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| mit | e5bc64e3ced46145529c90cf2af6bd1c | 27.341463 | 76 | 0.666954 | 5.052174 | false | false | false | false |
arnaudbenard/npm-stats | Pods/Charts/Charts/Classes/Charts/PieChartView.swift | 44 | 13094 | //
// PieChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// View that represents a pie chart. Draws cake like slices.
public class PieChartView: PieRadarChartViewBase
{
/// rect object that represents the bounds of the piechart, needed for drawing the circle
private var _circleBox = CGRect()
/// array that holds the width of each pie-slice in degrees
private var _drawAngles = [CGFloat]()
/// array that holds the absolute angle in degrees of each slice
private var _absoluteAngles = [CGFloat]()
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if (_dataNotSet)
{
return
}
let context = UIGraphicsGetCurrentContext()
renderer!.drawData(context: context)
if (valuesToHighlight())
{
renderer!.drawHighlighted(context: context, indices: _indicesToHightlight)
}
renderer!.drawExtras(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
}
internal override func calculateOffsets()
{
super.calculateOffsets()
// prevent nullpointer when no data set
if (_dataNotSet)
{
return
}
var radius = diameter / 2.0
var c = centerOffsets
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
_circleBox.origin.x = c.x - radius
_circleBox.origin.y = c.y - radius
_circleBox.size.width = radius * 2.0
_circleBox.size.height = radius * 2.0
}
internal override func calcMinMax()
{
super.calcMinMax()
calcAngles()
}
public override func getMarkerPosition(#entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
/// PieChart does not support MarkerView
return CGPoint(x: 0.0, y: 0.0)
}
/// calculates the needed angles for the chart slices
private func calcAngles()
{
_drawAngles = [CGFloat]()
_absoluteAngles = [CGFloat]()
_drawAngles.reserveCapacity(_data.yValCount)
_absoluteAngles.reserveCapacity(_data.yValCount)
var dataSets = _data.dataSets
var cnt = 0
for (var i = 0; i < _data.dataSetCount; i++)
{
var set = dataSets[i]
var entries = set.yVals
for (var j = 0; j < entries.count; j++)
{
_drawAngles.append(calcAngle(abs(entries[j].value)))
if (cnt == 0)
{
_absoluteAngles.append(_drawAngles[cnt])
}
else
{
_absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt])
}
cnt++
}
}
}
/// checks if the given index in the given DataSet is set for highlighting or not
public func needsHighlight(#xIndex: Int, dataSetIndex: Int) -> Bool
{
// no highlight
if (!valuesToHighlight() || dataSetIndex < 0)
{
return false
}
for (var i = 0; i < _indicesToHightlight.count; i++)
{
// check if the xvalue for the given dataset needs highlight
if (_indicesToHightlight[i].xIndex == xIndex
&& _indicesToHightlight[i].dataSetIndex == dataSetIndex)
{
return true
}
}
return false
}
/// calculates the needed angle for a given value
private func calcAngle(value: Double) -> CGFloat
{
return CGFloat(value) / CGFloat(_data.yValueSum) * 360.0
}
public override func indexForAngle(angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
var a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
for (var i = 0; i < _absoluteAngles.count; i++)
{
if (_absoluteAngles[i] > a)
{
return i
}
}
return -1; // return -1 if no index found
}
/// Returns the index of the DataSet this x-index belongs to.
public func dataSetIndexForIndex(xIndex: Int) -> Int
{
var dataSets = _data.dataSets
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].entryForXIndex(xIndex) !== nil)
{
return i
}
}
return -1
}
/// returns an integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
public var drawAngles: [CGFloat]
{
return _drawAngles
}
/// returns the absolute angles of the different chart slices (where the
/// slices end)
public var absoluteAngles: [CGFloat]
{
return _absoluteAngles
}
/// Sets the color for the hole that is drawn in the center of the PieChart (if enabled).
/// NOTE: Use holeTransparent with holeColor = nil to make the hole transparent.
public var holeColor: UIColor?
{
get
{
return (renderer as! PieChartRenderer).holeColor!
}
set
{
(renderer as! PieChartRenderer).holeColor = newValue
setNeedsDisplay()
}
}
/// Set the hole in the center of the PieChart transparent
public var holeTransparent: Bool
{
get
{
return (renderer as! PieChartRenderer).holeTransparent
}
set
{
(renderer as! PieChartRenderer).holeTransparent = newValue
setNeedsDisplay()
}
}
/// Returns true if the hole in the center of the PieChart is transparent, false if not.
public var isHoleTransparent: Bool
{
return (renderer as! PieChartRenderer).holeTransparent
}
/// true if the hole in the center of the pie-chart is set to be visible, false if not
public var drawHoleEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawHoleEnabled
}
set
{
(renderer as! PieChartRenderer).drawHoleEnabled = newValue
setNeedsDisplay()
}
}
/// :returns: true if the hole in the center of the pie-chart is set to be visible, false if not
public var isDrawHoleEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawHoleEnabled
}
}
/// the text that is displayed in the center of the pie-chart. By default, the text is "Total value + sum of all values"
public var centerText: String!
{
get
{
return (renderer as! PieChartRenderer).centerText
}
set
{
(renderer as! PieChartRenderer).centerText = newValue
setNeedsDisplay()
}
}
/// true if drawing the center text is enabled
public var drawCenterTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawCenterTextEnabled
}
set
{
(renderer as! PieChartRenderer).drawCenterTextEnabled = newValue
setNeedsDisplay()
}
}
/// :returns: true if drawing the center text is enabled
public var isDrawCenterTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawCenterTextEnabled
}
}
internal override var requiredBottomOffset: CGFloat
{
return _legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat
{
return 0.0
}
public override var radius: CGFloat
{
return _circleBox.width / 2.0
}
/// returns the circlebox, the boundingbox of the pie-chart slices
public var circleBox: CGRect
{
return _circleBox
}
/// returns the center of the circlebox
public var centerCircleBox: CGPoint
{
return CGPoint(x: _circleBox.midX, y: _circleBox.midY)
}
/// Sets the font of the center text of the piechart.
public var centerTextFont: UIFont
{
get
{
return (renderer as! PieChartRenderer).centerTextFont
}
set
{
(renderer as! PieChartRenderer).centerTextFont = newValue
setNeedsDisplay()
}
}
/// Sets the color of the center text of the piechart.
public var centerTextColor: UIColor
{
get
{
return (renderer as! PieChartRenderer).centerTextColor
}
set
{
(renderer as! PieChartRenderer).centerTextColor = newValue
setNeedsDisplay()
}
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
/// :default: 0.5 (50%) (half the pie)
public var holeRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).holeRadiusPercent
}
set
{
(renderer as! PieChartRenderer).holeRadiusPercent = newValue
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
/// :default: 0.55 (55%) -> means 5% larger than the center-hole by default
public var transparentCircleRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).transparentCircleRadiusPercent
}
set
{
(renderer as! PieChartRenderer).transparentCircleRadiusPercent = newValue
setNeedsDisplay()
}
}
/// set this to true to draw the x-value text into the pie slices
public var drawSliceTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawXLabelsEnabled
}
set
{
(renderer as! PieChartRenderer).drawXLabelsEnabled = newValue
setNeedsDisplay()
}
}
/// :returns: true if drawing x-values is enabled, false if not
public var isDrawSliceTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawXLabelsEnabled
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
public var usePercentValuesEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).usePercentValuesEnabled
}
set
{
(renderer as! PieChartRenderer).usePercentValuesEnabled = newValue
setNeedsDisplay()
}
}
/// :returns: true if drawing x-values is enabled, false if not
public var isUsePercentValuesEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).usePercentValuesEnabled
}
}
/// the line break mode for center text.
/// note that different line break modes give different performance results - Clipping being the fastest, WordWrapping being the slowst.
public var centerTextLineBreakMode: NSLineBreakMode
{
get
{
return (renderer as! PieChartRenderer).centerTextLineBreakMode
}
set
{
(renderer as! PieChartRenderer).centerTextLineBreakMode = newValue
setNeedsDisplay()
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
public var centerTextRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).centerTextRadiusPercent
}
set
{
(renderer as! PieChartRenderer).centerTextRadiusPercent = newValue
setNeedsDisplay()
}
}
} | mit | 9a090ec29ebc2dafb25226b456981bd0 | 26.741525 | 189 | 0.57145 | 5.171011 | false | false | false | false |
stephentyrone/swift | test/Incremental/Dependencies/private-subscript-fine.swift | 5 | 1209 | // REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -disable-direct-intramodule-dependencies -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -disable-direct-intramodule-dependencies -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps
struct Wrapper {
fileprivate subscript() -> InterestingType { fatalError() }
}
// CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int
// CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double
public var x = Wrapper()[] + 0
// CHECK-DEPS: topLevel interface '' InterestingType false
| apache-2.0 | ab6d0ac80b08bbd526198eb0f0f54fba | 56.571429 | 244 | 0.730356 | 3.396067 | false | false | false | false |
saagarjha/iina | iina/JavascriptMessageHub.swift | 1 | 3018 | //
// JavascriptMessageHub.swift
// iina
//
// Created by Collider LI on 22/10/2020.
// Copyright © 2020 lhc. All rights reserved.
//
import Foundation
import WebKit
class JavascriptMessageHub {
weak var reference: JavascriptAPI!
private var listeners: [String: JSManagedValue] = [:]
init(reference: JavascriptAPI) {
self.reference = reference
}
func postMessage(to webView: WKWebView, name: String, data: JSValue) {
DispatchQueue.main.async {
guard let object = data.toObject(),
let data = try? JSONSerialization.data(withJSONObject: object),
let dataString = String(data: data, encoding: .utf8) else {
webView.evaluateJavaScript("window.iina._emit(`\(name)`)")
return
}
webView.evaluateJavaScript("window.iina._emit(`\(name)`, `\(dataString)`)")
}
}
func clearListeners() {
listeners.removeAll()
}
func addListener(forEvent name: String, callback: JSValue) {
if let previousCallback = listeners[name] {
JSContext.current()!.virtualMachine.removeManagedReference(previousCallback, withOwner: reference)
}
let managed = JSManagedValue(value: callback)
listeners[name] = managed
JSContext.current()!.virtualMachine.addManagedReference(managed, withOwner: reference)
}
func callListener(forEvent name: String, withDataString dataString: String?) {
guard let callback = listeners[name] else { return }
guard let dataString = dataString,
let data = dataString.data(using: .utf8),
let decoded = try? JSONSerialization.jsonObject(with: data) else {
callback.value.call(withArguments: [])
return
}
callback.value.call(withArguments: [JSValue(object: decoded, in: callback.value.context) ?? NSNull()])
}
func callListener(forEvent name: String, withDataObject dataObject: Any?, userInfo: Any? = nil) {
guard let callback = listeners[name] else { return }
let data = JSValue(object: dataObject, in: callback.value.context) ?? NSNull()
let userInfo = userInfo ?? NSNull()
callback.value.call(withArguments: [data, userInfo])
}
func receiveMessageFromUserContentController(_ message: WKScriptMessage) {
guard let dict = message.body as? [Any], dict.count == 2,
let name = dict[0] as? String
else { return }
callListener(forEvent: name, withDataString: dict[1] as? String)
}
static let bridgeScript = """
window.iina = {
listeners: {},
_emit(name, data) {
const callback = this.listeners[name];
if (typeof callback === "function") {
callback.call(null, data ? JSON.parse(data) : undefined);
}
},
_simpleModeSetStyle(string) {
document.getElementById("style").innerHTML = string;
},
_simpleModeSetContent(string) {
document.getElementById("content").innerHTML = string;
},
onMessage(name, callback) {
this.listeners[name] = callback;
},
postMessage(name, data) {
webkit.messageHandlers.iina.postMessage([name, JSON.stringify(data)]);
},
};
"""
}
| gpl-3.0 | a1a9f22ed6eba7c94862345c81e12335 | 30.103093 | 106 | 0.679151 | 4.121585 | false | false | false | false |
TofPlay/Dockerfiles | vapor-sqlite/projects/ItWorks-Sqlite/Sources/App/Models/Post.swift | 13 | 2535 | import Vapor
import FluentProvider
import HTTP
final class Post: Model {
let storage = Storage()
// MARK: Properties and database keys
/// The content of the post
var content: String
/// The column names for `id` and `content` in the database
struct Keys {
static let id = "id"
static let content = "content"
}
/// Creates a new Post
init(content: String) {
self.content = content
}
// MARK: Fluent Serialization
/// Initializes the Post from the
/// database row
init(row: Row) throws {
content = try row.get(Post.Keys.content)
}
// Serializes the Post to the database
func makeRow() throws -> Row {
var row = Row()
try row.set(Post.Keys.content, content)
return row
}
}
// MARK: Fluent Preparation
extension Post: Preparation {
/// Prepares a table/collection in the database
/// for storing Posts
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string(Post.Keys.content)
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: JSON
// How the model converts from / to JSON.
// For example when:
// - Creating a new Post (POST /posts)
// - Fetching a post (GET /posts, GET /posts/:id)
//
extension Post: JSONConvertible {
convenience init(json: JSON) throws {
self.init(
content: try json.get(Post.Keys.content)
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Post.Keys.id, id)
try json.set(Post.Keys.content, content)
return json
}
}
// MARK: HTTP
// This allows Post models to be returned
// directly in route closures
extension Post: ResponseRepresentable { }
// MARK: Update
// This allows the Post model to be updated
// dynamically by the request.
extension Post: Updateable {
// Updateable keys are called when `post.update(for: req)` is called.
// Add as many updateable keys as you like here.
public static var updateableKeys: [UpdateableKey<Post>] {
return [
// If the request contains a String at key "content"
// the setter callback will be called.
UpdateableKey(Post.Keys.content, String.self) { post, content in
post.content = content
}
]
}
}
| mit | 51d16bc57f04518fb514eef1c113ddfe | 23.852941 | 76 | 0.605523 | 4.21797 | false | false | false | false |
iTofu/Xia | Sources/Xia.swift | 1 | 9111 | //
// Xia.swift
// Xia
//
// Created by Leo on 27/02/2017.
//
// Copyright (c) 2017 Leo <[email protected]>
//
// 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 SnapKit
public enum XiaType {
case Info
case Success
case Warning
}
open class Xia: UIView {
static let xiaBundlePath: String = Bundle(for: Xia.self).path(forResource: "Xia", ofType: "bundle")!
static let infoImagePath: String = xiaBundlePath.xiaStringByAppendingPathComponent("[email protected]")
static let succImagePath: String = xiaBundlePath.xiaStringByAppendingPathComponent("[email protected]")
static let warnImagePath: String = xiaBundlePath.xiaStringByAppendingPathComponent("[email protected]")
open static let infoImage: UIImage = UIImage(contentsOfFile: infoImagePath)!
open static let succImage: UIImage = UIImage(contentsOfFile: succImagePath)!
open static let warnImage: UIImage = UIImage(contentsOfFile: warnImagePath)!
open var autoHide = true {
didSet {
self.timer?.invalidate()
self.timer = nil
}
}
open var delay = 3.0
open var textColor = UIColor.black {
didSet {
self.textLabel.textColor = textColor
}
}
open var textFont = UIFont.systemFont(ofSize: 15.0) {
didSet {
self.textLabel.font = textFont
}
}
fileprivate let iconView = UIImageView()
fileprivate let textLabel = UILabel()
private var timer: Timer?
override init(frame: CGRect) {
super.init(frame: frame)
setupMainView()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupMainView()
}
private func setupMainView() {
self.backgroundColor = UIColor.white
let container = UIView()
self.addSubview(container)
container.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
make.bottom.equalToSuperview().offset(1.0)
make.height.equalTo(44.0)
}
container.addSubview(self.iconView)
iconView.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.left.equalToSuperview().offset(10.0)
make.size.equalTo(CGSize(width: 20.0, height: 20.0))
}
self.textLabel.textColor = self.textColor
self.textLabel.font = self.textFont
self.textLabel.adjustsFontSizeToFitWidth = true
container.addSubview(self.textLabel)
textLabel.snp.makeConstraints { (make) in
make.left.equalTo(iconView.snp.right).offset(8.0)
make.right.equalToSuperview().offset(-10.0)
make.top.bottom.equalToSuperview()
}
let swipeGR = UISwipeGestureRecognizer(
target: self,
action: #selector(onSwipe)
)
swipeGR.direction = .up
self.addGestureRecognizer(swipeGR)
}
@objc
private func onSwipe() {
self.hide()
self.timer?.invalidate()
self.timer = nil
}
@discardableResult
public class func show(type: XiaType, text: String?, textColor: UIColor = .black, backgroundColor: UIColor = .white) -> Xia {
return Xia().show(type: type, text: text, textColor: textColor, backgroundColor: backgroundColor)
}
@discardableResult
public class func showInfo(_ text: String?, textColor: UIColor = .black, backgroundColor: UIColor = .white) -> Xia {
return self.show(type: .Info, text: text, textColor: textColor, backgroundColor: backgroundColor)
}
@discardableResult
public class func showSuccess(_ text: String?, textColor: UIColor = .black, backgroundColor: UIColor = .white) -> Xia {
return self.show(type: .Success, text: text, textColor: textColor, backgroundColor: backgroundColor)
}
@discardableResult
public class func showWarning(_ text: String?, textColor: UIColor = .white, backgroundColor: UIColor = .orange) -> Xia {
return self.show(type: .Warning, text: text, textColor: textColor, backgroundColor: backgroundColor)
}
@discardableResult
public func show(type: XiaType, text: String?, textColor: UIColor = .black, backgroundColor: UIColor = .white) -> Xia {
switch type {
case .Info:
self.iconView.image = Xia.infoImage
case .Success:
self.iconView.image = Xia.succImage
case .Warning:
self.iconView.image = Xia.warnImage
}
self.textLabel.text = text
self.textColor = textColor
self.backgroundColor = backgroundColor;
return self.show()
}
@discardableResult
public func showInfo(_ text: String?, textColor: UIColor = .black, backgroundColor: UIColor = .white) -> Xia {
return self.show(type: .Info, text: text, textColor: textColor, backgroundColor: backgroundColor)
}
@discardableResult
public func showSuccess(_ text: String?, textColor: UIColor = .black, backgroundColor: UIColor = .white) -> Xia {
return self.show(type: .Success, text: text, textColor: textColor, backgroundColor: backgroundColor)
}
@discardableResult
public func showWarning(_ text: String?, textColor: UIColor = .white, backgroundColor: UIColor = .orange) -> Xia {
return self.show(type: .Warning, text: text, textColor: textColor, backgroundColor: backgroundColor)
}
@discardableResult
public func show() -> Xia {
if let keyWindow = UIApplication.shared.keyWindow {
self.xiaInstallShadow()
keyWindow.addSubview(self)
self.snp.makeConstraints({ (make) in
make.left.right.equalToSuperview()
make.height.equalTo(100.0)
make.bottom.equalTo(keyWindow.snp.top)
})
keyWindow.layoutIfNeeded()
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 1, options: .allowUserInteraction, animations: {
self.snp.updateConstraints({ (make) in
make.bottom.equalTo(keyWindow.snp.top).offset(65.0)
})
keyWindow.layoutIfNeeded()
}, completion: nil)
if self.autoHide {
self.timer = Timer.scheduledTimer(timeInterval: self.delay, target: self, selector: #selector(hideFromTimer), userInfo: nil, repeats: false)
RunLoop.main.add(self.timer!, forMode: RunLoopMode.commonModes)
}
} else {
print("Warning: No keyWindow!")
}
return self
}
@objc
private func hideFromTimer() {
self.hide()
}
public func hide(completion: (() -> Void)? = nil) {
if let keyWindow = self.superview {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 1, options: .allowUserInteraction, animations: {
self.snp.updateConstraints({ (make) in
make.bottom.equalTo(keyWindow.snp.top)
})
keyWindow.layoutIfNeeded()
}, completion: { (finished) in
self.removeFromSuperview()
completion?()
})
}
}
}
extension String {
func xiaStringByAppendingPathComponent(_ path: String) -> String {
let nsSt = self as NSString
return nsSt.appendingPathComponent(path)
}
}
extension UIView {
func xiaInstallShadow() {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 2.0)
layer.shadowOpacity = 0.1
layer.shadowRadius = 2.0
}
}
| mit | c8ac52fe2f10514f0376a073a6fa08ff | 35.011858 | 156 | 0.627593 | 4.698814 | false | false | false | false |
sclark01/Swift_VIPER_Demo | VIPER_Demo/VIPER_DemoTests/ModulesTests/PeopleListTests/Mocks/PeopleListPresenterMock.swift | 1 | 810 | import Foundation
@testable import VIPER_Demo
class PeopleListPresenterMock : PeopleListPresenterType {
var userInterface: PeopleListViewType?
var interactor: PeopleListInteractorType?
var peopleListWireFrame: PeopleListWireFrame?
var didCallUpdateView = false
var didCallDetailsForPersonWithID: Int?
var gotCalledWithPeople: [PersonForListData]!
var willSetViewWithPerson: Person!
func detailsForPerson(withId id: Int) {
didCallDetailsForPersonWithID = id
}
func gotPeople(people: [PersonForListData]) {
gotCalledWithPeople = people
}
func updateView() {
didCallUpdateView = true
let people = PeopleListDataModel(people: [PersonForListData(person: willSetViewWithPerson)])
userInterface?.set(people)
}
}
| mit | 1b40ba0545f04c9fa06ef3bae46dda68 | 26 | 100 | 0.72716 | 4.764706 | false | false | false | false |
zjjzmw1/SwiftCodeFragments | SwiftCodeFragments/AnimationResource/ImageMaskTransition.swift | 1 | 1719 | //
// ImageMaskTransition.swift
// gwlTransformAnim
//
// Created by wangrui on 16/8/30.
// Copyright © 2016年 tools. All rights reserved.
//
import UIKit
class ImageMaskTransition: NSObject {
var animator:ImageMaskAnimator
init(fromImageView:UIImageView , toImageView:UIImageView) {
self.animator = ImageMaskAnimator()
animator.fromImageView = fromImageView
animator.toImageView = toImageView
super.init()
}
}
extension ImageMaskTransition : UINavigationControllerDelegate,UIViewControllerTransitioningDelegate{
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .pop:
self.animator.transitionType = ImageMaskTransitionType.dismiss
return self.animator
case .push:
self.animator.transitionType = ImageMaskTransitionType.present
return self.animator
default:
return nil
}
}
// 返回present的动画
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.animator.transitionType = ImageMaskTransitionType.present
return self.animator
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.animator.transitionType = ImageMaskTransitionType.dismiss
return self.animator
}
}
| mit | f3454868ea523b68ebb0e3b729c36d29 | 33.816327 | 246 | 0.71864 | 6.071174 | false | false | false | false |
johnno1962/eidolon | KioskTests/ListingsViewModelTests.swift | 1 | 8366 | import Quick
import Nimble
import RxSwift
import Moya
@testable
import Kiosk
let testScheduleOnBackground: (observable: Observable<AnyObject>) -> Observable<AnyObject> = { observable in observable }
let testScheduleOnForeground: (observable: Observable<[SaleArtwork]>) -> Observable<[SaleArtwork]> = { observable in observable }
class ListingsViewModelTests: QuickSpec {
override func spec() {
var subject: ListingsViewModel!
let initialBidCount = 3
let finalBidCount = 5
var bidCount: Int!
var saleArtworksCount: Int?
var provider: Networking!
var disposeBag: DisposeBag!
beforeEach {
bidCount = initialBidCount
saleArtworksCount = nil
let endpointsClosure: MoyaProvider<ArtsyAPI>.EndpointClosure = { (target: ArtsyAPI) -> Endpoint<ArtsyAPI> in
switch target {
case ArtsyAPI.AuctionListings:
if let page = target.parameters!["page"] as? Int {
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponseClosure: {.NetworkResponse(200, listingsDataForPage(page, bidCount: bidCount, modelCount: saleArtworksCount))}, method: target.method, parameters: target.parameters)
} else {
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
default:
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
}
provider = Networking(provider: OnlineProvider(endpointClosure: endpointsClosure, stubClosure: MoyaProvider.ImmediatelyStub, online: Observable.just(true)))
disposeBag = DisposeBag()
}
afterEach {
// Force subject to deallocate and stop syncing.
subject = nil
}
it("paginates to the second page to retrieve all three sale artworks") {
subject = ListingsViewModel(provider: provider, selectedIndex: Observable.just(0), showDetails: { _ in }, presentModal: { _ in }, pageSize: 2, logSync: { _ in}, scheduleOnBackground: testScheduleOnBackground, scheduleOnForeground: testScheduleOnForeground)
kioskWaitUntil { done in
subject.updatedContents.take(1).subscribeCompleted {
done()
}.addDisposableTo(disposeBag)
}
expect(subject.numberOfSaleArtworks) == 3
}
it("updates with new values in existing sale artworks") {
subject = ListingsViewModel(provider: provider, selectedIndex: Observable.just(0), showDetails: { _ in }, presentModal: { _ in }, pageSize: 2, syncInterval: 1, logSync: { _ in}, scheduleOnBackground: testScheduleOnBackground, scheduleOnForeground: testScheduleOnForeground)
// Verify that initial value is correct
waitUntil(timeout: 5) { done in
subject.updatedContents.take(1).flatMap { _ in
return subject.saleArtworkViewModelAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)).numberOfBids().take(1)
}.subscribeNext { string in
expect(string) == "\(initialBidCount) bids placed"
done()
}.addDisposableTo(disposeBag)
}
// Simulate update from API, wait for sync to happen
bidCount = finalBidCount
waitUntil(timeout: 5) { done in
// We skip 1 to avoid getting the existing value, and wait for the updated one when the subject syncs.
subject.saleArtworkViewModelAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)).numberOfBids().skip(1).subscribeNext { string in
expect(string) == "\(finalBidCount) bids placed"
done()
}.addDisposableTo(disposeBag)
}
}
it("updates with new sale artworks when lengths differ") {
let subject = ListingsViewModel(provider: provider, selectedIndex: Observable.just(0), showDetails: { _ in }, presentModal: { _ in }, syncInterval: 1, logSync: { _ in}, scheduleOnBackground: testScheduleOnBackground, scheduleOnForeground: testScheduleOnForeground)
saleArtworksCount = 2
// Verify that initial value is correct
waitUntil(timeout: 5) { done in
subject.updatedContents.take(1).subscribeCompleted {
expect(subject.numberOfSaleArtworks) == 2
done()
}.addDisposableTo(disposeBag)
}
// Simulate update from API, wait for sync to happen
saleArtworksCount = 5
// Verify that initial value is correct
waitUntil(timeout: 5) { done in
subject.updatedContents.skip(1).take(1).subscribeCompleted {
expect(subject.numberOfSaleArtworks) == 5
done()
}.addDisposableTo(disposeBag)
}
}
it("syncs correctly even if lot numbers have changed") {
var reverseIDs = false
let endpointsClosure: MoyaProvider<ArtsyAPI>.EndpointClosure = { (target: ArtsyAPI) -> Endpoint<ArtsyAPI> in
switch target {
case ArtsyAPI.AuctionListings:
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponseClosure: {.NetworkResponse(200, listingsDataForPage(1, bidCount: 0, modelCount: 3, reverseIDs: reverseIDs))}, method: target.method, parameters: target.parameters)
default:
return Endpoint<ArtsyAPI>(URL: url(target), sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
}
let provider = Networking(provider: OnlineProvider(endpointClosure: endpointsClosure, stubClosure: MoyaProvider.ImmediatelyStub, online: Observable.just(true)))
subject = ListingsViewModel(provider: provider, selectedIndex: Observable.just(0), showDetails: { _ in }, presentModal: { _ in }, pageSize: 4, syncInterval: 1, logSync: { _ in}, scheduleOnBackground: testScheduleOnBackground, scheduleOnForeground: testScheduleOnForeground)
var initialFirstLotID: String?
var subsequentFirstLotID: String?
// First we get our initial sync
kioskWaitUntil { done in
subject.updatedContents.take(1).subscribeCompleted {
initialFirstLotID = subject.saleArtworkViewModelAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)).saleArtworkID
done()
}.addDisposableTo(disposeBag)
}
// Now we reverse the lot numbers
reverseIDs = true
kioskWaitUntil { done in
subject.updatedContents.skip(1).take(1).subscribeCompleted {
subsequentFirstLotID = subject.saleArtworkViewModelAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)).saleArtworkID
done()
}.addDisposableTo(disposeBag)
}
expect(initialFirstLotID).toNot( beEmpty() )
expect(subsequentFirstLotID).toNot( beEmpty() )
// Now that the IDs have changed, check that they're not equal.
expect(initialFirstLotID) != subsequentFirstLotID
}
}
}
func listingsDataForPage(page: Int, bidCount: Int, modelCount: Int?, reverseIDs: Bool = false) -> NSData {
let count = modelCount ?? (page == 1 ? 2 : 1)
let models = Array<Int>(1...count).map { index -> NSDictionary in
return [
"id": "\(count+page*10 + (reverseIDs ? count - index : index))",
"artwork": [
"id": "artwork-id",
"title": "artwork title",
"date": "late 2014",
"blurb": "Some description",
"price": "1200",
],
"lot_number": index,
"bidder_positions_count": bidCount
]
}
return try! NSJSONSerialization.dataWithJSONObject(models, options: [])
}
| mit | d1cd320ae3610955b5201bfd027183cb | 45.220994 | 285 | 0.613794 | 5.390464 | false | true | false | false |
melsomino/unified-ios | Unified/Library/Ui/Layout/LayoutText.swift | 1 | 2993 | //
// Created by Власов М.Ю. on 01.06.16.
// Copyright (c) 2016 Tensor. All rights reserved.
//
import Foundation
import UIKit
class LayoutText: LayoutViewItem {
var maxLines: Int {
didSet {
label?.numberOfLines = maxLines
}
}
let nowrap: Bool
let font: UIFont
var autoHideEmptyText = true
var text: String? {
didSet {
label?.text = text
if autoHideEmptyText {
hidden = text == nil || text!.isEmpty
}
}
}
override var boundView: UIView? {
return label
}
var label: UILabel! {
didSet {
if let label = label {
label.font = font
label.numberOfLines = maxLines
label.lineBreakMode = nowrap ? .ByClipping : .ByTruncatingTail
}
}
}
init(font: UIFont, maxLines: Int = 0, nowrap: Bool = false) {
self.font = font
self.maxLines = maxLines
self.nowrap = nowrap
}
// MARK: - LayoutItem
override func createViews(inSuperview superview: UIView) {
if label == nil {
label = UILabel()
superview.addSubview(label)
}
}
override var visible: Bool {
return !hidden && text != nil && !text!.isEmpty
}
override var fixedSize: Bool {
return nowrap
}
override func measureMaxSize(bounds: CGSize) -> CGSize {
guard visible else {
return CGSizeZero
}
let measuredText = textForMeasure
if nowrap {
return measureText(measuredText, CGFloat.max)
}
if maxLines > 0 {
let singleLine = measuredText.stringByReplacingOccurrencesOfString("\r", withString: "").stringByReplacingOccurrencesOfString("\n", withString: "")
let singleLineHeight = measureText(singleLine, CGFloat.max).height + 1
var maxSize = measureText(measuredText, bounds.width)
let maxHeight = singleLineHeight * CGFloat(maxLines)
if maxSize.height > maxHeight {
maxSize.height = maxHeight
}
return maxSize
}
return measureText(measuredText, bounds.width)
}
override func measureSize(bounds: CGSize) -> CGSize {
guard visible else {
return CGSizeZero
}
let measuredText = textForMeasure
if nowrap {
return measureText(measuredText, CGFloat.max)
}
if maxLines > 0 {
let singleLine = measuredText.stringByReplacingOccurrencesOfString("\r", withString: "").stringByReplacingOccurrencesOfString("\n", withString: "")
let singleLineHeight = measureText(singleLine, CGFloat.max).height + 1
var size = measureText(measuredText, bounds.width)
let maxHeight = singleLineHeight * CGFloat(maxLines)
if size.height > maxHeight {
size.height = maxHeight
}
return size
}
return measureText(measuredText, bounds.width)
}
// MARK: - Internals
private var textForMeasure: String {
return text ?? ""
}
private func measureText(text: String, _ width: CGFloat) -> CGSize {
let constraintSize = CGSize(width: width, height: CGFloat.max)
let size = text.boundingRectWithSize(constraintSize,
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
return size
}
}
| mit | c361f57d7079885a556a9167d291de16 | 19.033557 | 150 | 0.695812 | 3.680641 | false | false | false | false |
mactive/rw-courses-note | AdvancedSwift3/Swift3_page196.playground/Contents.swift | 1 | 547 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double){
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212)
boilingPointOfWater.temperatureInCelsius
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
freezingPointOfWater.temperatureInCelsius | mit | a0b4b8622d29f185bc30887daa63f088 | 26.4 | 56 | 0.745887 | 4.175573 | false | false | false | false |
emilgras/EGMenuBar | Example/Pods/EGMenuBar/EGMenuBar/Classes/EGMenuBarItem.swift | 1 | 1931 | //
// EGMenuBarItem.swift
// EGMenuBarExample
//
// Created by Emil Gräs on 21/10/2016.
// Copyright © 2016 Emil Gräs. All rights reserved.
//
import UIKit
protocol EGMenuBarItemDelegate: class {
func didSelectItemAtIndex(_ index: Int)
}
class EGMenuBarItem: UIView {
weak var delegate: EGMenuBarItemDelegate?
var index: Int?
var imageView: UIImageView = {
var imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
var image: UIImage? {
didSet {
imageView.image = image
}
}
var title: String? {
didSet {
// TODO:
}
}
// MARK: - Life Cycle
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
setupView()
setupTapGesture()
}
fileprivate func setupView() {
addSubview(imageView)
setupImageViewConstraints()
}
fileprivate func setupImageViewConstraints() {
imageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
fileprivate func setupTapGesture() {
let tap = UITapGestureRecognizer(target: self, action: #selector(EGMenuBarItem.handleTap))
addGestureRecognizer(tap)
}
@objc fileprivate func handleTap() {
if let index = index {
delegate?.didSelectItemAtIndex(index)
}
}
}
| mit | b9afc59f8075d08039e95eecdfacd0d0 | 23.405063 | 98 | 0.621369 | 5.007792 | false | false | false | false |
izotx/iTenWired-Swift | Conference App/TwitterViewController.swift | 1 | 5124 | // Copyright (c) 2016, Izotx
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Izotx nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// Created by Felipe Neves Brito on 12/5/16.
import UIKit
class TwitterViewController: UITableViewController{
let twitterController = TwitterController()
var tweets : [Twitter] = []
var photos = [Photorecord]()
let pendingOperarions = PendingOperarions()
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = self
self.fetchTweets()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("twitterCell", forIndexPath: indexPath) as? TwitterCell
if cell?.accessoryView == nil {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
cell?.accessoryView = indicator
}
let indicator = cell?.accessoryView as! UIActivityIndicatorView
let photoDetails = photos[indexPath.row]
switch (photoDetails.state){
case PhotoRecordState.Filtered, PhotoRecordState.Downloaded:
indicator.stopAnimating()
case PhotoRecordState.Failed:
indicator.stopAnimating()
//TODO:
case PhotoRecordState.New:
indicator.startAnimating()
self.startOperationForPhotoRecord(photoDetails, indexPath: indexPath)
}
cell?.build(tweets[indexPath.row])
cell?.setProfileImage(photoDetails)
return cell!
}
func startOperationForPhotoRecord(photoDetails: Photorecord, indexPath: NSIndexPath){
switch (photoDetails.state) {
case PhotoRecordState.New:
startDownloadForRecord(photoDetails, indexPath: indexPath)
break
default: print("Do Nothing..")
}
}
func startDownloadForRecord(photoDetails: Photorecord, indexPath: NSIndexPath){
if pendingOperarions.downloadsInProgress[indexPath.row] != nil{
return
}
let downloader = ImageDownloader(photoRecord: photoDetails)
downloader.completionBlock = {
if downloader.cancelled {
return
}
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperarions.downloadsInProgress.removeValueForKey(indexPath.row)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
})
}
pendingOperarions.downloadsInProgress.removeValueForKey(indexPath.row)
pendingOperarions.downloadQueue.addOperation(downloader)
}
func fetchTweets(){
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.tweets = twitterController.getTweets()
for tweet in self.tweets {
let url = NSURL(string: tweet.user.profileImage)
let photoRecord = Photorecord(name: tweet.user.profileImage, url: url!)
self.photos.append(photoRecord)
}
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
func checkForNewTweets() -> Bool{
//TODO:
return self.twitterController.getTweets().count != self.tweets.count
}
} | bsd-2-clause | b28d9a54e9b1dff77654d7101b0fa782 | 38.122137 | 118 | 0.667642 | 5.244626 | false | false | false | false |
Davidde94/StemCode_iOS | StemCode/StemProjectKitTests/FileTemplateParserTests.swift | 1 | 1516 | //
// FileTemplateParserTests.swift
// StemProjectKitTests
//
// Created by David Evans on 12/09/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import XCTest
@testable import StemProjectKit
class FileTemplateParserTests: XCTestCase {
func testReplaceName() {
let input = "<!@_username_@!>"
let output = FileTemplateParser.parseTest(input) { (component) -> String in
switch component {
case .UserName:
return "david"
case .ProjectName:
XCTFail()
return "fail"
}
}
XCTAssertEqual(output, "david")
}
func testReplaceMultiple() {
let input = "<!@_username_@!><!@_projectname_@!>"
let output = FileTemplateParser.parseTest(input) { (component) -> String in
switch component {
case .UserName:
return "david"
case .ProjectName:
return "project"
}
}
XCTAssertEqual(output, "davidproject")
}
func testNoReplace() {
let input = "this is a test"
let output = FileTemplateParser.parseTest(input) { (component) -> String in
switch component {
case .UserName:
XCTFail()
return "david"
case .ProjectName:
XCTFail()
return "project"
}
}
XCTAssertEqual(output, input)
}
func testDontReplaceSpecial() {
let input = "<!@_unsupported_@!>"
let output = FileTemplateParser.parseTest(input) { (component) -> String in
switch component {
case .UserName:
XCTFail()
return "david"
case .ProjectName:
XCTFail()
return "fail"
}
}
XCTAssertEqual(output, input)
}
}
| mit | f5fbf5c48c70b02b6c06f82e001ca6e2 | 17.9375 | 77 | 0.656766 | 3.389262 | false | true | false | false |
noppoMan/Prorsum | Sources/Prorsum/HTTP/Message/Cookie.swift | 1 | 2310 | //The MIT License (MIT)
//
//Copyright (c) 2015 Zewo
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
public struct Cookie : CookieProtocol {
public var name: String
public var value: String
public init(name: String, value: String) {
self.name = name
self.value = value
}
}
extension Cookie : Hashable {
public var hashValue: Int {
return name.hashValue
}
}
extension Cookie : Equatable {}
public func == (lhs: Cookie, rhs: Cookie) -> Bool {
return lhs.hashValue == rhs.hashValue
}
extension Cookie : CustomStringConvertible {
public var description: String {
return "\(name)=\(value)"
}
}
public protocol CookieProtocol {
init(name: String, value: String)
}
extension Set where Element : CookieProtocol {
public init?(cookieHeader: String) {
var cookies = Set<Element>()
let tokens = cookieHeader.split(separator: ";")
for token in tokens {
let cookieTokens = token.split(separator: "=", maxSplits: 1)
guard cookieTokens.count == 2 else {
return nil
}
cookies.insert(Element(name: cookieTokens[0].trim(), value: cookieTokens[1].trim()))
}
self = cookies
}
}
| mit | dd9654d3b6e5ea207d8f0e59a7f0e1ed | 31.083333 | 96 | 0.675325 | 4.511719 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift | 82 | 4887 | //
// Completable+AndThen.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/2/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Single<E>) -> Single<E> {
let completable = self.primitiveSequence.asObservable()
return Single(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Maybe<E>) -> Maybe<E> {
let completable = self.primitiveSequence.asObservable()
return Maybe(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen(_ second: Completable) -> Completable {
let completable = self.primitiveSequence.asObservable()
return Completable(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Observable<E>) -> Observable<E> {
let completable = self.primitiveSequence.asObservable()
return ConcatCompletable(completable: completable, second: second.asObservable())
}
}
final fileprivate class ConcatCompletable<Element> : Producer<Element> {
fileprivate let _completable: Observable<Never>
fileprivate let _second: Observable<Element>
init(completable: Observable<Never>, second: Observable<Element>) {
self._completable = completable
self._second = second
}
override func run<O>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O : ObserverType, O.E == Element {
let sink = ConcatCompletableSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final fileprivate class ConcatCompletableSink<O: ObserverType>
: Sink<O>
, ObserverType {
typealias E = Never
typealias Parent = ConcatCompletable<O.E>
private let _parent: Parent
private let _subscription = SerialDisposable()
init(parent: Parent, observer: O, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .next:
break
case .completed:
let otherSink = ConcatCompletableSinkOther(parent: self)
_subscription.disposable = _parent._second.subscribe(otherSink)
}
}
func run() -> Disposable {
let subscription = SingleAssignmentDisposable()
_subscription.disposable = subscription
subscription.setDisposable(_parent._completable.subscribe(self))
return _subscription
}
}
final fileprivate class ConcatCompletableSinkOther<O: ObserverType>
: ObserverType {
typealias E = O.E
typealias Parent = ConcatCompletableSink<O>
private let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<O.E>) {
_parent.forwardOn(event)
if event.isStopEvent {
_parent.dispose()
}
}
}
| mit | f9e8acb57559fcd2320d2b6232142706 | 36.015152 | 148 | 0.682358 | 4.804326 | false | false | false | false |
jtsmrd/Intrview | ViewControllers/SpotlightsTVC.swift | 1 | 5486 | //
// SpotlightsTVC.swift
// SnapInterview
//
// Created by JT Smrdel on 1/24/17.
// Copyright © 2017 SmrdelJT. All rights reserved.
//
import UIKit
protocol SpotlightsTVCDelegate {
func spotlightDataModified()
}
class SpotlightsTVC: UITableViewController, SpotlightsTVCDelegate {
var profile = (UIApplication.shared.delegate as! AppDelegate).profile
var spotlights = [Spotlight]()
var spotlightDetailVC: SpotlightDetailVC!
override func viewDidLoad() {
super.viewDidLoad()
spotlightDetailVC = SpotlightDetailVC(nibName: "SpotlightDetailVC", bundle: nil)
navigationController?.navigationBar.barTintColor = UIColor(red: 0, green: (162/255), blue: (4/255), alpha: 1)
let attributes = [NSForegroundColorAttributeName : UIColor.white]
navigationController?.navigationBar.titleTextAttributes = attributes
navigationItem.title = "Spotlights"
tableView.register(UINib(nibName: "SpotlightCell", bundle: nil), forCellReuseIdentifier: "SpotlightCell")
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
switch profile.profileType! {
case .Business:
self.spotlights = (self.profile.businessProfile?.spotlightCollection.spotlights)!
let newSpotlightCount = self.spotlights.filter({ (spotlight) -> Bool in
spotlight.businessNewFlag == true
}).count
if newSpotlightCount > 0 {
DispatchQueue.main.async {
self.tabBarItem.badgeValue = "\(newSpotlightCount)"
}
}
else {
DispatchQueue.main.async {
self.tabBarItem.badgeValue = nil
}
}
case .Individual:
self.spotlights = (self.profile.individualProfile?.spotlightCollection.spotlights)!
let newSpotlightCount = self.spotlights.filter({ (spotlight) -> Bool in
spotlight.individualNewFlag == true
}).count
if newSpotlightCount > 0 {
DispatchQueue.main.async {
self.tabBarItem.badgeValue = "\(newSpotlightCount)"
}
}
else {
DispatchQueue.main.async {
self.tabBarItem.badgeValue = nil
}
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
func spotlightDataModified() {
switch profile.profileType! {
case .Business:
self.spotlights = (self.profile.businessProfile?.spotlightCollection.spotlights)!
case .Individual:
self.spotlights = (self.profile.individualProfile?.spotlightCollection.spotlights)!
}
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if spotlights.isEmpty {
return 1
}
else {
return spotlights.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let spotlightCell = tableView.dequeueReusableCell(withIdentifier: "SpotlightCell", for: indexPath) as! SpotlightCell
let noDataCell = UITableViewCell(style: .default, reuseIdentifier: "NoDataCell")
switch profile.profileType! {
case .Business:
if !spotlights.isEmpty {
spotlightCell.configureCell(spotlight: spotlights[indexPath.row], profileName: spotlights[indexPath.row].individualName!, isNew: spotlights[indexPath.row].businessNewFlag)
return spotlightCell
}
else {
noDataCell.textLabel?.text = "No Spotlights Yet"
noDataCell.textLabel?.textColor = Global.grayColor
noDataCell.textLabel?.textAlignment = .center
return noDataCell
}
case .Individual:
if !spotlights.isEmpty {
spotlightCell.configureCell(spotlight: spotlights[indexPath.row], profileName: spotlights[indexPath.row].businessName!, isNew: spotlights[indexPath.row].individualNewFlag)
return spotlightCell
}
else {
noDataCell.textLabel?.text = "Search for a company to send a Spotlight"
noDataCell.textLabel?.textColor = Global.grayColor
noDataCell.textLabel?.textAlignment = .center
return noDataCell
}
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedSpotlight = spotlights[indexPath.row]
spotlightDetailVC.spotlight = selectedSpotlight
spotlightDetailVC.delegate = self
navigationController?.pushViewController(spotlightDetailVC, animated: true)
}
}
| mit | cebe0350261ef03abb38a97db293dc02 | 33.71519 | 187 | 0.590702 | 5.512563 | false | false | false | false |
kitasuke/PagingMenuController | Pod/Classes/MenuItemView.swift | 2 | 13531 | //
// MenuItemView.swift
// PagingMenuController
//
// Created by Yusuke Kita on 5/9/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
open class MenuItemView: UIView {
lazy public var titleLabel: UILabel = self.initLabel()
lazy public var descriptionLabel: UILabel = self.initLabel()
lazy public var menuImageView: UIImageView = {
$0.isUserInteractionEnabled = true
$0.translatesAutoresizingMaskIntoConstraints = false
return $0
}(UIImageView(frame: .zero))
public fileprivate(set) var customView: UIView? {
didSet {
guard let customView = customView else { return }
addSubview(customView)
}
}
public internal(set) var isSelected: Bool = false {
didSet {
if case .roundRect = menuOptions.focusMode {
backgroundColor = UIColor.clear
} else {
backgroundColor = isSelected ? menuOptions.selectedBackgroundColor : menuOptions.backgroundColor
}
switch menuItemOptions.displayMode {
case .text(let title):
updateLabel(titleLabel, text: title)
// adjust label width if needed
let labelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize)
widthConstraint.constant = labelSize.width
case let .multilineText(title, description):
updateLabel(titleLabel, text: title)
updateLabel(descriptionLabel, text: description)
// adjust label width if needed
widthConstraint.constant = calculateLabelSize(titleLabel, maxWidth: maxWindowSize).width
descriptionWidthConstraint.constant = calculateLabelSize(descriptionLabel, maxWidth: maxWindowSize).width
case let .image(image, selectedImage):
menuImageView.image = isSelected ? (selectedImage ?? image) : image
case .custom: break
}
}
}
lazy public fileprivate(set) var dividerImageView: UIImageView? = { [unowned self] in
guard let image = self.menuOptions.dividerImage else { return nil }
let imageView = UIImageView(image: image)
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
fileprivate var menuOptions: MenuViewCustomizable!
fileprivate var menuItemOptions: MenuItemViewCustomizable!
fileprivate var widthConstraint: NSLayoutConstraint!
fileprivate var descriptionWidthConstraint: NSLayoutConstraint!
fileprivate var horizontalMargin: CGFloat {
switch menuOptions.displayMode {
case .segmentedControl: return 0.0
default: return menuItemOptions.horizontalMargin
}
}
// MARK: - Lifecycle
internal init(menuOptions: MenuViewCustomizable, menuItemOptions: MenuItemViewCustomizable, addDiveder: Bool) {
super.init(frame: .zero)
self.menuOptions = menuOptions
self.menuItemOptions = menuItemOptions
switch menuItemOptions.displayMode {
case .text(let title):
commonInit({
self.setupTitleLabel(title)
self.layoutLabel()
})
case let .multilineText(title, description):
commonInit({
self.setupMultilineLabel(title, description: description)
self.layoutMultiLineLabel()
})
case .image(let image, _):
commonInit({
self.setupImageView(image)
self.layoutImageView()
})
case .custom(let view):
commonInit({
self.setupCustomView(view)
self.layoutCustomView()
})
}
}
fileprivate func commonInit(_ setupContentView: () -> Void) {
setupView()
setupContentView()
setupDivider()
layoutDivider()
}
fileprivate func initLabel() -> UILabel {
let label = UILabel(frame: .zero)
label.numberOfLines = 1
label.textAlignment = .center
label.isUserInteractionEnabled = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Constraints manager
internal func updateConstraints(_ size: CGSize) {
// set width manually to support ratotaion
guard case .segmentedControl = menuOptions.displayMode else { return }
switch menuItemOptions.displayMode {
case .text:
let labelSize = calculateLabelSize(titleLabel, maxWidth: size.width)
widthConstraint.constant = labelSize.width
case .multilineText:
widthConstraint.constant = calculateLabelSize(titleLabel, maxWidth: size.width).width
descriptionWidthConstraint.constant = calculateLabelSize(descriptionLabel, maxWidth: size.width).width
case .image, .custom:
widthConstraint.constant = size.width / CGFloat(menuOptions.itemsOptions.count)
}
}
// MARK: - Constructor
fileprivate func setupView() {
if case .roundRect = menuOptions.focusMode {
backgroundColor = UIColor.clear
} else {
backgroundColor = menuOptions.backgroundColor
}
translatesAutoresizingMaskIntoConstraints = false
}
fileprivate func setupTitleLabel(_ text: MenuItemText) {
setupLabel(titleLabel, text: text)
}
fileprivate func setupMultilineLabel(_ text: MenuItemText, description: MenuItemText) {
setupLabel(titleLabel, text: text)
setupLabel(descriptionLabel, text: description)
}
fileprivate func setupLabel(_ label: UILabel, text: MenuItemText) {
label.text = text.text
updateLabel(label, text: text)
addSubview(label)
}
fileprivate func updateLabel(_ label: UILabel, text: MenuItemText) {
label.textColor = isSelected ? text.selectedColor : text.color
label.font = isSelected ? text.selectedFont : text.font
}
fileprivate func setupImageView(_ image: UIImage) {
menuImageView.image = image
addSubview(menuImageView)
}
fileprivate func setupCustomView(_ view: UIView) {
customView = view
}
fileprivate func setupDivider() {
guard let dividerImageView = dividerImageView else { return }
addSubview(dividerImageView)
}
fileprivate func layoutMultiLineLabel() {
// H:|[titleLabel(==labelSize.width)]|
// H:|[descriptionLabel(==labelSize.width)]|
// V:|-margin-[titleLabel][descriptionLabel]-margin|
let titleLabelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize)
let descriptionLabelSize = calculateLabelSize(descriptionLabel, maxWidth: maxWindowSize)
let verticalMargin = max(menuOptions.height - (titleLabelSize.height + descriptionLabelSize.height), 0) / 2
widthConstraint = titleLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: titleLabelSize.width)
descriptionWidthConstraint = descriptionLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: descriptionLabelSize.width)
NSLayoutConstraint.activate([
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
widthConstraint,
descriptionLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
descriptionLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
descriptionWidthConstraint,
titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: verticalMargin),
titleLabel.bottomAnchor.constraint(equalTo: descriptionLabel.topAnchor, constant: 0),
descriptionLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: verticalMargin),
titleLabel.heightAnchor.constraint(equalToConstant: titleLabelSize.height),
])
}
fileprivate func layoutLabel() {
// H:|[titleLabel](==labelSize.width)|
// V:|[titleLabel]|
let titleLabelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize)
widthConstraint = titleLabel.widthAnchor.constraint(equalToConstant: titleLabelSize.width)
NSLayoutConstraint.activate([
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
widthConstraint,
titleLabel.topAnchor.constraint(equalTo: topAnchor),
titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
])
}
fileprivate func layoutImageView() {
guard let image = menuImageView.image else { return }
let width: CGFloat
switch menuOptions.displayMode {
case .segmentedControl:
if let windowWidth = UIApplication.shared.keyWindow?.bounds.size.width {
width = windowWidth / CGFloat(menuOptions.itemsOptions.count)
} else {
width = UIScreen.main.bounds.width / CGFloat(menuOptions.itemsOptions.count)
}
default:
width = image.size.width + horizontalMargin * 2
}
widthConstraint = widthAnchor.constraint(equalToConstant: width)
NSLayoutConstraint.activate([
menuImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
menuImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
menuImageView.widthAnchor.constraint(equalToConstant: image.size.width),
menuImageView.heightAnchor.constraint(equalToConstant: image.size.height),
widthConstraint
])
}
fileprivate func layoutCustomView() {
guard let customView = customView else { return }
widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: customView.frame.width)
NSLayoutConstraint.activate([
NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: customView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: customView.frame.width),
NSLayoutConstraint(item: customView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: customView.frame.height),
widthConstraint
])
}
fileprivate func layoutDivider() {
guard let dividerImageView = dividerImageView else { return }
NSLayoutConstraint.activate([
dividerImageView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 1.0),
dividerImageView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
}
extension MenuItemView {
func cleanup() {
switch menuItemOptions.displayMode {
case .text:
titleLabel.removeFromSuperview()
case .multilineText:
titleLabel.removeFromSuperview()
descriptionLabel.removeFromSuperview()
case .image:
menuImageView.removeFromSuperview()
case .custom:
customView?.removeFromSuperview()
}
dividerImageView?.removeFromSuperview()
}
}
// MARK: Lable Size
extension MenuItemView {
fileprivate func labelWidth(_ widthMode: MenuItemWidthMode, estimatedSize: CGSize) -> CGFloat {
switch widthMode {
case .flexible: return ceil(estimatedSize.width)
case .fixed(let width): return width
}
}
fileprivate func estimatedLabelSize(_ label: UILabel) -> CGSize {
guard let text = label.text else { return .zero }
return NSString(string: text).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: label.font], context: nil).size
}
fileprivate func calculateLabelSize(_ label: UILabel, maxWidth: CGFloat) -> CGSize {
guard let _ = label.text else { return .zero }
let itemWidth: CGFloat
switch menuOptions.displayMode {
case .standard(let widthMode, _, _):
itemWidth = labelWidth(widthMode, estimatedSize: estimatedLabelSize(label))
case .segmentedControl:
itemWidth = maxWidth / CGFloat(menuOptions.itemsOptions.count)
case .infinite(let widthMode, _):
itemWidth = labelWidth(widthMode, estimatedSize: estimatedLabelSize(label))
}
let itemHeight = floor(estimatedLabelSize(label).height)
return CGSize(width: itemWidth + horizontalMargin * 2, height: itemHeight)
}
fileprivate var maxWindowSize: CGFloat {
return UIApplication.shared.keyWindow?.bounds.width ?? UIScreen.main.bounds.width
}
}
| mit | 5d6dc5a5f616b3c84f7275855229a8cb | 40.12766 | 245 | 0.649767 | 5.612194 | false | false | false | false |
giangbvnbgit128/AnViet | AnViet/Class/Helpers/Extensions/UIWindow.swift | 1 | 1606 | //
// UIWindow.swift
// Koshien
//
// Created by Nguyen Nguyen Khoi on 6/2/16.
// Copyright © 2016 Khoi Nguyen Nguyen. All rights reserved.
//
import UIKit
public extension UIWindow {
func visibleViewController() -> UIViewController? {
if let rootViewController: UIViewController = self.rootViewController {
return UIWindow.getVisibleViewControllerFrom(rootViewController)
}
return nil
}
class func getVisibleViewControllerFrom(_ vc:UIViewController) -> UIViewController? {
if vc.isKind(of: UINavigationController.self) {
if let navigationController = vc as? UINavigationController,
let visibleVC = navigationController.visibleViewController {
return UIWindow.getVisibleViewControllerFrom(visibleVC)
} else {
return nil
}
} else if vc.isKind(of: UITabBarController.self) {
if let tabBarController = vc as? UITabBarController,
let selectedVC = tabBarController.selectedViewController {
return UIWindow.getVisibleViewControllerFrom(selectedVC)
} else {
return nil
}
} else {
if let presentedViewController = vc.presentedViewController,
let presentVC = presentedViewController.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(presentVC)
} else {
return vc;
}
}
}
}
| apache-2.0 | e2269bef524711fb98c5fe2d5e2597e1 | 31.755102 | 89 | 0.594393 | 6.125954 | false | false | false | false |
lyimin/iOS-Animation-Demo | iOS-Animation学习笔记/iOS-Animation学习笔记/SlidingPanels/RoomTransition.swift | 1 | 5241 | //
// RoomTransition.swift
// iOS-Animation学习笔记
//
// Created by 梁亦明 on 16/4/18.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
class RoomTransition: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
/**
状态
- None: 无
- Presenting: 进入
- Dismissing: 销毁
*/
enum State {
case none
case presenting
case dismissing
}
var state = State.none
var presentingController: UIViewController!
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.6
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let duration = transitionDuration(using: transitionContext)
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let containerView = transitionContext.containerView
var backgroundViewController = fromViewController
var foregroundViewController = toViewController
if (state == .dismissing) {
backgroundViewController = toViewController
foregroundViewController = fromViewController
}
// get detail view from view controllers
let backgroundDetailViewMaybe = (backgroundViewController as? PanelTransitionViewController)?.panelTransitionDetailViewForTransition(self)
let foregroundDetailViewMaybe = (foregroundViewController as? PanelTransitionViewController)?.panelTransitionDetailViewForTransition(self)
assert(backgroundDetailViewMaybe != nil, "Cannot find detail view in background view controller")
assert(foregroundDetailViewMaybe != nil, "Cannot find detail view in foreground view controller")
let backgroundDetailView = backgroundDetailViewMaybe!
let foregroundDetailView = foregroundDetailViewMaybe!
// add views to container
containerView.addSubview(backgroundViewController.view)
let wrapperView = UIView(frame: foregroundViewController.view.frame)
wrapperView.layer.shadowRadius = 5
wrapperView.layer.shadowOpacity = 0.3
wrapperView.layer.shadowOffset = CGSize.zero
wrapperView.addSubview(foregroundViewController.view)
foregroundViewController.view.clipsToBounds = true
containerView.addSubview(wrapperView)
// perform animation
(foregroundViewController as? PanelTransitionViewController)?.panelTransitionWillAnimateTransition?(self, presenting: state == .presenting, isForeground: true)
backgroundDetailView.isHidden = true
let backgroundFrame = containerView.convert(backgroundDetailView.frame, from: backgroundDetailView.superview)
let screenBounds = UIScreen.main.bounds
let scale = backgroundFrame.width / screenBounds.width
if state == .presenting {
wrapperView.transform = CGAffineTransform(scaleX: scale, y: scale)
foregroundDetailView.transitionProgress = 1
}
else {
wrapperView.transform = CGAffineTransform.identity
}
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { () -> Void in
[self]
if self.state == .presenting {
wrapperView.transform = CGAffineTransform.identity
foregroundDetailView.transitionProgress = 0
}
else {
wrapperView.transform = CGAffineTransform(scaleX: scale, y: scale)
foregroundDetailView.transitionProgress = 1
}
}) { (finished) -> Void in
backgroundDetailView.isHidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presentingController = presenting
if presented is PanelTransitionViewController &&
presenting is PanelTransitionViewController {
state = .presenting
return self
}
return nil
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if dismissed is PanelTransitionViewController &&
presentingController is PanelTransitionViewController {
state = .dismissing
return self
}
return nil
}
}
@objc
protocol PanelTransitionViewController {
func panelTransitionDetailViewForTransition(_ transition: RoomTransition) -> RoomsDetailView!
@objc optional func panelTransitionWillAnimateTransition(_ transition: RoomTransition, presenting: Bool, isForeground: Bool)
}
| mit | 658e112442391c5af2dbf9efe4405d8b | 40.349206 | 174 | 0.691363 | 6.46402 | false | false | false | false |
imitationgame/pokemonpassport | pokepass/Model/Create/MCreate.swift | 1 | 1085 | import Foundation
import CoreLocation
class MCreate
{
var locations:[MCreateAnnotation]
init()
{
locations = []
}
//MARK: public
func load(project:MProjectsItem)
{
var locations:[MCreateAnnotation] = []
if let dbLocations:NSOrderedSet = project.model.projectLocations
{
for dbLocation:Any in dbLocations
{
guard
let dbObject:DObjectLocation = dbLocation as? DObjectLocation
else
{
continue
}
let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(
latitude:dbObject.latitude,
longitude:dbObject.longitude)
let location:MCreateAnnotation = MCreateAnnotation(
coordinate:coordinate)
locations.append(location)
}
}
self.locations = locations
}
}
| mit | 40673608d0f3f1388905d45975cce2c1 | 23.659091 | 81 | 0.485714 | 6.271676 | false | false | false | false |
modocache/swift | test/SILGen/erasure_reabstraction.swift | 3 | 789 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
struct Foo {}
class Bar {}
// CHECK: [[CONCRETE:%.*]] = init_existential_addr [[EXISTENTIAL:%.*]] : $*Any, $Foo.Type
// CHECK: [[METATYPE:%.*]] = metatype $@thick Foo.Type
// CHECK: store [[METATYPE]] to [[CONCRETE]] : $*@thick Foo.Type
let x: Any = Foo.self
// CHECK: [[CONCRETE:%.*]] = init_existential_addr [[EXISTENTIAL:%.*]] : $*Any, $() -> ()
// CHECK: [[CLOSURE:%.*]] = function_ref
// CHECK: [[CLOSURE_THICK:%.*]] = thin_to_thick_function [[CLOSURE]]
// CHECK: [[REABSTRACTION_THUNK:%.*]] = function_ref @_TTRXFo___XFo_iT__iT__
// CHECK: [[CLOSURE_REABSTRACTED:%.*]] = partial_apply [[REABSTRACTION_THUNK]]([[CLOSURE_THICK]])
// CHECK: store [[CLOSURE_REABSTRACTED]] to [[CONCRETE]]
let y: Any = {() -> () in ()}
| apache-2.0 | b9962133ad8325b6288954e331a22784 | 40.526316 | 97 | 0.599493 | 3.506667 | false | false | false | false |
maxim-pervushin/HyperHabit | HyperHabit/HyperHabit/Extensions/NSDate+HyperHabit.swift | 1 | 7546 | //
// Created by Maxim Pervushin on 22/12/15.
// Copyright (c) 2015 Maxim Pervushin. All rights reserved.
//
import Foundation
extension NSDate {
func firstDayOfMonth() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components([.Year, .Month, .Day], fromDate: self)
dateComponent.day = 1
return calendar.dateFromComponents(dateComponent)!
}
convenience init(year: Int, month: Int, day: Int) {
let calendar = NSCalendar.currentCalendar()
let dateComponent = NSDateComponents()
dateComponent.year = year
dateComponent.month = month
dateComponent.day = day
self.init(timeInterval: 0, sinceDate: calendar.dateFromComponents(dateComponent)!)
}
func dateByAddingMonths(months: Int) -> NSDate {
let calendar = NSCalendar.currentCalendar()
let dateComponent = NSDateComponents()
dateComponent.month = months
return calendar.dateByAddingComponents(dateComponent, toDate: self, options: NSCalendarOptions.MatchNextTime)!
}
func dateByAddingDays(days: Int) -> NSDate {
let calendar = NSCalendar.currentCalendar()
let dateComponent = NSDateComponents()
dateComponent.day = days
return calendar.dateByAddingComponents(dateComponent, toDate: self, options: NSCalendarOptions.MatchNextTime)!
}
func hour() -> Int {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components(.Hour, fromDate: self)
return dateComponent.hour
}
func second() -> Int {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components(.Second, fromDate: self)
return dateComponent.second
}
func minute() -> Int {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components(.Minute, fromDate: self)
return dateComponent.minute
}
func day() -> Int {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components(.Day, fromDate: self)
return dateComponent.day
}
func weekday() -> Int {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components(.Weekday, fromDate: self)
return dateComponent.weekday
}
func month() -> Int {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components(.Month, fromDate: self)
return dateComponent.month
}
func year() -> Int {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components(.Year, fromDate: self)
return dateComponent.year
}
func numberOfDaysInMonth() -> Int {
let calendar = NSCalendar.currentCalendar()
let days = calendar.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: self)
return days.length
}
func dateByIgnoringTime() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let dateComponent = calendar.components([.Year, .Month, .Day], fromDate: self)
return calendar.dateFromComponents(dateComponent)!
}
func isSunday() -> Bool {
return (self.getWeekday() == 1)
}
func isMonday() -> Bool {
return (self.getWeekday() == 2)
}
func isTuesday() -> Bool {
return (self.getWeekday() == 3)
}
func isWednesday() -> Bool {
return (self.getWeekday() == 4)
}
func isThursday() -> Bool {
return (self.getWeekday() == 5)
}
func isFriday() -> Bool {
return (self.getWeekday() == 6)
}
func isSaturday() -> Bool {
return (self.getWeekday() == 7)
}
func getWeekday() -> Int {
let calendar = NSCalendar.currentCalendar()
return calendar.components(.Weekday, fromDate: self).weekday
}
func isToday() -> Bool {
let cal = NSCalendar.currentCalendar()
var components = cal.components([.Era, .Year, .Month, .Day], fromDate: NSDate())
let today = cal.dateFromComponents(components)!
components = cal.components([.Era, .Year, .Month, .Day], fromDate: self);
let otherDate = cal.dateFromComponents(components)!
return (today.isEqualToDate(otherDate))
}
}
func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
func <=(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending || lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
func >(lhs: NSDate, rhs: NSDate) -> Bool {
return rhs.compare(lhs) == NSComparisonResult.OrderedAscending
}
func >=(lhs: NSDate, rhs: NSDate) -> Bool {
return rhs.compare(lhs) == NSComparisonResult.OrderedAscending || rhs.compare(lhs) == NSComparisonResult.OrderedSame
}
extension NSDate {
private static var longDateRelativeFormatter: NSDateFormatter {
struct Static {
static var onceToken: dispatch_once_t = 0
static var formatter: NSDateFormatter! = nil
}
dispatch_once(&Static.onceToken) {
Static.formatter = NSDateFormatter()
Static.formatter.dateStyle = .LongStyle
Static.formatter.doesRelativeDateFormatting = true
}
return Static.formatter
}
var longDateRelativeString: String {
return NSDate.longDateRelativeFormatter.stringFromDate(self)
}
}
extension NSDate {
// Long string
private static var longDateFormatter: NSDateFormatter {
struct Static {
static var onceToken: dispatch_once_t = 0
static var formatter: NSDateFormatter! = nil
}
dispatch_once(&Static.onceToken) {
Static.formatter = NSDateFormatter()
Static.formatter.dateStyle = .LongStyle
}
return Static.formatter
}
var longDateString: String {
return NSDate.longDateFormatter.stringFromDate(self)
}
}
extension NSDate {
// Date component string
private static var dateComponentFormatter: NSDateFormatter {
struct Static {
static var onceToken: dispatch_once_t = 0
static var formatter: NSDateFormatter! = nil
}
dispatch_once(&Static.onceToken) {
Static.formatter = NSDateFormatter()
Static.formatter.dateFormat = "yyyy-MM-dd"
}
return Static.formatter
}
static func dateWithDateComponent(dateComponent: String) -> NSDate? {
return dateComponentFormatter.dateFromString(dateComponent)
}
var dateComponent: String {
return NSDate.dateComponentFormatter.stringFromDate(self)
}
}
extension NSDate {
private static var monthYearFormatter: NSDateFormatter {
struct Static {
static var onceToken: dispatch_once_t = 0
static var formatter: NSDateFormatter! = nil
}
dispatch_once(&Static.onceToken) {
Static.formatter = NSDateFormatter()
Static.formatter.dateFormat = "MMMM, yyyy"
}
return Static.formatter
}
static func dateWithMonthYear(monthYear: String) -> NSDate? {
return monthYearFormatter.dateFromString(monthYear)
}
var monthYear: String {
return NSDate.monthYearFormatter.stringFromDate(self)
}
}
| mit | 8fedc9770f4d3c8368ea2b74c4b567e3 | 28.361868 | 120 | 0.644977 | 4.935252 | false | false | false | false |
makingspace/NetworkingServiceKit | NetworkingServiceKit/Classes/Service.swift | 1 | 9647 | //
// Service.swift
// Makespace Inc.
//
// Created by Phillipe Casorla Sagot (@darkzlave) on 2/27/17.
//
//
import Foundation
import Alamofire
/// Defines the necessary methods that a service should implement
public protocol Service {
/// Builds a service with an auth token and a networkManager implementation
///
/// - Parameters:
/// - token: an auth token (if we are authenticated)
/// - networkManager: the networkManager we are currently using
init(token: APIToken?, networkManager: NetworkManager)
/// Current auth token this service has
var token: APIToken? { get set }
/// Current network manger this service is using
var networkManager: NetworkManager { get set }
/// Current API configuration
var currentConfiguration: APIConfiguration { get }
/// Default service version
var serviceVersion: String { get }
/// Default service path
var servicePath: String { get }
/// Builds a service query path with our version and default root path
///
/// - Parameters:
/// - query: the query to build
/// - overrideURL: manual override of default base URL
/// - overrideVersion: manual override of the service version
/// - Returns: a compose query with the baseURL, service version and service path included
func servicePath(for query: String, baseUrlOverride overrideURL: String?, serviceVersionOverride overrideVersion: String?) -> String
/// True if our auth token is valid
var isAuthenticated: Bool { get }
/// Executes a request with out current network Manager
///
/// - Parameters:
/// - path: a full URL
/// - baseUrlOverride: manual override of default base URL
/// - serviceVersionOverride: manual override of the service version
/// - method: HTTP method
/// - parameters: parameters for the request
/// - paginated: if we have to merge this request pagination
/// - cachePolicy: specifices the policy to follow for caching responses
/// - headers: optional headers to include in the request
/// - success: success block
/// - failure: failure block
func request(path: String,
baseUrlOverride: String?,
serviceVersionOverride: String?,
method: NetworkingServiceKit.HTTPMethod,
with parameters: RequestParameters,
paginated: Bool,
cachePolicy: CacheResponsePolicy,
headers: CustomHTTPHeaders,
success: @escaping SuccessResponseBlock,
failure: @escaping ErrorResponseBlock)
/// Returns a list of Service Stubs (api paths with a stub type)
var stubs:[ServiceStub] { get set }
}
/// Abstract Base Service, sets up a default implementations of the Service protocol. Defaults the service path and version into empty strings.
open class AbstractBaseService: NSObject, Service {
open var networkManager: NetworkManager
open var token: APIToken?
open var stubs:[ServiceStub] = [ServiceStub]()
open var currentConfiguration: APIConfiguration {
return self.networkManager.configuration
}
/// Init method for an Service, each service must have the current token auth and access to the networkManager to execute requests
///
/// - Parameters:
/// - token: an existing APIToken
/// - networkManager: an object that supports our NetworkManager protocol
public required init(token: APIToken?, networkManager: NetworkManager) {
self.token = token
self.networkManager = networkManager
}
/// Currently supported version of the service
open var serviceVersion: String {
return ""
}
/// Name here your service path
open var servicePath: String {
return ""
}
/// Returns the baseURL for this service, default is the current configuration URL
open var baseURL: String {
return currentConfiguration.baseURL
}
/// Returns a local path for an API request, this includes the service version and name. i.e v4/accounts/user_profile
///
/// - Parameters:
/// - query: api local path
/// - overrideURL: manual override of default base URL
/// - overrideVersion: manual override of the service version
/// - Returns: local path to the api for the given query
open func servicePath(for query: String, baseUrlOverride overrideURL: String?, serviceVersionOverride overrideVersion: String?) -> String {
var fullPath = overrideURL ?? self.baseURL
if (!self.servicePath.isEmpty) {
fullPath += "/" + self.servicePath
}
if let version = overrideVersion {
fullPath += "/" + version
}
else if (!self.serviceVersion.isEmpty) {
fullPath += "/" + self.serviceVersion
}
fullPath += "/" + query
return fullPath
}
/// Returns if this service has a valid token for authentication with our systems
open var isAuthenticated: Bool {
return (APITokenManager.currentToken != nil)
}
/// Creates and executes a request using our default Network Manager
///
/// - Parameters:
/// - path: full path to the URL
/// - baseUrlOverride: manual override of default base URL
/// - method: HTTP method, default is GET
/// - parameters: URL or body parameters depending on the HTTP method, default is empty
/// - paginated: if the request should follow pagination, success only if all pages are completed
/// - cachePolicy: specifices the policy to follow for caching responses
/// - headers: custom headers that should be attached with this request
/// - success: success block with a response
/// - failure: failure block with an error
open func request(path: String,
baseUrlOverride: String? = nil,
serviceVersionOverride: String? = nil,
method: NetworkingServiceKit.HTTPMethod = .get,
with parameters: RequestParameters = RequestParameters(),
paginated: Bool = false,
cachePolicy: CacheResponsePolicy = CacheResponsePolicy.default,
headers: CustomHTTPHeaders = CustomHTTPHeaders(),
success: @escaping SuccessResponseBlock,
failure: @escaping ErrorResponseBlock) {
networkManager.request(path: servicePath(for: path,
baseUrlOverride: baseUrlOverride,
serviceVersionOverride: serviceVersionOverride),
method: method,
with: parameters,
paginated: paginated,
cachePolicy: cachePolicy,
headers: headers,
stubs: self.stubs,
success: success,
failure: { error in
if error.hasTokenExpired && self.isAuthenticated {
//If our error response was because our token expired, then lets tell the delegate
ServiceLocator.shared.delegate?.authenticationTokenDidExpire(forService: self)
}
failure(error)
})
}
open func upload(path: String,
baseUrlOverride: String? = nil,
serviceVersionOverride: String? = nil,
withConstructingBlock constructingBlock: @escaping (MultipartFormData) -> Void,
progressBlock: ((Progress) -> Void)? = nil,
headers: CustomHTTPHeaders = CustomHTTPHeaders(),
success: @escaping SuccessResponseBlock,
failure: @escaping ErrorResponseBlock) {
networkManager.upload(path: servicePath(for: path, baseUrlOverride: baseUrlOverride, serviceVersionOverride: serviceVersionOverride),
withConstructingBlock: constructingBlock,
progressBlock: { progressBlock?($0) },
headers: headers,
stubs: self.stubs,
success: success,
failure: { error in
if error.hasTokenExpired && self.isAuthenticated {
//If our error response was because our token expired, then lets tell the delegate
ServiceLocator.shared.delegate?.authenticationTokenDidExpire(forService: self)
}
failure(error)
})
}
}
public extension AbstractBaseService {
static var resolved : Self {
guard let service = ServiceLocator.service(forType: self) else {
fatalError("Service of type \(Self.self) not found. Make sure you register it in the ServiceLocator first")
}
return service
}
static func stubbed(_ stubs: [ServiceStub]) -> Self {
guard let service = ServiceLocator.service(forType: self, stubs: stubs) else {
fatalError("Service of type \(Self.self) not found. Make sure you register it in the ServiceLocator first")
}
return service
}
}
| mit | 0e752d792d9930fa75007a941cb6b264 | 42.066964 | 143 | 0.59376 | 5.638223 | false | false | false | false |
xiwang126/BeeHive-swift | BeeHive-swift/Classes/BHServiceManager.swift | 1 | 3896 | //
// BHServiceManager.swift
// Pods
//
// Created by UgCode on 2017/3/14.
//
//
import Foundation
let kService: String = "service"
let kImpl: String = "impl"
public enum BHServiceManagerError: Error {
case createServiceClassFailed
case instantiationFailure
case protocolHasBeenRegisted
}
open class BHServiceManager {
// MARK: Public
open static let shared = BHServiceManager()
open var isEnableException: Bool = false
var allServices: [ServiceName: String] = [:]
var safeServices: [ServiceName: String] {
lock.lock()
let dic = allServices
lock.unlock()
return dic
}
lazy var lock = NSRecursiveLock()
open func registerLocalServices() {
let serviceConfigName = BHContext.shared.serviceConfigName
guard let plistPath = Bundle.main.path(forResource: serviceConfigName, ofType: "plist") else {
assert(false, "config file path error")
return
}
guard let serviceList = NSArray(contentsOfFile: plistPath) as? [[AnyHashable: String]] else {
assert(false, "read config error")
return
}
lock.lock()
for item in serviceList {
let serviceName = ServiceName(item[kService]!)
allServices[serviceName] = item[kImpl]
}
lock.unlock()
}
// open func registerAnnotationServices() {}
open func register(service: ServiceName, implClass: AnyClass) {
if !(implClass is BHServiceProtocol.Type) {
assert(false, "\(NSStringFromClass(implClass)) module does not comply with BHServiceProtocol protocol")
}
// if implClass.conforms(to: service) && isEnableException {
// assert(false, "\(NSStringFromClass(implClass)) module does not comply with \(NSStringFromProtocol(service)) protocol")
// }
if checkValid(service: service) && isEnableException {
assert(false, "\(service.rawValue) protocol has been registed")
}
lock.lock()
allServices[service] = NSStringFromClass(implClass)
lock.unlock()
}
open func create(service: ServiceName) throws -> AnyObject {
if !checkValid(service: service) && isEnableException {
assert(false, "\(service) protocol has been registed")
throw BHServiceManagerError.protocolHasBeenRegisted
}
guard let implClass = try serviceImplClass(service) as? BHServiceProtocol.Type else {
assert(false, "service Impl Class is nill or not comply BHServiceProtocol")
throw BHServiceManagerError.instantiationFailure
}
let instanceCreater = { implClass.shareInstance() ?? (implClass.init() as AnyObject) }
if implClass.singleton() {
var implInstance = BHContext.shared.getServiceInstance(fromServiceName: service.rawValue)
if implInstance == nil {
implInstance = instanceCreater()
}
BHContext.shared.addService(withImplInstance: implInstance!, serviceName: service.rawValue)
return implInstance!
} else {
return instanceCreater()
}
}
// MARK: Private
func serviceImplClass(_ service: ServiceName) throws -> AnyClass {
for (key, value) in safeServices {
if key == service {
guard let implClass = NSClassFromString(value) else {
throw BHServiceManagerError.createServiceClassFailed
}
return implClass
}
}
throw BHServiceManagerError.createServiceClassFailed
}
func checkValid(service: ServiceName) -> Bool {
for (key, _) in safeServices {
if key == service {
return true
}
}
return false
}
}
| mit | ed3296f00eed6ceb26160cac3d6f913a | 32.016949 | 132 | 0.613193 | 4.821782 | false | false | false | false |
square/wire | wire-library/wire-runtime-swift/src/main/swift/ProtoIntCodable+Implementations.swift | 1 | 4564 | /*
* Copyright 2020 Square Inc.
*
* 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
// MARK: -
extension Int32: ProtoIntCodable {
// MARK: - ProtoIntDecodable
public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// sfixed32 fields
self = try Int32(bitPattern: reader.readFixed32())
case .signed:
// sint32 fields
self = try reader.readVarint32().zigZagDecoded()
case .variable:
// int32 fields
self = try Int32(bitPattern: reader.readVarint32())
}
}
// MARK: - ProtoIntEncodable
/** Encode an `int32`, `sfixed32`, or `sint32` field */
public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// sfixed32 fields
writer.writeFixed32(self)
case .signed:
// sint32 fields
writer.writeVarint(zigZagEncoded())
case .variable:
// int32 fields
writer.writeVarint(UInt32(bitPattern: self))
}
}
}
// MARK: -
extension UInt32: ProtoIntCodable {
// MARK: - ProtoIntDecodable
public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// fixed32 fields
self = try reader.readFixed32()
case .signed:
fatalError("Unsupported")
case .variable:
// uint32 fields
self = try reader.readVarint32()
}
}
// MARK: - ProtoIntEncodable
/** Encode a `uint32` or `fixed32` field */
public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// fixed32 fields
writer.writeFixed32(self)
case .signed:
fatalError("Unsupported")
case .variable:
// uint32 fields
writer.writeVarint(self)
}
}
}
// MARK: -
extension Int64: ProtoIntCodable {
// MARK: - ProtoIntDecodable
public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// sfixed64 fields
self = try Int64(bitPattern: reader.readFixed64())
case .signed:
// sint64 fields
self = try reader.readVarint64().zigZagDecoded()
case .variable:
// int64 fields
self = try Int64(bitPattern: reader.readVarint64())
}
}
// MARK: - ProtoIntEncodable
/** Encode `int64`, `sint64`, or `sfixed64` field */
public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// sfixed64 fields
writer.writeFixed64(self)
case .signed:
// sint64 fields
writer.writeVarint(zigZagEncoded())
case .variable:
// int64 fields
writer.writeVarint(UInt64(bitPattern: self))
}
}
}
// MARK: -
extension UInt64: ProtoIntCodable {
// MARK: - ProtoIntDecodable
public init(from reader: ProtoReader, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// fixed64 fields
self = try reader.readFixed64()
case .signed:
fatalError("Unsupported")
case .variable:
// uint64 fields
self = try reader.readVarint64()
}
}
// MARK: - ProtoIntEncodable
/** Encode a `uint64` or `fixed64` field */
public func encode(to writer: ProtoWriter, encoding: ProtoIntEncoding) throws {
switch encoding {
case .fixed:
// fixed64 fields
writer.writeFixed64(self)
case .signed:
fatalError("Unsupported")
case .variable:
// uint64 fields
writer.writeVarint(self)
}
}
}
| apache-2.0 | a0103106e519d388634967bc135f1ba3 | 26.005917 | 83 | 0.584575 | 4.500986 | false | false | false | false |
GianniCarlo/Audiobook-Player | BookPlayer/Import/ImportManager.swift | 1 | 2127 | //
// ImportManager.swift
// BookPlayer
//
// Created by Gianni Carlo on 9/10/18.
// Copyright © 2018 Tortuga Power. All rights reserved.
//
import BookPlayerKit
import Combine
import Foundation
/**
Handles the creation of ImportOperation objects.
It waits a specified time wherein new files may be added before the operation is created
*/
final class ImportManager {
static let shared = ImportManager()
private let timeout = 2.0
private var subscription: AnyCancellable?
private var timer: Timer?
private var files = CurrentValueSubject<[URL], Never>([])
public func process(_ fileUrl: URL) {
// Avoid duplicating files
guard !self.files.value.contains(where: { $0 == fileUrl }) else { return }
// Avoid processing the creation of the Processed and Inbox folder
if fileUrl.lastPathComponent == DataManager.processedFolderName
|| fileUrl.lastPathComponent == "Inbox" { return }
self.files.value.append(fileUrl)
}
public func observeFiles() -> AnyPublisher<[URL], Never> {
return self.files.eraseToAnyPublisher()
}
public func removeFile(_ item: URL, updateCollection: Bool = true) throws {
if FileManager.default.fileExists(atPath: item.path) {
try FileManager.default.removeItem(at: item)
}
if updateCollection {
self.files.value = self.files.value.filter { $0 != item }
}
}
public func removeAllFiles() throws {
for file in self.files.value {
try self.removeFile(file, updateCollection: false)
}
self.files.value = []
}
public func createOperation() {
guard !self.files.value.isEmpty else { return }
let sortDescriptor = NSSortDescriptor(key: "path", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))
let orderedSet = NSOrderedSet(array: self.files.value)
guard let sortedFiles = orderedSet.sortedArray(using: [sortDescriptor]) as? [URL] else { return }
let operation = ImportOperation(files: sortedFiles)
self.files.value = []
NotificationCenter.default.post(name: .importOperation, object: nil, userInfo: ["operation": operation])
}
}
| gpl-3.0 | c9ce02992f814fe404140402c9c7e2ce | 28.527778 | 131 | 0.70461 | 4.338776 | false | false | false | false |
kenwilcox/LoginProject | LoginProject/LoginViewController.swift | 1 | 1729 | //
// LoginViewController.swift
// LoginProject
//
// Created by Kenneth Wilcox on 2/15/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "loginToCreateAccountSegue" {
var createAccountVC = segue.destinationViewController as CreateAccountViewController
createAccountVC.delegate = self
}
}
@IBAction func loginButtonPressed(sender: UIButton) {
let defaults = NSUserDefaults.standardUserDefaults()
let usernameSaved = defaults.objectForKey(kUserNameKey) as String
println(usernameSaved)
let passwordSaved = defaults.objectForKey(kPasswordKey) as String
println(passwordSaved)
if usernameTextField.text == usernameSaved && passwordTextField.text == passwordSaved {
self.performSegueWithIdentifier("loginToMainSegue", sender: self)
}
}
@IBAction func createAccountButtonPressed(sender: UIButton) {
self.performSegueWithIdentifier("loginToCreateAccountSegue", sender: self)
}
}
// MARK: CreatedAccountViewControllerDelegate
extension LoginViewController: CreateAccountViewControllerDelegate {
func accountCreated() {
self.performSegueWithIdentifier("loginToMainSegue", sender: nil)
}
} | mit | 577eded51f71aec258ad37863d5b423a | 29.892857 | 91 | 0.749566 | 5.223565 | false | false | false | false |
Mazy-ma/MiaoShow | MiaoShow/MiaoShow/Classes/Live/ViewController/LiveViewController.swift | 1 | 5076 | //
// LiveViewController.swift
// MiaoShow
//
// Created by Mazy on 2017/4/7.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
import MJRefresh
let liveCellID = "homeLiveCell"
let screenH = UIScreen.main.bounds.height
class LiveViewController: XMBaseViewController {
var liveModels: [LiveModel] = [LiveModel]()
/// 懒加载tableView
lazy var tableView: UITableView = {
let tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
tableView.dataSource = self
tableView.delegate = self
tableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0)
tableView.scrollIndicatorInsets = tableView.contentInset
return tableView
}()
var currentOffsetY: CGFloat?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// 取消顶部自动约束
automaticallyAdjustsScrollViewInsets = false
tableView.register(UINib.init(nibName: "LiveTableViewCell", bundle: nil), forCellReuseIdentifier: liveCellID)
view.addSubview(tableView)
tableView.rowHeight = view.bounds.width + 60
// 取消分割线
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
navigationItem.title = "广场"
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"search_head")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(search))
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named:"head_crown")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(search))
tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
NetworkManager.shared.get(pullup: false) { (results) in
self.liveModels.removeAll()
self.liveModels = results
// 刷新数据
DispatchQueue.main.async {
self.tableView.reloadData()
self.tableView.mj_header.endRefreshing()
}
}
})
tableView.mj_header.beginRefreshing()
tableView.mj_footer = MJRefreshAutoFooter(refreshingBlock: {
NetworkManager.shared.get(pullup: true) { (results) in
self.liveModels += results
// 刷新数据
DispatchQueue.main.async {
self.tableView.reloadData()
self.tableView.mj_footer.endRefreshing()
}
}
})
}
@objc func search() {
}
override func viewWillAppear(_ animated: Bool) {
if (navigationController?.toolbar.isHidden)! {
navigationController?.setNavigationBarHidden(false, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension LiveViewController:UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.liveModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: liveCellID) as! LiveTableViewCell
cell.liveModel = self.liveModels[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let model = self.liveModels[indexPath.row]
let showVC = LiveShowViewController()
showVC.liveModel = model
show(showVC, sender: nil)
}
}
// MARK: - scrollViewDelegate
extension LiveViewController {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
currentOffsetY = scrollView.contentOffset.y
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let rect = tabBarController?.tabBar.frame
if scrollView.contentOffset.y > currentOffsetY ?? 0 {
let distance = scrollView.contentOffset.y - currentOffsetY!
UIView.animate(withDuration: 0.5, animations: {
if distance < 49.0 {
self.tabBarController?.tabBar.frame = CGRect(x: (rect?.origin.x)!, y: screenH+distance, width: (rect?.width)!, height: (rect?.height)!)
}
self.navigationController?.setNavigationBarHidden(true, animated: true)
})
} else {
UIView.animate(withDuration: 0.5, animations: {
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.tabBarController?.tabBar.frame = CGRect(x: (rect?.origin.x)!, y: screenH-49, width: (rect?.width)!, height: (rect?.height)!)
})
}
}
}
| apache-2.0 | 6ad62902b117210b494c943edff12c2d | 31.816993 | 187 | 0.619 | 5.241127 | false | false | false | false |
sedler/AlamofireRSSParser | Pod/Classes/RSSItem.swift | 1 | 3046 | //
// RSSItem.swift
// AlamofireRSSParser
//
// Created by Donald Angelillo on 3/1/16.
// Copyright © 2016 Donald Angelillo. All rights reserved.
//
import Foundation
/**
Item-level elements are deserialized into `RSSItem` objects and stored in the `items` array of an `RSSFeed` instance
*/
open class RSSItem: CustomStringConvertible {
open var title: String? = nil
open var link: String? = nil
/**
Upon setting this property the `itemDescription` will be scanned for HTML and all image urls will be extracted and stored in `imagesFromDescription`
*/
open var itemDescription: String? = nil {
didSet {
if let itemDescription = self.itemDescription {
self.imagesFromDescription = self.imagesFromHTMLString(itemDescription)
}
}
}
public var content: String? = nil {
didSet {
if let content = self.content?.removingPercentEncoding {
self.imagesFromContent = self.imagesFromHTMLString(content)
}
}
}
open var guid: String? = nil
open var author: String? = nil
open var comments: String? = nil
open var source: String? = nil
open var pubDate: Date? = nil
open var mediaThumbnail: String? = nil;
open var mediaContent: String? = nil
open var featuredImage: String? = nil;
open var imagesFromDescription: [String]? = nil
open var imagesFromContent: [String]? = nil
open var description: String {
return "\ttitle: \(self.title)\n\tlink: \(self.link)\n\titemDescription: \(self.itemDescription)\n\tguid: \(self.guid)\n\tauthor: \(self.author)\n\tcomments: \(self.comments)\n\tsource: \(self.source)\n\tpubDate: \(self.pubDate)\nmediaThumbnail: \(self.mediaThumbnail)\nmediaContent: \(self.mediaContent)\nimagesFromDescription: \(self.imagesFromDescription)\nimagesFromContent: \(self.imagesFromContent)\n\n"
}
/**
Retrieves all the images (\<img\> tags) from a given String contaning HTML using a regex.
- Parameter htmlString: A String containing HTML
- Returns: an array of image url Strings ([String])
*/
fileprivate func imagesFromHTMLString(_ htmlString: String) -> [String] {
let htmlNSString = htmlString as NSString;
var images: [String] = Array();
do {
let regex = try NSRegularExpression(pattern: "(https?)\\S*(png|jpg|jpeg|gif)", options: [NSRegularExpression.Options.caseInsensitive])
regex.enumerateMatches(in: htmlString, options: [NSRegularExpression.MatchingOptions.reportProgress], range: NSMakeRange(0, htmlString.characters.count)) { (result, flags, stop) -> Void in
if let range = result?.range {
images.append(htmlNSString.substring(with: range)) //because Swift ranges are still completely ridiculous
}
}
}
catch {
}
return images;
}
}
| mit | 711eb9e0d161038ad8073169e082c2ef | 37.0625 | 417 | 0.633498 | 4.425872 | false | false | false | false |
artsy/Emergence | Emergence/Contexts/ArtworkSetViewController.swift | 1 | 1891 | import UIKit
class ArtworkSetViewController: UIPageViewController, UIPageViewControllerDataSource {
var artworks:[Artwork]!
var initialIndex: Int!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
dataSource = self
guard let artworkVC = viewControllerForIndex(initialIndex) else {
return print("Wrong current index given to artwork set VC")
}
setViewControllers([artworkVC], direction: .Forward, animated: false, completion: nil)
}
func isValidIndex(index: Int) -> Bool {
return index > -1 && index <= artworks.count - 1
}
func viewControllerForIndex(index: Int) -> ArtworkViewController? {
guard let storyboard = storyboard else { return nil }
guard isValidIndex(index) else { return nil }
guard let artworkVC = storyboard.instantiateViewControllerWithIdentifier("artwork") as? ArtworkViewController else { return nil}
artworkVC.artwork = artworks[index]
artworkVC.index = index
return artworkVC
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let currentArtworkVC = viewController as? ArtworkViewController else { return nil }
let newIndex = (currentArtworkVC.index + 1) % self.artworks.count;
return viewControllerForIndex(newIndex)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let currentArtworkVC = viewController as? ArtworkViewController else { return nil }
var newIndex = currentArtworkVC.index - 1
if (newIndex < 0) { newIndex = artworks.count - 1 }
return viewControllerForIndex(newIndex)
}
}
| mit | 33724552a57492bc084122ee554fcc62 | 41.022222 | 161 | 0.715494 | 5.52924 | false | false | false | false |
scotlandyard/expocity | expocity/Firebase/Database/Models/FDatabaseModelUserRooms.swift | 1 | 643 | import Foundation
class FDatabaseModelUserRooms:FDatabaseModel
{
let rooms:[String]
override init()
{
rooms = []
super.init()
}
init(rooms:[String])
{
self.rooms = rooms
super.init()
}
required init(snapshot:Any?)
{
let snapshotArray:[String]? = snapshot as? [String]
if snapshotArray == nil
{
rooms = []
}
else
{
rooms = snapshotArray!
}
super.init()
}
override func modelJson() -> Any
{
return rooms
}
}
| mit | 938758d8c8a12f73e03ae13b62518319 | 14.682927 | 59 | 0.44479 | 4.871212 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/Instruments/AKFMSynth.swift | 1 | 4891 | //
// AKFMSynth.swift
// AudioKit
//
// Created by Jeff Cooper, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
import AVFoundation
/// A wrapper for AKFMOscillator to make it playable as a polyphonic instrument.
public class AKFMSynth: AKPolyphonicInstrument {
/// This multiplied by the baseFrequency gives the carrier frequency.
public var carrierMultiplier: Double = 1.0 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.carrierMultiplier = carrierMultiplier
}
}
}
/// This multiplied by the baseFrequency gives the modulating frequency.
public var modulatingMultiplier: Double = 1 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.modulatingMultiplier = modulatingMultiplier
}
}
}
/// This multiplied by the modulating frequency gives the modulation amplitude.
public var modulationIndex: Double = 1 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.modulationIndex = modulationIndex
}
}
}
/// Attack time
public var attackDuration: Double = 0.1 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.adsr.attackDuration = attackDuration
}
}
}
/// Decay time
public var decayDuration: Double = 0.1 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.adsr.decayDuration = decayDuration
}
}
}
/// Sustain Level
public var sustainLevel: Double = 0.66 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.adsr.sustainLevel = sustainLevel
}
}
}
/// Release time
public var releaseDuration: Double = 0.5 {
didSet {
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.adsr.releaseDuration = releaseDuration
}
}
}
/// Instantiate the FM Oscillator Instrument
///
/// - parameter voiceCount: Maximum number of voices that will be required
///
public init(voiceCount: Int) {
super.init(voice: AKFMOscillatorVoice(), voiceCount: voiceCount)
for voice in voices {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.modulatingMultiplier = 4 //just some arbitrary default values
fmVoice.oscillator.modulationIndex = 10
}
}
/// Start a given voice playing a note.
///
/// - parameter voice: Voice to start
/// - parameter note: MIDI Note Number to start
/// - parameter velocity: MIDI Velocity (0-127) to trigger the note at
///
public override func playVoice(voice: AKVoice, note: Int, velocity: Int) {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.oscillator.baseFrequency = note.midiNoteToFrequency()
fmVoice.oscillator.amplitude = Double(velocity) / 127.0
fmVoice.start()
}
/// Stop a given voice playing a note.
///
/// - parameter voice: Voice to stop
/// - parameter note: MIDI Note Number to stop
///
public override func stopVoice(voice: AKVoice, note: Int) {
let fmVoice = voice as! AKFMOscillatorVoice
fmVoice.stop()
}
}
internal class AKFMOscillatorVoice: AKVoice {
var oscillator: AKFMOscillator
var adsr: AKAmplitudeEnvelope
/// Instantiate the FM Oscillator Voice
override init() {
oscillator = AKFMOscillator()
adsr = AKAmplitudeEnvelope(oscillator,
attackDuration: 0.2,
decayDuration: 0.2,
sustainLevel: 0.8,
releaseDuration: 1.0)
super.init()
avAudioNode = adsr.avAudioNode
}
/// Function create an identical new node for use in creating polyphonic instruments
override func duplicate() -> AKVoice {
let copy = AKFMOscillatorVoice()
return copy
}
/// Tells whether the node is processing (ie. started, playing, or active)
override var isStarted: Bool {
return oscillator.isPlaying
}
/// Function to start, play, or activate the node, all do the same thing
override func start() {
oscillator.start()
adsr.start()
}
/// Function to stop or bypass the node, both are equivalent
override func stop() {
adsr.stop()
}
}
| apache-2.0 | 508455c01f6684af11811477baf3719e | 30.548387 | 92 | 0.6 | 5.292208 | false | false | false | false |
cuappdev/tempo | Tempo/Views/ProfileHeaderView.swift | 1 | 7368 | //
// ProfileHeaderView.swift
// Tempo
//
// Created by Annie Cheng on 12/5/16.
// Copyright © 2016 CUAppDev. All rights reserved.
//
import Foundation
import UIKit
protocol ProfileHeaderViewDelegate {
func hipsterScoreButtonPressed()
func followersButtonPressed()
func followingButtonPressed()
}
class ProfileHeaderView: UIView, UIGestureRecognizerDelegate {
let profileImageLength: CGFloat = 85
let profileContainerHeight: CGFloat = 170
let profileButtonHeight: CGFloat = 30
var profileContainerView: UIView!
var profileBackgroundImageView: UIImageView!
var profileImageView: UIImageView!
var nameLabel: UILabel!
var usernameLabel: UILabel!
var profileButton: UIButton!
var wrapperViewSize = CGSize(width: 80.0, height: 40.0)
var isWrapperInterationEnabled = true
var followersWrapperView: UIView!
var followingWrapperView: UIView!
var hipsterScoreWrapperView: UIView!
var followersLabel: UILabel!
var followingLabel: UILabel!
var hipsterScoreLabel: UILabel!
var tapGestureRecognizer: UITapGestureRecognizer!
var delegate: ProfileHeaderViewDelegate?
let fontSize = iPhone5 ? 11.0 : 13.0
override init(frame: CGRect) {
super.init(frame: frame)
setUpProfileContainerView()
}
override func layoutSubviews() {
}
func setUpProfileContainerView() {
profileContainerView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: profileContainerHeight))
profileContainerView.backgroundColor = .unreadCellColor
profileBackgroundImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: profileContainerView.frame.width, height: profileContainerView.frame.height))
profileBackgroundImageView.center.x = profileContainerView.bounds.midX
profileBackgroundImageView.clipsToBounds = true
profileBackgroundImageView.contentMode = .scaleAspectFill
profileBackgroundImageView.alpha = 0.05
profileImageView = UIImageView(frame: CGRect(x: 18, y: 18, width: profileImageLength, height: profileImageLength))
profileImageView.layer.cornerRadius = profileImageLength / 2.0
profileImageView.clipsToBounds = true
profileImageView.contentMode = .scaleAspectFill
nameLabel = UILabel(frame: CGRect(x: profileImageLength + 40, y: (profileImageLength / 2.0) - 3, width: bounds.width - 115 - 20, height: 23))
nameLabel.text = "Name"
nameLabel.font = UIFont(name: "AvenirNext-Medium", size: 17.0)
nameLabel.textColor = .redTintedWhite
nameLabel.textAlignment = .left
usernameLabel = UILabel(frame: CGRect(x: profileImageLength + 40, y: (profileImageLength / 2.0) + 20, width: bounds.width - 115 - 20, height: 23))
usernameLabel.text = "Name"
usernameLabel.font = UIFont(name: "AvenirNext-Regular", size: 13.0)
usernameLabel.textColor = .paleRed
usernameLabel.textAlignment = .left
profileButton = UIButton(frame: CGRect(x: 23, y: profileImageView.frame.maxY + 18, width: 75, height: profileButtonHeight))
profileButton.setTitle("-", for: .normal)
profileButton.setTitleColor(.redTintedWhite, for: .normal)
profileButton.titleLabel?.font = UIFont(name: "AvenirNext-Medium", size: 12.0)
profileButton.layer.borderColor = UIColor.tempoRed.cgColor
profileButton.layer.borderWidth = 1.5
profileButton.layer.cornerRadius = 3
profileButton.clipsToBounds = true
let labelFont = UIFont(name: "AvenirNext-Medium", size: 13.0)
let descriptionFont = UIFont(name: "AvenirNext-Regular", size: 13.0)
followersWrapperView = UIView(frame: CGRect(origin: CGPoint(x: profileButton.frame.maxX + 20, y: profileImageView.frame.maxY + 10), size: wrapperViewSize))
followersLabel = UILabel(frame: CGRect(x: 0, y: 0, width: wrapperViewSize.width, height: wrapperViewSize.height / 2.0))
followersLabel.text = "-"
followersLabel.font = labelFont
followersLabel.textColor = .redTintedWhite
followersLabel.textAlignment = .center
let followerDescription = UILabel(frame: CGRect(x: 0, y: wrapperViewSize.height / 2.0, width: wrapperViewSize.width, height: wrapperViewSize.height / 2.0))
followerDescription.text = "Followers"
followerDescription.font = descriptionFont
followerDescription.textColor = .paleRed
followerDescription.textAlignment = .center
followersWrapperView.addSubview(followersLabel)
followersWrapperView.addSubview(followerDescription)
followingWrapperView = UIView(frame: CGRect(origin: CGPoint(x: followersWrapperView.frame.maxX, y: profileImageView.frame.maxY + 10), size: wrapperViewSize))
followingLabel = UILabel(frame: CGRect(x: 0, y: 0, width: wrapperViewSize.width, height: wrapperViewSize.height / 2.0))
followingLabel.text = "-"
followingLabel.font = labelFont
followingLabel.textColor = .redTintedWhite
followingLabel.textAlignment = .center
let followingDescription = UILabel(frame: CGRect(x: 0, y: wrapperViewSize.height / 2.0, width: wrapperViewSize.width, height: wrapperViewSize.height / 2.0))
followingDescription.text = "Following"
followingDescription.font = descriptionFont
followingDescription.textColor = .paleRed
followingDescription.textAlignment = .center
followingWrapperView.addSubview(followingLabel)
followingWrapperView.addSubview(followingDescription)
hipsterScoreWrapperView = UIView(frame: CGRect(origin: CGPoint(x: followingWrapperView.frame.maxX, y: profileImageView.frame.maxY + 10), size: wrapperViewSize))
hipsterScoreLabel = UILabel(frame: CGRect(x: 0, y: 0, width: wrapperViewSize.width, height: wrapperViewSize.height / 2.0))
hipsterScoreLabel.text = "-"
hipsterScoreLabel.font = labelFont
hipsterScoreLabel.textColor = .redTintedWhite
hipsterScoreLabel.textAlignment = .center
let hipsterScoreDescription = UILabel(frame: CGRect(x: 0, y: wrapperViewSize.height / 2.0, width: wrapperViewSize.width, height: wrapperViewSize.height / 2.0))
hipsterScoreDescription.text = "Hipster Cred"
hipsterScoreDescription.font = descriptionFont
hipsterScoreDescription.textColor = .paleRed
hipsterScoreDescription.textAlignment = .center
hipsterScoreWrapperView.addSubview(hipsterScoreLabel)
hipsterScoreWrapperView.addSubview(hipsterScoreDescription)
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerViewPressed(sender:)))
profileContainerView.addGestureRecognizer(tapGestureRecognizer)
profileContainerView.addSubview(profileBackgroundImageView)
profileContainerView.addSubview(profileImageView)
profileContainerView.addSubview(nameLabel)
profileContainerView.addSubview(usernameLabel)
profileContainerView.addSubview(profileButton)
profileContainerView.addSubview(followersWrapperView)
profileContainerView.addSubview(followingWrapperView)
profileContainerView.addSubview(hipsterScoreWrapperView)
addSubview(profileContainerView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Button Action Methods
func headerViewPressed(sender: UITapGestureRecognizer) {
guard let delegate = delegate else { return }
let tapPoint = sender.location(in: self)
let hitView = hitTest(tapPoint, with: nil)
if isWrapperInterationEnabled {
if hitView == followersWrapperView {
delegate.followersButtonPressed()
} else if hitView == followingWrapperView {
delegate.followingButtonPressed()
} else if hitView == hipsterScoreWrapperView {
delegate.hipsterScoreButtonPressed()
}
}
}
}
| mit | 774d293cdebe917f6007003dc179a4ea | 41.097143 | 162 | 0.780508 | 4.106466 | false | false | false | false |
OperatorFoundation/Postcard | Postcard/Postcard/DataModels/Packable.swift | 1 | 17548 | //
// Packable.swift
// Postcard
//
// Created by Brandon Wiley on 4/9/17.
// Copyright © 2017 operatorfoundation.org. All rights reserved.
//
import Foundation
import MessagePack
protocol Packable
{
init?(value: MessagePackValue)
func messagePackValue() -> MessagePackValue
}
struct PostcardMessage: Packable
{
var to: String
var subject: String
var body: String
init(to: String, subject: String, body: String)
{
self.to = to
self.subject = subject
self.body = body
}
init?(postcardData: Data)
{
do
{
let unpackResult = try unpack(postcardData)
let unpackValue: MessagePackValue = unpackResult.value
self.init(value: unpackValue)
}
catch let unpackError as NSError
{
print("Unpack postcard data error: \(unpackError.localizedDescription)")
return nil
}
}
func dataValue() -> Data?
{
let keyMessagePack = self.messagePackValue()
return pack(keyMessagePack)
}
internal init?(value: MessagePackValue)
{
guard let keyDictionary = value.dictionaryValue
else
{
print("Postcard Message deserialization error.")
return nil
}
//To
guard let toMessagePack = keyDictionary[.string(messageToKey)]
else
{
print("Postcard message deserialization error: unable to unpack 'to' property.")
return nil
}
guard let toString = toMessagePack.stringValue
else
{
print("Postcard message deserialization error: unable to get string value for 'to' property.")
return nil
}
//Subject
guard let subjectMessagePack = keyDictionary[.string(messageSubjectKey)]
else
{
print("Postcard message deserialization error: unable to unpack subject property.")
return nil
}
guard let subjectString = subjectMessagePack.stringValue
else
{
print("Postcard message deserialization error: unable to get string value for subject property.")
return nil
}
//Message Body
guard let bodyMessagePack = keyDictionary[.string(messageBodyKey)]
else
{
print("Postcard message deserialization error: unable to unpack body property.")
return nil
}
guard let bodyString = bodyMessagePack.stringValue
else
{
print("Postcard message deserialization error: unable to get string value for body property.")
return nil
}
self.to = toString
self.subject = subjectString
self.body = bodyString
}
internal func messagePackValue() -> MessagePackValue
{
let keyDictionary: Dictionary<MessagePackValue, MessagePackValue> = [
MessagePackValue(messageToKey): MessagePackValue(self.to),
MessagePackValue(messageSubjectKey): MessagePackValue(self.subject),
MessagePackValue(messageBodyKey): MessagePackValue(self.body)
]
return MessagePackValue(keyDictionary)
}
}
struct TimestampedSenderPublicKey: Packable
{
var senderPublicKey: Data
var senderKeyTimestamp: Int64
init(senderKey: Data, senderKeyTimestamp: Int64)
{
self.senderPublicKey = senderKey
self.senderKeyTimestamp = senderKeyTimestamp
}
init?(value: MessagePackValue)
{
guard let keyDictionary = value.dictionaryValue
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
//Sender Public Key
guard let senderKeyMessagePack = keyDictionary[.string(keyAttachmentSenderPublicKeyKey)]
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
guard let senderPKeyData = senderKeyMessagePack.dataValue
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
//Sender Key Timestamp
guard let senderTimestampMessagePack = keyDictionary[.string(keyAttachmentSenderPublicKeyTimestampKey)]
else
{
print("TimestampedPublicKeys deserialization error: Unable to deserialize the Timestamp MessagePack.")
return nil
}
guard let senderPKeyTimestamp = senderTimestampMessagePack.integerValue
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
self.senderPublicKey = senderPKeyData
self.senderKeyTimestamp = senderPKeyTimestamp
}
func messagePackValue() -> MessagePackValue
{
let keyDictionary: Dictionary<MessagePackValue, MessagePackValue> = [
MessagePackValue(keyAttachmentSenderPublicKeyKey): MessagePackValue(self.senderPublicKey),
MessagePackValue(keyAttachmentSenderPublicKeyTimestampKey): MessagePackValue(self.senderKeyTimestamp)
]
return MessagePackValue(keyDictionary)
}
}
struct TimestampedPublicKeys: Packable
{
var senderPublicKey: Data
var senderKeyTimestamp: Int64
var recipientPublicKey: Data
var recipientKeyTimestamp: Int64
init(senderKey: Data, senderKeyTimestamp: Int64, recipientKey: Data, recipientKeyTimestamp: Int64)
{
self.senderPublicKey = senderKey
self.senderKeyTimestamp = senderKeyTimestamp
self.recipientPublicKey = recipientKey
self.recipientKeyTimestamp = recipientKeyTimestamp
}
init?(value: MessagePackValue)
{
guard let keyDictionary = value.dictionaryValue
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
//Sender Public Key
guard let senderKeyMessagePack = keyDictionary[.string(keyAttachmentSenderPublicKeyKey)]
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
guard let senderPKeyData = senderKeyMessagePack.dataValue
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
//Sender Key Timestamp
guard let senderTimestampMessagePack = keyDictionary[.string(keyAttachmentSenderPublicKeyTimestampKey)]
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
guard let senderPKeyTimestamp = senderTimestampMessagePack.integerValue
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
//Recipient Public Key
guard let recipientKeyMessagePack = keyDictionary[.string(keyAttachmentRecipientPublicKeyKey)]
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
guard let recipientPKeyData = recipientKeyMessagePack.dataValue
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
//Recipient Key Timestamp
guard let recipientTimestampMessagePack = keyDictionary[.string(keyAttachmentRecipientPublicKeyTimestamp)]
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
guard let recipientPKeyTimestamp = recipientTimestampMessagePack.integerValue
else
{
print("TimestampedPublicKeys deserialization error.")
return nil
}
self.senderPublicKey = senderPKeyData
self.senderKeyTimestamp = senderPKeyTimestamp
self.recipientPublicKey = recipientPKeyData
self.recipientKeyTimestamp = recipientPKeyTimestamp
}
func messagePackValue() -> MessagePackValue
{
let keyDictionary: Dictionary<MessagePackValue, MessagePackValue> = [
MessagePackValue(keyAttachmentSenderPublicKeyKey): MessagePackValue(self.senderPublicKey),
MessagePackValue(keyAttachmentSenderPublicKeyTimestampKey): MessagePackValue(self.senderKeyTimestamp),
MessagePackValue(keyAttachmentRecipientPublicKeyKey): MessagePackValue(self.recipientPublicKey),
MessagePackValue(keyAttachmentRecipientPublicKeyTimestamp): MessagePackValue(self.recipientKeyTimestamp)
]
return MessagePackValue(keyDictionary)
}
}
//MARK: Key Attachments
struct VersionedData: Packable
{
var version: String
var serializedData: Data
init(version: String, serializedData: Data)
{
self.version = version
self.serializedData = serializedData
}
init?(value: MessagePackValue)
{
guard let versionDictionary = value.dictionaryValue
else
{
print("Version deserialization error.")
return nil
}
//Version
guard let versionMessagePack = versionDictionary[.string(versionKey)]
else
{
print("Version deserialization error.")
return nil
}
guard let versionValue = versionMessagePack.stringValue
else
{
print("Version deserialization error.")
return nil
}
//Serialized Data
guard let dataMessagePack = versionDictionary[.string(serializedDataKey)]
else
{
print("Version deserialization error.")
return nil
}
guard let sData = dataMessagePack.dataValue
else
{
print("Version deserialization error.")
return nil
}
self.version = versionValue
self.serializedData = sData
}
func messagePackValue() -> MessagePackValue
{
let versionDictionary: Dictionary<MessagePackValue, MessagePackValue> = [
MessagePackValue(versionKey): MessagePackValue(version),
MessagePackValue(serializedDataKey): MessagePackValue(serializedData)
]
return MessagePackValue(versionDictionary)
}
}
struct TimestampedUserKeys: Packable
{
var userPublicKey: Data
var userPrivateKey: Data
var userKeyTimestamp: Int64
init(userPublicKey: Data, userPrivateKey: Data, userKeyTimestamp: Int64)
{
self.userPublicKey = userPublicKey
self.userPrivateKey = userPrivateKey
self.userKeyTimestamp = userKeyTimestamp
}
init?(keyData: Data)
{
do
{
let unpackResult = try unpack(keyData)
let unpackValue: MessagePackValue = unpackResult.value
self.init(value: unpackValue)
}
catch let unpackError as NSError
{
print("Unpack user keys error: \(unpackError.localizedDescription)")
return nil
}
}
init?(value: MessagePackValue)
{
guard let keyDictionary = value.dictionaryValue
else
{
print("TimestampedUserKeys deserialization error.")
return nil
}
//User Public Key
guard let userPublicKeyMessagePack = keyDictionary[.string(userPublicKeyKey)]
else
{
print("TimestampedUserKeys deserialization error.")
return nil
}
guard let userPublicKeyData = userPublicKeyMessagePack.dataValue
else
{
print("TimestampedUserKeys deserialization error.")
return nil
}
//User Private Key
guard let userPrivateKeyMessagePack = keyDictionary[.string(userPrivateKeyKey)]
else
{
print("TimestampedUserKeys deserialization error.")
return nil
}
guard let userPrivateKeyData = userPrivateKeyMessagePack.dataValue
else
{
print("TimestampedUserKeys deserialization error.")
return nil
}
//Sender Key Timestamp
guard let userTimestampMessagePack = keyDictionary[.string(userKeyTimestampKey)]
else
{
print("TimestampedUserKeys deserialization error.")
return nil
}
guard let userKeyTimestamp = userTimestampMessagePack.integerValue
else
{
print("TimestampedUserKeys deserialization error.")
return nil
}
self.userPublicKey = userPublicKeyData
self.userPrivateKey = userPrivateKeyData
self.userKeyTimestamp = userKeyTimestamp
}
func messagePackValue() -> MessagePackValue
{
let keyDictionary: Dictionary<MessagePackValue, MessagePackValue> = [
MessagePackValue(userPublicKeyKey): MessagePackValue(self.userPublicKey),
MessagePackValue(userPrivateKeyKey): MessagePackValue(self.userPrivateKey),
MessagePackValue(userKeyTimestampKey): MessagePackValue(self.userKeyTimestamp)
]
return MessagePackValue(keyDictionary)
}
func dataValue() -> Data?
{
let keyMessagePack = self.messagePackValue()
return pack(keyMessagePack)
}
}
func dataToSenderPublicKeys(keyData: Data) -> TimestampedSenderPublicKey?
{
do
{
let unpackResult = try unpack(keyData)
let unpackValue: MessagePackValue = unpackResult.value
return TimestampedSenderPublicKey.init(value: unpackValue)
}
catch let unpackError as NSError
{
print("Unpack error: \(unpackError.localizedDescription)")
return nil
}
// let messagePack = MessagePackValue(keyData)
// guard let versionedData = VersionedData.init(value: messagePack)
// else
// {
// print("could not get versioned data")
// return nil
// }
//
// guard versionedData.version == keyFormatVersion
// else
// {
// print("Key format versions do not match.")
// return nil
// }
//
// return TimestampedSenderPublicKey.init(value: MessagePackValue(versionedData.serializedData))
}
func dataToPublicKeys(keyData: Data) -> TimestampedPublicKeys?
{
do
{
let unpackResult = try unpack(keyData)
let unpackValue: MessagePackValue = unpackResult.value
return TimestampedPublicKeys.init(value: unpackValue)
}
catch let unpackError as NSError
{
print("Unpack error: \(unpackError.localizedDescription)")
return nil
}
// let messagePack = MessagePackValue(keyData)
// guard let versionedData = VersionedData.init(value: messagePack)
// else
// {
// print("could not get versioned data")
// return nil
// }
//
// guard versionedData.version == keyFormatVersion
// else
// {
// print("Key format versions do not match.")
// return nil
// }
//
// return TimestampedPublicKeys.init(value: MessagePackValue(versionedData.serializedData))
}
func generateSenderPublicKeyAttachment(forPenPal penPal: PenPal) -> Data?
{
guard let senderKey = KeyController.sharedInstance.mySharedKey else {
return nil
}
guard let userKeyTimestamp = KeyController.sharedInstance.myKeyTimestamp else {
return nil
}
let senderKeyTimestamp = Int64(userKeyTimestamp.timeIntervalSince1970)
let timestampedKeys = TimestampedSenderPublicKey.init(senderKey: senderKey, senderKeyTimestamp: senderKeyTimestamp)
///TODO: Include Versioned Data
let keyMessagePack = timestampedKeys.messagePackValue()
return pack(keyMessagePack)
}
func generateKeyAttachment(forPenPal penPal: PenPal) -> Data?
{
guard let recipientKey = penPal.key else {
return nil
}
guard let senderKey = KeyController.sharedInstance.mySharedKey else {
return nil
}
guard let userKeyTimestamp = KeyController.sharedInstance.myKeyTimestamp else {
return nil
}
guard let penPalKeyTimestamp = penPal.keyTimestamp else {
return nil
}
let senderKeyTimestamp = Int64(userKeyTimestamp.timeIntervalSince1970)
let recipientKeyTimestamp = Int64(penPalKeyTimestamp.timeIntervalSince1970)
let timestampedKeys = TimestampedPublicKeys.init(senderKey: senderKey,
senderKeyTimestamp: senderKeyTimestamp,
recipientKey: recipientKey as Data,
recipientKeyTimestamp: recipientKeyTimestamp)
///TODO: Include Versioned Data
let keyMessagePack = timestampedKeys.messagePackValue()
return pack(keyMessagePack)
}
| mit | 9bc9ec3c7b1626163a3b047f0ea94121 | 29.623037 | 119 | 0.610703 | 5.715635 | false | false | false | false |
negusoft/Polyglot | Polyglot/Source/UINavigationItem+Polyglot.swift | 1 | 2061 | //
// Copyright (c) 2015 NEGU Soft
//
// 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
@IBDesignable
public extension UINavigationItem {
@IBInspectable
var titleKey: String {
get { return "" }
set {
self.title = Polyglot.localizedString(newValue)
}
}
@IBInspectable
var promptKey: String {
get { return "" }
set {
self.prompt = Polyglot.localizedString(newValue)
}
}
@IBInspectable
var backButtonKey: String {
get { return "" }
set {
if let backBarButtonItem = self.backBarButtonItem {
backBarButtonItem.title = Polyglot.localizedString(newValue)
} else {
self.backBarButtonItem = UIBarButtonItem(
title: Polyglot.localizedString(newValue),
style: UIBarButtonItem.Style.plain,
target: nil,
action: nil
)
}
}
}
}
| mit | c85e9321f06b0a40f5ab168e96d04535 | 33.932203 | 80 | 0.647744 | 4.942446 | false | false | false | false |
actilot/tesseract-swift | Source/Tesseract/Macros.swift | 1 | 6692 | //
// Macros.swift
// Tesseract
//
// Created by Axel Campaña on 11/22/16.
// Copyright © 2016 Axel Campaña. All rights reserved.
//
/**
This is a Swift version of Benihime, https://github.com/shiki/ios-benihime/blob/master/Benihime/BMacros.h
*/
import UIKit
// MARK: Orientation
public var ORIENTATION_IS_PORTRAIT: Bool { get { return UIApplication.shared.statusBarOrientation.isPortrait } }
public var ORIENTATION_IS_LANDSCAPE: Bool { get { return UIApplication.shared.statusBarOrientation.isLandscape } }
// MARK: Device
public var DEVICE_IS_IPAD: Bool { get { return UI_USER_INTERFACE_IDIOM() == .pad } }
public var DEVICE_IS_IPHONE: Bool { get { return UI_USER_INTERFACE_IDIOM() == .phone } }
// MARK: Device Height
/**
* 1st Generation Display Height
*
* 3.5" - iPhones (4S, older), iPod Touch Gen (4, older)
*/
public let GENERATION_1_IPHONE_HEIGHT: CGFloat = 480.0
/**
* 2nd Generation Display Height
*
* 4" - iPhones (5, 5s, 5c, SE), iPod Touch Gen (5, 6, 7)
*/
public let GENERATION_2_IPHONE_HEIGHT: CGFloat = 568.0
/**
* 3rd Generation Display Height
*
* 4.7" - iPhones (6, 6s, 7, 8, SE2)
*/
public let GENERATION_3_IPHONE_HEIGHT: CGFloat = 667.0
/**
* 3rd Generation Plus Display Height
*
* 5.5" - Plus iPhones (6, 6s, 7, 8)
*/
public let GENERATION_3_PLUS_IPHONE_HEIGHT: CGFloat = 736.0
/**
* 4th Generation Display Height
*
* 5.8" - iPhones (X, Xs, 11 Pro)
*/
public let GENERATION_4_IPHONE_HEIGHT: CGFloat = 812.0
/**
* 4th Generation Low-end Display Height
*
* 6.1" - iPhones (Xr, 11)
*/
public let GENERATION_4_LOWEND_IPHONE_HEIGHT: CGFloat = 896.0
/**
* 4th Generation Max Display Height
*
* 6.5" - Max iPhones (Xs, 11 Pro)
*/
public let GENERATION_4_MAX_IPHONE_HEIGHT: CGFloat = 896.0
/**
* Returns `true` if current device belongs to `1ST GENERATION IPHONE DISPLAY`
*
* 3.5" - iPhones (4S, older)
*/
public var DEVICE_IS_GENERATION_1_IPHONE : Bool { get { return DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_1_IPHONE_HEIGHT } }
/**
* Returns `true` if current device belongs to `2ND GENERATION IPHONE DISPLAY`
*
* 4" - iPhones (5, 5s, 5c, SE)
*/
public var DEVICE_IS_GENERATION_2_IPHONE : Bool { get { return DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_2_IPHONE_HEIGHT } }
/**
* Returns `true` if current device belongs to `3RD GENERATION IPHONE DISPLAY`
*
* 4.7" - iPhones (6, 6s, 7, 8, SE2)
*/
public var DEVICE_IS_GENERATION_3_IPHONE : Bool { get { return DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_3_IPHONE_HEIGHT } }
/**
* Returns `true` if current device belongs to `3RD GENERATION PLUS IPHONE DISPLAY`
*
* 5.5" - Plus iPhones (6, 6s, 7, 8)
*/
public var DEVICE_IS_GENERATION_3_PLUS_IPHONE : Bool { get { return DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_3_PLUS_IPHONE_HEIGHT } }
/**
* Returns `true` if current device belongs to `4TH GENERATION IPHONE DISPLAY`
*
* 5.8" - iPhones (X, Xs, 11 Pro)
*/
public var DEVICE_IS_GENERATION_4_IPHONE : Bool { get { return DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_4_IPHONE_HEIGHT } }
/**
* Returns `true` if current device belongs to `4TH GENERATION LOW-END IPHONE DISPLAY`
*
* 6.1" - iPhones (Xr, 11)
*/
public var DEVICE_IS_GENERATION_4_LOWEND_IPHONE : Bool { get { return DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_4_LOWEND_IPHONE_HEIGHT } }
/**
* Returns `true` if current device belongs to `4TH GENERATION MAX IPHONE DISPLAY`
*
* 6.5" - Max iPhones (Xs, 11 Pro)
*/
public var DEVICE_IS_GENERATION_4_MAX_IPHONE : Bool { get { return DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_4_MAX_IPHONE_HEIGHT } }
/**
* Returns `true` if current device belongs to `1ST GENERATION IPOD TOUCH DISPLAY`
*
* 3.5" - iPod Touch Gen (4, older)
*/
public var DEVICE_IS_GENERATION_1_IPOD_TOUCH : Bool { get { return !DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_1_IPHONE_HEIGHT } }
/**
* Returns `true` if current device belongs to `2ND GENERATION IPOD TOUCH DISPLAY`
*
* 4" - iPod Touch Gen (5, 6, 7)
*/
public var DEVICE_IS_GENERATION_2_IPOD_TOUCH : Bool { get { return !DEVICE_IS_IPHONE && DEVICE_HEIGHT == GENERATION_2_IPHONE_HEIGHT } }
// MARK: Screen
/**
* Returns the value of `UIScreen.main.bounds.size.height`
*/
public let DEVICE_HEIGHT: CGFloat = UIScreen.main.bounds.size.height
/**
* Returns `true` if current device has Screen Scale Factor of `1`
*
* **Devices**:
* - iPods 3 and older
* - iPhones 3Gs and older
*/
public var DEVICE_IS_NON_RETINA : Bool { get { return UIScreen.main.scale == 1 } }
/**
* Returns `true` if current device has Screen Scale Factor of `2`
*
* **Devices**:
* - iPods 4, 5, 6 and 7
* - iPhones 4, 4s
* - iPhones 5, 5s, 5c and SE
* - iPhones 6, 6s, 7, 8 and SE2
* - Plus iPhones 6, 6s, 7 and 8
* - iPhones Xr and 11
*/
public var DEVICE_IS_RETINA_HD : Bool { get { return UIScreen.main.scale == 2 } }
/**
* Returns `true` if current device has Screen Scale Factor of `2`
*
* **Devices**:
* - iPhones X, Xs and 11 pro
* - Max iPhones Xs and 11 Pro
*/
public var DEVICE_IS_SUPER_RETINA_HD : Bool { get { return UIScreen.main.scale == 3 } }
// MARK: System Versioning Preprocessor
public func SystemVersionIsEqualTo(_ version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) == .orderedSame }
public func SystemVersionIsGreaterThan(_ version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) == .orderedDescending }
public func SystemVersionIsGreaterThanOrEqualTo(_ version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) != .orderedAscending }
public func SystemVersionIsLessThan(_ version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) == .orderedAscending }
public func SystemVersionIsLessThanOrEqualTo(_ version: String) -> Bool { return UIDevice.current.systemVersion.compare(version, options: .numeric) != .orderedDescending }
// MARK: Null, Nil, Empty String
public func NilIfNull(_ object: Any) -> Any? {
if (object is NSNull) {
return nil
} else {
return object
}
}
public func NullIfNil(_ object: Any?) -> Any? {
if (object == nil) {
return NSNull()
} else {
return object
}
}
public func EmptyIfNil(_ object: Any?) -> String? {
if (object == nil) {
return ""
} else {
return object as! String?
}
}
public func EmptyIfNull(_ object: Any?) -> String? {
if (object is NSNull) {
return ""
} else {
return object as! String?
}
}
| mit | bc87fa33d265159a549f79e7c13596bf | 29.266968 | 173 | 0.662132 | 3.072577 | false | false | false | false |
banjun/SwiftBeaker | Examples/01. Simplest API.swift | 1 | 3851 | import Foundation
import APIKit
import URITemplate
protocol URITemplateContextConvertible: Encodable {}
extension URITemplateContextConvertible {
var context: [String: String] {
return ((try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: String]) ?? [:]
}
}
public enum RequestError: Error {
case encode
}
public enum ResponseError: Error {
case undefined(Int, String?)
case invalidData(Int, String?)
}
struct RawDataParser: DataParser {
var contentType: String? {return nil}
func parse(data: Data) -> Any { return data }
}
struct TextBodyParameters: BodyParameters {
let contentType: String
let content: String
func buildEntity() throws -> RequestBodyEntity {
guard let r = content.data(using: .utf8) else { throw RequestError.encode }
return .data(r)
}
}
public protocol APIBlueprintRequest: Request {}
extension APIBlueprintRequest {
public var dataParser: DataParser {return RawDataParser()}
func contentMIMEType(in urlResponse: HTTPURLResponse) -> String? {
return (urlResponse.allHeaderFields["Content-Type"] as? String)?.components(separatedBy: ";").first?.trimmingCharacters(in: .whitespaces)
}
func data(from object: Any, urlResponse: HTTPURLResponse) throws -> Data {
guard let d = object as? Data else {
throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse))
}
return d
}
func string(from object: Any, urlResponse: HTTPURLResponse) throws -> String {
guard let s = String(data: try data(from: object, urlResponse: urlResponse), encoding: .utf8) else {
throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse))
}
return s
}
func decodeJSON<T: Decodable>(from object: Any, urlResponse: HTTPURLResponse) throws -> T {
return try JSONDecoder().decode(T.self, from: data(from: object, urlResponse: urlResponse))
}
public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any {
return object
}
}
protocol URITemplateRequest: Request {
static var pathTemplate: URITemplate { get }
associatedtype PathVars: URITemplateContextConvertible
var pathVars: PathVars { get }
}
extension URITemplateRequest {
// reconstruct URL to use URITemplate.expand. NOTE: APIKit does not support URITemplate format other than `path + query`
public func intercept(urlRequest: URLRequest) throws -> URLRequest {
var req = urlRequest
req.url = URL(string: baseURL.absoluteString + type(of: self).pathTemplate.expand(pathVars.context))!
return req
}
}
/// indirect Codable Box-like container for recursive data structure definitions
public class Indirect<V: Codable>: Codable {
public var value: V
public init(_ value: V) {
self.value = value
}
public required init(from decoder: Decoder) throws {
self.value = try V(from: decoder)
}
public func encode(to encoder: Encoder) throws {
try value.encode(to: encoder)
}
}
// MARK: - Transitions
struct GET__message: APIBlueprintRequest {
let baseURL: URL
var method: HTTPMethod {return .get}
var path: String {return "/message"}
enum Responses {
case http200_text_plain(String)
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses {
let contentType = contentMIMEType(in: urlResponse)
switch (urlResponse.statusCode, contentType) {
case (200, "text/plain"?):
return .http200_text_plain(try string(from: object, urlResponse: urlResponse))
default:
throw ResponseError.undefined(urlResponse.statusCode, contentType)
}
}
}
// MARK: - Data Structures
| mit | 34d26481be4d5cae3b8f365a6cca84f3 | 30.308943 | 145 | 0.686575 | 4.530588 | false | false | false | false |
exponent/exponent | ios/versioned/sdk44/EXBlur/EXBlur/BlurView.swift | 2 | 651 | // Copyright 2015-present 650 Industries. All rights reserved.
import UIKit
@objc(ABI44_0_0EXBlurView)
public class BlurView : UIView {
private var blurEffectView: BlurEffectView
override init(frame: CGRect) {
blurEffectView = BlurEffectView()
super.init(frame: frame)
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
clipsToBounds = true
addSubview(blurEffectView)
}
required init?(coder: NSCoder) { nil }
@objc
public func setTint(_ tint: String) {
blurEffectView.tint = tint
}
@objc
public func setIntensity(_ intensity: Double) {
blurEffectView.intensity = intensity;
}
}
| bsd-3-clause | f0a8d6d7010f6ad7123fa32fe3db5f1c | 20.7 | 71 | 0.715822 | 4.369128 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/Utils/StringUtils/StringUtils.swift | 1 | 7462 | @objc extension StringUtils {
static func propertyTypeAndRoomsCount(hotel: HDKHotel) -> String {
let propertyType = HotelPropertyTypeUtils.hotelPropertyTypeEnum(hotel)
let propertyTypeString = propertyType != .unknown
? HotelPropertyTypeUtils.localizedHotelPropertyType(hotel)
: nil
var roomsCountString: String? = nil
if hotel.roomsCount > 0 {
roomsCountString = String(format: NSLSP("HOTEL_DETAIL_ROOMS_COUNT", Float(hotel.roomsCount)), hotel.roomsCount.description)
}
return [propertyTypeString, roomsCountString].compactMap { $0 }.joined(separator: ", ")
}
static func staffLanguages(languages: [String]) -> String? {
guard languages.count > 0 else { return nil }
let languagesString = languages.joined(separator: ", ")
let formatString = NSLSP("HL_HOTEL_DETAIL_STAFF_LANGUAGES", Float(languages.count))
return String(format: formatString, arguments: [languagesString])
}
static func attributedRangeValueText(currency: HDKCurrency,
minValue: Float,
maxValue: Float,
textColor: UIColor = JRColorScheme.lightTextColor(),
numberColor: UIColor = JRColorScheme.lightTextColor()) -> NSAttributedString {
let textFont = UIFont.systemFont(ofSize: 12)
let numberFont = UIFont.systemFont(ofSize: 12)
let textStyle = [NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor]
let lowerStr = StringUtils.attributedPriceString(withPrice: minValue, currency:currency, font:numberFont)
let upperStr = StringUtils.attributedPriceString(withPrice: maxValue, currency:currency, font:numberFont)
let str = String(format: NSLS("HL_LOC_FILTER_RANGE"), "lowerValue", "upperValue")
let result = NSMutableAttributedString(string: str)
result.addAttributes(textStyle, range: NSRange(location: 0, length: str.count))
let lowerPlaceholderRange = (result.string as NSString).range(of: "lowerValue")
if lowerPlaceholderRange.location != NSNotFound {
result.replaceCharacters(in: lowerPlaceholderRange, with: lowerStr)
}
let upperPlaceholderRange = (result.string as NSString).range(of: "upperValue")
if upperPlaceholderRange.location != NSNotFound {
result.replaceCharacters(in: upperPlaceholderRange, with: upperStr)
}
let lowerRange = (result.string as NSString).range(of: lowerStr.string)
if lowerRange.location != NSNotFound {
result.addAttribute(NSAttributedString.Key.foregroundColor, value: numberColor, range: lowerRange)
}
let upperRange = (result.string as NSString).range(of: upperStr.string, options: String.CompareOptions.backwards)
if upperRange.location != NSNotFound {
result.addAttribute(NSAttributedString.Key.foregroundColor, value: numberColor, range: upperRange)
}
return result
}
// MARK: - Rating
static func attributedRatingString(for rating: Int,
textColor: UIColor = JRColorScheme.lightTextColor(),
numberColor: UIColor = JRColorScheme.lightTextColor()) -> NSAttributedString {
let textStyle = [NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]
let numberStyle = [NSAttributedString.Key.foregroundColor: numberColor,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]
let textString = NSLS("HL_LOC_FILTER_FROM_STRING") + " "
let numberString = shortRatingString(rating)
let textAttrString = NSAttributedString(string: textString, attributes: textStyle)
let numberAttrString = NSAttributedString(string: numberString, attributes: numberStyle)
let result = NSMutableAttributedString(attributedString: textAttrString)
result.append(numberAttrString)
return result
}
static func reviewsCountDescription(with reviewsCount: Int) -> String {
if reviewsCount > 0 {
let countStr = StringUtils.formattedNumberString(withNumber: reviewsCount)
let title = NSLSP("HL_HOTEL_DETAIL_HEADER_TITLE_RATING_BASED", Float(reviewsCount))
return String(format: title, countStr)
} else {
return NSLS("HL_NO_HOTEL_REVIEWS")
}
}
static func ratingHotelDescription(with reviewsCount: Int) -> String {
if reviewsCount > 0 {
let countStr = StringUtils.formattedNumberString(withNumber: reviewsCount)
var title = NSLSP("HL_HOTEL_DETAIL_HEADER_TITLE_RATING_BASED", Float(reviewsCount))
title = String(format: "(%@)", title)
return String(format: title, countStr)
} else {
return NSLS("HL_HOTEL_REVIEWS")
}
}
static func reviewDate(date: Date) -> String {
let formatter = HDKDateUtil.standardFormatter()
formatter.dateStyle = .long
return formatter.string(from: date)
}
@nonobjc static func offersString(withCount count: Int?) -> String {
guard let count = count else { return "" }
let countString = NSLSP("HL_HOTEL_DETAIL_OFFERS_COUNT", Float(count))
return String(format: countString, count)
}
static func ratingAttributedString(rating: Int, full: Bool) -> NSAttributedString {
guard rating > 0 else { return NSAttributedString() }
let ratingNumbers = shortRatingString(forRating: rating)
let boldAttr = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.bold), NSAttributedString.Key.foregroundColor: UIColor.white]
let attributedText = NSMutableAttributedString(string: ratingNumbers, attributes: boldAttr)
if full {
let lightAttr = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.light), NSAttributedString.Key.foregroundColor: UIColor.white]
let attributedRatingText = NSAttributedString(string: ratingText(forRating: rating), attributes: lightAttr)
attributedText.append(attributedRatingText)
attributedText.addAttribute(NSAttributedString.Key.kern, value: 5, range: NSRange(location: ratingNumbers.count - 1, length: 1))
}
return attributedText
}
static func shortRatingString(forRating rating: Int, locale: Locale = Locale.current) -> String {
if rating == 0 || rating == 100 {
return String(rating / 10)
} else {
return String.init(format: "%.1f", Double(rating) / 10.0)
}
}
static func ratingText(forRating rating: Int) -> String {
if rating > 95 {
return NSLS("HOTEL_RATING_EXCEPTIONAL")
} else if rating > 89 {
return NSLS("HOTEL_RATING_WONDERFUL")
} else if rating > 85 {
return NSLS("HOTEL_RATING_EXCELLENT")
} else if rating > 79 {
return NSLS("HOTEL_RATING_VERY_GOOD")
} else if rating > 69 {
return NSLS("HOTEL_RATING_GOOD")
} else {
return NSLS("HOTEL_RATING_FAIR")
}
}
}
| mit | d6327247e007e38af2fd7ad7989212f7 | 43.682635 | 172 | 0.647682 | 4.783333 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/JetpackSecuritySettingsViewController.swift | 1 | 16394 | import Foundation
import CocoaLumberjack
import WordPressShared
/// The purpose of this class is to render and modify the Jetpack Settings associated to a site.
///
open class JetpackSecuritySettingsViewController: UITableViewController {
// MARK: - Private Properties
fileprivate var blog: Blog!
fileprivate var service: BlogJetpackSettingsService!
fileprivate lazy var handler: ImmuTableViewHandler = {
return ImmuTableViewHandler(takeOver: self)
}()
// MARK: - Computed Properties
fileprivate var settings: BlogSettings {
return blog.settings!
}
// MARK: - Static Properties
fileprivate static let footerHeight = CGFloat(34.0)
fileprivate static let learnMoreUrl = "https://jetpack.com/support/sso/"
fileprivate static let wordPressLoginSection = 2
// MARK: - Initializer
public convenience init(blog: Blog) {
self.init(style: .grouped)
self.blog = blog
self.service = BlogJetpackSettingsService(managedObjectContext: settings.managedObjectContext!)
}
// MARK: - View Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Security", comment: "Title for the Jetpack Security Settings Screen")
ImmuTable.registerRows([SwitchRow.self], tableView: tableView)
ImmuTable.registerRows([NavigationItemRow.self], tableView: tableView)
WPStyleGuide.configureColors(for: view, andTableView: tableView)
reloadViewModel()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadSelectedRow()
tableView.deselectSelectedRowWithAnimation(true)
refreshSettings()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
// MARK: - Model
fileprivate func reloadViewModel() {
handler.viewModel = tableViewModel()
}
func tableViewModel() -> ImmuTable {
var monitorRows = [ImmuTableRow]()
monitorRows.append(
SwitchRow(title: NSLocalizedString("Monitor your site's uptime",
comment: "Jetpack Monitor Settings: Monitor site's uptime"),
value: self.settings.jetpackMonitorEnabled,
onChange: self.jetpackMonitorEnabledValueChanged())
)
if self.settings.jetpackMonitorEnabled {
monitorRows.append(
SwitchRow(title: NSLocalizedString("Send notifications by email",
comment: "Jetpack Monitor Settings: Send notifications by email"),
value: self.settings.jetpackMonitorEmailNotifications,
onChange: self.sendNotificationsByEmailValueChanged())
)
monitorRows.append(
SwitchRow(title: NSLocalizedString("Send push notifications",
comment: "Jetpack Monitor Settings: Send push notifications"),
value: self.settings.jetpackMonitorPushNotifications,
onChange: self.sendPushNotificationsValueChanged())
)
}
var bruteForceAttackRows = [ImmuTableRow]()
bruteForceAttackRows.append(
SwitchRow(title: NSLocalizedString("Block malicious login attempts",
comment: "Jetpack Settings: Block malicious login attempts"),
value: self.settings.jetpackBlockMaliciousLoginAttempts,
onChange: self.blockMaliciousLoginAttemptsValueChanged())
)
if self.settings.jetpackBlockMaliciousLoginAttempts {
bruteForceAttackRows.append(
NavigationItemRow(title: NSLocalizedString("Whitelisted IP addresses",
comment: "Jetpack Settings: Whitelisted IP addresses"),
action: self.pressedWhitelistedIPAddresses())
)
}
var wordPressLoginRows = [ImmuTableRow]()
wordPressLoginRows.append(
SwitchRow(title: NSLocalizedString("Allow WordPress.com login",
comment: "Jetpack Settings: Allow WordPress.com login"),
value: self.settings.jetpackSSOEnabled,
onChange: self.ssoEnabledChanged())
)
if self.settings.jetpackSSOEnabled {
wordPressLoginRows.append(
SwitchRow(title: NSLocalizedString("Match accounts using email",
comment: "Jetpack Settings: Match accounts using email"),
value: self.settings.jetpackSSOMatchAccountsByEmail,
onChange: self.matchAccountsUsingEmailChanged())
)
wordPressLoginRows.append(
SwitchRow(title: NSLocalizedString("Require two-step authentication",
comment: "Jetpack Settings: Require two-step authentication"),
value: self.settings.jetpackSSORequireTwoStepAuthentication,
onChange: self.requireTwoStepAuthenticationChanged())
)
}
return ImmuTable(sections: [
ImmuTableSection(
headerText: "",
rows: monitorRows,
footerText: nil),
ImmuTableSection(
headerText: NSLocalizedString("Brute Force Attack Protection",
comment: "Jetpack Settings: Brute Force Attack Protection Section"),
rows: bruteForceAttackRows,
footerText: nil),
ImmuTableSection(
headerText: NSLocalizedString("WordPress.com login",
comment: "Jetpack Settings: WordPress.com Login settings"),
rows: wordPressLoginRows,
footerText: nil)
])
}
// MARK: Learn More footer
open override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == JetpackSecuritySettingsViewController.wordPressLoginSection {
return JetpackSecuritySettingsViewController.footerHeight
}
return 0.0
}
open override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == JetpackSecuritySettingsViewController.wordPressLoginSection {
let footer = UITableViewHeaderFooterView(frame: CGRect(x: 0.0,
y: 0.0,
width: tableView.frame.width,
height: JetpackSecuritySettingsViewController.footerHeight))
footer.textLabel?.text = NSLocalizedString("Learn more...",
comment: "Jetpack Settings: WordPress.com Login WordPress login footer text")
footer.textLabel?.font = UIFont.preferredFont(forTextStyle: .footnote)
footer.textLabel?.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(handleLearnMoreTap(_:)))
footer.addGestureRecognizer(tap)
return footer
}
return nil
}
// MARK: - Row Handlers
fileprivate func jetpackMonitorEnabledValueChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackMonitorEnabled = newValue
self.reloadViewModel()
self.service.updateJetpackSettingsForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
fileprivate func sendNotificationsByEmailValueChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackMonitorEmailNotifications = newValue
self.service.updateJetpackMonitorSettingsForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
fileprivate func sendPushNotificationsValueChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackMonitorPushNotifications = newValue
self.service.updateJetpackMonitorSettingsForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
fileprivate func blockMaliciousLoginAttemptsValueChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackBlockMaliciousLoginAttempts = newValue
self.reloadViewModel()
self.service.updateJetpackSettingsForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
func pressedWhitelistedIPAddresses() -> ImmuTableAction {
return { [unowned self] row in
let whiteListedIPs = self.settings.jetpackLoginWhiteListedIPAddresses
let settingsViewController = SettingsListEditorViewController(collection: whiteListedIPs)
settingsViewController.title = NSLocalizedString("Whitelisted IP Addresses",
comment: "Whitelisted IP Addresses Title")
settingsViewController.insertTitle = NSLocalizedString("New IP or IP Range",
comment: "IP Address or Range Insertion Title")
settingsViewController.editTitle = NSLocalizedString("Edit IP or IP Range",
comment: "IP Address or Range Edition Title")
settingsViewController.footerText = NSLocalizedString("You may whitelist an IP address or series of addresses preventing them from ever being blocked by Jetpack. IPv4 and IPv6 are acceptable. To specify a range, enter the low value and high value separated by a dash. Example: 12.12.12.1-12.12.12.100.",
comment: "Text rendered at the bottom of the Whitelisted IP Addresses editor, should match Calypso.")
settingsViewController.onChange = { [weak self] (updated: Set<String>) in
self?.settings.jetpackLoginWhiteListedIPAddresses = updated
guard let blog = self?.blog else {
return
}
self?.service.updateJetpackSettingsForBlog(blog,
success: { [weak self] in
// viewWillAppear will trigger a refresh, maybe before
// the new IPs are saved, so lets refresh again here
self?.refreshSettings()
},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
self.navigationController?.pushViewController(settingsViewController, animated: true)
}
}
fileprivate func ssoEnabledChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackSSOEnabled = newValue
self.reloadViewModel()
self.service.updateJetpackSettingsForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
fileprivate func matchAccountsUsingEmailChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackSSOMatchAccountsByEmail = newValue
self.service.updateJetpackSettingsForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
fileprivate func requireTwoStepAuthenticationChanged() -> (_ newValue: Bool) -> Void {
return { [unowned self] newValue in
self.settings.jetpackSSORequireTwoStepAuthentication = newValue
self.service.updateJetpackSettingsForBlog(self.blog,
success: {},
failure: { [weak self] (_) in
self?.refreshSettingsAfterSavingError()
})
}
}
// MARK: - Footer handler
@objc fileprivate func handleLearnMoreTap(_ sender: UITapGestureRecognizer) {
guard let url = URL(string: JetpackSecuritySettingsViewController.learnMoreUrl) else {
return
}
let webViewController = WebViewControllerFactory.controller(url: url)
if presentingViewController != nil {
navigationController?.pushViewController(webViewController, animated: true)
} else {
let navController = UINavigationController(rootViewController: webViewController)
present(navController, animated: true, completion: nil)
}
}
// MARK: - Persistance
fileprivate func refreshSettings() {
service.syncJetpackSettingsForBlog(blog,
success: { [weak self] in
self?.reloadViewModel()
DDLogInfo("Reloaded Jetpack Settings")
},
failure: { (error: Error?) in
DDLogError("Error while syncing blog Jetpack Settings: \(String(describing: error))")
})
}
fileprivate func refreshSettingsAfterSavingError() {
let errorTitle = NSLocalizedString("Error updating Jetpack settings",
comment: "Title of error dialog when updating jetpack settins fail.")
let errorMessage = NSLocalizedString("Please contact support for assistance.",
comment: "Message displayed on an error alert to prompt the user to contact support")
WPError.showAlert(withTitle: errorTitle, message: errorMessage, withSupportButton: true)
refreshSettings()
}
}
| gpl-2.0 | a392eb6b7fba7862d3708c5d74e61164 | 49.134557 | 315 | 0.527083 | 6.752059 | false | false | false | false |
jvd001/ios | Owncloud iOs Client/Tabs/FileTab/Share/Cells/ShareLinkHeaderCell.swift | 1 | 1255 | //
// ShareLinkHeaderCell.swift
// Owncloud iOs Client
//
// Created by Gonzalo Gonzalez on 4/8/15.
//
/*
Copyright (C) 2015, ownCloud, Inc.
This code is covered by the GNU Public License Version 3.
For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/
You should have received a copy of this license
along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.en.html>.
*/
import UIKit
class ShareLinkHeaderCell:UITableViewCell {
let switchCornerRadious: CGFloat = 17.0
@IBOutlet weak var titleSection: UILabel!
@IBOutlet weak var switchSection: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
fileprivate func setup(){
switchSection.backgroundColor = UIColor.white
switchSection.layer.cornerRadius = switchCornerRadious
self.contentView.backgroundColor = UIColor.ofNavigationBar()
titleSection.textColor = UIColor.ofNavigationTitle()
}
}
| gpl-3.0 | 46c71fcac2cce53a9aa3cfd4fcad9dc4 | 26.888889 | 109 | 0.688446 | 4.357639 | false | false | false | false |
r14r-work/fork_swift_intro-playgrounds | 11-StructuresAndClasses.playground/section-1.swift | 2 | 6476 | // Playground - noun: a place where people can play
import Cocoa
// *****************************************************************************
// S T R U C T U R E S
// *****************************************************************************
// *************************************************
// Define a structure holding a 2-dimensional point.
// *************************************************
struct Point {
var x = 0.0
var y = 0.0
}
// *************************************************************
// Create an instance of the structure using initializer syntax.
// *************************************************************
let origin = Point()
// Print values of structure properties.
println("Point at (\(origin.x), \(origin.y))")
// *******************************************
// Memberwise Initializers for Structure Types
// *******************************************
let point = Point(x: 5.0, y: 10.0)
// ***************************
// Structures are value types.
// ***************************
var o1 = origin
var o2 = o1
o1.x = 5.0
o1
o2
// ******************
// Nesting Structures
// ******************
struct Size {
var width = 0.0
var height = 0.0
}
struct Rectangle {
var origin = Point()
var size = Size()
}
var square1 = Rectangle(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))
// *****************************************************************************
// C L A S S E S
// *****************************************************************************
// *************************************
// Define a class that describes a shape
// *************************************
class Shape {
var x = 0
var y = 0
var name: String?
}
// ********************************************
// Create an instance using initializer syntax.
// ********************************************
let shape = Shape()
println("shape at (\(shape.x), \(shape.y)) with name '\(shape.name)'")
// No memberwise initializer provided for a class!
// ***************************
// Classes are Reference Types
// ***************************
var s1 = shape
var s2 = s1
s1.x = 10
s1
s2
// Maybe unexpected, but value of property in constant was also changed!
shape
// ******************
// Identity Operators
// ******************
// Identical to (===)
// Not identitical to (!==)
s1 === s2
s2 === shape
let s3 = Shape()
s3.x = 10
s2 === s3
// **********************
// Lazy Stored Properties
// **********************
class ComputeTask {
@lazy var description = String()
var name = "ComputeTask"
}
var ct = ComputeTask()
ct
ct.description = "a task"
ct
// ************************************
// Compute Properties (class or struct)
// ************************************
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
// "newValue" is default name for passed value
// Could replace with named parameter if desired.
set /*(newCenter)*/ {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
var square2 = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square2.center
square2.center = Point(x: 15.0, y: 15.0)
square2
// Read-only Computed Properties
// Must declare as 'var', not 'let' They change when computed!
struct Square {
var size = Size()
var area: Double { return size.width * size.height }
}
let s = Square(size: Size(width: 10.0, height: 10.0))
s.area
// s.area = 100
// ******************
// Property Observers
// ******************
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
// New value passed in using named parameter
println("About to set totalSteps to \(newTotalSteps)")
}
didSet {
// "oldValue" is default name for parameter
if totalSteps > oldValue {
println("added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
stepCounter.totalSteps = 360
stepCounter.totalSteps = 896
// ***************
// Type Properties
// ***************
struct CountedPoint {
static var numberOfInstances: Int = 0
var x = 0.0
var y = 0.0
}
println("There are \(CountedPoint.numberOfInstances) instances of CountedPoint right now.")
// Not yet supported, but this is how they would be done.
//class CountedObject {
// class var numberOfInstances: Int = 0
//}
//println("There are \(CountedObject.numberOfInstances) instances right now.")
// *****************************************************************************
// M E T H O D S
// *****************************************************************************
class Counter {
var count = 0
func increment() {
count++
}
func incrementBy(amount: Int) {
incrementBy(amount, numberOfTimes: 1)
}
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
func reset() {
// The use of self is optional here.
self.count = 0
}
func resetToCount(#count: Int) {
// The use of self is required here to disambiguate.
self.count = count
}
}
let counter = Counter()
counter.increment()
counter.incrementBy(5)
counter.reset()
counter.resetToCount(count: 10)
// ************************************************************
// Method parameter naming (local and external parameter names)
// ************************************************************
func ex1_incrementBy(amount: Int, numberOfTimes: Int) {
// Does nothing...
}
func ex2_incrementBy(amount: Int, #numberOfTimes: Int) {
// Does nothing...
}
ex1_incrementBy(10, 10)
ex2_incrementBy(10, numberOfTimes: 10)
// Notice that method definition did not explicitly provide an external
// parameter name for "numberOfTimes", but Swift provided one.
counter.incrementBy(10, numberOfTimes: 10)
// Next Week - More About Classes & Structures
//
// - Opting into mutating behavior on value types.
// - Type Methods
// - Subscripts
// - Inheritance (base classes, subclassing, overriding)
// - Initialization
| mit | 5389d3f5ab7178076d97e2c910ebff9a | 21.722807 | 93 | 0.48425 | 4.268952 | false | false | false | false |
FelixSFD/FDRatingView | Shared/FDStarView.swift | 1 | 3174 | //
// FDStarView.swift
// FDRatingView
//
// Created by Felix Deil on 11.05.16.
// Copyright © 2016 Felix Deil. All rights reserved.
//
//import UIKit
import QuartzCore
/**
This `UIView` displays a star, that can be fully or partially filled.
- author: Felix Deil
*/
internal class FDStarView: FDRatingElementView {
// - MARK: Private properties
/**
The layer that draws a fully filled star
*/
private var fullStar: CAShapeLayer!
/**
The layer that draws the border of a star
*/
private var borderStar: CAShapeLayer!
override internal var tintColor: FDColor! {
get {
return FDColor.black
}
set (color) {
fullStar.fillColor = color.cgColor
borderStar.strokeColor = color.cgColor
}
}
// - MARK: Initialize the View
/**
Initializes the `FDStarView`
- parameter frame: The frame for the view
- parameter fillValue: `Float` bewteen 0 and 1
- parameter color: The color of the star. Not the background of the view. Acts like `tintColor`
- paramter lineWidth: The with of the border-line (default is 1, but for really small stars, lower values are recommended)
- author: Felix Deil
*/
internal init(frame: CGRect, fillValue fill: Float, color fillColor: FDColor, lineWidth: CGFloat) {
super.init(frame: frame)
//layer for complete filled star
fullStar = CAShapeLayer()
fullStar.path = Star().CGPathInRect(frame)
fullStar.fillColor = fillColor.cgColor
self.layer.addSublayer(fullStar)
//layer for border
borderStar = CAShapeLayer()
borderStar.path = fullStar.path
borderStar.fillColor = FDColor.clear.cgColor
borderStar.lineWidth = lineWidth
borderStar.strokeColor = fillColor.cgColor
self.layer.addSublayer(borderStar)
//create fill-mask
let fillWidth = frame.size.width * CGFloat(fill)
let fillPath = FDBezierPath(roundedRect: CGRect(x: 0, y: 0, width: fillWidth, height: frame.size.height), cornerRadius: 0)
fillMask = CAShapeLayer()
fillMask.path = fillPath.cgPath
fullStar.mask = fillMask
}
/**
Initializes the `FDStarView`
- parameter frame: The frame for the view
- parameter fillValue: `Float` bewteen 0 and 1
- parameter color: The color of the star. Not the background of the view. Acts like `tintColor`
- author: Felix Deil
*/
internal convenience init(frame: CGRect, fillValue fill: Float, color fillColor: FDColor) {
self.init(frame:frame, fillValue: fill, color: fillColor, lineWidth: 1)
}
/**
Initializes the view with a frame
*/
override private init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = FDColor.clear
tintColor = FDView().tintColor
}
required internal init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 5b0d347aa758de9858c60f8939d2fdb9 | 27.330357 | 130 | 0.616766 | 4.500709 | false | false | false | false |
thanegill/RxSwift | Tests/RxSwiftTests/Tests/VirtualSchedulerTest.swift | 9 | 6289 | //
// VirtualSchedulerTest.swift
// Tests
//
// Created by Krunoslav Zaher on 12/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import XCTest
#if os(Linux)
import Glibc
#endif
class VirtualSchedulerTest : RxTest {
}
extension VirtualSchedulerTest {
func testVirtualScheduler_initialClock() {
let scheduler = TestVirtualScheduler(initialClock: 10)
XCTAssertEqual(scheduler.now, NSDate(timeIntervalSince1970: 100.0))
XCTAssertEqual(scheduler.clock, 10)
}
func testVirtualScheduler_start() {
let scheduler = TestVirtualScheduler()
var times: [Int] = []
scheduler.scheduleRelative((), dueTime: 10.0) { _ in
times.append(scheduler.clock)
scheduler.scheduleRelative((), dueTime: 20.0) { _ in
times.append(scheduler.clock)
return NopDisposable.instance
}
return scheduler.schedule(()) { _ in
times.append(scheduler.clock)
return NopDisposable.instance
}
}
scheduler.start()
XCTAssertEqual(times, [
1,
1,
3
])
}
func testVirtualScheduler_disposeStart() {
let scheduler = TestVirtualScheduler()
var times: [Int] = []
scheduler.scheduleRelative((), dueTime: 10.0) { _ in
times.append(scheduler.clock)
let d = scheduler.scheduleRelative((), dueTime: 20.0) { _ in
times.append(scheduler.clock)
return NopDisposable.instance
}
let d2 = scheduler.schedule(()) { _ in
times.append(scheduler.clock)
return NopDisposable.instance
}
d2.dispose()
d.dispose()
return NopDisposable.instance
}
scheduler.start()
XCTAssertEqual(times, [
1
])
}
func testVirtualScheduler_advanceToAfter() {
let scheduler = TestVirtualScheduler()
var times: [Int] = []
scheduler.scheduleRelative((), dueTime: 10.0) { _ in
times.append(scheduler.clock)
scheduler.scheduleRelative((), dueTime: 20.0) { _ in
times.append(scheduler.clock)
return NopDisposable.instance
}
return scheduler.schedule(()) { _ in
times.append(scheduler.clock)
return NopDisposable.instance
}
}
scheduler.advanceTo(10)
XCTAssertEqual(times, [
1,
1,
3
])
}
func testVirtualScheduler_advanceToBefore() {
let scheduler = TestVirtualScheduler()
var times: [Int] = []
scheduler.scheduleRelative((), dueTime: 10.0) { [weak scheduler] _ in
times.append(scheduler!.clock)
scheduler!.scheduleRelative((), dueTime: 20.0) { _ in
times.append(scheduler!.clock)
return NopDisposable.instance
}
return scheduler!.schedule(()) { _ in
times.append(scheduler!.clock)
return NopDisposable.instance
}
}
scheduler.advanceTo(1)
XCTAssertEqual(times, [
1,
1
])
}
func testVirtualScheduler_disposeAdvanceTo() {
let scheduler = TestVirtualScheduler()
var times: [Int] = []
scheduler.scheduleRelative((), dueTime: 10.0) { [weak scheduler] _ in
times.append(scheduler!.clock)
let d1 = scheduler!.scheduleRelative((), dueTime: 20.0) { _ in
times.append(scheduler!.clock)
return NopDisposable.instance
}
let d2 = scheduler!.schedule(()) { _ in
times.append(scheduler!.clock)
return NopDisposable.instance
}
d1.dispose()
d2.dispose()
return NopDisposable.instance
}
scheduler.advanceTo(20)
XCTAssertEqual(times, [
1,
])
}
func testVirtualScheduler_stop() {
let scheduler = TestVirtualScheduler()
var times: [Int] = []
scheduler.scheduleRelative((), dueTime: 10.0) { [weak scheduler] _ in
times.append(scheduler!.clock)
scheduler!.scheduleRelative((), dueTime: 20.0) { _ in
times.append(scheduler!.clock)
return NopDisposable.instance
}
scheduler!.schedule(()) { _ in
times.append(scheduler!.clock)
return NopDisposable.instance
}
scheduler!.stop()
return NopDisposable.instance
}
scheduler.start()
XCTAssertEqual(times, [
1,
])
}
func testVirtualScheduler_sleep() {
let scheduler = TestVirtualScheduler()
var times: [Int] = []
scheduler.scheduleRelative((), dueTime: 10.0) { [weak scheduler] _ in
times.append(scheduler!.clock)
scheduler!.sleep(10)
scheduler!.scheduleRelative((), dueTime: 20.0) { _ in
times.append(scheduler!.clock)
return NopDisposable.instance
}
scheduler!.schedule(()) { _ in
times.append(scheduler!.clock)
return NopDisposable.instance
}
return NopDisposable.instance
}
scheduler.start()
XCTAssertEqual(times, [
1,
11,
13
])
}
func testVirtualScheduler_stress() {
let scheduler = TestVirtualScheduler()
var times = [Int]()
var ticks = [Int]()
for _ in 0 ..< 20000 {
let random = Int(rand() % 10000)
times.append(random)
scheduler.scheduleRelative((), dueTime: RxTimeInterval(10 * random)) { [weak scheduler] _ in
ticks.append(scheduler!.clock)
return NopDisposable.instance
}
}
scheduler.start()
times = times.sort()
XCTAssertEqual(times, ticks)
}
}
| mit | aff11a717bf4230e0b2968c02c492c5f | 25.644068 | 104 | 0.528785 | 5.166804 | false | true | false | false |
Majki92/SwiftEmu | SwiftBoy/FileIO.swift | 2 | 2263 | //
// FileIO.swift
// SwiftBoy
//
// Created by Michal Majczak on 02.03.2016.
// Copyright © 2016 Michal Majczak. All rights reserved.
//
import Foundation
// Function for creating folder at specified location
func createFolderAt(_ folder: String, location: FileManager.SearchPathDirectory ) -> Bool {
guard let locationUrl = FileManager().urls(for: location, in: .userDomainMask).first else { return false }
do {
try FileManager().createDirectory(at: locationUrl.appendingPathComponent(folder), withIntermediateDirectories: false, attributes: nil)
return true
} catch let error as NSError {
// folder already exists return true
if error.code == 17 || error.code == 516 {
//LogD(folder + " already exists at " + locationUrl.absoluteString + " , ignoring")
return true
}
LogE(folder + " couldn't be created at " + locationUrl.absoluteString)
LogE(error.description)
return false
}
}
// Function for saving to binary file at specified location
func saveBinaryFile(_ name: String, location: FileManager.SearchPathDirectory, buffer: [UInt8]) -> Bool {
guard
let locationURL = FileManager().urls(for: location, in: .userDomainMask).first
else {
LogE("Failed to resolve path while saving file.")
return false
}
let fileURL = locationURL.appendingPathComponent(name)
let data = Data(bytes: UnsafePointer<UInt8>(buffer), count: buffer.count)
return ((try? data.write(to: fileURL, options: [.atomic])) != nil)
}
// Function for loading from binary file at specified location
func loadBinaryFile(_ name: String, location: FileManager.SearchPathDirectory, buffer: inout [UInt8]) -> Bool {
guard
let locationURL = FileManager().urls(for: location, in: .userDomainMask).first
else {
LogE("Failed to find " + name + " file!")
return false
}
let fileURL = locationURL.appendingPathComponent(name)
guard
let ramData = try? Data(contentsOf: fileURL)
else {
LogD("Failed to load " + name + " file!")
return false
}
(ramData as NSData).getBytes(&buffer, length: ramData.count)
return true
}
| gpl-2.0 | ac730a629da762aeef6f8f9ed5c7474f | 36.081967 | 142 | 0.654288 | 4.470356 | false | false | false | false |
groue/GRDB.swift | Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerCreationView.swift | 1 | 1624 | import SwiftUI
/// The view that creates a new player.
struct PlayerCreationView: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
@Environment(\.dismiss) private var dismiss
@State private var form = PlayerForm(name: "", score: "")
@State private var errorAlertIsPresented = false
@State private var errorAlertTitle = ""
var body: some View {
NavigationView {
PlayerFormView(form: $form)
.alert(
isPresented: $errorAlertIsPresented,
content: { Alert(title: Text(errorAlertTitle)) })
.navigationBarTitle("New Player")
.navigationBarItems(
leading: Button(role: .cancel) {
dismiss()
} label: {
Text("Cancel")
},
trailing: Button {
Task { await save() }
} label: {
Text("Save")
})
}
}
private func save() async {
do {
var player = Player(id: nil, name: "", score: 0)
form.apply(to: &player)
try await appDatabase.savePlayer(&player)
dismiss()
} catch {
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
errorAlertIsPresented = true
}
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView()
}
}
| mit | 95a44a440dcbf4a43a16153e8112650f | 31.48 | 97 | 0.512931 | 5.359736 | false | false | false | false |
ppoh71/motoRoutes | motoRoutes/MRCellView.swift | 1 | 1665 | //
// motoRouteCellControllerTableViewCell.swift
// motoRoutes
//
// Created by Peter Pohlmann on 26.01.16.
// Copyright © 2016 Peter Pohlmann. All rights reserved.
//
import UIKit
import CoreLocation
class MRCellView: UITableViewCell {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var distanceLabel: UILabel!
@IBOutlet var routeImage: MRCellViewImage!
@IBOutlet var fromLabel: UILabel!
@IBOutlet var toLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
/*
routeImage.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
routeImage.layer.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
routeImage.layer.masksToBounds = false
routeImage.layer.borderWidth = 1.0
routeImage.layer.borderColor = UIColor.whiteColor().CGColor
routeImage.layer.cornerRadius = (routeImage.layer.frame.height/2)
routeImage.clipsToBounds = true
routeImage.layer.masksToBounds = true
print("rounded \(routeImage.frame.size.height/2)")
*/
}
//config func of cell
func configureCell(_ name:String, distance:String, image: UIImage, fromLocation: String, toLocation: String){
nameLabel.text = name
distanceLabel.text = distance
routeImage.image = image
fromLabel.text = fromLocation
toLabel.text = toLocation
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 | 9aeec97065feeb260e3046169358852b | 27.20339 | 113 | 0.644231 | 4.461126 | false | true | false | false |
carabina/TapGestureGenerater | TapGestureGeneraterExample/Tests/Tests.swift | 1 | 1186 | // https://github.com/Quick/Quick
import Quick
import Nimble
import TapGestureGenerater
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 0bddd75f0dc2ea2c5024c09d402bab92 | 22.6 | 63 | 0.368644 | 5.488372 | false | false | false | false |
hirohisa/RxSwift | RxSwift/RxSwift/Subjects/BehaviorSubject.swift | 15 | 3528 | //
// BehaviorSubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
private class BehaviorSubjectSubscription<Element> : Disposable {
typealias Parent = BehaviorSubject<Element>
typealias DisposeKey = Parent.ObserverBag.KeyType
let parent: Parent
var disposeKey: DisposeKey?
init(parent: BehaviorSubject<Element>, disposeKey: DisposeKey) {
self.parent = parent
self.disposeKey = disposeKey
}
func dispose() {
self.parent.lock.performLocked {
if let disposeKey = disposeKey {
self.parent.observers.removeKey(disposeKey)
self.disposeKey = nil
}
}
}
}
public class BehaviorSubject<Element> : SubjectType<Element, Element> {
typealias ObserverOf = Observer<Element>
typealias ObserverBag = Bag<Observer<Element>>
let lock = NSRecursiveLock()
private var _value: Element
private var observers: ObserverBag = Bag()
private var stoppedEvent: Event<Element>?
public init(value: Element) {
self._value = value
super.init()
}
// Returns value if value exists or throws exception if subject contains error
public var value: Element {
get {
return lock.calculateLocked {
if let error = stoppedEvent?.error {
// intentionally throw exception
return failure(error).get()
}
else {
return _value
}
}
}
}
public var valueResult: RxResult<Element> {
get {
return lock.calculateLocked {
if let error = stoppedEvent?.error {
// intentionally throw exception
return failure(error)
}
else {
return success(_value)
}
}
}
}
public var hasObservers: Bool {
get {
return lock.calculateLocked {
observers.count > 0
}
}
}
public override func on(event: Event<Element>) {
let observers = lock.calculateLocked { () -> [Observer<Element>]? in
if self.stoppedEvent != nil {
return nil
}
switch event {
case .Next(let boxedValue):
self._value = boxedValue.value
case .Error:
self.stoppedEvent = event
case .Completed:
self.stoppedEvent = event
}
return self.observers.all
}
dispatch(event, observers)
}
override public func subscribe<O : ObserverType where O.Element == Element>(observer: O) -> Disposable {
let disposeKey = lock.calculateLocked { () -> ObserverBag.KeyType? in
if let stoppedEvent = stoppedEvent {
send(observer, stoppedEvent)
return nil
}
let key = observers.put(ObserverOf.normalize(observer))
sendNext(observer, _value)
return key
}
if let disposeKey = disposeKey {
return BehaviorSubjectSubscription(parent: self, disposeKey: disposeKey)
}
else {
return NopDisposable.instance
}
}
} | mit | 12a462ce014ee1fc318799ed7bbc0938 | 27.007937 | 108 | 0.533447 | 5.57346 | false | false | false | false |
pocketworks/Spring | Spring/LoadingView.swift | 1 | 2913 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class LoadingView: UIView {
@IBOutlet public weak var indicatorView: SpringView!
override public func awakeFromNib() {
let animation = CABasicAnimation()
animation.keyPath = "transform.rotation.z"
animation.fromValue = degreesToRadians(0)
animation.toValue = degreesToRadians(360)
animation.duration = 0.9
animation.repeatCount = HUGE
indicatorView.layer.addAnimation(animation, forKey: "")
}
class func designCodeLoadingView() -> UIView {
return NSBundle(forClass: self).loadNibNamed("LoadingView", owner: self, options: nil)[0] as! UIView
}
}
public extension UIView {
struct LoadingViewConstants {
static let Tag = 1000
}
public func showLoading() {
if let loadingXibView = self.viewWithTag(LoadingViewConstants.Tag) {
// If loading view is already found in current view hierachy, do nothing
return
}
let loadingXibView = LoadingView.designCodeLoadingView()
loadingXibView.frame = self.bounds
loadingXibView.tag = LoadingViewConstants.Tag
self.addSubview(loadingXibView)
loadingXibView.alpha = 0
spring(0.7, animations: {
loadingXibView.alpha = 1
})
}
public func hideLoading() {
if let loadingXibView = self.viewWithTag(LoadingViewConstants.Tag) {
loadingXibView.alpha = 1
springWithCompletion(0.7, animations: {
loadingXibView.alpha = 0
loadingXibView.transform = CGAffineTransformMakeScale(3, 3)
}, completion: { (completed) -> Void in
loadingXibView.removeFromSuperview()
})
}
}
}
| mit | d22689b15ac30d6c48208781fd9e15ea | 34.52439 | 108 | 0.683488 | 4.945671 | false | false | false | false |
practicalswift/swift | validation-test/compiler_crashers_2_fixed/0182-rdar45680857.swift | 31 | 710 | // RUN: %target-swift-frontend -emit-ir %s
public protocol Graph: class, Collection {
associatedtype V
associatedtype E
}
public protocol EdgeContainer {
associatedtype E
associatedtype Visitor: NeighboursVisitor where Visitor.C == Self
func push(_ thing: E)
}
public protocol NeighboursVisitor {
associatedtype C: EdgeContainer
associatedtype G: Graph where G.E == C.E
}
public enum LIFONeighboursVisitor<C: EdgeContainer, G: Graph>: NeighboursVisitor where G.E == C.E {
}
public class Stack<T, G: Graph>: EdgeContainer where T == G.E {
public typealias E = T
public typealias Visitor = LIFONeighboursVisitor<Stack<T, G>, G>
public func push(_ thing: T) { }
}
| apache-2.0 | e590e0d92b290a55e731172a04d0cbed | 23.482759 | 99 | 0.705634 | 3.604061 | false | false | false | false |
linggaozhen/Living | LivingApplication/LivingApplication/Classess/Home/Controller/HomeViewController.swift | 1 | 3976 | //
// HomeViewController.swift
// LivingApplication
//
// Created by ioser on 17/5/15.
// Copyright © 2017年 ioser. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
// titleView懒加载
lazy var pageTitleView : PageTitleView = {
let titleViewFrame = CGRect(x: 0, y: 64, width: KScreenW, height: 40)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleView = PageTitleView(frame: titleViewFrame, titles: titles)
titleView.delegate = self
return titleView
}()
// contentView 懒加载
lazy var contentView : pageContentView = {[weak self] in
// 通过一个数组保存控制器
var controllerArray = [UIViewController]()
let recommerController = RecommerController()
let gameViewController = GameViewController()
controllerArray.append(recommerController)
controllerArray.append(gameViewController)
for i in 0...1 {
let viewController = UIViewController()
viewController.view.backgroundColor = UIColor.init(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
controllerArray.append(viewController)
}
// 初始化contentView,把数组传进去
let contentView = pageContentView(frame: (self?.view.bounds)!, childViewController: controllerArray, parentController: self!)
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
// 扩展方法
extension HomeViewController{
private func setupUI() -> Void {
automaticallyAdjustsScrollViewInsets = false
// 1 设置导航栏
setNavigationItem()
// 2 设置titleView
setTitleView()
// 3 设置contentView
setcontentView()
}
/**
setTitleView
*/
private func setTitleView(){
view.addSubview(self.pageTitleView)
}
private func setcontentView(){
let contentViewY = self.pageTitleView.frame.maxY
contentView.frame = CGRect(x: 0, y: contentViewY, width: KScreenW, height: KScreenH - contentViewY - 44)
contentView.scrollerDelegate = self
contentView.backgroundColor = UIColor.yellowColor()
view.addSubview(contentView)
}
/**
setNavigationItem
*/
private func setNavigationItem(){
// 左边item
// let leftItem = UIBarButtonItem.createBarButtonItem("logo")
let leftItem = UIBarButtonItem(imageName: "logo")
navigationItem.leftBarButtonItem = leftItem
// 右边item
let size = CGSizeMake(40, 40)
// 利用构造函数创建
let historyItem = UIBarButtonItem(imageName: "image_my_history", hightImageName: "image_my_history_click", size: size)
let qrCoderItem = UIBarButtonItem(imageName: "Image_scan", hightImageName: "Image_scan_click", size: size)
let SearchItem = UIBarButtonItem(imageName: "btn_search", hightImageName: "btn_search_clicked", size: size)
navigationItem.rightBarButtonItems = [historyItem,qrCoderItem,SearchItem]
}
}
// MARK: - titleView Label 的点击事件
extension HomeViewController : pageTitleViewDelegate{
func pageLabelClick(selectIndext: Int, titleView: PageTitleView) {
self.contentView.pageTitleLabelClick(selectIndext)
}
}
// contentView的代理事件
extension HomeViewController : pageContentViewScrollerDelegate{
func scrollerProgress(progress: CGFloat, beginIndext: Int, targetIndext: Int) {
// print("begin \(beginIndext) target \(targetIndext) progress \(progress)")
self.pageTitleView.changeLineFrameAndLabelColor(beginIndext, targetIndext: targetIndext, progress: progress)
}
}
| apache-2.0 | 9b6d1e7a4617f2d4ab6155b68293764c | 29.181102 | 173 | 0.645708 | 4.971466 | false | false | false | false |
adamdahan/MaterialKit | Source/MaterialButton.swift | 1 | 4671 | //
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public class MaterialButton : UIButton {
//
// :name: backgroundColorView
//
internal lazy var backgroundColorView: UIView = UIView()
//
// :name: pulseView
//
internal var pulseView: UIView?
/**
:name: backgroundColor
*/
public override var backgroundColor: UIColor? {
didSet {
backgroundColorView.backgroundColor = backgroundColor
}
}
/**
:name: pulseColor
*/
public var pulseColor: UIColor?
/**
:name: init
*/
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareView()
}
/**
:name: init
*/
public required override init(frame: CGRect) {
super.init(frame: frame)
prepareView()
}
/**
:name: init
*/
public convenience init() {
self.init(frame: CGRectZero)
}
/**
:name: touchesBegan
*/
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
pulseBegan(touches, withEvent: event)
}
/**
:name: touchesEnded
*/
public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
shrink()
pulseEnded(touches, withEvent: event)
}
/**
:name: touchesCancelled
*/
public override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
super.touchesCancelled(touches, withEvent: event)
shrink()
pulseEnded(touches, withEvent: event)
}
/**
:name: drawRect
*/
final public override func drawRect(rect: CGRect) {
prepareContext(rect)
prepareButton()
prepareBackgroundColorView()
}
//
// :name: prepareButton
//
internal func prepareButton() {
backgroundColorView.frame = bounds
}
//
// :name: pulseBegan
//
internal func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
let touchLocation = touch.locationInView(self)
pulseView = UIView()
pulseView!.frame = CGRectMake(0, 0, bounds.height, bounds.height)
pulseView!.layer.cornerRadius = bounds.height / 2
pulseView!.center = touchLocation
pulseView!.backgroundColor = pulseColor?.colorWithAlphaComponent(0.5)
backgroundColorView.addSubview(pulseView!)
}
//
// :name: pulseEnded
//
internal func pulseEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
UIView.animateWithDuration(0.3,
animations: { _ in
self.pulseView?.alpha = 0
}
) { _ in
self.pulseView?.removeFromSuperview()
self.pulseView = nil
}
}
//
// :name: prepareShadow
//
internal func prepareShadow() {
layer.shadowOffset = CGSizeMake(1, 1)
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = 0.5
layer.shadowRadius = 5
}
//
// :name: prepareBackgroundColorView
//
// We need this view so we can use the masksToBounds
// so the pulse doesn't animate off the button
private func prepareBackgroundColorView() {
backgroundColorView.layer.masksToBounds = true
backgroundColorView.clipsToBounds = true
backgroundColorView.userInteractionEnabled = false
insertSubview(backgroundColorView, atIndex: 0)
}
//
// :name: prepareView
//
private func prepareView() {
setTranslatesAutoresizingMaskIntoConstraints(false)
}
//
// :name: prepareContext
//
private func prepareContext(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context);
CGContextAddEllipseInRect(context, rect)
CGContextSetFillColorWithColor(context, UIColor.clearColor().CGColor)
CGContextFillPath(context)
CGContextRestoreGState(context);
}
//
// :name: shrink
//
private func shrink() {
UIView.animateWithDuration(0.3,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 10,
options: nil,
animations: {
self.transform = CGAffineTransformIdentity
},
completion: nil
)
}
}
| agpl-3.0 | a2cacdc7a806439b0b84498e4425be36 | 22.953846 | 92 | 0.716121 | 3.649219 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0362-clang-stmt-statisticsenabled.swift | 13 | 923 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func e<l {
j {
}
func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(p: (Any, Any) -> Any) -> Any in
func n<n : l,) {
}
j j j.o = {
t) {
}
protocol o {
}
class j: o{ class func o {}
e o<j : u> {
}
func n<q>() {
b b {
}
}
func n(j: Any, t: Any) -> (((Any, Any) -> Any) -> Any) {
k {
}
}
}
struct c<e> {
}
func b<c {
enum b {
class A : NSManagedObject {
func b<T: A>() -> [T] {
}
}
class d<c>: NSObject {
init(b: c) {
}
}
}
class f<p : k, p : k where p.n == p> : n {
}
class f<p, p> {
}
protocol k {
}
o: i where k.j == f> {l func k() { }
}
func k<o {
enum k {
() {
}
}
var f1: Int -> Int = {
}
}
snit(foo: T) {
}
}
}
import {
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
| apache-2.0 | a5dc25dfc5a3f7fc078b8f276944223e | 11.472973 | 87 | 0.52546 | 2.245742 | false | false | false | false |
tevelee/CodeGenerator | output/swift/RecordBuilder.swift | 1 | 781 | import Foundation
struct RecordBuilder {
var name: String
var creator: Person
var date: Date
func build () -> Record {
return Record(name: name, creator: creator, date: date)
}
//MARK: Initializers
init(existingRecord: Record) {
name = existingRecord.name
creator = existingRecord.creator
date = existingRecord.date
}
//MARK: Property setters
mutating func withName(_ name: String) -> RecordBuilder {
self.name = name
return self
}
mutating func withCreator(_ creator: Person) -> RecordBuilder {
self.creator = creator
return self
}
mutating func withDate(_ date: Date) -> RecordBuilder {
self.date = date
return self
}
}
| mit | 37e65a80bd1632d68b0c73bca11369ce | 20.694444 | 67 | 0.599232 | 4.594118 | false | false | false | false |
ycaihua/Paranormal | Paranormal/ParanormalTests/Tools/ToolsViewControllerTests.swift | 2 | 7321 | import Cocoa
import Quick
import Nimble
import Paranormal
class ToolsViewControllerTests: QuickSpec {
override func spec() {
describe("ToolsViewController") {
var document : Document?
var editorView : EditorView?
var activeTool : EditorActiveTool?
var windowController : WindowController?
var plane : NSButton?
var emphasize : NSButton?
var flatten : NSButton?
var smooth : NSButton?
var sharpen : NSButton?
var tilt : NSButton?
var pan : NSButton?
var buttons : [NSButton?]!
var expectOnlyButtonSelected : (NSButton?) -> Void = {(currentbutton) in
for button in buttons {
if (button == currentbutton) {
expect(button?.bordered).to(beTrue())
} else {
expect(button?.bordered).to(beFalse())
}
}
}
beforeEach {
let documentController = DocumentController()
document = documentController
.makeUntitledDocumentOfType("Paranormal", error: nil) as? Document
documentController.addDocument(document!)
document?.makeWindowControllers()
windowController = document?.singleWindowController
windowController?.editorViewController?.view
windowController?.toolsViewController?.view
windowController?.editorViewController?.activeEditorTool = nil
plane = windowController?.toolsViewController?.plane
emphasize = windowController?.toolsViewController?.emphasize
flatten = windowController?.toolsViewController?.flatten
smooth = windowController?.toolsViewController?.smooth
sharpen = windowController?.toolsViewController?.sharpen
tilt = windowController?.toolsViewController?.tilt
pan = windowController?.toolsViewController?.pan
buttons = [plane, emphasize, flatten, smooth, sharpen, tilt, pan]
}
describe("planePressed") {
it("sets the active tool on the editorViewController to be an PlaneTool") {
windowController?.toolsViewController?.planePressed(plane!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expect(activeTool as? PlaneTool).toNot(beNil())
}
it("tests to see if plane is only button pressed") {
windowController?.toolsViewController?.planePressed(plane!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expectOnlyButtonSelected(plane)
}
}
describe("emphasizePressed") {
it("sets the active tool on the editorViewController to be an EmphasizeTool") {
windowController?.toolsViewController?.emphasizePressed(emphasize!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expect(activeTool as? EmphasizeTool).toNot(beNil())
}
it("tests to see if emphasize is only button pressed") {
windowController?.toolsViewController?.emphasizePressed(emphasize!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expectOnlyButtonSelected(emphasize)
}
}
describe("flattenPressed") {
it("sets the active tool on the editorViewController to b a FlattenTool") {
windowController?.toolsViewController?.flattenPressed(flatten!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expect(activeTool as? FlattenTool).toNot(beNil())
}
it("tests to see if flatten is only button pressed") {
windowController?.toolsViewController?.flattenPressed(flatten!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expectOnlyButtonSelected(flatten)
}
}
describe("smoothPressed") {
it("sets the active tool on the editorViewController to b a SmoothTool") {
windowController?.toolsViewController?.smoothPressed(smooth!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expect(activeTool as? SmoothTool).toNot(beNil())
}
it("tests to see if smooth is only button pressed") {
windowController?.toolsViewController?.smoothPressed(smooth!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expectOnlyButtonSelected(smooth)
}
}
describe("sharpenPressed") {
it("sets the active tool on the editorViewController to b a SharpenTool") {
windowController?.toolsViewController?.sharpenPressed(sharpen!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expect(activeTool as? SharpenTool).toNot(beNil())
}
it("tests to see if sharpen is only button pressed") {
windowController?.toolsViewController?.sharpenPressed(sharpen!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expectOnlyButtonSelected(sharpen)
}
}
describe("tiltPressed") {
it("sets the active tool on the editorViewController to b a TiltTool") {
windowController?.toolsViewController?.tiltPressed(tilt!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expect(activeTool as? TiltTool).toNot(beNil())
}
it("tests to see if tilt is only button pressed") {
windowController?.toolsViewController?.tiltPressed(tilt!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expectOnlyButtonSelected(tilt)
}
}
describe("panPressed") {
it("sets the active tool on the editorViewController to be a PanTool") {
windowController?.toolsViewController?.panPressed(pan!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expect(activeTool as? PanTool).toNot(beNil())
}
it("tests to see if pan is only button pressed") {
windowController?.toolsViewController?.panPressed(pan!)
let activeTool = windowController?.editorViewController?.activeEditorTool
expectOnlyButtonSelected(pan)
}
}
}
}
}
| mit | 6aa841e49a3b67341d7f7e3eae56fc4e | 43.91411 | 95 | 0.579292 | 6.230638 | false | false | false | false |
OrWest/Poseidon | src/NavigatingMap.swift | 1 | 1392 | //
// NavigationMap.swift
// Poseidon
//
// Created by Alex Motor on 02.07.17.
// Copyright © 2017 Alex Motor. All rights reserved.
//
import UIKit
public class NavigatingMap {
/**
Persited storybaords with their identifier.
*/
let storyboardsByID: [String : UIStoryboard]
let defaultStoryboard: UIStoryboard
/**
Initializer to create application map to navigation.
This method create dictionary with IDs and its related item(UIStoryboard or UINib), which will be use to navigate.
- parameters:
- storyboardsID: Array of storyboard names. This storyboard will be initialized and persist to fetch controllers.
- defaultStoryboardName: Name of the storyboard, which will be use by default to fetch controller.
This name must be in storyboardsID array.
*/
public init(_ storyboardsID: [String], _ defaultStoryboardName: String) {
var storyboardsByID = [String : UIStoryboard]()
storyboardsID.forEach { (name) in
storyboardsByID[name] = UIStoryboard(name: name, bundle: nil)
}
self.storyboardsByID = storyboardsByID
assert(storyboardsByID[defaultStoryboardName] != nil, "MainStoryboardName must be in storyboardsID array.")
self.defaultStoryboard = storyboardsByID[defaultStoryboardName]!
}
}
| mit | 2fae4bffa8d7646bb66bcfbba3ddd304 | 32.119048 | 121 | 0.671459 | 4.780069 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.