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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
elpassion/el-space-ios | ELSpaceTests/TestCases/ViewModels/DailyReportViewModelSpec.swift | 1 | 13619 | import Quick
import Nimble
import SwiftDate
@testable import ELSpace
class DailyReportViewModelSpec: QuickSpec {
override func spec() {
describe("DailyReportViewModel") {
var sut: DailyReportViewModel!
var formatter: DateFormatter!
beforeEach {
formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
}
afterEach {
sut = nil
formatter = nil
}
context("when initialize with 2 normal weekday reports") {
var dateFake: Date!
beforeEach {
dateFake = formatter.date(from: "2017/08/09 22:31")
let fakeReports: [ReportDTO] = [
ReportDTO.fakeReportDto(projectId: 10, value: "3.0", performedAt: "2017/08/09 22:31", comment: "fake_comment1", reportType: 0),
ReportDTO.fakeReportDto(projectId: 11, value: "5.0", performedAt: "2017/08/09 22:31", comment: "fake_comment2", reportType: 0)
]
let fakeProjectsDTO = [
ProjectDTO.fakeProjectDto(name: "fake_name1", id: 10),
ProjectDTO.fakeProjectDto(name: "fake_name2", id: 11)
]
sut = DailyReportViewModel(date: dateFake, todayDate: dateFake, reports: fakeReports, projects: fakeProjectsDTO, isHoliday: false)
}
it("should have correct title") {
expect(sut.title?.string).to(equal("Total: 8.0 hours"))
}
it("should have correct day") {
expect(sut.day.string).to(equal(DateFormatter.dayFormatter.string(from: dateFake)))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.weekday))
}
it("should have correct stripeColor") {
expect(sut.stripeColor).to(equal(UIColor(color: .green92ECB4)))
}
it("should have correct backgroundColor") {
expect(sut.backgroundColor).to(equal(UIColor.white))
}
it("should have correct hideAddReportButton value") {
expect(sut.hideAddReportButton).to(beFalse())
}
describe("ReportsViewModel") {
var reportsViewModel: [ReportDetailsViewModelProtocol]!
beforeEach {
reportsViewModel = sut.reportsViewModel
}
it("should have 2 elements") {
expect(reportsViewModel).to(haveCount(2))
}
}
}
context("when initialize with weekday report with type 1") {
var dateFake: Date!
beforeEach {
dateFake = formatter.date(from: "2017/08/09 22:31")
let fakeReports: [ReportDTO] = [
ReportDTO.fakeReportDto(projectId: nil, value: "8.0", performedAt: "2017/08/09 22:31", comment: nil, reportType: 1)
]
let fakeProjectsDTO = [
ProjectDTO.fakeProjectDto(name: "fake_name1", id: 10),
ProjectDTO.fakeProjectDto(name: "fake_name2", id: 11)
]
sut = DailyReportViewModel(date: dateFake, todayDate: dateFake, reports: fakeReports, projects: fakeProjectsDTO, isHoliday: false)
}
it("should have correct title") {
expect(sut.title?.string).to(equal("Total: 8.0 hours"))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.weekday))
}
it("should have correct hideAddReportButton value") {
expect(sut.hideAddReportButton).to(beFalse())
}
}
context("when initialize with weekday report with type 2") {
var dateFake: Date!
beforeEach {
dateFake = formatter.date(from: "2017/08/09 22:31")
let fakeReports: [ReportDTO] = [
ReportDTO.fakeReportDto(projectId: nil, value: "8.0", performedAt: "2017/08/09 22:31", comment: nil, reportType: 2)
]
let fakeProjectsDTO = [
ProjectDTO.fakeProjectDto(name: "fake_name1", id: 10),
ProjectDTO.fakeProjectDto(name: "fake_name2", id: 11)
]
sut = DailyReportViewModel(date: dateFake, todayDate: dateFake, reports: fakeReports, projects: fakeProjectsDTO, isHoliday: false)
}
it("should have correct title") {
expect(sut.title?.string).to(equal("Unpaid vacations"))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.weekday))
}
it("should have correct hideAddReportButton value") {
expect(sut.hideAddReportButton).to(beTrue())
}
}
context("when initialize with weekday report with type 3") {
var dateFake: Date!
beforeEach {
dateFake = formatter.date(from: "2017/08/09 22:31")
let fakeReports: [ReportDTO] = [
ReportDTO.fakeReportDto(projectId: nil, value: "8.0", performedAt: "2017/08/09 22:31", comment: nil, reportType: 3)
]
let fakeProjectsDTO = [
ProjectDTO.fakeProjectDto(name: "fake_name1", id: 10),
ProjectDTO.fakeProjectDto(name: "fake_name2", id: 11)
]
sut = DailyReportViewModel(date: dateFake, todayDate: dateFake, reports: fakeReports, projects: fakeProjectsDTO, isHoliday: false)
}
it("should have correct title") {
expect(sut.title?.string).to(equal("Sick leave"))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.weekday))
}
it("should have correct hideAddReportButton value") {
expect(sut.hideAddReportButton).to(beTrue())
}
}
context("when initialize with weekday report with type 3") {
var dateFake: Date!
beforeEach {
dateFake = formatter.date(from: "2017/08/09 22:31")
let fakeReports: [ReportDTO] = [
ReportDTO.fakeReportDto(projectId: nil, value: "8.0", performedAt: "2017/08/09 22:31", comment: nil, reportType: 4)
]
sut = DailyReportViewModel(date: dateFake, todayDate: dateFake, reports: fakeReports, projects: [], isHoliday: false)
}
it("should have correct title") {
expect(sut.title?.string).to(equal("Conference"))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.weekday))
}
it("should have correct hideAddReportButton value") {
expect(sut.hideAddReportButton).to(beTrue())
}
}
context("when initialize with weekend date") {
var dateFake: Date!
beforeEach {
dateFake = formatter.date(from: "2017/08/12 22:31")
sut = DailyReportViewModel(date: dateFake, todayDate: dateFake, reports: [], projects: [], isHoliday: false)
}
it("should have correct title") {
expect(sut.title?.string).to(equal("Weekend!"))
}
it("should have correct day") {
expect(sut.day.string).to(equal(DateFormatter.dayFormatter.string(from: dateFake)))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.weekend))
}
it("should have correct stripeColor") {
expect(sut.stripeColor).to(equal(UIColor.clear))
}
it("should have correct backgroundColor") {
expect(sut.backgroundColor).to(equal(UIColor.clear))
}
describe("ReportsViewModel") {
var reportsViewModel: [ReportDetailsViewModelProtocol]!
beforeEach {
reportsViewModel = sut.reportsViewModel
}
it("should have 0 elements") {
expect(reportsViewModel).to(haveCount(0))
}
}
}
context("when initialize with comming date") {
var dateFake: Date!
beforeEach {
var date = Date() + 1.day
while date.isInWeekend == true {
date = date + 1.day // swiftlint:disable:this shorthand_operator
}
dateFake = date
sut = DailyReportViewModel(date: dateFake, todayDate: dateFake, reports: [], projects: [], isHoliday: false)
}
it("should have correct title") {
expect(sut.title).to(beNil())
}
it("should have correct day") {
expect(sut.day.string).to(equal(DateFormatter.dayFormatter.string(from: dateFake)))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.comming))
}
it("should have correct stripeColor") {
expect(sut.stripeColor).to(equal(UIColor(color: .grayE4E4E4)))
}
it("should have correct backgroundColor") {
expect(sut.backgroundColor).to(equal(UIColor.white))
}
describe("ReportsViewModel") {
var reportsViewModel: [ReportDetailsViewModelProtocol]!
beforeEach {
reportsViewModel = sut.reportsViewModel
}
it("should have 0 elements") {
expect(reportsViewModel).to(haveCount(0))
}
}
}
context("when initialize with previous Date and empty reports") {
var dateFake: Date!
beforeEach {
var date = Date() - 1.day
while date.isInWeekend == true {
date = date - 1.day // swiftlint:disable:this shorthand_operator
}
dateFake = date
sut = DailyReportViewModel(date: dateFake, todayDate: Date(), reports: [], projects: [], isHoliday: false)
}
it("should have correct title") {
expect(sut.title?.string).to(equal("Missing"))
}
it("should have correct day") {
expect(sut.day.string).to(equal(DateFormatter.dayFormatter.string(from: dateFake)))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.missing))
}
it("should have correct stripeColor") {
expect(sut.stripeColor).to(equal(UIColor(color: .redBA6767)))
}
it("should have correct backgroundColor") {
expect(sut.backgroundColor).to(equal(UIColor.white))
}
describe("ReportsViewModel") {
var reportsViewModel: [ReportDetailsViewModelProtocol]!
beforeEach {
reportsViewModel = sut.reportsViewModel
}
it("should have 0 elements") {
expect(reportsViewModel).to(haveCount(0))
}
}
}
context("when day isHoliday") {
beforeEach {
sut = DailyReportViewModel(date: formatter.date(from: "2018/06/08 12:00")!,
todayDate: formatter.date(from: "2018/06/08 12:00")!,
reports: [],
projects: [],
isHoliday: true)
}
it("should have correct title") {
expect(sut.title?.string).to(equal("Holiday"))
}
it("should have correct dayType") {
expect(sut.dayType).to(equal(DayType.holiday))
}
it("should have correct stripeColor") {
expect(sut.stripeColor).to(equal(UIColor.clear))
}
it("should have correct backgroundColor") {
expect(sut.backgroundColor).to(equal(UIColor.clear))
}
}
}
}
}
| gpl-3.0 | ac9a7df4b16a50a098b3bf9927d37c40 | 38.475362 | 151 | 0.47911 | 5.125706 | false | false | false | false |
insidegui/WWDC | WWDC/MultipleChoiceFilter.swift | 1 | 3465 | //
// MultipleChoiceFilter.swift
// WWDC
//
// Created by Guilherme Rambo on 27/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
struct FilterOption: Equatable, Codable {
let title: String
let value: String
var isNegative: Bool = false
init(title: String, value: String, isNegative: Bool = false) {
self.title = title
self.value = value
self.isNegative = isNegative
}
func negated(with newTitle: String) -> FilterOption {
return FilterOption(title: newTitle, value: value, isNegative: true)
}
enum CodingKeys: String, CodingKey {
case value, title
}
}
extension Array where Element == FilterOption {
init?(_ fromArray: [Any]?) {
guard let fromArray = fromArray as? [[String: String]] else {
return nil
}
self = [FilterOption]()
for i in fromArray {
if let title = i["title"], let value = i["value"] {
append(FilterOption(title: title, value: value))
}
}
}
}
struct MultipleChoiceFilter: FilterType {
var identifier: FilterIdentifier
var isSubquery: Bool
var collectionKey: String
var modelKey: String
var options: [FilterOption]
private var _selectedOptions: [FilterOption] = [FilterOption]()
var selectedOptions: [FilterOption] {
get {
return _selectedOptions
}
set {
// For state preservation we ensure that selected options are actually part of the options that are available on this filter
_selectedOptions = newValue.filter { options.contains($0) }
}
}
var emptyTitle: String
var isEmpty: Bool {
return selectedOptions.isEmpty
}
var title: String {
if isEmpty || selectedOptions.count == options.count {
return emptyTitle
} else {
let t = selectedOptions.reduce("", { $0 + ", " + $1.title })
guard !t.isEmpty else { return t }
return String(t[t.index(t.startIndex, offsetBy: 2)...])
}
}
var predicate: NSPredicate? {
guard !isEmpty else { return nil }
let subpredicates = selectedOptions.map { option -> NSPredicate in
let format: String
let op = option.isNegative ? "!=" : "=="
if isSubquery {
format = "SUBQUERY(\(collectionKey), $\(collectionKey), $\(collectionKey).\(modelKey) \(op) %@).@count > 0"
} else {
format = "\(modelKey) \(op) %@"
}
return NSPredicate(format: format, option.value)
}
return NSCompoundPredicate(orPredicateWithSubpredicates: subpredicates)
}
init(identifier: FilterIdentifier, isSubquery: Bool, collectionKey: String, modelKey: String, options: [FilterOption], selectedOptions: [FilterOption], emptyTitle: String) {
self.identifier = identifier
self.isSubquery = isSubquery
self.collectionKey = collectionKey
self.modelKey = modelKey
self.options = options
self.emptyTitle = emptyTitle
// Computed property
self.selectedOptions = selectedOptions
}
mutating func reset() {
selectedOptions = []
}
var state: State {
State(selectedOptions: selectedOptions)
}
struct State: Codable {
let selectedOptions: [FilterOption]
}
}
| bsd-2-clause | 2935401d192f87b52f42aa999b04f670 | 25.852713 | 177 | 0.59873 | 4.649664 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/Pods/Alamofire/Source/AFError.swift | 42 | 19750 | //
// AFError.swift
//
// Copyright (c) 2014 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
/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
/// their own associated reasons.
///
/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`.
/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process.
/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails.
/// - responseValidationFailed: Returned when a `validate()` call fails.
/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process.
public enum AFError: Error {
/// The underlying reason the parameter encoding error occurred.
///
/// - missingURL: The URL request did not have a URL to encode.
/// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the
/// encoding process.
/// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during
/// encoding process.
public enum ParameterEncodingFailureReason {
case missingURL
case jsonEncodingFailed(error: Error)
case propertyListEncodingFailed(error: Error)
}
/// The underlying reason the multipart encoding error occurred.
///
/// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a
/// file URL.
/// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty
/// `lastPathComponent` or `pathExtension.
/// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable.
/// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw
/// an error.
/// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory.
/// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by
/// the system.
/// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided
/// threw an error.
/// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`.
/// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the
/// encoded data to disk.
/// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file
/// already exists at the provided `fileURL`.
/// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is
/// not a file URL.
/// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an
/// underlying error.
/// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with
/// underlying system error.
public enum MultipartEncodingFailureReason {
case bodyPartURLInvalid(url: URL)
case bodyPartFilenameInvalid(in: URL)
case bodyPartFileNotReachable(at: URL)
case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
case bodyPartFileIsDirectory(at: URL)
case bodyPartFileSizeNotAvailable(at: URL)
case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
case bodyPartInputStreamCreationFailed(for: URL)
case outputStreamCreationFailed(for: URL)
case outputStreamFileAlreadyExists(at: URL)
case outputStreamURLInvalid(url: URL)
case outputStreamWriteFailed(error: Error)
case inputStreamReadFailed(error: Error)
}
/// The underlying reason the response validation error occurred.
///
/// - dataFileNil: The data file containing the server response did not exist.
/// - dataFileReadFailed: The data file containing the server response could not be read.
/// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes`
/// provided did not contain wildcard type.
/// - unacceptableContentType: The response `Content-Type` did not match any type in the provided
/// `acceptableContentTypes`.
/// - unacceptableStatusCode: The response status code was not acceptable.
public enum ResponseValidationFailureReason {
case dataFileNil
case dataFileReadFailed(at: URL)
case missingContentType(acceptableContentTypes: [String])
case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
case unacceptableStatusCode(code: Int)
}
/// The underlying reason the response serialization error occurred.
///
/// - inputDataNil: The server response contained no data.
/// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length.
/// - inputFileNil: The file containing the server response did not exist.
/// - inputFileReadFailed: The file containing the server response could not be read.
/// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`.
/// - jsonSerializationFailed: JSON serialization failed with an underlying system error.
/// - propertyListSerializationFailed: Property list serialization failed with an underlying system error.
public enum ResponseSerializationFailureReason {
case inputDataNil
case inputDataNilOrZeroLength
case inputFileNil
case inputFileReadFailed(at: URL)
case stringSerializationFailed(encoding: String.Encoding)
case jsonSerializationFailed(error: Error)
case propertyListSerializationFailed(error: Error)
}
case invalidURL(url: URLConvertible)
case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
case responseValidationFailed(reason: ResponseValidationFailureReason)
case responseSerializationFailed(reason: ResponseSerializationFailureReason)
}
// MARK: - Adapt Error
struct AdaptError: Error {
let error: Error
}
extension Error {
var underlyingAdaptError: Error? { return (self as? AdaptError)?.error }
}
// MARK: - Error Booleans
extension AFError {
/// Returns whether the AFError is an invalid URL error.
public var isInvalidURLError: Bool {
if case .invalidURL = self { return true }
return false
}
/// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncodingError: Bool {
if case .parameterEncodingFailed = self { return true }
return false
}
/// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties
/// will contain the associated values.
public var isMultipartEncodingError: Bool {
if case .multipartEncodingFailed = self { return true }
return false
}
/// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, and `responseCode` properties will contain the associated values.
public var isResponseValidationError: Bool {
if case .responseValidationFailed = self { return true }
return false
}
/// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and
/// `underlyingError` properties will contain the associated values.
public var isResponseSerializationError: Bool {
if case .responseSerializationFailed = self { return true }
return false
}
}
// MARK: - Convenience Properties
extension AFError {
/// The `URLConvertible` associated with the error.
public var urlConvertible: URLConvertible? {
switch self {
case .invalidURL(let url):
return url
default:
return nil
}
}
/// The `URL` associated with the error.
public var url: URL? {
switch self {
case .multipartEncodingFailed(let reason):
return reason.url
default:
return nil
}
}
/// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`,
/// `.multipartEncodingFailed` or `.responseSerializationFailed` error.
public var underlyingError: Error? {
switch self {
case .parameterEncodingFailed(let reason):
return reason.underlyingError
case .multipartEncodingFailed(let reason):
return reason.underlyingError
case .responseSerializationFailed(let reason):
return reason.underlyingError
default:
return nil
}
}
/// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
public var acceptableContentTypes: [String]? {
switch self {
case .responseValidationFailed(let reason):
return reason.acceptableContentTypes
default:
return nil
}
}
/// The response `Content-Type` of a `.responseValidationFailed` error.
public var responseContentType: String? {
switch self {
case .responseValidationFailed(let reason):
return reason.responseContentType
default:
return nil
}
}
/// The response code of a `.responseValidationFailed` error.
public var responseCode: Int? {
switch self {
case .responseValidationFailed(let reason):
return reason.responseCode
default:
return nil
}
}
/// The `String.Encoding` associated with a failed `.stringResponse()` call.
public var failedStringEncoding: String.Encoding? {
switch self {
case .responseSerializationFailed(let reason):
return reason.failedStringEncoding
default:
return nil
}
}
}
extension AFError.ParameterEncodingFailureReason {
var underlyingError: Error? {
switch self {
case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error):
return error
default:
return nil
}
}
}
extension AFError.MultipartEncodingFailureReason {
var url: URL? {
switch self {
case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url),
.bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url),
.bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url),
.outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url),
.bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _):
return url
default:
return nil
}
}
var underlyingError: Error? {
switch self {
case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error),
.outputStreamWriteFailed(let error), .inputStreamReadFailed(let error):
return error
default:
return nil
}
}
}
extension AFError.ResponseValidationFailureReason {
var acceptableContentTypes: [String]? {
switch self {
case .missingContentType(let types), .unacceptableContentType(let types, _):
return types
default:
return nil
}
}
var responseContentType: String? {
switch self {
case .unacceptableContentType(_, let responseType):
return responseType
default:
return nil
}
}
var responseCode: Int? {
switch self {
case .unacceptableStatusCode(let code):
return code
default:
return nil
}
}
}
extension AFError.ResponseSerializationFailureReason {
var failedStringEncoding: String.Encoding? {
switch self {
case .stringSerializationFailed(let encoding):
return encoding
default:
return nil
}
}
var underlyingError: Error? {
switch self {
case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error):
return error
default:
return nil
}
}
}
// MARK: - Error Descriptions
extension AFError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidURL(let url):
return "URL is not valid: \(url)"
case .parameterEncodingFailed(let reason):
return reason.localizedDescription
case .multipartEncodingFailed(let reason):
return reason.localizedDescription
case .responseValidationFailed(let reason):
return reason.localizedDescription
case .responseSerializationFailed(let reason):
return reason.localizedDescription
}
}
}
extension AFError.ParameterEncodingFailureReason {
var localizedDescription: String {
switch self {
case .missingURL:
return "URL request to encode was missing a URL"
case .jsonEncodingFailed(let error):
return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
case .propertyListEncodingFailed(let error):
return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)"
}
}
}
extension AFError.MultipartEncodingFailureReason {
var localizedDescription: String {
switch self {
case .bodyPartURLInvalid(let url):
return "The URL provided is not a file URL: \(url)"
case .bodyPartFilenameInvalid(let url):
return "The URL provided does not have a valid filename: \(url)"
case .bodyPartFileNotReachable(let url):
return "The URL provided is not reachable: \(url)"
case .bodyPartFileNotReachableWithError(let url, let error):
return (
"The system returned an error while checking the provided URL for " +
"reachability.\nURL: \(url)\nError: \(error)"
)
case .bodyPartFileIsDirectory(let url):
return "The URL provided is a directory: \(url)"
case .bodyPartFileSizeNotAvailable(let url):
return "Could not fetch the file size from the provided URL: \(url)"
case .bodyPartFileSizeQueryFailedWithError(let url, let error):
return (
"The system returned an error while attempting to fetch the file size from the " +
"provided URL.\nURL: \(url)\nError: \(error)"
)
case .bodyPartInputStreamCreationFailed(let url):
return "Failed to create an InputStream for the provided URL: \(url)"
case .outputStreamCreationFailed(let url):
return "Failed to create an OutputStream for URL: \(url)"
case .outputStreamFileAlreadyExists(let url):
return "A file already exists at the provided URL: \(url)"
case .outputStreamURLInvalid(let url):
return "The provided OutputStream URL is invalid: \(url)"
case .outputStreamWriteFailed(let error):
return "OutputStream write failed with error: \(error)"
case .inputStreamReadFailed(let error):
return "InputStream read failed with error: \(error)"
}
}
}
extension AFError.ResponseSerializationFailureReason {
var localizedDescription: String {
switch self {
case .inputDataNil:
return "Response could not be serialized, input data was nil."
case .inputDataNilOrZeroLength:
return "Response could not be serialized, input data was nil or zero length."
case .inputFileNil:
return "Response could not be serialized, input file was nil."
case .inputFileReadFailed(let url):
return "Response could not be serialized, input file could not be read: \(url)."
case .stringSerializationFailed(let encoding):
return "String could not be serialized with encoding: \(encoding)."
case .jsonSerializationFailed(let error):
return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
case .propertyListSerializationFailed(let error):
return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)"
}
}
}
extension AFError.ResponseValidationFailureReason {
var localizedDescription: String {
switch self {
case .dataFileNil:
return "Response could not be validated, data file was nil."
case .dataFileReadFailed(let url):
return "Response could not be validated, data file could not be read: \(url)."
case .missingContentType(let types):
return (
"Response Content-Type was missing and acceptable content types " +
"(\(types.joined(separator: ","))) do not match \"*/*\"."
)
case .unacceptableContentType(let acceptableTypes, let responseType):
return (
"Response Content-Type \"\(responseType)\" does not match any acceptable types: " +
"\(acceptableTypes.joined(separator: ","))."
)
case .unacceptableStatusCode(let code):
return "Response status code was unacceptable: \(code)."
}
}
}
| mit | 598283383849ccd7fd024d093140711c | 41.934783 | 122 | 0.647797 | 5.533763 | false | false | false | false |
nlambson/CanvasKit | CanvasKitTests/Model Tests/CKIFolderTests.swift | 3 | 2899 | //
// CKIFolderTests.swift
// CanvasKit
//
// Created by Nathan Lambson on 7/17/14.
// Copyright (c) 2014 Instructure. All rights reserved.
//
import UIKit
import XCTest
class CKIFolderTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testJSONModelConversion() {
let folderDictionary = Helpers.loadJSONFixture("folder") as NSDictionary
let folder = CKIFolder(fromJSONDictionary: folderDictionary)
XCTAssertEqual(folder.contextType!, "Course", "Folder contextType did not parse correctly")
XCTAssertEqual(folder.contextID!, "1401", "Folder contextID did not parse correctly")
XCTAssertEqual(folder.filesCount, 10, "Folder filesCount did not parse correctly")
XCTAssertEqual(folder.foldersCount, 0, "Folder foldersCount did not parse correctly")
var url = NSURL(string:"https://www.example.com/api/v1/folders/2937/folders")
XCTAssertEqual(folder.foldersURL!, url!, "Folder foldersURL did not parse correctly")
url = NSURL(string:"https://www.example.com/api/v1/folders/2937/files")
XCTAssertEqual(folder.filesURL!, url!, "Folder filesURL did not parse correctly")
let formatter = ISO8601DateFormatter()
formatter.includeTime = true
let date = formatter.dateFromString("2012-07-06T14:58:50Z")
XCTAssertEqual(folder.createdAt!, date, "Folder createdAt did not parse correctly")
XCTAssertEqual(folder.updatedAt!, date, "Folder updatedAt did not parse correctly")
XCTAssertEqual(folder.unlockAt!, date, "Folder unlockAt did not parse correctly")
XCTAssertEqual(folder.id!, "2937", "Folder id did not parse correctly")
XCTAssertEqual(folder.name!, "11folder", "Folder name did not parse correctly")
XCTAssertEqual(folder.fullName!, "course files/11folder", "Folder fullName did not parse correctly")
XCTAssertEqual(folder.lockAt!, date, "Folder lockAt did not parse correctly")
XCTAssertEqual(folder.parentFolderID!, "2934", "Folder parentFolderID did not parse correctly")
XCTAssertFalse(folder.hiddenForUser, "Folder hiddenForUser did not parse correctly")
XCTAssertEqual(folder.position, 3, "Folder position did not parse correctly")
XCTAssertEqual(folder.path!, "/api/v1/folders/2937", "Folder path did not parse correctly")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit | 505bcfd2a90cb9f37e142ba9a01c4107 | 45.015873 | 111 | 0.690238 | 4.572555 | false | true | false | false |
brentsimmons/Evergreen | Articles/Sources/Articles/Article.swift | 1 | 4475 | //
// Article.swift
// NetNewsWire
//
// Created by Brent Simmons on 7/1/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
public typealias ArticleSetBlock = (Set<Article>) -> Void
public struct Article: Hashable {
public let articleID: String // Unique database ID (possibly sync service ID)
public let accountID: String
public let webFeedID: String // Likely a URL, but not necessarily
public let uniqueID: String // Unique per feed (RSS guid, for example)
public let title: String?
public let contentHTML: String?
public let contentText: String?
public let rawLink: String? // We store raw source value, but use computed url or link other than where raw value required.
public let rawExternalLink: String? // We store raw source value, but use computed externalURL or externalLink other than where raw value required.
public let summary: String?
public let rawImageLink: String? // We store raw source value, but use computed imageURL or imageLink other than where raw value required.
public let datePublished: Date?
public let dateModified: Date?
public let authors: Set<Author>?
public let status: ArticleStatus
public init(accountID: String, articleID: String?, webFeedID: String, uniqueID: String, title: String?, contentHTML: String?, contentText: String?, url: String?, externalURL: String?, summary: String?, imageURL: String?, datePublished: Date?, dateModified: Date?, authors: Set<Author>?, status: ArticleStatus) {
self.accountID = accountID
self.webFeedID = webFeedID
self.uniqueID = uniqueID
self.title = title
self.contentHTML = contentHTML
self.contentText = contentText
self.rawLink = url
self.rawExternalLink = externalURL
self.summary = summary
self.rawImageLink = imageURL
self.datePublished = datePublished
self.dateModified = dateModified
self.authors = authors
self.status = status
if let articleID = articleID {
self.articleID = articleID
}
else {
self.articleID = Article.calculatedArticleID(webFeedID: webFeedID, uniqueID: uniqueID)
}
}
public static func calculatedArticleID(webFeedID: String, uniqueID: String) -> String {
return databaseIDWithString("\(webFeedID) \(uniqueID)")
}
// MARK: - Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(articleID)
}
// MARK: - Equatable
static public func ==(lhs: Article, rhs: Article) -> Bool {
return lhs.articleID == rhs.articleID && lhs.accountID == rhs.accountID && lhs.webFeedID == rhs.webFeedID && lhs.uniqueID == rhs.uniqueID && lhs.title == rhs.title && lhs.contentHTML == rhs.contentHTML && lhs.contentText == rhs.contentText && lhs.rawLink == rhs.rawLink && lhs.rawExternalLink == rhs.rawExternalLink && lhs.summary == rhs.summary && lhs.rawImageLink == rhs.rawImageLink && lhs.datePublished == rhs.datePublished && lhs.dateModified == rhs.dateModified && lhs.authors == rhs.authors
}
}
public extension Set where Element == Article {
func articleIDs() -> Set<String> {
return Set<String>(map { $0.articleID })
}
func unreadArticles() -> Set<Article> {
let articles = self.filter { !$0.status.read }
return Set(articles)
}
func contains(accountID: String, articleID: String) -> Bool {
return contains(where: { $0.accountID == accountID && $0.articleID == articleID})
}
}
public extension Array where Element == Article {
func articleIDs() -> [String] {
return map { $0.articleID }
}
}
public extension Article {
private static let allowedTags: Set = ["b", "bdi", "bdo", "cite", "code", "del", "dfn", "em", "i", "ins", "kbd", "mark", "q", "s", "samp", "small", "strong", "sub", "sup", "time", "u", "var"]
func sanitizedTitle(forHTML: Bool = true) -> String? {
guard let title = title else { return nil }
let scanner = Scanner(string: title)
scanner.charactersToBeSkipped = nil
var result = ""
result.reserveCapacity(title.count)
while !scanner.isAtEnd {
if let text = scanner.scanUpToString("<") {
result.append(text)
}
if let _ = scanner.scanString("<") {
// All the allowed tags currently don't allow attributes
if let tag = scanner.scanUpToString(">") {
if Self.allowedTags.contains(tag.replacingOccurrences(of: "/", with: "")) {
forHTML ? result.append("<\(tag)>") : result.append("")
} else {
forHTML ? result.append("<\(tag)>") : result.append("<\(tag)>")
}
let _ = scanner.scanString(">")
}
}
}
return result
}
}
| mit | 1f8cd4450070865ce0caf3c72f0bd0cc | 33.682171 | 499 | 0.696916 | 3.747069 | false | false | false | false |
GirAppe/Blackhole | Example/Tests/SendingPromisesTestCase.swift | 1 | 1617 | import UIKit
import XCTest
import Blackhole
class SendingPromisesTestCase: BlackholeTestCase {
// MARK: - Basic Tests
func testSimpleSendingSuccess() {
let identifier = "someIdentifier"
let message: BlackholeMessage = ["someKey":"stringValue"]
let expectation: XCTestExpectation = self.expectation(description: "Expect message to be sent")
self.session.emit(TestSession.EmitResult(success: true))
emitter.promiseSendMessage(message, withIdentifier: identifier)
.onSuccess {
expectation.fulfill()
}
.onFailure { error in
XCTAssert(false)
}
self.waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTAssert(false, "Error sending: \(error)")
}
}
}
func testSimpleSendingFailure() {
let identifier = "someIdentifier"
let message: BlackholeMessage = ["someKey":"stringValue"]
let expectation: XCTestExpectation = self.expectation(description: "Expect message to be sent")
self.session.emit(TestSession.EmitResult(success: false))
emitter.promiseSendMessage(message, withIdentifier: identifier)
.onSuccess {
XCTAssert(false)
}
.onFailure { error in
expectation.fulfill()
}
self.waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTAssert(false, "Error sending: \(error)")
}
}
}
}
| mit | 48f21f008d87f9bc21fbecb68e2f1790 | 28.944444 | 103 | 0.581323 | 5.408027 | false | true | false | false |
robbdimitrov/pixelgram-ios | PixelGram/Classes/Shared/ViewModels/ImageViewModel.swift | 1 | 3224 | //
// ImageViewModel.swift
// PixelGram
//
// Created by Robert Dimitrov on 10/27/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import UIKit
import RxSwift
class ImageViewModel {
var image: Image
var user: User?
var likes: Variable<Int>
static let dateFormatter = DateFormatter()
init(with image: Image) {
likes = Variable(image.likes)
self.image = image
user = UserLoader.shared.user(withId: image.owner)
configureDateFormatter()
}
// Getters
var isLikedByCurrentUser: Bool {
return image.isLiked
}
var isOwnedByCurrentUser: Bool {
if let currentUserId = Session.shared.currentUser?.id {
return image.owner == currentUserId
}
return false
}
var imageURL: URL? {
if image.filename.count > 0 {
return URL(string: APIClient.shared.urlForImage(image.filename))
}
return nil
}
var usernameText: String {
return user?.username ?? "Loading.."
}
var ownerAvatarURL: URL? {
if let avatarURL = user?.avatarURL, avatarURL.count > 0 {
return URL(string: APIClient.shared.urlForImage(avatarURL))
}
return nil
}
var likesText: String {
return "\(image.likes) \(image.likes == 1 ? "like" : "likes")"
}
var descriptionText: NSAttributedString? {
let usernameFont = UIFont.boldSystemFont(ofSize: 15.0)
let attributedString = NSMutableAttributedString(string: "\(user?.username ?? "Loading...") \(image.description)")
attributedString.setAttributes([.font : usernameFont], range: (attributedString.string as NSString).range(of: user?.username ?? "Loading..."))
return attributedString
}
var dateCreatedText: String {
return ImageViewModel.dateFormatter.string(from: image.dateCreated)
}
// MARK: - Actions
func likeImage(with user: User) {
let imageId = image.id
let isLiked = image.isLiked
let numberOfLikes = image.likes
let completion: () -> Void = {}
let failure: (String) -> Void = { [weak self] error in
self?.image.isLiked = isLiked
self?.image.likes = numberOfLikes
print("Liking image failed \(error)")
}
if isLikedByCurrentUser {
if let userId = Session.shared.currentUser?.id {
APIClient.shared.dislikeImage(withUserId: userId, imageId: imageId, completion: completion, failure: failure)
}
} else {
APIClient.shared.likeImage(withImageId: imageId, completion: completion, failure: failure)
}
image.isLiked = !isLiked
image.likes = (!isLiked ? numberOfLikes + 1 : numberOfLikes - 1)
}
// Configure date formatter
func configureDateFormatter() {
ImageViewModel.dateFormatter.dateStyle = .medium
ImageViewModel.dateFormatter.timeStyle = .short
ImageViewModel.dateFormatter.doesRelativeDateFormatting = true
}
}
| mit | f9dc5fd3002c4e9d80fe49c8d2ae1af1 | 27.026087 | 150 | 0.593546 | 4.875946 | false | false | false | false |
malcommac/Hydra | Sources/Hydra/Promise+All.swift | 1 | 3791 | /*
* Hydra
* Fullfeatured lightweight Promise & Await Library for Swift
*
* Created by: Daniele Margutti
* Email: [email protected]
* Web: http://www.danielemargutti.com
* Twitter: @danielemargutti
*
* Copyright © 2017 Daniele Margutti
*
*
* 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
/// Return a Promises that resolved when all input Promises resolves.
/// Promises are resolved in parallel in background QoS queue.
/// It rejects as soon as a promises reject for any reason; result reject with returned error.
///
/// - Parameters:
/// - promises: list of promises to resolve in parallel
/// - Returns: resolved promise which contains all resolved values from input promises (value are reported in the same order of input promises)
public func all<L>(_ promises: Promise<L>..., concurrency: UInt = UInt.max) -> Promise<[L]> {
return all(promises, concurrency: concurrency)
}
public func all<L, S: Sequence>(_ promises: S, concurrency: UInt = UInt.max) -> Promise<[L]> where S.Iterator.Element == Promise<L> {
guard Array(promises).count > 0, concurrency > 0 else {
// If number of passed promises is zero we want to return a resolved promises with an empty array as result
return Promise<[L]>(resolved: [])
}
// We want to create a Promise which groups all input Promises and return only
// when all input promises fulfill or one of them reject.
// Promises are resolved in parallel but the array with the results of all promises is reported
// in the same order of the input promises.
let allPromise = Promise<[L]> { (resolve, reject, operation) in
var countRemaining = Array(promises).count
var countRunningPromises: UInt = 0
let allPromiseContext = Context.custom(queue: DispatchQueue(label: "com.hydra.queue.all"))
for currentPromise in promises {
// Listen for each promise in list to fulfill or reject
currentPromise.add(in: allPromiseContext, onResolve: { value in
// if currentPromise fulfill
// decrement remaining promise to fulfill
countRemaining -= 1
if countRemaining == 0 {
// if all promises are fulfilled we can resolve our chain Promise
// with an array of all values results of our input promises (in the same order)
let allResults = promises.map({ return $0.state.value! })
resolve(allResults)
} else {
let nextPromise = promises.first(where: { $0.state.isPending && !$0.bodyCalled })
nextPromise?.runBody()
}
// if currentPromise reject the entire chain is broken and we reject the group Promise itself
}, onReject: { err in
reject(err)
}, onCancel: {
operation.cancel()
})
if concurrency > countRunningPromises {
currentPromise.runBody()
countRunningPromises += 1
}
}
}
return allPromise
}
| mit | 24d681f42ced95db702f5c09a3124426 | 40.648352 | 143 | 0.73219 | 4.092873 | false | false | false | false |
FunctioningFunctionalist/ramda.swift | Ramda/Extensions/allPass.swift | 1 | 1904 | //
// allPass.swift
// Ramda
//
// Created by TYRONE AVNIT on 2019/08/29.
//
import Foundation
extension R {
/**
Takes a list of predicates and returns a predicate that returns true for a given list of
arguments if every one of the provided predicates is satisfied by those arguments.
- parameter predicates: An array of predicates to check
- returns: Bool
*/
public class func allPassK<T>(_ predicates: [(T) -> Bool], _ list: [T]) -> Bool {
let fn = apply(predicates.compactMap(R.all))
return fn(list).filter(not).count == 0
}
/**
Takes a list of predicates and returns a predicate that returns true for a given list of
arguments if every one of the provided predicates is satisfied by those arguments.
- parameter predicates: An array of predicates to check
- returns: Curried function
*/
public class func allPassK<T>(_ predicates: [(T) -> Bool]) -> ([T]) -> Bool {
return curry(allPassK)(predicates)
}
/**
Takes a list of predicates and returns a predicate that returns true for a given list of
arguments if every one of the provided predicates is satisfied by those arguments.
- parameter predicates: An array of predicates to check
- returns: Bool
*/
public class func allPass<T>(_ predicates: [(T) -> Bool], _ arg: T) -> Bool {
let fn = apply(predicates)
return fn(arg).filter(not).count == 0
}
/**
Takes a list of predicates and returns a predicate that returns true for a given list of
arguments if every one of the provided predicates is satisfied by those arguments.
- parameter predicates: An array of predicates to check
- returns: Curried function
*/
public class func allPass<T>(_ predicates: [(T) -> Bool]) -> (T) -> Bool {
return curry(allPass)(predicates)
}
}
| mit | 88f85197ae121f88844bbf8150a899ae | 24.72973 | 93 | 0.644958 | 4.397229 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios | Source/Logger/Logger.swift | 1 | 3664 | // Copyright 2016 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CocoaLumberjack
class Logger {
static let defaultLevel = DDLogLevel.info
static func verbose(_ message: @autoclosure () -> String, error: Error? = nil, level: DDLogLevel = defaultLevel, file: String = #file, function: String = #function, line: UInt = #line) {
log(message(), level: level, flag: DDLogFlag.verbose, file: file, function: function, line: line)
}
static func debug(_ message: @autoclosure () -> String, error: Error? = nil, level: DDLogLevel = defaultLevel, file: String = #file, function: String = #function, line: UInt = #line) {
log(message(), level: level, flag: DDLogFlag.debug, file: file, function: function, line: line)
}
static func info(_ message: @autoclosure () -> String, error: Error? = nil, level: DDLogLevel = defaultLevel, file: String = #file, function: String = #function, line: UInt = #line) {
log(message(), level: level, flag: DDLogFlag.info, file: file, function: function, line: line)
}
static func warn(_ message: @autoclosure () -> String, error: Error? = nil, level: DDLogLevel = defaultLevel, file: String = #file, function: String = #function, line: UInt = #line) {
log(message(), level: level, flag: DDLogFlag.warning, file: file, function: function, line: line)
}
static func error(_ message: @autoclosure () -> String, error: Error? = nil, level: DDLogLevel = defaultLevel, file: String = #file, function: String = #function, line: UInt = #line) {
log(message(), level: level, flag: DDLogFlag.error, file: file, function: function, line: line, asynchronous: false)
}
static private func log(_ message: @autoclosure () -> String, error: Error? = nil, level: DDLogLevel, flag: DDLogFlag, context: Int = 0, file: String, function: String, line: UInt, tag: Any? = nil, asynchronous: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
guard LoggerManager.sharedInstance.hasSetup() else {
return
}
if level.rawValue & flag.rawValue != 0 {
let actualMessage: String
if let error = error as? NSError {
actualMessage = "\(message()): \(error.localizedFailureReason)"
} else {
actualMessage = message()
}
let logMessage = DDLogMessage(message: actualMessage, level: level, flag: flag, context: context, file: file, function: function, line: line, tag: tag, options: [.copyFile, .copyFunction], timestamp: nil)
ddlog.log(asynchronous: asynchronous, message: logMessage)
}
}
}
| mit | 8a1d88b4501363e545b5f97426996d5a | 56.25 | 269 | 0.68941 | 4.221198 | false | false | false | false |
TouchInstinct/LeadKit | TILogging/Sources/Views/LoggerWindow/LoggingTogglingWindow.swift | 1 | 3591 | //
// Copyright (c) 2022 Touch Instinct
//
// 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 TIUIKitCore
import UIKit
@available(iOS 15, *)
public final class LoggingTogglingWindow: UIWindow {
let loggingController = LoggingTogglingViewController()
override public init(windowScene: UIWindowScene) {
super.init(windowScene: windowScene)
}
override public init(frame: CGRect) {
super.init(frame: frame)
rootViewController = loggingController
windowLevel = .statusBar
backgroundColor = .clear
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake,
!loggingController.isLogsPresented {
openLoggingScreen()
} else {
super.motionEnded(motion, with: event)
}
}
public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let rootView = rootViewController else { return false }
if let loggingController = rootView.presentedViewController {
return loggingController.view.point(inside: point, with: event)
}
if let button = rootView.view.subviews.first {
let buttonPoint = convert(point, to: button)
return button.point(inside: buttonPoint, with: event)
}
return false
}
// MARK: - Public methdos
public func set(isRegisteredForShakingEvent: Bool) {
loggingController.set(isRegisteredForShakingEvent: isRegisteredForShakingEvent)
}
public func set(isVisible: Bool) {
loggingController.set(isVisible: isVisible)
}
// MARK: - Private methods
private func openLoggingScreen() {
if loggingController.isRegisteredForShakingEvent {
openLoggingScreenOnTopViewController()
} else {
loggingController.openLoggingScreen()
}
}
private func openLoggingScreenOnTopViewController() {
guard let rootViewController = rootViewController else {
return
}
let topViewController = rootViewController.topVisibleViewController
topViewController.present(LogsListViewController(), animated: true, completion: { [weak self] in
self?.loggingController.set(isLogsPresented: false)
})
loggingController.set(isLogsPresented: true)
}
}
| apache-2.0 | 65cef614f9c9d6b8d91f99ef42b311cd | 32.877358 | 104 | 0.690058 | 4.846154 | false | false | false | false |
pdil/PDColorPicker | Source/PDColorPickerGridView.swift | 1 | 6819 | //
// PDColorPickerGridView.swift
// PDColorPicker
//
// Created by Paolo Di Lorenzo on 8/8/17.
// Copyright © 2017 Paolo Di Lorenzo. All rights reserved.
//
import UIKit
protocol PDColorPickerGridDelegate: class {
func colorChanged(to newColor: PDColor)
}
protocol PDColorPickerGridDataSource: class {
func selectedHueForColorPicker() -> CGFloat?
}
class PDColorPickerGridView: UIView {
// MARK: - Gesture Recognizer
lazy var panRecognizer: PDPanGestureRecognizer = {
return PDPanGestureRecognizer(target: self, action: #selector(colorDragged(_:)))
}()
lazy var tapRecognizer: PDTapGestureRecognizer = {
return PDTapGestureRecognizer(target: self, action: #selector(colorTapped(_:)))
}()
// MARK: - Properties
weak var delegate: PDColorPickerGridDelegate?
weak var dataSource: PDColorPickerGridDataSource?
var currentColor: PDColor? {
didSet { setSliderCircle() }
}
var selectedHue: CGFloat? {
didSet {
guard let selectedHue = selectedHue else { return }
backgroundColor = UIColor(hue: selectedHue, saturation: 1, brightness: 1, alpha: 1)
}
}
// MARK: - Slider Properties
lazy var sliderCircle: UIView = {
let circle = UIView()
circle.layer.borderColor = UIColor.black.cgColor
circle.layer.borderWidth = 2.0
circle.backgroundColor = UIColor.white.withAlphaComponent(0.6)
circle.alpha = 0
return circle
}()
lazy var sliderCircleX: NSLayoutConstraint = {
let constraint = NSLayoutConstraint(item: self.sliderCircle, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 100)
return constraint
}()
lazy var sliderCircleY: NSLayoutConstraint = {
let constraint = NSLayoutConstraint(item: self.sliderCircle, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 100)
return constraint
}()
let sliderSize: CGFloat = 25
let visibilityOffset: CGFloat = 60
let circleGrowthScale: CGFloat = 3
// MARK: - Initializer
init() {
super.init(frame: .zero)
if #available(iOS 11.0, *) {
accessibilityIgnoresInvertColors = true
}
addGestureRecognizer(panRecognizer)
addGestureRecognizer(tapRecognizer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Life Cycle
var initialViewLoad = true
override func layoutSubviews() {
super.layoutSubviews()
setupGradient()
if initialViewLoad {
addSubview(sliderCircle)
sliderCircle.anchor(height: sliderSize, width: sliderSize)
addConstraints([sliderCircleX, sliderCircleY])
layoutIfNeeded()
sliderCircle.layer.cornerRadius = sliderCircle.frame.width / 2
setSliderCircle()
initialViewLoad = false
}
}
// MARK: - Setup
var saturationGradient = CAGradientLayer()
var brightnessGradient = CAGradientLayer()
func setupGradient() {
saturationGradient.removeFromSuperlayer()
brightnessGradient.removeFromSuperlayer()
saturationGradient = gradientLayerWithEndPoints(CGPoint(x: 0, y: 0.5), CGPoint(x: 1, y: 0.5), endColor: .white)
brightnessGradient = gradientLayerWithEndPoints(CGPoint(x: 0.5, y: 0), CGPoint(x: 0.5, y: 1), endColor: .black)
layer.addSublayer(saturationGradient)
layer.addSublayer(brightnessGradient)
bringSubviewToFront(sliderCircle)
}
private func gradientLayerWithEndPoints(_ start: CGPoint, _ end: CGPoint, endColor: UIColor) -> CAGradientLayer {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.colors = [UIColor.clear.cgColor, endColor.cgColor]
gradientLayer.startPoint = start
gradientLayer.endPoint = end
return gradientLayer
}
// MARK: - Gesture
@objc func colorDragged(_ recognizer: PDPanGestureRecognizer) {
let pos = recognizer.location(in: self)
let comps = colorComponents(at: pos)
let sliderCenter = constrainPosition(pos, toBounds: bounds)
delegate?.colorChanged(to: comps)
sliderCircle.backgroundColor = comps.uiColor
switch recognizer.state {
case .began:
animateCircleSlider(.grow)
case .changed:
sliderCircleX.constant = sliderCenter.x
sliderCircleY.constant = sliderCenter.y - visibilityOffset
case .ended:
sliderCircle.backgroundColor = UIColor.white.withAlphaComponent(0.6)
animateCircleSlider(.shrink)
default:
break
}
}
@objc func colorTapped(_ recognizer: PDTapGestureRecognizer) {
let pos = recognizer.location(in: self)
let comps = colorComponents(at: pos)
let sliderCenter = constrainPosition(pos, toBounds: bounds)
delegate?.colorChanged(to: comps)
sliderCircle.backgroundColor = comps.uiColor
animateCircleSlider(.grow)
sliderCircleX.constant = sliderCenter.x
sliderCircleY.constant = sliderCenter.y - visibilityOffset
sliderCircle.backgroundColor = UIColor.white.withAlphaComponent(0.6)
animateCircleSlider(.shrink)
}
// MARK: - Slider Management
enum FadeMode { case `in`, out }
func fadeSlider(_ mode: FadeMode) {
UIView.animate(withDuration: 0.25) {
self.sliderCircle.alpha = (mode == .in) ? 1 : 0
}
}
func setSliderCircle() {
guard let currentColor = currentColor else { return }
sliderCircleX.constant = (1 - currentColor.s) * bounds.width
sliderCircleY.constant = (1 - currentColor.b) * bounds.height
sliderCircle.setNeedsLayout()
}
func constrainPosition(_ pos: CGPoint, toBounds rect: CGRect) -> CGPoint {
let x = min(max(pos.x, 0), rect.width)
let y = min(max(pos.y, 0), rect.height)
return CGPoint(x: x, y: y)
}
enum CircleSliderAnimationType: Int {
case grow = -1, shrink = 1
}
func animateCircleSlider(_ type: CircleSliderAnimationType) {
let sliderOffsetDirection: CGFloat = CGFloat(type.rawValue)
// if sliderOffsetDirection = 1, scale = circleGrowthScale, otherwise scale = circleGrowthScale ^ -1
let scale = pow(circleGrowthScale, -sliderOffsetDirection)
let transform = sliderCircle.transform.scaledBy(x: scale, y: scale)
sliderCircleY.constant += visibilityOffset * sliderOffsetDirection
UIView.animate(withDuration: 0.25, animations: {
self.sliderCircle.transform = transform
self.layoutIfNeeded()
})
}
func colorComponents(at point: CGPoint) -> PDColor {
let s = min(max(bounds.width - point.x, 0) / bounds.width, 1)
let b = min(max(bounds.height - point.y, 0) / bounds.height, 1)
return PDColor(h: dataSource?.selectedHueForColorPicker() ?? 1, s: s, b: b, a: 1)
}
}
| mit | 684b0eb7603138bc9a57d81b1ad3893d | 28.261803 | 169 | 0.688032 | 4.331639 | false | false | false | false |
apple/swift-syntax | CodeGeneration/Sources/Utils/SyntaxBuildableChild.swift | 1 | 2974 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftSyntax
import SwiftSyntaxBuilder
import SyntaxSupport
/// Extension to the `Child` type to provide functionality specific to
/// SwiftSyntaxBuilder.
public extension Child {
/// The type of this child, represented by a `SyntaxBuildableType`, which can
/// be used to create the corresponding `Buildable` and `ExpressibleAs` types.
var type: SyntaxBuildableType {
SyntaxBuildableType(
syntaxKind: syntaxKind,
isOptional: isOptional
)
}
var parameterBaseType: String {
if !self.nodeChoices.isEmpty {
return self.name
} else {
return type.parameterBaseType
}
}
var parameterType: Type {
return self.type.optionalWrapped(type: Type(parameterBaseType))
}
/// If the child node has documentation associated with it, return it as single
/// line string. Otherwise return an empty string.
var documentation: String {
flattened(indentedDocumentation: description ?? "")
}
/// If this node is a token that can't contain arbitrary text, generate a Swift
/// `assert` statement that verifies the variable with name var_name and of type
/// `TokenSyntax` contains one of the supported text options. Otherwise return `nil`.
func generateAssertStmtTextChoices(varName: String) -> FunctionCallExpr? {
guard type.isToken else {
return nil
}
let choices: [String]
if !textChoices.isEmpty {
choices = textChoices
} else if tokenCanContainArbitraryText {
// Don't generate an assert statement if token can contain arbitrary text.
return nil
} else if !tokenChoices.isEmpty {
choices = tokenChoices.compactMap(\.text)
} else {
return nil
}
var assertChoices: [Expr] = []
if type.isOptional {
assertChoices.append(Expr(SequenceExpr {
IdentifierExpr(identifier: .identifier(varName))
BinaryOperatorExpr(text: "==")
NilLiteralExpr()
}))
}
for textChoice in choices {
assertChoices.append(Expr(SequenceExpr {
MemberAccessExpr(base: type.forceUnwrappedIfNeeded(expr: Expr(varName)), name: "text")
BinaryOperatorExpr(text: "==")
StringLiteralExpr(content: textChoice)
}))
}
let disjunction = ExprList(assertChoices.flatMap { [$0, Expr(BinaryOperatorExpr(text: "||"))] }.dropLast())
return FunctionCallExpr(callee: "assert") {
TupleExprElement(expression: SequenceExpr(elements: disjunction))
}
}
}
| apache-2.0 | ed5abbdc3e2ca7617204e7dd41591d8a | 33.183908 | 111 | 0.658373 | 4.705696 | false | false | false | false |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Access/AccessDataSource.swift | 1 | 5139 | //
// AccessDataSource.swift
// ZeeQL
//
// Created by Helge Hess on 24/02/17.
// Copyright © 2017-2020 ZeeZide GmbH. All rights reserved.
//
/**
* This class has a set of operations targetted at SQL based applications. It
* has three major subclasses with specific characteristics:
*
* - `DatabaseDataSource`
* - `ActiveDataSource`
* - `AdaptorDataSource`
*
* All of those datasources are very similiar in the operations they provide,
* but they differ in the feature set and overhead.
*
* `DatabaseDataSource` works on top of an `EditingContext`. It has the biggest
* overhead but provides features like object uniquing/registry. Eg if you need
* to fetch a bunch of objects and then perform subsequent processing on them
* (for example permission checks), it is convenient because the context
* remembers the fetched objects. This datasource returns DatabaseObject's as
* specified in the associated Model.
*
* `ActiveDataSource` is similiar to `DatabaseDataSource`, but it directly works
* on a channel. It has a reasonably small overhead and still provides a good
* feature set, like object mapping or prefetching.
*
* Finally `AdaptorDataSource`. This datasource does not perform object mapping,
* that is, it returns `AdaptorRecord` objects and works directly on top of an
* `AdaptorChannel`.
*/
open class AccessDataSource<Object: SwiftObject> : DataSource<Object> {
open var log : ZeeQLLogger = globalZeeQLLogger
var _fsname : String?
override open var fetchSpecification : FetchSpecification? {
set {
super.fetchSpecification = newValue
_fsname = nil
}
get {
if let fs = super.fetchSpecification { return fs }
if let name = _fsname, let entity = entity {
return entity[fetchSpecification: name]
}
return nil
}
}
open var fetchSpecificationName : String? {
set {
_fsname = newValue
if let name = _fsname, let entity = entity {
super.fetchSpecification = entity[fetchSpecification: name]
}
else {
super.fetchSpecification = nil
}
}
get { return _fsname }
}
var _entityName : String? = nil
open var entityName : String? {
set { _entityName = newValue }
get {
if let entityName = _entityName { return entityName }
if let entity = entity { return entity.name }
if let fs = fetchSpecification, let ename = fs.entityName { return ename }
return nil
}
}
open var auxiliaryQualifier : Qualifier?
open var isFetchEnabled = true
open var qualifierBindings : Any? = nil
// MARK: - Abstract Base Class
open var entity : Entity? {
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchObjects(_ fs: FetchSpecification,
yield: ( Object ) throws -> Void) throws
{
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchCount(_ fs: FetchSpecification) throws -> Int {
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchGlobalIDs(_ fs: FetchSpecification,
yield: ( GlobalID ) throws -> Void) throws {
fatalError("implement in subclass: \(#function)")
}
override open func fetchObjects(cb yield: ( Object ) -> Void) throws {
try _primaryFetchObjects(try fetchSpecificationForFetch(), yield: yield)
}
override open func fetchCount() throws -> Int {
return try _primaryFetchCount(try fetchSpecificationForFetch())
}
open func fetchGlobalIDs(yield: ( GlobalID ) throws -> Void) throws {
try _primaryFetchGlobalIDs(try fetchSpecificationForFetch(), yield: yield)
}
// MARK: - Bindings
var qualifierBindingKeys : [ String ] {
let q = fetchSpecification?.qualifier
let aux = auxiliaryQualifier
guard q != nil || aux != nil else { return [] }
var keys = Set<String>()
q?.addBindingKeys(to: &keys)
aux?.addBindingKeys(to: &keys)
return Array(keys)
}
// MARK: - Fetch Specification
func fetchSpecificationForFetch() throws -> FetchSpecification {
/* copy fetchspec */
var fs : FetchSpecification
if let ofs = fetchSpecification {
fs = ofs // a copy, it is a struct
}
else if let e = entity {
fs = ModelFetchSpecification(entity: e)
}
else if let entityName = entityName {
fs = ModelFetchSpecification(entityName: entityName)
}
else {
throw AccessDataSourceError
.CannotConstructFetchSpecification(.missingEntity)
}
let qb = qualifierBindings
let aux = auxiliaryQualifier
if qb == nil && aux == nil { return fs }
/* merge in aux qualifier */
if let aux = aux {
let combined = and(aux, fs.qualifier)
fs.qualifier = combined
}
/* apply bindings */
if let qb = qb {
guard let fs = try fs.fetchSpecificiationWith(bindings: qb) else {
throw AccessDataSourceError
.CannotConstructFetchSpecification(.bindingFailed)
}
return fs
}
else { return fs }
}
}
| apache-2.0 | fc58b09f0ed3c1dd90d169f86d3f92cf | 29.766467 | 80 | 0.655313 | 4.372766 | false | false | false | false |
ChadChang/CCTvOS | CCTvOS/MyJSClass.swift | 1 | 834 | //
// MyJSClass.swift
// CCTvOS
//
// Created by Chad on 10/13/15.
// Copyright © 2015 Chad. All rights reserved.
//
import UIKit
import TVMLKit
import CCMockData
@objc protocol MyJSClass : JSExport {
func getEdtiorListStr() -> String
func setItem(key:String, data:String)
}
class MyClass: NSObject, MyJSClass {
func getEdtiorListStr() -> String {
let motionKit = CCMockFrameworks.init()
let editorList = motionKit.getEditorPickList()
var str:String = ""
for product:Product in editorList
{
str += "<lockup videoURL=''><img src='"+product.imageUrl+"' width='500' height='350' /><title></title> <description>"+product.title+"</description></lockup>"
}
return str
}
func setItem(key: String, data: String) {
print("Set key:\(key) value:\(data)")
}
} | mit | c27d0a47bc7f6d4051d8421496928b7d | 20.947368 | 163 | 0.641056 | 3.470833 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Notifications/Views/NoteBlockTextTableViewCell.swift | 2 | 4137 | import Foundation
import WordPressShared
// MARK: - NoteBlockTextTableViewCell
//
class NoteBlockTextTableViewCell: NoteBlockTableViewCell, RichTextViewDataSource, RichTextViewDelegate {
// MARK: - IBOutlets
@IBOutlet private weak var textView: RichTextView!
@IBOutlet private var horizontalEdgeConstraints: [NSLayoutConstraint]!
/// onUrlClick: Called whenever a URL is pressed within the textView's Area.
///
@objc var onUrlClick: ((URL) -> Void)?
/// onAttachmentClick: Called whenever a NSTextAttachment receives a press event
///
@objc var onAttachmentClick: ((NSTextAttachment) -> Void)?
/// Attributed Text!
///
@objc var attributedText: NSAttributedString? {
set {
textView.attributedText = newValue
invalidateIntrinsicContentSize()
}
get {
return textView.attributedText
}
}
/// Indicates if this is a Badge Block
///
override var isBadge: Bool {
didSet {
backgroundColor = WPStyleGuide.Notifications.blockBackgroundColorForRichText(isBadge)
}
}
/// Indicates if this should be styled as a larger title
///
var isTitle: Bool = false {
didSet {
guard FeatureFlag.milestoneNotifications.enabled else {
return
}
let spacing: CGFloat = isTitle ? Metrics.titleHorizontalSpacing : Metrics.standardHorizontalSpacing
// Conditional chaining here means this won't crash for any subclasses
// that don't have edge constraints (such as comment cells)
horizontalEdgeConstraints?.forEach({ $0.constant = spacing })
}
}
/// TextView's NSLink Color
///
@objc var linkColor: UIColor? {
didSet {
if let unwrappedLinkColor = linkColor {
textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: unwrappedLinkColor]
}
}
}
/// TextView's Data Detectors
///
@objc var dataDetectors: UIDataDetectorTypes {
set {
textView.dataDetectorTypes = newValue
}
get {
return textView.dataDetectorTypes
}
}
/// Wraps Up TextView.selectable Property
///
@objc var isTextViewSelectable: Bool {
set {
textView.selectable = newValue
}
get {
return textView.selectable
}
}
/// Wraps Up TextView.isUserInteractionEnabled Property
///
@objc var isTextViewClickable: Bool {
set {
textView.isUserInteractionEnabled = newValue
}
get {
return textView.isUserInteractionEnabled
}
}
// MARK: - View Methods
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = WPStyleGuide.Notifications.blockBackgroundColor
selectionStyle = .none
textView.contentInset = .zero
textView.textContainerInset = .zero
textView.backgroundColor = .clear
textView.editable = false
textView.selectable = true
textView.dataDetectorTypes = UIDataDetectorTypes()
textView.dataSource = self
textView.delegate = self
textView.translatesAutoresizingMaskIntoConstraints = false
}
override func prepareForReuse() {
super.prepareForReuse()
isTitle = false
}
// MARK: - RichTextView Data Source
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
onUrlClick?(URL)
return false
}
func textView(_ textView: UITextView, didPressLink link: URL) {
onUrlClick?(link)
}
func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {
onAttachmentClick?(textAttachment)
return false
}
private enum Metrics {
static let standardHorizontalSpacing: CGFloat = 20
static let titleHorizontalSpacing: CGFloat = 40
}
}
| gpl-2.0 | 2ee13c38995505f2057c5e9a43702448 | 27.335616 | 144 | 0.632342 | 5.674897 | false | false | false | false |
TonyStark106/SwiftFlatBuffers | Example/Example/ViewController.swift | 1 | 1171 | //
// ViewController.swift
// Example
//
// Created by TonyStark106 on 2017/5/21.
// Copyright © 2017年 TonyStark106. All rights reserved.
//
import UIKit
import MyFlatBuffers
class ViewController: UIViewController {
var ses: URLSession?
override func viewDidLoad() {
super.viewDidLoad()
let m = Monster()
m.name = "Tony"
m.hp = 255
m.testarrayofstring = ["Spitfire", "coding"]
let data = m.toFBData()
// Deserialize
if let n = Monster(root: data) {
print("Monster name: \(n.name!)")
print("Monster hp: \(n.hp)")
print("Monster skills: \(n.testarrayofstring!)")
return
}
print("fail to serialize or deserialize")
// let url = URL(string: "http://127.0.0.1:44444")!
// ses = URLSession(configuration: URLSessionConfiguration.default)
// let task = ses?.dataTask(with: url) { (data, res, err) in
// if let d = data {
// let m = Monster(root: d)
// print(m!.name!)
// }
// }
// task?.resume()
}
}
| apache-2.0 | b502ee2304f80b71c5ca9788c3042ed4 | 23.333333 | 74 | 0.519692 | 3.880399 | false | false | false | false |
zhugejunwei/LeetCode | 33. Search in Rotated Sorted Array.swift | 1 | 1101 | import Darwin
// Linear search just as a contrast, 24 ms
//func search(nums: [Int], _ target: Int) -> Int {
// for num in nums {
// if target == num {
// return nums.indexOf(num)!
// }
// }
// return -1
//}
// Binary Search, 24 ms
func search(nums: [Int], _ target: Int) -> Int {
var left = 0, right = nums.count-1
while left <= right {
let mid = (left + right)/2
if nums[mid] == target {
return mid
}
if nums[left] <= nums[mid] {
if target >= nums[left] && target <= nums[mid] {
right = mid
}else {
left = mid + 1
}
}else if nums[mid] < nums[right] {
if target > nums[mid] && target <= nums[right] {
left = mid + 1
}else {
right = mid
}
}else if nums[left] == nums[right] {
if target == nums[mid] {
return mid
}else {
return -1
}
}
}
return -1
}
var a = [3,1]
search(a, 1) | mit | 58dda62c4e35d6aca4b31852ee0e7237 | 21.958333 | 60 | 0.41871 | 3.707071 | false | false | false | false |
xiabob/ZhiHuDaily | ZhiHuDaily/ZhiHuDaily/Views/Menu/MenuFullCell.swift | 1 | 1598 | //
// MenuFullCell.swift
// ZhiHuDaily
//
// Created by xiabob on 17/4/10.
// Copyright © 2017年 xiabob. All rights reserved.
//
import UIKit
class MenuFullCell: MenuCell {
override func configViews() {
super.configViews()
addSubview(iconView)
addSubview(titleLabel)
addSubview(flagView)
setLayout()
}
fileprivate func setLayout() {
iconView.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.centerY.equalTo(self)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(iconView.snp.right).offset(20)
make.centerY.equalTo(iconView)
}
flagView.snp.makeConstraints { (make) in
make.right.equalTo(0)
make.centerY.equalTo(iconView)
make.width.equalTo(80)
}
}
func refreshViews(with iconImage: UIImage, model: ThemeModel) {
themeModel = model
iconView.image = iconImage
titleLabel.text = model.name
if model.isSubscribed {
flagView.setImage(#imageLiteral(resourceName: "Menu_Enter"), for: .normal)
} else {
flagView.setImage(#imageLiteral(resourceName: "Dark_Menu_Follow"), for: .normal)
}
if model.isSelected {
backgroundColor = kMenuSelectedColor
titleLabel.textColor = UIColor.white
} else {
backgroundColor = kMenuBackgroundColor
titleLabel.textColor = kMenuGrayWhiteTextColor
}
}
}
| mit | 2d9da15acf1dc90fd26cc8989a7db1ef | 26.033898 | 92 | 0.583072 | 4.636628 | false | false | false | false |
JohnUni/SensorTester | network/FantasticRawNetworkHandler.swift | 1 | 8717 | /*
* FantasticRawNetworkHandler.swift
* SensorTester
*
* Created by John Wong on 8/09/2015.
* Copyright (c) 2015-2015, John Wong <john dot innovation dot au at gmail dot com>
*
* All rights reserved.
*
* http://www.bitranslator.com
*
* 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.
*
* 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.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
public class FantasticRawNetworkHandler : BaseNetworkDataHandler
{
public override init( messageHandler: IMessageHandler )
{
super.init(messageHandler: messageHandler)
}
override func processParseBuffer() -> Bool
{
var bRet: Bool = true
if( m_byteDataBuffer != nil )
{
let nDataInBufferLength: Int32 = Int32(m_byteDataBuffer!.length)
//var nProcessingOffset: Int32 = 0
// 68 58 68 59 10 D:D;
// 68 58 83 59 10 D:S;
// 68 58 82 59 10
// 68 58 82 59 10 68 58 82 59 10
var buffer:Array<UInt8> = Array<UInt8>(count:Int(nDataInBufferLength), repeatedValue:0x0)
m_byteDataBuffer!.getBytes( &buffer, length: Int(nDataInBufferLength))
// for( var i: Int32 = 0; i<nDataInBufferLength; ++i )
// {
// let ch: UInt8 = buffer[Int(i)]
// print( "\(ch) " )
// }
// print( "\n" )
//nProcessingOffset = nDataInBufferLength - 1
//for( var i: Int32 = nDataInBufferLength - 1; i>=0; i-- )
//{
// let ch: UInt8 = buffer[Int(i)]
// if( 0x0A == ch )
// {
// nProcessingOffset = i
// break
// }
//}
let strData: NSString? = NSString(data: m_byteDataBuffer!, encoding:NSUTF8StringEncoding )
if( strData != nil )
{
let strValue: String = strData as! String
let strSplit: String = "\n"
let arrayStringData: Array<String> = strValue.componentsSeparatedByString( strSplit )
let nCount: Int32 = Int32(arrayStringData.count)
for( var i: Int32=0; i<nCount; i += 1 )
{
let str: String = arrayStringData[Int(i)]
let nStrLen: Int = str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
// print( "\(i):\(str), len:\(str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))\n" )
if( nStrLen > 0 )
{
//0:D:S;, len:4
let charArray: Array<Character> = Array<Character>(str.characters)
if( ("D" == charArray[0]) && (":" == charArray[1]) )
{
processCommand( str )
}
else if( ("C" == charArray[0]) && (":" == charArray[1]) )
{
processColor( str )
}
else if( ("S" == charArray[0]) && (":" == charArray[1]) )
{
processSensor( str )
}
else if( ("N" == charArray[0]) && (":" == charArray[1]) )
{
processNotification( str )
}
else
{
print( "unknown command:\(charArray[0]),\(charArray[1]) \n", terminator: "" )
}
}
else
{
// Okay
}
}
}
else
{
print("unknown message format, remove all buffer!\n", terminator: "")
m_byteDataBuffer = nil
bRet = false
}
if( m_byteDataBuffer != nil )
{
m_byteDataBuffer = nil
bRet = true
}
}
return bRet
}
private func processCommand( strLine: String ) -> Bool
{
var bRet: Bool = false
// U D L R S E
// up, down, left, right, stop, exit
let charArray: Array<Character> = Array<Character>(strLine.characters)
//let messageType: enumRemoteCommand = .MESSAGE_TYPE_REMOTE_COMMAND
var subType: enumRemoteSubCommand = .MESSAGE_SUBTYPE_UNKNOWN
var bErrorOccur: Bool = false
let chDirection: Character = charArray[2]
switch( chDirection )
{
case "U":
subType = .MESSAGE_SUBTYPE_REMOTE_COMMAND_FORWARD
break
case "D":
subType = .MESSAGE_SUBTYPE_REMOTE_COMMAND_BACKWARD
break
case "L":
subType = .MESSAGE_SUBTYPE_REMOTE_COMMAND_TURN_LEFT
break
case "R":
subType = .MESSAGE_SUBTYPE_REMOTE_COMMAND_TURN_RIGHT
break
case "S":
subType = .MESSAGE_SUBTYPE_REMOTE_COMMAND_STOP
break
case "E":
subType = .MESSAGE_SUBTYPE_REMOTE_COMMAND_RESET
break
default:
print( "unknown direction in command:\(charArray[0]),\(charArray[1]),\(charArray[2]) \n", terminator: "" )
bErrorOccur = true
break
}
if( bErrorOccur )
{
print("fantastic process error, remove !\n", terminator: "")
// m_byteDataBuffer = nil
bRet = false
}
else
{
let objMessage: IDataMessage = RemoteCommandMessage(subType: subType, isAck: false)
// var objAckMessage: IDataMessage? =
let bHandle: Bool = handleMessage( objMessage )
if( !bHandle )
{
print("fantastic remote handle fail!\n", terminator: "")
}
}
return bRet
}
private func processColor( strLine: String ) -> Bool
{
let bRet: Bool = false
print( "color:\(strLine) \n", terminator: "" )
return bRet
}
private func processSensor( strLine: String ) -> Bool
{
let bRet: Bool = false
print( "sensor:\(strLine) \n", terminator: "" )
return bRet
}
private func processNotification( strLine: String ) -> Bool
{
let bRet: Bool = false
print( "notification:\(strLine) \n", terminator: "" )
return bRet
}
}
| apache-2.0 | 7152795cdd7bd0015112eb42ad04792d | 35.62605 | 118 | 0.531949 | 4.711892 | false | false | false | false |
urbanthings/urbanthings-sdk-apple | UrbanThingsAPI/Internal/Response/UTTransitStopScheduledCallSummary.swift | 1 | 1362 | //
// UTTransitStopScheduledCallSummary.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 29/04/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import Foundation
import CoreLocation
class UTTransitStopScheduledCallSummary : UTObject, TransitStopScheduledCallSummary {
let transitStopPrimaryCode:String
let transitStopName:String?
let transitStopLocalityName:String?
let scheduledCall:TransitScheduledCall
let transitStopLocation:Location?
override init(json:[String:Any]) throws {
self.transitStopPrimaryCode = try parse(required:json, key: .TransitStopPrimaryCode, type: UTTransitStopScheduledCallSummary.self)
self.transitStopName = try parse(optional:json, key: .TransitStopName, type: UTTransitStopScheduledCallSummary.self)
self.transitStopLocalityName = try parse(optional:json, key: .TransitStopLocalityName, type: UTTransitStopScheduledCallSummary.self)
self.transitStopLocation = try parse(optional: json, type: UTTransitRouteInfo.self, property: "transitStopLocation") { try UTLocation(optional:$0, latitude: .TransitStopLatitude, longitude: .TransitStopLongitude) }
self.scheduledCall = try parse(required:json, key: .ScheduledCall, type: UTTransitStopScheduledCallSummary.self) as UTTransitScheduledCall
try super.init(json:json)
}
}
| apache-2.0 | ff05313f9de18b6c0ad1adcb883ae5f3 | 47.607143 | 222 | 0.775165 | 4.418831 | false | false | false | false |
warren-gavin/OBehave | OBehave/Classes/Animations/RotateView/OBRotateBehavior.swift | 1 | 1878 | //
// OBRotateBehavior.swift
// OBehave
//
// Created by Warren Gavin on 30/10/15.
// Copyright © 2015 Apokrupto. All rights reserved.
//
import UIKit
public final class OBRotateBehavior: OBAnimatingViewBehavior {
@IBInspectable public var angle: CGFloat = .rotationAngle
// MARK: OBAnimatingViewBehaviorDelegate
override public func executeAnimation(_ behavior: OBAnimatingViewBehavior) {
guard let animatingViews = animatingViews else {
return
}
for view in animatingViews {
animateRotation(view)
}
}
}
private extension OBRotateBehavior {
func angleInRadians(_ reverse: Bool = false) -> CGFloat {
let pi = (reverse ? CGFloat(Double.pi) : CGFloat(-Double.pi))
return angle * pi / CGFloat(180.0)
}
func animateRotation(_ view: UIView) {
if fadeIn {
view.alpha = 0.0
}
let applyRotation = { [unowned self] in
view.alpha = 1.0
view.transform = view.transform.rotated(by: self.angleInRadians())
}
let undoRotation = { [unowned self] (finished: Bool) -> Void in
if finished && self.autoReverse {
view.transform = view.transform.rotated(by: self.angleInRadians(true))
}
}
let options = (autoReverse ? UIView.AnimationOptions.autoreverse : UIView.AnimationOptions())
UIView.animate(withDuration: duration,
delay: delay,
usingSpringWithDamping: damping,
initialSpringVelocity: velocity,
options: options,
animations: applyRotation,
completion: undoRotation)
}
}
private extension CGFloat {
static let rotationAngle: CGFloat = 90.0
}
| mit | 59725006569f805ad13e0430d0d0c246 | 29.274194 | 101 | 0.582312 | 4.850129 | false | false | false | false |
jblorenzo/BSImagePicker | Example/Pods/BSGridCollectionViewLayout/Pod/Classes/GridCollectionViewLayout.swift | 1 | 9854 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
/**
Provides a grid collection view layout
*/
@objc(BSGridCollectionViewLayout)
public final class GridCollectionViewLayout: UICollectionViewLayout {
/**
Spacing between items (horizontal and vertical)
*/
public var itemSpacing: CGFloat = 0 {
didSet {
itemSize = estimatedItemSize()
}
}
/**
Number of items per row
*/
public var itemsPerRow = 3 {
didSet {
itemSize = estimatedItemSize()
}
}
/**
Item height ratio relative to it's width
*/
public var itemHeightRatio: CGFloat = 1 {
didSet {
itemSize = estimatedItemSize()
}
}
/**
Size for each item
*/
public private(set) var itemSize = CGSize.zero
var items = 0
var rows = 0
public override func prepareLayout() {
// Set total number of items and rows
items = estimatedNumberOfItems()
rows = items / itemsPerRow + ((items % itemsPerRow > 0) ? 1 : 0)
// Set item size
itemSize = estimatedItemSize()
}
/**
See UICollectionViewLayout documentation
*/
public override func collectionViewContentSize() -> CGSize {
guard let collectionView = collectionView where rows > 0 else {
return CGSize.zero
}
let height = estimatedRowHeight() * CGFloat(rows)
return CGSize(width: collectionView.bounds.width, height: height)
}
/**
See UICollectionViewLayout documentation
*/
public override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return indexPathsInRect(rect).map { (indexPath) -> UICollectionViewLayoutAttributes? in
return self.layoutAttributesForItemAtIndexPath(indexPath)
}.flatMap { $0 }
}
/**
See UICollectionViewLayout documentation
*/
public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
// Guard against negative row/sections.
guard indexPath.row >= 0 && indexPath.section >= 0 else {
return nil
}
let itemIndex = flatIndex(indexPath) // index among total number of items
let rowIndex = itemIndex % itemsPerRow // index within it's row
let row = itemIndex / itemsPerRow // which row for that item
let x = (CGFloat(rowIndex) * itemSpacing) + (CGFloat(rowIndex) * itemSize.width)
let y = (CGFloat(row) * itemSpacing) + (CGFloat(row) * itemSize.height)
let width = itemSize.width
let height = itemSize.height
let attribute = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attribute.frame = CGRect(x: x, y: y, width: width, height: height)
return attribute
}
/**
See UICollectionViewLayout documentation
*/
public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
// No decoration or supplementary views
/**
See UICollectionViewLayout documentation
*/
public override func layoutAttributesForDecorationViewOfKind(kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return nil
}
/**
See UICollectionViewLayout documentation
*/
public override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return nil
}
}
extension GridCollectionViewLayout {
/**
Calculates which index paths are within a given rect
- parameter rect: The rect which we want index paths for
- returns: An array of indexPaths for that rect
*/
func indexPathsInRect(rect: CGRect) -> [NSIndexPath] {
// Make sure we have items/rows
guard items > 0 && rows > 0 else { return [] }
let rowHeight = estimatedRowHeight()
let startRow = GridCollectionViewLayout.firstRowInRect(rect, withRowHeight: rowHeight)
let endRow = GridCollectionViewLayout.lastRowInRect(rect, withRowHeight: rowHeight, max: rows)
guard startRow <= endRow else { return [] }
let startIndex = GridCollectionViewLayout.firstIndexInRow(min(startRow, endRow), withItemsPerRow: itemsPerRow)
let endIndex = GridCollectionViewLayout.lastIndexInRow(max(startRow, endRow), withItemsPerRow: itemsPerRow, numberOfItems: items)
guard startIndex <= endIndex else { return [] }
let indexPaths = (startIndex...endIndex).map { indexPathFromFlatIndex($0) }
return indexPaths
}
/**
Calculates which row index would be first for a given rect.
- parameter rect: The rect to check
- parameter rowHeight: Height for a row
- returns: First row index
*/
static func firstRowInRect(rect: CGRect, withRowHeight rowHeight: CGFloat) -> Int {
if rect.origin.y / rowHeight < 0 {
return 0
} else {
return Int(rect.origin.y / rowHeight)
}
}
/**
Calculates which row index would be last for a given rect.
- parameter rect: The rect to check
- parameter rowHeight: Height for a row
- returns: Last row index
*/
static func lastRowInRect(rect: CGRect, withRowHeight rowHeight: CGFloat, max: Int) -> Int {
guard rect.size.height >= rowHeight else { return 0 }
if (rect.origin.y + rect.height) / rowHeight > CGFloat(max) {
return max - 1
} else {
return Int(ceil((rect.origin.y + rect.height) / rowHeight)) - 1
}
}
/**
Calculates which index would be the first for a given row.
- parameter row: Row index
- parameter itemsPerRow: How many items there can be in a row
- returns: First index
*/
static func firstIndexInRow(row: Int, withItemsPerRow itemsPerRow: Int) -> Int {
return row * itemsPerRow
}
/**
Calculates which index would be the last for a given row.
- parameter row: Row index
- parameter itemsPerRow: How many items there can be in a row
- parameter numberOfItems: The total number of items.
- returns: Last index
*/
static func lastIndexInRow(row: Int, withItemsPerRow itemsPerRow: Int, numberOfItems: Int) -> Int {
let maxIndex = (row + 1) * itemsPerRow - 1
let bounds = numberOfItems - 1
if maxIndex > bounds {
return bounds
} else {
return maxIndex
}
}
/**
Takes an index path (which are 2 dimensional) and turns it into a 1 dimensional index
- parameter indexPath: The index path we want to flatten
- returns: A flat index
*/
func flatIndex(indexPath: NSIndexPath) -> Int {
guard let collectionView = collectionView else {
return 0
}
return (0..<(indexPath as NSIndexPath).section).reduce((indexPath as NSIndexPath).row) { $0 + collectionView.numberOfItemsInSection($1)}
}
/**
Converts a flat index into an index path
- parameter index: The flat index
- returns: An index path
*/
func indexPathFromFlatIndex(index: Int) -> NSIndexPath {
guard let collectionView = collectionView else {
return NSIndexPath(forItem: 0, inSection: 0)
}
var item = index
var section = 0
while(item >= collectionView.numberOfItemsInSection(section)) {
item -= collectionView.numberOfItemsInSection(section)
section += 1
}
return NSIndexPath(forItem: item, inSection: section)
}
/**
Estimated the size of the items
- returns: Estimated item size
*/
func estimatedItemSize() -> CGSize {
guard let collectionView = collectionView else {
return CGSize.zero
}
let itemWidth = (collectionView.bounds.width - CGFloat(itemsPerRow - 1) * itemSpacing) / CGFloat(itemsPerRow)
return CGSize(width: itemWidth, height: itemWidth * itemHeightRatio)
}
/**
Estimated total number of items
- returns: Total number of items
*/
func estimatedNumberOfItems() -> Int {
guard let collectionView = collectionView else {
return 0
}
return (0..<collectionView.numberOfSections()).reduce(0, combine: {$0 + collectionView.numberOfItemsInSection($1)})
}
/**
Height for each row
- returns: Row height
*/
func estimatedRowHeight() -> CGFloat {
return itemSize.height+itemSpacing
}
}
| mit | b58d153700f0445076d2d3d53765249f | 32.975862 | 153 | 0.646808 | 5.137122 | false | false | false | false |
kinyong/KYWeiboDemo-Swfit | AYWeibo/AYWeibo/classes/Main/VisitorView.swift | 2 | 1843 | //
// VisitorView.swift
// AYWeibo
//
// Created by Ayong on 16/6/4.
// Copyright © 2016年 Ayong. All rights reserved.
//
import UIKit
class VisitorView: UIView {
/// 登入按钮
@IBOutlet var loginButton: UIButton!
/// 注册按钮
@IBOutlet var registerButton: UIButton!
/// 转盘图片
@IBOutlet private var rotationImgView: UIImageView!
/// 文本标签
@IBOutlet private var titleLabel: UILabel!
/// 图标图片
@IBOutlet private var iconImgView: UIImageView!
// MARK: - 外部方法
class func visitorView() -> VisitorView {
let vistView = NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).first as! VisitorView
return vistView
}
// MARK: - 内部方法
/// 提供设置访客视图上的数据
func setupVisitorInfo(imageName: String?, title: String) {
// 1.设置标题
titleLabel.text = title
// 2.判断是否为首页
guard let name = imageName else { // 不设置图标,默认为首页
rotationImgView.hidden = false
// 执行转盘动画
startAnimation()
return
}
// 3.设置其他数据
iconImgView.image = UIImage(named: name)
rotationImgView.hidden = true
}
/// 转盘旋转动画
private func startAnimation() {
let animation = CABasicAnimation()
animation.keyPath = "transform.rotation"
animation.toValue = 2 * M_PI
animation.duration = 5.0
animation.repeatCount = MAXFLOAT
animation.removedOnCompletion = false // 切换视图控制器时候动画继续
rotationImgView.layer.addAnimation(animation, forKey: nil)
}
}
| apache-2.0 | 942439982a897c4b769a0c991f20e961 | 22.971014 | 120 | 0.579807 | 4.482385 | false | false | false | false |
wookay/Look | samples/LookSample/Pods/C4/C4/Core/C4Vector.swift | 3 | 10146 | // Copyright © 2014 C4
//
// 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 CoreGraphics
/// The C4Vector class is used for coordinate values and direction vectors.
public struct C4Vector : Equatable, CustomStringConvertible {
/// The x-value of the vector.
public var x: Double = 0
/// The y-value of the vector.
public var y: Double = 0
/// The z-value of the vector.
public var z: Double = 0
/// Creates a vector with default values {0,0,0,}
///
/// ````
/// let v = C4Vector()
/// ````
public init() {
}
/// Create a vector with a cartesian representation: an x and a y coordinates. The `z` variable is optional.
///
/// ````
/// let v = C4Vector(x: 1.0, y: 1.0, z: 1.0)
/// let v = C4Vector(x: 1.0, y: 1.0)
/// ````
public init(x: Double, y: Double, z: Double = 0) {
self.x = x
self.y = y
self.z = z
}
/// Create a vector with a cartesian representation: an x and a y coordinates.
///
/// ````
/// let v = C4Vector(x: 1, y: 1, z: 1)
/// ````
public init(x: Int, y: Int, z: Int = 0) {
self.x = Double(x)
self.y = Double(y)
self.z = Double(z)
}
/// Create a vector with a polar representation: a magnitude and an angle in radians. The `z` variable is optional.
/// [Polar coordinate system - Wikipedia](http://en.wikipedia.org/wiki/Polar_coordinate_system)
///
/// ````
/// let m = sqrt(2.0)
/// let h = M_PI_4
/// let v = C4Vector(magnitude: m, heading: h)
/// v //-> {1,1,0}
/// ````
public init(magnitude: Double, heading: Double, z: Double = 0) {
x = magnitude * cos(heading)
y = magnitude * sin(heading)
self.z = z
}
/// Initializes a C4Vector from a CGPoint
///
/// - parameter point: a previously initialized CGPoint
public init(_ point: CGPoint) {
x = Double(point.x)
y = Double(point.y)
z = 0
}
/// Initializes a C4Vector from a C4Point
///
/// - parameter point: a previously initialized C4Point
public init(_ point: C4Point) {
x = point.x
y = point.y
z = 0
}
/// The polar representation magnitude of the vector.
///
/// ````
/// let v = C4Vector(x: 2.0, y: 1.0, z: 0.0)
/// v.magnitude //-> √2
/// ````
public var magnitude: Double {
get {
return sqrt(x * x + y * y + z * z)
}
set {
x = newValue * cos(heading)
y = newValue * sin(heading)
}
}
/// The polar representation heading angle of the vector, in radians.
///
/// ````
/// let v = C4Vector(1,1,0)
/// v.heading //-> M_PI_4
/// ````
public var heading : Double {
get {
return atan2(y, x);
}
set {
x = magnitude * cos(newValue)
y = magnitude * sin(newValue)
}
}
/// The angle between two vectors, based on {0,0}
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1, z: 0)
/// let v2 = C4Vector(x: -1, y: 1, z: 0)
/// v1.angleTo(v2) //-> M_PI_2
/// ````
public func angleTo(vec: C4Vector) -> Double {
return acos(self ⋅ vec / (self.magnitude * vec.magnitude))
}
/// The angle between two vectors, based on a provided point
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1, z: 0)
/// let v2 = C4Vector(x: -1, y: 1, z: 0)
/// let b = C4Vector(x: 0, y: 1, z: 0)
/// v1.angleTo(v2, basedOn: b) //-> PI
/// ````
public func angleTo(vec: C4Vector, basedOn: C4Vector) -> Double {
var vecA = self
var vecB = vec
vecA -= basedOn
vecB -= basedOn
return acos(vecA ⋅ vecB / (vecA.magnitude * vecB.magnitude))
}
/// Return the dot product. **You should use the ⋅ operator instead.**
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1, z: 0)
/// let v2 = C4Vector(x: -1, y: 1, z: 0)
/// v1.dot(v2) //-> 0.0
/// ````
public func dot(vec: C4Vector) -> Double {
return x * vec.x + y * vec.y + z * vec.z
}
/// Return a vector with the same heading but a magnitude of 1.
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1, z: 0)
/// v1.unitVector() //-> {M_PI_4,M_PI_4,0}
/// ````
public func unitVector() -> C4Vector? {
let mag = self.magnitude
if mag == 0 {
return nil
}
return C4Vector(x: x / mag, y: y / mag, z: z / mag)
}
/// Return `true` if the vector is zero.
///
/// ````
/// let v = C4Vector()
/// v.isZero() //-> true
/// ````
public func isZero() -> Bool {
return x == 0 && y == 0 && z == 0
}
/// Transform the vector.
///
/// ````
/// var v = C4Vector(x: 1, y: 1, z:0)
/// let t = C4Transform.makeRotation(M_PI, axis: C4Vector(x: 0, y:0, z:1))
/// v.transform(t) //-> {-1, -1, 0}
/// ````
public mutating func transform(t: C4Transform) {
x = x * t[0, 0] + y * t[0, 1] + z * t[0, 2]
y = x * t[1, 0] + y * t[1, 1] + z * t[1, 2]
z = x * t[2, 0] + y * t[2, 1] + z * t[2, 2]
}
/// A string representation of the vector.
///
/// - returns: A string formatted to look like {x,y,z}
public var description : String {
get {
return "{\(x), \(y), \(z)}"
}
}
}
/// Returns true if the coordinates of both vectors are identical
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1)
/// let v2 = C4Vector(x: 1, y: 0)
/// v1 == v2 //-> false
/// ````
public func == (lhs: C4Vector, rhs: C4Vector) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
/// Transforms the left-hand vector by adding the values of the right-hand vector
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1)
/// let v2 = C4Vector(x: 1, y: 0)
/// v1 += v2 //-> v1 = {2,1,0}
/// ````
public func += (inout lhs: C4Vector, rhs: C4Vector) {
lhs.x += rhs.x
lhs.y += rhs.y
lhs.z += rhs.z
}
/// Transforms the left-hand vector by subtracting the values of the right-hand vector
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1)
/// let v2 = C4Vector(x: 1, y: 0)
/// v1 += v2 //-> v1 = {0,1,0}
/// ````
public func -= (inout lhs: C4Vector, rhs: C4Vector) {
lhs.x -= rhs.x
lhs.y -= rhs.y
lhs.z -= rhs.z
}
/// Transforms the left-hand vector by multiplying each by the values of the right-hand vector
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1)
/// v *= 2.0 //-> v1 = {2,2,0}
/// ````
public func *= (inout lhs: C4Vector, rhs: Double) {
lhs.x *= rhs
lhs.y *= rhs
lhs.z *= rhs
}
/// Transforms the left-hand vector by dividing each by the values of the right-hand vector
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1)
/// v /= 2.0 //-> v = {0.5,0.5,0.0}
/// ````
public func /= (inout lhs: C4Vector, rhs: Double) {
lhs.x /= rhs
lhs.y /= rhs
lhs.z /= rhs
}
/// Returns a new vector whose coordinates are the sum of both input vectors
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1)
/// let v2 = C4Vector(x: 1, y: 0)
/// v1+v2 //-> {2,1,0}
/// ````
public func + (lhs: C4Vector, rhs: C4Vector) -> C4Vector {
return C4Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z)
}
/// Returns a new vector whose coordinates are the subtraction of the right-hand vector from the left-hand vector
///
/// ````
/// var v1 = C4Vector(x: 1, y: 1)
/// var v2 = C4Vector(x: 1, y: 1)
/// v1-v2 //-> {0,0,0}
/// ````
public func - (lhs: C4Vector, rhs: C4Vector) -> C4Vector {
return C4Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y, z: lhs.z - rhs.z)
}
infix operator ⋅ { associativity left precedence 150 }
/// Returns a new vector that is the dot product of the both input vectors. **Use this instead of v.dot(v)**
///
/// ````
/// let v1 = C4Vector(x: 1, y: 1)
/// let v2 = C4Vector(x: -1, y: 1)
/// v1 ⋅ v2 //-> 0.0
/// ````
public func ⋅ (lhs: C4Vector, rhs: C4Vector) -> Double {
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z
}
/// Returns a new vector whose coordinates are the division of the left-hand vector coordinates by those of the right-hand vector
///
/// ````
/// var v1 = C4Vector(x: 1, y: 1)
/// var v2 = v1 / 2.0
/// v2 //-> {0.5,0.5,0}
/// ````
public func / (lhs: C4Vector, rhs: Double) -> C4Vector {
return C4Vector(x: lhs.x / rhs, y: lhs.y / rhs, z: lhs.z / rhs)
}
/// Returns a new vector whose coordinates are the multiplication of the left-hand vector coordinates by those of the right-hand
/// vector
///
/// ````
/// var v1 = C4Vector(x: 1, y: 1)
/// var v2 = v2 * 2.0
/// v2 //-> {2,2,0}
/// ````
public func * (lhs: C4Vector, rhs: Double) -> C4Vector {
return C4Vector(x: lhs.x * rhs, y: lhs.y * rhs, z: lhs.z * rhs)
}
/// Returns a new vector whose coordinates are the negative values of the receiver
///
/// ````
/// var v1 = C4Vector(x: 1, y: 1)
/// var v2 = -v1
/// v2 //-> {-1,-1}
/// ````
public prefix func - (vector: C4Vector) -> C4Vector {
return C4Vector(x: -vector.x, y: -vector.y, z: -vector.z)
} | mit | 0e393581cf80332b86296824f085a89d | 28.539359 | 129 | 0.538841 | 3.10101 | false | false | false | false |
ICTatRTI/pam | ema/ResearchContainerSegue.swift | 1 | 997 | //
// ResearchContainerSegue.swift
// ema
//
// Created by Adam Preston on 4/20/16.
// Copyright © 2016 RTI. All rights reserved.
//
import UIKit
class ResearchContainerSegue: UIStoryboardSegue {
override func perform() {
let controllerToReplace = source.childViewControllers.first
let destinationControllerView = destination.view
destinationControllerView?.translatesAutoresizingMaskIntoConstraints = true
destinationControllerView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
destinationControllerView?.frame = source.view.bounds
controllerToReplace?.willMove(toParentViewController: nil)
source.addChildViewController(destination)
source.view.addSubview(destinationControllerView!)
controllerToReplace?.view.removeFromSuperview()
destination.didMove(toParentViewController: source)
controllerToReplace?.removeFromParentViewController()
}
}
| mit | 70f2590200465fde2eb00c554c68c7ec | 31.129032 | 87 | 0.71988 | 5.893491 | false | false | false | false |
nathawes/swift | test/DebugInfo/inlinescopes.swift | 3 | 1415 | // RUN: %empty-directory(%t)
// RUN: echo "public var x = Int64()" \
// RUN: | %target-swift-frontend -module-name FooBar -emit-module -o %t -
// RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o %t.ll
// RUN: %FileCheck %s < %t.ll
// RUN: %FileCheck %s -check-prefix=TRANSPARENT-CHECK < %t.ll
// CHECK: define{{( dllexport)?}}{{( protected)?( signext)?}} i32 @main{{.*}}
// CHECK: call swiftcc i64 @"$s4main8noinlineys5Int64VADF"(i64 %{{.*}})
// CHECK-SAME: !dbg ![[CALL:.*]]
// CHECK-DAG: ![[TOPLEVEL:.*]] = !DIFile(filename: "{{.*}}inlinescopes.swift"
import FooBar
@inline(never)
func use(_ x: Int64) -> Int64 { return x }
@inline(never)
func noinline(_ x: Int64) -> Int64 { return use(x) }
@_transparent
func transparent(_ x: Int64) -> Int64 { return noinline(x) }
@inline(__always)
func inlined(_ x: Int64) -> Int64 {
// CHECK-DAG: ![[CALL]] = !DILocation(line: [[@LINE+2]], column: {{.*}}, scope: ![[SCOPE:.*]], inlinedAt: ![[INLINED:.*]])
// CHECK-DAG: ![[SCOPE:.*]] = distinct !DILexicalBlock(
let result = transparent(x)
// TRANSPARENT-CHECK-NOT: !DISubprogram(name: "transparent"
return result
}
// CHECK-DAG: !DIGlobalVariable(name: "y",{{.*}} file: ![[TOPLEVEL]],{{.*}} line: [[@LINE+1]]
public let y = inlined(x)
// Check if the inlined and removed function still has the correct linkage name.
// CHECK-DAG: !DISubprogram(name: "inlined", linkageName: "$s4main7inlinedys5Int64VADF"
| apache-2.0 | cc06dac25e6e71a96266abbd25d3b249 | 37.243243 | 122 | 0.633216 | 3.130531 | false | false | false | false |
X140Yu/Lemon | Lemon/Library/Router/Router.swift | 1 | 2855 | import UIKit
import SafariServices
private let apiPrefix = "https://api.github.com"
private let webPrefix = "https://github.com/"
class Router {
class func handleURL(_ url: String?, _ navigationController: UINavigationController?) -> Bool {
guard var u = url, let nav = navigationController else { return false }
if u.characters.last == "/" {
// remove the last charactor if it is '/'
u = String(u.dropLast())
}
if u.hasPrefix("\(apiPrefix)/repos/") {
guard let name = u.components(separatedBy: "/repos/").last else { return false }
let components = name.components(separatedBy: "/")
guard let owner = components.first, let _ = components.last else { return false }
let repoVC = R.storyboard.repoViewController.repoViewController()!
repoVC.name = name
repoVC.ownerLogin = owner
nav.pushViewController(repoVC, animated: true)
return true
}
if u.hasPrefix("\(apiPrefix)/users/") {
let profileVC = ProfileViewController.profileVC(login: u.components(separatedBy: "/").last!)
nav.pushViewController(profileVC, animated: true)
return true
}
return handleWebURL(u, nav)
}
private class func handleWebURL(_ u: String, _ nav: UINavigationController) -> Bool {
/// https://github.com/X140Yu/Switcher
if u.hasPrefix(webPrefix) && u.replacingOccurrences(of: webPrefix, with: "").components(separatedBy: "/").count == 2 {
let name = u.replacingOccurrences(of: webPrefix, with: "")
let components = name.components(separatedBy: "/")
guard let owner = components.first, let _ = components.last else { return false }
let repoVC = R.storyboard.repoViewController.repoViewController()!
repoVC.name = name
repoVC.ownerLogin = owner
nav.pushViewController(repoVC, animated: true)
return true
}
/// https://github.com/X140Yu
if u.hasPrefix(webPrefix) && !u.replacingOccurrences(of: webPrefix, with: "").contains("/") {
guard let login = u.components(separatedBy: "/").last else { return false }
if !login.contains("trending") &&
!login.contains("?") {
let profileVC = ProfileViewController.profileVC(login: login)
nav.pushViewController(profileVC, animated: true)
return true
}
}
if u.hasPrefix("file://") {
return false
}
if u.hasPrefix("mailto:") {
// TODO: handle email
return false
}
// all above can not handle
//guard let url = URL(string: u) else { return }
//let safari = SFSafariViewController(url: url)
//nav.present(safari, animated: true, completion: nil)
return false
}
@discardableResult
class func handleURL(_ URL: URL?, _ navigationController: UINavigationController?) -> Bool {
return handleURL(URL?.absoluteString, navigationController)
}
}
| gpl-3.0 | 9106d8363cb15db5016f82998471d09d | 34.6875 | 122 | 0.658144 | 4.299699 | false | false | false | false |
wfleming/SwiftLint | Source/SwiftLintFramework/Extensions/String+SwiftLint.swift | 1 | 2354 | //
// String+SwiftLint.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
extension String {
internal func hasTrailingWhitespace() -> Bool {
if isEmpty {
return false
}
if let character = utf16.suffix(1).first {
return NSCharacterSet.whitespaceCharacterSet().characterIsMember(character)
}
return false
}
internal func isUppercase() -> Bool {
return self == uppercaseString
}
internal func nameStrippingLeadingUnderscoreIfPrivate(dict: [String: SourceKitRepresentable]) ->
String {
let privateACL = "source.lang.swift.accessibility.private"
if dict["key.accessibility"] as? String == privateACL && characters.first == "_" {
return self[startIndex.successor()..<endIndex]
}
return self
}
internal subscript (range: Range<Int>) -> String {
let nsrange = NSRange(location: range.startIndex, length: range.endIndex - range.startIndex)
if let indexRange = nsrangeToIndexRange(nsrange) {
return substringWithRange(indexRange)
}
fatalError("invalid range")
}
internal func substring(from: Int, length: Int? = nil) -> String {
if let length = length {
return self[from..<from + length]
}
return substringFromIndex(startIndex.advancedBy(from, limit: endIndex))
}
internal func lastIndexOf(search: String) -> Int? {
if let range = rangeOfString(search, options: [.LiteralSearch, .BackwardsSearch]) {
return startIndex.distanceTo(range.startIndex)
}
return nil
}
internal func nsrangeToIndexRange(nsrange: NSRange) -> Range<Index>? {
let from16 = utf16.startIndex.advancedBy(nsrange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsrange.length, limit: utf16.endIndex)
if let from = Index(from16, within: self), to = Index(to16, within: self) {
return from..<to
}
return nil
}
public func absolutePathStandardized() -> String {
return (self.absolutePathRepresentation() as NSString).stringByStandardizingPath
}
}
| mit | f931400d757e56a93e4aa484708f898a | 31.694444 | 100 | 0.626168 | 4.82377 | false | false | false | false |
m-patton/patton_MAD | Project One/milestone three/buzzed — bac calculator/buzzed — bac calculator/SecondViewController.swift | 1 | 2711 | //
// SecondViewController.swift
// buzzed — bac calculator
//
// Created by Mae Patton on 10/8/16.
// Copyright © 2016 Mae Patton. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var bacLabel: UILabel!
@IBOutlet weak var soberLabel: UILabel!
@IBOutlet weak var limitLabel: UILabel!
var bacText:String! //this variable gets bac information from view controller
func updateInfo() {
var baccount = Float(bacText)
bacLabel.text = String(format:"%.3f", baccount!)
//CALCULATE HOURS UNTIL BAC = 0
var min:Float = 0.0
var minutes: Int = 0
var hourCount = 0
while baccount > 0 { //if the person has a bac over 0
baccount = baccount! - 0.015
hourCount += 1
}
if baccount < 0 { //calculate minutes
hourCount -= 1
baccount = baccount!/0.015
min = baccount!*60.0*(-1.0)
minutes = Int(min)
}
soberLabel.text = "\(hourCount) hrs and \(minutes) min"
//CALCULATE HOURS UNTIL BELOW 0.08
min = 0.0
minutes = 0
hourCount = 0
baccount = Float(bacText)
var newHour = 0
var seccount:Float = 0.0
while baccount > 0.08 { //if the person has a bac over 0.08
baccount = baccount! - 0.015
hourCount += 1
if baccount < 0.08 { //calculate minutes
newHour = hourCount - 1
seccount = 0.08 - baccount!
seccount = seccount / 0.015
min = seccount*60.0
minutes = Int(min)
}else{
minutes = 0
}
}//end while
limitLabel.text = "\(newHour) hrs and \(minutes) min"
}//end updateInfo
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
override func viewDidLoad() {
super.viewDidLoad()
//bacLabel.text = bacText
updateInfo() //run this function upon loading the view
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0b16399c4dc7c35f45a4cb42117d5996 | 29.426966 | 106 | 0.577548 | 4.278041 | false | false | false | false |
Motsai/neblina-motiondemo-swift | SitStand/iOS/SitStand/MasterViewController.swift | 2 | 8827 | //
// MasterViewController.swift
// SitStand
//
// Created by Hoan Hoang on 2015-11-18.
// Copyright © 2015 Hoan Hoang. All rights reserved.
//
import UIKit
import CoreBluetooth
/*
struct NebDevice {
let id : UInt64
let peripheral : CBPeripheral
}
*/
class MasterViewController: UITableViewController, CBCentralManagerDelegate {
var detailViewController: DetailViewController? = nil
var objects = [Neblina]()
var bleCentralManager : CBCentralManager!
//var NebPeripheral : CBPeripheral!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.navigationItem.leftBarButtonItem = self.editButtonItem()
bleCentralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MasterViewController.insertRefreshScan(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func insertRefreshScan(_ sender: AnyObject) {
bleCentralManager.stopScan()
objects.removeAll()
bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil)
// objects.insert(NSDate(), atIndex: 0)
//let indexPath = NSIndexPath(forRow: 0, inSection: 0)
//self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row]
bleCentralManager.connect(object.device, options: nil)
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
//controller.NebDevice.setPeripheral(object)
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
if (controller.nebdev != nil) {
bleCentralManager.cancelPeripheralConnection((controller.nebdev.device)!)
}
controller.nebdev = object
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = objects[indexPath.row]
cell.textLabel!.text = object.device.name
print("\(cell.textLabel!.text)")
cell.textLabel!.text = object.device.name! + String(format: "_%lX", object.id)
print("Cell Name : \(cell.textLabel!.text)")
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
objects.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
// MARK: - Bluetooth
func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData : [String : Any],
rssi RSSI: NSNumber) {
//NebPeripheral = peripheral
//central.connectPeripheral(peripheral, options: nil)
// We have to set the discoveredPeripheral var we declared earlier to reference the peripheral, otherwise we won't be able to interact with it in didConnectPeripheral. And you will get state = connecting> is being dealloc'ed while pending connection error.
//self.discoveredPeripheral = peripheral
//var curDevice = UIDevice.currentDevice()
//iPad or iPhone
// println("VENDOR ID: \(curDevice.identifierForVendor) BATTERY LEVEL: \(curDevice.batteryLevel)\n\n")
//println("DEVICE DESCRIPTION: \(curDevice.description) MODEL: \(curDevice.model)\n\n")
// Hardware beacon
print("PERIPHERAL NAME: \(peripheral.name)\n AdvertisementData: \(advertisementData)\n RSSI: \(RSSI)\n")
print("UUID DESCRIPTION: \(peripheral.identifier.uuidString)\n")
print("IDENTIFIER: \(peripheral.identifier)\n")
if advertisementData[CBAdvertisementDataManufacturerDataKey] == nil {
return
}
//sensorData.text = sensorData.text + "FOUND PERIPHERALS: \(peripheral) AdvertisementData: \(advertisementData) RSSI: \(RSSI)\n"
var id : UInt64 = 0
(advertisementData[CBAdvertisementDataManufacturerDataKey] as AnyObject).getBytes(&id, range: NSMakeRange(2, 8))
if (id == 0) {
return
}
var name : String? = nil
if advertisementData[CBAdvertisementDataLocalNameKey] == nil {
print("bad, no name")
name = peripheral.name
}
else {
name = advertisementData[CBAdvertisementDataLocalNameKey] as! String
}
let device = Neblina(devName: name!, devid: id, peripheral: peripheral)
/*for dev in objects
{
if (dev.id == id)
{
return;
}
}*/
//print("Peri : \(peripheral)\n");
//devices.addObject(peripheral)
print("DEVICES: \(device)\n")
// peripheral.name = String("\(peripheral.name)_")
objects.insert(device, at: 0)
tableView.reloadData();
// stop scanning, saves the battery
//central.stopScan()
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
//peripheral.delegate = self
peripheral.discoverServices(nil)
//gameView.PeripheralConnected(peripheral)
// detailView.setPeripheral(NebDevice)
//NebDevice.setPeripheral(peripheral)
print("Connected to peripheral")
}
func centralManager(_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?) {
//peripheral.delegate = self
//peripheral.discoverServices(nil)
//gameView.PeripheralConnected(peripheral)
// detailView.setPeripheral(NebDevice)
//NebDevice.setPeripheral(peripheral)
print("disconnected from peripheral")
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
// sensorData.text = "FAILED TO CONNECT \(error)"
}
func scanPeripheral(sender: CBCentralManager)
{
print("Scan for peripherals")
bleCentralManager.scanForPeripherals(withServices: nil, options: nil)
}
@objc func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOff:
print("CoreBluetooth BLE hardware is powered off")
//self.sensorData.text = "CoreBluetooth BLE hardware is powered off\n"
break
case .poweredOn:
print("CoreBluetooth BLE hardware is powered on and ready")
//self.sensorData.text = "CoreBluetooth BLE hardware is powered on and ready\n"
// We can now call scanForBeacons
let lastPeripherals = central.retrieveConnectedPeripherals(withServices: [NEB_SERVICE_UUID])
if lastPeripherals.count > 0 {
// let device = lastPeripherals.last as CBPeripheral;
//connectingPeripheral = device;
//centralManager.connectPeripheral(connectingPeripheral, options: nil)
}
//scanPeripheral(central)
bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil)
break
case .resetting:
print("CoreBluetooth BLE hardware is resetting")
//self.sensorData.text = "CoreBluetooth BLE hardware is resetting\n"
break
case .unauthorized:
print("CoreBluetooth BLE state is unauthorized")
//self.sensorData.text = "CoreBluetooth BLE state is unauthorized\n"
break
case .unknown:
print("CoreBluetooth BLE state is unknown")
//self.sensorData.text = "CoreBluetooth BLE state is unknown\n"
break
case .unsupported:
print("CoreBluetooth BLE hardware is unsupported on this platform")
//self.sensorData.text = "CoreBluetooth BLE hardware is unsupported on this platform\n"
break
default:
break
}
}
}
| mit | 2ad660575d606e0e63b8e0379050bfe3 | 32.816092 | 259 | 0.729096 | 4.263768 | false | false | false | false |
SunLiner/Floral | Floral/Floral/Classes/Profile/Columnist/Controller/ColumnistViewController.swift | 1 | 8543 | //
// ColumnistViewController.swift
// Floral
//
// Created by 孙林 on 16/5/19.
// Copyright © 2016年 ALin. All rights reserved.
// 专栏/用户的控制器
import UIKit
let ArticlesreuseIdentifier = "ArticlesCollectionViewCell"
// 专栏头部的重用标识符
//private let headerReuseIdentifier = "headerReuseIdentifier"
// 用户头部的重用标识符
private let UserHeaderReuseIdentifier = "UserHeaderReuseIdentifier"
// 专栏简介的cell重用标识符
private let AuthorIntroReuseIdentifier = "AuthorIntroViewCell"
// 作者简介的cell重用标识符
private let UserCellReuseIdentifier = "UserCollectionCell"
class ColumnistViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var author : Author?
// 是否是用户(用户和专栏是不一样的)
var isUser : Bool = false
{
didSet{
if isUser {
collectionView?.registerClass(UserCollectionViewCell.self, forCellWithReuseIdentifier: UserCellReuseIdentifier)
// collectionView?.registerNib(UINib.init(nibName: "UserHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: UserHeaderReuseIdentifier)
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "pc_setting_40x40"), style: .Plain, target: self, action: #selector(ColumnistViewController.gotoSetting))
}
}
}
var articles : [Article]?
{
didSet{
if let _ = articles {
collectionView!.reloadData()
}
}
}
init() {
super.init(collectionViewLayout: CollectionViewFlowLayout())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - view
override func viewDidLoad() {
super.viewDidLoad()
setup()
getList()
}
deinit
{
ALinLog("deinit...")
}
// MARK: - private method
// 数据获取
private func getList()
{
NetworkTool.sharedTools.getUserDetail(author!.id!) { (author, error) in
self.author = author
self.collectionView?.reloadSections(NSIndexSet(index: 0))
}
NetworkTool.sharedTools.columnistDetails(["currentPageIndex":"0", "userId":author!.id!]) { (articles, error, isLoadAll) in
if error == nil
{
if isLoadAll{
self.showHint("已经到最后了", duration: 2.0, yOffset: 0)
}else{
self.articles = articles
}
}else{
self.showHint("网络异常", duration: 2.0, yOffset: 0)
}
}
}
// 基本设置
func setup()
{
collectionView?.backgroundColor = UIColor.init(gray: 241.0)
navigationItem.title = "个人中心"
collectionView!.registerClass(ArticlesCollectionViewCell.self, forCellWithReuseIdentifier: ArticlesreuseIdentifier)
collectionView?.registerClass(AuthorIntroViewCell.self, forCellWithReuseIdentifier: AuthorIntroReuseIdentifier)
// collectionView?.registerClass(HeaderReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerReuseIdentifier)
collectionView?.registerNib(UINib.init(nibName: "UserHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: UserHeaderReuseIdentifier)
}
// 跳转到设置按钮
func gotoSetting() {
let setting = UIStoryboard.init(name: "SettingViewController", bundle: nil).instantiateInitialViewController()
setting?.navigationItem.title = "设置"
navigationController?.pushViewController(setting!, animated: true)
}
// MARK: - UICollectionView Datasource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 1 {
return articles?.count ?? 0
}
return 1
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
if isUser {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(UserCellReuseIdentifier, forIndexPath: indexPath) as! UserCollectionViewCell
cell.author = author
cell.clickShopCar = {
ALinLog("点击了购物车")
}
cell.clickRemind = {
self.navigationController?.pushViewController(RemindViewController(), animated: true)
}
cell.parentViewController = self
return cell
}else{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(AuthorIntroReuseIdentifier, forIndexPath: indexPath) as! AuthorIntroViewCell
cell.author = author
cell.parentViewController = self
return cell
}
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ArticlesreuseIdentifier, forIndexPath: indexPath) as! ArticlesCollectionViewCell
let count = articles?.count ?? 0
if count > 0 {
cell.article = articles![indexPath.item]
}
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView
{
var header : UICollectionReusableView?
// if isUser {
header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: UserHeaderReuseIdentifier, forIndexPath: indexPath)
// }
// else{ // 这儿应该分两种情况的, 有一个接口没有获取到, 后期补上
// header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: headerReuseIdentifier, forIndexPath: indexPath)
// header!.backgroundColor = (indexPath.section % 2 == 0) ? UIColor.purpleColor() : UIColor.orangeColor()
// }
return header!
}
// MARK: - UICollectionView Delegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 {
let detail = DetailViewController()
detail.article = articles![indexPath.row]
navigationController?.pushViewController(detail, animated: true)
}
}
// MAKR: - UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
if indexPath.section == 0 {
if isUser {
return CGSizeMake(UIScreen.mainScreen().bounds.width
, 160);
}else{
return CGSizeMake(UIScreen.mainScreen().bounds.width
, 130);
}
}else{
return CGSizeMake((UIScreen.mainScreen().bounds.width - 24)/2, 230);
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize
{
if section == 0 {
return CGSizeZero
}
return CGSize(width: UIScreen.mainScreen().bounds.width
, height: 40)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
{
if section == 0 {
return UIEdgeInsetsZero
}
return UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 10)
}
}
class CollectionViewFlowLayout: LevitateHeaderFlowLayout {
override func prepareLayout() {
super.prepareLayout()
collectionView?.alwaysBounceVertical = true
scrollDirection = .Vertical
minimumLineSpacing = 5
minimumInteritemSpacing = 0
}
}
| mit | f54108f9c29023cd8a49a833b4e8ae0e | 36.333333 | 207 | 0.643822 | 5.680603 | false | false | false | false |
dduan/swift | stdlib/public/core/LazyCollection.swift | 1 | 6029 | //===--- LazyCollection.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection on which normally-eager operations such as `map` and
/// `filter` are implemented lazily.
///
/// Please see `LazySequenceProtocol` for background; `LazyCollectionProtocol`
/// is an analogous component, but for collections.
///
/// To add new lazy collection operations, extend this protocol with
/// methods that return lazy wrappers that are themselves
/// `LazyCollectionProtocol`s.
///
/// - See Also: `LazySequenceProtocol`, `LazyCollection`
public protocol LazyCollectionProtocol
: Collection, LazySequenceProtocol {
/// A `Collection` that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// - See also: `elements`
associatedtype Elements : Collection = Self
}
/// When there's no special associated `Elements` type, the `elements`
/// property is provided.
extension LazyCollectionProtocol where Elements == Self {
/// Identical to `self`.
public var elements: Self { return self }
}
/// A collection containing the same elements as a `Base` collection,
/// but on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceProtocol`, `LazyCollection`
public struct LazyCollection<Base : Collection>
: LazyCollectionProtocol {
/// The type of the underlying collection
public typealias Elements = Base
/// The underlying collection
public var elements: Elements { return _base }
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Base.Index
/// Construct an instance with `base` as its underlying Collection
/// instance.
internal init(_base: Base) {
self._base = _base
}
internal var _base: Base
}
/// Forward implementations to the base collection, to pick up any
/// optimizations it might implement.
extension LazyCollection : Sequence {
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
public func makeIterator() -> Base.Iterator {
return _base.makeIterator()
}
/// Returns a value less than or equal to the number of elements in
/// `self`, **nondestructively**.
///
/// - Complexity: O(N).
public var underestimatedCount: Int { return _base.underestimatedCount }
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Iterator.Element> {
return _base._copyToNativeArrayBuffer()
}
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Base.Iterator.Element>
) -> UnsafeMutablePointer<Base.Iterator.Element> {
return _base._copyContents(initializing: ptr)
}
public func _customContainsEquatableElement(
element: Base.Iterator.Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
}
extension LazyCollection : Collection {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Base.Index {
return _base.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Base.Index {
return _base.endIndex
}
/// Access the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Base.Iterator.Element {
return _base[position]
}
/// Returns a collection representing a contiguous sub-range of
/// `self`'s elements.
///
/// - Complexity: O(1)
public subscript(bounds: Range<Index>) -> LazyCollection<Slice<Base>> {
return Slice(_base: _base, bounds: bounds).lazy
}
/// Returns `true` iff `self` is empty.
public var isEmpty: Bool {
return _base.isEmpty
}
/// Returns the number of elements.
///
/// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`;
/// O(N) otherwise.
public var count: Index.Distance {
return _base.count
}
// The following requirement enables dispatching for index(of:) when
// the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found;
/// `nil` otherwise.
///
/// - Complexity: O(N).
public func _customIndexOfEquatableElement(
element: Base.Iterator.Element
) -> Index?? {
return _base._customIndexOfEquatableElement(element)
}
/// Returns the first element of `self`, or `nil` if `self` is empty.
public var first: Base.Iterator.Element? {
return _base.first
}
}
/// Augment `self` with lazy methods such as `map`, `filter`, etc.
extension Collection {
/// A collection with contents identical to `self`, but on which
/// normally-eager operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See Also: `LazySequenceProtocol`, `LazyCollectionProtocol`.
public var lazy: LazyCollection<Self> {
return LazyCollection(_base: self)
}
}
extension LazyCollectionProtocol {
/// Identical to `self`.
public var lazy: Self { // Don't re-wrap already-lazy collections
return self
}
}
@available(*, unavailable, renamed: "LazyCollectionProtocol")
public typealias LazyCollectionType = LazyCollectionProtocol
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
| apache-2.0 | 216b41033ad6112e7096dededf9217bd | 30.238342 | 80 | 0.678554 | 4.45932 | false | false | false | false |
codercd/DPlayer | DPlayer/NetworkManager.swift | 1 | 1601 | //
// NetworkManager.swift
// DPlayer
//
// Created by LiChendi on 16/4/20.
// Copyright © 2016年 LiChendi. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import ObjectMapper
class NetworkManager: NSObject {
func getHomepageJson(block:(HomepageModel->Void)) {
Alamofire.request(.GET, "http://www.quanmin.tv/json/page/appv2-index/info.json").responseJSON() {
response in
switch response.result {
case .Success:
if let value = response.result.value {
let homepageModel = HomepageModel()
var dic = JSON(value).dictionary!
homepageModel.mapTable = dic["list"]!.array!
dic.removeValueForKey("list")
homepageModel.homepageItems = dic
block(homepageModel)
}
case .Failure(let error):
print(error)
}
}
}
func getHomeInfo(roomID:String, block: (RMRoomModel ->Void)) {
Alamofire.request(.GET, "http://www.quanmin.tv/json/rooms/\(roomID)/info.json").responseJSON() {
response in
switch response.result {
case .Success:
if let value = response.result.value {
let roomModel = RMRoomModel(json: JSON(value))
block(roomModel)
}
case .Failure(let error):
print(error)
}
}
}
}
| mit | ab1e00217001cfdc9389988d11190ac0 | 28.592593 | 105 | 0.508761 | 4.827795 | false | false | false | false |
Fidetro/SwiftFFDB | Swift-FFDB/Example/TableListViewController.swift | 1 | 1820 | //
// TableListViewController.swift
// Example
//
// Created by Fidetro on 2017/10/18.
// Copyright © 2017年 Fidetro. All rights reserved.
//
import UIKit
class TableListViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var dataSource = [FFObject.Type]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
registerTable()
tableView.delegate = self
tableView.dataSource = self
}
func registerTable() {
dataSource.append(FFShop.self)
dataSource.append(FFGood.self)
FFShop.registerTable()
FFGood.registerTable()
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = TableListTableViewCell.dequeueReusableWithTableView(tableView: tableView, style: .subtitle)
let objectType = dataSource[indexPath.row]
cell.updateDataSource(table: objectType)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TableDetailViewController") as! TableDetailViewController
let objectType = dataSource[indexPath.row]
detailVC.type = objectType
navigationController?.pushViewController(detailVC, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| apache-2.0 | 6215af56467629e89f863e18d248a7f3 | 29.79661 | 162 | 0.680242 | 5.281977 | false | false | false | false |
RyanTech/BRYXBanner | Pod/Classes/Banner.swift | 6 | 13831 | //
// Banner.swift
//
// Created by Harlan Haskins on 7/27/15.
// Copyright (c) 2015 Bryx. All rights reserved.
//
import Foundation
private enum BannerState {
case Showing, Hidden, Gone
}
/// A level of 'springiness' for Banners.
///
/// - None: The banner will slide in and not bounce.
/// - Slight: The banner will bounce a little.
/// - Heavy: The banner will bounce a lot.
public enum BannerSpringiness {
case None, Slight, Heavy
private var springValues: (damping: CGFloat, velocity: CGFloat) {
switch self {
case .None: return (damping: 1.0, velocity: 1.0)
case .Slight: return (damping: 0.7, velocity: 1.5)
case .Heavy: return (damping: 0.6, velocity: 2.0)
}
}
}
/// Banner is a dropdown notification view that presents above the main view controller, but below the status bar.
public class Banner: UIView {
private class func topWindow() -> UIWindow? {
for window in (UIApplication.sharedApplication().windows as! [UIWindow]).reverse() {
if window.windowLevel == UIWindowLevelNormal && !window.hidden { return window }
}
return nil
}
private let contentView = UIView()
private let labelView = UIView()
private let backgroundView = UIView()
/// How long the slide down animation should last.
public var animationDuration: NSTimeInterval = 0.4
public var springiness = BannerSpringiness.Slight
/// The color of the text as well as the image tint color if `shouldTintImage` is `true`.
public var textColor = UIColor.whiteColor() {
didSet {
resetTintColor()
}
}
/// Whether or not the banner should show a shadow when presented.
public var hasShadows = true {
didSet {
resetShadows()
}
}
/// The color of the background view. Defaults to `nil`.
override public var backgroundColor: UIColor? {
get { return backgroundView.backgroundColor }
set { backgroundView.backgroundColor = newValue }
}
/// The opacity of the background view. Defaults to 0.95.
override public var alpha: CGFloat {
get { return backgroundView.alpha }
set { backgroundView.alpha = newValue }
}
/// A block to call when the uer taps on the banner.
public var didTapBlock: (() -> ())?
/// A block to call after the banner has finished dismissing and is off screen.
public var didDismissBlock: (() -> ())?
/// Whether or not the banner should dismiss itself when the user taps. Defaults to `true`.
public var dismissesOnTap = true
/// Whether or not the banner should dismiss itself when the user swipes up. Defaults to `true`.
public var dismissesOnSwipe = true
/// Whether or not the banner should tint the associated image to the provided `textColor`. Defaults to `true`.
public var shouldTintImage = true {
didSet {
resetTintColor()
}
}
/// The label that displays the banner's title.
public let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.numberOfLines = 0
label.setTranslatesAutoresizingMaskIntoConstraints(false)
return label
}()
/// The label that displays the banner's subtitle.
public let detailLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
label.numberOfLines = 0
label.setTranslatesAutoresizingMaskIntoConstraints(false)
return label
}()
/// The image on the left of the banner.
let image: UIImage?
/// The image view that displays the `image`.
public let imageView: UIImageView = {
let imageView = UIImageView()
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
imageView.contentMode = .ScaleAspectFit
return imageView
}()
private var bannerState = BannerState.Hidden {
didSet {
if bannerState != oldValue {
forceUpdates()
}
}
}
/// A Banner with the provided `title`, `subtitle`, and optional `image`, ready to be presented with `show()`.
///
/// :param: title The title of the banner. Optional. Defaults to nil.
/// :param: subtitle The subtitle of the banner. Optional. Defaults to nil.
/// :param: image The image on the left of the banner. Optional. Defaults to nil.
/// :param: backgroundColor The color of the banner's background view. Defaults to `UIColor.blackColor()`.
/// :param: didTapBlock An action to be called when the user taps on the banner. Optional. Defaults to `nil`.
public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, backgroundColor: UIColor = UIColor.blackColor(), didTapBlock: (() -> ())? = nil) {
self.didTapBlock = didTapBlock
self.image = image
super.init(frame: CGRectZero)
resetShadows()
addGestureRecognizers()
initializeSubviews()
resetTintColor()
titleLabel.text = title
detailLabel.text = subtitle
backgroundView.backgroundColor = backgroundColor
backgroundView.alpha = 0.95
}
private func forceUpdates() {
if let superview = superview, showingConstraint = showingConstraint, hiddenConstraint = hiddenConstraint {
switch bannerState {
case .Hidden:
superview.removeConstraint(showingConstraint)
superview.addConstraint(hiddenConstraint)
case .Showing:
superview.removeConstraint(hiddenConstraint)
superview.addConstraint(showingConstraint)
case .Gone:
superview.removeConstraint(hiddenConstraint)
superview.removeConstraint(showingConstraint)
superview.removeConstraints(commonConstraints)
}
setNeedsLayout()
setNeedsUpdateConstraints()
layoutIfNeeded()
updateConstraintsIfNeeded()
}
}
internal func didTap(recognizer: UITapGestureRecognizer) {
if dismissesOnTap {
dismiss()
}
didTapBlock?()
}
internal func didSwipe(recognizer: UISwipeGestureRecognizer) {
if dismissesOnSwipe {
dismiss()
}
}
private func addGestureRecognizers() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTap:"))
let swipe = UISwipeGestureRecognizer(target: self, action: "didSwipe:")
swipe.direction = .Up
addGestureRecognizer(swipe)
}
private func resetTintColor() {
titleLabel.textColor = textColor
detailLabel.textColor = textColor
imageView.image = shouldTintImage ? image?.imageWithRenderingMode(.AlwaysTemplate) : image
imageView.tintColor = shouldTintImage ? textColor : nil
}
private func resetShadows() {
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 4
}
private func initializeSubviews() {
let views = [
"backgroundView": backgroundView,
"contentView": contentView,
"imageView": imageView,
"labelView": labelView,
"titleLabel": titleLabel,
"detailLabel": detailLabel
]
setTranslatesAutoresizingMaskIntoConstraints(false)
addSubview(backgroundView)
backgroundView.setTranslatesAutoresizingMaskIntoConstraints(false)
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[backgroundView]|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundView(>=80)]|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
backgroundView.backgroundColor = backgroundColor
contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
backgroundView.addSubview(contentView)
labelView.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addSubview(labelView)
labelView.addSubview(titleLabel)
labelView.addSubview(detailLabel)
let statusBarSize = UIApplication.sharedApplication().statusBarFrame.size
let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice.
for format in ["H:|[contentView]|", "V:|-(\(heightOffset))-[contentView]|"] {
backgroundView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: .DirectionLeadingToTrailing, metrics: nil, views: views))
}
let leftConstraintText: String
if let image = image {
contentView.addSubview(imageView)
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(15)-[imageView]", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 25.0))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: imageView, attribute: .Width, multiplier: 1.0, constant: 0.0))
leftConstraintText = "[imageView]"
} else {
leftConstraintText = "|"
}
let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=1)-[labelView]-(>=1)-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
backgroundView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .AlignAllCenterY, metrics: nil, views: views))
for view in [titleLabel, detailLabel] {
let constraintFormat = "H:|-(15)-[label]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: ["label": view]))
}
labelView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var showingConstraint: NSLayoutConstraint?
private var hiddenConstraint: NSLayoutConstraint?
private var commonConstraints = [NSLayoutConstraint]()
override public func didMoveToSuperview() {
super.didMoveToSuperview()
if let superview = superview where bannerState != .Gone {
commonConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[banner]|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["banner": self]) as! [NSLayoutConstraint]
superview.addConstraints(commonConstraints)
let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen.
showingConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: window, attribute: .Top, multiplier: 1.0, constant: yOffset)
hiddenConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: window, attribute: .Top, multiplier: 1.0, constant: yOffset)
}
}
/// Shows the banner. If a `duration` is specified, the banner dismisses itself automatically after that duration elapses.
/// :param: duration A time interval, after which the banner will dismiss itself. Optional. Defaults to `nil`.
public func show(duration: NSTimeInterval? = nil) {
if let window = Banner.topWindow() {
window.addSubview(self)
forceUpdates()
let (damping, velocity) = self.springiness.springValues
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Showing
}, completion: { finished in
if let duration = duration {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(duration * NSTimeInterval(NSEC_PER_SEC))), dispatch_get_main_queue(), self.dismiss)
}
})
} else {
println("[Banner]: Could not find window. Aborting.")
}
}
/// Dismisses the banner.
public func dismiss() {
let (damping, velocity) = self.springiness.springValues
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Hidden
}, completion: { finished in
self.bannerState = .Gone
self.removeFromSuperview()
self.didDismissBlock?()
})
}
}
| mit | af89db0cad963e856b46361909ac4fe0 | 44.496711 | 196 | 0.66163 | 5.352554 | false | false | false | false |
jasnig/ScrollPageView | ScrollViewController/缩放+颜色渐变 效果/vc1Controller.swift | 1 | 4583 | //
// vc1Controller.swift
// ScrollViewController
//
// Created by jasnig on 16/4/8.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class vc1Controller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 这个是必要的设置
automaticallyAdjustsScrollViewInsets = false
var style = SegmentStyle()
// 缩放文字
style.scaleTitle = true
// 颜色渐变
style.gradualChangeTitleColor = true
// segment可以滚动
style.scrollTitle = true
style.showExtraButton = true
let childVcs = setChildVcs()
let titles = childVcs.map { $0.title! }
let scrollPageView = ScrollPageView(frame: CGRect(x: 0, y: 64, width: view.bounds.size.width, height: view.bounds.size.height - 64), segmentStyle: style, titles: titles, childVcs: childVcs, parentViewController: self)
view.addSubview(scrollPageView)
}
func setChildVcs() -> [UIViewController] {
// 特别注意的是如果你的控制器是使用的storyBoard初始化, 务必重写这个初始化方法中注册通知监听者, 如果在viewDidLoad中注册,在第一次的时候将不会接受到通知
// 例如vc1 ---> 进入TestController中查看示例
let vc1 = storyboard!.instantiateViewControllerWithIdentifier("test")
vc1.title = "国内头条"
let vc2 = UIViewController()
vc2.view.backgroundColor = UIColor.greenColor()
vc2.title = "国际要闻"
let vc3 = UIViewController()
vc3.view.backgroundColor = UIColor.redColor()
vc3.title = "趣事"
let vc4 = UIViewController()
vc4.view.backgroundColor = UIColor.yellowColor()
vc4.title = "囧图"
let vc5 = UIViewController()
vc5.view.backgroundColor = UIColor.lightGrayColor()
vc5.title = "明星八卦"
let vc6 = UIViewController()
vc6.view.backgroundColor = UIColor.brownColor()
vc6.title = "爱车"
let vc7 = UIViewController()
vc7.view.backgroundColor = UIColor.orangeColor()
vc7.title = "国防要事"
let vc8 = UIViewController()
vc8.view.backgroundColor = UIColor.blueColor()
vc8.title = "科技频道"
let vc9 = UIViewController()
vc9.view.backgroundColor = UIColor.brownColor()
vc9.title = "手机专页"
let vc10 = UIViewController()
vc10.view.backgroundColor = UIColor.orangeColor()
vc10.title = "风景图"
let vc11 = UIViewController()
vc11.view.backgroundColor = UIColor.blueColor()
vc11.title = "段子"
return [vc1, vc2, vc3,vc4, vc5, vc6, vc7, vc8, vc9, vc10, vc11]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 2e67df8e4872fef6e3d117d7928b08d5 | 35.066667 | 225 | 0.658965 | 4.255654 | false | false | false | false |
kay-kim/stitch-examples | todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/ExtendedJson/Int+ExtendedJson.swift | 1 | 3505 | //
// Int+ExtendedJson.swift
// ExtendedJson
//
// Created by Jason Flax on 10/3/17.
// Copyright © 2017 MongoDB. All rights reserved.
//
import Foundation
extension Int: ExtendedJsonRepresentable {
public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable {
guard let json = xjson as? [String: Any] else {
throw BsonError.parseValueFailure(value: xjson, attemptedType: Int.self)
}
if let value = json[ExtendedJsonKeys.numberInt.rawValue] as? String,
let intValue = Int(value) {
return intValue
} else if let value = json[ExtendedJsonKeys.numberLong.rawValue] as? String,
let intValue = Int(value) {
return intValue
}
throw BsonError.parseValueFailure(value: xjson, attemptedType: Int.self)
}
public var toExtendedJson: Any {
// check if we're on a 32-bit or 64-bit platform and act accordingly
if MemoryLayout<Int>.size == MemoryLayout<Int32>.size {
let int32: Int32 = Int32(self)
return int32.toExtendedJson
}
let int64: Int64 = Int64(self)
return int64.toExtendedJson
}
public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool {
if let other = other as? Int {
return self == other
} else if let other = other as? Int32 {
return self == other
} else if let other = other as? Int64 {
return self == other
}
return false
}
}
extension Int32: ExtendedJsonRepresentable {
public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable {
guard let json = xjson as? [String: Any],
let value = json[ExtendedJsonKeys.numberInt.rawValue] as? String,
let int32Value = Int32(value) else {
throw BsonError.parseValueFailure(value: xjson, attemptedType: Int32.self)
}
return int32Value
}
public var toExtendedJson: Any {
return [ExtendedJsonKeys.numberInt.rawValue: String(self)]
}
public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool {
if let other = other as? Int32 {
return self == other
} else if let other = other as? Int {
return self == other
}
return false
}
}
extension Int64: ExtendedJsonRepresentable {
enum CodingKeys: String,CodingKey {
case numberLong = "$numberLong"
}
public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable {
guard let json = xjson as? [String: Any],
let value = json[ExtendedJsonKeys.numberLong.rawValue] as? String,
let int64Value = Int64(value) else {
throw BsonError.parseValueFailure(value: xjson, attemptedType: Int64.self)
}
return int64Value
}
public var toExtendedJson: Any {
return [ExtendedJsonKeys.numberLong.rawValue: String(self)]
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.init(try container.decode(Double.self, forKey: CodingKeys.numberLong))
}
public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool {
if let other = other as? Int64 {
return self == other
} else if let other = other as? Int {
return self == other
}
return false
}
}
| apache-2.0 | d158b5ced77dd90afc4bda534518f7ce | 31.747664 | 90 | 0.624715 | 4.315271 | false | false | false | false |
TZLike/GiftShow | GiftShow/GiftShow/Classes/Common/UIColor+extension.swift | 1 | 2460 | //
// UIColor+extension.swift
// SwiftLove
//
// Created by admin on 16/10/27.
// Copyright © 2016年 李苛. All rights reserved.
//
import UIKit
extension UIColor {
class func colorWithCustom(_ r: CGFloat, g:CGFloat, b:CGFloat) -> UIColor {
return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1)
}
class func randomColor() -> UIColor {
let r = CGFloat(arc4random_uniform(256))
let g = CGFloat(arc4random_uniform(256))
let b = CGFloat(arc4random_uniform(256))
return UIColor.colorWithCustom(r, g: g, b: b)
}
class func colorWithHexString(_ hex:String)->UIColor{
return colorWithHexString(hex, alpha: 1.0)
}
class func colorWithHexString(_ hex:String , alpha:CGFloat)->UIColor{
//删除字符串中的空格
// var cString = hex .stringByTrimmingCharactersInSet(NSCharacterSet .whitespaceAndNewlineCharacterSet()).uppercased() as NSString
var cString = hex.uppercased() as NSString
if (cString.length < 6)
{
return UIColor.clear
}
// //如果是0x开头的,那么截取字符串,字符串从索引为2的位置开始,一直到末尾
if (cString .hasPrefix("0X"))
{
// cString = cString .substring(from: 2)
cString = cString.substring(from: 2) as NSString
// cString = cString.substring(from: )
}
// //如果是#开头的,那么截取字符串,字符串从索引为1的位置开始,一直到末尾
if (cString .hasPrefix("#"))
{
cString = cString .substring(to: 1)
as NSString }
if (cString.length != 6)
{
return UIColor.clear
}
let rString = cString .substring(to: 2)
let gString = (cString .substring(from: 2)as NSString) .substring(to: 2)
let bString = (cString .substring(from: 4)as NSString) .substring(to: 2)
var r:CUnsignedInt = 0
var g:CUnsignedInt = 0
var b:CUnsignedInt = 0
Scanner(string:rString as String).scanHexInt32(&r)
Scanner(string:gString as String).scanHexInt32(&g)
Scanner(string:bString as String).scanHexInt32(&b)
return UIColor(red: (CGFloat(r) / 255.0), green: (CGFloat(g) / 255.0), blue: (CGFloat(b) / 255.0), alpha: 1.0)
}
}
| apache-2.0 | ed9b9b8f981af1277de7d84b4f4d6e59 | 30.986111 | 138 | 0.575771 | 3.877104 | false | false | false | false |
apple/swift-numerics | Sources/_TestSupport/Error.swift | 1 | 1236 | //===--- Error.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ComplexModule
import RealModule
public func relativeError(_ tst: Float, _ ref: Double) -> Double {
let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))
let error = (Double(tst) - ref).magnitude
return error / scale
}
public func componentwiseError(_ tst: Complex<Float>, _ ref: Complex<Double>) -> Double {
return max(relativeError(tst.real, ref.real),
relativeError(tst.imaginary, ref.imaginary))
}
public func relativeError(_ tst: Complex<Float>, _ ref: Complex<Double>) -> Double {
let scale = max(ref.magnitude, Double(Float.leastNormalMagnitude))
let dtst = Complex(Double(tst.real), Double(tst.imaginary))
let error = (dtst - ref).magnitude
return error / scale
}
| apache-2.0 | 40efbd24b87ee5adac6b40714dd714b1 | 37.625 | 89 | 0.642395 | 4.189831 | false | false | false | false |
malaonline/iOS | mala-ios/View/MemberPrivilegesView/LearningReportCollectionViewCell/LearningReportAbilityImproveCell.swift | 1 | 7978 | //
// LearningReportAbilityImproveCell.swift
// mala-ios
//
// Created by 王新宇 on 16/5/19.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
import Charts
class LearningReportAbilityImproveCell: MalaBaseReportCardCell {
// MARK: - Property
/// 提分点数据
private var model: [SingleTopicScoreData] = MalaConfig.scoreSampleData() {
didSet {
resetData()
}
}
override var asSample: Bool {
didSet {
if asSample {
model = MalaConfig.scoreSampleData()
}else {
hideDescription()
model = MalaSubjectReport.score_analyses
}
}
}
// MARK: - Components
/// 图例布局视图
private lazy var legendView: CombinedLegendView = {
let view = CombinedLegendView()
return view
}()
/// 组合统计视图(条形&折线)
private lazy var combinedChartView: CombinedChartView = {
let chartView = CombinedChartView()
chartView.animate(xAxisDuration: 0.65)
chartView.drawOrder = [
CombinedChartView.DrawOrder.bar.rawValue,
CombinedChartView.DrawOrder.line.rawValue
]
chartView.chartDescription?.text = ""
chartView.scaleXEnabled = false
chartView.scaleYEnabled = false
chartView.dragEnabled = false
chartView.drawBarShadowEnabled = false
chartView.drawValueAboveBarEnabled = true
let labels = self.getXVals()
let xAxis = chartView.xAxis
xAxis.labelCount = labels.count
xAxis.spaceMin = 0.4
xAxis.spaceMax = 0.6
xAxis.granularityEnabled = true
xAxis.granularity = 1
xAxis.labelFont = UIFont.systemFont(ofSize: 8)
xAxis.labelTextColor = UIColor(named: .ChartLabel)
xAxis.drawGridLinesEnabled = false
xAxis.labelPosition = .bottom
xAxis.valueFormatter = IndexAxisValueFormatter(values: labels)
let leftAxis = chartView.leftAxis
leftAxis.labelFont = UIFont.systemFont(ofSize: 10)
leftAxis.labelTextColor = UIColor(named: .ChartLabel)
leftAxis.gridLineDashLengths = [2,2]
leftAxis.gridColor = UIColor(named: .ChartLegendGray)
leftAxis.drawGridLinesEnabled = true
leftAxis.axisMinimum = 0
leftAxis.axisMaximum = 100
leftAxis.labelCount = 5
let pFormatter = NumberFormatter()
pFormatter.numberStyle = .percent
pFormatter.maximumFractionDigits = 1
pFormatter.multiplier = 1
pFormatter.percentSymbol = "%"
leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: pFormatter)
chartView.rightAxis.enabled = false
chartView.legend.enabled = false
return chartView
}()
// MARK: - Instance Method
override init(frame: CGRect) {
super.init(frame: frame)
configure()
setupUserInterface()
resetData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func configure() {
titleLabel.text = "提分点分析"
descDetailLabel.text = "学生对于圆的知识点、函数初步知识点和几何变换知识点能力突出,可减少习题数。实数可加强练习。"
legendView.addLegend(image: "dot_legend", title: "平均分数")
legendView.addLegend(image: "histogram_legend", title: "我的评分")
}
private func setupUserInterface() {
// Style
// SubViews
layoutView.addSubview(combinedChartView)
layoutView.addSubview(legendView)
// Autolayout
legendView.snp.makeConstraints { (maker) in
maker.left.equalTo(descView)
maker.right.equalTo(descView)
maker.height.equalTo(12)
maker.top.equalTo(layoutView.snp.bottom).multipliedBy(0.17)
}
combinedChartView.snp.makeConstraints { (maker) in
maker.top.equalTo(legendView.snp.bottom)
maker.left.equalTo(descView)
maker.right.equalTo(descView)
maker.bottom.equalTo(layoutView).multipliedBy(0.68)
}
}
// 设置样本数据
private func setupSampleData() {
}
// 重置数据
private func resetData() {
var aveScoreIndex = -1
var myScoreIndex = -1
// 设置折线图数据
let lineEntries = model.map({ (data) -> ChartDataEntry in
aveScoreIndex += 1
return ChartDataEntry(x: Double(aveScoreIndex), y: data.ave_score.doubleValue*100)
})
let lineDataSet = LineChartDataSet(values: lineEntries, label: "")
lineDataSet.setColor(UIColor(named: .ChartLegentLightBlue))
lineDataSet.fillAlpha = 1
lineDataSet.circleRadius = 6
lineDataSet.mode = .cubicBezier
lineDataSet.drawValuesEnabled = true
lineDataSet.setDrawHighlightIndicators(false)
let lineData = LineChartData()
lineData.addDataSet(lineDataSet)
lineData.setDrawValues(false)
// 设置柱状图数据
let barEntries = model.map({ (data) -> BarChartDataEntry in
myScoreIndex += 1
return BarChartDataEntry(x: Double(myScoreIndex), y: data.my_score.doubleValue*100)
})
let barDataSet = BarChartDataSet(values: barEntries, label: "")
barDataSet.drawValuesEnabled = true
barDataSet.colors = MalaConfig.chartsColor()
barDataSet.highlightEnabled = false
let barData = BarChartData()
barData.addDataSet(barDataSet)
barData.setDrawValues(false)
// 设置组合图数据
let data = CombinedChartData()
data.lineData = lineData
data.barData = barData
combinedChartView.data = data
}
// 获取X轴文字信息
private func getXVals() -> [String] {
/// 若当前数据无效,则使用默认数据
guard model.count != 0 else {
return MalaConfig.homeworkDataChartsTitle()
}
let xVals = model.map { (data) -> String in
return data.name
}
return xVals
}
override func hideDescription() {
descDetailLabel.text = "矩形为学生各模块分数,折线为所有学生平均分数。通过矩形和折线的上下关系可发现学生与平均分数之间的对比关系。"
}
}
// MARK: - LegendView
open class CombinedLegendView: UIView {
// MARK: - Property
private var currentButton: UIButton?
// MARK: - Constructed
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult
open func addLegend(image imageName: String, title: String) -> UIButton {
let button = UIButton()
button.adjustsImageWhenHighlighted = false
button.setImage(UIImage(named: imageName), for: UIControlState())
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 5)
button.setTitle(title, for: UIControlState())
button.titleLabel?.font = UIFont.systemFont(ofSize: 10)
button.setTitleColor(UIColor(named: .ChartLabel), for: UIControlState())
button.sizeToFit()
self.addSubview(button)
button.snp.makeConstraints { (maker) in
maker.centerY.equalTo(self.snp.centerY)
maker.right.equalTo(currentButton?.snp.left ?? self.snp.right).offset(-13)
}
currentButton = button
return button
}
}
| mit | 8b75db5519b1d6a32cc8c65b76cf857c | 30.384298 | 95 | 0.607637 | 4.642421 | false | false | false | false |
odemolliens/blockchain-ios-sdk | SDK_SWIFT/ODBlockChainWallet/ODBlockChainWallet/Domain/ODBlockChainError.swift | 1 | 5673 | //
//Copyright 2014 Olivier Demolliens - @odemolliens
//
//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
enum ODBCError {
case ODBCErrorParse
case ODBCErrorUnexpectedObject
case ODBCErrorMissingKeys
case ODBCErrorNetwork
case ODBCErrorAPI
case ODBCErrorNone
}
enum ODBCErrorAPI {
case Unknow
case ApiUnavailable
//case CloudFareUnavailable //http code 522 -> case ApiUnavailable
case PasswordLength
case ApiKey
case Email
case AlphaNumericOnly
case Hash
case Index
case NotFound
case TransactionNotFound
case IllegalCharacter
case Invalid
case DecryptingWallet
}
class ODBlockChainError : NSObject
{
// MARK: Domain
var type : ODBCError;
var error : NSError;
// MARK: Constructor
override init()
{
self.type = ODBCError.ODBCErrorNone;
self.error = NSError();
}
// MARK: Methods
func contentMessage() -> NSString
{
var error : NSString = NSString();
var dic : NSDictionary = self.error.userInfo as NSDictionary!;
// TODO : need optimization
if((dic.valueForKey("content")) != nil){
//if(dic.valueForKey("content").isKindOfClass(NSString)){
error = dic.valueForKey("content") as NSString;
//}
}
if(error.length>0){
return error;
}else{
return "NO_CONTENT";
}
}
// MARK: Static methods
class func parseError(parseError: NSError) -> ODBlockChainError
{
var nsError : NSError = NSError();
var odError : ODBlockChainError = ODBlockChainError();
odError.type = ODBCError.ODBCErrorParse;
odError.error = nsError;
return odError;
}
class func parseError(expected: NSString, result : NSString) -> ODBlockChainError
{
//TODO : manage error domain + error code
var nsError : NSError = NSError(domain: "ParseErrorUnexpectedObjectClass", code: -49, userInfo: NSDictionary(object: NSString(format:"expected:%@ result:%@",expected,result), forKey: "error"));
var odError : ODBlockChainError = ODBlockChainError();
odError.type = ODBCError.ODBCErrorParse;
odError.error = nsError;
return odError;
}
class func parseUnexpectedObject() -> ODBlockChainError
{
//TODO : manage error domain + error code
var nsError : NSError = NSError(domain: "ParseErrorUnexpectedObject", code: -50, userInfo: NSDictionary());
var odError : ODBlockChainError = ODBlockChainError();
odError.type = ODBCError.ODBCErrorUnexpectedObject;
odError.error = nsError;
return odError;
}
//TODO : this is not used for the moment
class func parseErrorMissingKeys(missingKeys : NSDictionary) -> ODBlockChainError
{
//TODO : manage error domain + error code
var nsError : NSError = NSError(domain: "ParseMissingKeysError", code: -51, userInfo: missingKeys);
var odError : ODBlockChainError = ODBlockChainError();
odError.type = ODBCError.ODBCErrorMissingKeys;
odError.error = nsError;
return odError;
}
class func network(networkError: NSError) -> ODBlockChainError
{
var odError : ODBlockChainError = ODBlockChainError();
odError.type = ODBCError.ODBCErrorNetwork;
odError.error = networkError;
return odError;
}
class func api(apiError: NSError) -> ODBlockChainError
{
var statusCode : NSNumber = NSNumber();
var odError : ODBlockChainError = ODBlockChainError();
var dic : NSDictionary = apiError.userInfo as NSDictionary!;
if((dic.valueForKey("httpcode")) != nil){
//if(dic.valueForKey("httpcode").isKindOfClass(NSNumber)){
statusCode = dic.valueForKey("httpcode") as NSNumber;
if(statusCode==522){
odError.type = ODBCError.ODBCErrorAPI;
odError.error = apiError;
//Force key for contentMessage() method
var dicError : NSDictionary = odError.error.userInfo as NSDictionary!;
dicError.setValue("CloudFare", forKey: "content");
return odError;
}
//}
}
odError.type = ODBCError.ODBCErrorAPI;
odError.error = apiError;
return odError;
}
class func parseManualError(error : NSString) -> ODBlockChainError
{
//TODO : manage error domain + error code
var nsError : NSError = NSError(domain: "parseManualError", code: -46, userInfo: NSDictionary(object: error, forKey: "content"));
var odError : ODBlockChainError = ODBlockChainError();
odError.type = ODBCError.ODBCErrorAPI;
odError.error = nsError;
return odError;
}
} | apache-2.0 | d92bab517c89cc83fe4d46f1a9f99683 | 29.021164 | 201 | 0.609201 | 4.894737 | false | false | false | false |
GraphStory/neo4j-ios | Sources/Theo/Model/QueryStats.swift | 2 | 1575 | import Foundation
import Bolt
import PackStream
public class QueryStats {
public var propertiesSetCount: UInt64
public var labelsAddedCount: UInt64
public var nodesCreatedCount: UInt64
public var resultAvailableAfter: UInt64
public var resultConsumedAfter: UInt64
public var type: String
public init(propertiesSetCount: UInt64 = 0,
labelsAddedCount: UInt64 = 0,
nodesCreatedCount: UInt64 = 0,
resultAvailableAfter: UInt64 = 0,
resultConsumedAfter: UInt64 = 0,
type: String = "") {
self.propertiesSetCount = propertiesSetCount
self.labelsAddedCount = labelsAddedCount
self.nodesCreatedCount = nodesCreatedCount
self.resultAvailableAfter = resultAvailableAfter
self.resultConsumedAfter = resultConsumedAfter
self.type = type
}
init?(data: PackProtocol) {
if let map = data as? Map,
let stats = map.dictionary["stats"] as? Map,
let propertiesSetCount = stats.dictionary["properties-set"]?.uintValue(),
let labelsAddedCount = stats.dictionary["labels-added"]?.uintValue(),
let nodesCreatedCount = stats.dictionary["nodes-created"]?.uintValue() {
self.propertiesSetCount = propertiesSetCount
self.labelsAddedCount = labelsAddedCount
self.nodesCreatedCount = nodesCreatedCount
self.resultAvailableAfter = 0
self.resultConsumedAfter = 0
self.type = "N/A"
} else {
return nil
}
}
}
| mit | 1d3cb1f5392c8ce08fcc2438d1225e59 | 29.288462 | 85 | 0.651429 | 4.646018 | false | false | false | false |
jhwayne/Brew | DNApp/Spring/SpringTextField.swift | 1 | 1641 | //
// SpringTextField.swift
// SpringApp
//
// Created by James Tang on 15/1/15.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
public class SpringTextField: UITextField, Springable {
@IBInspectable public var autostart: Bool = false
@IBInspectable public var autohide: Bool = false
@IBInspectable public var animation: String = ""
@IBInspectable public var force: CGFloat = 1
@IBInspectable public var delay: CGFloat = 0
@IBInspectable public var duration: CGFloat = 0.7
@IBInspectable public var damping: CGFloat = 0.7
@IBInspectable public var velocity: CGFloat = 0.7
@IBInspectable public var x: CGFloat = 0
@IBInspectable public var y: CGFloat = 0
@IBInspectable public var scaleX: CGFloat = 1
@IBInspectable public var scaleY: CGFloat = 1
@IBInspectable public var rotate: CGFloat = 0
@IBInspectable public var curve: String = ""
public var opacity: CGFloat = 1
public var animateFrom: Bool = false
lazy private var spring : Spring = Spring(self)
override public func awakeFromNib() {
super.awakeFromNib()
self.spring.customAwakeFromNib()
}
override public func didMoveToWindow() {
super.didMoveToWindow()
self.spring.customDidMoveToWindow()
}
public func animate() {
self.spring.animate()
}
public func animateNext(completion: () -> ()) {
self.spring.animateNext(completion)
}
public func animateTo() {
self.spring.animateTo()
}
public func animateToNext(completion: () -> ()) {
self.spring.animateToNext(completion)
}
} | mit | c54407de9de3f75c30232c9b00edc2f7 | 28.321429 | 55 | 0.671542 | 4.571031 | false | false | false | false |
yannickl/Cocarde | Cocarde/CocardeLayer.swift | 1 | 5058 | /*
* Cocarde
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Foundation
import UIKit
import QuartzCore
/**
Abstract class to help the implementation of custom loader.
*/
internal class CocardeLayer: CALayer {
private let hideAnimationKey = "plots.hide"
private let revealAnimationKey = "plots.reveal"
let segmentCount: UInt
let segmentColors: [UIColor]
let loopDuration: Double
internal var hideAnimationDefaultKeyPath: String {
get {
return "transform.scale"
}
}
var animating: Bool = false {
didSet {
if animating {
startAnimating()
}
else {
stopAnimating(true)
}
}
}
/**
A Boolean value that controls whether the receiver is hidden when the
animation is stopped.
*/
var hidesWhenStopped: Bool = false {
didSet {
stopAnimating(true)
}
}
override var frame: CGRect {
didSet {
clearDrawing()
drawInRect(bounds)
if !animating {
stopAnimating(false)
}
}
}
/**
Initializes a layer with parameters.
- parameter segmentCount: Generic parameters display
- parameter segmentColors: Color list
- parameter loopDuration: Duration in second for the loop animation
*/
required init(segmentCount segments: UInt, segmentColors colors: [UIColor], loopDuration duration: Double) {
segmentCount = segments
segmentColors = colors
loopDuration = duration
super.init()
}
override init(layer: AnyObject) {
if layer is CocardeLayer {
segmentCount = layer.segmentCount
segmentColors = layer.segmentColors
loopDuration = layer.loopDuration
hidesWhenStopped = layer.hidesWhenStopped
animating = layer.animating
}
else {
fatalError("init(layer:) has not been implemented")
}
super.init(layer: layer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setNeedsDisplay() {
super.setNeedsDisplay()
clearDrawing()
drawInRect(bounds)
}
// MARK: - Drawing Cocarde Activity
internal func clearDrawing() {
if let layers = sublayers {
for layer in layers {
layer.removeAllAnimations()
layer.removeFromSuperlayer()
}
}
removeAllAnimations()
}
internal func drawInRect(rect: CGRect) {
}
// MARK: - Managing Animations
internal func startAnimating() {
if let layers = sublayers {
for layer in layers {
layer.speed = 1
}
}
speed = 1
if animationForKey(hideAnimationKey) != nil {
let anim = CABasicAnimation(keyPath: hideAnimationDefaultKeyPath)
anim.duration = 0.4
anim.fromValue = 0
anim.toValue = 1
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
addAnimation(anim, forKey: revealAnimationKey)
removeAnimationForKey(hideAnimationKey)
}
}
internal func stopAnimating(animated: Bool) {
if !hidesWhenStopped {
let currentTime = CACurrentMediaTime()
if let layers = sublayers {
for layer in layers {
layer.timeOffset = layer.convertTime(currentTime, fromLayer: nil)
layer.speed = 0
}
}
timeOffset = convertTime(currentTime, fromLayer: nil)
speed = 0
}
else {
speed = 1
let anim = CABasicAnimation(keyPath: hideAnimationDefaultKeyPath)
anim.duration = animated ? 0.4 : 0.01
anim.toValue = 0
anim.removedOnCompletion = false
anim.fillMode = kCAFillModeBoth
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
addAnimation(anim, forKey: hideAnimationKey)
}
}
}
| mit | 49bddd1559157efc69b90236c73263f4 | 25.904255 | 110 | 0.655002 | 4.896418 | false | false | false | false |
Lucky13Tech/L13MessageKit | L13MessageKit/Actionable/UIGestureRecognizerClosure.swift | 1 | 4030 |
//
// UIGestureRecognizerClosure.swift
//
// Adds closures to gesture setup. Just an example of using an extension.
//
// Usage:
//
// self.view.addGestureRecognizer(UITapGestureRecognizer(){
// print("UITapGestureRecognizer")
// })
//
// let longpressGesture = UILongPressGestureRecognizer() {
// print("UILongPressGestureRecognizer")
// }
// self.view.addGestureRecognizer(longpressGesture)
//
// Michael L. Collard
// [email protected]
import UIKit
//
// Associator.swift
// STP
//
// Created by Chris O'Neil on 10/11/15.
// Copyright © 2015 Because. All rights reserved.
//
import ObjectiveC
private final class Wrapper<T> {
let value: T
init(_ x: T) {
value = x
}
}
class Associator {
static private func wrap<T>(x: T) -> Wrapper<T> {
return Wrapper(x)
}
static func setAssociatedObject<T>(object: AnyObject, value: T, associativeKey: UnsafePointer<Void>, policy: objc_AssociationPolicy) {
if let v: AnyObject = value as? AnyObject {
objc_setAssociatedObject(object, associativeKey, v, policy)
}
else {
objc_setAssociatedObject(object, associativeKey, wrap(value), policy)
}
}
static func getAssociatedObject<T>(object: AnyObject, associativeKey: UnsafePointer<Void>) -> T? {
if let v = objc_getAssociatedObject(object, associativeKey) as? T {
return v
}
else if let v = objc_getAssociatedObject(object, associativeKey) as? Wrapper<T> {
return v.value
}
else {
return nil
}
}
}
private class MultiDelegate : NSObject, UIGestureRecognizerDelegate {
@objc func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension UIGestureRecognizer {
struct PropertyKeys {
static var blockKey = "BCBlockPropertyKey"
static var multiDelegateKey = "BCMultiDelegateKey"
}
private var block:((recognizer:UIGestureRecognizer) -> Void) {
get {
return Associator.getAssociatedObject(self, associativeKey:&PropertyKeys.blockKey)!
}
set {
Associator.setAssociatedObject(self, value: newValue, associativeKey:&PropertyKeys.blockKey, policy: .OBJC_ASSOCIATION_RETAIN)
}
}
private var multiDelegate:MultiDelegate {
get {
return Associator.getAssociatedObject(self, associativeKey:&PropertyKeys.multiDelegateKey)!
}
set {
Associator.setAssociatedObject(self, value: newValue, associativeKey:&PropertyKeys.multiDelegateKey, policy: .OBJC_ASSOCIATION_RETAIN)
}
}
convenience init(block:(recognizer:UIGestureRecognizer) -> Void) {
self.init()
self.block = block
self.multiDelegate = MultiDelegate()
self.delegate = self.multiDelegate
self.addTarget(self, action: "didInteractWithGestureRecognizer:")
}
@objc func didInteractWithGestureRecognizer(sender:UIGestureRecognizer) {
self.block(recognizer: sender)
}
}
// Global array of targets, as extensions cannot have non-computed properties
//private var target = [Target]()
//
//extension UIGestureRecognizer {
//
// convenience init(trailingClosure closure: (() -> ())) {
// // let UIGestureRecognizer do its thing
// self.init()
//
// target.append(Target(closure))
// self.addTarget(target.last!, action: "invoke")
// }
//}
//
//private class Target {
//
// // store closure
// private var trailingClosure: (() -> ())
//
// init(_ closure:(() -> ())) {
// trailingClosure = closure
// }
//
// // function that gesture calls, which then
// // calls closure
// /* Note: Note sure why @IBAction is needed here */
// @IBAction func invoke() {
// trailingClosure()
// }
//} | mit | 346253676b1a79c1c2f6c8fb580237eb | 27.181818 | 178 | 0.637627 | 4.491639 | false | false | false | false |
victorchee/IconMaker | IconMaker/IconMaker/ViewController.swift | 1 | 4363 | //
// ViewController.swift
// IconMaker
//
// Created by qihaijun on 8/7/15.
// Copyright (c) 2015 VictorChee. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var iconView: IconView!
@IBOutlet weak var faviconView: FaviconView!
@IBOutlet weak var faviconLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
faviconLabel.font = UIFont.systemFontOfSize(500)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
saveIcons()
saveFavicons()
}
func saveIcons() {
let originalImage = captureView(iconView);
saveToDocument(originalImage, name: "1024") // 1024
saveToDocument(originalImage.resize(CGSizeMake(29*1, 29*1)), name: "29")
saveToDocument(originalImage.resize(CGSizeMake(29*2, 29*2)), name: "29@2x")
saveToDocument(originalImage.resize(CGSizeMake(29*3, 29*3)), name: "29@3x")
saveToDocument(originalImage.resize(CGSizeMake(40*1, 40*1)), name: "40")
saveToDocument(originalImage.resize(CGSizeMake(40*2, 40*2)), name: "40@2x")
saveToDocument(originalImage.resize(CGSizeMake(40*3, 40*3)), name: "40@3x")
saveToDocument(originalImage.resize(CGSizeMake(50*1, 50*1)), name: "50")
saveToDocument(originalImage.resize(CGSizeMake(50*2, 50*2)), name: "50@2x")
saveToDocument(originalImage.resize(CGSizeMake(57*1, 57*1)), name: "57")
saveToDocument(originalImage.resize(CGSizeMake(57*2, 57*2)), name: "57@2x")
saveToDocument(originalImage.resize(CGSizeMake(60*2, 60*2)), name: "60@2x")
saveToDocument(originalImage.resize(CGSizeMake(60*3, 60*3)), name: "60@3x")
saveToDocument(originalImage.resize(CGSizeMake(72*1, 72*1)), name: "72")
saveToDocument(originalImage.resize(CGSizeMake(72*2, 72*2)), name: "72@2x")
saveToDocument(originalImage.resize(CGSizeMake(76*1, 76*1)), name: "76")
saveToDocument(originalImage.resize(CGSizeMake(76*2, 76*2)), name: "76@2x")
}
func saveFavicons() {
let originalImage = captureView(faviconView);
saveToDocument(originalImage, name: "1024") // 1024
saveToDocument(originalImage.resize(CGSizeMake(57, 57)), name: "apple-icon-57x57")
saveToDocument(originalImage.resize(CGSizeMake(60, 60)), name: "apple-icon-60x60")
saveToDocument(originalImage.resize(CGSizeMake(72, 72)), name: "apple-icon-72x72")
saveToDocument(originalImage.resize(CGSizeMake(76, 76)), name: "apple-icon-76x76")
saveToDocument(originalImage.resize(CGSizeMake(114, 114)), name: "apple-icon-114x114")
saveToDocument(originalImage.resize(CGSizeMake(120, 120)), name: "apple-icon-120x120")
saveToDocument(originalImage.resize(CGSizeMake(144, 144)), name: "apple-icon-144x144")
saveToDocument(originalImage.resize(CGSizeMake(152, 152)), name: "apple-icon-152x152")
saveToDocument(originalImage.resize(CGSizeMake(180, 180)), name: "apple-icon-180x180")
saveToDocument(originalImage.resize(CGSizeMake(16, 16)), name: "favicon-16x16")
saveToDocument(originalImage.resize(CGSizeMake(32, 32)), name: "favicon-32x32")
saveToDocument(originalImage.resize(CGSizeMake(96, 96)), name: "favicon-96x96")
saveToDocument(originalImage.resize(CGSizeMake(192, 192)), name: "favicon-192x192")
}
func captureView(view: UIView) -> UIImage {
UIGraphicsBeginImageContext(view.bounds.size)
let context = UIGraphicsGetCurrentContext()
view.layer.renderInContext(context!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func saveToDocument(image: UIImage, name: String) {
let data = UIImagePNGRepresentation(image)
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
if let url = urls.first?.URLByAppendingPathComponent(name + ".png") {
data?.writeToURL(url, atomically: true)
}
}
}
| mit | 68d9d45c7e4873ec9770bed38d46eb21 | 47.477778 | 114 | 0.682329 | 4.058605 | false | false | false | false |
6ag/AppScreenshots | AppScreenshots/Classes/Application/JFAdManager.swift | 1 | 11039 | //
// JFAdManager.swift
// JianSanWallpaper
//
// Created by zhoujianfeng on 16/8/13.
// Copyright © 2016年 六阿哥. All rights reserved.
//
import UIKit
import Firebase
import GoogleMobileAds
/// 应用ID
fileprivate let AD_APPLICATION_ID = "ca-app-pub-3941303619697740~8182246519"
/// 插页式广告ID
fileprivate let AD_INTERSTITIAL_ID = "ca-app-pub-3941303619697740/9658979714"
/// banner广告ID
fileprivate let AD_BANNER_ID = "ca-app-pub-3941303619697740/4039136115"
/// 插页式广告显示频率
fileprivate let AD_TIME_INTERVAL: TimeInterval = 120
/// 是否显示广告 - 这里是用来方便隐藏广告的
fileprivate let AD_SHOULD_SHOW = true
/// 广告配置类 - 全局配置
class JFAdConfiguration {
/// 广告配置单利
static let shared = JFAdConfiguration()
/// 应用ID - 目前无用
var applicationId: String = AD_APPLICATION_ID
/// 插页式广告ID
var interstitialId: String = AD_INTERSTITIAL_ID
/// banner广告ID
var bannerId: String = AD_BANNER_ID
/// 插页式广告显示频率
var timeInterval: TimeInterval = AD_TIME_INTERVAL
/// 是否显示广告 - 这里是用来方便隐藏广告的
var isShouldShow: Bool = AD_SHOULD_SHOW
/// 配置广告
///
/// - Parameters:
/// - applicationId: 应用id
/// - interstitialId: 插页式广告id
/// - bannerId: banner广告id
/// - timeInterval: 插页式广告显示频率 单位秒
func config(applicationId: String,
interstitialId: String,
bannerId: String,
timeInterval: TimeInterval = AD_TIME_INTERVAL,
isShouldShow: Bool = AD_SHOULD_SHOW) {
self.applicationId = applicationId
self.interstitialId = interstitialId
self.bannerId = bannerId
self.timeInterval = timeInterval
self.isShouldShow = isShouldShow
// 配置Firebase - 国内被墙了
// FIRApp.configure()
// 初始化广告管理者
JFAdManager.shared.initial()
}
}
/// 广告管理类
class JFAdManager: NSObject {
/// 广告管理单利
static let shared: JFAdManager = {
let shared = JFAdManager()
shared.updateSharedHideAd()
shared.timer = Timer(timeInterval: JFAdConfiguration.shared.timeInterval, target: shared, selector: #selector(changedInterstitialState), userInfo: nil, repeats: true)
RunLoop.current.add(shared.timer!, forMode: RunLoopMode.commonModes)
return shared
}()
/// 已经准备好的插页式广告
fileprivate var interstitials = [GADInterstitial]()
/// 不能展示的插页式广告 - 只是用来暂存插页式广告对象,防止释放
fileprivate var notReadInterstitials = [GADInterstitial]()
/// 定时器
fileprivate var timer: Timer?
/// 插页式广告是否能够展示 - 频率控制
fileprivate var isShow = true
/// 是否在分享隐藏广告期间内
fileprivate var isSharedHide = false
/// 日期格式化器 - 这样做是为了提升性能
lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
/// 改变插页式广告状态 - 控制显示频率
@objc fileprivate func changedInterstitialState() {
isShow = true && !isSharedHide
}
/// 弹出分享提示信息
///
/// - Parameter vc: 需要弹出的控制器
func showShareAlert(vc: UIViewController) -> Bool {
// 判断有没有分享过,如果没有则要求分享一次
if !UserDefaults.standard.bool(forKey: "isShouldSave") && !UserDefaults.standard.bool(forKey: "isUpdatingVersion") {
let alertC = UIAlertController(title: "第一次保存需要先分享哦", message: "分享后2天无广告!独乐乐不如众乐乐,好东西要分享给身边的朋友们哦!", preferredStyle: .alert)
alertC.addAction(UIAlertAction(title: "立即分享", style: .default, handler: { [weak vc] (_) in
UMSocialUIManager.showShareMenuViewInWindow { (platformType, userInfo) in
let messageObject = UMSocialMessageObject()
let shareObject = UMShareWebpageObject.shareObject(withTitle: "开发者专用应用截图制作工具", descr: "轻松快速生成漂亮的app应用截图,提升您的app装机量!", thumImage: UIImage(named: "app_icon"))
shareObject?.webpageUrl = "https://itunes.apple.com/app/id\(APPSTORE_ID)"
messageObject.shareObject = shareObject
UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: vc) { (data, error) in
JFProgressHUD.showSuccessWithStatus("不管有没有分享成功,谢谢支持")
UserDefaults.standard.set(true, forKey: "isShouldSave")
// 设置隐藏广告时间
let currentDateString = JFAdManager.shared.dateFormatter.string(from: Date())
log("从currentDateString = \(currentDateString)起,2天内无广告")
UserDefaults.standard.set(currentDateString, forKey: "removeAdAtTime")
UserDefaults.standard.synchronize()
JFAdManager.shared.updateSharedHideAd()
}
}
}))
alertC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
vc.present(alertC, animated: true, completion: nil)
return true
} else {
return false
}
}
/// 更新分享隐藏广告的标识状态
func updateSharedHideAd() {
if let removeAdAtTime = UserDefaults.standard.string(forKey: "removeAdAtTime") {
// 分享时的日期
let shareDate = dateFormatter.date(from: removeAdAtTime)!
// 两天后的日期
let twoDayAfterDate = Date(timeInterval: 60 * 60 * 24 * 2, since: shareDate)
// 分享2天后的日期和当前日期比较,判断是否已经超过了2天。如果超过,则显示广告
let result = twoDayAfterDate.compare(Date())
log("从分享时开始计算,2天后的日期为\(dateFormatter.string(from: twoDayAfterDate))")
log("当前日期为 \(dateFormatter.string(from: Date()))")
// 降序
if result == .orderedDescending {
// 还可以继续隐藏广告
isSharedHide = true
log("还可以继续隐藏广告")
}
}
}
/// 初始化广告管理者 - 其实就是先创建一个插页广告
func initial() {
createInterstitial()
}
/// 获取一个有效的插页式广告对象
///
/// - Returns: 插页式广告对象
func getReadyIntersitial() -> GADInterstitial? {
// 如果已经在分享隐藏广告期间,则直接返回nil。防止浪费流量
if isSharedHide {
return nil
}
if interstitials.count > 0 {
let firstInterstitial = interstitials.removeFirst()
createInterstitial()
if firstInterstitial.isReady && isShow && JFAdConfiguration.shared.isShouldShow {
return firstInterstitial
} else {
return nil
}
}
createInterstitial()
return nil
}
/// 创建Baner广告 - 一个对象就是一个view
///
/// - Parameters:
/// - rootViewController: rootViewController
/// - bannerId: 广告id - 缺省值就是配置JFAdConfiguration时的
/// - Returns: banerView 可能为空
func createBannerView(_ rootViewController: UIViewController, bannerId: String = JFAdConfiguration.shared.bannerId) -> GADBannerView? {
let bannerView = GADBannerView()
bannerView.rootViewController = rootViewController
bannerView.adUnitID = bannerId
bannerView.load(GADRequest())
if JFAdConfiguration.shared.isShouldShow {
return bannerView
} else {
return nil
}
}
/// 创建插页式广告 - 一个对象只能展示一次
fileprivate func createInterstitial() {
let interstitial = GADInterstitial(adUnitID: JFAdConfiguration.shared.interstitialId)
interstitial.delegate = self
interstitial.load(GADRequest())
notReadInterstitials.append(interstitial)
}
}
// MARK: - GADInterstitialDelegate
extension JFAdManager: GADInterstitialDelegate {
/// 插页式广告请求成功时调用。
/// 在应用程序中的下一个转换点显示它,例如在视图控制器之间转换时。
func interstitialDidReceiveAd(_ ad: GADInterstitial) {
log("插页式广告接收成功,能够被展示 \(ad)")
interstitials.append(ad)
notReadInterstitials.removeFirst()
}
/// 在插页式广告请求完成且未显示插页式广告时调用。
/// 这是常见的,因为插页式广告会向用户谨慎显示。
func interstitial(_ ad: GADInterstitial, didFailToReceiveAdWithError error: GADRequestError) {
log("插页式广告接收失败,可能是网络原因 \(ad)")
notReadInterstitials.removeFirst()
}
/// 在展示插页式广告之前调用。
/// 在此方法完成后,插页式广告将在屏幕上动画。 利用这个机会停止动画并保存应用程序的状态,以防用户在屏幕上显示插页式广告时离开(例如,通过插页式广告上的链接访问App Store)。
func interstitialWillPresentScreen(_ ad: GADInterstitial) {
log("插页式广告即将显示 \(ad)")
isShow = false
}
/// 当插页式广告展示失败时调用。
func interstitialDidFail(toPresentScreen ad: GADInterstitial) {
log("插页式广告展示失败 \(ad)")
}
/// 在插页式广告即将隐藏时调用
func interstitialWillDismissScreen(_ ad: GADInterstitial) {
log("插页式广告即将隐藏 \(ad)")
}
/// 在插页式广告已经隐藏时调用
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
log("插页式广告已经隐藏 \(ad)")
}
/// 由于用户点击了将启动其他应用程序的广告(例如App Store),应用程序之前调用该应用程序就会退出或终止。
/// 正常的UIApplicationDelegate方法,如applicationDidEnterBackground :,将在此之前立即被调用。
func interstitialWillLeaveApplication(_ ad: GADInterstitial) {
log("app进入后台 \(ad)")
}
}
| mit | 7119fe5b811c9d6781304a6f4ee70a3b | 32.369963 | 176 | 0.611855 | 4.006157 | false | false | false | false |
cszrs/refresher | PullToRefreshDemo/CustomSubview.swift | 8 | 1134 | //
// CustomSubview.swift
// PullToRefresh
//
// Created by Josip Cavar on 30/03/15.
// Copyright (c) 2015 Josip Cavar. All rights reserved.
//
import UIKit
import Refresher
class CustomSubview: UIView, PullToRefreshViewDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var labelTitle: UILabel!
func pullToRefreshAnimationDidStart(view: PullToRefreshView) {
activityIndicator.startAnimating()
labelTitle.text = "Loading"
}
func pullToRefreshAnimationDidEnd(view: PullToRefreshView) {
activityIndicator.stopAnimating()
labelTitle.text = ""
}
func pullToRefresh(view: PullToRefreshView, progressDidChange progress: CGFloat) {
}
func pullToRefresh(view: PullToRefreshView, stateDidChange state: PullToRefreshViewState) {
switch state {
case .Loading:
labelTitle.text = "Loading"
case .PullToRefresh:
labelTitle.text = "Pull to refresh"
case .ReleaseToRefresh:
labelTitle.text = "Release to refresh"
}
}
} | mit | 0de15f6dcb4169015b55f076f2ea864c | 25.395349 | 95 | 0.662257 | 5.131222 | false | false | false | false |
vapor/fluent | Tests/FluentTests/CredentialTests.swift | 1 | 5613 | import XCTFluent
import XCTVapor
import Fluent
import Vapor
final class CredentialTests: XCTestCase {
func testCredentialsAuthentication() throws {
let app = Application(.testing)
defer { app.shutdown() }
// Setup test db.
let testDB = ArrayTestDatabase()
app.databases.use(testDB.configuration, as: .test)
// Configure sessions.
app.middleware.use(app.sessions.middleware)
// Setup routes.
let sessionRoutes = app.grouped(CredentialsUser.sessionAuthenticator())
let credentialRoutes = sessionRoutes.grouped(CredentialsUser.credentialsAuthenticator())
credentialRoutes.post("login") { req -> Response in
guard req.auth.has(CredentialsUser.self) else {
throw Abort(.unauthorized)
}
return req.redirect(to: "/protected")
}
let protectedRoutes = sessionRoutes.grouped(CredentialsUser.redirectMiddleware(path: "/login"))
protectedRoutes.get("protected") { req -> HTTPStatus in
_ = try req.auth.require(CredentialsUser.self)
return .ok
}
// Create user
let password = "password-\(Int.random())"
let passwordHash = try Bcrypt.hash(password)
let testUser = CredentialsUser(id: UUID(), username: "user-\(Int.random())", password: passwordHash)
testDB.append([TestOutput(testUser)])
testDB.append([TestOutput(testUser)])
testDB.append([TestOutput(testUser)])
testDB.append([TestOutput(testUser)])
// Test login
let loginData = ModelCredentials(username: testUser.username, password: password)
try app.test(.POST, "/login", beforeRequest: { req in
try req.content.encode(loginData, as: .urlEncodedForm)
}) { res in
XCTAssertEqual(res.status, .seeOther)
XCTAssertEqual(res.headers[.location].first, "/protected")
let sessionID = try XCTUnwrap(res.headers.setCookie?["vapor-session"]?.string)
// Test accessing protected route
try app.test(.GET, "/protected", beforeRequest: { req in
var cookies = HTTPCookies()
cookies["vapor-session"] = .init(string: sessionID)
req.headers.cookie = cookies
}) { res in
XCTAssertEqual(res.status, .ok)
}
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
func testAsyncCredentialsAuthentication() async throws {
let app = Application(.testing)
defer { app.shutdown() }
// Setup test db.
let testDB = ArrayTestDatabase()
app.databases.use(testDB.configuration, as: .test)
// Configure sessions.
app.middleware.use(app.sessions.middleware)
// Setup routes.
let sessionRoutes = app.grouped(CredentialsUser.sessionAuthenticator())
let credentialRoutes = sessionRoutes.grouped(CredentialsUser.asyncCredentialsAuthenticator())
credentialRoutes.post("login") { req -> Response in
guard req.auth.has(CredentialsUser.self) else {
throw Abort(.unauthorized)
}
return req.redirect(to: "/protected")
}
let protectedRoutes = sessionRoutes.grouped(CredentialsUser.redirectMiddleware(path: "/login"))
protectedRoutes.get("protected") { req -> HTTPStatus in
_ = try req.auth.require(CredentialsUser.self)
return .ok
}
// Create user
let password = "password-\(Int.random())"
let passwordHash = try Bcrypt.hash(password)
let testUser = CredentialsUser(id: UUID(), username: "user-\(Int.random())", password: passwordHash)
testDB.append([TestOutput(testUser)])
testDB.append([TestOutput(testUser)])
testDB.append([TestOutput(testUser)])
testDB.append([TestOutput(testUser)])
// Test login
let loginData = ModelCredentials(username: testUser.username, password: password)
try app.test(.POST, "/login", beforeRequest: { req in
try req.content.encode(loginData, as: .urlEncodedForm)
}) { res in
XCTAssertEqual(res.status, .seeOther)
XCTAssertEqual(res.headers[.location].first, "/protected")
let sessionID = try XCTUnwrap(res.headers.setCookie?["vapor-session"]?.string)
// Test accessing protected route
try app.test(.GET, "/protected", beforeRequest: { req in
var cookies = HTTPCookies()
cookies["vapor-session"] = .init(string: sessionID)
req.headers.cookie = cookies
}) { res in
XCTAssertEqual(res.status, .ok)
}
}
}
#endif
}
final class CredentialsUser: Model {
static let schema = "users"
@ID(key: .id)
var id: UUID?
@Field(key: "username")
var username: String
@Field(key: "password")
var password: String
init() { }
init(id: UUID? = nil, username: String, password: String) {
self.id = id
self.username = username
self.password = password
}
}
extension CredentialsUser: ModelCredentialsAuthenticatable {
static let usernameKey = \CredentialsUser.$username
static let passwordHashKey = \CredentialsUser.$password
func verify(password: String) throws -> Bool {
try Bcrypt.verify(password, created: self.password)
}
}
extension CredentialsUser: ModelSessionAuthenticatable {}
| mit | b930649e4969d785b7f2906546ed7a41 | 34.525316 | 108 | 0.61803 | 4.60082 | false | true | false | false |
qutheory/fluent | Tests/FluentTests/OperatorTests.swift | 2 | 1849 | import Fluent
import Vapor
import XCTVapor
final class OperatorTests: XCTestCase {
func testCustomOperators() throws {
let db = DummyDatabase()
// name contains string anywhere, prefix, suffix
_ = Planet.query(on: db)
.filter(\.$name ~~ "art")
_ = Planet.query(on: db)
.filter(\.$name =~ "art")
_ = Planet.query(on: db)
.filter(\.$name ~= "art")
// name doesn't contain string anywhere, prefix, suffix
_ = Planet.query(on: db)
.filter(\.$name !~ "art")
_ = Planet.query(on: db)
.filter(\.$name !=~ "art")
_ = Planet.query(on: db)
.filter(\.$name !~= "art")
// name in array
_ = Planet.query(on: db)
.filter(\.$name ~~ ["Earth", "Mars"])
// name not in array
_ = Planet.query(on: db)
.filter(\.$name !~ ["Earth", "Mars"])
}
}
private final class Planet: Model {
static let schema = "planets"
@ID(custom: .id)
var id: Int?
@Field(key: "name")
var name: String
}
private struct DummyDatabase: Database {
var inTransaction: Bool {
false
}
var context: DatabaseContext {
fatalError()
}
func execute(query: DatabaseQuery, onOutput: @escaping (DatabaseOutput) -> ()) -> EventLoopFuture<Void> {
fatalError()
}
func execute(schema: DatabaseSchema) -> EventLoopFuture<Void> {
fatalError()
}
func execute(enum: DatabaseEnum) -> EventLoopFuture<Void> {
fatalError()
}
func withConnection<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> {
fatalError()
}
func transaction<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> {
fatalError()
}
}
| mit | df87bb9dbd022ee42bc2213f3ef7ef5d | 25.414286 | 109 | 0.548945 | 4.028322 | false | false | false | false |
touchbar/Touch-Bar-Preview | Touch Bar Preview/Touch Bar Preview/WindowController.swift | 1 | 3145 | //
// WindowController.swift
// Touch Bar Preview
//
// This Software is released under the MIT License
//
// Copyright (c) 2017 Alexander Käßner
//
// 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.
//
// For more information see: https://github.com/touchbar/Touch-Bar-Preview
//
import Cocoa
class WindowController: NSWindowController {
@IBOutlet var touchBarImageView: NSImageView!
@IBOutlet weak var emptyLabel: NSTextField!
@IBOutlet weak var imageViewSpaceConstraintLeft: NSLayoutConstraint!
@IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
var titlebarAccessoryViewController : NSTitlebarAccessoryViewController!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
if let ddvc: ViewController = self.window?.contentViewController as? ViewController {
ddvc.windowDelegate = self
}
// Accessory view controller to hold the "Download UI Kit" button as part of the window's titlebar.
titlebarAccessoryViewController = storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "titleBarAccessory")) as? NSTitlebarAccessoryViewController
titlebarAccessoryViewController.layoutAttribute = .right
self.window?.addTitlebarAccessoryViewController(self.titlebarAccessoryViewController)
}
// MARK: - Touch Bar
@available(OSX 10.12.2, *)
func showImageInTouchBar(_ url: URL) {
//print(url)
if let touchbarImage = NSImage(contentsOf:url) {
touchBarImageView.image = touchbarImage
if touchbarImage.size.width == TouchBarSizes.fullWidth || touchbarImage.size.width == TouchBarSizes.fullWidth/2 {
imageViewSpaceConstraintLeft.constant = -TouchBarSizes.systemButtonWidth-TouchBarSizes.regionSpace
}
emptyLabel.isHidden = true
}
}
}
| mit | 1d0e31104ba63c422a0b4a2813796e16 | 40.355263 | 190 | 0.715558 | 4.934066 | false | false | false | false |
Codility-BMSTU/Codility | Codility/Codility/OBJKHCodeParser.swift | 1 | 2491 | //
// OBJKHCodeParser.swift
// OpenBank
//
// Created by Aleksander Evtuhov on 17/09/2017.
// Copyright © 2017 Aleksander Evtuhov. All rights reserved.
//
import Foundation
class OBJKHCodeParser{
static var ex = "ST00012|Name=Филиал \"КолАтомЭнергоСбыт\" АтомЭнергоСбыт|PersonalAcc=40702810300010006644| BankName=Центральный филиал АБ РОССИЯ|BIC=044599132|CorrespAcc=30101810400000000132|PersAcc=514100595728|Sum=49208|PayeeINN=519043001|PayerINN=519043001|PaymPeriod=СЕНТЯБРЬ 2015|TechCode=02"
static func validateCode(code: String) -> Bool {
return code.contains("PersonalAcc=") &&
code.contains("BankName=") &&
code.contains("PayerINN=") &&
code.contains("Sum=") &&
code.contains("BIC=") &&
code.contains("CorrespAcc=")
}
static func getAccountDictionary(code:String)->Dictionary<String, String>{
var mapperDictionary: Dictionary<String, String> = [
"INNTextFieled" : "PayerINN=",
"accountTextFieled" : "PersonalAcc=",
"BIKtextFieled" : "BIC=",
"corpAccountTextFieled" : "CorrespAcc=",
"bankNameTextFieled" : "BankName=",
"sumTextFieled" : "Sum="
]
var accountDictionary: Dictionary<String, String> = [
"INNTextFieled" : "",
"accountTextFieled" : "",
"BIKtextFieled" : "",
"corpAccountTextFieled" : "",
"bankNameTextFieled" : "",
"sumTextFieled" : ""
]
var parameterStringArray = code.components(separatedBy: "|")
for key in accountDictionary.keys{
var mappedParameterName = mapperDictionary[key]
for varString in parameterStringArray{
if varString.contains(mappedParameterName!){
accountDictionary[key] = varString.replacingOccurrences(of: mappedParameterName!, with: "")
}
}
}
return accountDictionary
}
static func parseCode(code:String)->Dictionary<String, String>?{
if(validateCode(code: code)){
return getAccountDictionary(code:code)
}else{
return nil
}
}
static func test(){
var dic = parseCode(code: ex)
print(dic)
}
}
| apache-2.0 | 2424ffc5e841b86936e783d236a3c651 | 31.266667 | 302 | 0.57438 | 3.88443 | false | false | false | false |
katzbenj/MeBoard | Keyboard/DeleteViewController.swift | 2 | 3880 | //
// File.swift
// MeBoard
//
// Created by Benjamin Katz on 12/9/16.
// Copyright © 2016 Apple. All rights reserved.
//
import Foundation
import Foundation
import UIKit
class DeleteViewController: UIViewController{
let parentView:UIView
var warningView:PassThroughView
var warningTitle:UILabel
var warningMessage:UILabel
var cancelButton:UIButton
var deleteButton:UIButton
init(view: UIView, type:String, name:String)
{
self.parentView = view
self.warningView = PassThroughView()
self.warningTitle = UILabel()
self.warningMessage = UILabel()
self.cancelButton = UIButton()
self.deleteButton = UIButton()
super.init(nibName: nil, bundle: nil)
let largeFont = CGFloat(30)
let fontSize = CGFloat(22)
self.warningView.layer.cornerRadius = 20
self.warningView.backgroundColor = UIColor.white
self.warningView.layer.borderColor = UIColor.gray.cgColor
self.warningView.layer.borderWidth = 1
self.warningView.isUserInteractionEnabled = true
self.parentView.addSubview(self.warningView)
self.parentView.bringSubview(toFront: self.warningView)
self.warningTitle.font = UIFont.boldSystemFont(ofSize: largeFont)
self.warningTitle.adjustsFontSizeToFitWidth = true
self.warningTitle.textAlignment = .center
self.warningTitle.text = "Warning"
self.warningView.addSubview(self.warningTitle)
self.warningMessage.font = UIFont.systemFont(ofSize: fontSize)
self.warningMessage.textAlignment = .center
self.warningMessage.adjustsFontSizeToFitWidth = true
self.warningMessage.numberOfLines = 0
self.warningMessage.text = "Are you sure you would like to delete the \(type):\n\(name)"
self.warningView.addSubview(self.warningMessage)
self.cancelButton.setTitle("Cancel", for: .normal)
self.cancelButton.isEnabled = true
self.cancelButton.isUserInteractionEnabled = true
self.cancelButton.setTitleColor(UIColor.init(red: 20/255, green: 123/255, blue: 255/255, alpha: 1), for: UIControlState.normal)
self.cancelButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: largeFont)
self.warningView.addSubview(self.cancelButton)
self.deleteButton.setTitle("Delete", for: .normal)
self.deleteButton.setTitleColor(UIColor.red, for: UIControlState.normal)
self.deleteButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: largeFont)
self.warningView.addSubview(self.deleteButton)
let warningViewWidth = (self.parentView.frame.maxX - self.parentView.frame.minX) * CGFloat(0.75)
let warningViewHeight = (self.parentView.frame.maxY - self.parentView.frame.minY) * CGFloat(0.9)
self.warningView.frame = CGRect(x: self.parentView.frame.midX - warningViewWidth / CGFloat(2), y: self.parentView.frame.midY - warningViewHeight / CGFloat(2), width: warningViewWidth, height: warningViewHeight)
self.warningTitle.frame = CGRect(x: 0, y: 0, width: warningViewWidth, height: warningViewHeight / CGFloat(4))
self.warningMessage.frame = CGRect(x: 0, y: self.warningTitle.frame.maxY, width: warningViewWidth, height: warningViewHeight / CGFloat(2))
self.cancelButton.frame = CGRect(x: 0, y: self.warningMessage.frame.maxY, width: warningViewWidth / CGFloat(2), height: warningViewHeight / CGFloat(4))
self.deleteButton.frame = CGRect(x: self.cancelButton.frame.maxX, y: self.warningMessage.frame.maxY, width: warningViewWidth / CGFloat(2), height: warningViewHeight / CGFloat(4))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| bsd-3-clause | 8120c3b026b6495d3ca74f8b30d54e8f | 42.1 | 218 | 0.690126 | 4.428082 | false | false | false | false |
teacurran/alwaysawake-ios | Pods/p2.OAuth2/Sources/Base/OAuth2Base.swift | 2 | 12274 | //
// OAuth2Base.swift
// OAuth2
//
// Created by Pascal Pfiffner on 6/2/15.
// Copyright 2015 Pascal Pfiffner
//
// 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
/// Typealias to ease working with JSON dictionaries.
public typealias OAuth2JSON = [String: AnyObject]
/// Typealias to work with dictionaries full of strings.
public typealias OAuth2StringDict = [String: String]
/// Typealias to work with headers
public typealias OAuth2Headers = [String: String]
/**
Abstract base class for OAuth2 authorization as well as client registration classes.
*/
public class OAuth2Base {
/// Server-side settings, as set upon initialization.
final let settings: OAuth2JSON
/// Set to `true` to log all the things. `false` by default. Use `"verbose": bool` in settings or assign `logger` yourself.
public var verbose = false {
didSet {
logger = verbose ? OAuth2DebugLogger() : nil
}
}
/// The logger being used. Auto-assigned to a debug logger if you set `verbose` to true or false.
public var logger: OAuth2Logger?
/// If set to `true` (the default) will use system keychain to store tokens. Use `"keychain": bool` in settings.
public var useKeychain = true {
didSet {
if useKeychain {
updateFromKeychain()
}
}
}
/// The keychain account to use to store tokens. Defaults to "currentTokens".
public var keychainAccountForTokens = "currentTokens" {
didSet {
assert(!keychainAccountForTokens.isEmpty)
}
}
/// The keychain account name to use to store client credentials. Defaults to "clientCredentials".
public var keychainAccountForClientCredentials = "clientCredentials" {
didSet {
assert(!keychainAccountForClientCredentials.isEmpty)
}
}
/// Defaults to `kSecAttrAccessibleWhenUnlocked`
public internal(set) var keychainAccessMode = kSecAttrAccessibleWhenUnlocked
/**
Base initializer.
Looks at the `keychain`, `keychain_access_mode` and `verbose` keys in the _settings_ dict. Everything else is handled by subclasses.
*/
public init(settings: OAuth2JSON) {
self.settings = settings
// client settings
if let keychain = settings["keychain"] as? Bool {
useKeychain = keychain
}
if let accessMode = settings["keychain_access_mode"] as? String {
keychainAccessMode = accessMode
}
if let verb = settings["verbose"] as? Bool {
verbose = verb
if verbose {
logger = OAuth2DebugLogger()
}
}
// init from keychain
if useKeychain {
updateFromKeychain()
}
logger?.debug("OAuth2", msg: "Initialization finished")
}
// MARK: - Keychain Integration
/** The service key under which to store keychain items. Returns "http://localhost", subclasses override to return the authorize URL. */
public func keychainServiceName() -> String {
return "http://localhost"
}
/** Queries the keychain for tokens stored for the receiver's authorize URL, and updates the token properties accordingly. */
private func updateFromKeychain() {
logger?.debug("OAuth2", msg: "Looking for items in keychain")
do {
var creds = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials)
let creds_data = try creds.fetchedFromKeychain()
updateFromKeychainItems(creds_data)
}
catch {
logger?.warn("OAuth2", msg: "Failed to load client credentials from keychain: \(error)")
}
do {
var toks = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens)
let toks_data = try toks.fetchedFromKeychain()
updateFromKeychainItems(toks_data)
}
catch {
logger?.warn("OAuth2", msg: "Failed to load tokens from keychain: \(error)")
}
}
/** Updates instance properties according to the items found in the given dictionary, which was found in the keychain. */
func updateFromKeychainItems(items: [String: NSCoding]) {
}
/**
Items that should be stored when storing client credentials.
- returns: A dictionary with `String` keys and `NSCoding` adopting items
*/
public func storableCredentialItems() -> [String: NSCoding]? {
return nil
}
/** Stores our client credentials in the keychain. */
internal func storeClientToKeychain() {
if let items = storableCredentialItems() {
logger?.debug("OAuth2", msg: "Storing client credentials to keychain")
let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials, data: items)
do {
try keychain.saveInKeychain()
}
catch {
logger?.warn("OAuth2", msg: "Failed to store client credentials to keychain: \(error)")
}
}
}
/**
Items that should be stored when tokens are stored to the keychain.
- returns: A dictionary with `String` keys and `NSCoding` adopting items
*/
public func storableTokenItems() -> [String: NSCoding]? {
return nil
}
/** Stores our current token(s) in the keychain. */
internal func storeTokensToKeychain() {
if let items = storableTokenItems() {
logger?.debug("OAuth2", msg: "Storing tokens to keychain")
let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens, data: items)
do {
try keychain.saveInKeychain()
}
catch {
logger?.warn("OAuth2", msg: "Failed to store tokens to keychain: \(error)")
}
}
}
/** Unsets the client credentials and deletes them from the keychain. */
public func forgetClient() {
logger?.debug("OAuth2", msg: "Forgetting client credentials and removing them from keychain")
let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForClientCredentials)
do {
try keychain.removeFromKeychain()
}
catch {
logger?.warn("OAuth2", msg: "Failed to delete credentials from keychain: \(error)")
}
}
/** Unsets the tokens and deletes them from the keychain. */
public func forgetTokens() {
logger?.debug("OAuth2", msg: "Forgetting tokens and removing them from keychain")
let keychain = OAuth2KeychainAccount(oauth2: self, account: keychainAccountForTokens)
do {
try keychain.removeFromKeychain()
}
catch {
logger?.warn("OAuth2", msg: "Failed to delete tokens from keychain: \(error)")
}
}
// MARK: - Requests
/// The instance's current session, creating one by the book if necessary. Defaults to using an ephemeral session, you can use
/// `sessionConfiguration` and/or `sessionDelegate` to affect how the session is configured.
public var session: NSURLSession {
if nil == _session {
let config = sessionConfiguration ?? NSURLSessionConfiguration.ephemeralSessionConfiguration()
_session = NSURLSession(configuration: config, delegate: sessionDelegate, delegateQueue: nil)
}
return _session!
}
/// The backing store for `session`.
private var _session: NSURLSession?
/// The configuration to use when creating `session`. Uses an `+ephemeralSessionConfiguration()` if nil.
public var sessionConfiguration: NSURLSessionConfiguration? {
didSet {
_session = nil
}
}
/// URL session delegate that should be used for the `NSURLSession` the instance uses for requests.
public var sessionDelegate: NSURLSessionDelegate? {
didSet {
_session = nil
}
}
/**
Perform the supplied request and call the callback with the response JSON dict or an error. This method is intended for authorization
calls, not for data calls outside of the OAuth2 dance.
This implementation uses the shared `NSURLSession` and executes a data task. If the server responds with an error, this will be
converted into an error according to information supplied in the response JSON (if availale).
- parameter request: The request to execute
- parameter callback: The callback to call when the request completes/fails; data and error are mutually exclusive
*/
public func performRequest(request: NSURLRequest, callback: ((data: NSData?, status: Int?, error: ErrorType?) -> Void)) {
self.logger?.trace("OAuth2", msg: "REQUEST\n\(request.debugDescription)\n---")
let task = session.dataTaskWithRequest(request) { sessData, sessResponse, error in
self.abortableTask = nil
self.logger?.trace("OAuth2", msg: "RESPONSE\n\(sessResponse?.debugDescription ?? "no response")\n\n\(NSString(data: sessData ?? NSData(), encoding: NSUTF8StringEncoding) ?? "no data")\n---")
if let error = error {
if NSURLErrorDomain == error.domain && -999 == error.code { // request was cancelled
callback(data: nil, status: nil, error: OAuth2Error.RequestCancelled)
}
else {
callback(data: nil, status: nil, error: error)
}
}
else if let data = sessData, let http = sessResponse as? NSHTTPURLResponse {
callback(data: data, status: http.statusCode, error: nil)
}
else {
let error = OAuth2Error.Generic("Unknown response \(sessResponse) with data “\(NSString(data: sessData!, encoding: NSUTF8StringEncoding))”")
callback(data: nil, status: nil, error: error)
}
}
abortableTask = task
task.resume()
}
/// Currently running abortable session task.
private var abortableTask: NSURLSessionTask?
/**
Can be called to immediately abort the currently running authorization request, if it was started by `performRequest()`.
- returns: A bool indicating whether a task was aborted or not
*/
func abortTask() -> Bool {
guard let task = abortableTask else {
return false
}
logger?.debug("OAuth2", msg: "Aborting request")
task.cancel()
return true
}
// MARK: - Response Verification
/**
Handles access token error response.
- parameter params: The URL parameters returned from the server
- parameter fallback: The message string to use in case no error description is found in the parameters
- returns: An OAuth2Error
*/
public func assureNoErrorInResponse(params: OAuth2JSON, fallback: String? = nil) throws {
// "error_description" is optional, we prefer it if it's present
if let err_msg = params["error_description"] as? String {
throw OAuth2Error.ResponseError(err_msg)
}
// the "error" response is required for error responses, so it should be present
if let err_code = params["error"] as? String {
throw OAuth2Error.fromResponseError(err_code, fallback: fallback)
}
}
// MARK: - Utilities
/**
Parse string-only JSON from NSData.
- parameter data: NSData returned from the call, assumed to be JSON with string-values only.
- returns: An OAuth2JSON instance
*/
func parseJSON(data: NSData) throws -> OAuth2JSON {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? OAuth2JSON {
return json
}
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) {
logger?.warn("OAuth2", msg: "Unparsable JSON was: \(str)")
}
throw OAuth2Error.JSONParserError
}
/**
Parse a query string into a dictionary of String: String pairs.
If you're retrieving a query or fragment from NSURLComponents, use the `percentEncoded##` variant as the others
automatically perform percent decoding, potentially messing with your query string.
- parameter query: The query string you want to have parsed
- returns: A dictionary full of strings with the key-value pairs found in the query
*/
public final class func paramsFromQuery(query: String) -> OAuth2StringDict {
let parts = query.characters.split() { $0 == "&" }.map() { String($0) }
var params = OAuth2StringDict(minimumCapacity: parts.count)
for part in parts {
let subparts = part.characters.split() { $0 == "=" }.map() { String($0) }
if 2 == subparts.count {
params[subparts[0]] = subparts[1].wwwFormURLDecodedString
}
}
return params
}
}
/**
Helper function to ensure that the callback is executed on the main thread.
*/
func callOnMainThread(callback: (Void -> Void)) {
if NSThread.isMainThread() {
callback()
}
else {
dispatch_sync(dispatch_get_main_queue(), callback)
}
}
| apache-2.0 | e84eaa809cb507e5a73c21b23268371a | 31.983871 | 193 | 0.717196 | 3.936477 | false | false | false | false |
tehprofessor/SwiftyFORM | Example/Usecases/ReportViewController.swift | 1 | 4003 | // MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved.
import UIKit
import MessageUI
import SwiftyFORM
class ReportViewController: FormViewController, MFMailComposeViewControllerDelegate {
let sendButton = ButtonFormItem()
override func populate(builder: FormBuilder) {
configureButton()
builder.navigationTitle = "Report"
builder.demo_showInfo("Report a problem\nTroubleshooting\nNeed help")
builder += SectionHeaderTitleFormItem().title("Send report to the developer")
builder += sendButton
builder += SectionHeaderTitleFormItem().title("Device info")
builder += deviceName()
builder += systemVersion()
builder += SectionHeaderTitleFormItem().title("App info")
builder += appName()
builder += appVersion()
builder += appBuild()
}
func configureButton() {
sendButton.title("Send Now!")
sendButton.action = { [weak self] in
self?.sendMail()
}
}
static func platformModelString() -> String? {
if let key = "hw.machine".cStringUsingEncoding(NSUTF8StringEncoding) {
var size: Int = 0
sysctlbyname(key, nil, &size, nil, 0)
var machine = [CChar](count: Int(size), repeatedValue: 0)
sysctlbyname(key, &machine, &size, nil, 0)
return String.fromCString(machine)!
}
return nil
}
func deviceName() -> StaticTextFormItem {
let string = ReportViewController.platformModelString() ?? "N/A"
return StaticTextFormItem().title("Device").value(string)
}
func systemVersion() -> StaticTextFormItem {
let string: String = UIDevice.currentDevice().systemVersion
return StaticTextFormItem().title("iOS").value(string)
}
func appName() -> StaticTextFormItem {
let mainBundle = NSBundle.mainBundle()
let string0 = mainBundle.objectForInfoDictionaryKey("CFBundleDisplayName") as? String
let string1 = mainBundle.objectForInfoDictionaryKey(kCFBundleNameKey as String) as? String
let string = string0 ?? string1 ?? "Unknown"
return StaticTextFormItem().title("Name").value(string)
}
func appVersion() -> StaticTextFormItem {
let mainBundle = NSBundle.mainBundle()
let string0 = mainBundle.objectForInfoDictionaryKey("CFBundleShortVersionString") as? String
let string = string0 ?? "Unknown"
return StaticTextFormItem().title("Version").value(string)
}
func appBuild() -> StaticTextFormItem {
let mainBundle = NSBundle.mainBundle()
let string0 = mainBundle.objectForInfoDictionaryKey(kCFBundleVersionKey as String) as? String
let string = string0 ?? "Unknown"
return StaticTextFormItem().title("Build").value(string)
}
func sendMail() {
if MFMailComposeViewController.canSendMail() {
let mc = configuredMailComposeViewController()
presentViewController(mc, animated: true, completion: nil)
} else {
form_simpleAlert("Could Not Send Mail", "Your device could not send mail. Please check mail configuration and try again.")
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let emailTitle = "Report"
let messageBody = "This is a test email body"
let toRecipents = ["[email protected]"]
let mc = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(emailTitle)
mc.setMessageBody(messageBody, isHTML: false)
mc.setToRecipients(toRecipents)
return mc
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
dismissViewControllerAnimated(false) { [weak self] in
self?.showMailResultAlert(result, error: error)
}
}
func showMailResultAlert(result: MFMailComposeResult, error: NSError?) {
switch result.rawValue {
case MFMailComposeResultCancelled.rawValue:
form_simpleAlert("Status", "Mail cancelled")
case MFMailComposeResultSaved.rawValue:
form_simpleAlert("Status", "Mail saved")
case MFMailComposeResultSent.rawValue:
form_simpleAlert("Status", "Mail sent")
case MFMailComposeResultFailed.rawValue:
form_simpleAlert("Mail failed", "error: \(error)")
default:
break
}
}
}
| mit | 95ae7229dc8963df858e1208486c3f48 | 32.923729 | 136 | 0.745941 | 4.191623 | false | false | false | false |
motylevm/skstylekit | StyleKitTests/SKImageViewTests.swift | 1 | 2232 | //
// Copyright (c) 2016 Mikhail Motylev https://twitter.com/mikhail_motylev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import XCTest
@testable import SKStyleKit
class SKImageViewTests: XCTestCase {
override func setUp() {
super.setUp()
basicSetup()
}
func testSetStyle() {
// given
let style = StyleKit.style(withName: "viewStyle")
let view = SKImageView()
// when
view.style = style
// then
XCTAssertNotNil(style)
XCTAssertEqual(view.styleName, "viewStyle")
checkViewStyle(view)
}
func testSetStyleByName() {
// given
let view = SKImageView()
// when
view.styleName = "viewStyle"
// then
XCTAssertNotNil(view.style)
checkViewStyle(view)
}
func testSetStyleByFullName() {
// given
let view = SKImageView()
// when
view.styleName = "controls.viewStyle"
// then
XCTAssertNotNil(view.style)
checkViewStyle(view)
}
}
| mit | 6381a32f408cddb6066a2ca4776bfbb7 | 30 | 86 | 0.629928 | 4.779443 | false | true | false | false |
eselkin/DirectionFieldiOS | Pods/GRDB.swift/GRDB/Core/Protocols/DatabaseValueConvertible.swift | 1 | 12075 | // MARK: - DatabaseValueConvertible
/// Types that adopt DatabaseValueConvertible can be initialized from
/// database values.
///
/// The protocol comes with built-in methods that allow to fetch sequences,
/// arrays, or single values:
///
/// String.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String?>
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// String.fetch(statement, arguments:...) // DatabaseSequence<String?>
/// String.fetchAll(statement, arguments:...) // [String?]
/// String.fetchOne(statement, arguments:...) // String?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public protocol DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from *databaseValue*, if possible.
///
/// - parameter databaseValue: A DatabaseValue.
/// - returns: An optional Self.
static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self?
}
// MARK: - Fetching DatabaseValueConvertible
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// sequences, arrays, or single values:
///
/// String.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String>
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// String.fetch(statement, arguments:...) // DatabaseSequence<String>
/// String.fetchAll(statement, arguments:...) // [String]
/// String.fetchOne(statement, arguments:...) // String
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public extension DatabaseValueConvertible {
// MARK: - Fetching From SelectStatement
/// Returns a sequence of values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let names = String.fetch(statement) // DatabaseSequence<String>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = String.fetch(statement)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - returns: A sequence.
public static func fetch(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Self> {
let sqliteStatement = statement.sqliteStatement
return statement.fetch(arguments: arguments) {
let dbv = DatabaseValue(sqliteStatement: sqliteStatement, index: 0)
guard let value = Self.fromDatabaseValue(dbv) else {
if let arguments = statement.arguments {
fatalError("Could not convert \(dbv) to \(Self.self) while iterating `\(statement.sql)` with arguments \(arguments).")
} else {
fatalError("Could not convert \(dbv) to \(Self.self) while iterating `\(statement.sql)`.")
}
}
return value
}
}
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let names = String.fetchAll(statement) // [String]
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - returns: An array.
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> [Self] {
return Array(fetch(statement, arguments: arguments))
}
/// Returns a single value fetched from a prepared statement.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let name = String.fetchOne(statement) // String?
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - returns: An optional value.
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> Self? {
let sequence: DatabaseSequence<Self?> = statement.fetch(arguments: arguments) {
fromDatabaseValue(DatabaseValue(sqliteStatement: statement.sqliteStatement, index: 0))
}
var generator = sequence.generate()
if let value = generator.next() { // Unwrap Self? from Self??
return value
}
return nil
}
// MARK: - Fetching From Database
/// Returns a sequence of values fetched from an SQL query.
///
/// let names = String.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = String.fetch(db, "SELECT name FROM ...")
/// Array(names) // Arthur, Barbara
/// execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - returns: A sequence.
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Self> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
}
/// Returns an array of values fetched from an SQL query.
///
/// let names = String.fetchAll(db, "SELECT name FROM ...") // [String]
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - returns: An array.
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> [Self] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
/// Returns a single value fetched from an SQL query.
///
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let name = String.fetchOne(db, "SELECT name FROM ...") // String?
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - returns: An optional value.
public static func fetchOne(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> Self? {
return fetchOne(try! db.selectStatement(sql), arguments: arguments)
}
}
// MARK: - Fetching optional DatabaseValueConvertible
/// Swift's Optional comes with built-in methods that allow to fetch sequences
/// and arrays of optional DatabaseValueConvertible:
///
/// Optional<String>.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String?>
/// Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// Optional<String>.fetch(statement, arguments:...) // DatabaseSequence<String?>
/// Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: - Fetching From SelectStatement
/// Returns a sequence of optional values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let names = Optional<String>.fetch(statement) // DatabaseSequence<String?>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = Optional<String>.fetch(statement)
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - returns: A sequence of optional values.
public static func fetch(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Wrapped?> {
let sqliteStatement = statement.sqliteStatement
return statement.fetch(arguments: arguments) {
Wrapped.fromDatabaseValue(DatabaseValue(sqliteStatement: sqliteStatement, index: 0))
}
}
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = db.selectStatement("SELECT name FROM ...")
/// let names = Optional<String>.fetchAll(statement) // [String?]
///
/// - parameter statement: The statement to run.
/// - parameter arguments: Statement arguments.
/// - returns: An array of optional values.
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments = StatementArguments.Default) -> [Wrapped?] {
return Array(fetch(statement, arguments: arguments))
}
// MARK: - Fetching From Database
/// Returns a sequence of optional values fetched from an SQL query.
///
/// let names = Optional<String>.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String?>
///
/// The returned sequence can be consumed several times, but it may yield
/// different results, should database changes have occurred between two
/// generations:
///
/// let names = Optional<String>.fetch(db, "SELECT name FROM ...")
/// Array(names) // Arthur, Barbara
/// db.execute("DELETE ...")
/// Array(names) // Arthur
///
/// If the database is modified while the sequence is iterating, the
/// remaining elements are undefined.
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - returns: A sequence of optional values.
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> DatabaseSequence<Wrapped?> {
return fetch(try! db.selectStatement(sql), arguments: arguments)
}
/// Returns an array of optional values fetched from an SQL query.
///
/// let names = String.fetchAll(db, "SELECT name FROM ...") // [String?]
///
/// - parameter db: A Database.
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - returns: An array of optional values.
public static func fetchAll(db: Database, _ sql: String, arguments: StatementArguments = StatementArguments.Default) -> [Wrapped?] {
return fetchAll(try! db.selectStatement(sql), arguments: arguments)
}
}
| gpl-3.0 | 24a336c7e20739c72ad1ac4a3ae55115 | 43.888476 | 149 | 0.637516 | 4.839679 | false | false | false | false |
XSega/Words | Words/Scenes/Trainings/EngRuTraining/TrainingInteractor.swift | 1 | 3931 | //
// EngRuTrainingInteractor.swift
// Words
//
// Created by Sergey Ilyushin on 30/07/2017.
// Copyright (c) 2017 Sergey Ilyushin. All rights reserved.
//
import UIKit
protocol ITrainingInteractor {
func start()
func checkVariantIndex(_ index: Int)
func skipMeaning()
func listenAgain()
}
class TrainingInteractor: ITrainingInteractor, ITrainingDataStore {
var presenter: ITrainingPresenter!
// MARK: Training vars
var meanings: [Meaning]!
var mistakes: Int = 0
var words: Int = 0
var learnedIdentifiers = [Int]()
// MARK: Private vars
fileprivate var currentMeaningIndex: Int = 0
fileprivate var currentCorrectIndex: Int = 0
fileprivate var currentVariants: [Variant]!
// MARK: IEngRuTrainingInteractor
func start() {
currentMeaningIndex = 0
mistakes = 0
words = 0
learnedIdentifiers.removeAll()
presentCurrentMeaning()
}
func finish() {
currentMeaningIndex = 0
presenter.presentFinish()
}
func checkVariantIndex(_ index: Int) {
let meaning = meanings[currentMeaningIndex]
if currentCorrectIndex == index {
didCorrectSelection(meaning: meaning, index: index)
} else {
didWrongSelection(meaning: meaning, correctIndex: currentCorrectIndex, wrongIndex: index)
}
}
func listenAgain() {
let meaning = meanings[currentMeaningIndex]
presenter.presentMeaningSound(meaning: meaning)
}
func skipMeaning(){
let meaning = meanings[currentMeaningIndex]
didSkipAction(meaning: meaning, correctIndex: currentCorrectIndex)
}
// MARK: Private func
fileprivate func didCorrectSelection(meaning: Meaning, index: Int) {
presentCorrectAlert(meaning: meaning, correctIndex: index)
learnedIdentifiers.append(meaning.identifier)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [unowned self] in
self.nextPair()
}
}
fileprivate func didWrongSelection(meaning: Meaning, correctIndex: Int, wrongIndex: Int) {
mistakes += 1
presentWrongAlert(meaning: meaning, correctIndex: correctIndex, wrongIndex: wrongIndex)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [unowned self] in
self.nextPair()
}
}
fileprivate func didSkipAction(meaning: Meaning, correctIndex: Int) {
mistakes += 1
presentSkipAlert(meaning: meaning, correctIndex: correctIndex)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [unowned self] in
self.nextPair()
}
}
fileprivate func nextPair() {
currentMeaningIndex += 1
guard currentMeaningIndex < meanings.count else {
finish()
return
}
presentCurrentMeaning()
}
fileprivate func presentCurrentMeaning() {
let meaning = meanings[currentMeaningIndex]
currentVariants = meaning.randomVariants()
if let index = currentVariants.map({$0.text}).index(of: meaning.text) {
currentCorrectIndex = index
}
presenter.present(meaning: meaning, variants: currentVariants)
words += 1
}
fileprivate func presentCorrectAlert(meaning: Meaning, correctIndex: Int) {
presenter.presentCorrectAlert(meaning: meaning, correctIndex: correctIndex)
}
fileprivate func presentWrongAlert(meaning: Meaning,correctIndex: Int, wrongIndex: Int) {
presenter.presentWrongAlert(meaning: meaning, correctIndex: correctIndex, wrongIndex: wrongIndex)
}
fileprivate func presentSkipAlert(meaning: Meaning, correctIndex: Int) {
presenter.presentSkipAlert(meaning: meaning, correctIndex: correctIndex)
}
}
| mit | 5b7f876717e75dcfeead8f8e1313a9d2 | 28.780303 | 105 | 0.638769 | 4.674197 | false | false | false | false |
Higgcz/Buildasaur | BuildaKit/SyncPair_Branch_NoBot.swift | 6 | 1181 | //
// SyncPair_Branch_NoBot.swift
// Buildasaur
//
// Created by Honza Dvorsky on 20/05/15.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import XcodeServerSDK
import BuildaGitServer
class SyncPair_Branch_NoBot: SyncPair {
let branch: Branch
let repo: Repo
init(branch: Branch, repo: Repo) {
self.branch = branch
self.repo = repo
super.init()
}
override func sync(completion: Completion) {
//create a bot for this branch
let syncer = self.syncer
let branch = self.branch
let repo = self.repo
SyncPair_Branch_NoBot.createBotForBranch(syncer: syncer, branch: branch, repo: repo, completion: completion)
}
override func syncPairName() -> String {
return "Branch (\(self.branch.name)) + No Bot"
}
//MARK: Internal
private class func createBotForBranch(syncer syncer: HDGitHubXCBotSyncer, branch: Branch, repo: Repo, completion: Completion) {
syncer.createBotFromBranch(branch, repo: repo, completion: { () -> () in
completion(error: nil)
})
}
}
| mit | 057687a4ec40b2af4066c58e78d786a0 | 24.673913 | 131 | 0.61812 | 4.278986 | false | false | false | false |
cpmpercussion/microjam | Pods/DropDown/DropDown/helpers/DPDConstants.swift | 1 | 1296 | //
// Constants.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
internal struct DPDConstant {
internal struct KeyPath {
static let Frame = "frame"
}
internal struct ReusableIdentifier {
static let DropDownCell = "DropDownCell"
}
internal struct UI {
static let TextColor = UIColor.black
static let SelectedTextColor = UIColor.black
static let TextFont = UIFont.systemFont(ofSize: 15)
static let BackgroundColor = UIColor(white: 0.94, alpha: 1)
static let SelectionBackgroundColor = UIColor(white: 0.89, alpha: 1)
static let SeparatorColor = UIColor.clear
static let CornerRadius: CGFloat = 2
static let RowHeight: CGFloat = 44
static let HeightPadding: CGFloat = 20
struct Shadow {
static let Color = UIColor.darkGray
static let Offset = CGSize.zero
static let Opacity: Float = 0.4
static let Radius: CGFloat = 8
}
}
internal struct Animation {
static let Duration = 0.15
static let EntranceOptions: UIView.AnimationOptions = [.allowUserInteraction, .curveEaseOut]
static let ExitOptions: UIView.AnimationOptions = [.allowUserInteraction, .curveEaseIn]
static let DownScaleTransform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}
}
| mit | 7851056c84ef269d5b8888efe04f4143 | 21.736842 | 94 | 0.725309 | 3.88024 | false | false | false | false |
noremac/Futures | Futures/FutureCache.swift | 1 | 6162 | /*
The MIT License (MIT)
Copyright (c) 2016 Cameron Pulsford
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
final public class FutureCache<T> {
public init() {
}
// MARK: - Adding items
/**
Adds a Future to the cache.
- parameter key: The key to store the Future by.
- parameter future: The Future to store.
*/
@discardableResult
public func add(_ key: String, future: Future<T>) -> Future<T> {
futureCacheQueue.async {
if let oldValue = self.cache[key] {
oldValue.cancel()
}
self.cache[key] = future
}
return future
}
/**
Adds a Future to the cache.
- parameter key: The key to store the Future by.
- parameter startDelay: Set this parameter to delay the execution of the Future. Optional.
- parameter work: The Future to store.
*/
@discardableResult
public func add(_ key: String, queue: DispatchQueue = GlobalFutureQueue, startDelay: TimeInterval? = nil, _ work: @autoclosure(escaping) () -> T) -> Future<T> {
return add(key, future: Future.success(queue: queue, startDelay: startDelay, work))
}
/**
Adds a default Future to the cache.
- parameter key: The key to store the Future by.
- parameter future: The Future to store.
*/
public func addDefault(_ key: String, future: Future<T>) -> Future<T> {
futureCacheQueue.async {
if let oldValue = self.defaultCache[key] {
oldValue.cancel()
}
self.defaultCache[key] = future
}
return future
}
/**
Adds a default Future to the cache.
- parameter key: The key to store the Future by.
- parameter startDelay: Set this parameter to delay the execution of the Future. Optional.
- parameter work: The Future to store.
*/
public func addDefault(_ key: String, queue: DispatchQueue = GlobalFutureQueue, startDelay: TimeInterval? = nil, _ work: @autoclosure(escaping) () -> T) -> Future<T> {
return addDefault(key, future: Future.success(queue: queue, startDelay: startDelay, work))
}
// MARK: - Removing items
/**
Cancels and removes a Future from the cache.
- parameter key: The key to remove.
*/
public func remove(_ key: String) {
futureCacheQueue.async {
if let future = self.cache[key] {
future.cancel()
self.cache.removeValue(forKey: key)
}
}
}
/**
Cancels and removes a default Future from the cache.
- parameter key: The key to remove.
*/
public func removeDefault(_ key: String) {
futureCacheQueue.async {
if let future = self.defaultCache[key] {
future.cancel()
self.defaultCache.removeValue(forKey: key)
}
}
}
/**
Cancels all Futures in the cache and then empties the cache.
*/
public func cancelAndRemoveAll() {
futureCacheQueue.sync {
for future in self.cache.values {
future.cancel()
}
for future in self.defaultCache.values {
future.cancel()
}
self.cache.removeAll()
self.defaultCache.removeAll()
}
}
// MARK: - Getters
/**
Returns the Future for the given key.
- parameter key: The key.
- returns: The future, or `nil`, for the given key.
*/
public func future(forKey key: String) -> Future<T>? {
var f: Future<T>?
futureCacheQueue.sync {
f = self.cache[key] ?? self.defaultCache[key]
}
return f
}
/**
Returns the Future's value, or `nil` if the future didn't exist.
- parameter key: The key.
- returns: The Future's value, or `nil` if the future didn't exist.
*/
public func result(forKey key: String) -> DerefValue<T>? {
return future(forKey: key)?.value
}
public func value(forKey key: String) -> T? {
return result(forKey: key)?.successValue
}
/**
Returns the Future's .Success value or the provided defaultValue if the Future was invalid or did not exist in the cache.
- parameter key: The key.
- parameter defaultValue: The default value to use if the Future was invalid or did not exist in the cache.
- returns: The Future's .Success value or the provided defaultValue if the Future was invalid or did not exist in the cache.
*/
public func valueForKey(_ key: String, defaultValue: @autoclosure () -> T) -> T {
return value(forKey: key) ?? defaultValue()
}
// MARK: - Subscript support.
public subscript(key: String) -> T? {
return value(forKey: key)
}
// MARK: - Private vars
private var cache = [String: Future<T>]()
private var defaultCache = [String: Future<T>]()
private var futureCacheQueue = DispatchQueue(label: "com.smd.Futures.FutureCacheQueue", attributes: DispatchQueueAttributes.serial)
}
| mit | 6230de2d26cac350c9fe97d19dd43e6d | 29.656716 | 171 | 0.62285 | 4.478198 | false | false | false | false |
bytor99999/WatchFlashLight | WatchLightFlash WatchKit Extension/ComplicationController.swift | 1 | 4691 | //
// ComplicationController.swift
// WatchLightFlash WatchKit Extension
//
// Created by Mark Spritzler on 8/19/15.
// Copyright © 2015 Perfect World Programming. All rights reserved.
//
import ClockKit
let flashlightImage = UIImage(named: "flashlight")!
let flashLightImageProvider = CLKImageProvider(onePieceImage: flashlightImage)
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.None])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(nil)
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(nil)
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
// Call the handler with the current timeline entry
let entry = CLKComplicationTimelineEntry()
switch complication.family {
case CLKComplicationFamily.CircularSmall :
let template = CLKComplicationTemplateCircularSmallSimpleImage()
template.imageProvider = flashLightImageProvider
entry.complicationTemplate = template
case CLKComplicationFamily.ModularSmall :
let template = CLKComplicationTemplateModularSmallSimpleImage()
template.imageProvider = flashLightImageProvider
entry.complicationTemplate = template
case CLKComplicationFamily.UtilitarianLarge :
let template = CLKComplicationTemplateUtilitarianLargeFlat()
template.imageProvider = flashLightImageProvider
entry.complicationTemplate = template
default:
let template = CLKComplicationTemplateUtilitarianSmallFlat()
template.imageProvider = flashLightImageProvider
entry.complicationTemplate = template
}
entry.date = NSDate()
handler(entry)
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
handler(nil)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
handler(nil);
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
switch complication.family {
case CLKComplicationFamily.CircularSmall :
let template = CLKComplicationTemplateCircularSmallSimpleImage()
template.imageProvider = flashLightImageProvider
handler(template)
case CLKComplicationFamily.ModularSmall :
let template = CLKComplicationTemplateModularSmallSimpleImage()
template.imageProvider = flashLightImageProvider
handler(template)
case CLKComplicationFamily.UtilitarianLarge :
let template = CLKComplicationTemplateUtilitarianLargeFlat()
template.imageProvider = flashLightImageProvider
template.textProvider = CLKSimpleTextProvider(text: "Flash Light")
handler(template)
default:
let template = CLKComplicationTemplateUtilitarianSmallFlat()
template.imageProvider = flashLightImageProvider
template.textProvider = CLKSimpleTextProvider(text: "Flash Light")
handler(template)
}
}
}
| gpl-2.0 | 56894999d47efa266f5db96b2d58dead | 39.431034 | 178 | 0.685928 | 6.596343 | false | false | false | false |
TongjiUAppleClub/WeCitizens | WeCitizens/LoginViewController.swift | 1 | 2392 | //
// ViewController.swift
// WeCitizens
//
// Created by Harold LIU on 2/4/16.
// Copyright © 2016 Tongji Apple Club. All rights reserved.
//
import UIKit
import ParseUI
class LoginViewController: PFLogInViewController {
override func viewDidLoad() {
super.viewDidLoad()
logInView?.signUpButton?.removeFromSuperview()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
ConfigureUI()
}
func ConfigureUI()
{
let offsetX = CGFloat(30)
let TheColor = UIColor.lxd_MainBlueColor()
// logo
var logoF = logInView?.logo?.frame
logoF?.origin.y -= 50
logInView?.logo?.frame = logoF!
var userframe = logInView?.usernameField?.frame
userframe!.size.width -= offsetX * 2
userframe?.origin.x += offsetX
userframe?.origin.y -= 20
logInView?.usernameField!.borderStyle = .None
logInView?.usernameField?.frame = userframe!
logInView?.usernameField!.layer.borderWidth = 1.3
logInView?.usernameField!.layer.borderColor = TheColor.CGColor
logInView?.usernameField!.layer.cornerRadius = (logInView?.usernameField?.frame.height)!/2
var passframe = userframe
passframe?.origin.y += (userframe?.size.height)! + 32
logInView?.passwordField?.borderStyle = .None
logInView?.passwordField?.frame = passframe!
logInView?.passwordField?.layer.cornerRadius = (logInView?.passwordField?.frame.height)!/2
logInView?.passwordField?.layer.borderColor = TheColor.CGColor
logInView?.passwordField?.layer.borderWidth = 1.3
var buttonF = logInView?.logInButton?.frame
buttonF?.origin.x += 50
buttonF?.size.width -= 100
buttonF?.size.height -= 10
buttonF?.origin.y += 20
logInView?.logInButton?.setBackgroundImage(nil, forState: .Normal)
logInView?.logInButton?.frame = buttonF!
logInView?.logInButton?.layer.borderWidth = 1.2
logInView?.logInButton?.layer.cornerRadius = (logInView?.logInButton?.frame.height)!/2
logInView?.logInButton?.layer.borderColor = TheColor.CGColor
logInView?.logInButton?.backgroundColor = TheColor
}
}
| mit | 443710e9448fb2e52e1a5a5d03902a92 | 30.051948 | 98 | 0.621497 | 4.889571 | false | false | false | false |
yskamoona/a-ds | Playground/w1/shuffle.playground/Contents.swift | 1 | 743 | /*
You are given an array and a random number generator. Shuffle the array.
*/
import UIKit
func random(upperLimit:Int) -> Int
{ return Int(arc4random_uniform(UInt32(upperLimit))) }
func shuffle(ogArr:Array<Int>) -> Array<Int>
{
var indicesArr = Array(1...ogArr.count-1)
var shuffledArr = ogArr
while indicesArr.count > 0
{
let randomIndex = random(upperLimit: indicesArr.count-1)
let index = indicesArr[randomIndex]
let tempElem = shuffledArr[index]
shuffledArr[index] = shuffledArr[0]
shuffledArr[0] = tempElem
indicesArr.remove(at: randomIndex)
}
return shuffledArr
}
shuffle(ogArr: [1, 5, 3, 76, 23, 34, 523, 25])
| mit | 64391308fc7ea24a0d69630d3009c992 | 21.515152 | 77 | 0.620458 | 3.660099 | false | false | false | false |
ArtisOracle/libSwiftCal | libSwiftCal/RecurrenceDate.swift | 1 | 5500 | //
// RecurrenceDate.swift
// libSwiftCal
//
// Created by Stefan Arambasich on 10/15/14.
//
// Copyright (c) 2014 Stefan Arambasich. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//func model__serializeRdates(rdates: [RecurrenceDate]) -> String {
// var result = ""
//
// result += kRDATE
//
// var didParams = false // Okay, so this logic here is a bit janky. Sorry.
//
// for r in rdates {
// if r.parameters.count > 0 && !didParams { // This is saying that only the first reminder's parameters get saved, so that applies for all in the array.
// result += kSEMICOLON
// didParams = true
// for p in r.parameters {
// result += p.serializeToiCal()
// }
// }
//
// if r === rdates.first { result += kCOLON } // 😕
// else { result += kCOMMA }
//
// var date: NSDate?
// var dateFormat = DateFormats.ISO8601UTC
//
// if let d = r.dateTime {
// date = d
// } else if let d = r.date {
// dateFormat = DateFormats.ISO8601Date
// date = d
// }
//
// if let d = date {
// result += d.toString(dateFormat: dateFormat)
// } else if let p = r.timePeriod {
// result += p.serializeToiCal()
// } else {
// fatalError("Invalid date or time period")
// }
// }
//
// result += kCRLF
//
// return result
//}
/**
DATE-TIME values for recurring events, to-dos, journal entries, or time zone
definitions.
*/
public class RecurrenceDate: Property {
/// The recurrence date
var date = [NSDate]()
/// The recurrence date time
var dateTime = [NSDate]()
/// The date values of the receiver, if applicable
public var value: [NSDate]? {
get {
if self.date.count > 0 {
return self.date
} else if self.dateTime.count > 0 {
return self.dateTime
}
return nil
} set {
if self.date.count > 0 {
self.date = newValue!
} else {
self.dateTime = newValue!
}
}
}
/// The recurrence time period (if this exists, value will exist and have only ONE value)
public private(set) var timePeriod = [TimePeriod]()
public required init() {
super.init()
}
public func isEmpty() -> Bool {
return self.value == nil || self.key == nil
}
// MARK: - NSCoding
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Serializable
public required init(dictionary: [String : AnyObject]) {
super.init(dictionary: dictionary)
if let timePers = dictionary[kPERIOD] as? [[String : AnyObject]] {
for t in timePers {
let timePer = TimePeriod(dictionary: t)
self.timePeriod.append(timePer)
}
}
}
public override var serializationKeys: [String] {
get {
return super.serializationKeys + [kDATE, kDATE_TIME, kPERIOD]
}
}
public override func serializeToiCal() -> String {
if self.isEmpty() { return String.Empty }
var result = String(kRDATE)
if self.parameters.count > 0 {
result += kSEMICOLON
result += self.serializeParameters()
}
result += kCOLON
if self.date.count > 0 {
for d in self.date {
if d !== self.date.first { result += kCOMMA }
result += d.toString(dateFormat: DateFormats.ISO8601Date)
}
} else if self.dateTime.count > 0 {
for d in self.dateTime {
if d !== self.dateTime.first { result += kCOMMA }
result += d.toString(timezone: NSTimeZone(forSecondsFromGMT: 0))
}
} else if self.timePeriod.count > 0 {
for p in self.timePeriod {
if p !== self.timePeriod.first { result += kCOMMA }
result += p.serializeToiCal()
}
}
result.foldiCalendarString()
result += kCRLF
return result
}
}
| mit | 13b7d48905f731a3ab8b4ce170847aff | 31.146199 | 160 | 0.552483 | 4.251353 | false | false | false | false |
shohei/firefox-ios | Client/Frontend/Home/RemoteTabsPanel.swift | 1 | 18207 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Account
import Shared
import SnapKit
import Storage
import Sync
import XCGLogger
// TODO: same comment as for SyncAuthState.swift!
private let log = XCGLogger.defaultInstance()
private struct RemoteTabsPanelUX {
static let HeaderHeight: CGFloat = SiteTableViewControllerUX.RowHeight // Not HeaderHeight!
static let RowHeight: CGFloat = SiteTableViewControllerUX.RowHeight
static let HeaderBackgroundColor = UIColor(rgb: 0xf8f8f8)
static let EmptyStateTitleFont = UIFont.boldSystemFontOfSize(15)
static let EmptyStateTitleTextColor = UIColor.darkGrayColor()
static let EmptyStateInstructionsFont = UIFont.systemFontOfSize(15)
static let EmptyStateInstructionsTextColor = UIColor.grayColor()
static let EmptyStateInstructionsWidth = 256
static let EmptyStateTopPaddingInBetweenItems: CGFloat = 8 // UX TODO I set this to 8 so that it all fits on landscape
static let EmptyStateSignInButtonColor = UIColor(red: 0.259, green: 0.49, blue: 0.831, alpha: 1.0)
static let EmptyStateSignInButtonTitleFont = UIFont.systemFontOfSize(20)
static let EmptyStateSignInButtonTitleColor = UIColor.whiteColor()
static let EmptyStateSignInButtonCornerRadius: CGFloat = 6
static let EmptyStateSignInButtonHeight = 56
static let EmptyStateSignInButtonWidth = 272
static let EmptyStateCreateAccountButtonFont = UIFont.systemFontOfSize(12)
}
private let RemoteClientIdentifier = "RemoteClient"
private let RemoteTabIdentifier = "RemoteTab"
class RemoteTabsPanel: UITableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var profile: Profile!
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier)
tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier)
tableView.rowHeight = RemoteTabsPanelUX.RowHeight
tableView.separatorInset = UIEdgeInsetsZero
tableView.delegate = nil
tableView.dataSource = nil
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: "SELrefresh", forControlEvents: UIControlEvents.ValueChanged)
view.backgroundColor = UIConstants.PanelBackgroundColor
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
refresh()
}
var tableViewDelegate: RemoteTabsPanelDataSource? {
didSet {
self.tableView.delegate = tableViewDelegate
self.tableView.dataSource = tableViewDelegate
}
}
func refresh() {
tableView.scrollEnabled = false
tableView.allowsSelection = false
tableView.tableFooterView = UIView(frame: CGRectZero)
// Short circuit if the user is not logged in
if profile.getAccount() == nil {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NotLoggedIn)
self.tableView.reloadData()
return
}
self.profile.getCachedClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in
if let clientAndTabs = result.successValue {
self.updateDelegateClientAndTabData(clientAndTabs)
}
// Otherwise, fetch the tabs cloud if its been more than 1 minute since last sync
let lastSyncTime = self.profile.prefs.timestampForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
if NSDate.now() - (lastSyncTime ?? 0) > OneMinuteInMilliseconds {
self.profile.getClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in
if let clientAndTabs = result.successValue {
self.profile.prefs.setTimestamp(NSDate.now(), forKey: PrefsKeys.KeyLastRemoteTabSyncTime)
self.updateDelegateClientAndTabData(clientAndTabs)
}
self.endRefreshing()
}
} else {
// If we failed before and didn't sync, show the failure delegate
if let failed = result.failureValue {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .FailedToSync)
}
self.endRefreshing()
}
}
}
func endRefreshing() {
self.refreshControl?.endRefreshing()
self.tableView.scrollEnabled = true
self.tableView.reloadData()
}
func updateDelegateClientAndTabData(clientAndTabs: [ClientAndTabs]) {
if clientAndTabs.count == 0 {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoClients)
} else {
let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 }
if nonEmptyClientAndTabs.count == 0 {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoTabs)
} else {
self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(homePanel: self, clientAndTabs: nonEmptyClientAndTabs)
self.tableView.allowsSelection = true
}
}
}
@objc private func SELrefresh() {
self.refreshControl?.beginRefreshing()
refresh()
}
}
enum RemoteTabsError {
case NotLoggedIn
case NoClients
case NoTabs
case FailedToSync
func localizedString() -> String {
switch self {
case NotLoggedIn:
return ""
case NoClients:
return "You currently don't have any other devices connected to Firefox Sync." // TODO L10N
case NoTabs:
return "You currently don't have any tabs open on your other Firefox-enabled devices." // TODO L10N
case FailedToSync:
return "There was a problem fetching tabs from the cloud. Please try again in a few moments." // TODO L10N
}
}
}
protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate {
}
class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource {
weak var homePanel: HomePanel?
private var clientAndTabs: [ClientAndTabs]
init(homePanel: HomePanel, clientAndTabs: [ClientAndTabs]) {
self.homePanel = homePanel
self.clientAndTabs = clientAndTabs
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.clientAndTabs.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.clientAndTabs[section].tabs.count
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return RemoteTabsPanelUX.HeaderHeight
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let clientTabs = self.clientAndTabs[section]
let client = clientTabs.client
let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(RemoteClientIdentifier) as! TwoLineHeaderFooterView
view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight)
view.textLabel.text = client.name
view.contentView.backgroundColor = RemoteTabsPanelUX.HeaderBackgroundColor
/*
* A note on timestamps.
* We have access to two timestamps here: the timestamp of the remote client record,
* and the set of timestamps of the client's tabs.
* Neither is "last synced". The client record timestamp changes whenever the remote
* client uploads its record (i.e., infrequently), but also whenever another device
* sends a command to that client -- which can be much later than when that client
* last synced.
* The client's tabs haven't necessarily changed, but it can still have synced.
* Ideally, we should save and use the modified time of the tabs record itself.
* This will be the real time that the other client uploaded tabs.
*/
let timestamp = clientTabs.approximateLastSyncTime()
let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.")
view.detailTextLabel.text = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString())
let image: UIImage?
if client.type == "desktop" {
image = UIImage(named: "deviceTypeDesktop")
image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list")
} else {
image = UIImage(named: "deviceTypeMobile")
image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list")
}
view.imageView.image = image
view.mergeAccessibilityLabels()
return view
}
private func tabAtIndexPath(indexPath: NSIndexPath) -> RemoteTab {
return clientAndTabs[indexPath.section].tabs[indexPath.item]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(RemoteTabIdentifier, forIndexPath: indexPath) as! TwoLineTableViewCell
let tab = tabAtIndexPath(indexPath)
cell.setLines(tab.title, detailText: tab.URL.absoluteString)
// TODO: Bug 1144765 - Populate image with cached favicons.
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let tab = tabAtIndexPath(indexPath)
if let homePanel = self.homePanel {
// It's not a bookmark, so let's call it Typed (which means History, too).
homePanel.homePanelDelegate?.homePanel(homePanel, didSelectURL: tab.URL, visitType: VisitType.Typed)
}
}
}
// MARK: -
class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource {
weak var homePanel: HomePanel?
var error: RemoteTabsError
init(homePanel: HomePanel, error: RemoteTabsError) {
self.homePanel = homePanel
self.error = error
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return tableView.bounds.height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch error {
case .NotLoggedIn:
let cell = RemoteTabsNotLoggedInCell(homePanel: homePanel)
return cell
default:
let cell = RemoteTabsErrorCell(error: self.error)
return cell
}
}
}
// MARK: -
class RemoteTabsErrorCell: UITableViewCell {
static let Identifier = "RemoteTabsErrorCell"
init(error: RemoteTabsError) {
super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier)
separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0)
let containerView = UIView()
contentView.addSubview(containerView)
let imageView = UIImageView()
imageView.image = UIImage(named: "emptySync")
containerView.addSubview(imageView)
imageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(containerView)
make.centerX.equalTo(containerView)
}
let instructionsLabel = UILabel()
instructionsLabel.font = RemoteTabsPanelUX.EmptyStateInstructionsFont
instructionsLabel.text = error.localizedString()
instructionsLabel.textAlignment = NSTextAlignment.Center
instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor
instructionsLabel.numberOfLines = 0
containerView.addSubview(instructionsLabel)
instructionsLabel.snp_makeConstraints({ (make) -> Void in
make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(containerView)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
})
containerView.snp_makeConstraints({ (make) -> Void in
// Let the container wrap around the content
make.top.equalTo(imageView.snp_top)
make.left.bottom.right.equalTo(instructionsLabel)
// And then center it in the overlay view that sits on top of the UITableView
make.center.equalTo(contentView)
})
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: -
class RemoteTabsNotLoggedInCell: UITableViewCell {
static let Identifier = "RemoteTabsNotLoggedInCell"
var homePanel: HomePanel?
init(homePanel: HomePanel?) {
super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier)
self.homePanel = homePanel
let containerView = UIView()
contentView.addSubview(containerView)
let imageView = UIImageView()
imageView.image = UIImage(named: "emptySync")
containerView.addSubview(imageView)
imageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(containerView)
make.centerX.equalTo(containerView)
}
let titleLabel = UILabel()
titleLabel.font = RemoteTabsPanelUX.EmptyStateTitleFont
titleLabel.text = NSLocalizedString("Welcome to Sync", comment: "See http://mzl.la/1Qtkf0j")
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor
containerView.addSubview(titleLabel)
titleLabel.snp_makeConstraints({ (make) -> Void in
make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(containerView)
})
let instructionsLabel = UILabel()
instructionsLabel.font = RemoteTabsPanelUX.EmptyStateInstructionsFont
instructionsLabel.text = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "See http://mzl.la/1Qtkf0j")
instructionsLabel.textAlignment = NSTextAlignment.Center
instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor
instructionsLabel.numberOfLines = 0
containerView.addSubview(instructionsLabel)
instructionsLabel.snp_makeConstraints({ (make) -> Void in
make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(containerView)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
})
let signInButton = UIButton()
signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor
signInButton.setTitle(NSLocalizedString("Sign in", comment: "See http://mzl.la/1Qtkf0j"), forState: .Normal)
signInButton.setTitleColor(RemoteTabsPanelUX.EmptyStateSignInButtonTitleColor, forState: .Normal)
signInButton.titleLabel?.font = RemoteTabsPanelUX.EmptyStateSignInButtonTitleFont
signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius
signInButton.clipsToBounds = true
signInButton.addTarget(self, action: "SELsignIn", forControlEvents: UIControlEvents.TouchUpInside)
containerView.addSubview(signInButton)
signInButton.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(containerView)
make.top.equalTo(instructionsLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth)
}
let createAnAccountButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
createAnAccountButton.setTitle(NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j"), forState: .Normal)
createAnAccountButton.titleLabel?.font = RemoteTabsPanelUX.EmptyStateCreateAccountButtonFont
createAnAccountButton.addTarget(self, action: "SELcreateAnAccount", forControlEvents: UIControlEvents.TouchUpInside)
containerView.addSubview(createAnAccountButton)
createAnAccountButton.snp_makeConstraints({ (make) -> Void in
make.centerX.equalTo(containerView)
make.top.equalTo(signInButton.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
})
containerView.snp_makeConstraints({ (make) -> Void in
// Let the container wrap around the content
make.top.equalTo(imageView.snp_top)
make.bottom.equalTo(createAnAccountButton)
make.left.equalTo(signInButton)
make.right.equalTo(signInButton)
// And then center it in the overlay view that sits on top of the UITableView
make.center.equalTo(contentView)
})
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func SELsignIn() {
if let homePanel = self.homePanel {
homePanel.homePanelDelegate?.homePanelDidRequestToSignIn(homePanel)
}
}
@objc private func SELcreateAnAccount() {
if let homePanel = self.homePanel {
homePanel.homePanelDelegate?.homePanelDidRequestToCreateAccount(homePanel)
}
}
}
| mpl-2.0 | e2ec1ef8a5834c0550df6c78873c135b | 41.84 | 153 | 0.696765 | 5.22439 | false | false | false | false |
rokuz/omim | iphone/Maps/UI/Discovery/Collection Cells/DiscoveryGuideCell.swift | 1 | 3061 | @objc(MWMDiscoveryGuideCell)
final class DiscoveryGuideCell: UICollectionViewCell {
@IBOutlet var avatar: UIImageView!
@IBOutlet var titleLabel: UILabel! {
didSet {
titleLabel.font = UIFont.medium14()
titleLabel.textColor = UIColor.blackPrimaryText()
titleLabel.numberOfLines = 2
}
}
@IBOutlet var subtitleLabel: UILabel! {
didSet {
subtitleLabel.font = UIFont.regular12()
subtitleLabel.textColor = UIColor.blackSecondaryText()
subtitleLabel.numberOfLines = 1
}
}
@IBOutlet var proLabel: UILabel! {
didSet {
proLabel.font = UIFont.bold12()
proLabel.textColor = UIColor.white()
proLabel.backgroundColor = .clear
proLabel.text = "";
}
}
@IBOutlet var proContainer: UIView!
@IBOutlet var detailsButton: UIButton! {
didSet {
detailsButton.titleLabel?.font = UIFont.semibold14()
detailsButton.setTitleColor(UIColor.linkBlue(), for: .normal)
detailsButton.setTitle(L("details"), for: .normal)
}
}
typealias OnDetails = () -> Void
private var onDetails: OnDetails?
override var isHighlighted: Bool {
didSet {
UIView.animate(withDuration: kDefaultAnimationDuration,
delay: 0,
options: [.allowUserInteraction, .beginFromCurrentState],
animations: { self.alpha = self.isHighlighted ? 0.3 : 1 },
completion: nil)
}
}
override func awakeFromNib() {
super.awakeFromNib()
layer.borderColor = UIColor.blackDividers().cgColor
}
override func prepareForReuse() {
super.prepareForReuse()
avatar.image = UIImage(named: "img_guide_placeholder")
titleLabel.text = ""
subtitleLabel.text = ""
proLabel.text = ""
proContainer.isHidden = true
onDetails = nil
}
private func setAvatar(_ avatarURL: String?) {
guard let avatarURL = avatarURL else { return }
if !avatarURL.isEmpty, let url = URL(string: avatarURL) {
avatar.image = UIImage(named: "img_guide_placeholder")
avatar.wi_setImage(with: url, transitionDuration: kDefaultAnimationDuration)
} else {
avatar.image = UIImage(named: "img_guide_placeholder")
}
}
@objc func config(avatarURL: String?,
title: String,
subtitle: String,
label: String?,
labelHexColor: String?,
onDetails: @escaping OnDetails) {
setAvatar(avatarURL)
titleLabel.text = title
subtitleLabel.text = subtitle
self.onDetails = onDetails
guard let label = label, !label.isEmpty else {
proContainer.isHidden = true
return
}
proLabel.text = label
if let labelHexColor = labelHexColor, labelHexColor.count == 6 {
proContainer.backgroundColor = UIColor(fromHexString: labelHexColor)
} else {
proContainer.backgroundColor = UIColor.ratingRed()
}
proContainer.isHidden = false
}
@IBAction private func detailsAction() {
onDetails?()
}
}
| apache-2.0 | c32e738ac8bb34c0ec6aba2d5b92941b | 28.718447 | 82 | 0.6377 | 4.616893 | false | false | false | false |
jdipanfilo/Stormy-with-location | TreeHouse_Stormy_Network_Version/TreeHouse Stormy/CurrentWeather.swift | 1 | 2627 | //
// CurrentWeather.swift
// TreeHouse Stormy
//
// Created by John DiPanfilo on 8/9/15.
// Copyright (c) 2015 bc9000. All rights reserved.
//
import Foundation
import UIKit
//Enum for using the "icon" data from the weatherDictionary to dislay a coresponding icon on the main view.
enum Icon: String {
case ClearDay = "clear-day"
case ClearNight = "clear-night"
case Rain = "rain"
case Snow = "snow"
case Sleet = "sleet"
case Wind = "wind"
case Fog = "fog"
case Cloudy = "cloudy"
case PartlyCloudyDay = "partly-cloudy-day"
case PartlyCloudyNight = "partly-cloudy-night"
//Method to display the correct image.
func toImage() -> UIImage? {
var imageName: String
//There was a incorrect image name in course that I corrected.
switch self {
case Icon.ClearDay:
imageName = "clear-day"
case Icon.ClearNight:
imageName = "clear-night"
case Icon.Rain:
imageName = "rain"
case Icon.Snow:
imageName = "snow"
case Icon.Sleet:
imageName = "sleet"
case Icon.Wind:
imageName = "wind"
case Icon.Fog:
imageName = "fog"
case Icon.Cloudy:
imageName = "cloudy"
case Icon.PartlyCloudyDay:
// imageName = "partly-cloudy-day"
imageName = "cloudy-day"
case Icon.PartlyCloudyNight:
// imageName = "partly-cloudy-night"
imageName = "cloudy_night"
}
return UIImage(named: imageName)
}
}
//Struct that works through the weatherDictionary created from the pulled JSON data
struct CurrentWeather {
let temperature: Int?
let humidity: Int?
let precipProbability: Int?
let summary: String?
var icon: UIImage? = UIImage(named: "default.png")
init(weatherDictionary: [String: AnyObject]) {
temperature = weatherDictionary["temperature"] as? Int
if let humidityFloat = weatherDictionary["humidity"] as? Double {
humidity = Int(humidityFloat*100)
} else {
humidity = nil
}
if let precipFloat = weatherDictionary["precipProbability"] as? Double {
precipProbability = Int(precipFloat*100)
} else {
precipProbability = nil
}
summary = weatherDictionary["summary"] as? String
if let iconString = weatherDictionary["icon"] as? String, let weatherIcon: Icon = Icon(rawValue: iconString) {
icon = weatherIcon.toImage()
}
}
}
| gpl-2.0 | 7d64e8fbc30d906aa40b7a8835958fc5 | 29.195402 | 118 | 0.593453 | 4.342149 | false | false | false | false |
qutheory/vapor | Sources/Vapor/Multipart/MultipartParser.swift | 1 | 7659 | import CMultipartParser
/// Parses multipart-encoded `Data` into `MultipartPart`s. Multipart encoding is a widely-used format for encoding/// web-form data that includes rich content like files. It allows for arbitrary data to be encoded
/// in each part thanks to a unique delimiter "boundary" that is defined separately. This
/// boundary is guaranteed by the client to not appear anywhere in the data.
///
/// `multipart/form-data` is a special case of `multipart` encoding where each part contains a `Content-Disposition`
/// header and name. This is used by the `FormDataEncoder` and `FormDataDecoder` to convert `Codable` types to/from
/// multipart data.
///
/// See [Wikipedia](https://en.wikipedia.org/wiki/MIME#Multipart_messages) for more information.
///
/// Seealso `form-urlencoded` encoding where delimiter boundaries are not required.
public final class MultipartParser {
public var onHeader: (String, String) -> ()
public var onBody: (inout ByteBuffer) -> ()
public var onPartComplete: () -> ()
private var callbacks: multipartparser_callbacks
private var parser: multipartparser
private enum HeaderState {
case ready
case field(field: String)
case value(field: String, value: String)
}
private var headerState: HeaderState
/// Creates a new `MultipartParser`.
public init(boundary: String) {
self.onHeader = { _, _ in }
self.onBody = { _ in }
self.onPartComplete = { }
var parser = multipartparser()
multipartparser_init(&parser, boundary)
var callbacks = multipartparser_callbacks()
multipartparser_callbacks_init(&callbacks)
self.callbacks = callbacks
self.parser = parser
self.headerState = .ready
self.callbacks.on_header_field = { parser, data, size in
guard let context = Context.from(parser) else {
return 1
}
let string = String(cPointer: data, count: size)
context.parser.handleHeaderField(string)
return 0
}
self.callbacks.on_header_value = { parser, data, size in
guard let context = Context.from(parser) else {
return 1
}
let string = String(cPointer: data, count: size)
context.parser.handleHeaderValue(string)
return 0
}
self.callbacks.on_data = { parser, data, size in
guard let context = Context.from(parser) else {
return 1
}
var buffer = context.slice(at: data, count: size)
context.parser.handleData(&buffer)
return 0
}
self.callbacks.on_body_begin = { parser in
return 0
}
self.callbacks.on_headers_complete = { parser in
guard let context = Context.from(parser) else {
return 1
}
context.parser.handleHeadersComplete()
return 0
}
self.callbacks.on_part_end = { parser in
guard let context = Context.from(parser) else {
return 1
}
context.parser.handlePartEnd()
return 0
}
self.callbacks.on_body_end = { parser in
return 0
}
}
struct Context {
static func from(_ pointer: UnsafeMutablePointer<multipartparser>?) -> Context? {
guard let parser = pointer?.pointee else {
return nil
}
return parser.data.assumingMemoryBound(to: MultipartParser.Context.self).pointee
}
unowned let parser: MultipartParser
let unsafeBuffer: UnsafeRawBufferPointer
let buffer: ByteBuffer
func slice(at pointer: UnsafePointer<Int8>?, count: Int) -> ByteBuffer {
guard let pointer = pointer else {
fatalError("no data pointer")
}
guard let unsafeBufferStart = unsafeBuffer.baseAddress?.assumingMemoryBound(to: Int8.self) else {
fatalError("no base address")
}
let unsafeBufferEnd = unsafeBufferStart.advanced(by: unsafeBuffer.count)
if pointer >= unsafeBufferStart && pointer <= unsafeBufferEnd {
// we were given back a pointer inside our buffer, we can be efficient
let offset = unsafeBufferStart.distance(to: pointer)
guard let buffer = self.buffer.getSlice(at: offset, length: count) else {
fatalError("invalid offset")
}
return buffer
} else {
// the buffer is to somewhere else, like a statically allocated string
// let's create a new buffer
let bytes = UnsafeRawBufferPointer(
start: UnsafeRawPointer(pointer),
count: count
)
var buffer = ByteBufferAllocator().buffer(capacity: bytes.count)
buffer.writeBytes(bytes)
return buffer
}
}
}
public func execute(_ string: String) throws {
try self.execute([UInt8](string.utf8))
}
public func execute<Data>(_ data: Data) throws
where Data: DataProtocol
{
var buffer = ByteBufferAllocator().buffer(capacity: data.count)
buffer.writeBytes(data)
return try self.execute(buffer)
}
public func execute(_ buffer: ByteBuffer) throws {
let result = buffer.withUnsafeReadableBytes { (unsafeBuffer: UnsafeRawBufferPointer) -> Int in
var context = Context(parser: self, unsafeBuffer: unsafeBuffer, buffer: buffer)
return withUnsafeMutablePointer(to: &context) { (contextPointer: UnsafeMutablePointer<Context>) -> Int in
self.parser.data = .init(contextPointer)
return multipartparser_execute(&self.parser, &self.callbacks, unsafeBuffer.baseAddress?.assumingMemoryBound(to: Int8.self), unsafeBuffer.count)
}
}
guard result == buffer.readableBytes else {
throw MultipartError.invalidFormat
}
}
// MARK: Private
private func handleHeaderField(_ new: String) {
switch self.headerState {
case .ready:
self.headerState = .field(field: new)
case .field(let existing):
self.headerState = .field(field: existing + new)
case .value(let field, let value):
self.onHeader(field, value)
self.headerState = .field(field: new)
}
}
private func handleHeaderValue(_ new: String) {
switch self.headerState {
case .field(let name):
self.headerState = .value(field: name, value: new)
case .value(let name, let existing):
self.headerState = .value(field: name, value: existing + new)
default: fatalError()
}
}
private func handleHeadersComplete() {
switch self.headerState {
case .value(let field, let value):
self.onHeader(field, value)
self.headerState = .ready
case .ready: break
default: fatalError()
}
}
private func handleData(_ data: inout ByteBuffer) {
self.onBody(&data)
}
private func handlePartEnd() {
self.onPartComplete()
}
}
private extension String {
init(cPointer: UnsafePointer<Int8>?, count: Int) {
let pointer = UnsafeRawPointer(cPointer)?.assumingMemoryBound(to: UInt8.self)
self.init(decoding: UnsafeBufferPointer(start: pointer, count: count), as: UTF8.self)
}
}
| mit | 6f5a63a1b72d0876a4216d41301c6b53 | 36.729064 | 213 | 0.60047 | 4.751241 | false | false | false | false |
mattwelborn/HSTracker | HSTracker/Database/Cards.swift | 1 | 5500 | //
// Cards.swift
// HSTracker
//
// Created by Benjamin Michotte on 24/05/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
final class Cards {
static let classes: [CardClass] = {
return [.DRUID, .HUNTER, .MAGE, .PALADIN, .PRIEST,
.ROGUE, .SHAMAN, .WARLOCK, .WARRIOR]
.sort { NSLocalizedString($0.rawValue.lowercaseString, comment: "")
< NSLocalizedString($1.rawValue.lowercaseString, comment: "") }
}()
static var cards = [Card]()
static func heroById(cardId: String) -> Card? {
if let card = cards.firstWhere({ $0.id == cardId && $0.type == .HERO }) {
return card.copy()
}
return nil
}
static func isHero(cardId: String?) -> Bool {
guard !String.isNullOrEmpty(cardId) else { return false }
return heroById(cardId!) != .None
}
static func byId(cardId: String?) -> Card? {
guard !String.isNullOrEmpty(cardId) else { return nil }
if let card = cards.filter({
$0.type != .HERO && $0.type != .HERO_POWER
}).firstWhere({ $0.id == cardId }) {
return card.copy()
}
return nil
}
static func anyById(cardId: String) -> Card? {
if let card = cards.firstWhere({ $0.id == cardId }) {
return card.copy()
}
return nil
}
static func heroByPlayerClass(name: CardClass) -> Card? {
switch name {
case .DRUID: return self.heroById(CardIds.Collectible.Druid.MalfurionStormrage)
case .HUNTER: return self.heroById(CardIds.Collectible.Hunter.Rexxar)
case .MAGE: return self.heroById(CardIds.Collectible.Mage.JainaProudmoore)
case .PALADIN: return self.heroById(CardIds.Collectible.Paladin.UtherLightbringer)
case .PRIEST: return self.heroById(CardIds.Collectible.Priest.AnduinWrynn)
case .ROGUE: return self.heroById(CardIds.Collectible.Rogue.ValeeraSanguinar)
case .SHAMAN: return self.heroById(CardIds.Collectible.Shaman.Thrall)
case .WARLOCK: return self.heroById(CardIds.Collectible.Warlock.Guldan)
case .WARRIOR: return self.heroById(CardIds.Collectible.Warrior.GarroshHellscream)
default: return nil
}
}
static func byName(name: String) -> Card? {
if let card = collectible().firstWhere({ $0.name == name }) {
return card.copy()
}
return nil
}
static func byEnglishName(name: String) -> Card? {
if let card = collectible().firstWhere({ $0.enName == name || $0.name == name }) {
return card.copy()
}
return nil
}
static func collectible() -> [Card] {
return cards.filter { $0.collectible && $0.type != .HERO && $0.type != .HERO_POWER }
}
static func byClass(className: CardClass?, set: String?) -> [Card] {
var sets: [CardSet] = []
if let set = CardSet(rawValue: set ?? "") {
sets.append(set)
}
return byClass(className, sets: sets)
}
static func byClass(className: CardClass?, sets: [CardSet]) -> [Card] {
var _cards = collectible().filter { $0.playerClass == className }
if !sets.isEmpty {
_cards = _cards.filter { $0.set != nil && sets.contains($0.set!) }
}
return _cards
}
static func search(className className: CardClass?, sets: [CardSet] = [],
term: String = "", cost: Int = -1,
rarity: Rarity? = .None, standardOnly: Bool = false,
damage: Int = -1, health: Int = -1, type: CardType = .INVALID,
race: Race?) -> [Card] {
var cards = collectible()
if term.isEmpty {
cards = cards.filter { $0.playerClass == className }
} else {
cards = cards.filter { $0.playerClass == className || $0.playerClass == .NEUTRAL }
.filter {
$0.name.lowercaseString.contains(term.lowercaseString) ||
$0.enName.lowercaseString.contains(term.lowercaseString) ||
$0.text.lowercaseString.contains(term.lowercaseString) ||
$0.rarity.rawValue.contains(term.lowercaseString) ||
$0.type.rawString().lowercaseString.contains(term.lowercaseString) ||
$0.race.rawValue.lowercaseString.contains(term.lowercaseString)
}
}
if type != .INVALID {
cards = cards.filter { $0.type == type }
}
if let race = race {
cards = cards.filter { $0.race == race }
}
if health != -1 {
cards = cards.filter { $0.health == health }
}
if damage != -1 {
cards = cards.filter { $0.attack == damage }
}
if standardOnly {
cards = cards.filter { $0.isStandard }
}
if let rarity = rarity {
cards = cards.filter { $0.rarity == rarity }
}
if !sets.isEmpty {
cards = cards.filter { $0.set != nil && sets.contains($0.set!) }
}
if cost != -1 {
cards = cards.filter {
if cost == 7 {
return $0.cost >= 7
}
return $0.cost == cost
}
}
return cards.sortCardList()
}
}
| mit | 9ffe4775692ea0ff9d5863382632a124 | 32.944444 | 95 | 0.537734 | 4.040411 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Lint/MarkRule.swift | 1 | 10493 | import Foundation
import SourceKittenFramework
struct MarkRule: CorrectableRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "mark",
name: "Mark",
description: "MARK comment should be in valid format. e.g. '// MARK: ...' or '// MARK: - ...'",
kind: .lint,
nonTriggeringExamples: [
Example("// MARK: good\n"),
Example("// MARK: - good\n"),
Example("// MARK: -\n"),
Example("// BOOKMARK"),
Example("//BOOKMARK"),
Example("// BOOKMARKS"),
issue1749Example
],
triggeringExamples: [
Example("↓//MARK: bad"),
Example("↓// MARK:bad"),
Example("↓//MARK:bad"),
Example("↓// MARK: bad"),
Example("↓// MARK: bad"),
Example("↓// MARK: -bad"),
Example("↓// MARK:- bad"),
Example("↓// MARK:-bad"),
Example("↓//MARK: - bad"),
Example("↓//MARK:- bad"),
Example("↓//MARK: -bad"),
Example("↓//MARK:-bad"),
Example("↓//Mark: bad"),
Example("↓// Mark: bad"),
Example("↓// MARK bad"),
Example("↓//MARK bad"),
Example("↓// MARK - bad"),
Example("↓//MARK : bad"),
Example("↓// MARKL:"),
Example("↓// MARKR "),
Example("↓// MARKK -"),
Example("↓/// MARK:"),
Example("↓/// MARK bad"),
issue1029Example
],
corrections: [
Example("↓//MARK: comment"): Example("// MARK: comment"),
Example("↓// MARK: comment"): Example("// MARK: comment"),
Example("↓// MARK:comment"): Example("// MARK: comment"),
Example("↓// MARK: comment"): Example("// MARK: comment"),
Example("↓//MARK: - comment"): Example("// MARK: - comment"),
Example("↓// MARK:- comment"): Example("// MARK: - comment"),
Example("↓// MARK: -comment"): Example("// MARK: - comment"),
Example("↓// MARK: - comment"): Example("// MARK: - comment"),
Example("↓// Mark: comment"): Example("// MARK: comment"),
Example("↓// Mark: - comment"): Example("// MARK: - comment"),
Example("↓// MARK - comment"): Example("// MARK: - comment"),
Example("↓// MARK : comment"): Example("// MARK: comment"),
Example("↓// MARKL:"): Example("// MARK:"),
Example("↓// MARKL: -"): Example("// MARK: -"),
Example("↓// MARKK "): Example("// MARK: "),
Example("↓// MARKK -"): Example("// MARK: -"),
Example("↓/// MARK:"): Example("// MARK:"),
Example("↓/// MARK comment"): Example("// MARK: comment"),
issue1029Example: issue1029Correction,
issue1749Example: issue1749Correction
]
)
private let spaceStartPattern = "(?:\(nonSpaceOrTwoOrMoreSpace)\(mark))"
private let endNonSpacePattern = "(?:\(mark)\(nonSpace))"
private let endTwoOrMoreSpacePattern = "(?:\(mark)\(twoOrMoreSpace))"
private let invalidEndSpacesPattern = "(?:\(mark)\(nonSpaceOrTwoOrMoreSpace))"
private let twoOrMoreSpacesAfterHyphenPattern = "(?:\(mark) -\(twoOrMoreSpace))"
private let nonSpaceOrNewlineAfterHyphenPattern = "(?:\(mark) -[^ \n])"
private let invalidSpacesAfterHyphenPattern = "(?:\(mark) -\(nonSpaceOrTwoOrMoreSpaceOrNewline))"
private let invalidLowercasePattern = "(?:// ?[Mm]ark:)"
private let missingColonPattern = "(?:// ?MARK[^:])"
// The below patterns more specifically describe some of the above pattern's failure cases for correction.
private let oneOrMoreSpacesBeforeColonPattern = "(?:// ?MARK +:)"
private let nonWhitespaceBeforeColonPattern = "(?:// ?MARK\\S+:)"
private let nonWhitespaceNorColonBeforeSpacesPattern = "(?:// ?MARK[^\\s:]* +)"
private let threeSlashesInsteadOfTwo = "/// MARK:?"
private var pattern: String {
return [
spaceStartPattern,
invalidEndSpacesPattern,
invalidSpacesAfterHyphenPattern,
invalidLowercasePattern,
missingColonPattern,
threeSlashesInsteadOfTwo
].joined(separator: "|")
}
func validate(file: SwiftLintFile) -> [StyleViolation] {
return violationRanges(in: file, matching: pattern).map {
StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
func correct(file: SwiftLintFile) -> [Correction] {
var result = [Correction]()
result.append(contentsOf: correct(file: file,
pattern: spaceStartPattern,
replaceString: "// MARK:"))
result.append(contentsOf: correct(file: file,
pattern: endNonSpacePattern,
replaceString: "// MARK: ",
keepLastChar: true))
result.append(contentsOf: correct(file: file,
pattern: endTwoOrMoreSpacePattern,
replaceString: "// MARK: "))
result.append(contentsOf: correct(file: file,
pattern: twoOrMoreSpacesAfterHyphenPattern,
replaceString: "// MARK: - "))
result.append(contentsOf: correct(file: file,
pattern: nonSpaceOrNewlineAfterHyphenPattern,
replaceString: "// MARK: - ",
keepLastChar: true))
result.append(contentsOf: correct(file: file,
pattern: oneOrMoreSpacesBeforeColonPattern,
replaceString: "// MARK:",
keepLastChar: false))
result.append(contentsOf: correct(file: file,
pattern: nonWhitespaceBeforeColonPattern,
replaceString: "// MARK:",
keepLastChar: false))
result.append(contentsOf: correct(file: file,
pattern: nonWhitespaceNorColonBeforeSpacesPattern,
replaceString: "// MARK: ",
keepLastChar: false))
result.append(contentsOf: correct(file: file,
pattern: invalidLowercasePattern,
replaceString: "// MARK:"))
result.append(contentsOf: correct(file: file,
pattern: threeSlashesInsteadOfTwo,
replaceString: "// MARK:"))
return result.unique
}
private func correct(file: SwiftLintFile,
pattern: String,
replaceString: String,
keepLastChar: Bool = false) -> [Correction] {
let violations = violationRanges(in: file, matching: pattern)
let matches = file.ruleEnabled(violatingRanges: violations, for: self)
if matches.isEmpty { return [] }
var nsstring = file.contents.bridge()
let description = Self.description
var corrections = [Correction]()
for var range in matches.reversed() {
if keepLastChar {
range.length -= 1
}
let location = Location(file: file, characterOffset: range.location)
nsstring = nsstring.replacingCharacters(in: range, with: replaceString).bridge()
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(nsstring.bridge())
return corrections
}
private func violationRanges(in file: SwiftLintFile, matching pattern: String) -> [NSRange] {
return file.rangesAndTokens(matching: pattern).filter { matchRange, syntaxTokens in
guard
let syntaxToken = syntaxTokens.first,
let syntaxKind = syntaxToken.kind,
SyntaxKind.commentKinds.contains(syntaxKind),
case let tokenLocation = Location(file: file, byteOffset: syntaxToken.offset),
case let matchLocation = Location(file: file, characterOffset: matchRange.location),
// Skip MARKs that are part of a multiline comment
tokenLocation.line == matchLocation.line
else {
return false
}
return true
}.compactMap { range, syntaxTokens in
let byteRange = ByteRange(location: syntaxTokens[0].offset, length: 0)
let identifierRange = file.stringView.byteRangeToNSRange(byteRange)
return identifierRange.map { NSUnionRange($0, range) }
}
}
}
private let issue1029Example = Example("""
↓//MARK:- Top-Level bad mark
↓//MARK:- Another bad mark
struct MarkTest {}
↓// MARK:- Bad mark
extension MarkTest {}
""")
private let issue1029Correction = Example("""
// MARK: - Top-Level bad mark
// MARK: - Another bad mark
struct MarkTest {}
// MARK: - Bad mark
extension MarkTest {}
""")
// https://github.com/realm/SwiftLint/issues/1749
// https://github.com/realm/SwiftLint/issues/3841
private let issue1749Example = Example(
"""
/*
func test1() {
}
//MARK: mark
func test2() {
}
*/
"""
)
// This example should not trigger changes
private let issue1749Correction = issue1749Example
// These need to be at the bottom of the file to work around https://bugs.swift.org/browse/SR-10486
private let nonSpace = "[^ ]"
private let twoOrMoreSpace = " {2,}"
private let mark = "MARK:"
private let nonSpaceOrTwoOrMoreSpace = "(?:\(nonSpace)|\(twoOrMoreSpace))"
private let nonSpaceOrTwoOrMoreSpaceOrNewline = "(?:[^ \n]|\(twoOrMoreSpace))"
| mit | 19eb31d821ec6069bac1372407e9c6ea | 40.787149 | 110 | 0.530802 | 5.102992 | false | false | false | false |
ismailbozk/ObjectScanner | ObjectScanner/ObjectScanner/Managers/OSScannerManager.swift | 1 | 8867 | //
// OSScannerManager.swift
// ObjectScanner
//
// Created by Ismail Bozkurt on 25/07/2015.
// The MIT License (MIT)
//
// Copyright (c) 2015 Ismail Bozkurt
//
// 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 simd
private let kOSScannerManagerMinNumberOfMatchesForRegistrationProcess = 3;
enum OSScannerManagerState: String
{
case Idle = "OSScannerManagerIdle"
case ContentLoading = "OSScannerManagerDidStartContentLoading"
case ContentLoaded = "OSScannerManagerDidStartContentLoaded"
case Scanning = "OSScannerManagerScaning"
case ScanCompleted = "OSScannerManagerScanCompleted"
}
protocol OSScannerManagerDelegate : class
{
func scannerManagerDidPreparedFrame(_ scannerManager: OSScannerManager, frame: OSBaseFrame) -> Void;
}
class OSScannerManager : OS3DFrameConsumerProtocol
{
// MARK: Properties
weak var delegate : OSScannerManagerDelegate?;
var state : OSScannerManagerState = .Idle {
didSet
{
DispatchQueue.main.async { () -> Void in
NotificationCenter.default.post(name: Notification.Name(rawValue: self.state.rawValue), object:self);
};
}
};
fileprivate let calibrationSemaphore : DispatchSemaphore = DispatchSemaphore(value: 1);
fileprivate let featureExtractionSemaphore : DispatchSemaphore = DispatchSemaphore(value: 1);
fileprivate let threadSafeConcurrentFrameArrayConcurrentQueue : DispatchQueue = DispatchQueue(label: "OSScannerManagerThreadSafeConcurrentFrameArrayConcurrentQueue", attributes: DispatchQueue.Attributes.concurrent);//don't use that queue anywhere else other than custom getters and setters for consecutiveFrames property.
fileprivate var consecutiveFrames : [OSBaseFrame] = [OSBaseFrame]();
fileprivate var isThisTheFirstTime = true;
// MARK: Custom concurrentFrameArray Getter/Setters
fileprivate func frameAtIndex(_ index : Int) -> OSBaseFrame
{
var frame : OSBaseFrame!
self.threadSafeConcurrentFrameArrayConcurrentQueue.sync { () -> Void in
frame = self.consecutiveFrames[index];
};
return frame;
}
fileprivate func removeFrame(_ index : Int)
{
self.threadSafeConcurrentFrameArrayConcurrentQueue.async(flags: .barrier, execute: { () -> Void in
self.consecutiveFrames.remove(at: index);
}) ;
}
fileprivate func appendFrame(_ frame : OSBaseFrame)
{
self.threadSafeConcurrentFrameArrayConcurrentQueue.async(flags: .barrier, execute: { () -> Void in
self.consecutiveFrames.append(frame);
}) ;
}
// MARK: Lifecycle
static let sharedInstance = OSScannerManager();
init()
{
OSCameraFrameProviderSwift.sharedInstance.delegate = self;
self.startLoadingContent();
}
// MARK: Publics
func startSimulating()
{
switch (self.state)
{
case .Idle, .ContentLoading:
print("warning: content is not loaded, first the content must be loaded.");
break
case .ContentLoaded:
self.state = .Scanning;
OSCameraFrameProviderSwift.sharedInstance.startSimulatingFrameCaptures();
break
case .Scanning:
print("warning: scanning is in progress.");
break
case .ScanCompleted:
print("warning: scanning is already completed.");
break
}
}
// MARK: Utilities
/**
@param frame the frame that will be calibrated and put into the scanning process
@abstract this methd is consist of single frame calibration and image surf feature extractions
*/
fileprivate func startSingleFrameOperations(_ frame : OSBaseFrame)
{
self.calibrationSemaphore.wait(timeout: DispatchTime.distantFuture);
self.appendFrame(frame);
// calibrating the frame
frame.preparePointCloud {[unowned self] () -> Void in
let matchCoordinatesIn2D: NSArray? = OSImageFeatureMatcher.sharedInstance().match(frame.image);
if let matchCoordinatesIn2D = matchCoordinatesIn2D,
(matchCoordinatesIn2D.count > kOSScannerManagerMinNumberOfMatchesForRegistrationProcess && !self.isThisTheFirstTime)
{
let trainFrame = self.frameAtIndex(self.consecutiveFrames.count - 1 - 1);
var matchesIn3D = NSMutableArray();
var matchIn2D: OSMatch = OSMatch();
let count = matchCoordinatesIn2D.count
for i: Int in 0..<count
{
let val: NSValue? = matchCoordinatesIn2D.object(at: i) as? NSValue;
val?.getValue(&matchIn2D);
let trainImageIndex = (Int)(matchIn2D.trainPoint.y) * frame.width + (Int)(matchIn2D.trainPoint.x);
let queryImageIndex = (Int)(matchIn2D.queryPoint.y) * frame.width + (Int)(matchIn2D.queryPoint.x);
if (frame.pointCloud[queryImageIndex].isValid() && trainFrame.pointCloud[trainImageIndex].isValid())
{
var singleMatch: OSMatch3D = OSMatch3D(queryPoint: frame.pointCloud[queryImageIndex].point, trainPoint: trainFrame.pointCloud[trainImageIndex].point);
let singleMatchData: Data = Data(bytes: &singleMatch, count: MemoryLayout<OSMatch3D>.size);
matchesIn3D.add(singleMatchData);
}
}
let transformationMatrixData: Data = OSRegistrationUtility.createTransformationMatrix(withMatches: matchesIn3D as [AnyObject]);
var transformationMatrix: Matrix4 = Matrix4.Identity;
(transformationMatrixData as NSData).getBytes(&transformationMatrix, length: MemoryLayout<Matrix4>.size);
frame.transformationMatrix = trainFrame.transformationMatrix * transformationMatrix;
self.delegate?.scannerManagerDidPreparedFrame(self, frame: frame);
}
else if (self.isThisTheFirstTime)
{
self.isThisTheFirstTime = false;
self.delegate?.scannerManagerDidPreparedFrame(self, frame: frame);
}
self.calibrationSemaphore.signal();
};
}
/**
@abstract this method will process the consecutive frames
*/
fileprivate func startConsecutiveFrameOperations()
{
}
// MARK: Privates
fileprivate func startLoadingContent()
{
OSTimer.tic();
self.state = .ContentLoading;
let contentLoadingGroup : DispatchGroup = DispatchGroup();
contentLoadingGroup.enter();
OSCameraFrameProviderSwift.loadContent { () -> Void in
contentLoadingGroup.leave();
};
contentLoadingGroup.enter();
OSBaseFrame.loadContent { () -> Void in
contentLoadingGroup.leave();
};
contentLoadingGroup.enter();
OSPointCloudView.loadContent { () -> Void in
contentLoadingGroup.leave();
};
contentLoadingGroup.notify(queue: DispatchQueue.main) { () -> Void in
OSTimer.toc("content loaded");
self.state = .ContentLoaded;
};
}
// MARK: Utilities
// MARK: OS3DFrameConsumerProtocol
func didCapturedFrame(_ image: UIImage, depthFrame: [Float])
{
let capturedFrame : OSBaseFrame = OSBaseFrame(image: image, depth: depthFrame);
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).async { () -> Void in
self.startSingleFrameOperations(capturedFrame);
};
}
}
| mit | 15768a57b35261ce5a03c01a832cfcc8 | 38.234513 | 325 | 0.649712 | 4.792973 | false | false | false | false |
groue/GRDB.swift | Documentation/Playgrounds/TransactionObserver.playground/Contents.swift | 1 | 2730 | //: To run this playground:
//:
//: - Open GRDB.xcworkspace
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
//: - Build: menu Product > Build
//: - Select the playground in the Playgrounds Group
//: - Run the playground
import GRDB
// Create the database
let dbQueue = try DatabaseQueue() // Memory database
var migrator = DatabaseMigrator()
migrator.registerMigration("createPerson") { db in
try db.create(table: "person") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
}
migrator.registerMigration("createPet") { db in
try db.create(table: "pet") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("ownerId", .integer).references("person", onDelete: .cascade)
}
}
try! migrator.migrate(dbQueue)
//
class TableChangeObserver : NSObject, TransactionObserver {
private var changedTableNames: Set<String> = []
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true }
func databaseDidChange(with event: DatabaseEvent) {
changedTableNames.insert(event.tableName)
}
func databaseDidCommit(_ db: Database) {
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
changedTableNames = []
}
func databaseDidRollback(_ db: Database) {
changedTableNames = []
}
}
let observer = TableChangeObserver()
dbQueue.add(transactionObserver: observer)
//
print("-- Changes without transaction")
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
let arthurId = db.lastInsertedRowID
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
}
print("-- Rollbacked changes")
try dbQueue.inTransaction { db in
try db.execute(sql: "INSERT INTO person (name) VALUES ('Arthur')")
try db.execute(sql: "INSERT INTO person (name) VALUES ('Barbara')")
return .rollback
}
print("-- Changes wrapped in a transaction")
try dbQueue.write { db in
try db.execute(sql: "DELETE FROM person")
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
let arthurId = db.lastInsertedRowID
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
}
| mit | b6eebf5345617ce54d3ed0ed8cdb8fa6 | 31.5 | 106 | 0.667033 | 4.068554 | false | false | false | false |
Constantine-Fry/das-quadrat | Demo/Demo-iOS/Demo-iOS/Cells.swift | 1 | 1338 | //
// VenueCell.swift
// Demo-iOS
//
// Created by Constantine Fry on 29/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
import UIKit
/** A cell to display venue name, rating and user tip. */
class VenueTableViewCell: UITableViewCell {
@IBOutlet weak var userPhotoImageView: UIImageView!
@IBOutlet weak var venueNameLabel: UILabel!
@IBOutlet weak var venueRatingLabel: UILabel!
@IBOutlet weak var venueCommentLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.userPhotoImageView.layer.cornerRadius = 4
self.userPhotoImageView.layer.shouldRasterize = true
self.userPhotoImageView.layer.rasterizationScale = UIScreen.main.scale
}
override func prepareForReuse() {
super.prepareForReuse()
self.userPhotoImageView.image = nil
}
}
/** A cell to display user. */
class FriendTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
self.photoImageView.layer.cornerRadius = 4
self.photoImageView.layer.shouldRasterize = true
self.photoImageView.layer.rasterizationScale = UIScreen.main.scale
}
}
| bsd-2-clause | 6fe802ddb37dc27f6964394464b3263b | 26.306122 | 78 | 0.69432 | 4.744681 | false | false | false | false |
HamzaGhazouani/HGCircularSlider | Example/Tests/CircularSliderTests.swift | 1 | 3648 | //
// CircularSliderTests.swift
// HGCircularSlider_Tests
//
// Created by Hamza on 20/10/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import XCTest
@testable import HGCircularSlider
class CircularSliderTests: XCTestCase {
func testEndPointPositionWithZeroAsInitialValueAnd90DegreesAsTouchPosition() {
// Given
let circularSlider = CircularSlider(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
let startPosition = CGPoint(x: 25, y: 0)
circularSlider.minimumValue = 0
circularSlider.maximumValue = 100
circularSlider.endPointValue = 0
let touchPosition = CGPoint(x: 50, y: 25)
// When
let newValue = circularSlider.newValue(from: circularSlider.endPointValue, touch: touchPosition, start: startPosition)
// Then
XCTAssertEqual(newValue, 25, accuracy: 0.001)
}
func testEndPointPositionWithValueGratherThanZeroAsInitialValueAnd90DegreesAsTouchPosition() {
// Given
let circularSlider = CircularSlider(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
let startPosition = CGPoint(x: 25, y: 0)
circularSlider.minimumValue = 5
circularSlider.maximumValue = 25
circularSlider.endPointValue = 5
let touchPosition = CGPoint(x: 50, y: 25)
// When
let newValue = circularSlider.newValue(from: circularSlider.endPointValue, touch: touchPosition, start: startPosition)
// Then
XCTAssertEqual(newValue, 10, accuracy: 0.001)
}
func testndPointPositionWithValueGratherThanZeroAsInitialValueAnd180DegreesAsTouchPosition() {
// Given
let circularSlider = CircularSlider(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
let startPosition = CGPoint(x: 25, y: 0)
circularSlider.minimumValue = 5
circularSlider.maximumValue = 25
circularSlider.endPointValue = 10
let touchPosition = CGPoint(x: 25, y: 50)
// When
let newValue = circularSlider.newValue(from: circularSlider.endPointValue, touch: touchPosition, start: startPosition)
// Then
XCTAssertEqual(newValue, 15, accuracy: 0.001)
}
func testndPointPositionWithValueGratherThanZeroAsInitialValueAnd270DegreesAsTouchPosition() {
// Given
let circularSlider = CircularSlider(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
let startPosition = CGPoint(x: 25, y: 0)
circularSlider.minimumValue = 5
circularSlider.maximumValue = 25
circularSlider.endPointValue = 10
let touchPosition = CGPoint(x: 0, y: 25)
// When
let newValue = circularSlider.newValue(from: circularSlider.endPointValue, touch: touchPosition, start: startPosition)
// Then
XCTAssertEqual(newValue, 20, accuracy: 0.001)
}
func testndPointPositionWithValueGratherThanZeroAsInitialValueAnd360DegreesAsTouchPosition() {
// Given
let circularSlider = CircularSlider(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
let startPosition = CGPoint(x: 25, y: 0)
circularSlider.minimumValue = 5
circularSlider.maximumValue = 25
circularSlider.endPointValue = 10
let touchPosition = CGPoint(x: 24.999, y: 0)
// When
let newValue = circularSlider.newValue(from: circularSlider.endPointValue, touch: touchPosition, start: startPosition)
// Then
XCTAssertEqual(newValue, 25, accuracy: 0.001)
}
}
| mit | 2ba3d26def9a68252383cfb4bc0f4ee4 | 36.214286 | 126 | 0.649301 | 4.485855 | false | true | false | false |
zhenghuadong11/firstGitHub | 旅游app_useSwift/旅游app_useSwift/MYScenicSpotTranformImageView.swift | 1 | 1286 | //
// MYScenicSpotTranformImageView.swift
// 旅游app_useSwift
//
// Created by zhenghuadong on 16/5/3.
// Copyright © 2016年 zhenghuadong. All rights reserved.
//
import UIKit
class MYScenicSpotTranformImageView: UIImageView {
var index:Int = 1
var imageNames:Array<String>{
set{
self.userInteractionEnabled = true
self.imageNamesTmp = newValue
self.image = UIImage.init(named: imageNames[0])
}
get{
return self.imageNamesTmp!
}
}
var imageNamesTmp:Array<String>?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if index == self.imageNames.count
{
index = 0
}
self.image = UIImage.init(named: self.imageNames[index])
index += 1
let anim = CATransition.init()
anim.type = "pageCurl"
anim.duration = 1
self.layer .addAnimation(anim, forKey: nil)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| apache-2.0 | 4026ee170b4863a9bcc1d7e4edf2c96f | 22.685185 | 82 | 0.574668 | 4.380137 | false | false | false | false |
FuruyamaTakeshi/NumericKeyboardSample | SampleKeyboard/ViewController.swift | 1 | 3358 | //
// ViewController.swift
// SampleKeyboard
//
// Created by Furuyama Takeshi on 2015/02/28.
// Copyright (c) 2015年 Furuyama Takeshi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, NumericKeyboardViewDelegate {
@IBOutlet weak var numericKeyboard: NumericKeyboardView!
@IBOutlet weak var myTextField: UITextField!
var boxlayer :CALayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let boxlayer = CALayer()
boxlayer.bounds = CGRectMake(0.0, 0.0, 85.0, 85.0)
boxlayer.position = CGPointMake(160.0, 300.0)
let color = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.5)
let cgReddish = color.CGColor
boxlayer.backgroundColor = cgReddish
// UIImageを生成する
let layerImage = UIImage(named: "Hypno")
let image = layerImage?.CGImage
boxlayer.contents = image
boxlayer.contentsRect = CGRectMake(-0.1, -0.1, 1.2, 1.2)
boxlayer.contentsGravity = kCAGravityResizeAspect
self.boxlayer = boxlayer
self.numericKeyboard.layer.position = CGPointMake(160.0, 160.0)
self.numericKeyboard.hidden = true
self.numericKeyboard.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var t: AnyObject = touches.anyObject()!
var p = t.locationInView(self.view)
println("\(p), \(self.numericKeyboard.frame)")
if (self.numericKeyboard.frame.origin.x < p.x && p.x < CGRectGetMaxX(self.numericKeyboard.frame) &&
self.numericKeyboard.frame.origin.y < p.y && p.y < self.numericKeyboard.frame.origin.y + 40) {
self.numericKeyboard.layer.position = p
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
var t: AnyObject = touches.anyObject()!
var p = t.locationInView(self.view)
if (self.numericKeyboard.frame.origin.x < p.x && p.x < CGRectGetMaxX(self.numericKeyboard.frame) &&
self.numericKeyboard.frame.origin.y < p.y && p.y < self.numericKeyboard.frame.origin.y + 40) {
self.numericKeyboard.layer.position = p
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
var t: AnyObject = touches.anyObject()!
var p = t.locationInView(self.view)
println(p)
if (self.numericKeyboard.frame.origin.x < p.x && p.x < CGRectGetMaxX(self.numericKeyboard.frame) &&
self.numericKeyboard.frame.origin.y < p.y && p.y < self.numericKeyboard.frame.origin.y + 40) {
self.numericKeyboard.layer.position = p
}
}
// MARK: -
func textFieldDidBeginEditing(textField: UITextField) {
textField.resignFirstResponder()
self.numericKeyboard.hidden = false
self.numericKeyboard.center = self.view.center
}
func enterButtonDidPushed(resultLabelString: String?) {
myTextField.text = resultLabelString
self.numericKeyboard.hidden = true
}
}
| mit | 2387e1efd26bea8ac3b259d0ce05bac5 | 34.978495 | 107 | 0.643754 | 4.156522 | false | false | false | false |
jasnig/UsefulPickerView | Example/Vc2Controller.swift | 1 | 5353 | //
// Vc2Controller.swift
// UsefulPickerVIew
//
// Created by jasnig on 16/4/24.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class Vc2Controller: UIViewController {
@IBOutlet weak var singleTextField: SelectionTextField!
@IBOutlet weak var multipleTextField: SelectionTextField!
@IBOutlet weak var multipleAssociatedTextField: SelectionTextField!
@IBOutlet weak var citiesTextField: SelectionTextField!
@IBOutlet weak var dateTextField: SelectionTextField!
@IBOutlet weak var timeTextField: SelectionTextField!
@IBOutlet weak var selectedDataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
singleTextField.showSingleColPicker("编程语言选择", data: singleData, defaultSelectedIndex: 2, autoSetSelectedText: true) {[unowned self] (textField, selectedIndex, selectedValue) in
// 可以使用textField 也可以使用 self.singleTextField
textField.text = "选中了第\(selectedIndex)行----选中的数据为\(selectedValue)"
self.selectedDataLabel.text = "选中了第\(selectedIndex)行----选中的数据为\(selectedValue)"
}
multipleTextField.showMultipleColsPicker("持续时间选择", data: multipleData, defaultSelectedIndexs: [0,1,1], autoSetSelectedText: true) {[unowned self] (textField, selectedIndexs, selectedValues) in
self.multipleTextField.text = "选中了第\(selectedIndexs)行----选中的数据为\(selectedValues)"
}
// 注意这里设置的是默认的选中值, 而不是选中的下标
multipleAssociatedTextField.showMultipleAssociatedColsPicker("多列关联数据", data: multipleAssociatedData, defaultSelectedValues: ["交通工具","陆地","自行车"], autoSetSelectedText: true) {[unowned self] (textField, selectedIndexs, selectedValues) in
self.multipleAssociatedTextField.text = "选中了第\(selectedIndexs)行----选中的数据为\(selectedValues)"
self.selectedDataLabel.text = "选中了第\(selectedIndexs)行----选中的数据为\(selectedValues)"
}
citiesTextField.showCitiesPicker("省市区选择", defaultSelectedValues: ["四川", "成都", "郫县"], autoSetSelectedText: false) {[unowned self] (textField, selectedIndexs, selectedValues) in
self.citiesTextField.text = "选中了第\(selectedIndexs)行----选中的数据为\(selectedValues)"
self.selectedDataLabel.text = "选中了第\(selectedIndexs)行----选中的数据为\(selectedValues)"
}
dateTextField.showDatePicker("日期选择", autoSetSelectedText: true) { (textField, selectedDate) in
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let string = formatter.stringFromDate(selectedDate)
textField.text = string
}
var dateStyle = DatePickerSetting()
dateStyle.dateMode = .Time
/// /// @author ZeroJ, 16-04-25 17:04:28
/// 注意使用这种方式的时候, 请设置 autoSetSelectedText = false, 否则显示的格式可能不是您需要的
timeTextField.showDatePicker("时间选择", datePickerSetting: dateStyle, autoSetSelectedText: false) { (textField, selectedDate) in
let formatter = NSDateFormatter()
// H -> 24小时制
formatter.dateFormat = "HH: mm"
let string = formatter.stringFromDate(selectedDate)
textField.text = string
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 16c977d7c5919a03e9c64ffa41517485 | 43.810811 | 242 | 0.694813 | 4.464991 | false | false | false | false |
ZulwiyozaPutra/Alien-Adventure-Tutorial | Alien Adventure/Settings.swift | 1 | 1036 | //
// Settings.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 9/18/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: - Settings
struct Settings {
// MARK: Common
struct Common {
static let GameDataURL = Bundle.main.url(forResource: "GameData", withExtension: "plist")!
static let Font = "Superclarendon-Italic"
static let FontColor = UIColor.white
static var Level = 2
static var ShowBadges = false
static let RequestsToSkip = 6
}
// MARK: Dialogue (Set by UDDataLoader)
struct Dialogue {
static var StartingDialogue = ""
static var RequestingDialogue = ""
static var TransitioningDialogue = ""
static var WinningDialogue = ""
static var LosingDialogue = ""
}
// MARK: Names
struct Names {
static let Hero = "Hero"
static let Background = "Background"
static let Treasure = "Treasure"
}
}
| mit | b3083601915d13ce3b50f54015bf2bc7 | 23.069767 | 98 | 0.589372 | 4.461207 | false | false | false | false |
mro/ShaarliOS | swift4/ShaarliOS/AppDelegate.swift | 1 | 3783 | //
// AppDelegate.swift
// ShaarliOS
//
// Created by Marcus Rohrmoser on 09.06.19.
// Copyright © 2019-2022 Marcus Rohrmoser mobile Software http://mro.name/me. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
static let shared = UIApplication.shared.delegate as! AppDelegate
let semver = info_to_semver(Bundle.main.infoDictionary)
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UINavigationBar.appearance().barTintColor = .darkGray
UINavigationBar.appearance().tintColor = ShaarliM.buttonColor
// UIBarButtonItem.appearance().tintColor = ShaarliM.buttonColor
UIButton.appearance().tintColor = ShaarliM.buttonColor
UILabel.appearance(whenContainedInInstancesOf: [SettingsVC.self]).textColor = ShaarliM.labelColor
let info = Bundle.main.infoDictionary ?? [:]
assert(BUNDLE_ID == info["CFBundleIdentifier"] as? String, "CFBundleIdentifier")
let urlt = info["CFBundleURLTypes"] as? [[String:Any]]
let urls = urlt?[0]["CFBundleURLSchemes"] as? [String]
assert(SELF_URL_PREFIX == urls?[0], "CFBundleURLTypes"+"/"+"CFBundleURLSchemes")
// UIView.setAnimationsEnabled(false) // nil != launchOptions[UIApplicationLaunchOptionsURLKey]];
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-3.0 | 818ab014497493b2c31413735ccbaa48 | 50.808219 | 285 | 0.73982 | 5.009272 | false | false | false | false |
Shedward/SwiftyNotificationCenter | Example/SwiftyNotificationCenter/AppDelegate.swift | 1 | 2329 | //
// AppDelegate.swift
// SwiftyNotificationCenter
//
// Created by Vladislav Maltsev on 12/04/2016.
// Copyright (c) 2016 Vladislav Maltsev.
//
// 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 SwiftyNotificationCenter
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var disposeBag = NotificationDisposeBag()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
showStoryboard(name: "Main")
NotificationCenter.default.observe { [unowned self] (event: LoginStateChanged) in
if event.userIsLoggedIn {
self.showStoryboard(name: "Main")
} else {
self.showStoryboard(name: "Login")
}
}.disposeWith(disposeBag: &disposeBag)
return true
}
func showStoryboard(name: String) {
let initialViewController = UIStoryboard(name: name, bundle: nil).instantiateInitialViewController()
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
}
}
| mit | 19e601e89973d519a597097003a2ef70 | 39.155172 | 151 | 0.70717 | 4.852083 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCIReadRemoteExtendedFeatures.swift | 1 | 2445 | //
// HCIReadRemoteExtendedFeatures.swift
// Bluetooth
//
// Created by Carlos Duclos on 8/8/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// Read Remote Extended Features Command
///
/// The Read_Remote_Extended_Features command returns the requested page of the extended LMP features for the remote device identified by the specified Connection_Handle. The Connection_Handle must be the Connection_Handle for an ACL connection. This command is only available if the extended features feature is implemented by the remote device. The Read Remote Extended Features Complete event will return the requested information.
func readRemoteExtendedFeatures(handle: UInt16,
pageNumber: UInt8,
timeout: HCICommandTimeout = .default) async throws -> BitMaskOptionSet<LMPFeature> {
let readRemoteExtendedFeatures = HCIReadRemoteExtendedFeatures(handle: handle, pageNumber: pageNumber)
return try await deviceRequest(readRemoteExtendedFeatures,
HCIReadRemoteExtendedFeaturesComplete.self,
timeout: timeout).features
}
}
// MARK: - Command
/// Read Remote Extended Features Command
///
/// The Read_Remote_Extended_Features command returns the requested page of the extended LMP features for the remote device identified by the specified Connection_Handle. The Connection_Handle must be the Connection_Handle for an ACL connection. This command is only available if the extended features feature is implemented by the remote device. The Read Remote Extended Features Complete event will return the requested information.
@frozen
public struct HCIReadRemoteExtendedFeatures: HCICommandParameter {
public static let command = LinkControlCommand.readRemoteExtendedFeatures
/// Specifies which Connection_Handle’s LMP-supported features list to get.
public var handle: UInt16
public var pageNumber: UInt8
public init(handle: UInt16, pageNumber: UInt8) {
self.handle = handle
self.pageNumber = pageNumber
}
public var data: Data {
let handleBytes = handle.littleEndian.bytes
return Data([handleBytes.0, handleBytes.1, pageNumber])
}
}
| mit | 0e42b54f314f8c07d6f7afb8947d398d | 41.842105 | 438 | 0.706798 | 5.217949 | false | false | false | false |
tjnet/NewsAppWithSwift | NewsApp/NewsApp/FeedTableViewCell.swift | 1 | 1827 | //
// FeedTableViewCell.swift
// NewsApp
//
// Created by TanakaJun on 2015/12/31.
// Copyright © 2015年 edu.self. All rights reserved.
//
import UIKit
import WebImage
import Alamofire
class FeedTableViewCell: UITableViewCell {
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
var link: String! {
didSet {
Alamofire.request(.GET, ArticleAPI.ogpImage + link).responseObject("") { (response: Response<OGPResponse, NSError>) in
var imageUrl: NSURL?
let ogpResponse = response.result.value
if let ogpImgSrc = ogpResponse?.image {
imageUrl = NSURL(string: ogpImgSrc)
// print(imageUrl)
self.setThumbnailWithFadeInAnimation(imageUrl)
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(entry: Entry){
titleLabel.text = entry.title
descriptionLabel.text = entry.contentSnippet
self.link = entry.link
}
func setThumbnailWithFadeInAnimation(imageUrl: NSURL!){
self.thumbnailImageView.loadWebImage(imageUrl, placeholderImage: nil, completeion: {
(image, error, cacheType, url) ->Void in
self.thumbnailImageView.alpha = 0
UIView.animateWithDuration(0.25,
animations: {
self.thumbnailImageView.alpha = 1
})
})
}
}
| mit | 52ae87b990f672e78447a5949f9516ad | 27.952381 | 130 | 0.594846 | 4.956522 | false | false | false | false |
lyngbym/SwiftGraph | SwiftGraphLib/SwiftGraphLib/WeightedGraph.swift | 3 | 4104 | //
// WeightedGraph.swift
// SwiftGraph
//
// Copyright (c) 2014-2016 David Kopec
//
// 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.
/// A subclass of Graph that has convenience methods for adding and removing WeightedEdges. All added Edges should have the same generic Comparable type W as the WeightedGraph itself.
open class WeightedGraph<T: Equatable, W: Comparable & Summable>: Graph<T> {
public override init() {
super.init()
}
public override init(vertices: [T]) {
super.init(vertices: vertices)
}
/// Find all of the neighbors of a vertex at a given index.
///
/// - parameter index: The index for the vertex to find the neighbors of.
/// - returns: An array of tuples including the vertices as the first element and the weights as the second element.
public func neighborsForIndexWithWeights(_ index: Int) -> [(T, W)] {
var distanceTuples: [(T, W)] = [(T, W)]();
for edge in edges[index] {
if let edge = edge as? WeightedEdge<W> {
distanceTuples += [(vertices[edge.v], edge.weight)]
}
}
return distanceTuples;
}
/// Add an edge to the graph. It must be weighted or the call will be ignored.
///
/// - parameter edge: The edge to add.
public override func addEdge(_ edge: Edge) {
guard edge.weighted else {
print("Error: Tried adding non-weighted Edge to WeightedGraph. Ignoring call.")
return
}
super.addEdge(edge)
}
/// This is a convenience method that adds a weighted edge.
///
/// - parameter from: The starting vertex's index.
/// - parameter to: The ending vertex's index.
/// - parameter directed: Is the edge directed? (default false)
/// - parameter weight: the Weight of the edge to add.
public func addEdge(from: Int, to: Int, directed: Bool = false, weight:W) {
addEdge(WeightedEdge<W>(u: from, v: to, directed: directed, weight: weight))
}
/// This is a convenience method that adds a weighted edge between the first occurence of two vertices. It takes O(n) time.
///
/// - parameter from: The starting vertex.
/// - parameter to: The ending vertex.
/// - parameter directed: Is the edge directed? (default false)
/// - parameter weight: the Weight of the edge to add.
public func addEdge(from: T, to: T, directed: Bool = false, weight: W) {
if let u = indexOfVertex(from) {
if let v = indexOfVertex(to) {
addEdge(WeightedEdge<W>(u: u, v: v, directed: directed, weight:weight))
}
}
}
//Have to have two of these because Edge protocol cannot adopt Equatable
/// Removes a specific weighted edge in both directions (if it's not directional). Or just one way if it's directed.
///
/// - parameter edge: The edge to be removed.
public func removeEdge(_ edge: WeightedEdge<W>) {
if let i = (edges[edge.u] as! [WeightedEdge<W>]).index(of: edge) {
edges[edge.u].remove(at: i)
if !edge.directed {
if let i = (edges[edge.v] as! [WeightedEdge<W>]).index(of: edge.reversed as! WeightedEdge) {
edges[edge.v].remove(at: i)
}
}
}
}
//Implement Printable protocol
public override var description: String {
var d: String = ""
for i in 0..<vertices.count {
d += "\(vertices[i]) -> \(neighborsForIndexWithWeights(i))\n"
}
return d
}
}
| apache-2.0 | 1ecd95c090672ff6c3c4cebbdb3d9e5a | 38.84466 | 183 | 0.61769 | 4.116349 | false | false | false | false |
CatchChat/Yep | YepPreview/Transiton/PhotoTransitonController.swift | 1 | 2147 | //
// PhotoTransitonController.swift
// Yep
//
// Created by NIX on 16/6/17.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
class PhotoTransitonController: NSObject {
lazy var animator = PhotoTransitionAnimator()
lazy var interactionController = PhotoDismissalInteractionController()
var forcesNonInteractiveDismissal = true
var startingView: UIView? {
return animator.startingView
}
func setStartingView(view: UIView?) {
animator.startingView = view
}
var endingView: UIView? {
return animator.endingView
}
func setEndingView(view: UIView?) {
animator.endingView = view
}
func didPanWithPanGestureRecognizer(pan: UIPanGestureRecognizer, viewToPan: UIView, anchorPoint: CGPoint) {
interactionController.didPanWithPanGestureRecognizer(pan, viewToPan: viewToPan, anchorPoint: anchorPoint)
}
}
extension PhotoTransitonController: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
animator.isDismissing = false
return animator
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
animator.isDismissing = true
return animator
}
func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if forcesNonInteractiveDismissal {
return nil
}
if let endingView = endingView {
self.animator.endingViewForAnimation = PhotoTransitionAnimator.newAnimationViewFromView(endingView)
}
interactionController.animator = animator
interactionController.shouldAnimateUsingAnimator = (endingView != nil)
interactionController.viewToHideWhenBeginningTransition = (startingView == nil) ? nil : endingView
return interactionController
}
}
| mit | 9e85f4fa8540e803a2101e8ea639132a | 28.369863 | 217 | 0.737873 | 5.906336 | false | false | false | false |
ayong6/iOSNote | swift语言/swift语言/AppDelegate.swift | 1 | 6082 | //
// AppDelegate.swift
// swift语言
//
// Created by Ayong on 16/1/12.
// Copyright © 2016年 阿勇. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "org.ayong.swift__" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("swift__", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| apache-2.0 | 6edfa4d14e56617a67f9c55a0533c5f1 | 53.693694 | 291 | 0.718168 | 5.877057 | false | false | false | false |
RobertGummesson/BuildTimeAnalyzer-for-Xcode | BuildTimeAnalyzer/ViewController.swift | 1 | 11163 | //
// ViewController.swift
// BuildTimeAnalyzer
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet var buildManager: BuildManager!
@IBOutlet weak var cancelButton: NSButton!
@IBOutlet weak var compileTimeTextField: NSTextField!
@IBOutlet weak var derivedDataTextField: NSTextField!
@IBOutlet weak var instructionsView: NSView!
@IBOutlet weak var leftButton: NSButton!
@IBOutlet weak var perFileButton: NSButton!
@IBOutlet weak var progressIndicator: NSProgressIndicator!
@IBOutlet weak var projectSelection: ProjectSelection!
@IBOutlet weak var searchField: NSSearchField!
@IBOutlet weak var statusLabel: NSTextField!
@IBOutlet weak var statusTextField: NSTextField!
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var tableViewContainerView: NSScrollView!
private let dataSource = ViewControllerDataSource()
private var currentKey: String?
private var nextDatabase: XcodeDatabase?
private var processor = LogProcessor()
var processingState: ProcessingState = .waiting {
didSet {
updateViewForState()
}
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureLayout()
buildManager.delegate = self
projectSelection.delegate = self
projectSelection.listFolders()
tableView.tableColumns[0].sortDescriptorPrototype = NSSortDescriptor(key: CompileMeasure.Order.time.rawValue, ascending: true)
tableView.tableColumns[1].sortDescriptorPrototype = NSSortDescriptor(key: CompileMeasure.Order.filename.rawValue, ascending: true)
NotificationCenter.default.addObserver(self, selector: #selector(windowWillClose(notification:)), name: NSWindow.willCloseNotification, object: nil)
}
override func viewWillAppear() {
super.viewWillAppear()
// Set window level before view is displayed
makeWindowTopMost(topMost: UserSettings.windowShouldBeTopMost)
}
override func viewWillDisappear() {
super.viewWillDisappear()
// Reset window level before view is hidden
// Reference: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/WinPanel/Concepts/WindowLevel.html
makeWindowTopMost(topMost: false)
}
@objc func windowWillClose(notification: NSNotification) {
guard let object = notification.object, !(object is NSPanel) else { return }
NotificationCenter.default.removeObserver(self)
processor.shouldCancel = true
NSApp.terminate(self)
}
// MARK: Layout
func configureLayout() {
updateTotalLabel(with: 0)
updateViewForState()
showInstructions(true)
derivedDataTextField.stringValue = UserSettings.derivedDataLocation
makeWindowTopMost(topMost: UserSettings.windowShouldBeTopMost)
}
func showInstructions(_ show: Bool) {
instructionsView.isHidden = !show
let views: [NSView] = [compileTimeTextField, leftButton, perFileButton, searchField, statusLabel, statusTextField, tableViewContainerView]
views.forEach{ $0.isHidden = show }
if show && processingState == .processing {
processor.shouldCancel = true
cancelButton.isHidden = true
progressIndicator.isHidden = true
}
}
func updateViewForState() {
switch processingState {
case .processing:
showInstructions(false)
progressIndicator.isHidden = false
progressIndicator.startAnimation(self)
statusTextField.stringValue = ProcessingState.processingString
cancelButton.isHidden = false
case .completed(_, let stateName):
progressIndicator.isHidden = true
progressIndicator.stopAnimation(self)
statusTextField.stringValue = stateName
cancelButton.isHidden = true
case .waiting:
progressIndicator.isHidden = true
progressIndicator.stopAnimation(self)
statusTextField.stringValue = ProcessingState.waitingForBuildString
cancelButton.isHidden = true
}
if instructionsView.isHidden {
searchField.isHidden = !cancelButton.isHidden
}
}
func makeWindowTopMost(topMost: Bool) {
if let window = NSApplication.shared.windows.first {
let level: CGWindowLevelKey = topMost ? .floatingWindow : .normalWindow
window.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(level)))
}
}
// MARK: Actions
@IBAction func perFileCheckboxClicked(_ sender: NSButton) {
dataSource.aggregateByFile = (sender.state.rawValue == 1)
tableView.reloadData()
}
@IBAction func clipboardButtonClicked(_ sender: AnyObject) {
NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects(["-Xfrontend -debug-time-function-bodies" as NSPasteboardWriting])
}
@IBAction func visitDerivedData(_ sender: AnyObject) {
NSWorkspace.shared.openFile(derivedDataTextField.stringValue)
}
@IBAction func cancelButtonClicked(_ sender: AnyObject) {
processor.shouldCancel = true
}
@IBAction func leftButtonClicked(_ sender: NSButton) {
configureMenuItems(showBuildTimesMenuItem: true)
cancelProcessing()
showInstructions(true)
projectSelection.listFolders()
}
func controlTextDidChange(_ obj: Notification) {
if let field = obj.object as? NSSearchField, field == searchField {
dataSource.filter = searchField.stringValue
tableView.reloadData()
} else if let field = obj.object as? NSTextField, field == derivedDataTextField {
buildManager.stopMonitoring()
UserSettings.derivedDataLocation = field.stringValue
projectSelection.listFolders()
buildManager.startMonitoring()
}
}
// MARK: Utilities
func cancelProcessing() {
guard processingState == .processing else { return }
processor.shouldCancel = true
cancelButton.isHidden = true
}
func configureMenuItems(showBuildTimesMenuItem: Bool) {
if let appDelegate = NSApp.delegate as? AppDelegate {
appDelegate.configureMenuItems(showBuildTimesMenuItem: showBuildTimesMenuItem)
}
}
func processLog(with database: XcodeDatabase) {
guard processingState != .processing else {
if let currentKey = currentKey, currentKey != database.key {
nextDatabase = database
processor.shouldCancel = true
}
return
}
configureMenuItems(showBuildTimesMenuItem: false)
processingState = .processing
currentKey = database.key
updateTotalLabel(with: database.buildTime)
processor.processDatabase(database: database) { [weak self] (result, didComplete, didCancel) in
self?.handleProcessorUpdate(result: result, didComplete: didComplete, didCancel: didCancel)
}
}
func handleProcessorUpdate(result: [CompileMeasure], didComplete: Bool, didCancel: Bool) {
dataSource.resetSourceData(newSourceData: result)
tableView.reloadData()
if didComplete {
completeProcessorUpdate(didCancel: didCancel)
}
}
func completeProcessorUpdate(didCancel: Bool) {
let didSucceed = !dataSource.isEmpty()
var stateName = ProcessingState.failedString
if didCancel {
stateName = ProcessingState.cancelledString
} else if didSucceed {
stateName = ProcessingState.completedString
}
processingState = .completed(didSucceed: didSucceed, stateName: stateName)
currentKey = nil
if let nextDatabase = nextDatabase {
self.nextDatabase = nil
processLog(with: nextDatabase)
}
if !didSucceed {
let text = "Ensure the Swift compiler flags has been added."
NSAlert.show(withMessage: ProcessingState.failedString, andInformativeText: text)
showInstructions(true)
configureMenuItems(showBuildTimesMenuItem: true)
}
}
func updateTotalLabel(with buildTime: Int) {
let text = "Build duration: " + (buildTime < 60 ? "\(buildTime)s" : "\(buildTime / 60)m \(buildTime % 60)s")
compileTimeTextField.stringValue = text
}
}
// MARK: NSTableViewDataSource
extension ViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return dataSource.count()
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
guard let item = dataSource.measure(index: row) else { return false }
NSWorkspace.shared.openFile(item.path)
let gotoLineScript =
"tell application \"Xcode\"\n" +
" activate\n" +
"end tell\n" +
"tell application \"System Events\"\n" +
" keystroke \"l\" using command down\n" +
" keystroke \"\(item.location)\"\n" +
" keystroke return\n" +
"end tell"
DispatchQueue.main.async {
if let script = NSAppleScript(source: gotoLineScript) {
script.executeAndReturnError(nil)
}
}
return true
}
}
// MARK: NSTableViewDelegate
extension ViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let tableColumn = tableColumn, let columnIndex = tableView.tableColumns.firstIndex(of: tableColumn) else { return nil }
guard let item = dataSource.measure(index: row) else { return nil }
let result = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell\(columnIndex)"), owner: self) as? NSTableCellView
result?.textField?.stringValue = item[columnIndex]
return result
}
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
dataSource.sortDescriptors = tableView.sortDescriptors
tableView.reloadData()
}
}
// MARK: BuildManagerDelegate
extension ViewController: BuildManagerDelegate {
func buildManager(_ buildManager: BuildManager, shouldParseLogWithDatabase database: XcodeDatabase) {
processLog(with: database)
}
func derivedDataDidChange() {
projectSelection.listFolders()
}
}
// MARK: ProjectSelectionDelegate
extension ViewController: ProjectSelectionDelegate {
func didSelectProject(with database: XcodeDatabase) {
processLog(with: database)
}
}
| mit | 98cc1fc2593bc7127c7703bda78f2a1d | 33.453704 | 156 | 0.651169 | 5.400581 | false | false | false | false |
AlphaJian/LarsonApp | LarsonApp/LarsonApp/Class/Appointment/Views/AppointmentsTableView.swift | 1 | 3217 | //
// AppointmentsTableView.swift
// LarsonApp
//
// Created by Jian Zhang on 11/1/16.
// Copyright © 2016 Jian Zhang. All rights reserved.
//
import UIKit
class AppointmentsTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var items = [AppointmentModel]()
var cellClickBlock: ReturnBlock?
var cellPhoneBlock: ReturnBlock?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
self.backgroundColor = UIColor(red: 226.0/255.0, green: 226.0/255.0, blue: 226.0/255.0, alpha: 1.0)
self.register(UINib(nibName: "TodoAppointmentTableViewCell", bundle: nil), forCellReuseIdentifier: "TODO")
self.register(UINib(nibName: "CompleteAppointmentTableViewCell", bundle: nil), forCellReuseIdentifier: "COMPLETE")
self.rowHeight = UITableViewAutomaticDimension
self.estimatedRowHeight = 60.0
self.separatorStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let appointModel: AppointmentModel = items[indexPath.section]
if appointModel.currentStatus.lowercased() == "completed" {
let cell: CompleteAppointmentTableViewCell = tableView.dequeueReusableCell(withIdentifier: "COMPLETE", for: indexPath) as! CompleteAppointmentTableViewCell
cell.setupCellData(model: appointModel)
return cell
} else {
let cell: TodoAppointmentTableViewCell = tableView.dequeueReusableCell(withIdentifier: "TODO", for: indexPath) as! TodoAppointmentTableViewCell
cell.setupCellData(model: appointModel)
return cell
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let placeholderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 10))
placeholderView.backgroundColor = .clear
return placeholderView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == items.count - 1 {
return 10.0
} else {
return 0
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let placeholderView = UIView()
placeholderView.backgroundColor = .clear
return placeholderView
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selecetedModel = items[indexPath.section]
if self.cellClickBlock != nil {
self.cellClickBlock!(selecetedModel)
}
}
}
| apache-2.0 | e5394de917fe65a02d17935ebfb45296 | 34.733333 | 167 | 0.660759 | 4.978328 | false | false | false | false |
sgtsquiggs/WordSearch | WordSearch/Coordinate.swift | 1 | 1492 | //
// Coordinate.swift
// WordSearch
//
// Created by Matthew Crenshaw on 11/7/15.
// Copyright © 2015 Matthew Crenshaw. All rights reserved.
//
import Foundation
struct Coordinate {
let x: Int
let y: Int
init(_ x: Int, _ y: Int) {
self.x = x
self.y = y
}
/// Decode array of coordinates from csv format "x1,y1,x2,y2,x3,y3,x4,y4".
static func decodeCsv(csv: String) -> [Coordinate]? {
let strings = csv.componentsSeparatedByString(",")
if strings.count % 2 != 0 {
return nil
}
let numbers = strings.flatMap({ Int($0) })
if strings.count != numbers.count {
return nil
}
var results: [Coordinate] = []
for var index = 0; index < numbers.count; index+=2 {
results.append(Coordinate(numbers[index], numbers[index+1]))
}
return results
}
func isCardinalToCoordinate(coordinate: Coordinate) -> Bool {
let deltaX = self.x - coordinate.x
let deltaY = self.y - coordinate.y
let radians = atan2(Double(deltaX), Double(deltaY))
let degrees = abs(radians * (180.0 / M_PI)) % 90
guard degrees == 0 || degrees == 45 else {
return false
}
return true
}
}
// MARK: - Equatable
extension Coordinate : Equatable {}
// comparison operator defined in global scope
func ==(lhs: Coordinate, rhs: Coordinate) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
| mit | f794511229fbf9099cdddebb2387369b | 25.157895 | 78 | 0.574111 | 3.793893 | false | false | false | false |
abelsanchezali/ViewBuilder | ViewBuilderDemo/ViewBuilderDemo/Integration/Models/NSLayoutConstraint+Models.swift | 1 | 3737 | //
// NSLayoutConstraint.swift
// ViewBuilderDemo
//
// Created by Abel Sanchez on 8/3/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import ViewBuilder
import UIKit
// MARK: - UILayoutConstraintAxis
extension NSLayoutConstraint.Axis: NSValueConvertible {
public func convertToNSValue() -> NSValue? {
return NSNumber(value: self.rawValue as Int)
}
}
public class Axis: Object, TextDeserializer {
private static let AxisByText: [String: NSLayoutConstraint.Axis] = ["Horizontal": NSLayoutConstraint.Axis.horizontal,
"Vertical": NSLayoutConstraint.Axis.vertical]
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let value = text else {
return nil
}
return Axis.AxisByText[value]
}
}
// MARK: - UIStackViewAlignment
@available(iOS 9.0, *)
extension UIStackView.Alignment: NSValueConvertible {
public func convertToNSValue() -> NSValue? {
return NSNumber(value: self.rawValue as Int)
}
}
@available(iOS 9.0, *)
class StackViewAlignment: TextDeserializer {
private static let StackViewAlignmentByText: [String: UIStackView.Alignment] = ["Fill": UIStackView.Alignment.fill,
"Leading": UIStackView.Alignment.leading,
"FirstBaseline": UIStackView.Alignment.firstBaseline,
"Center": UIStackView.Alignment.center,
"Trailing": UIStackView.Alignment.trailing,
"LastBaseline": UIStackView.Alignment.lastBaseline,
"Top": UIStackView.Alignment.top,
"Bottom": UIStackView.Alignment.bottom]
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let value = text else {
return nil
}
return StackViewAlignment.StackViewAlignmentByText[value]
}
}
// MARK: - UIStackViewDistribution
@available(iOS 9.0, *)
extension UIStackView.Distribution: NSValueConvertible {
public func convertToNSValue() -> NSValue? {
return NSNumber(value: self.rawValue as Int)
}
}
@available(iOS 9.0, *)
class StackViewDistribution: TextDeserializer {
private static let StackViewDistributionByText: [String: UIStackView.Distribution] = ["EqualCentering": UIStackView.Distribution.equalCentering,
"EqualSpacing": UIStackView.Distribution.equalSpacing,
"Fill": UIStackView.Distribution.fill,
"FillEqually": UIStackView.Distribution.fillEqually,
"FillProportionally": UIStackView.Distribution.fillProportionally]
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let value = text else {
return nil
}
return StackViewDistribution.StackViewDistributionByText[value]
}
}
| mit | f663a2dbdb70339ccfdb5ca40bf0f728 | 43.47619 | 156 | 0.530246 | 6.216306 | false | false | false | false |
Mazy-ma/DemoBySwift | Solive/Solive/Home/View/EmotionKeyboardView/EmotionView.swift | 1 | 6640 | //
// EmotionView.swift
// EmotionKeyboard
//
// Created by Mazy on 2017/8/25.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
protocol EmotionViewDataSource {
func numberOfSections(in emotionView: EmotionView) -> Int
func numberOfItemsInSection(emotionView: EmotionView, section: Int) -> Int
func collectionView(emotionView: EmotionView, collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
}
@objc protocol EmotionViewDelegate {
@objc optional func collectionView(collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
}
class EmotionView: UIView {
var dataSource: EmotionViewDataSource?
var delegate: EmotionViewDelegate?
var collectionView: UICollectionView?
fileprivate var pageControl: UIPageControl!
fileprivate var flowLayout: CollectionViewHorizontalFlowLayout
fileprivate var titleView: TopTitlesView!
fileprivate var titleProperty: TitleViewProperty
fileprivate var titles: [String]
fileprivate var sourceIndexPath : IndexPath = IndexPath(item: 0, section: 0)
init(frame: CGRect,titles: [String], layout: CollectionViewHorizontalFlowLayout, property: TitleViewProperty) {
self.flowLayout = layout
self.titleProperty = property
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension EmotionView {
func setupUI() {
let kWidth: CGFloat = UIScreen.main.bounds.width
collectionView = UICollectionView(frame: CGRect(x: 0, y: titleProperty.isInTop ? 0 : titleProperty.titleHeight, width: self.bounds.width, height: self.bounds.height - titleProperty.titleHeight - titleProperty.titleMargin), collectionViewLayout: flowLayout)
collectionView?.isPagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.dataSource = self
collectionView?.delegate = self
addSubview(collectionView!)
collectionView?.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin, .flexibleHeight]
pageControl = UIPageControl(frame: CGRect(x: 0, y: collectionView!.frame.maxY, width: kWidth, height: 20))
pageControl.backgroundColor = UIColor.black
pageControl.isUserInteractionEnabled = false
addSubview(pageControl)
pageControl.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleTopMargin]
titleProperty.isScrollEnable = false
titleProperty.isHiddenBottomLine = false
titleView = TopTitlesView(frame: CGRect(x: 0, y: titleProperty.isInTop ? pageControl.frame.maxY : 0, width: kWidth, height: titleProperty.titleHeight), titles: titles, titleProperty: titleProperty)
titleView.delegate = self
addSubview(titleView)
}
}
extension EmotionView: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource?.numberOfSections(in: self) ?? 0
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let itemCount = dataSource?.numberOfItemsInSection(emotionView: self, section: section) ?? 0
if section == 0 {
pageControl.numberOfPages = (itemCount - 1) / (flowLayout.cols * flowLayout.rows) + 1
}
return itemCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return dataSource!.collectionView(emotionView: self, collectionView: collectionView, cellForItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let delegate = delegate {
delegate.collectionView!(collectionView: collectionView, didSelectItemAt: indexPath)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewEndScroll()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollViewEndScroll()
}
}
fileprivate func scrollViewEndScroll() {
// 1.取出在屏幕中显示的Cell
let point = CGPoint(x: flowLayout.sectionInset.left + 2 + collectionView!.contentOffset.x, y: flowLayout.sectionInset.top + 2)
guard let indexPath = collectionView?.indexPathForItem(at: point) else { return }
// 3.2.设置titleView位置
titleView.setTitleWithContentOffset(UIScreen.main.bounds.width * CGFloat(indexPath.section))
// 2.判断分组是否有发生改变
if sourceIndexPath.section != indexPath.section {
// 修改 pageControl 的个数
let itemCount = dataSource?.numberOfItemsInSection(emotionView: self, section: indexPath.section) ?? 0
pageControl.numberOfPages = (itemCount - 1) / (flowLayout.cols * flowLayout
.rows) + 1
// 3.3.记录最新indexPath
sourceIndexPath = indexPath
}
// 3.根据indexPath设置pageControl
pageControl.currentPage = indexPath.item / (flowLayout.cols * flowLayout.rows)
}
}
// MARK: - 开放方法,注册 cell
extension EmotionView {
open func register(cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String) {
collectionView?.register(cellClass, forCellWithReuseIdentifier: identifier)
}
open func register(nib: UINib?, forCellWithReuseIdentifier identifier: String) {
collectionView?.register(nib, forCellWithReuseIdentifier: identifier)
}
}
extension EmotionView: TopTitlesViewDelegate {
func didClickTopTitleView(_ titlesView: TopTitlesView, selectedIndex index: Int) {
let indexPath = IndexPath(item: 0, section: index)
collectionView?.scrollToItem(at: indexPath, at: .left, animated: false)
collectionView!.contentOffset.x -= flowLayout.sectionInset.left
// 修改 pageControl 的个数
let itemCount = dataSource?.numberOfItemsInSection(emotionView: self, section: indexPath.section) ?? 0
pageControl.numberOfPages = (itemCount - 1) / (flowLayout.cols * flowLayout.rows) + 1
// 3.3.记录最新indexPath
sourceIndexPath = indexPath
}
}
| apache-2.0 | 5a296fbea7b69fafc92eab6d36b999fe | 39.067485 | 264 | 0.694534 | 5.419917 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Option/ReformaCrossing/Lane/Abstract/MOptionReformaCrossingLane.swift | 1 | 1749 | import UIKit
class MOptionReformaCrossingLane:MGameUpdate<MOptionReformaCrossing>
{
let positionY:CGFloat
var foes:[MOptionReformaCrossingFoeItem]
private(set) var possibleFoes:[MOptionReformaCrossingFoeItem.Type]
private(set) var direction:CGFloat
private(set) var sceneWidth:CGFloat
private(set) var addedSpeed:CGFloat
private let deltaVertical:CGFloat
init(deltaVertical:CGFloat)
{
self.deltaVertical = deltaVertical
foes = []
possibleFoes = []
direction = 0
addedSpeed = 0
let size:CGSize = MGame.sceneSize
let sceneHeight_2:CGFloat = size.height / 2.0
sceneWidth = size.width
positionY = sceneHeight_2 + deltaVertical
super.init()
}
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionReformaCrossing>)
{
for foe:MOptionReformaCrossingFoeItem in foes
{
foe.update(
elapsedTime:elapsedTime,
scene:scene)
}
}
//MARK: public
func foeTrip(foe:MOptionReformaCrossingFoeItem) -> MOptionReformaCrossingFoeItemTrip?
{
return nil
}
func hasFoeWaiting() -> Bool
{
return false
}
func removeFoe(item:MOptionReformaCrossingFoeItem)
{
var foes:[MOptionReformaCrossingFoeItem] = []
for foe:MOptionReformaCrossingFoeItem in self.foes
{
if foe !== item
{
foes.append(foe)
}
}
self.foes = foes
}
func restart(addedSpeed:CGFloat)
{
self.addedSpeed = addedSpeed
foes = []
}
}
| mit | 1da1a502a757de33b1a6fa9ed26468bb | 22.958904 | 89 | 0.587764 | 4.651596 | false | false | false | false |
vknabel/Rock | Sources/RockLib/Rockfile.swift | 1 | 4701 | import Foundation
import Yaml
import Result
import PathKit
import PromptLine
public extension Array {
func flatMap<ElementOfResult, ErrorOfResult: Error>(
_ transform: (Element) -> Result<ElementOfResult, ErrorOfResult>
) -> Result<[ElementOfResult], ErrorOfResult> {
return self.reduce(.success([]), { (previousResult, element) -> Result<[ElementOfResult], ErrorOfResult> in
return previousResult.flatMap({ p in transform(element).map({ p + [$0] })})
})
}
}
public enum Dependency {
public typealias Name = String
public typealias Version = String
case named(Name, Version?)
case inlined(RocketSpec, Version?)
case overriding(Name, Yaml, Version?)
public static func from(string: String) -> Dependency? {
let fragments = string.components(separatedBy: "@")
guard let head = fragments.first else { return nil }
let version = fragments.dropFirst().first
return Dependency.named(head, version ?? "master")
}
}
public extension Dependency {
public static func fromYaml(_ yaml: Yaml) -> Result<Dependency, RockError> {
switch yaml {
case let .dictionary(root):
if case .some(.string(_)) = root["url"], case let .some(.string(name)) = root["name"] {
return RocketSpec.fromYaml(yaml, named: name)
.map {
Dependency.inlined($0, root["version"]?.string)
}
} else if case .some(.string(_)) = root["name"] {
return .failure(.notImplemented("Dependencies by name are not supported yet"))
}
return .failure(.notImplemented("Cannot handle dictionary dependencies without url and name"))
case let .string(name):
return .success(Dependency.from(string: name) ?? .named(name, "master"))
default:
return .failure(.rockfileHasInvalidDependency)
}
}
}
/// Represents a Rockfile.yaml file.
///
/// ```yaml
/// swift-version: 3.0.1
/// dependencies:
/// - needless
/// - name: sourcery
/// version: 0.5.0
/// - name: langserver-swift
/// swift-version: DEVELOPMENT-SNAPSHOT-2016-12-01-a
/// - name: xcopen
/// url: https://github.com/vknabel/xcopen
/// ```
public struct Rockfile {
public typealias Runner = PromptRunner<RockError>
public let name: String
public let dependencies: [Dependency]
public let scriptRunners: [String: Runner]
public static func global(with dependencies: [Dependency]) -> Rockfile {
return Rockfile(name: "global", dependencies: dependencies, scriptRunners: [:])
}
}
public extension Rockfile {
public static func fromPath(_ path: Path) -> Result<Rockfile, RockError> {
let yaml = Result<Yaml, AnyError>(attempt: {
do {
let text: String = try (path + "Rockfile").read()
return try Yaml.rendering(text)
} catch {
throw AnyError(error)
}
}).mapError { anyError -> RockError in
if case let Yaml.ResultError.message(message) = anyError.error {
return RockError.rockfileIsNotValidYaml(message)
} else {
return RockError.rockfileCouldNotBeRead(path, anyError.error)
}
}
return yaml.flatMap(Rockfile.fromYaml)
}
public static func fromYaml(_ yaml: Yaml) -> Result<Rockfile, RockError> {
guard case let .dictionary(root) = yaml
else { return .failure(.rockfileMustContainDictionary) }
guard case let .some(.string(name)) = root["name"]
else { return .failure(.rockfileMustHaveAName) }
guard case let .some(.array(rawDependencies)) = root["dependencies"]
else { return .failure(.rockfileMustHaveDependencies) }
return rawDependencies.flatMap(Dependency.fromYaml).map {
let defaultScripts = [
"build": runnerFromStrings(yaml["build"].stringArray ?? [], or: RockConfig.rockConfig.debugBuildScript)
%? { RockError.rockfileCustomScriptFailed("build", $0) },
"test": runnerFromStrings(yaml["test"].stringArray ?? [], or: RockConfig.rockConfig.testScript)
%? { RockError.rockfileCustomScriptFailed("test", $0) },
"archive": runnerFromStrings(yaml["archive"].stringArray ?? [], or: RockConfig.rockConfig.archiveScript)
%? { RockError.rockfileCustomScriptFailed("archive", $0) }
]
let scripts = (yaml.dictionary?["scripts"]?.dictionary ?? [:])
.reduce(defaultScripts, { (scripts, element) in
if let name = element.key.string, let shell = element.value.stringArray {
var scripts = scripts
scripts[name] = runnerFromStrings(shell, or: []) %? { RockError.rockfileCustomScriptFailed(name, $0) }
return scripts
} else {
return scripts
}
})
return Rockfile(name: name, dependencies: $0, scriptRunners: scripts)
}
}
}
| mit | f5f4207198df3eb2706575e0b64b87df | 35.726563 | 114 | 0.65986 | 4.045611 | false | false | false | false |
adrfer/swift | test/1_stdlib/Filter.swift | 2 | 2039 | //===--- Filter.swift - tests for lazy filtering --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
// 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
#if _runtime(_ObjC)
import ObjectiveC
#endif
let FilterTests = TestSuite("Filter")
// Check that the generic parameter is called 'Base'.
protocol TestProtocol1 {}
extension LazyFilterGenerator where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension LazyFilterSequence where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension LazyFilterIndex where BaseElements : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension LazyFilterCollection where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
FilterTests.test("filtering collections") {
let f0 = LazyFilterCollection(0..<30) { $0 % 7 == 0 }
expectEqualSequence([0, 7, 14, 21, 28], f0)
let f1 = LazyFilterCollection(1..<30) { $0 % 7 == 0 }
expectEqualSequence([7, 14, 21, 28], f1)
}
FilterTests.test("filtering sequences") {
let f0 = (0..<30).generate().lazy.filter { $0 % 7 == 0 }
expectEqualSequence([0, 7, 14, 21, 28], f0)
let f1 = (1..<30).generate().lazy.filter { $0 % 7 == 0 }
expectEqualSequence([7, 14, 21, 28], f1)
}
runAllTests()
| apache-2.0 | 038e18970b6e55bcd5d27846dea84052 | 28.128571 | 80 | 0.672388 | 4.094378 | false | true | false | false |
DavdRoman/rehatch | Sources/CLI/Logger.swift | 1 | 1498 | import Foundation
import CLISpinner
public enum Logger {
private static let pattern = Pattern.dots
private static let spinner = Spinner(pattern: pattern, color: .lightCyan)
private static var isStepping = false
public static func step(_ description: String, succeedPrevious: Bool = true) {
if isStepping, succeedPrevious {
spinner.text = description
} else {
spinner._text = description
}
spinner.pattern = Pattern(from: pattern.symbols.map { $0.applyingColor(.lightCyan) })
spinner.start()
isStepping = true
}
public static func info(_ description: String, succeedPrevious: Bool = true) {
if isStepping, succeedPrevious {
spinner.succeed()
}
spinner.info(text: description)
isStepping = false
}
public static func warn(_ description: String, succeedPrevious: Bool = true) {
if isStepping, succeedPrevious {
spinner.succeed()
}
spinner.warn(text: description)
isStepping = false
}
public static func fail(_ description: String) {
if isStepping {
spinner.fail()
isStepping = false
} else {
spinner.fail(text: "An error ocurred")
}
let prettifiedErrorDescription = description
.components(separatedBy: "\n")
.map { "☛ " + $0 }
.joined(separator: "\n")
fputs(prettifiedErrorDescription + "\n", stderr)
}
public static func succeed(_ description: String? = nil) {
if isStepping {
spinner.succeed(text: description)
isStepping = false
}
}
public static func finish() {
spinner.unhideCursor()
}
}
| mit | 905cc4b1ab50813c6ff0a19971399e37 | 22.746032 | 87 | 0.701203 | 3.536643 | false | false | false | false |
halo/LinkLiar | LinkTools/FileObserver.swift | 1 | 3645 | /*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* 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.
*/
// See https://blog.beecomedigital.com/2015/06/27/developing-a-filesystemwatcher-for-os-x-by-using-fsevents-with-swift-2/
// See https://gist.github.com/DivineDominion/56e56f3db43216d9eaab300d3b9f049a
import Foundation
public class FileObserver {
let callback: () -> Void
public init(path: String, sinceWhen: FSEventStreamEventId = FSEventStreamEventId(kFSEventStreamEventIdSinceNow), callback: @escaping () -> Void) {
self.lastEventId = sinceWhen
self.pathsToWatch = [path]
self.callback = callback
start()
}
deinit {
stop()
}
// MARK: - Private Properties
typealias FSEventStreamCallback = @convention(c) (ConstFSEventStreamRef, UnsafeMutableRawPointer?, Int, UnsafeMutableRawPointer, UnsafePointer<FSEventStreamEventFlags>, UnsafePointer<FSEventStreamEventId>) -> Void
private let eventCallback: FSEventStreamCallback = { (stream, contextInfo, numEvents, eventPaths, eventFlags, eventIds) in
let fileSystemWatcher: FileObserver = unsafeBitCast(contextInfo, to: FileObserver.self)
guard let paths = unsafeBitCast(eventPaths, to: NSArray.self) as? [String] else { return }
for index in 0..<numEvents {
fileSystemWatcher.processEvent(eventId: eventIds[index], eventPath: paths[index], eventFlags: eventFlags[index])
}
fileSystemWatcher.lastEventId = eventIds[numEvents - 1]
}
private let pathsToWatch: [String]
private var started = false
private var streamRef: FSEventStreamRef!
private func processEvent(eventId: FSEventStreamEventId, eventPath: String, eventFlags: FSEventStreamEventFlags) {
callback()
}
public private(set) var lastEventId: FSEventStreamEventId
public func start() {
guard started == false else { return }
var context = FSEventStreamContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = Unmanaged.passUnretained(self).toOpaque()
let flags = UInt32(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents)
streamRef = FSEventStreamCreate(kCFAllocatorDefault, eventCallback, &context, pathsToWatch as CFArray, lastEventId, 0, flags)
FSEventStreamScheduleWithRunLoop(streamRef, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
FSEventStreamStart(streamRef)
started = true
}
public func stop() {
guard started == true else { return }
FSEventStreamStop(streamRef)
FSEventStreamInvalidate(streamRef)
FSEventStreamRelease(streamRef)
streamRef = nil
started = false
}
}
| mit | 83532600332a3e3e53ec1e22732cd274 | 40.896552 | 215 | 0.760219 | 4.396864 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/GroupCallInvitation.swift | 1 | 28257 | //
// GroupCallInv.swift
// Telegram
//
// Created by Mikhail Filimonov on 12.12.2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
import Postbox
import ColorPalette
import TelegramCore
private final class InvitationArguments {
let account: Account
let copyLink: (String)->Void
let inviteGroupMember:(PeerId)->Void
let inviteContact:(PeerId)->Void
init(account: Account, copyLink: @escaping(String)->Void, inviteGroupMember:@escaping(PeerId)->Void, inviteContact:@escaping(PeerId)->Void) {
self.account = account
self.copyLink = copyLink
self.inviteGroupMember = inviteGroupMember
self.inviteContact = inviteContact
}
}
private struct InvitationPeer : Equatable {
let peer: Peer
let presence: PeerPresence?
let contact: Bool
let enabled: Bool
static func ==(lhs:InvitationPeer, rhs: InvitationPeer) -> Bool {
if !lhs.peer.isEqual(rhs.peer) {
return false
}
if let lhsPresence = lhs.presence, let rhsPresence = rhs.presence {
return lhsPresence.isEqual(to: rhsPresence)
} else if (lhs.presence != nil) != (rhs.presence != nil) {
return false
}
if lhs.contact != rhs.contact {
return false
}
if lhs.enabled != rhs.enabled {
return false
}
return true
}
}
final class GroupCallAddMembersBehaviour : SelectPeersBehavior {
fileprivate let data: GroupCallUIController.UIData
private let disposable = MetaDisposable()
private let window: Window
init(data: GroupCallUIController.UIData, window: Window) {
self.data = data
self.window = window
super.init(settings: [], excludePeerIds: [], limit: 1, customTheme: { GroupCallTheme.customTheme })
}
private let cachedContacts:Atomic<[PeerId]> = Atomic(value: [])
func isContact(_ peerId: PeerId) -> Bool {
return cachedContacts.with {
$0.contains(peerId)
}
}
override func start(context: AccountContext, search: Signal<SearchState, NoError>, linkInvation: ((Int) -> Void)? = nil) -> Signal<([SelectPeerEntry], Bool), NoError> {
let peerMemberContextsManager = data.peerMemberContextsManager
let account = data.call.account
let peerId = data.call.peerId
let engine = data.call.engine
let customTheme = self.customTheme
let cachedContacts = self.cachedContacts
let members = data.call.members |> filter { $0 != nil } |> map { $0! }
let invited = data.call.invitedPeers
let peer = data.call.peer
let isUnmutedForAll: Signal<Bool, NoError> = data.call.state |> take(1) |> map { value in
if let muteState = value.defaultParticipantMuteState {
switch muteState {
case .muted:
return false
case .unmuted:
return true
}
}
return false
}
return search |> mapToSignal { search in
var contacts:Signal<([Peer], [PeerId : PeerPresence]), NoError>
if search.request.isEmpty {
contacts = context.engine.data.subscribe(TelegramEngine.EngineData.Item.Contacts.List(includePresences: true)) |> map {
return ($0.peers.map { $0._asPeer() }, $0.presences.mapValues { $0._asPresence() })
}
} else {
contacts = context.engine.contacts.searchContacts(query: search.request) |> map {
($0.0.map { $0._asPeer() }, $0.1.mapValues { $0._asPresence() })
}
}
contacts = combineLatest(account.postbox.peerView(id: peerId), contacts) |> map { peerView, contacts in
if let peer = peerViewMainPeer(peerView) {
if peer.groupAccess.canAddMembers {
return contacts
} else {
return ([], [:])
}
} else {
return ([], [:])
}
}
let globalSearch: Signal<[Peer], NoError>
if search.request.isEmpty {
globalSearch = .single([])
} else if let peer = peer, peer.groupAccess.canAddMembers {
globalSearch = engine.contacts.searchRemotePeers(query: search.request.lowercased()) |> map {
return $0.0.map {
$0.peer
} + $0.1.map {
$0.peer
}
}
} else {
globalSearch = .single([])
}
struct Participant {
let peer: Peer
let presence: PeerPresence?
}
let groupMembers:Signal<[Participant], NoError> = Signal { subscriber in
let disposable: Disposable
if peerId.namespace == Namespaces.Peer.CloudChannel {
(disposable, _) = peerMemberContextsManager.recent(peerId: peerId, searchQuery: search.request.isEmpty ? nil : search.request, updated: { state in
if case .ready = state.loadingState {
subscriber.putNext(state.list.map {
return Participant(peer: $0.peer, presence: $0.presences[$0.peer.id])
})
subscriber.putCompletion()
}
})
} else {
let signal: Signal<[Participant], NoError> = account.postbox.peerView(id: peerId) |> map { peerView in
let participants = (peerView.cachedData as? CachedGroupData)?.participants
let list:[Participant] = participants?.participants.compactMap { value in
if let peer = peerView.peers[value.peerId] {
return Participant(peer: peer, presence: peerView.peerPresences[value.peerId])
} else {
return nil
}
} ?? []
return list
}
disposable = signal.start(next: { list in
subscriber.putNext(list)
})
}
return disposable
}
let allMembers: Signal<([InvitationPeer], [InvitationPeer], [InvitationPeer]), NoError> = combineLatest(groupMembers, members, contacts, globalSearch, invited) |> map { recent, participants, contacts, global, invited in
let membersList = recent.filter { value in
if participants.participants.contains(where: { $0.peer.id == value.peer.id }) {
return false
}
return !value.peer.isBot
}.map {
InvitationPeer(peer: $0.peer, presence: $0.presence, contact: false, enabled: !invited.contains($0.peer.id))
}
var contactList:[InvitationPeer] = []
for contact in contacts.0 {
let containsInCall = participants.participants.contains(where: { $0.peer.id == contact.id })
let containsInMembers = membersList.contains(where: { $0.peer.id == contact.id })
if !containsInMembers && !containsInCall {
contactList.append(InvitationPeer(peer: contact, presence: contacts.1[contact.id], contact: true, enabled: !invited.contains(contact.id)))
}
}
var globalList:[InvitationPeer] = []
for peer in global {
let containsInCall = participants.participants.contains(where: { $0.peer.id == peer.id })
let containsInMembers = membersList.contains(where: { $0.peer.id == peer.id })
let containsInContacts = contactList.contains(where: { $0.peer.id == peer.id })
if !containsInMembers && !containsInCall && !containsInContacts {
if !peer.isBot && peer.isUser {
globalList.append(.init(peer: peer, presence: nil, contact: false, enabled: !invited.contains(peer.id)))
}
}
}
_ = cachedContacts.swap(contactList.map { $0.peer.id } + globalList.map { $0.peer.id })
return (membersList, contactList, globalList)
}
let previousSearch: Atomic<String> = Atomic<String>(value: "")
return combineLatest(queue: .mainQueue(), allMembers, isUnmutedForAll) |> map { members, isUnmutedForAll in
var entries:[SelectPeerEntry] = []
var index:Int32 = 0
if search.request.isEmpty {
if let linkInvation = linkInvation, let peer = peer {
if peer.groupAccess.canMakeVoiceChat {
if peer.isSupergroup, isUnmutedForAll {
entries.append(.inviteLink(strings().voiceChatInviteCopyInviteLink, GroupCallTheme.invite_link, 0, customTheme(), linkInvation))
} else {
entries.append(.inviteLink(strings().voiceChatInviteCopyListenersLink, GroupCallTheme.invite_listener, 0, customTheme(), linkInvation))
entries.append(.inviteLink(strings().voiceChatInviteCopySpeakersLink, GroupCallTheme.invite_speaker, 1, customTheme(), linkInvation))
}
} else {
entries.append(.inviteLink(strings().voiceChatInviteCopyInviteLink, GroupCallTheme.invite_link, 0, customTheme(), linkInvation))
}
}
}
if !members.0.isEmpty {
entries.append(.separator(index, customTheme(), strings().voiceChatInviteGroupMembers))
index += 1
}
for member in members.0 {
entries.append(.peer(SelectPeerValue(peer: member.peer, presence: member.presence, subscribers: nil, customTheme: customTheme()), index, member.enabled))
index += 1
}
if !members.1.isEmpty {
entries.append(.separator(index, customTheme(), strings().voiceChatInviteContacts))
index += 1
}
for member in members.1 {
entries.append(.peer(SelectPeerValue(peer: member.peer, presence: member.presence, subscribers: nil, customTheme: customTheme()), index, member.enabled))
index += 1
}
if !members.2.isEmpty {
entries.append(.separator(index, customTheme(), strings().voiceChatInviteGlobalSearch))
index += 1
}
for member in members.2 {
entries.append(.peer(SelectPeerValue(peer: member.peer, presence: member.presence, subscribers: nil, customTheme: customTheme()), index, member.enabled))
index += 1
}
let updatedSearch = previousSearch.swap(search.request) != search.request
if entries.isEmpty {
entries.append(.searchEmpty(customTheme(), NSImage(named: "Icon_EmptySearchResults")!.precomposed(customTheme().grayTextColor)))
}
return (entries, updatedSearch)
}
}
}
deinit {
var bp:Int = 0
bp += 1
}
}
final class GroupCallInviteMembersBehaviour : SelectPeersBehavior {
fileprivate let data: GroupCallUIController.UIData
private let disposable = MetaDisposable()
private let window: Window
init(data: GroupCallUIController.UIData, window: Window) {
self.data = data
self.window = window
super.init(settings: [], excludePeerIds: [], limit: 100, customTheme: { GroupCallTheme.customTheme })
}
override var okTitle: String? {
return strings().voiceChatInviteInvite
}
private let cachedContacts:Atomic<[PeerId]> = Atomic(value: [])
func isContact(_ peerId: PeerId) -> Bool {
return cachedContacts.with {
$0.contains(peerId)
}
}
override func start(context: AccountContext, search: Signal<SearchState, NoError>, linkInvation: ((Int) -> Void)? = nil) -> Signal<([SelectPeerEntry], Bool), NoError> {
let account = data.call.account
let peerId = data.call.peerId
let engine = data.call.engine
let customTheme = self.customTheme
let cachedContacts = self.cachedContacts
let members = data.call.members |> filter { $0 != nil } |> map { $0! }
let invited = data.call.invitedPeers
let peer = data.call.peer
let isUnmutedForAll: Signal<Bool, NoError> = data.call.state |> take(1) |> map { value in
if let muteState = value.defaultParticipantMuteState {
switch muteState {
case .muted:
return false
case .unmuted:
return true
}
}
return false
}
return search |> mapToSignal { search in
var dialogs:Signal<([Peer]), NoError>
if search.request.isEmpty {
dialogs = account.viewTracker.tailChatListView(groupId: .root, count: 100) |> map { value in
var entries:[Peer] = []
for entry in value.0.entries.reversed() {
switch entry {
case let .MessageEntry(_, _, _, _, _, renderedPeer, _, _, _, _, _):
if let peer = renderedPeer.chatMainPeer, peer.canSendMessage() {
entries.append(peer)
}
default:
break
}
}
return entries
}
} else {
dialogs = .single([])
}
let globalSearch: Signal<[Peer], NoError>
if search.request.isEmpty {
globalSearch = .single([])
} else {
globalSearch = engine.contacts.searchRemotePeers(query: search.request.lowercased()) |> map {
return $0.0.map {
$0.peer
} + $0.1.map {
$0.peer
}
}
}
struct Participant {
let peer: Peer
let presence: PeerPresence?
}
let allMembers: Signal<([InvitationPeer], [InvitationPeer]), NoError> = combineLatest(members, dialogs, globalSearch, invited) |> map { recent, contacts, global, invited in
let membersList = recent.participants.map {
InvitationPeer(peer: $0.peer, presence: nil, contact: false, enabled: !invited.contains($0.peer.id))
}
var contactList:[InvitationPeer] = []
for contact in contacts {
let containsInMembers = membersList.contains(where: { $0.peer.id == contact.id })
if !containsInMembers {
contactList.append(InvitationPeer(peer: contact, presence: nil, contact: true, enabled: !invited.contains(contact.id)))
}
}
var globalList:[InvitationPeer] = []
for peer in global {
let containsInMembers = membersList.contains(where: { $0.peer.id == peer.id })
let containsInContacts = contactList.contains(where: { $0.peer.id == peer.id })
if !containsInMembers && !containsInContacts {
if peer.canSendMessage() {
globalList.append(.init(peer: peer, presence: nil, contact: false, enabled: !invited.contains(peer.id)))
}
}
}
_ = cachedContacts.swap(contactList.map { $0.peer.id } + globalList.map { $0.peer.id })
return (contactList, globalList)
}
let inviteLink: Signal<Bool, NoError> = account.viewTracker.peerView(peerId) |> map { peerView in
if let peer = peerViewMainPeer(peerView) {
return peer.groupAccess.canMakeVoiceChat
}
return (false)
}
let previousSearch: Atomic<String> = Atomic<String>(value: "")
return combineLatest(allMembers, inviteLink, isUnmutedForAll) |> map { members, inviteLink, isUnmutedForAll in
var entries:[SelectPeerEntry] = []
var index:Int32 = 0
if search.request.isEmpty {
if let linkInvation = linkInvation, let peer = peer {
if peer.addressName != nil {
if peer.groupAccess.canMakeVoiceChat {
if peer.isSupergroup, isUnmutedForAll {
entries.append(.inviteLink(strings().voiceChatInviteCopyInviteLink, GroupCallTheme.invite_link, 0, customTheme(), linkInvation))
} else {
entries.append(.inviteLink(strings().voiceChatInviteCopyListenersLink, GroupCallTheme.invite_listener, 0, customTheme(), linkInvation))
entries.append(.inviteLink(strings().voiceChatInviteCopySpeakersLink, GroupCallTheme.invite_speaker, 1, customTheme(), linkInvation))
}
} else {
entries.append(.inviteLink(strings().voiceChatInviteCopyInviteLink, GroupCallTheme.invite_link, 0, customTheme(), linkInvation))
}
} else {
entries.append(.inviteLink(strings().voiceChatInviteCopyInviteLink, GroupCallTheme.invite_link, 0, customTheme(), linkInvation))
}
}
}
if !members.0.isEmpty {
entries.append(.separator(index, customTheme(), strings().voiceChatInviteChats))
index += 1
}
for member in members.0 {
entries.append(.peer(SelectPeerValue(peer: member.peer, presence: member.presence, subscribers: nil, customTheme: customTheme(), ignoreStatus: true), index, member.enabled))
index += 1
}
if !members.1.isEmpty {
entries.append(.separator(index, customTheme(), strings().voiceChatInviteGlobalSearch))
index += 1
}
for member in members.1 {
entries.append(.peer(SelectPeerValue(peer: member.peer, presence: nil, subscribers: nil, customTheme: customTheme(), ignoreStatus: true), index, member.enabled))
index += 1
}
let updatedSearch = previousSearch.swap(search.request) != search.request
if entries.isEmpty {
entries.append(.searchEmpty(customTheme(), NSImage(named: "Icon_EmptySearchResults")!.precomposed(customTheme().grayTextColor)))
}
return (entries, updatedSearch)
}
}
}
}
func GroupCallAddmembers(_ data: GroupCallUIController.UIData, window: Window) -> Signal<[PeerId], NoError> {
let behaviour: SelectPeersBehavior
let title: String
if let peer = data.call.peer, peer.isChannel {
title = strings().voiceChatInviteChannelsTitle
behaviour = GroupCallInviteMembersBehaviour(data: data, window: window)
} else {
title = strings().voiceChatInviteTitle
behaviour = GroupCallAddMembersBehaviour(data: data, window: window)
}
let account = data.call.account
let context = data.call.accountContext
let callPeerId = data.call.peerId
let peerMemberContextsManager = data.peerMemberContextsManager
let peer = data.call.peer
let links = data.call.inviteLinks
return selectModalPeers(window: window, context: data.call.accountContext, title: title, settings: [], excludePeerIds: [], limit: behaviour is GroupCallAddMembersBehaviour ? 1 : 100, behavior: behaviour, confirmation: { [weak behaviour, weak window, weak data] peerIds in
if let behaviour = behaviour as? GroupCallAddMembersBehaviour {
guard let peerId = peerIds.first else {
return .single(false)
}
if behaviour.isContact(peerId) {
return account.postbox.transaction {
return (user: $0.getPeer(peerId), chat: $0.getPeer(callPeerId))
} |> mapToSignal { [weak window] values in
if let window = window {
return confirmSignal(for: window, information: strings().voiceChatInviteMemberToGroupFirstText(values.user?.displayTitle ?? "", values.chat?.displayTitle ?? ""), okTitle: strings().voiceChatInviteMemberToGroupFirstAdd, appearance: darkPalette.appearance) |> filter { $0 }
|> take(1)
|> mapToSignal { _ in
if peerId.namespace == Namespaces.Peer.CloudChannel {
return peerMemberContextsManager.addMember(peerId: callPeerId, memberId: peerId) |> map { _ in
return true
}
} else {
return context.engine.peers.addGroupMember(peerId: callPeerId, memberId: peerId)
|> map {
return true
} |> `catch` { _ in
return .single(false)
}
}
} |> deliverOnMainQueue
} else {
return .single(false)
}
}
} else {
return .single(true)
}
} else if let call = data?.call {
let isUnmutedForAll: Signal<Bool, NoError> = call.state |> take(1) |> map { value in
if let muteState = value.defaultParticipantMuteState {
switch muteState {
case .muted:
return false
case .unmuted:
return true
}
}
return false
}
return combineLatest(queue: .mainQueue(), links, isUnmutedForAll) |> mapToSignal { [weak window] links, isUnmutedForAll in
return Signal { [weak window] subscriber in
if let window = window, let links = links, let peer = peer {
let third: String?
if peer.groupAccess.canMakeVoiceChat, peer.addressName != nil {
if peer.isSupergroup && isUnmutedForAll {
third = nil
} else {
third = strings().voiceChatInviteConfirmThird
}
} else {
third = nil
}
if let third = third {
modernConfirm(for: window, header: strings().voiceChatInviteConfirmHeader, information: strings().voiceChatInviteConfirmText, okTitle: strings().voiceChatInviteConfirmOK, cancelTitle: strings().modalCancel, thridTitle: third, successHandler: { result in
let link: String
switch result {
case .basic:
link = links.listenerLink
case .thrid:
link = links.speakerLink ?? links.listenerLink
}
for peerId in peerIds {
_ = enqueueMessages(account: account, peerId: peerId, messages: [EnqueueMessage.message(text: link, attributes: [], inlineStickers: [:], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])]).start()
}
subscriber.putNext(true)
subscriber.putCompletion()
}, appearance: GroupCallTheme.customTheme.appearance)
} else {
for peerId in peerIds {
_ = enqueueMessages(account: account, peerId: peerId, messages: [EnqueueMessage.message(text: links.listenerLink, attributes: [], inlineStickers: [:], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil, correlationId: nil, bubbleUpEmojiOrStickersets: [])]).start()
}
subscriber.putNext(true)
subscriber.putCompletion()
}
} else {
subscriber.putNext(false)
subscriber.putCompletion()
}
return EmptyDisposable
}
}
} else {
return .single(false)
}
}, linkInvation: { [weak window] index in
if let peer = peer {
if let window = window {
if peer.addressName != nil {
_ = showModalProgress(signal: links, for: window).start(next: { [weak window] links in
if let links = links, let window = window {
if index == 0 {
copyToClipboard(links.listenerLink)
} else if let speakerLink = links.speakerLink {
copyToClipboard(speakerLink)
}
showModalText(for: window, text: strings().shareLinkCopied)
}
})
} else {
_ = showModalProgress(signal: permanentExportedInvitation(context: context, peerId: callPeerId), for: window).start(next: { [weak window] link in
if let link = link, let window = window, let link = link._invitation {
copyToClipboard(link.link)
showModalText(for: window, text: strings().shareLinkCopied)
}
})
}
}
}
})
}
| gpl-2.0 | c00c7bf9dad812a30506466b9e464a5c | 46.489076 | 311 | 0.501274 | 5.449566 | false | false | false | false |
practicalswift/swift | stdlib/public/core/SipHash.swift | 6 | 3249 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// This file implements SipHash-2-4 and SipHash-1-3
/// (https://131002.net/siphash/).
///
/// This file is based on the reference C implementation, which was released
/// to public domain by:
///
/// * Jean-Philippe Aumasson <[email protected]>
/// * Daniel J. Bernstein <[email protected]>
//===----------------------------------------------------------------------===//
extension Hasher {
// FIXME: Remove @usableFromInline and @_fixed_layout once Hasher is resilient.
// rdar://problem/38549901
@usableFromInline @_fixed_layout
internal struct _State {
// "somepseudorandomlygeneratedbytes"
private var v0: UInt64 = 0x736f6d6570736575
private var v1: UInt64 = 0x646f72616e646f6d
private var v2: UInt64 = 0x6c7967656e657261
private var v3: UInt64 = 0x7465646279746573
// The fields below are reserved for future use. They aren't currently used.
private var v4: UInt64 = 0
private var v5: UInt64 = 0
private var v6: UInt64 = 0
private var v7: UInt64 = 0
@inline(__always)
internal init(rawSeed: (UInt64, UInt64)) {
v3 ^= rawSeed.1
v2 ^= rawSeed.0
v1 ^= rawSeed.1
v0 ^= rawSeed.0
}
}
}
extension Hasher._State {
@inline(__always)
private static func _rotateLeft(_ x: UInt64, by amount: UInt64) -> UInt64 {
return (x &<< amount) | (x &>> (64 - amount))
}
@inline(__always)
private mutating func _round() {
v0 = v0 &+ v1
v1 = Hasher._State._rotateLeft(v1, by: 13)
v1 ^= v0
v0 = Hasher._State._rotateLeft(v0, by: 32)
v2 = v2 &+ v3
v3 = Hasher._State._rotateLeft(v3, by: 16)
v3 ^= v2
v0 = v0 &+ v3
v3 = Hasher._State._rotateLeft(v3, by: 21)
v3 ^= v0
v2 = v2 &+ v1
v1 = Hasher._State._rotateLeft(v1, by: 17)
v1 ^= v2
v2 = Hasher._State._rotateLeft(v2, by: 32)
}
@inline(__always)
private func _extract() -> UInt64 {
return v0 ^ v1 ^ v2 ^ v3
}
}
extension Hasher._State {
@inline(__always)
internal mutating func compress(_ m: UInt64) {
v3 ^= m
_round()
v0 ^= m
}
@inline(__always)
internal mutating func finalize(tailAndByteCount: UInt64) -> UInt64 {
compress(tailAndByteCount)
v2 ^= 0xff
for _ in 0..<3 {
_round()
}
return _extract()
}
}
extension Hasher._State {
@inline(__always)
internal init() {
self.init(rawSeed: Hasher._executionSeed)
}
@inline(__always)
internal init(seed: Int) {
let executionSeed = Hasher._executionSeed
// Prevent sign-extending the supplied seed; this makes testing slightly
// easier.
let seed = UInt(bitPattern: seed)
self.init(rawSeed: (
executionSeed.0 ^ UInt64(truncatingIfNeeded: seed),
executionSeed.1))
}
}
| apache-2.0 | d7f1c0c64c14b7657dbdb266f9420850 | 27.752212 | 81 | 0.59249 | 3.512432 | false | false | false | false |
leo150/Pelican | Sources/Pelican/Session/Modules/Moderator/Moderator.swift | 1 | 5449 | //
// SessionModerator.swift
// PelicanTests
//
// Created by Takanu Kyriako on 26/07/2017.
//
//
import Foundation
import Vapor
/**
Contains the permissions associated with a single user or chat. A SessionModerator can only be
applied to a Chat or User, as every other ID lacks any kind of persistence to be useful for
moderation purposes. (Don't do it, please).
*/
public class SessionModerator {
/// The session the moderator is delegating for, as identified by it's tag.
private var tag: SessionTag
private var changeTitleCallback: (SessionIDType, String, [Int], Bool) -> ()
private var checkTitleCallback: (Int, SessionIDType) -> ([String])
public var getID: Int { return tag.getSessionID }
public var getTitles: [String] { return checkTitleCallback(tag.sessionID, tag.sessionIDType) }
/**
Attempts to create a SessionModerator.
- warning: This should not be used under any circumstances if your session does not represent a User or Chat session, and
if the SessionBuilder used to create is is not using User or Chat IDs respectively. 🙏
*/
init?(tag: SessionTag, moderator: Moderator) {
self.tag = tag
self.changeTitleCallback = moderator.switchTitle
self.checkTitleCallback = moderator.getTitles
if tag.sessionIDType != .chat || tag.sessionIDType != .user { return }
}
/**
Adds a title to this session.
*/
public func add(_ title: String) {
changeTitleCallback(tag.sessionIDType, title, [tag.sessionID], false)
}
/**
Adds a title to the IDs of the users specified.
*/
public func addToUsers(title: String, users: User...) {
changeTitleCallback(.user, title, users.map({$0.tgID}), false)
}
/**
Adds a title to the IDs of the chats specified.
*/
public func addToChats(title: String, chats: Chat...) {
changeTitleCallback(.chat, title, chats.map({$0.tgID}), false)
}
/**
Removes a title from this session, if associated with it.
*/
public func remove(_ title: String) {
changeTitleCallback(tag.sessionIDType, title, [tag.sessionID], true)
}
/**
Adds a title to the IDs of the users specified.
*/
public func removeFromUsers(title: String, users: User...) {
changeTitleCallback(.user, title, users.map({$0.tgID}), true)
}
/**
Adds a title to the IDs of the chats specified.
*/
public func removeFromChats(title: String, chats: Chat...) {
changeTitleCallback(.chat, title, chats.map({$0.tgID}), true)
}
/**
Checks to see whether a User has the specified title.
- returns: True if it does, false if not.
*/
public func getTitles(forUser user: User) -> [String] {
return checkTitleCallback(user.tgID, .user)
}
/**
Checks to see whether a Chat has the specified title.
- returns: True if it does, false if not.
*/
public func getTitles(forChat chat: Chat) -> [String] {
return checkTitleCallback(chat.tgID, .chat)
}
/**
Checks to see whether this Session has a given title.
- returns: True if it does, false if not.
*/
public func checkTitle(_ title: String) -> Bool {
let titles = checkTitleCallback(tag.sessionID, tag.sessionIDType)
if titles.contains(title) { return true }
return false
}
/**
Checks to see whether a User has the specified title.
- returns: True if it does, false if not.
*/
public func checkTitle(forUser user: User, title: String) -> Bool {
let titles = checkTitleCallback(user.tgID, .user)
if titles.contains(title) { return true }
return false
}
/**
Checks to see whether a Chat has the specified title.
- returns: True if it does, false if not.
*/
public func checkTitle(forChat chat: Chat, title: String) -> Bool {
let titles = checkTitleCallback(chat.tgID, .chat)
if titles.contains(title) { return true }
return false
}
/**
Removes all titles associated with this session ID.
*/
public func clearTitles() {
let titles = checkTitleCallback(tag.sessionID, tag.sessionIDType)
for title in titles {
changeTitleCallback(tag.sessionIDType, title, [tag.sessionID], true)
}
}
/**
Blacklists the Session ID, which closes the Session and any associated ScheduleEvents, and adds the session
to the Moderator blacklist, preventing the ID from being able to make updates that
the bot can interpret or that could propogate a new, active session.
This continues until the ID is removed from the blacklist.
- note: This does not deinitialize the Session, to avoid scenarios where the Session potentially needs
to be used by another operation at or near the timeframe where this occurs.
*/
public func blacklist() {
PLog.info("Adding to blacklist - \(tag.getBuilderID)")
tag.sendEvent(type: .blacklist, action: .blacklist)
}
/**
Blacklists a different session from the one attached to this delegate, which does the following:
- Closes the Session and any associated ScheduleEvents
- Adds the session to the Moderator blacklist, preventing the ID from being able to make updates that
the bot can interpret or that could propogate a new, active session.
This continues until the ID is removed from the blacklist.
- note: This will only work with Sessions that subclass from ChatSession or UserSession - all else will fail.
*/
// This has been commented out to prevent unforeseen problems in how Session removal occurs.
/*
func blacklist(sessions: Session...) {
for session in sessions {
if session is UserSession || session is ChatSession {
}
}
}
*/
}
| mit | da7802d1d3f5a5b05581e81309c89be3 | 26.928205 | 123 | 0.711164 | 3.621011 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.