repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HTWDD/HTWDresden-iOS | refs/heads/master | HTWDD/Components/RoomOccupancy/Main/Views/RoomViewCell.swift | gpl-2.0 | 1 | //
// RoomViewCell.swift
// HTWDD
//
// Created by Mustafa Karademir on 26.07.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
class RoomViewCell: UITableViewCell {
// MARK: - Outlets
@IBOutlet weak var main: UIView!
@IBOutlet weak var lblRoomName: BadgeLabel!
@IBOutlet weak var lblCountOfOccupancies: BadgeLabel!
@IBOutlet weak var lblCurrentLesson: UILabel!
@IBOutlet weak var imageViewChevron: UIImageView!
@IBOutlet weak var viewSeparator: UIView!
// MARK: - Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
main.apply {
$0.layer.cornerRadius = 4
$0.backgroundColor = UIColor.htw.cellBackground
}
lblRoomName.apply {
$0.textColor = UIColor.htw.Label.primary
}
lblCurrentLesson.apply {
$0.textColor = UIColor.htw.Label.secondary
}
lblCountOfOccupancies.apply {
$0.textColor = UIColor.htw.Label.primary
$0.backgroundColor = UIColor.htw.Badge.primary
}
imageViewChevron.apply {
$0.tintColor = UIColor.htw.Icon.primary
}
}
}
// MARK: - Nib Loadable
extension RoomViewCell: FromNibLoadable {
// MARK: - Setup
func setup(with model: RoomRealm) {
lblRoomName.text = model.name.uppercased()
lblCountOfOccupancies.text = "\(model.occupancies.count)"
// Get current occupancy for the day
let occupanciesToday = Array(model.occupancies.filter("day = \(Date().weekday.dayByAdding(days: 1).rawValue)")).map { content -> Occupancy in
let weeks = String(String(content.weeksOnly.dropFirst()).dropLast()).replacingOccurrences(of: " ", with: "").components(separatedBy: ",")
return Occupancy(id: content.id,
name: content.name,
type: content.type,
day: content.day,
beginTime: content.beginTime,
endTime: content.endTime,
week: content.week,
professor: content.professor,
weeksOnly: weeks.compactMap( { Int($0) }))
}
if let current = occupanciesToday.filter({ $0.weeksOnly.contains(Date().weekday.rawValue) && ($0.beginTime...$0.endTime).contains(Date().string(format: "HH:mm:ss"))
}).first {
lblCurrentLesson.text = current.name
viewSeparator.backgroundColor = UIColor.htw.Material.red
} else {
lblCurrentLesson.text = R.string.localizable.roomOccupancyFree()
viewSeparator.backgroundColor = UIColor.htw.Material.green
}
}
}
| fb290365dea384d8e0a7543d10f0b5d6 | 34.493827 | 172 | 0.570435 | false | false | false | false |
roddi/UltraschallHub | refs/heads/develop | Application/UltraschallHub/AudioEngineCell.swift | mit | 1 | //
// AudioEngineCell.swift
// UltraschallHub
//
// Created by Daniel Lindenfelser on 05.10.14.
// Copyright (c) 2014 Daniel Lindenfelser. All rights reserved.
//
import Cocoa
@IBDesignable
class AudioEngineCell: NSTableCellView, NSTextFieldDelegate {
@IBOutlet weak var statusLabel: NSTextField!
@IBOutlet weak var numChannelsPopUpButton: NSPopUpButton!
var engine: AudioEngine?
override func controlTextDidChange(obj: NSNotification) {
if (engine != nil) {
engine!.engineDescription = statusLabel.stringValue
}
}
@IBAction func valueChanged(sender: AnyObject) {
var value = numChannelsPopUpButton.itemTitleAtIndex(numChannelsPopUpButton.indexOfSelectedItem)
if let number = value.toInt() {
if (engine != nil) {
engine!.engineChannels = number
}
}
}
func setAudioEngine(engine :AudioEngine) {
statusLabel.editable = true
self.engine = engine
statusLabel.stringValue = engine.engineDescription
numChannelsPopUpButton.selectItemWithTitle(String(engine.engineChannels))
statusLabel.delegate = self
}
}
| 4e12fefedc3749f9db2f1d7397b1355d | 28.85 | 103 | 0.670017 | false | false | false | false |
Czajnikowski/TrainTrippin | refs/heads/master | LibrarySample/Pods/RxSwift/RxSwift/Observable.swift | mit | 3 | //
// Observable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
A type-erased `ObservableType`.
It represents a push style sequence.
*/
public class Observable<Element> : ObservableType {
/**
Type of elements in sequence.
*/
public typealias E = Element
init() {
#if TRACE_RESOURCES
let _ = Resources.incrementTotal()
#endif
}
public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
abstractMethod()
}
public func asObservable() -> Observable<E> {
return self
}
deinit {
#if TRACE_RESOURCES
let _ = Resources.decrementTotal()
#endif
}
// this is kind of ugly I know :(
// Swift compiler reports "Not supported yet" when trying to override protocol extensions, so ¯\_(ツ)_/¯
/**
Optimizations for map operator
*/
internal func composeMap<R>(_ selector: @escaping (Element) throws -> R) -> Observable<R> {
return Map(source: self, transform: selector)
}
}
| 2e89a4916ee2b5a72d4f6fb97319c2e9 | 20.653846 | 107 | 0.620782 | false | false | false | false |
che1404/RGViperChat | refs/heads/master | RGViperChat/Signup/Interactor/SignupInteractorSpec.swift | mit | 1 | //
// Created by Roberto Garrido
// Copyright (c) 2017 Roberto Garrido. All rights reserved.
//
import Quick
import Nimble
import Cuckoo
@testable import RGViperChat
class SignupInteractorSpec: QuickSpec {
var interactor: SignupInteractor!
var mockPresenter: MockSignupInteractorOutputProtocol!
var mockAPIDataManager: MockSignupAPIDataManagerInputProtocol!
var mockLocalDataManager: MockSignupLocalDataManagerInputProtocol!
override func spec() {
beforeEach {
self.mockPresenter = MockSignupInteractorOutputProtocol()
self.mockAPIDataManager = MockSignupAPIDataManagerInputProtocol()
self.mockLocalDataManager = MockSignupLocalDataManagerInputProtocol()
self.interactor = SignupInteractor()
self.interactor.presenter = self.mockPresenter
self.interactor.APIDataManager = self.mockAPIDataManager
self.interactor.localDataManager = self.mockLocalDataManager
}
context("When sign up use case is selected") {
beforeEach {
stub(self.mockAPIDataManager) { mock in
when(mock).signup(withUsername: anyString(), email: anyString(), password: anyString(), completion: anyClosure()).thenDoNothing()
}
self.interactor.signup(withUsername: "roberto", email: "[email protected]", password: "viperchat")
}
it("Calls the sigup method on the API data manager") {
verify(self.mockAPIDataManager).signup(withUsername: anyString(), email: anyString(), password: anyString(), completion: anyClosure())
}
context("When the sign up was OK") {
beforeEach {
stub(self.mockAPIDataManager) { mock in
when(mock).signup(withUsername: anyString(), email: anyString(), password: anyString(), completion: anyClosure()).then { _, _, _, completion in
completion(true)
}
}
stub(self.mockPresenter) { mock in
when(mock).successfulSignup().thenDoNothing()
}
self.interactor.signup(withUsername: "roberto", email: "[email protected]", password: "viperchat")
}
it("Responds the presenter with successful signup") {
verify(self.mockPresenter).successfulSignup()
}
}
}
afterEach {
self.interactor = nil
self.mockPresenter = nil
self.mockAPIDataManager = nil
}
}
}
| cdd1913ba5743b66139db52518bc4787 | 39.059701 | 167 | 0.605067 | false | false | false | false |
a2/Gulliver | refs/heads/master | Gulliver Tests/Source/AlternateBirthdaySpec.swift | mit | 1 | import AddressBook
import Gulliver
import Nimble
import Quick
class AlternateBirthdaySpec: QuickSpec {
override func spec() {
describe("rawValue") {
it("should contain the correct data") {
let birthday = AlternateBirthday(calendarIdentifier: NSCalendarIdentifierHebrew, era: 0, year: 5718, month: 4, day: 14, isLeapMonth: false)
let rawValue = birthday.rawValue
expect((rawValue[kABPersonAlternateBirthdayCalendarIdentifierKey as String] as! String)) == NSCalendarIdentifierHebrew
expect((rawValue[kABPersonAlternateBirthdayDayKey as String] as! Int)) == 14
expect((rawValue[kABPersonAlternateBirthdayEraKey as String] as! Int)) == 0
expect((rawValue[kABPersonAlternateBirthdayIsLeapMonthKey as String] as! Bool)) == false
expect((rawValue[kABPersonAlternateBirthdayMonthKey as String] as! Int)) == 4
expect((rawValue[kABPersonAlternateBirthdayYearKey as String] as! Int)) == 5718
}
it("is a valid representation") {
let birthday = AlternateBirthday(calendarIdentifier: NSCalendarIdentifierHebrew, era: 0, year: 5718, month: 4, day: 14, isLeapMonth: false)
let record: ABRecordRef = ABPersonCreate().takeRetainedValue()
var error: Unmanaged<CFErrorRef>? = nil
if !ABRecordSetValue(record, kABPersonAlternateBirthdayProperty, birthday.rawValue, &error) {
let nsError = (error?.takeUnretainedValue()).map { unsafeBitCast($0, NSError.self) }
fail("Could not set value on record: \(nsError?.localizedDescription)")
}
}
}
describe("init(rawValue:)") {
it("creates a valid AlternateBirthday") {
let rawValue: [NSObject : AnyObject] = [
kABPersonAlternateBirthdayCalendarIdentifierKey as String: NSCalendarIdentifierHebrew,
kABPersonAlternateBirthdayDayKey as String: 14,
kABPersonAlternateBirthdayEraKey as String: 0,
kABPersonAlternateBirthdayIsLeapMonthKey as String: false,
kABPersonAlternateBirthdayMonthKey as String: 4,
kABPersonAlternateBirthdayYearKey as String: 5718,
]
let birthday = AlternateBirthday(rawValue: rawValue)
expect(birthday).notTo(beNil())
expect(birthday!.calendarIdentifier) == NSCalendarIdentifierHebrew
expect(birthday!.day) == 14
expect(birthday!.era) == 0
expect(birthday!.isLeapMonth) == false
expect(birthday!.month) == 4
expect(birthday!.year) == 5718
}
it("fails if a required key is not present") {
let correctRawValue: [NSObject : AnyObject] = [
kABPersonAlternateBirthdayCalendarIdentifierKey as String: NSCalendarIdentifierHebrew,
kABPersonAlternateBirthdayDayKey as String: 14,
kABPersonAlternateBirthdayEraKey as String: 0,
kABPersonAlternateBirthdayIsLeapMonthKey as String: false,
kABPersonAlternateBirthdayMonthKey as String: 4,
kABPersonAlternateBirthdayYearKey as String: 5718,
]
for index in indices(correctRawValue) {
var rawValue = correctRawValue
rawValue.removeAtIndex(index)
let birthday = AlternateBirthday(rawValue: rawValue)
expect(birthday).to(beNil())
}
}
it("works with vCard data") {
let fileURL = NSBundle(forClass: AlternateBirthdaySpec.self).URLForResource("Johnny B. Goode", withExtension: "vcf")!
let data = NSData(contentsOfURL: fileURL)!
let records = ABPersonCreatePeopleInSourceWithVCardRepresentation(nil, data as CFDataRef).takeRetainedValue() as [ABRecordRef]
let rawValue = ABRecordCopyValue(records[0], kABPersonAlternateBirthdayProperty)!.takeRetainedValue() as! [NSObject : AnyObject]
let birthday = AlternateBirthday(rawValue: rawValue)
expect(birthday).notTo(beNil())
expect(birthday!.calendarIdentifier) == NSCalendarIdentifierHebrew
expect(birthday!.day) == 14
expect(birthday!.era) == 0
expect(birthday!.isLeapMonth) == false
expect(birthday!.month) == 4
expect(birthday!.year) == 5718
}
}
describe("dateComponents") {
it("should contain the correct data") {
let birthday = AlternateBirthday(calendarIdentifier: NSCalendarIdentifierHebrew, era: 0, year: 5718, month: 4, day: 14, isLeapMonth: false)
let components = birthday.dateComponents
expect(components.calendar?.calendarIdentifier) == NSCalendarIdentifierHebrew
expect(components.day) == 14
expect(components.era) == 0
expect(components.leapMonth) == false
expect(components.month) == 4
expect(components.year) == 5718
}
}
describe("init(dateComponents:)") {
it("creates a valid AlternateBirthday") {
let dateComponents = NSDateComponents()
dateComponents.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierHebrew)
dateComponents.day = 14
dateComponents.era = 0
dateComponents.leapMonth = false
dateComponents.month = 4
dateComponents.year = 5718
let birthday = AlternateBirthday(dateComponents: dateComponents)
expect(birthday).notTo(beNil())
expect(birthday!.calendarIdentifier) == NSCalendarIdentifierHebrew
expect(birthday!.day) == 14
expect(birthday!.era) == 0
expect(birthday!.isLeapMonth) == false
expect(birthday!.month) == 4
expect(birthday!.year) == 5718
}
it("fails if a required value is not present") {
let allConfigurationBlocks: [NSDateComponents -> Void] = [
{ $0.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierHebrew) },
{ $0.day = 14 },
{ $0.era = 0 },
{ $0.month = 4 },
{ $0.year = 5718 },
]
for index in indices(allConfigurationBlocks) {
let dateComponents = NSDateComponents()
var configurationBlocks = allConfigurationBlocks
// Assignment to _ is necessary because the result is "NSDateComponents -> Void"
// and the compiler warns about an unused function result. The idea is that we
// don't want to execute it, but simply remove it from the array.
_ = configurationBlocks.removeAtIndex(index)
for block in configurationBlocks {
block(dateComponents)
}
let birthday = AlternateBirthday(dateComponents: dateComponents)
expect(birthday).to(beNil())
}
}
}
}
}
| 406f6a420c8c2aa12eab8d97aea016de | 48.736842 | 155 | 0.57963 | false | false | false | false |
realm/SwiftLint | refs/heads/main | Source/SwiftLintFramework/Rules/Metrics/NestingRule.swift | mit | 1 | import SourceKittenFramework
struct NestingRule: ConfigurationProviderRule {
var configuration = NestingConfiguration(typeLevelWarning: 1,
typeLevelError: nil,
functionLevelWarning: 2,
functionLevelError: nil)
init() {}
static let description = RuleDescription(
identifier: "nesting",
name: "Nesting",
description:
"Types should be nested at most 1 level deep, and functions should be nested at most 2 levels deep.",
kind: .metrics,
nonTriggeringExamples: NestingRuleExamples.nonTriggeringExamples,
triggeringExamples: NestingRuleExamples.triggeringExamples
)
private let omittedStructureKinds = SwiftDeclarationKind.variableKinds
.union([.enumcase, .enumelement])
.map(SwiftStructureKind.declaration)
private struct ValidationArgs {
var typeLevel: Int = -1
var functionLevel: Int = -1
var previousKind: SwiftStructureKind?
var violations: [StyleViolation] = []
func with(previousKind: SwiftStructureKind?) -> ValidationArgs {
var args = self
args.previousKind = previousKind
return args
}
}
func validate(file: SwiftLintFile) -> [StyleViolation] {
return validate(file: file, substructure: file.structureDictionary.substructure, args: ValidationArgs())
}
private func validate(file: SwiftLintFile, substructure: [SourceKittenDictionary],
args: ValidationArgs) -> [StyleViolation] {
return args.violations + substructure.flatMap { dictionary -> [StyleViolation] in
guard let kindString = dictionary.kind, let structureKind = SwiftStructureKind(kindString) else {
return validate(file: file, substructure: dictionary.substructure, args: args.with(previousKind: nil))
}
guard !omittedStructureKinds.contains(structureKind) else {
return args.violations
}
switch structureKind {
case let .declaration(declarationKind):
return validate(file: file, structureKind: structureKind,
declarationKind: declarationKind, dictionary: dictionary, args: args)
case .expression, .statement:
guard configuration.checkNestingInClosuresAndStatements else {
return args.violations
}
return validate(file: file, substructure: dictionary.substructure,
args: args.with(previousKind: structureKind))
}
}
}
private func validate(file: SwiftLintFile, structureKind: SwiftStructureKind, declarationKind: SwiftDeclarationKind,
dictionary: SourceKittenDictionary, args: ValidationArgs) -> [StyleViolation] {
let isTypeOrExtension = SwiftDeclarationKind.typeKinds.contains(declarationKind)
|| SwiftDeclarationKind.extensionKinds.contains(declarationKind)
let isFunction = SwiftDeclarationKind.functionKinds.contains(declarationKind)
guard isTypeOrExtension || isFunction else {
return validate(file: file, substructure: dictionary.substructure,
args: args.with(previousKind: structureKind))
}
let currentTypeLevel = isTypeOrExtension ? args.typeLevel + 1 : args.typeLevel
let currentFunctionLevel = isFunction ? args.functionLevel + 1 : args.functionLevel
var violations = args.violations
if let violation = levelViolation(file: file, dictionary: dictionary,
previousKind: args.previousKind,
level: isFunction ? currentFunctionLevel : currentTypeLevel,
forFunction: isFunction) {
violations.append(violation)
}
return validate(file: file, substructure: dictionary.substructure,
args: ValidationArgs(
typeLevel: currentTypeLevel,
functionLevel: currentFunctionLevel,
previousKind: structureKind,
violations: violations
)
)
}
private func levelViolation(file: SwiftLintFile, dictionary: SourceKittenDictionary,
previousKind: SwiftStructureKind?, level: Int, forFunction: Bool) -> StyleViolation? {
guard let offset = dictionary.offset else {
return nil
}
let targetLevel = forFunction ? configuration.functionLevel : configuration.typeLevel
var violatingSeverity: ViolationSeverity?
if configuration.alwaysAllowOneTypeInFunctions,
case let .declaration(previousDeclarationKind)? = previousKind,
!SwiftDeclarationKind.functionKinds.contains(previousDeclarationKind) {
violatingSeverity = configuration.severity(with: targetLevel, for: level)
} else if forFunction || !configuration.alwaysAllowOneTypeInFunctions || previousKind == nil {
violatingSeverity = configuration.severity(with: targetLevel, for: level)
} else {
violatingSeverity = nil
}
guard let severity = violatingSeverity else {
return nil
}
let targetName = forFunction ? "Functions" : "Types"
let threshold = configuration.threshold(with: targetLevel, for: severity)
let pluralSuffix = threshold > 1 ? "s" : ""
return StyleViolation(
ruleDescription: Self.description,
severity: severity,
location: Location(file: file, byteOffset: offset),
reason: "\(targetName) should be nested at most \(threshold) level\(pluralSuffix) deep"
)
}
}
private enum SwiftStructureKind: Equatable {
case declaration(SwiftDeclarationKind)
case expression(SwiftExpressionKind)
case statement(StatementKind)
init?(_ structureKind: String) {
if let declarationKind = SwiftDeclarationKind(rawValue: structureKind) {
self = .declaration(declarationKind)
} else if let expressionKind = SwiftExpressionKind(rawValue: structureKind) {
self = .expression(expressionKind)
} else if let statementKind = StatementKind(rawValue: structureKind) {
self = .statement(statementKind)
} else {
return nil
}
}
}
| 14a99d3235d87a3ba1a8139359916a9e | 43.624161 | 120 | 0.623853 | false | true | false | false |
leo150/Pelican | refs/heads/develop | Sources/Pelican/API/Request+Admin.swift | mit | 1 | //
// Request+Admin.swift
// PelicanTests
//
// Created by Takanu Kyriako on 10/07/2017.
//
//
import Foundation
import Vapor
import FluentProvider
import HTTP
import FormData
import Multipart
/**
Adds an extension that deals in creating requests for administrating a chat. The bot must be an administrator to use these requests.
*/
extension TelegramRequest {
/*
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to kick a user from a group or a supergroup. In the case of supergroups, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator
in the group for this to work. Returns True on success.
*/
public static func kickChatMember(chatID: Int, userID: Int) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID,
"user_id": userID
]
// Set the Request, Method and Content
request.methodName = "getChatMember"
return request
}
/*
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work. Returns
True on success.
*/
public static func unbanChatMember(chatID: Int, userID: Int) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID,
"user_id": userID
]
// Set the Request, Method and Content
request.methodName = "unbanChatMember"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a
user. Returns True on success.
*/
public static func restrictChatMember(chatID: Int, userID: Int, restrictUntil: Int?, restrictions: (msg: Bool, media: Bool, stickers: Bool, webPreview: Bool)?) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID,
"user_id": userID,
"until_date": restrictUntil
]
if restrictUntil != nil { request.query["until_date"] = restrictUntil! }
if restrictions != nil {
request.query["can_send_messages"] = restrictions!.msg
request.query["can_send_media_messages"] = restrictions!.media
request.query["can_send_other_messages"] = restrictions!.stickers
request.query["can_add_web_page_previews"] = restrictions!.webPreview
}
// Set the Request, Method and Content
request.methodName = "restrictChatMember"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a
user. Returns True on success.
*/
public static func promoteChatMember(chatID: Int, userID: Int, rights: (info: Bool, msg: Bool, edit: Bool, delete: Bool, invite: Bool, restrict: Bool, pin: Bool, promote: Bool)?) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID,
"user_id": userID,
]
if rights != nil {
request.query["can_change_info"] = rights!.info
request.query["can_post_messages"] = rights!.msg
request.query["can_edit_messages"] = rights!.edit
request.query["can_delete_messages"] = rights!.delete
request.query["can_invite_users"] = rights!.invite
request.query["can_restrict_members"] = rights!.restrict
request.query["can_pin_messages"] = rights!.pin
request.query["can_promote_members"] = rights!.promote
}
// Set the Request, Method and Content
request.methodName = "promoteChatMember"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns exported invite link as String on success.
*/
public static func exportChatInviteLink(chatID: Int) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID
]
// Set the Request, Method and Content
request.methodName = "exportChatInviteLink"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
- note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.
*/
public static func setChatPhoto(chatID: Int, file: MessageFile) -> TelegramRequest {
let request = TelegramRequest()
request.form["chat_id"] = Field(name: "chat_id", filename: nil, part: Part(headers: [:], body: String(chatID).bytes))
//form[link.type.rawValue] = Field(name: link.type.rawValue, filename: link.name, part: Part(headers: [:], body: data!))
// Set the Request, Method and Content
request.methodName = "setChatPhoto"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
- note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.
*/
public static func deleteChatPhoto(chatID: Int) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID
]
// Set the Request, Method and Content
request.methodName = "deleteChatPhoto"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*/
public static func setChatTitle(chatID: Int, title: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID,
"title": title
]
// Set the Request, Method and Content
request.methodName = "setChatTitle"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*/
public static func setChatDescription(chatID: Int, description: String) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID,
"description": description
]
// Set the Request, Method and Content
request.methodName = "setChatTitle"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*/
public static func pinChatMessage(chatID: Int, messageID: Int, disableNtf: Bool = false) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID,
"message_id": messageID,
"disable_notification": disableNtf
]
// Set the Request, Method and Content
request.methodName = "pinChatMessage"
return request
}
/**
Builds and returns a TelegramRequest for the API method with the given arguments.
## API Description
Use this method to unpin a message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
*/
public static func unpinChatMessage(chatID: Int) -> TelegramRequest {
let request = TelegramRequest()
request.query = [
"chat_id": chatID
]
// Set the Request, Method and Content
request.methodName = "unpinChatMessage"
return request
}
}
| 54cd953ba2be289ffeb9e2e81e76f947 | 32.405204 | 233 | 0.723236 | false | false | false | false |
wagnersouz4/replay | refs/heads/master | Replay/Replay/Source/Models/Movie.swift | mit | 1 | //
// Movie.swift
// Replay
//
// Created by Wagner Souza on 24/03/17.
// Copyright © 2017 Wagner Souza. All rights reserved.
//
import Foundation
struct Movie {
var movieId: Int
var genres: [String]
var title: String
var overview: String
var releaseDate: Date
/// Not every movie has a posterPath
var posterPath: String?
var videos: [YoutubeVideo]
/// Array of backdrops images sorted by its rating.
var backdropImagesPath: [String]
var runtime: Int
}
// MARK: Conforming to JSONable
extension Movie: JSONable {
init?(json: JSONDictionary) {
guard let genresList = json["genres"] as? [JSONDictionary],
let genres: [String] = JsonHelper.generateList(using: genresList, key: "name") else { return nil }
guard let videosList = json["videos"] as? JSONDictionary,
let videosResult = videosList["results"] as? [JSONDictionary],
let videos: [YoutubeVideo] = JsonHelper.generateList(using: videosResult) else { return nil }
guard let images = json["images"] as? JSONDictionary,
let backdropImages = images["backdrops"] as? [JSONDictionary],
let backdropImagesPath: [String] = JsonHelper.generateList(using: backdropImages,
key: "file_path")
else { return nil }
guard let movieId = json["id"] as? Int,
let title = json["original_title"] as? String,
let overview = json["overview"] as? String,
let poster = json["poster_path"] as? String,
let releaseDateString = json["release_date"] as? String,
let runtime = json["runtime"] as? Int else { return nil }
let posterPath = (poster == "N/A") ? nil : poster
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-d"
guard let releaseDate = formatter.date(from: releaseDateString) else {
fatalError("Invalid date format")
}
self.init(movieId: movieId,
genres: genres,
title: title,
overview: overview,
releaseDate: releaseDate,
posterPath: posterPath,
videos: videos,
backdropImagesPath: backdropImagesPath,
runtime: runtime)
}
}
// MARK: Conforming to GriddableContent
extension Movie: GriddableContent {
var identifier: Any? {
return movieId
}
var gridPortraitImageUrl: URL? {
guard let imagePath = posterPath else { return nil }
return TMDbHelper.createImageURL(using: imagePath)
}
var gridLandscapeImageUrl: URL? {
guard !backdropImagesPath.isEmpty else { return nil }
return TMDbHelper.createImageURL(using: backdropImagesPath[0])
}
var gridTitle: String {
return title
}
}
| af2f46c6cdb1eb3dcf5083b56c9fdca9 | 31.311111 | 110 | 0.601788 | false | false | false | false |
vhart/PPL-iOS | refs/heads/master | PPL-iOS/LogManager.swift | mit | 1 | //
// LogManager.swift
// PPL-iOS
//
// Created by Jovanny Espinal on 2/17/16.
// Copyright © 2016 Jovanny Espinal. All rights reserved.
//
import Foundation
import CoreData
class LogManager {
static let sharedInstance = LogManager()
var collectionOfWorkoutLogs = NSOrderedSet()
private init()
{
collectionOfWorkoutLogs = NSOrderedSet()
}
func setProperties(exercises: [WorkoutLog])
{
let mutableCopy = collectionOfWorkoutLogs.mutableCopy() as! NSMutableOrderedSet
mutableCopy.addObjectsFromArray(exercises)
collectionOfWorkoutLogs = mutableCopy
}
func createWorkoutLog(managedContext: NSManagedObjectContext) -> WorkoutLog
{
let currentWorkoutLog = WorkoutLog(typeOfWorkout: LogManager.sharedInstance.getWorkoutType(), context: managedContext)
return currentWorkoutLog
}
func addWorkoutLog(workoutLog: WorkoutLog)
{
let setOfworkoutLogs = collectionOfWorkoutLogs.mutableCopy() as! NSMutableOrderedSet
var arrayOfWorkoutLogs = [WorkoutLog]()
arrayOfWorkoutLogs.append(workoutLog)
setOfworkoutLogs.addObjectsFromArray(arrayOfWorkoutLogs)
collectionOfWorkoutLogs = setOfworkoutLogs
}
}
extension LogManager {
}
| fb5110e62b5ba24ddcd6ab0da2c81cda | 23.462963 | 126 | 0.691143 | false | false | false | false |
larryhou/swift | refs/heads/master | Tachograph/Tachograph/VideoScrollController.swift | mit | 1 | //
// VideoScrollController.swift
// Tachograph
//
// Created by larryhou on 04/08/2017.
// Copyright © 2017 larryhou. All rights reserved.
//
import Foundation
import UIKit
import AVKit
class VideoPlayController: AVPlayerViewController, PageProtocol {
var PlayerStatusContext: String?
static func instantiate(_ storyboard: UIStoryboard) -> PageProtocol {
return storyboard.instantiateViewController(withIdentifier: "VideoPlayController") as! PageProtocol
}
var pageAsset: Any? {
didSet {
if let data = self.pageAsset as? CameraModel.CameraAsset {
self.url = data.url
}
}
}
var index: Int = -1
var url: String?
override func viewDidLoad() {
super.viewDidLoad()
self.player = AVPlayer()
let press = UILongPressGestureRecognizer(target: self, action: #selector(pressUpdate(sender:)))
view.addGestureRecognizer(press)
}
@objc func pressUpdate(sender: UILongPressGestureRecognizer) {
if sender.state != .began {return}
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "保存到相册", style: .default, handler: { _ in self.saveToAlbum() }))
alertController.addAction(UIAlertAction(title: "分享", style: .default, handler: { _ in self.share() }))
alertController.addAction(UIAlertAction(title: "删除", style: .destructive, handler: { _ in self.delete() }))
alertController.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
present(alertController, animated: true, completion: nil)
}
func delete() {
guard let url = self.url else {return}
dismiss(animated: true) {
let success = AssetManager.shared.remove(url)
AlertManager.show(title: success ? "文件删除成功" : "文件删除失败", message: url, sender: self)
}
}
func saveToAlbum() {
guard let url = self.url else {return}
UISaveVideoAtPathToSavedPhotosAlbum(url, self, #selector(video(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func video(_ videoPath: String, didFinishSavingWithError error: NSError?, contextInfo context: Any?) {
AlertManager.show(title: error == nil ? "视频保存成功" : "视频保存失败", message: error?.debugDescription, sender: self)
}
func share() {
guard let url = self.url else {return}
if let location = AssetManager.shared.get(cacheOf: url) {
let controller = UIActivityViewController(activityItems: [location], applicationActivities: nil)
present(controller, animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.player?.pause()
if let identifier = self.observerIdentifier {
self.player?.removeTimeObserver(identifier)
self.observerIdentifier = nil
}
}
var lastUrl: String?
var observerIdentifier: Any?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let player = self.player else {return}
guard let url = self.url else {
player.pause()
player.replaceCurrentItem(with: nil)
return
}
let interval = CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
observerIdentifier = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) {
if let duration = player.currentItem?.duration, $0 >= duration {
self.play(from: 0)
}
}
if lastUrl == url { return }
let item: AVPlayerItem
if url.hasPrefix("http") {
item = AVPlayerItem(url: URL(string: url)!)
} else {
item = AVPlayerItem(url: URL(fileURLWithPath: url))
}
player.replaceCurrentItem(with: item)
lastUrl = url
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.player?.play()
}
func play(from position: Double = 0) {
guard let player = self.player else {return}
let position = CMTime(seconds: position, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
player.seek(to: position)
player.play()
}
}
class VideoScrollController: PageController<VideoPlayController, CameraModel.CameraAsset>, UIGestureRecognizerDelegate {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIViewPropertyAnimator.init(duration: 0.25, dampingRatio: 1.0) {
self.navigationController?.navigationBar.alpha = 0
}.startAnimation()
let pan = UIPanGestureRecognizer(target: self, action: #selector(panUpdate(sender:)))
pan.delegate = self
view.addGestureRecognizer(pan)
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return UIDevice.current.orientation.isPortrait
}
var fractionComplete = CGFloat.nan
var dismissAnimator: UIViewPropertyAnimator!
@objc func panUpdate(sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
dismissAnimator = UIViewPropertyAnimator(duration: 0.2, curve: .linear) { [unowned self] in
self.view.frame.origin.y = self.view.frame.height
}
dismissAnimator.addCompletion { [unowned self] position in
if position == .end {
self.dismiss(animated: false, completion: nil)
}
self.fractionComplete = CGFloat.nan
}
dismissAnimator.pauseAnimation()
case .changed:
if fractionComplete.isNaN {fractionComplete = 0}
let translation = sender.translation(in: view)
fractionComplete += translation.y / view.frame.height
fractionComplete = min(1, max(0, fractionComplete))
dismissAnimator.fractionComplete = fractionComplete
sender.setTranslation(CGPoint.zero, in: view)
default:
if dismissAnimator.fractionComplete <= 0.25 {
dismissAnimator.isReversed = true
}
dismissAnimator.continueAnimation(withTimingParameters: nil, durationFactor: 1.0)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIViewPropertyAnimator.init(duration: 0.25, dampingRatio: 1.0) {
self.navigationController?.navigationBar.alpha = 1
}.startAnimation()
}
}
| 7c2abc4543904130cd7438447b262cdf | 36.131148 | 120 | 0.63223 | false | false | false | false |
yscode001/YSExtension | refs/heads/master | YSExtension/YSExtension/YSExtension/UIKit/UIImage+ysExtension.swift | mit | 1 | import UIKit
extension UIImage{
public var ys_width:CGFloat{
get{
return size.width
}
}
public var ys_height:CGFloat{
get{
return size.height
}
}
}
extension UIImage{
/// 创建图片
public static func ys_create(color:UIColor,size:CGSize) -> UIImage?{
if size == CGSize.zero{
return nil
}
guard let context = UIGraphicsGetCurrentContext() else{
return nil
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(size)
context.setFillColor(color.cgColor)
context.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
/// 等比例缩放
public func ys_scale(width:CGFloat) -> UIImage?{
if width <= 0{
return nil
}
let scaleHeight = width / size.width * size.height
let scaleSize = CGSize(width: width, height: scaleHeight)
UIGraphicsBeginImageContextWithOptions(scaleSize, false, 0)
draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
/// 异步裁切
public func ys_corner(size:CGSize,fillColor:UIColor,callBack:((UIImage) -> ())?){
if size.width <= 0 || size.height <= 0{
callBack?(self)
return
}
DispatchQueue.global().async {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
fillColor.setFill()
UIRectFill(rect)
let path = UIBezierPath(ovalIn: rect)
path.addClip()
self.draw(in: rect)
if let img = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()
DispatchQueue.main.sync {
callBack?(img)
}
} else{
UIGraphicsEndImageContext()
DispatchQueue.main.sync {
callBack?(self)
}
}
}
}
/// 颜色填充
public func ys_tint(color:UIColor) -> UIImage?{
guard let context = UIGraphicsGetCurrentContext() else{
return nil
}
guard let cgImg = cgImage else{
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.setBlendMode(.normal)
context.draw(cgImg, in: rect)
context.setBlendMode(.sourceIn)
color.setFill()
context.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
extension UIImage{
/// 生成二维码
public static func ys_qrCode(code:String,width:CGFloat,height:CGFloat) -> UIImage?{
// 1、创建滤镜:CIQRCodeGenerator
guard let filter = CIFilter(name: "CIQRCodeGenerator") else{
return nil
}
// 2、设置属性:先设置默认、再设置自定义选项
filter.setDefaults()
filter.setValue(code.data(using: .utf8), forKey: "inputMessage")
// 3、根据滤镜生成图片
guard var ciImage = filter.outputImage else{
return nil
}
// 4、设置缩放,要不模糊
let scaleX = width / ciImage.extent.size.width
let scaleY = height / ciImage.extent.size.height
ciImage = ciImage.transformed(by: CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY))
return UIImage(ciImage: ciImage)
}
/// 生成条形码
public static func ys_barCode(code:String,width:CGFloat,height:CGFloat) -> UIImage?{
guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else{
return nil
}
filter.setDefaults()
filter.setValue(code.data(using: .utf8), forKey: "inputMessage")
guard var ciImage = filter.outputImage else{
return nil
}
let scaleX = width / ciImage.extent.size.width
let scaleY = height / ciImage.extent.size.height
ciImage = ciImage.transformed(by: CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY))
return UIImage(ciImage: ciImage)
}
}
| 8fb9eb41c181f5b37819e227a3a6950e | 28.202454 | 100 | 0.554622 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/UI/User/ViewModels/UserFriendsStreamCardViewModel.swift | mit | 1 | //
// UserFriendsStreamCardViewModel.swift
// Accented
//
// Created by Tiangong You on 9/9/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class UserFriendsStreamCardViewModel: SingleHeaderStreamViewModel {
var user : UserModel
override var headerHeight: CGFloat {
return UserStreamLayoutSpec.streamHeaderHeight
}
override var cardRendererReuseIdentifier : String {
return "cardRenderer"
}
override func registerCellTypes() {
super.registerCellTypes()
collectionView.register(StreamCardPhotoCell.self, forCellWithReuseIdentifier: cardRendererReuseIdentifier)
}
override func createLayoutTemplateGenerator(_ maxWidth: CGFloat) -> StreamTemplateGenerator {
return PhotoCardTemplateGenerator(maxWidth: maxWidth)
}
required init(user : UserModel, stream : StreamModel, collectionView : UICollectionView, flowLayoutDelegate: UICollectionViewDelegateFlowLayout) {
self.user = user
super.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: flowLayoutDelegate)
}
required init(stream: StreamModel, collectionView: UICollectionView, flowLayoutDelegate: UICollectionViewDelegateFlowLayout) {
fatalError("init(stream:collectionView:flowLayoutDelegate:) has not been implemented")
}
override func streamHeader(_ indexPath : IndexPath) -> UICollectionViewCell {
let streamHeaderCell = collectionView.dequeueReusableCell(withReuseIdentifier: streamHeaderReuseIdentifier, for: indexPath) as! DefaultSingleStreamHeaderCell
let userName = TextUtils.preferredAuthorName(user).uppercased()
streamHeaderCell.titleLabel.text = "PHOTOS FROM\n\(userName)'S FRIENDS"
if let photoCount = user.photoCount {
if photoCount == 0 {
streamHeaderCell.subtitleLabel.text = "NO ITEMS"
} else if photoCount == 1 {
streamHeaderCell.subtitleLabel.text = "1 ITEM"
} else {
streamHeaderCell.subtitleLabel.text = "\(photoCount) ITEMS"
}
} else {
streamHeaderCell.subtitleLabel.isHidden = true
}
streamHeaderCell.orderButton.isHidden = true
streamHeaderCell.orderLabel.isHidden = true
return streamHeaderCell
}
}
| 0a186296993956ecce12cdc0f5c67af5 | 37.532258 | 165 | 0.695689 | false | false | false | false |
AnyPresence/justapis-swift-sdk | refs/heads/master | Source/FoundationNetworkAdapter.swift | mit | 1 | //
// FoundationNetworkAdapter.swift
// JustApisSwiftSDK
//
// Created by Andrew Palumbo on 12/9/15.
// Copyright © 2015 AnyPresence. All rights reserved.
//
import Foundation
public class FoundationNetworkAdapter : NSObject, NetworkAdapter, NSURLSessionDataDelegate, NSURLSessionDelegate
{
typealias TaskCompletionHandler = (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void;
public init(sslCertificate:SSLCertificate? = nil)
{
self.sslCertificate = sslCertificate
super.init()
self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)
}
private let sslCertificate:SSLCertificate?
private var session:NSURLSession!
private var taskToRequestMap = [Int: (request:Request, handler:TaskCompletionHandler)]()
@objc public func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response:
NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void) {
if let taskRequest = self.taskToRequestMap[task.taskIdentifier]
{
if (taskRequest.request.followRedirects)
{
// Allow redirect
completionHandler(request)
}
else
{
// Reject redirect
completionHandler(nil)
// HACK: For a currently unclear reason, the data task's completion handler doesn't
// get called by the NSURLSession framework if we reject the redirect here.
// So we call it here explicitly.
taskRequest.handler(data:nil, response: response, error:nil)
}
}
else
{
completionHandler(request)
}
}
@objc public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
// If we have a SSL certificate for certificate pinning, verify it
guard let serverTrust = challenge.protectionSpace.serverTrust else
{
// APPROVE: This isn't the challenge we're looking for
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, nil)
return
}
let credential = NSURLCredential(forTrust: serverTrust)
guard let sslCertificate = self.sslCertificate else
{
// APPROVE: We're not worried about trusting the server as we have no certificate pinned
challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
return
}
guard let remoteCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else
{
// FAIL: We want to verify the server ceritifate, but it didn't give us one!
challenge.sender?.cancelAuthenticationChallenge(challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
return
}
guard let
remoteCertificateData:NSData = SecCertificateCopyData(remoteCertificate)
where
remoteCertificateData.isEqualToData(sslCertificate.data) else
{
// FAIL: The certificates didn't match!
challenge.sender?.cancelAuthenticationChallenge(challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
return
}
// APPROVE: We checked for a certificate and it was valid!
challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
return
}
public func submitRequest(request: Request, gateway:CompositedGateway)
{
// Build the request
guard let urlRequest:NSURLRequest = request.toNSURLRequest(gateway) else
{
// TODO: construct error indicating invalid request and invoke callback
return
}
var taskIdentifier:Int!
let taskCompletionHandler = { [weak self]
(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
var gatewayResponse:MutableResponseProperties? = nil
// Generate a Gateway Response, if there's
if let foundationResponse = response as? NSHTTPURLResponse
{
gatewayResponse = MutableResponseProperties(foundationResponse, data:data, requestedURL:urlRequest.URL!, gateway: gateway, request: request)
}
self?.taskToRequestMap.removeValueForKey(taskIdentifier)
// Let the gateway finish processing the response (on main thread)
dispatch_async(dispatch_get_main_queue(), {
gateway.fulfillRequest(request, response:gatewayResponse, error:error);
})
}
// Submit the request on the session
let task = self.session.dataTaskWithRequest(urlRequest, completionHandler: taskCompletionHandler)
taskIdentifier = task.taskIdentifier
self.taskToRequestMap[taskIdentifier] = (request, taskCompletionHandler)
task.resume()
}
}
internal extension MutableResponseProperties
{
// Internal initializer method to populate an Immutable Response
internal init(_ response:NSHTTPURLResponse, data:NSData?, requestedURL:NSURL, gateway:Gateway, request:Request)
{
self.gateway = gateway
self.request = request
self.statusCode = response.statusCode
var headers = Headers()
for (key, value) in response.allHeaderFields
{
if let keyString = key as? String, let valueString = value as? String
{
headers[keyString] = valueString
}
}
self.headers = headers
self.requestedURL = requestedURL
self.resolvedURL = response.URL ?? nil
self.body = data
self.parsedBody = nil
self.retreivedFromCache = false
}
}
internal extension Request
{
/// Internal method to convert any type of Request to a NSURLRequest for Foundation networking
internal func toNSURLRequest(gateway:Gateway) -> NSURLRequest?
{
// Identify the absolute URL endpoint
let endpointUrl:NSURL = gateway.baseUrl.URLByAppendingPathComponent(self.path);
var url:NSURL = endpointUrl
// If params are assigned, apply them
if nil != self.params && self.params!.count > 0
{
let params = self.params!
// Create a components object
guard let urlComponents:NSURLComponents = NSURLComponents(URL: endpointUrl, resolvingAgainstBaseURL: false) else
{
// Could not parse NSURL through this technique
return nil
}
// Build query list
var queryItems = Array<NSURLQueryItem>()
for (key,value) in params
{
if let arrayValue = value as? Array<AnyObject>
{
for (innerValue) in arrayValue
{
let queryItem:NSURLQueryItem = NSURLQueryItem(name: key + "[]", value:String(innerValue))
queryItems.append(queryItem)
}
}
else if let _ = value as? NSNull
{
let queryItem:NSURLQueryItem = NSURLQueryItem(name: key, value: nil);
queryItems.append(queryItem)
}
else if let stringValue = value as? CustomStringConvertible
{
let queryItem:NSURLQueryItem = NSURLQueryItem(name: key, value: String(stringValue));
queryItems.append(queryItem)
}
else
{
assert(false, "Unsupported query item value. Must be array, NSNull, or a CustomStringConvertible type")
}
}
urlComponents.queryItems = queryItems
// Try to resolve the URLComponents
guard let completeUrl = urlComponents.URL else
{
// Could not resolve to URL once we included query parameters
return nil
}
url = completeUrl
}
// Create the request object
let urlRequest:NSMutableURLRequest = NSMutableURLRequest(URL: url);
// Set the method
urlRequest.HTTPMethod = self.method;
// If headers were assigned, apply them
if nil != self.headers && self.headers!.count > 0
{
let headers = self.headers!
for (field,value) in headers
{
urlRequest.addValue(value, forHTTPHeaderField: field);
}
}
// If a body was assigned, apply it
if let body = self.body
{
urlRequest.HTTPBody = body
}
return urlRequest
}
}
| b4882d083d1ed9caad82eb445d8ab548 | 37.794355 | 203 | 0.600769 | false | false | false | false |
BenziAhamed/Nevergrid | refs/heads/master | NeverGrid/Source/CreditsScene.swift | isc | 1 | //
// CreditsScene.swift
// NeverGrid
//
// Created by Benzi on 05/03/15.
// Copyright (c) 2015 Benzi Ahamed. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
class CreditsScene : NavigatingScene {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init () {
super.init(context:NavigationContext())
}
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
setBackgroundImage("background_credits")
let logo = textSprite("credits")
logo.position = frame.mid() //CGPointMake(frame.midX, 0.66 * frame.height)
worldNode.addChild(logo)
// home button
let home = textSprite("home_level")
let homeButton = WobbleButton(node: home, action: Callback(self, CreditsScene.goToHome))
homeButton.position = CGPointMake(
self.frame.width - home.frame.width,
home.frame.height
)
worldNode.addChild(homeButton)
// twitter button
let twitter = textSprite("twitter")
let twitterButton = WobbleButton(node: twitter, action: Callback(self, CreditsScene.showTwitter))
twitterButton.position = CGPointMake(logo.position.x, logo.position.y-logo.frame.height/2.0-twitter.frame.height)
worldNode.addChild(twitterButton)
}
func goToHome() {
self.navigation.displayMainMenuWithReveal(SKTransitionDirection.Left)
}
func showTwitter() {
UIApplication.sharedApplication().openURL(NSURL(string: "http://twitter.com/benziahamed")!)
}
} | 99e366ae3b97508d1ea635949f44554b | 27.877193 | 121 | 0.643769 | false | false | false | false |
ChenWeiLee/Black-Fu | refs/heads/master | Black-Fu/Black-Fu/NewsWebViewController.swift | gpl-2.0 | 1 | //
// NewsWebViewController.swift
// Black-Fu
//
// Created by Li Chen wei on 2016/1/8.
// Copyright © 2016年 TWML. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class NewsWebViewController: UIViewController,UIWebViewDelegate {
@IBOutlet var newsWebView: UIWebView!
var loadWebString:String = String()
var loadingActivity:NVActivityIndicatorView = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), type: .BallClipRotatePulse, color: UIColor(red: 0.49, green: 0.87, blue: 0.47, alpha: 1.0), size: CGSizeMake(100, 100))
override func viewDidLoad() {
super.viewDidLoad()
loadingActivity.center = self.view.center
self.view.addSubview(loadingActivity)
guard let requestURL = NSURL(string:loadWebString) else {
return
}
let request = NSURLRequest(URL: requestURL)
newsWebView.loadRequest(request)
}
func webViewDidStartLoad(webView: UIWebView) {
loadingActivity.startAnimation()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?){
loadingActivity.stopAnimation()
print("\(error)")
}
func webViewDidFinishLoad(webView: UIWebView) {
loadingActivity.stopAnimation()
}
}
| 0c4ec85d43a81b9ebd3b811f17178967 | 24.309091 | 245 | 0.637213 | false | false | false | false |
emericspiroux/Open42 | refs/heads/master | Pods/p2.OAuth2/Sources/Base/OAuth2CodeGrant.swift | apache-2.0 | 2 | //
// OAuth2CodeGrant.swift
// OAuth2
//
// Created by Pascal Pfiffner on 6/16/14.
// Copyright 2014 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
/**
A class to handle authorization for confidential clients via the authorization code grant method.
This auth flow is designed for clients that are capable of protecting their client secret but can be used from installed apps. During code
exchange and token refresh flows, **if** the client has a secret, a "Basic key:secret" Authorization header will be used. If not the client
key will be embedded into the request body.
*/
public class OAuth2CodeGrant: OAuth2 {
public override class var grantType: String {
return "authorization_code"
}
override public class var responseType: String? {
return "code"
}
// MARK: - Token Request
/**
Generate the request to be used for the token request from known instance variables and supplied parameters.
This will set "grant_type" to "authorization_code", add the "code" provided and fill the remaining parameters. The "client_id" is only
added if there is no secret (public client) or if the request body is used for id and secret.
- parameter code: The code you want to exchange for an access token
- parameter params: Optional additional params to add as URL parameters
- returns: A request you can use to create a URL request to exchange the code for an access token
*/
func tokenRequestWithCode(code: String, params: OAuth2StringDict? = nil) throws -> OAuth2AuthRequest {
guard let clientId = clientConfig.clientId where !clientId.isEmpty else {
throw OAuth2Error.NoClientId
}
guard let redirect = context.redirectURL else {
throw OAuth2Error.NoRedirectURL
}
let req = OAuth2AuthRequest(url: (clientConfig.tokenURL ?? clientConfig.authorizeURL))
req.params["code"] = code
req.params["grant_type"] = self.dynamicType.grantType
req.params["redirect_uri"] = redirect
req.params["client_id"] = clientId
return req
}
/**
Extracts the code from the redirect URL and exchanges it for a token.
*/
override public func handleRedirectURL(redirect: NSURL) {
logger?.debug("OAuth2", msg: "Handling redirect URL \(redirect.description)")
do {
let code = try validateRedirectURL(redirect)
exchangeCodeForToken(code)
}
catch let error {
didFail(error)
}
}
/**
Takes the received code and exchanges it for a token.
*/
public func exchangeCodeForToken(code: String) {
do {
guard !code.isEmpty else {
throw OAuth2Error.PrerequisiteFailed("I don't have a code to exchange, let the user authorize first")
}
let post = try tokenRequestWithCode(code).asURLRequestFor(self)
logger?.debug("OAuth2", msg: "Exchanging code \(code) for access token at \(post.URL!)")
performRequest(post) { data, status, error in
do {
guard let data = data else {
throw error ?? OAuth2Error.NoDataInResponse
}
let params = try self.parseAccessTokenResponseData(data)
if status < 400 {
self.logger?.debug("OAuth2", msg: "Did exchange code for access [\(nil != self.clientConfig.accessToken)] and refresh [\(nil != self.clientConfig.refreshToken)] tokens")
self.didAuthorize(params)
}
else {
throw OAuth2Error.Generic("\(status)")
}
}
catch let error {
self.didFail(error)
}
}
}
catch let error {
didFail(error)
}
}
// MARK: - Utilities
/**
Validates the redirect URI: returns a tuple with the code and nil on success, nil and an error on failure.
*/
func validateRedirectURL(redirect: NSURL) throws -> String {
guard let expectRedirect = context.redirectURL else {
throw OAuth2Error.NoRedirectURL
}
let comp = NSURLComponents(URL: redirect, resolvingAgainstBaseURL: true)
if !redirect.absoluteString.hasPrefix(expectRedirect) && (!redirect.absoluteString.hasPrefix("urn:ietf:wg:oauth:2.0:oob") && "localhost" != comp?.host) {
throw OAuth2Error.InvalidRedirectURL("Expecting «\(expectRedirect)» but received «\(redirect)»")
}
if let compQuery = comp?.query where compQuery.characters.count > 0 {
let query = OAuth2CodeGrant.paramsFromQuery(comp!.percentEncodedQuery!)
try assureNoErrorInResponse(query)
if let cd = query["code"] {
// we got a code, use it if state is correct (and reset state)
try assureMatchesState(query)
return cd
}
throw OAuth2Error.ResponseError("No “code” received")
}
throw OAuth2Error.PrerequisiteFailed("The redirect URL contains no query fragment")
}
}
| cffa190c9a5cd65885a1df4ce53329bb | 32.9 | 175 | 0.717994 | false | false | false | false |
ahmed93/AAShimmerView | refs/heads/master | AAShimmerView/Classes/UIView+AAShimmerView.swift | mit | 1 | //
// UIView+AAShimmerView.swift
// AAShimmerView
//
// Created by Ahmed Magdi on 6/11/17.
// Copyright © 2017 Ahmed Magdi. All rights reserved.
//
import UIKit
public enum ShimmerAlignment {
case center
case top
case bottom
}
public extension UIView {
private static let association_subViews = ObjectAssociation<[UIView]>()
private static let association_viewHeight = ObjectAssociation<CGFloat>()
private static let association_viewAlpha = ObjectAssociation<CGFloat>()
private static let association_FBShimmerView = ObjectAssociation<AAShimmerView>()
private static let association_shimmerColors = ObjectAssociation<[UIColor]>()
private static let association_shimmerVerticalAlignment = ObjectAssociation<ShimmerAlignment>()
private var shimmerView: AAShimmerView? {
get { return UIView.association_FBShimmerView[self] }
set { UIView.association_FBShimmerView[self] = newValue }
}
var aaShimmerViewAlpha: CGFloat {
get { return UIView.association_viewAlpha[self] ?? self.alpha }
set { UIView.association_viewAlpha[self] = newValue }
}
public var aaShimmerSubViews: [UIView]? {
get { return UIView.association_subViews[self] }
set { UIView.association_subViews[self] = newValue }
}
public var aaShimmerHeight: CGFloat {
get { return UIView.association_viewHeight[self] ?? self.frame.height }
set { UIView.association_viewHeight[self] = newValue }
}
public var isShimmering:Bool {
return shimmerView != nil
}
public var aashimmerColors:[UIColor]? {
get { return UIView.association_shimmerColors[self] }
set { UIView.association_shimmerColors[self] = newValue }
}
/// Vertical Alignment by default is set to center.
public var aashimmerVerticalAlignment:ShimmerAlignment {
get { return UIView.association_shimmerVerticalAlignment[self] ?? .center }
set { UIView.association_shimmerVerticalAlignment[self] = newValue }
}
public func startShimmering() {
if shimmerView == nil {
shimmerView = AAShimmerView(rootView: self)
}
shimmerView?.start()
}
public func stopShimmering() {
if shimmerView == nil {
return
}
shimmerView?.stop()
shimmerView = nil
}
}
| 111daf2a3ccca02aa482af58077a6216 | 30.973333 | 99 | 0.667223 | false | false | false | false |
JGiola/swift | refs/heads/main | benchmark/single-source/IntegerParsing.swift | apache-2.0 | 10 | //===--- IntegerParsing.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 TestsUtils
// - Definitions
public let benchmarks = [
// IntSmall
BenchmarkInfo(name: "ParseInt.IntSmall.Decimal",
runFunction: run_ParseIntFromIntSmallDecimal,
tags: [.validation, .api],
setUpFunction: {
blackHole(intSmallValuesSum)
blackHole(intSmallDecimalStrings)
}),
BenchmarkInfo(name: "ParseInt.IntSmall.Binary",
runFunction: run_ParseIntFromIntSmallBinary,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(intSmallValuesSum)
blackHole(intSmallBinaryStrings)
}),
BenchmarkInfo(name: "ParseInt.IntSmall.Hex",
runFunction: run_ParseIntFromIntSmallHex,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(intSmallValuesSum)
blackHole(intSmallHexStrings)
}),
BenchmarkInfo(name: "ParseInt.IntSmall.UncommonRadix",
runFunction: run_ParseIntFromIntSmallUncommonRadix,
tags: [.validation, .api],
setUpFunction: {
blackHole(intSmallValuesSum)
blackHole(intSmallUncommonRadixStrings)
}),
// UIntSmall
BenchmarkInfo(name: "ParseInt.UIntSmall.Decimal",
runFunction: run_ParseIntFromUIntSmallDecimal,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uintSmallValuesSum)
blackHole(uintSmallDecimalStrings)
}),
BenchmarkInfo(name: "ParseInt.UIntSmall.Binary",
runFunction: run_ParseIntFromUIntSmallBinary,
tags: [.validation, .api],
setUpFunction: {
blackHole(uintSmallValuesSum)
blackHole(uintSmallBinaryStrings)
}),
BenchmarkInfo(name: "ParseInt.UIntSmall.Hex",
runFunction: run_ParseIntFromUIntSmallHex,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uintSmallValuesSum)
blackHole(uintSmallHexStrings)
}),
BenchmarkInfo(name: "ParseInt.UIntSmall.UncommonRadix",
runFunction: run_ParseIntFromUIntSmallUncommonRadix,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uintSmallValuesSum)
blackHole(uintSmallUncommonRadixStrings)
}),
// Int32
BenchmarkInfo(name: "ParseInt.Int32.Decimal",
runFunction: run_ParseIntFromInt32Decimal,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(int32ValuesSum)
blackHole(int32DecimalStrings)
}),
BenchmarkInfo(name: "ParseInt.Int32.Binary",
runFunction: run_ParseIntFromInt32Binary,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(int32ValuesSum)
blackHole(int32BinaryStrings)
}),
BenchmarkInfo(name: "ParseInt.Int32.Hex",
runFunction: run_ParseIntFromInt32Hex,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(int32ValuesSum)
blackHole(int32HexStrings)
}),
BenchmarkInfo(name: "ParseInt.Int32.UncommonRadix",
runFunction: run_ParseIntFromInt32UncommonRadix,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(int32ValuesSum)
blackHole(int32UncommonRadixStrings)
}),
// Int64
BenchmarkInfo(name: "ParseInt.Int64.Decimal",
runFunction: run_ParseIntFromInt64Decimal,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(int64ValuesSum)
blackHole(int64DecimalStrings)
}),
BenchmarkInfo(name: "ParseInt.Int64.Binary",
runFunction: run_ParseIntFromInt64Binary,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(int64ValuesSum)
blackHole(int64BinaryStrings)
}),
BenchmarkInfo(name: "ParseInt.Int64.Hex",
runFunction: run_ParseIntFromInt64Hex,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(int64ValuesSum)
blackHole(int64HexStrings)
}),
BenchmarkInfo(name: "ParseInt.Int64.UncommonRadix",
runFunction: run_ParseIntFromInt64UncommonRadix,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(int64ValuesSum)
blackHole(int64UncommonRadixStrings)
}),
// UInt32
BenchmarkInfo(name: "ParseInt.UInt32.Decimal",
runFunction: run_ParseIntFromUInt32Decimal,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uint32ValuesSum)
blackHole(uint32DecimalStrings)
}),
BenchmarkInfo(name: "ParseInt.UInt32.Binary",
runFunction: run_ParseIntFromUInt32Binary,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uint32ValuesSum)
blackHole(uint32BinaryStrings)
}),
BenchmarkInfo(name: "ParseInt.UInt32.Hex",
runFunction: run_ParseIntFromUInt32Hex,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uint32ValuesSum)
blackHole(uint32HexStrings)
}),
BenchmarkInfo(name: "ParseInt.UInt32.UncommonRadix",
runFunction: run_ParseIntFromUInt32UncommonRadix,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uint32ValuesSum)
blackHole(uint32UncommonRadixStrings)
}),
// UInt64
BenchmarkInfo(name: "ParseInt.UInt64.Decimal",
runFunction: run_ParseIntFromUInt64Decimal,
tags: [.validation, .api],
setUpFunction: {
blackHole(uint64ValuesSum)
blackHole(uint64DecimalStrings)
}),
BenchmarkInfo(name: "ParseInt.UInt64.Binary",
runFunction: run_ParseIntFromUInt64Binary,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uint64ValuesSum)
blackHole(uint64BinaryStrings)
}),
BenchmarkInfo(name: "ParseInt.UInt64.Hex",
runFunction: run_ParseIntFromUInt64Hex,
tags: [.validation, .api],
setUpFunction: {
blackHole(uint64ValuesSum)
blackHole(uint64HexStrings)
}),
BenchmarkInfo(name: "ParseInt.UInt64.UncommonRadix",
runFunction: run_ParseIntFromUInt64UncommonRadix,
tags: [.validation, .api, .skip],
setUpFunction: {
blackHole(uint64ValuesSum)
blackHole(uint64UncommonRadixStrings)
}),
]
// - Verification Sums
private let intSmallValuesSum: Int
= intSmallValues.reduce(0, &+)
private let uintSmallValuesSum: UInt
= uintSmallValues.reduce(0, &+)
private let int32ValuesSum: Int32
= int32Values.reduce(0, &+)
private let int64ValuesSum: Int64
= int64Values.reduce(0, &+)
private let uint32ValuesSum: UInt32
= uint32Values.reduce(0, &+)
private let uint64ValuesSum: UInt64
= uint64Values.reduce(0, &+)
// - Values
func generateValues<Integer : FixedWidthInteger>(
in range: ClosedRange<Integer>, count: Int
) -> [Integer] {
var rng = SplitMix64(seed: 42)
return (0..<count).map { _ in
Integer.random(in: range, using: &rng)
}
}
private let intSmallValues: [Int]
= generateValues(in: -9999 ... 9999, count: 1000)
private let uintSmallValues: [UInt]
= generateValues(in: 0 ... 9999, count: 1000)
private let int32Values: [Int32]
= generateValues(in: .min ... .max, count: 1000)
private let int64Values: [Int64]
= generateValues(in: .min ... .max, count: 1000)
private let uint32Values: [UInt32]
= generateValues(in: .min ... .max, count: 1000)
private let uint64Values: [UInt64]
= generateValues(in: .min ... .max, count: 1000)
// - Strings
// IntSmall
private let intSmallDecimalStrings: [String]
= intSmallValues.map { String($0, radix: 10) }
private let intSmallBinaryStrings: [String]
= intSmallValues.map { String($0, radix: 2) }
private let intSmallHexStrings: [String]
= intSmallValues.map { String($0, radix: 16) }
private let intSmallUncommonRadixStrings: [String]
= intSmallValues.map { String($0, radix: 7) }
// UIntSmall
private let uintSmallDecimalStrings: [String]
= uintSmallValues.map { String($0, radix: 10) }
private let uintSmallBinaryStrings: [String]
= uintSmallValues.map { String($0, radix: 2) }
private let uintSmallHexStrings: [String]
= uintSmallValues.map { String($0, radix: 16) }
private let uintSmallUncommonRadixStrings: [String]
= uintSmallValues.map { String($0, radix: 7) }
// Int32
private let int32DecimalStrings: [String]
= int32Values.map { String($0, radix: 10) }
private let int32BinaryStrings: [String]
= int32Values.map { String($0, radix: 2) }
private let int32HexStrings: [String]
= int32Values.map { String($0, radix: 16) }
private let int32UncommonRadixStrings: [String]
= int32Values.map { String($0, radix: 7) }
// Int64
private let int64DecimalStrings: [String]
= int64Values.map { String($0, radix: 10) }
private let int64BinaryStrings: [String]
= int64Values.map { String($0, radix: 2) }
private let int64HexStrings: [String]
= int64Values.map { String($0, radix: 16) }
private let int64UncommonRadixStrings: [String]
= int64Values.map { String($0, radix: 7) }
// UInt32
private let uint32DecimalStrings: [String]
= uint32Values.map { String($0, radix: 10) }
private let uint32BinaryStrings: [String]
= uint32Values.map { String($0, radix: 2) }
private let uint32HexStrings: [String]
= uint32Values.map { String($0, radix: 16) }
private let uint32UncommonRadixStrings: [String]
= uint32Values.map { String($0, radix: 7) }
// UInt64
private let uint64DecimalStrings: [String]
= uint64Values.map { String($0, radix: 10) }
private let uint64BinaryStrings: [String]
= uint64Values.map { String($0, radix: 2) }
private let uint64HexStrings: [String]
= uint64Values.map { String($0, radix: 16) }
private let uint64UncommonRadixStrings: [String]
= uint64Values.map { String($0, radix: 7) }
// - Implementations
// IntSmall
@inline(never)
public func run_ParseIntFromIntSmallDecimal(n: Int) {
var result: Int = 0
let count = n * 20
for _ in 0..<count {
for string in intSmallDecimalStrings {
result &+= Int(string, radix: 10)!
}
}
check(result == intSmallValuesSum &* Int(count))
}
@inline(never)
public func run_ParseIntFromIntSmallBinary(n: Int) {
var result: Int = 0
let count = n * 20
for _ in 0..<count {
for string in intSmallBinaryStrings {
result &+= Int(string, radix: 2)!
}
}
check(result == intSmallValuesSum &* Int(count))
}
@inline(never)
public func run_ParseIntFromIntSmallHex(n: Int) {
var result: Int = 0
let count = n * 20
for _ in 0..<count {
for string in intSmallHexStrings {
result &+= Int(string, radix: 16)!
}
}
check(result == intSmallValuesSum &* Int(count))
}
@inline(never)
public func run_ParseIntFromIntSmallUncommonRadix(n: Int) {
var result: Int = 0
let count = n * 20
for _ in 0..<count {
for string in intSmallUncommonRadixStrings {
result &+= Int(string, radix: 7)!
}
}
check(result == intSmallValuesSum &* Int(count))
}
// UIntSmall
@inline(never)
public func run_ParseIntFromUIntSmallDecimal(n: Int) {
var result: UInt = 0
let count = n * 20
for _ in 0..<count {
for string in uintSmallDecimalStrings {
result &+= UInt(string, radix: 10)!
}
}
check(result == uintSmallValuesSum &* UInt(count))
}
@inline(never)
public func run_ParseIntFromUIntSmallBinary(n: Int) {
var result: UInt = 0
let count = n * 20
for _ in 0..<count {
for string in uintSmallBinaryStrings {
result &+= UInt(string, radix: 2)!
}
}
check(result == uintSmallValuesSum &* UInt(count))
}
@inline(never)
public func run_ParseIntFromUIntSmallHex(n: Int) {
var result: UInt = 0
let count = n * 20
for _ in 0..<count {
for string in uintSmallHexStrings {
result &+= UInt(string, radix: 16)!
}
}
check(result == uintSmallValuesSum &* UInt(count))
}
@inline(never)
public func run_ParseIntFromUIntSmallUncommonRadix(n: Int) {
var result: UInt = 0
let count = n * 20
for _ in 0..<count {
for string in uintSmallUncommonRadixStrings {
result &+= UInt(string, radix: 7)!
}
}
check(result == uintSmallValuesSum &* UInt(count))
}
// Int32
@inline(never)
public func run_ParseIntFromInt32Decimal(n: Int) {
var result: Int32 = 0
let count = n * 8
for _ in 0..<count {
for string in int32DecimalStrings {
result &+= Int32(string, radix: 10)!
}
}
check(result == int32ValuesSum &* Int32(count))
}
@inline(never)
public func run_ParseIntFromInt32Binary(n: Int) {
var result: Int32 = 0
let count = n * 8
for _ in 0..<count {
for string in int32BinaryStrings {
result &+= Int32(string, radix: 2)!
}
}
check(result == int32ValuesSum &* Int32(count))
}
@inline(never)
public func run_ParseIntFromInt32Hex(n: Int) {
var result: Int32 = 0
let count = n * 8
for _ in 0..<count {
for string in int32HexStrings {
result &+= Int32(string, radix: 16)!
}
}
check(result == int32ValuesSum &* Int32(count))
}
@inline(never)
public func run_ParseIntFromInt32UncommonRadix(n: Int) {
var result: Int32 = 0
let count = n * 8
for _ in 0..<count {
for string in int32UncommonRadixStrings {
result &+= Int32(string, radix: 7)!
}
}
check(result == int32ValuesSum &* Int32(count))
}
// Int64
@inline(never)
public func run_ParseIntFromInt64Decimal(n: Int) {
var result: Int64 = 0
let count = n * 4
for _ in 0..<count {
for string in int64DecimalStrings {
result &+= Int64(string, radix: 10)!
}
}
check(result == int64ValuesSum &* Int64(count))
}
@inline(never)
public func run_ParseIntFromInt64Binary(n: Int) {
var result: Int64 = 0
let count = n * 4
for _ in 0..<count {
for string in int64BinaryStrings {
result &+= Int64(string, radix: 2)!
}
}
check(result == int64ValuesSum &* Int64(count))
}
@inline(never)
public func run_ParseIntFromInt64Hex(n: Int) {
var result: Int64 = 0
let count = n * 4
for _ in 0..<count {
for string in int64HexStrings {
result &+= Int64(string, radix: 16)!
}
}
check(result == int64ValuesSum &* Int64(count))
}
@inline(never)
public func run_ParseIntFromInt64UncommonRadix(n: Int) {
var result: Int64 = 0
let count = n * 4
for _ in 0..<count {
for string in int64UncommonRadixStrings {
result &+= Int64(string, radix: 7)!
}
}
check(result == int64ValuesSum &* Int64(count))
}
// UInt32
@inline(never)
public func run_ParseIntFromUInt32Decimal(n: Int) {
var result: UInt32 = 0
let count = n * 8
for _ in 0..<count {
for string in uint32DecimalStrings {
result &+= UInt32(string, radix: 10)!
}
}
check(result == uint32ValuesSum &* UInt32(count))
}
@inline(never)
public func run_ParseIntFromUInt32Binary(n: Int) {
var result: UInt32 = 0
let count = n * 8
for _ in 0..<count {
for string in uint32BinaryStrings {
result &+= UInt32(string, radix: 2)!
}
}
check(result == uint32ValuesSum &* UInt32(count))
}
@inline(never)
public func run_ParseIntFromUInt32Hex(n: Int) {
var result: UInt32 = 0
let count = n * 8
for _ in 0..<count {
for string in uint32HexStrings {
result &+= UInt32(string, radix: 16)!
}
}
check(result == uint32ValuesSum &* UInt32(count))
}
@inline(never)
public func run_ParseIntFromUInt32UncommonRadix(n: Int) {
var result: UInt32 = 0
let count = n * 8
for _ in 0..<count {
for string in uint32UncommonRadixStrings {
result &+= UInt32(string, radix: 7)!
}
}
check(result == uint32ValuesSum &* UInt32(count))
}
// UInt64
@inline(never)
public func run_ParseIntFromUInt64Decimal(n: Int) {
var result: UInt64 = 0
let count = n * 4
for _ in 0..<count {
for string in uint64DecimalStrings {
result &+= UInt64(string, radix: 10)!
}
}
check(result == uint64ValuesSum &* UInt64(count))
}
@inline(never)
public func run_ParseIntFromUInt64Binary(n: Int) {
var result: UInt64 = 0
let count = n * 4
for _ in 0..<count {
for string in uint64BinaryStrings {
result &+= UInt64(string, radix: 2)!
}
}
check(result == uint64ValuesSum &* UInt64(count))
}
@inline(never)
public func run_ParseIntFromUInt64Hex(n: Int) {
var result: UInt64 = 0
let count = n * 4
for _ in 0..<count {
for string in uint64HexStrings {
result &+= UInt64(string, radix: 16)!
}
}
check(result == uint64ValuesSum &* UInt64(count))
}
@inline(never)
public func run_ParseIntFromUInt64UncommonRadix(n: Int) {
var result: UInt64 = 0
let count = n * 4
for _ in 0..<count {
for string in uint64UncommonRadixStrings {
result &+= UInt64(string, radix: 7)!
}
}
check(result == uint64ValuesSum &* UInt64(count))
}
| c5f8341655911cbb9b543491137057b2 | 27.483705 | 80 | 0.674636 | false | false | false | false |
sunlijian/sinaBlog_repository | refs/heads/master | sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Module/Compose/View/IWComposeView.swift | apache-2.0 | 1 | //
// IWComposeView.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/18.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
import pop
let COMPOSE_BUTTON_MAGIN: CGFloat = (SCREEN_W - 3*COMPOSE_BUTTON_W) / 4
class IWComposeView: UIView {
var targetVC : UIViewController?
override init(frame: CGRect) {
super.init(frame: frame)
//设置大小
self.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H)
//添加背景图片
let imageView = UIImageView(image: screenImage())
imageView.size = size
addSubview(imageView)
//添加 button
addMeumButton()
//添加compose_slogan
addCompose_sloganImage()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//屏幕载图
private func screenImage() -> UIImage{
//取出 window
let window = UIApplication.sharedApplication().keyWindow
//开启图形上下文
UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_W, SCREEN_H), false, 0)
//把当前 window 显示的图形添加到上下文中
window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: false)
//获取图片
var image = UIGraphicsGetImageFromCurrentImageContext()
//进行模糊渲染
image = image.applyLightEffect()
//关闭图形上下文
UIGraphicsEndImageContext()
return image
}
//添加 button
private func addMeumButton(){
//解析 plist 文件
let path = NSBundle.mainBundle().pathForResource("compose", ofType: "plist")
let composeButtonInfos = NSArray(contentsOfFile: path!)
//遍历添加 button
for i in 0..<composeButtonInfos!.count{
//创建 button
let buttonInfo = IWComposeButton()
//添加监听事件
buttonInfo.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
//取出字典
let info = composeButtonInfos![i] as! [String: AnyObject]
//给 button 赋值
buttonInfo.setImage(UIImage(named: (info["icon"] as! String)), forState: UIControlState.Normal)
buttonInfo.setTitle((info["title"] as! String), forState: UIControlState.Normal)
//设置 button 的 位置
let rowIndex = i / 3
let colIndex = i % 3
buttonInfo.x = CGFloat(colIndex) * COMPOSE_BUTTON_W + CGFloat(colIndex + 1) * COMPOSE_BUTTON_MAGIN
buttonInfo.y = CGFloat(rowIndex) * COMPOSE_BUTTON_H + CGFloat(rowIndex + 1) * COMPOSE_BUTTON_MAGIN + SCREEN_H
print(buttonInfo.x)
//添加到当前 view 上
addSubview(buttonInfo)
//添加到数组中
composeButtons.append(buttonInfo)
}
}
//点击加号按钮
func show(target:UIViewController){
target.view.addSubview(self)
self.targetVC = target
//添加动画
for (index, value) in composeButtons.enumerate(){
anmi(value, centerY: value.centerY - 400, index: index)
}
}
//点击屏幕消失
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
dismiss()
}
func dismiss(){
for (index, value) in composeButtons.reverse().enumerate(){
anmi(value, centerY: value.centerY + 400, index: index)
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
self.removeFromSuperview()
}
}
//初始化添加顶部控件到 view 上
private func addCompose_sloganImage(){
addSubview(sloganImage)
}
//懒加载顶部的 logo控件
private lazy var sloganImage : UIImageView = {
let imageView = UIImageView(image: UIImage(named: "compose_slogan"))
imageView.centerX = SCREEN_W * 0.5
imageView.y = 100
return imageView
}()
//button 数组的懒加载
private lazy var composeButtons :[IWComposeButton] = [IWComposeButton]()
//button 的点击事件
@objc private func composeButtonClick(button: IWComposeButton){
UIView.animateWithDuration(0.25, animations: { () -> Void in
//改变 button 的 transform
for value in self.composeButtons{
if value == button {
value.transform = CGAffineTransformMakeScale(2, 2)
}else{
value.transform = CGAffineTransformMakeScale(0, 0)
}
value.alpha = 0
}
}) { (finish) -> Void in
let vc = IWComposeViewController()
let nv = IWNavigationController(rootViewController: vc)
self.targetVC?.presentViewController(nv, animated: true, completion: { () -> Void in
self.removeFromSuperview()
})
}
}
//动画
private func anmi(value:UIButton, centerY:CGFloat, index: Int){
//初始化一个弹性动画对象
let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
anim.toValue = NSValue(CGPoint: CGPointMake(value.centerX, centerY))
//动画的弹性幅度
anim.springBounciness = 10
//动画的速度
anim.springSpeed = 10
//动画的执行时间(相对于现在来说 向后延迟多少秒)
anim.beginTime = CACurrentMediaTime() + Double(index) * 0.025
//给控件添加动画对象
value.pop_addAnimation(anim, forKey: nil)
}
}
| e99eb79fc276caae91323f8096a89615 | 32.233129 | 134 | 0.587595 | false | false | false | false |
nlgb/VVSPageView | refs/heads/master | VVSPageView/VVSPageView/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// VVSPageView
//
// Created by sw on 17/4/19.
// Copyright © 2017年 sw. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let style = VVSPageStyle()
style.titleIsScrollEnable = false
automaticallyAdjustsScrollViewInsets = false
let titles = ["精华","热门视频","图片","文字"]
// let titles = ["精华","热门视频","动态图片","搞笑文字","热门游戏","广告"]
var childVcs = [UIViewController]()
for _ in 0..<titles.count {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1.0)
childVcs.append(vc)
}
let pageViewFrame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64)
let pageView = VVSPageView(frame: pageViewFrame, style: style, titles: titles, childVcs: childVcs, parentVc: self)
pageView.backgroundColor = .blue
view.addSubview(pageView)
}
}
| 3a80d361c8ba872b760d25c2c5b3ab2c | 31.297297 | 195 | 0.628452 | false | false | false | false |
balthild/Mathemalpha | refs/heads/master | Carthage/Checkouts/KeyHolder/Carthage/Checkouts/Magnet/Lib/Magnet/HotKey.swift | gpl-3.0 | 1 | //
// HotKey.swift
// Magnet
//
// Created by 古林俊佑 on 2016/03/09.
// Copyright © 2016年 Shunsuke Furubayashi. All rights reserved.
//
import Cocoa
import Carbon
public final class HotKey: Equatable {
// MARK: - Properties
public let identifier: String
public let keyCombo: KeyCombo
public var target: AnyObject?
public var action: Selector?
public var hotKeyId: UInt32?
public var hotKeyRef: EventHotKeyRef?
// MARK: - Init
public init(identifier: String, keyCombo: KeyCombo, target: AnyObject? = nil, action: Selector? = nil) {
self.identifier = identifier
self.keyCombo = keyCombo
self.target = target
self.action = action
}
}
// MARK: - Invoke
public extension HotKey {
public func invoke() {
if let target = target as? NSObject, let selector = action {
if target.responds(to: selector) {
target.perform(selector, with: self)
}
}
}
}
// MARK: - Register & UnRegister
public extension HotKey {
@discardableResult
public func register() -> Bool {
return HotKeyCenter.shared.register(with: self)
}
public func unregister() {
return HotKeyCenter.shared.unregister(with: self)
}
}
// MARK: - Equatable
public func ==(lhs: HotKey, rhs: HotKey) -> Bool {
return lhs.identifier == rhs.identifier &&
lhs.keyCombo == rhs.keyCombo &&
lhs.hotKeyId == rhs.hotKeyId &&
lhs.hotKeyRef == rhs.hotKeyRef
}
| 69cf065a0c9a05adc811eb7258a1385c | 24.466667 | 108 | 0.61911 | false | false | false | false |
yuenhsi/interactive-bridge | refs/heads/master | Interactive Bridge/Interactive Bridge/Hand.swift | mit | 1 | //
// Hand.swift
// Interactive Bridge
//
// Created by Yuen Hsi Chang on 1/26/17.
// Copyright © 2017 Yuen Hsi Chang. All rights reserved.
//
import Foundation
class Hand {
var cards: [Card]!
init(_ cards: [Card]) {
self.cards = cards
self.cards.sort { sortCardsBySuit(first: $0, second: $1) }
}
func sortCardsBySuit(first: Card, second: Card) -> Bool {
if first.Suit == second.Suit {
return first.Rank.hashValue > second.Rank.hashValue
} else {
return first.Suit.hashValue > second.Suit.hashValue
}
}
func cardsIn(suit: Suit) -> Int {
return (cards.filter { $0.Suit == suit }).count
}
func addCard(card: Card) {
self.cards.append(card)
}
func removeCard(card: Card) {
self.cards = self.cards.filter() { $0 != card }
}
func sort() {
self.cards.sort { sortCardsBySuit(first: $0, second: $1) }
}
func removeAll() {
self.cards.removeAll()
}
func hasSuit(suit: Suit?) -> Bool {
if suit == nil {
return false
}
return self.cards.contains(where: { $0.Suit == suit} )
}
}
| 19b5977372e7e633825feee34ddee9c0 | 21.62963 | 66 | 0.536825 | false | false | false | false |
mikina/Right-Direction | refs/heads/master | RightDirection/RightDirection/Controller/GameBoardViewController.swift | mit | 1 | //
// GameBoardViewController.swift
// RightDirection
//
// Created by Mike Mikina on 3/3/16.
// Copyright © 2016 FDT. All rights reserved.
//
import UIKit
class GameBoardViewController: UIViewController {
let topBarHeight = 44 //size of top navigation bar, navbar here it's just normal UIView
let minDirectionViewSquare = 200 //minimum size of view with directions
let maxDirectionViewSquare = 250 //maximum size of view with directions
let playTime = 60
@IBOutlet weak var directionsViewHeight: NSLayoutConstraint!
@IBOutlet weak var directionsViewWidth: NSLayoutConstraint!
@IBOutlet weak var directionsViewAxisX: NSLayoutConstraint!
@IBOutlet weak var directionsViewAxisY: NSLayoutConstraint!
@IBOutlet weak var directionsView: DirectionsView!
var scoreManager: ScoreManager?
var timeManager: TimerManager?
var updatePoints: ((points: Int) -> ())?
var updateTime: ((time: Int) -> ())?
var badgeView: BadgeView?
// When false we block all swipe gestures,
// game is inactive at the begining and at the end when time pass
var isGameActive = false
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.showHelloMessages([NSLocalizedString("Prepare...", comment: "Prepare..."), NSLocalizedString("3", comment: "3"), NSLocalizedString("2", comment: "2"), NSLocalizedString("1", comment: "1"), NSLocalizedString("Go!", comment: "Go!")])
}
func startGame() {
self.isGameActive = true
self.timeManager?.startCountdown(self.playTime)
self.setupDirections()
self.setRandomPosition()
}
func finishGame() {
self.isGameActive = false
self.directionsView.cleanUp()
if let scoreManager = self.scoreManager {
let finalMessage = NSLocalizedString("You have: ", comment: "You have: ") + String(scoreManager.userScore) + NSLocalizedString(" points!", comment: " points!")
self.showFinalMessage(finalMessage)
}
self.getFromUser(NSLocalizedString("Enter your name", comment: "Enter your name")) { (name) -> () in
self.scoreManager?.saveScoreForUser(name)
}
}
func setup() {
self.scoreManager = ScoreManager()
self.setupView()
self.timeManager = TimerManager()
if let update = self.updateTime, time = self.timeManager {
// This closure is called every second the timer is running, we use it
// to run another closure which updates label in GameTabVC
time.tick = { timeValue in
update(time: timeValue)
}
// This closure is called when timer finish countdown
time.completeCountdown = {
self.finishGame()
}
}
}
func setupView() {
for direction in [.Right, .Left, .Up, .Down] as [UISwipeGestureRecognizerDirection] {
self.addSwipeRecognizerForDirection(direction)
}
if let badge = NSBundle.mainBundle().loadNibNamed("BadgeView", owner: self, options: nil)[0] as? BadgeView {
self.view.addSubview(badge)
self.badgeView = badge
badge.setupAsModal(self.view, width: badge.badgeViewWidth, height: badge.badgeViewHeight, corners: badge.badgeRoundedCorners)
}
}
func setupDirections() {
self.directionsView.cleanUp()
if let directions = NSBundle.mainBundle().loadNibNamed("DirectionsView", owner: self, options: nil)[0] as? DirectionsView {
directions.datasource = DirectionsManager.sharedInstance.getItem()
directions.setup()
self.directionsView.addSubview(directions)
directions.pinToAll(self.directionsView)
}
}
func setRandomPosition() {
let randomSquareSize = Int.random(self.minDirectionViewSquare...self.maxDirectionViewSquare)
let maxX = Int(self.view.frame.size.width) - randomSquareSize
let maxY = Int(self.view.frame.size.height - CGFloat(self.topBarHeight)) - randomSquareSize
let randomX = Int.random(1...maxX)
let randomY = Int.random(1...maxY)
self.directionsViewAxisX.constant = CGFloat(randomX)
self.directionsViewAxisY.constant = CGFloat(randomY)
self.directionsViewWidth.constant = CGFloat(randomSquareSize)
self.directionsViewHeight.constant = CGFloat(randomSquareSize)
}
func addSwipeRecognizerForDirection(direction: UISwipeGestureRecognizerDirection) {
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(GameBoardViewController.handleSwipe(_:)))
swipeGesture.direction = direction //it's also possible to pass whole array here, but apparently in that case only left and right swipe works (Xcode 7.2)
self.view.addGestureRecognizer(swipeGesture)
}
func handleSwipe(swipe: UISwipeGestureRecognizer) {
if !self.isGameActive {
return
}
let direction: DirectionsType = swipe.direction.translateToDirection()
let result = DirectionsManager.sharedInstance.validateDirection(direction)
self.scoreManager?.calculateScore(result)
self.badgeView?.setupBadgeWithResult(result)
self.updateScoreView()
self.setupDirections()
self.setRandomPosition()
}
func updateScoreView() {
if let updatePoints = self.updatePoints {
if let score = self.scoreManager {
updatePoints(points: score.userScore)
}
}
}
}
| 881107ffa7bd2570b27f65b8b83ebc10 | 34.506667 | 240 | 0.708787 | false | false | false | false |
leizh007/HiPDA | refs/heads/master | HiPDA/HiPDA/General/Views/BaseTableView.swift | mit | 1 | //
// BaseTableView.swift
// HiPDA
//
// Created by leizh007 on 2016/11/16.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import MJRefresh
/// BaseTableView的Rx扩展
extension Reactive where Base: BaseTableView {
/// 状态
var status: UIBindingObserver<Base, DataLoadStatus> {
return UIBindingObserver(UIElement: base) { (tableView, status) in
tableView.status = status
}
}
/// 是否正在编辑
var isEditing: UIBindingObserver<Base, Bool> {
return UIBindingObserver(UIElement: base) { (tableView, isEditing) in
tableView.isEditing = isEditing
}
}
}
class BaseTableView: UITableView, DataLoadable {
var refreshHeader: MJRefreshNormalHeader? {
get {
return mj_header as? MJRefreshNormalHeader
}
set {
mj_header = newValue
}
}
var loadMoreFooter: MJRefreshBackNormalFooter? {
get {
return mj_footer as? MJRefreshBackNormalFooter
}
set {
mj_footer = newValue
}
}
var hasRefreshHeader = false {
didSet {
didSetHasRefreshHeader()
}
}
var hasLoadMoreFooter = false {
didSet {
didSetHasLoadMoreFooter()
}
}
weak var dataLoadDelegate: DataLoadDelegate?
var status = DataLoadStatus.loading {
didSet {
didSetStatus()
}
}
lazy var noResultView: NoResultView = {
NoResultView.xibInstance
}()
override func layoutSubviews() {
super.layoutSubviews()
if noResultView.superview != nil {
noResultView.frame = bounds
noResultView.tapToLoadDelegate = self
bringSubview(toFront: noResultView)
}
}
}
| 0b71fed9069718739dfd755ac399c22d | 21.411765 | 77 | 0.581102 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | refs/heads/master | Classes/Core/User/UserStandardAttributeModels.swift | apache-2.0 | 1 | //
// UserStandardAttributeModels.swift
// MobileMessaging
//
// Created by Andrey Kadochnikov on 29/11/2018.
//
import Foundation
@objc public enum MMGenderNonnull: Int {
case Female
case Male
case Undefined
var toGender: MMGender? {
switch self {
case .Female : return .Female
case .Male : return .Male
case .Undefined : return nil
}
}
static func make(from gender: MMGender?) -> MMGenderNonnull {
if let gender = gender {
switch gender {
case .Female: return .Female
case .Male: return .Male
}
} else {
return .Undefined
}
}
}
public enum MMGender: Int {
case Female
case Male
public var name: String {
switch self {
case .Female : return "Female"
case .Male : return "Male"
}
}
static func make(with name: String) -> MMGender? {
switch name {
case "Female":
return MMGender.Female
case "Male":
return MMGender.Male
default:
return nil
}
}
}
@objcMembers public final class MMPhone: NSObject, NSCoding, JSONDecodable, DictionaryRepresentable {
public let number: String
public var preferred: Bool
// more properties needed? ok but look at the code below first.
required init?(dictRepresentation dict: DictionaryRepresentation) {
fatalError("init(dictRepresentation:) has not been implemented")
}
var dictionaryRepresentation: DictionaryRepresentation {
return ["number": number]
}
public override var hash: Int {
return number.hashValue// ^ preferred.hashValue // use hasher combine
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MMPhone else {
return false
}
return self.number == object.number // preferred is not supported yet on mobile api
}
convenience init?(json: JSON) {
let preferred = false
guard let number = json["number"].string else { // preferred is not supported yet on mobile api
return nil
}
self.init(number: number, preferred: preferred)
}
public init(number: String, preferred: Bool) {
self.number = number
self.preferred = preferred
}
required public init?(coder aDecoder: NSCoder) {
number = aDecoder.decodeObject(forKey: "number") as! String
preferred = aDecoder.decodeBool(forKey: "preferred")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(number, forKey: "number")
aCoder.encode(preferred, forKey: "preferred")
}
}
@objcMembers public final class MMEmail: NSObject, NSCoding, JSONDecodable, DictionaryRepresentable {
public let address: String
public var preferred: Bool
// more properties needed? ok but look at the code below first.
required init?(dictRepresentation dict: DictionaryRepresentation) {
fatalError("init(dictRepresentation:) has not been implemented")
}
var dictionaryRepresentation: DictionaryRepresentation {
return ["address": address]
}
public override var hash: Int {
return address.hashValue// ^ preferred.hashValue // use hasher combine
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MMEmail else {
return false
}
return self.address == object.address
}
convenience init?(json: JSON) {
let preferred = false
guard let address = json["address"].string else { // preferred is not supported yet on mobile api
return nil
}
self.init(address: address, preferred: preferred)
}
public init(address: String, preferred: Bool) {
self.address = address
self.preferred = preferred
}
required public init?(coder aDecoder: NSCoder) {
address = aDecoder.decodeObject(forKey: "address") as! String
preferred = aDecoder.decodeBool(forKey: "preferred")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(address, forKey: "address")
aCoder.encode(preferred, forKey: "preferred")
}
}
@objcMembers public class MMUserIdentity: NSObject {
public let phones: [String]?
public let emails: [String]?
public let externalUserId: String?
/// Default initializer. The object won't be initialized if all three arguments are nil/empty. Unique user identity must have at least one value.
@objc public init?(phones: [String]?, emails: [String]?, externalUserId: String?) {
if (phones == nil || phones!.isEmpty) && (emails == nil || emails!.isEmpty) && externalUserId == nil {
return nil
}
self.phones = phones
self.emails = emails
self.externalUserId = externalUserId
}
}
@objcMembers public class MMUserAttributes: NSObject, DictionaryRepresentable {
/// The user's first name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var firstName: String?
/// A user's middle name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var middleName: String?
/// A user's last name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var lastName: String?
/// A user's tags. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var tags: Set<String>?
/// A user's gender. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var gender: MMGender?
public var genderNonnull: MMGenderNonnull {
set { gender = newValue.toGender }
get { return MMGenderNonnull.make(from: gender) }
}
/// A user's birthday. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var birthday: Date?
/// Returns user's custom data. Arbitrary attributes that are related to a particular user. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var customAttributes: [String: MMAttributeType]? {
willSet {
newValue?.assertCustomAttributesValid()
}
}
convenience public init(firstName: String?
,middleName: String?
,lastName: String?
,tags: Set<String>?
,genderNonnull: MMGenderNonnull
,birthday: Date?
,customAttributes: [String: MMAttributeType]?) {
self.init(firstName: firstName, middleName: middleName, lastName: lastName, tags: tags, gender: genderNonnull.toGender, birthday: birthday, customAttributes: customAttributes)
}
public init(firstName: String?
,middleName: String?
,lastName: String?
,tags: Set<String>?
,gender: MMGender?
,birthday: Date?
,customAttributes: [String: MMAttributeType]?) {
self.firstName = firstName
self.middleName = middleName
self.lastName = lastName
self.tags = tags
self.gender = gender
self.birthday = birthday
self.customAttributes = customAttributes
}
public required convenience init?(dictRepresentation dict: DictionaryRepresentation) {
let value = JSON.init(dict)
self.init(firstName: value["firstName"].string,
middleName: value["middleName"].string,
lastName: value["lastName"].string,
tags: arrayToSet(arr: value["tags"].arrayObject as? [String]),
gender: value["gender"].string.ifSome({ MMGender.make(with: $0) }),
birthday: value["birthday"].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }),
customAttributes: value["customAttributes"].dictionary?.decodeCustomAttributesJSON)
}
public var dictionaryRepresentation: DictionaryRepresentation {
return [
"firstName" : firstName as Any,
"middleName" : middleName as Any,
"lastName" : lastName as Any,
"tags" : tags?.asArray as Any,
"gender" : gender?.name as Any,
"birthday" : birthday.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.string(from: $0) }) as Any,
"customAttributes" : UserDataMapper.makeCustomAttributesPayload(customAttributes) as Any
]
}
}
@objcMembers public final class MMUser: MMUserAttributes, JSONDecodable, NSCoding, NSCopying, Archivable {
var version: Int = 0
static var currentPath = getDocumentsDirectory(filename: "user")
static var dirtyPath = getDocumentsDirectory(filename: "dirty-user")
static var cached = ThreadSafeDict<MMUser>()
static var empty: MMUser {
return MMUser(externalUserId: nil, firstName: nil, middleName: nil, lastName: nil, phones: nil, emails: nil, tags: nil, gender: nil, birthday: nil, customAttributes: nil, installations: nil)
}
func removeSensitiveData() {
if MobileMessaging.privacySettings.userDataPersistingDisabled == true {
self.firstName = nil
self.middleName = nil
self.lastName = nil
self.gender = nil
self.emails = nil
self.phones = nil
self.customAttributes = nil
self.birthday = nil
self.externalUserId = nil
}
}
func handleCurrentChanges(old: MMUser, new: MMUser) {
// nothing to do
}
func handleDirtyChanges(old: MMUser, new: MMUser) {
// nothing to do
}
//
static var delta: [String: Any]? {
guard let currentUserDict = MobileMessaging.sharedInstance?.currentUser().dictionaryRepresentation, let dirtyUserDict = MobileMessaging.sharedInstance?.dirtyUser().dictionaryRepresentation else {
return [:]
}
return deltaDict(currentUserDict, dirtyUserDict)
}
/// The user's id you can provide in order to link your own unique user identifier with Mobile Messaging user id, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var externalUserId: String?
/// User's phone numbers. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var phones: Array<String>? {
set {
phonesObjects = newValue?.map({ return MMPhone(number: $0, preferred: false) })
}
get {
return phonesObjects?.map({ return $0.number })
}
}
var phonesObjects: Array<MMPhone>?
/// User's email addresses. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var emails: Array<String>? {
set {
emailsObjects = newValue?.map({ return MMEmail(address: $0, preferred: false) })
}
get {
return emailsObjects?.map({ return $0.address })
}
}
var emailsObjects: Array<MMEmail>?
/// All installations personalized with the user
public internal(set) var installations: Array<MMInstallation>?
convenience init(userIdentity: MMUserIdentity, userAttributes: MMUserAttributes?) {
self.init(externalUserId: userIdentity.externalUserId, firstName: userAttributes?.firstName, middleName: userAttributes?.middleName, lastName: userAttributes?.lastName, phones: userIdentity.phones, emails: userIdentity.emails, tags: userAttributes?.tags, gender: userAttributes?.gender, birthday: userAttributes?.birthday, customAttributes: userAttributes?.customAttributes, installations: nil)
}
init(externalUserId: String?
,firstName: String?
,middleName: String?
,lastName: String?
,phones: Array<String>?
,emails: Array<String>?
,tags: Set<String>?
,gender: MMGender?
,birthday: Date?
,customAttributes: [String: MMAttributeType]?
,installations: Array<MMInstallation>?) {
super.init(firstName: firstName, middleName: middleName, lastName: lastName, tags: tags, gender: gender, birthday: birthday, customAttributes: customAttributes)
self.installations = installations
self.externalUserId = externalUserId
self.phones = phones
self.emails = emails
}
convenience init?(json value: JSON) {
self.init(externalUserId: value[Attributes.externalUserId.rawValue].string,
firstName: value[Attributes.firstName.rawValue].string,
middleName: value[Attributes.middleName.rawValue].string,
lastName: value[Attributes.lastName.rawValue].string,
phones: value[Attributes.phones.rawValue].array?.compactMap({ return MMPhone(json: $0)?.number }),
emails: value[Attributes.emails.rawValue].array?.compactMap({ return MMEmail(json: $0)?.address }),
tags: arrayToSet(arr: value[Attributes.tags.rawValue].arrayObject as? [String]),
gender: value[Attributes.gender.rawValue].string.ifSome({ MMGender.make(with: $0) }),
birthday: value[Attributes.birthday.rawValue].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }),
customAttributes: value[Attributes.customAttributes.rawValue].dictionary?.decodeCustomAttributesJSON,
installations: value[Attributes.instances.rawValue].array?.compactMap({ MMInstallation(json: $0) }))
}
// must be extracted to cordova plugin srcs
public required convenience init?(dictRepresentation dict: DictionaryRepresentation) {
let value = JSON.init(dict)
self.init(externalUserId: value["externalUserId"].string,
firstName: value["firstName"].string,
middleName: value["middleName"].string,
lastName: value["lastName"].string,
phones: (value["phones"].arrayObject as? [String])?.compactMap({ return MMPhone(number: $0, preferred: false).number }),
emails: (value["emails"].arrayObject as? [String])?.compactMap({ return MMEmail(address: $0, preferred: false).address }),
tags: arrayToSet(arr: value["tags"].arrayObject as? [String]),
gender: value["gender"].string.ifSome({ MMGender.make(with: $0) }),
birthday: value["birthday"].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }),
customAttributes: value["customAttributes"].dictionary?.decodeCustomAttributesJSON,
installations: value["installations"].array?.compactMap({ MMInstallation(json: $0) }))
}
public override var dictionaryRepresentation: DictionaryRepresentation {
var ret = super.dictionaryRepresentation
ret["externalUserId"] = externalUserId as Any
ret["phones"] = phones as Any
ret["emails"] = emails as Any
ret["installations"] = installations?.map({ return $0.dictionaryRepresentation }) as Any
return ret
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MMUser else {
return false
}
return externalUserId == object.externalUserId &&
firstName == object.firstName &&
middleName == object.middleName &&
lastName == object.lastName &&
phones == object.phones &&
emails == object.emails &&
tags == object.tags &&
gender == object.gender &&
contactsServiceDateEqual(birthday, object.birthday) &&
customAttributes == object.customAttributes &&
installations == object.installations
}
required public init?(coder aDecoder: NSCoder) {
super.init(firstName: aDecoder.decodeObject(forKey: "firstName") as? String,
middleName: aDecoder.decodeObject(forKey: "middleName") as? String,
lastName: aDecoder.decodeObject(forKey: "lastName") as? String,
tags: arrayToSet(arr: aDecoder.decodeObject(forKey: "tags") as? [String]),
gender: MMGender(rawValue: (aDecoder.decodeObject(forKey: "gender") as? Int) ?? 999) ,
birthday: aDecoder.decodeObject(forKey: "birthday") as? Date,
customAttributes: aDecoder.decodeObject(forKey: "customAttributes") as? [String: MMAttributeType])
externalUserId = aDecoder.decodeObject(forKey: "externalUserId") as? String
phonesObjects = aDecoder.decodeObject(forKey: "phones") as? Array<MMPhone>
emailsObjects = aDecoder.decodeObject(forKey: "emails") as? Array<MMEmail>
installations = aDecoder.decodeObject(forKey: "installations") as? Array<MMInstallation>
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(externalUserId, forKey: "externalUserId")
aCoder.encode(firstName, forKey: "firstName")
aCoder.encode(middleName, forKey: "middleName")
aCoder.encode(lastName, forKey: "lastName")
aCoder.encode(phonesObjects, forKey: "phones")
aCoder.encode(emailsObjects, forKey: "emails")
aCoder.encode(tags, forKey: "tags")
aCoder.encode(gender?.rawValue, forKey: "gender")
aCoder.encode(birthday, forKey: "birthday")
aCoder.encode(customAttributes, forKey: "customAttributes")
aCoder.encode(installations, forKey: "installations")
}
public func copy(with zone: NSZone? = nil) -> Any {
return MMUser(externalUserId: externalUserId, firstName: firstName, middleName: middleName, lastName: lastName, phones: phones, emails: emails, tags: tags, gender: gender, birthday: birthday, customAttributes: customAttributes, installations: installations)
}
}
| b2d797a0314e358c5f4724a24c5a7179 | 37.74359 | 396 | 0.7372 | false | false | false | false |
mahabaleshwarhnr/GitHub-challenges---iOS | refs/heads/master | GithubApiDemo/GithubApiDemo/Tasks/HttpTasksHandler.swift | mit | 1 | //
// HttpTasksHandler.swift
// GithubApiDemo
//
// Created by Mahabaleshwar on 23/08/16.
// Copyright © 2016 DP Samant. All rights reserved.
//
import Foundation
import UIKit
class HttpTasksHandler {
typealias CompletionHandler = (reponseData: NSData?, response: NSURLResponse?, error: NSError?) -> Void
var completionHandler: CompletionHandler?
var taskType: HttpTaskType = .None
var dataTask: NSURLSessionDataTask?
private var hostUrl: String?
let defaultSession: NSURLSession
//MARK:- Initialization
init?() {
defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
}
func sendGetRequest(taskType: HttpTaskType,info:[String: AnyObject]?, completionHandler:CompletionHandler) -> Void {
self.completionHandler = completionHandler
switch taskType {
case .DownloadRepositories:
let language = (info!["langauage"] as! String).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
self.hostUrl = UrlBuilder.getRepositoriesUrl(language!)
downloadRepositoriesList(language!, completionHandler: completionHandler)
break
default:
break
}
}
////MARK:- Helper Methods
func downloadRepositoriesList(langauage: String, completionHandler: CompletionHandler) -> Void {
let serviceUrl = NSURL(string: self.hostUrl!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.dataTask = self.defaultSession.dataTaskWithURL(serviceUrl!, completionHandler: { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
//completionHandler(reponseData: data!, response: response!, error: error!)
self.completionHandler!(reponseData: data, response: response, error: error)
}
})
dataTask?.resume()
}
}
| 6227e6717f9b128cf39672fee0c801fc | 32.166667 | 155 | 0.656007 | false | false | false | false |
DRybochkin/Spika.swift | refs/heads/master | Spika/Views/ImagePreviewView/CSImagePreviewView.swift | mit | 1 | //
// ImagePreviewView.h
// Prototype
//
// Created by Dmitry Rybochkin on 25.02.17.
// Copyright (c) 2015 Clover Studio. All rights reserved.
//
import UIKit
class CSImagePreviewView: CSBasePreviewView {
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var backGroundView: UIView!
@IBOutlet weak var localImage: UIImageView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
@IBAction func onClose(_ sender: Any) {
dismiss()
}
override func initializeView(message: CSMessageModel!, size: Float, dismiss: dismissPreview!) {
self.dismiss = dismiss
var viewRect: CGRect = UIScreen.main.bounds
viewRect.size.height = viewRect.size.height - CGFloat(size)
var className: String = String(describing: type(of: self))
className = className.replacingOccurrences(of: Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as! String, with: "")
className = className.replacingOccurrences(of: ".", with: "")
let path: String! = Bundle.main.path(forResource: className, ofType: "nib")
if (!FileManager.default.fileExists(atPath: path)) {
return
}
var array: [Any]! = Bundle.main.loadNibNamed(className, owner: self, options: nil)
assert(array.count == 1, "Invalid number of nibs")
frame = viewRect
let backGR: UIView! = array[0] as! UIView
backGR?.frame = viewRect
addSubview(backGR)
closeButton.layer.cornerRadius = closeButton.frame.size.width / 2
closeButton.layer.masksToBounds = true
closeButton.backgroundColor = kAppDefaultColor(0.8)
backGroundView.layer.cornerRadius = 10
backGroundView.layer.masksToBounds = true
setImage(message: message)
}
func setImage(path: String) {
localImage.image = UIImage(contentsOfFile: path)
localImage.contentMode = .scaleAspectFit
loadingIndicator.stopAnimating()
loadingIndicator.isHidden = true
}
func setImage(message: CSMessageModel) {
localImage.layer.cornerRadius = 8
localImage.layer.masksToBounds = true
if (message.file.thumb != nil) {
localImage.sd_setImage(with: URL(string: CSUtils.generateDownloadURLFormFileId(message.file.thumb.id)))
} else if (message.file.file != nil) {
localImage.sd_setImage(with: URL(string: CSUtils.generateDownloadURLFormFileId(message.file.file.id)))
}
}
}
| 0b7384ae18389fe643a8227144428a85 | 39.290323 | 139 | 0.672538 | false | false | false | false |
BitBaum/Swift-Big-Integer | refs/heads/master | Tests/BIntTests.swift | mit | 1 | //
// BInt.swift
// BigNumberTests
//
// Created by Zachary Gorak on 3/2/18.
// Copyright © 2018 Marcel Kröker. All rights reserved.
//
import XCTest
class BIntTests: 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 testRadixInitializerAndGetter()
{
let chars: [Character] = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
"y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
]
for _ in 0..<1000
{
let fromBase = math.random(2...62)
let toBase = math.random(2...62)
let numLength = math.random(1...10)
var num = math.random(0...1) == 1 ? "-" : ""
for i in 0..<numLength
{
if i == 0
{
num.append(chars[math.random(1..<fromBase)])
}
else
{
num.append(chars[math.random(0..<fromBase)])
}
}
// Convert the random number to a BInt type
let b1 = BInt(num, radix: fromBase)
// Get the number as a string with the second base
let s1 = b1!.asString(radix: toBase)
// Convert that number to a BInt type
let b2 = BInt(s1, radix: toBase)
// Get the number back as as string in the start base
let s2 = b2!.asString(radix: fromBase)
XCTAssert(b1 == b2)
XCTAssert(s2 == num)
}
let bigHex = "abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef00"
let x = BInt(bigHex, radix: 16)!
XCTAssert(x.asString(radix: 16) == bigHex)
}
func testRadix() {
XCTAssert(BInt("ffff",radix:16) == 65535)
XCTAssert(BInt("ff",radix:16) == 255.0)
XCTAssert(BInt("ff",radix:16) != 100.0)
XCTAssert(BInt("ffff",radix:16)! > 255.0)
XCTAssert(BInt("f",radix:16)! < 255.0)
XCTAssert(BInt("0",radix:16)! <= 1.0)
XCTAssert(BInt("f", radix: 16)! >= 1.0)
XCTAssert(BInt("rfff",radix:16) == nil)
XCTAssert(BInt("ffff",radix:16) == 65535)
XCTAssert(BInt("rfff",radix:16) == nil)
XCTAssert(BInt("ff",radix:10) == nil)
XCTAssert(BInt("255",radix:6) == 107)
XCTAssert(BInt("999",radix:10) == 999)
XCTAssert(BInt("ff",radix:16) == 255.0)
XCTAssert(BInt("ff",radix:16) != 100.0)
XCTAssert(BInt("ffff",radix:16)! > 255.0)
XCTAssert(BInt("f",radix:16)! < 255.0)
XCTAssert(BInt("0",radix:16)! <= 1.0)
XCTAssert(BInt("f",radix:16)! >= 1.0)
XCTAssert(BInt("44",radix:5) == 24)
XCTAssert(BInt("44",radix:5) != 100.0)
XCTAssert(BInt("321",radix:5)! == 86)
XCTAssert(BInt("3",radix:5)! < 255.0)
XCTAssert(BInt("0",radix:5)! <= 1.0)
XCTAssert(BInt("4",radix:5)! >= 1.0)
XCTAssert(BInt("923492349",radix:32)! == 9967689075849)
}
func testPerformanceStringInit() {
self.measure {
for _ in (0...15000) {
let _ = BInt(String(arc4random()))
}
}
}
func testPerformanceStringRadixInit() {
self.measure {
for _ in (0...15000) {
let _ = BInt(String(arc4random()), radix: 10)
}
}
}
}
| 6b5d6b3e8172ea439b055a9742a22802 | 28.769231 | 283 | 0.59977 | false | true | false | false |
alex-vasenin/SwiftAA | refs/heads/master | Tests/SwiftAATests/TimesTests.swift | mit | 1 | //
// TimesTests.swift
// SwiftAA
//
// Created by Cédric Foellmi on 20/02/2017.
// Copyright © 2017 onekiloparsec. All rights reserved.
//
import XCTest
@testable import SwiftAA
class TimesTests: XCTestCase {
func testHourMinusSignConstructor() {
XCTAssertEqual(Hour(.minus, 1, 7, 30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, -1, 7, 30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, 1, -7, 30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, 1, 7, -30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, -1, -7, 30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, 1, -7, -30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, -1, 7, -30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, -1, -7, -30.0).value, -1.125)
}
func testHourPlusSignConstructor() {
XCTAssertEqual(Hour(.plus, 1, 7, 30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, -1, 7, 30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, 1, -7, 30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, 1, 7, -30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, -1, -7, 30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, -1, -7, -30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, -1, 7, -30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, 1, -7, -30.0).value, 1.125)
}
func testHourMinusZeroSignConstructor() {
XCTAssertEqual(Hour(.minus, 0, 7, 30.0).value, -0.125)
XCTAssertEqual(Hour(.minus, 0, -7, 30.0).value, -0.125)
XCTAssertEqual(Hour(.minus, 0, 7, -30.0).value, -0.125)
XCTAssertEqual(Hour(.minus, 0, -7, -30.0).value, -0.125)
XCTAssertEqual(Hour(.minus, 0, 0, 90.0).value, -0.025)
XCTAssertEqual(Hour(.minus, 0, 0, -90.0).value, -0.025)
}
func testHourPlusZeroSignConstructor() {
XCTAssertEqual(Hour(.plus, 0, 7, 30.0).value, 0.125)
XCTAssertEqual(Hour(.plus, 0, -7, 30.0).value, 0.125)
XCTAssertEqual(Hour(.plus, 0, 7, -30.0).value, 0.125)
XCTAssertEqual(Hour(.plus, 0, -7, -30.0).value, 0.125)
XCTAssertEqual(Hour(.plus, 0, 0, 90.0).value, 0.025)
XCTAssertEqual(Hour(.plus, 0, 0, -90.0).value, 0.025)
}
func testHourSexagesimalTransform() {
let hplus = Hour(1.125)
let hplussexagesimal: SexagesimalNotation = (.plus, 1, 7, 30.0)
XCTAssertTrue(hplus.sexagesimal == hplussexagesimal)
let hminus = Hour(-1.125)
let hminussexagesimal: SexagesimalNotation = (.minus, 1, 7, 30.0)
XCTAssertTrue(hminus.sexagesimal == hminussexagesimal)
}
// See AATests.cpp
func testTTtoUTRoundTripping() {
let earth = Earth(julianDay: JulianDay(year: 1962, month: 1, day: 1), highPrecision: false)
let northwardEquinox = earth.equinox(of: .northwardSpring)
XCTAssertEqual(northwardEquinox.value, JulianDay(2437744.6042503607).value)
// TT
XCTAssertEqual(northwardEquinox, JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 30, second: 7.231168))
// TT -> UT
XCTAssertEqual(northwardEquinox.TTtoUTC(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 29, second: 33.112424))
// TT -> UT -> TT
XCTAssertEqual(northwardEquinox.TTtoUTC().UTCtoTT(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 30, second: 7.231168))
}
// See AATests.cpp
func testTTtoTAIRoundTripping() {
let earth = Earth(julianDay: JulianDay(year: 1962, month: 1, day: 1), highPrecision: false)
let northwardEquinox = earth.equinox(of: .northwardSpring)
XCTAssertEqual(northwardEquinox.value, JulianDay(2437744.6042503607).value)
// TT -> TAI
XCTAssertEqual(northwardEquinox.TTtoTAI(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 29, second: 35.047155))
// TT -> TAI -> TT
XCTAssertEqual(northwardEquinox.TTtoTAI().TAItoTT(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 30, second: 7.231168))
}
// See AATests.cpp
func testTTtoUT1RoundTripping() {
let earth = Earth(julianDay: JulianDay(year: 1962, month: 1, day: 1), highPrecision: false)
let northwardEquinox = earth.equinox(of: .northwardSpring)
XCTAssertEqual(northwardEquinox.value, JulianDay(2437744.6042503607).value)
// TT -> UT1
XCTAssertEqual(northwardEquinox.TTtoUT1(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 29, second: 33.140024))
// TT -> UT1 -> TT
XCTAssertEqual(northwardEquinox.TTtoUT1().UT1toTT(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 30, second: 7.231168))
}
// Based on data downloadable from http://tycho.usno.navy.mil/systime.html
func testUT1minusUTC() {
let jd1 = JulianDay(modified: 58018.0) // 2017 9 22, the day of writing this test...
AssertEqual(jd1.UT1minusUTC(), Second(0.32103), accuracy: Second(0.01))
let jd2 = JulianDay(modified: 58118.0) // 2017 12 31
// Expected value in aaplus-1.91 = 0.19553
// Expected value in aaplus-1.99 = 0.21742
AssertEqual(jd2.UT1minusUTC(), Second(0.21742), accuracy: Second(0.001))
// Not sure why the one below fails.
// let jd3 = JulianDay(modified: 58382.0) // 2018 9 21
// AssertEqual(jd3.UT1minusUTC(), Second(-0.07169), accuracy: Second(0.01))
}
func testDaysSince2000January1() {
XCTAssertEqual(JulianDay(year: 2017, month: 9, day: 23, hour: 9, minute: 0, second: 0.0).date.daysSince2000January1(), 6476)
}
func testDayConversions() {
let t1 = 3.1415
let t2 = -2.718
XCTAssertEqual(Day(t1).inHours.value, t1*24.0)
XCTAssertEqual(Day(t2).inHours.value, t2*24.0)
XCTAssertEqual(Day(t1).inMinutes.value, t1*24.0*60.0)
XCTAssertEqual(Day(t2).inMinutes.value, t2*24.0*60.0)
XCTAssertEqual(Day(t1).inSeconds.value, t1*24.0*3600.0)
XCTAssertEqual(Day(t2).inSeconds.value, t2*24.0*3600.0)
XCTAssertEqual(Day(t1).inJulianDays.value, t1)
}
func testHourConversion() {
let t1 = 3.1415
let t2 = -2.718
XCTAssertEqual(Hour(t1).inDays.value, t1/24.0)
XCTAssertEqual(Hour(t2).inDays.value, t2/24.0)
XCTAssertEqual(Hour(t1).inMinutes.value, t1*60.0)
XCTAssertEqual(Hour(t2).inMinutes.value, t2*60.0)
XCTAssertEqual(Hour(t1).inSeconds.value, t1*3600.0)
XCTAssertEqual(Hour(t2).inSeconds.value, t2*3600.0)
XCTAssertEqual(Hour(12.0).inRadians.value, .pi, accuracy: 0.00000000001) // rounding errors
XCTAssertEqual(Hour(-6.0).inRadians.value, -.pi/2.0, accuracy: 0.00000000001) // rounding errors
}
func testMinuteConversion() {
let t1 = 3.1415
let t2 = -2.718
XCTAssertEqual(Minute(t1).inDays.value, t1/(24.0*60.0))
XCTAssertEqual(Minute(t2).inDays.value, t2/(24.0*60.0))
XCTAssertEqual(Minute(t1).inHours.value, t1/60.0)
XCTAssertEqual(Minute(t2).inHours.value, t2/60.0)
XCTAssertEqual(Minute(t1).inSeconds.value, t1*60.0)
XCTAssertEqual(Minute(t2).inSeconds.value, t2*60.0)
}
func testSecondConversion() {
let t1 = 3.1415
let t2 = -2.718
XCTAssertEqual(Second(t1).inDays.value, t1/(24.0*3600.0))
XCTAssertEqual(Second(t2).inDays.value, t2/(24.0*3600.0))
XCTAssertEqual(Second(t1).inHours.value, t1/3600.0)
XCTAssertEqual(Second(t2).inHours.value, t2/3600.0)
XCTAssertEqual(Second(t1).inMinutes.value, t1/60.0)
XCTAssertEqual(Second(t2).inMinutes.value, t2/60.0)
}
func testHourReduce() {
AssertEqual(Hour(-25).reduced, Hour(23))
AssertEqual(Hour(-23).reduced, Hour(1))
AssertEqual(Hour(-13).reduced, Hour(11))
AssertEqual(Hour(-1).reduced, Hour(23))
AssertEqual(Hour(1).reduced, Hour(1))
AssertEqual(Hour(13).reduced, Hour(13))
AssertEqual(Hour(23).reduced, Hour(23))
AssertEqual(Hour(25).reduced, Hour(1))
}
func testHourReduce0() {
AssertEqual(Hour(-25).reduced0, Hour(-1))
AssertEqual(Hour(-23).reduced0, Hour(1))
AssertEqual(Hour(-13).reduced0, Hour(11))
AssertEqual(Hour(-1).reduced0, Hour(-1))
AssertEqual(Hour(1).reduced0, Hour(1))
AssertEqual(Hour(13).reduced0, Hour(-11))
AssertEqual(Hour(23).reduced0, Hour(-1))
AssertEqual(Hour(25).reduced0, Hour(1))
}
func testMinuteReduce() {
AssertEqual(Minute(-61).reduced, Minute(59))
AssertEqual(Minute(-59).reduced, Minute(1))
AssertEqual(Minute(-31).reduced, Minute(29))
AssertEqual(Minute(-1).reduced, Minute(59))
AssertEqual(Minute(1).reduced, Minute(1))
AssertEqual(Minute(31).reduced, Minute(31))
AssertEqual(Minute(59).reduced, Minute(59))
AssertEqual(Minute(61).reduced, Minute(1))
}
func testDescriptions() {
XCTAssertNotNil(String(describing: Day(3.141519)))
XCTAssertNotNil(String(describing: Hour(3.141519)))
XCTAssertNotNil(String(describing: Minute(3.141519)))
XCTAssertNotNil(String(describing: Second(3.141519)))
}
}
| 029e68907d0c41c1392ecf6706f2babb | 41.066964 | 141 | 0.615515 | false | true | false | false |
1457792186/JWSwift | refs/heads/master | SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGAssertGridViewCell.swift | apache-2.0 | 1 | //
// LGAssertGridViewCell.swift
// LGChatViewController
//
// Created by jamy on 10/22/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
class LGAssertGridViewCell: UICollectionViewCell {
let buttonWidth: CGFloat = 30
var assetIdentifier: String!
var imageView:UIImageView!
var playIndicator: UIImageView?
var selectIndicator: UIButton
var assetModel: LGAssetModel! {
didSet {
if assetModel.asset.mediaType == .video {
self.playIndicator?.isHidden = false
} else {
self.playIndicator?.isHidden = true
}
}
}
var buttonSelect: Bool {
willSet {
if newValue {
selectIndicator.isSelected = true
selectIndicator.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState())
} else {
selectIndicator.isSelected = false
selectIndicator.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
}
}
}
override init(frame: CGRect) {
selectIndicator = UIButton(type: .custom)
selectIndicator.tag = 1
buttonSelect = false
super.init(frame: frame)
imageView = UIImageView(frame: bounds)
//imageView.contentMode = .ScaleAspectFit
contentView.addSubview(imageView)
playIndicator = UIImageView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
playIndicator?.center = contentView.center
playIndicator?.image = UIImage(named: "mmplayer_idle")
contentView.addSubview(playIndicator!)
playIndicator?.isHidden = true
selectIndicator.frame = CGRect(x: bounds.width - buttonWidth , y: 0, width: buttonWidth, height: buttonWidth)
contentView.addSubview(selectIndicator)
selectIndicator.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
backgroundColor = UIColor.white
imageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: 0))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let durationTime = 0.3
func selectButton(_ button: UIButton) {
if button.tag == 1 {
button.tag = 0
let groupAnimation = CAAnimationGroup()
let animationZoomOut = CABasicAnimation(keyPath: "transform.scale")
animationZoomOut.fromValue = 0
animationZoomOut.toValue = 1.2
animationZoomOut.duration = 3/4 * durationTime
let animationZoomIn = CABasicAnimation(keyPath: "transform.scale")
animationZoomIn.fromValue = 1.2
animationZoomIn.toValue = 1.0
animationZoomIn.beginTime = 3/4 * durationTime
animationZoomIn.duration = 1/4 * durationTime
groupAnimation.animations = [animationZoomOut, animationZoomIn]
buttonSelect = true
assetModel.select = true
selectIndicator.layer.add(groupAnimation, forKey: "selectZoom")
} else {
button.tag = 1
buttonSelect = false
assetModel.select = false
}
}
}
| 3858ea2313812a6676f2a0494e994a5a | 38.544554 | 178 | 0.634201 | false | false | false | false |
wikimedia/wikipedia-ios | refs/heads/main | Wikipedia/Code/OldTalkPageReplyCell.swift | mit | 1 | import UIKit
protocol OldTalkPageReplyCellDelegate: AnyObject {
func tappedLink(_ url: URL, cell: OldTalkPageReplyCell, sourceView: UIView, sourceRect: CGRect?)
}
class OldTalkPageReplyCell: CollectionViewCell {
weak var delegate: OldTalkPageReplyCellDelegate?
private let titleTextView = UITextView()
private let depthMarker = UIView()
private var depth: UInt = 0
private var theme: Theme?
private var isDeviceRTL: Bool {
return effectiveUserInterfaceLayoutDirection == .rightToLeft
}
var semanticContentAttributeOverride: UISemanticContentAttribute = .unspecified {
didSet {
textAlignmentOverride = semanticContentAttributeOverride == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left
titleTextView.semanticContentAttribute = semanticContentAttributeOverride
}
}
private var textAlignmentOverride: NSTextAlignment = .left {
didSet {
titleTextView.textAlignment = textAlignmentOverride
}
}
override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let isRTL = semanticContentAttributeOverride == .forceRightToLeft
let adjustedMargins = UIEdgeInsets(top: layoutMargins.top, left: layoutMargins.left, bottom: 0, right: layoutMargins.right)
var depthIndicatorOrigin: CGPoint?
if depth > 0 {
var depthIndicatorX = isRTL ? size.width - adjustedMargins.right : adjustedMargins.left
let depthAdjustmentMultiplier = CGFloat(13) // todo: may want to shift this higher or lower depending on screen size. Also possibly give it a max value
if isRTL {
depthIndicatorX -= (CGFloat(depth) - 1) * depthAdjustmentMultiplier
} else {
depthIndicatorX += (CGFloat(depth) - 1) * depthAdjustmentMultiplier
}
depthIndicatorOrigin = CGPoint(x: depthIndicatorX, y: adjustedMargins.top)
}
var titleX: CGFloat
if isRTL {
titleX = adjustedMargins.left
} else {
titleX = depthIndicatorOrigin == nil ? adjustedMargins.left : depthIndicatorOrigin!.x + 10
}
let titleOrigin = CGPoint(x: titleX, y: adjustedMargins.top)
var titleMaximumWidth: CGFloat
if isRTL {
titleMaximumWidth = depthIndicatorOrigin == nil ? size.width - adjustedMargins.right - titleOrigin.x : depthIndicatorOrigin!.x - adjustedMargins.left
} else {
titleMaximumWidth = (size.width - adjustedMargins.right) - titleOrigin.x
}
let titleTextViewFrame = titleTextView.wmf_preferredFrame(at: titleOrigin, maximumWidth: titleMaximumWidth, alignedBy: semanticContentAttributeOverride, apply: apply)
let finalHeight = adjustedMargins.top + titleTextViewFrame.size.height + adjustedMargins.bottom
if let depthIndicatorOrigin = depthIndicatorOrigin,
apply {
depthMarker.frame = CGRect(origin: depthIndicatorOrigin, size: CGSize(width: 2, height: titleTextViewFrame.height))
}
if apply {
titleTextView.textAlignment = textAlignmentOverride
}
return CGSize(width: size.width, height: finalHeight)
}
func configure(title: String, depth: UInt) {
self.depth = depth
depthMarker.isHidden = depth < 1
let attributedString = title.byAttributingHTML(with: .body, boldWeight: .semibold, matching: traitCollection, color: titleTextView.textColor, linkColor: theme?.colors.link, handlingLists: true, handlingSuperSubscripts: true)
setupTitle(for: attributedString)
setNeedsLayout()
}
override func reset() {
super.reset()
titleTextView.attributedText = nil
depth = 0
depthMarker.isHidden = true
depthMarker.frame = .zero
}
private func setupTitle(for attributedText: NSAttributedString) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 7
let attrString = NSMutableAttributedString(attributedString: attributedText)
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSRange(location: 0, length: attrString.length))
titleTextView.attributedText = attrString
}
override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
setupTitle(for: titleTextView.attributedText)
}
override func setup() {
titleTextView.isEditable = false
titleTextView.isScrollEnabled = false
titleTextView.delegate = self
contentView.addSubview(titleTextView)
contentView.addSubview(depthMarker)
super.setup()
}
}
// MARK: Themeable
extension OldTalkPageReplyCell: Themeable {
func apply(theme: Theme) {
self.theme = theme
titleTextView.textColor = theme.colors.primaryText
titleTextView.backgroundColor = theme.colors.paperBackground
depthMarker.backgroundColor = theme.colors.depthMarker
contentView.backgroundColor = theme.colors.paperBackground
}
}
// MARK: UITextViewDelegate
extension OldTalkPageReplyCell: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
delegate?.tappedLink(URL, cell: self, sourceView: textView, sourceRect: textView.frame(of: characterRange))
return false
}
}
| 5b74e7ea0b32d82cf8da4ed3ed4d4be1 | 39 | 232 | 0.677289 | false | false | false | false |
neilpa/Termios | refs/heads/master | Termios/Termios.swift | mit | 1 | //
// Termios.swift
// Termios
//
// Created by Neil Pankey on 3/20/15.
// Copyright (c) 2015 Neil Pankey. All rights reserved.
//
import Darwin.POSIX.termios
import ErrNo
import Result
/// Swift wrapper around the raw C `termios` structure.
public struct Termios {
// MARK: Constructors
/// Constructs an empty `Termios` structure.
public init() {
self.init(termios())
}
/// Constructs a `Termios` structure from a given file descriptor `fd`.
public static func fetch(fd: Int32) -> Result<Termios, ErrNo> {
var raw = termios()
return tryMap(tcgetattr(fd, &raw)) { _ in Termios(raw) }
}
// MARK: Properties
/// Input flags
public var inputFlags: InputFlags {
get { return InputFlags(raw.c_iflag) }
set { raw.c_iflag = newValue.rawValue }
}
/// Output flags
public var outputFlags: OutputFlags {
get { return OutputFlags(raw.c_oflag) }
set { raw.c_oflag = newValue.rawValue }
}
/// Control flags
public var controlFlags: ControlFlags {
get { return ControlFlags(raw.c_cflag) }
set { raw.c_cflag = newValue.rawValue }
}
/// Local flags
public var localFlags: LocalFlags {
get { return LocalFlags(raw.c_lflag) }
set { raw.c_lflag = newValue.rawValue }
}
/// Input speed
public var inputSpeed: UInt {
return raw.c_ispeed
}
/// Output speed
public var outputSpeed: UInt {
return raw.c_ispeed
}
// MARK: Operations
/// Updates the file descriptor's `Termios` structure.
public mutating func update(fd: Int32) -> Result<(), ErrNo> {
return try(tcsetattr(fd, TCSANOW, &raw))
}
/// Set the input speed.
public mutating func setInputSpeed(baud: UInt) -> Result<(), ErrNo> {
return try(cfsetispeed(&raw, baud))
}
/// Set the output speed.
public mutating func setOutputSpeed(baud: UInt) -> Result<(), ErrNo> {
return try(cfsetospeed(&raw, baud))
}
/// Set both input and output speed.
public mutating func setSpeed(baud: UInt) -> Result<(), ErrNo> {
return try(cfsetspeed(&raw, baud))
}
// MARK: Private
/// Wraps the `termios` structure.
private init(_ termios: Darwin.termios) {
raw = termios
}
/// The wrapped termios struct.
private var raw: termios
}
| d9e0388601941c34f2ad979453137415 | 24.178947 | 75 | 0.60786 | false | false | false | false |
Davidde94/StemCode_iOS | refs/heads/master | StemCode/Siri/CreateNoteIntentHandler.swift | mit | 1 | //
// CreateNoteIntentHandler.swift
// Siri
//
// Created by David Evans on 06/09/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import Foundation
import Intents
import StemProjectKit
class CreateNoteIntentHandler: NSObject, INCreateNoteIntentHandling {
func resolveTitle(for intent: INCreateNoteIntent, with completion: @escaping (INSpeakableStringResolutionResult) -> Void) {
let result: INSpeakableStringResolutionResult
if let title = intent.title {
result = INSpeakableStringResolutionResult.success(with: title)
} else {
result = INSpeakableStringResolutionResult.needsValue()
}
completion(result)
}
func handle(intent: INCreateNoteIntent, completion: @escaping (INCreateNoteIntentResponse) -> Void) {
// guard let title = intent.title else {
// let response = INCreateNoteIntentResponse(code: .failure, userActivity: nil)
// completion(response)
// return
// }
//
// let project = Stem(name: title.spokenPhrase, image: nil)
// StemManager.shared.saveProject(project, isNew: true)
//
// let projectImage = INImage(imageData: project.image.pngData()!)
// let filesModifier = project.files.count == 1 ? "file" : "files"
// let projectInfo = "Empty Project - \(project.files.count) \(filesModifier)"
//
// let contents = [
// INImageNoteContent(image: projectImage),
// INTextNoteContent(text: projectInfo)
// ]
// let createdNote = INNote(title: title, contents: contents, groupName: nil, createdDateComponents: nil, modifiedDateComponents: nil, identifier: project.identifier)
// let response = INCreateNoteIntentResponse(code: .success, userActivity: nil)
// response.createdNote = createdNote
// completion(response)
}
}
| c8d8c2ddb5edf4ad5c25de7208d90f58 | 31.132075 | 167 | 0.739871 | false | false | false | false |
exponent/exponent | refs/heads/master | apps/bare-expo/ios/BareExpo/AppDelegate.swift | bsd-3-clause | 2 | //
// AppDelegate.swift
// BareExpo
//
// Created by the Expo team on 5/27/20.
// Copyright © 2020 Expo. All rights reserved.
//
import Foundation
import ExpoModulesCore
import EXDevMenuInterface
#if EX_DEV_MENU_ENABLED
import EXDevMenu
#endif
#if FB_SONARKIT_ENABLED && canImport(FlipperKit)
import FlipperKit
#endif
@UIApplicationMain
class AppDelegate: ExpoAppDelegate, RCTBridgeDelegate, EXDevLauncherControllerDelegate {
var bridge: RCTBridge?
var launchOptions: [UIApplication.LaunchOptionsKey: Any]?
let useDevClient: Bool = false
override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
initializeFlipper(with: application)
window = UIWindow(frame: UIScreen.main.bounds)
self.launchOptions = launchOptions;
if (useDevClient) {
let controller = EXDevLauncherController.sharedInstance()
controller.start(with: window!, delegate: self, launchOptions: launchOptions);
} else {
initializeReactNativeBridge(launchOptions);
}
super.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
@discardableResult
func initializeReactNativeBridge(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> RCTBridge {
let bridge = reactDelegate.createBridge(delegate: self, launchOptions: launchOptions)
let rootView = reactDelegate.createRootView(bridge: bridge, moduleName: "main", initialProperties: nil)
let rootViewController = reactDelegate.createRootViewController()
rootView.backgroundColor = UIColor.white
rootViewController.view = rootView
window?.rootViewController = rootViewController
window?.makeKeyAndVisible()
self.bridge = bridge
return bridge
}
#if RCT_DEV
func bridge(_ bridge: RCTBridge!, didNotFindModule moduleName: String!) -> Bool {
return true
}
#endif
override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if (useDevClient && EXDevLauncherController.sharedInstance().onDeepLink(url, options: options)) {
return true;
}
return RCTLinkingManager.application(app, open: url, options: options)
}
private func initializeFlipper(with application: UIApplication) {
#if FB_SONARKIT_ENABLED && canImport(FlipperKit)
let client = FlipperClient.shared()
let layoutDescriptorMapper = SKDescriptorMapper(defaults: ())
client?.add(FlipperKitLayoutPlugin(rootNode: application, with: layoutDescriptorMapper!))
client?.add(FKUserDefaultsPlugin(suiteName: nil))
client?.add(FlipperKitReactPlugin())
client?.add(FlipperKitNetworkPlugin(networkAdapter: SKIOSNetworkAdapter()))
client?.start()
#endif
}
// MARK: - RCTBridgeDelegate
func sourceURL(for bridge: RCTBridge!) -> URL! {
// DEBUG must be setup in Swift projects: https://stackoverflow.com/a/24112024/4047926
#if DEBUG
if (useDevClient) {
return EXDevLauncherController.sharedInstance().sourceUrl()
} else {
return RCTBundleURLProvider.sharedSettings()?.jsBundleURL(forBundleRoot: "index", fallbackResource: nil)
}
#else
return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
func extraModules(for bridge: RCTBridge!) -> [RCTBridgeModule] {
var extraModules = [RCTBridgeModule]()
// You can inject any extra modules that you would like here, more information at:
// https://facebook.github.io/react-native/docs/native-modules-ios.html#dependency-injection
return extraModules
}
// MARK: - EXDevelopmentClientControllerDelegate
func devLauncherController(_ developmentClientController: EXDevLauncherController, didStartWithSuccess success: Bool) {
developmentClientController.appBridge = initializeReactNativeBridge(developmentClientController.getLaunchOptions())
}
}
| f0d7cb40b33e013b189d2a97450fab41 | 34.196429 | 152 | 0.746068 | false | false | false | false |
Plotac/DouYu | refs/heads/master | DouYu/DouYu/Classes/Main/View/PageTitleView.swift | apache-2.0 | 2 | //
// PageTitleView.swift
// DouYu
//
// Created by Plo on 2017/6/14.
// Copyright © 2017年 Plo. All rights reserved.
//
import UIKit
//Mark: - 定义常量
private let kScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85)
private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0)
//Mark: - 定义协议
protocol PageTitleViewDelegate : class{
func pagetTitleView(titleView: PageTitleView,selectIndex: Int)
}
//Mark: - 定义PageTitleView类
class PageTitleView : UIView {
//定义属性
//标题数组
fileprivate var titles : [String]
fileprivate var currentIndex : Int = 0
weak var delegate : PageTitleViewDelegate?
//懒加载属性
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
//滚动视图
fileprivate lazy var scrollView : UIScrollView = {
let scroll = UIScrollView()
scroll.showsHorizontalScrollIndicator = false
scroll.scrollsToTop = false
scroll.bounces = false
return scroll
}()
//滑块
fileprivate lazy var scrollLine : UIView = {
let line = UIView()
line.backgroundColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
return line
}()
// Mark: - 自定义构造函数
init(frame: CGRect , titles: [String]) {
self.titles = titles;
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//Mark: - 设置UI
extension PageTitleView {
fileprivate func setUpUI() {
//添加ScrollView
addSubview(scrollView)
scrollView.frame = bounds
//创建label
setUpTitleLabels()
//创建滑块和底线
setUpBottomLineAndScrollLine()
}
private func setUpTitleLabels() {
let labelW : CGFloat = frame.width/CGFloat(self.titles.count)
let labelH : CGFloat = frame.height - kScrollLineH
let labelY : CGFloat = 0.0
for (index,title) in self.titles.enumerated() {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.tag = index
label.text = title
label.isUserInteractionEnabled = true
let labelX = CGFloat(index) * labelW
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titleLabels.append(label)
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.labelClick(tap:)))
label.addGestureRecognizer(tapGes)
}
}
private func setUpBottomLineAndScrollLine() {
//底部横线
let bottomLine = UIView()
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height-lineH, width: frame.size.width, height: lineH)
bottomLine.backgroundColor = UIColor.lightGray
addSubview(bottomLine)
//滑块
scrollView.addSubview(scrollLine)
guard let firstLabel = titleLabels.first else { return }
firstLabel.textColor = UIColor.orange
scrollLine.frame = CGRect(x: 10, y: frame.height-kScrollLineH, width: firstLabel.frame.width-10*2, height: kScrollLineH)
}
}
//Mark: - 监听label点击事件
extension PageTitleView {
@objc fileprivate func labelClick(tap : UITapGestureRecognizer) {
//1.拿到点击之后的当前label
guard let currentLabel = tap.view as? UILabel else {
return
}
if currentIndex == currentLabel.tag {
delegate?.pagetTitleView(titleView: self, selectIndex: currentIndex)
return
}
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
//2.点击之前的旧label
let oldLabel = titleLabels[currentIndex]
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
currentIndex = currentLabel.tag
//3.滑块位置改变
let linePositionX = currentLabel.frame.width * CGFloat(currentLabel.tag) + 10
UIView.animate(withDuration: 0.15) {
self.scrollLine.frame.origin.x = linePositionX
}
delegate?.pagetTitleView(titleView: self, selectIndex: currentIndex)
}
}
//Mark: - 对外暴露的方法
extension PageTitleView {
func setTitlesWith(progress: CGFloat,sourceIndex: Int,targetIndex: Int) {
//取出sourceLabel和targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
//滑块渐变
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + 10 + moveX
//颜色渐变
//1.颜色变化的总范围
let colorRange = (kSelectColor.0 - kNormalColor.0,kSelectColor.1 - kNormalColor.1,kSelectColor.2 - kNormalColor.2)
//2.变化sourceLabel颜色
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorRange.0 * progress, g: kSelectColor.1 - colorRange.1 * progress, b: kSelectColor.2 - colorRange.2 * progress)
//3.变化targetLabel颜色
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorRange.0 * progress, g: kNormalColor.1 + colorRange.1 * progress, b: kNormalColor.2 + colorRange.2 * progress)
//4.记录最新的Index
currentIndex = targetIndex
}
}
| 52923860439b5f021f3539bad106c1ba | 30.005405 | 174 | 0.613842 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | refs/heads/master | Parse Dashboard for iOS/Views/CollectionViewCells/ActionSheetCell.swift | mit | 1 | //
// ActionSheetCell.swift
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 11/7/17.
//
import IGListKit
import UIKit
final class ActionSheetCell: UICollectionViewCell {
// MARK: - Properties
var image: UIImage? {
didSet {
imageView.image = image?.withRenderingMode(.alwaysTemplate)
}
}
var title: String? {
didSet {
textLabel.text = title
}
}
var style: UIAlertActionStyle = .default {
didSet {
switch style {
case .default, .cancel:
textLabel.textColor = .black
imageView.tintColor = .darkGray
contentView.backgroundColor = .white
rippleColor = UIColor.white.darker()
case .destructive:
textLabel.textColor = .white
imageView.tintColor = .white
contentView.backgroundColor = .red
rippleColor = UIColor.red.darker()
}
}
}
var ripplePercent: Float = 0.8 {
didSet {
setupRippleView()
}
}
var rippleColor: UIColor = UIColor(white: 0.9, alpha: 1) {
didSet {
rippleView.backgroundColor = rippleColor
}
}
var rippleBackgroundColor: UIColor {
get {
return rippleBackgroundView.backgroundColor ?? .clear
}
set {
rippleBackgroundView.backgroundColor = newValue
}
}
var rippleOverBounds: Bool = false
var shadowRippleRadius: Float = 1
var shadowRippleEnable: Bool = false
var trackTouchLocation: Bool = true
var touchUpAnimationTime: Double = 0.3
let rippleView = UIView()
let rippleBackgroundView = UIView()
fileprivate var tempShadowRadius: CGFloat = 0
fileprivate var tempShadowOpacity: Float = 0
fileprivate var touchCenterLocation: CGPoint?
fileprivate var rippleMask: CAShapeLayer? {
get {
if !rippleOverBounds {
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds,
cornerRadius: layer.cornerRadius).cgPath
return maskLayer
} else {
return nil
}
}
}
// MARK: - Subviews
private let imageView: UIImageView = {
let view = UIImageView()
view.contentMode = .scaleAspectFit
view.tintColor = .darkGray
return view
}()
private let textLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
label.adjustsFontSizeToFitWidth = true
return label
}()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(textLabel)
contentView.addSubview(imageView)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
let bounds = contentView.bounds
let insets = UIEdgeInsets(top: 2, left: 16, bottom: 2, right: 16)
if image == nil {
textLabel.frame = UIEdgeInsetsInsetRect(bounds, insets)
imageView.frame = .zero
} else {
// Layout similar to a standard UITableViewCell
let height = bounds.height - insets.top - insets.bottom
let imageViewOrigin = CGPoint(x: insets.left, y: insets.top + 8)
let imageViewSize = CGSize(width: height - 16, height: height - 16)
imageView.frame = CGRect(origin: imageViewOrigin, size: imageViewSize)
let textLabelOrigin = CGPoint(x: imageViewOrigin.x + imageViewSize.width + 24,
y: insets.top)
let textLabelSize = CGSize(width: bounds.width - insets.right - imageViewOrigin.x - imageViewSize.width - 16,
height: height)
textLabel.frame = CGRect(origin: textLabelOrigin, size: textLabelSize)
}
setupRippleView()
if let knownTouchCenterLocation = touchCenterLocation {
rippleView.center = knownTouchCenterLocation
}
rippleBackgroundView.layer.frame = bounds
rippleBackgroundView.layer.mask = rippleMask
}
// MARK: - Selection Animation
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if trackTouchLocation {
rippleView.center = touches.first?.location(in: self) ?? contentView.center
} else {
rippleView.center = contentView.center
}
UIView.animate(withDuration: 0.1, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 1
}, completion: nil)
rippleView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.7, delay: 0, options: [UIViewAnimationOptions.curveEaseOut, UIViewAnimationOptions.allowUserInteraction],
animations: {
self.rippleView.transform = CGAffineTransform.identity
}, completion: nil)
if shadowRippleEnable {
tempShadowRadius = layer.shadowRadius
tempShadowOpacity = layer.shadowOpacity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = shadowRippleRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = 1
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.isRemovedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
layer.add(groupAnim, forKey:"shadow")
}
return super.touchesBegan(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
animateToNormal()
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
animateToNormal()
}
fileprivate func setup() {
setupRippleView()
rippleBackgroundView.backgroundColor = rippleBackgroundColor
rippleBackgroundView.frame = bounds
rippleBackgroundView.addSubview(rippleView)
rippleBackgroundView.alpha = 0
contentView.insertSubview(rippleBackgroundView, at: 0)
layer.shadowRadius = 0
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowColor = UIColor(white: 0.0, alpha: 0.5).cgColor
}
fileprivate func setupRippleView() {
let size: CGFloat = bounds.width * CGFloat(ripplePercent)
let x: CGFloat = (bounds.width/2) - (size/2)
let y: CGFloat = (bounds.height/2) - (size/2)
let corner: CGFloat = size/2
rippleView.backgroundColor = rippleColor
rippleView.frame = CGRect(x: x, y: y, width: size, height: size)
rippleView.layer.cornerRadius = corner
}
fileprivate func animateToNormal() {
UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 1
}, completion: {(success: Bool) -> () in
UIView.animate(withDuration: self.touchUpAnimationTime, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 0
}, completion: nil)
})
UIView.animate(withDuration: 0.7, delay: 0, options: [.curveEaseOut, .beginFromCurrentState, .allowUserInteraction],
animations: {
self.rippleView.transform = CGAffineTransform.identity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = self.tempShadowRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = self.tempShadowOpacity
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.isRemovedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
self.layer.add(groupAnim, forKey:"shadowBack")
}, completion: nil)
}
}
| a93bacb2a137ce0269883c8b5c6e88f8 | 35.949458 | 145 | 0.599707 | false | false | false | false |
Harley-xk/SimpleDataKit | refs/heads/master | SimpleDataKit/Classes/SQLite.swift | mit | 1 | //
// SQLite.swift
// Comet
//
// Created by Harley.xk on 2018/1/7.
//
import Foundation
public protocol DataType {
}
extension Int: DataType{}
extension String: DataType{}
extension Double: DataType{}
extension Bool: DataType{}
extension Date: DataType{}
public struct Field<T: DataType> {
public let name: String
public let optional: Bool
public let `default`: T?
public let primary: Bool
public let unique: Bool
}
public protocol IdentifierType {
}
extension Int: IdentifierType {}
//public struct Field {
//
// public enum DataType {
// case id(type: IdentifierType)
// case int
// case string(length: Int?)
// case double
// case bool
// case bytes
// case date
// case custom(type: String)
// }
//
// var name: String
// var dataType: DataType
//}
protocol SQLiteTable {
}
class Student: SQLiteTable {
var name = ""
var age = 0
// var tableMap: [KeyPath<SQLiteTable, DataType>: String] {
//
// let id = Field.id
// let builder = builder
// try builder.field(for: \.name)
//
// return [
// \Student.name: "name"
// ]
// }
}
protocol SQLiteEncodable: Encodable {
associatedtype SQLiteColumns where SQLiteColumns: CodingKey
}
extension SQLiteEncodable {
func encode(to encoder: Encoder) throws {
// let c = encoder.container(keyedBy: SQLiteColumns.self)
}
}
struct User: SQLiteEncodable {
var id = 0
var name = ""
var age = 0
enum SQLiteColumns: String, CodingKey {
case id
case name
case age
}
}
| b4b83dbb59a90d36d89f9ca34bc12925 | 16.547368 | 64 | 0.593881 | false | false | false | false |
Raizlabs/SketchyCode | refs/heads/master | SketchyCode/Generation/Writer.swift | mit | 1 | //
// Writer.swift
// SketchyCode
//
// Created by Brian King on 10/3/17.
// Copyright © 2017 Brian King. All rights reserved.
//
import Foundation
// Writer is responsible for managing the structure of the generated output.
final class Writer {
static var indentation: String = " "
var content: String = ""
var level: Int = 0
func indent(work: () throws -> Void) throws {
level += 1
try work()
level -= 1
}
func block(appending: String = "", work: () throws -> Void) throws {
append(line: "{")
try indent(work: work)
append(line: "}\(appending)")
}
var addIndentation: Bool {
return content.count == 0 || content.last == "\n"
}
func append(line: String, addNewline: Bool = true) {
var value = ""
if addIndentation {
for _ in 0..<level {
value.append(Writer.indentation)
}
}
value.append(line)
if addNewline {
value.append("\n")
}
content.append(value)
}
}
| ab735ffa91db2b02460895f5d132f9a1 | 22.434783 | 76 | 0.540816 | false | false | false | false |
ContinuousLearning/PokemonKit | refs/heads/master | Carthage/Checkouts/PromiseKit/Categories/UIKit/UIActionSheet+Promise.swift | mit | 1 | #if !COCOAPODS
import PromiseKit
#endif
import UIKit.UIActionSheet
/**
To import the `UIActionSheet` category:
use_frameworks!
pod "PromiseKit/UIKit"
Or `UIKit` is one of the categories imported by the umbrella pod:
use_frameworks!
pod "PromiseKit"
And then in your sources:
#if !COCOAPODS
import PromiseKit
#endif
*/
extension UIActionSheet {
public func promiseInView(view: UIView) -> Promise<Int> {
let proxy = PMKActionSheetDelegate()
delegate = proxy
proxy.retainCycle = proxy
showInView(view)
if numberOfButtons == 1 && cancelButtonIndex == 0 {
NSLog("PromiseKit: An action sheet is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.")
}
return proxy.promise
}
}
private class PMKActionSheetDelegate: NSObject, UIActionSheetDelegate {
let (promise, fulfill, reject) = Promise<Int>.defer_()
var retainCycle: NSObject?
@objc func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
if buttonIndex != actionSheet.cancelButtonIndex {
fulfill(buttonIndex)
} else {
reject(NSError.cancelledError())
}
retainCycle = nil
}
}
| 6928df23d866ee5c2c585490b8c74aa9 | 27.34 | 281 | 0.685956 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | refs/heads/develop | Aztec/Classes/Processor/ShortcodeAttribute.swift | gpl-2.0 | 2 | import Foundation
public class ShortcodeAttribute: CustomReflectable {
// MARK: Value
public enum Value: Equatable, CustomReflectable {
case `nil`
case string(String)
// MARK: - Equatable
public static func == (lhs: ShortcodeAttribute.Value, rhs: ShortcodeAttribute.Value) -> Bool {
switch (lhs, rhs) {
case (.nil, .nil):
return true
case let (.string(l), .string(r)):
return l == r
default:
return false
}
}
// MARK: - CustomReflectable
public var customMirror: Mirror {
get {
switch self {
case .nil:
return Mirror(self, children: ["value": 0])
case .string(let string):
return Mirror(self, children: ["value": string])
}
}
}
}
// MARK: - Attribute definition
public let key: String
public let value: Value
// MARK: - Initializers
public init(key: String, value: Value) {
self.key = key
self.value = value
}
public init(key: String, value: String) {
self.key = key
self.value = .string(value)
}
public init(key: String) {
self.key = key
self.value = .nil
}
// MARK: - CustomReflectable
public var customMirror: Mirror {
get {
return Mirror(self, children: ["key": key, "value": value])
}
}
}
| ec7ec9e1eb8baafea4a11dc22afc0588 | 23.19403 | 102 | 0.476249 | false | false | false | false |
yasuo-/smartNews-clone | refs/heads/master | SmartNews/News2ViewController.swift | mit | 1 | //
// News2ViewController.swift
// SmartNews
//
// CNN(all) RSSのXMLデータをTableControllerに加えていく
// Created by 栗原靖 on 2017/04/03.
// Copyright © 2017年 Yasuo Kurihara. All rights reserved.
//
import UIKit
import SDWebImage
// UIViewController
// UITableViewDelegate
// UITableViewDataSource
// UIWebViewDelegate
// XMLParserDelegate
// これらのメソッドを使う宣言を行う
class News2ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate, XMLParserDelegate {
// 初期化
var urlArray = [String]()
// tableView
var tableView: UITableView = UITableView()
// 引っ張ってロード
var refreshControl: UIRefreshControl!
// webView
var webView: UIWebView = UIWebView()
// goButton
var goButton: UIButton!
// back Button
var backButton: UIButton!
// cancel Button
var cancelButton: UIButton!
// dots view
var dotsView: DotsLoader! = DotsLoader()
// parser
var parser = XMLParser()
// 両方入るもの
var totalBox = NSMutableArray()
var elements = NSMutableDictionary()
var element = String()
var titleString = NSMutableString()
var linkString = NSMutableString()
var urlString = String()
// はじめに画面が呼ばれた時に出るもの
override func viewDidLoad() {
super.viewDidLoad()
// コードでviewを作る
// 背景画像を作る
let imageView = UIImageView()
// 画面いっぱい広げる
imageView.frame = self.view.bounds
imageView.image = UIImage(named: "2.jpg")
// 画面に貼り付ける
self.view.addSubview(imageView)
// 引っ張って更新
refreshControl = UIRefreshControl()
// ローディングの色
refreshControl.tintColor = UIColor.white
// どのメソッド => 自分
//
refreshControl.addTarget(self, action: #selector(refresh), for: UIControlEvents.valueChanged)
// tableViewを作成する
tableView.delegate = self
tableView.dataSource = self
// x,y軸
// width => 自分のviewの全体の幅
// height => 自分のviewの全体の高さ - 54.0(tabの高さ分)
tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height - 54.0)
// 背景をクリアにすると画像が透けて見える (デフォルトは白)
// tableView.backgroundColor = UIColor.clear
tableView.backgroundColor = UIColor.white
// tableViewとrefreshViewが合体する
tableView.addSubview(refreshControl)
// 自分の画面をつける refreshControlが付いている
self.view.addSubview(tableView)
// webViewの作成
// 大きさ tableViewの大きさにする
webView.frame = tableView.frame
webView.delegate = self
webView.scalesPageToFit = true//self
// .scaleAspectFit => 画面の中に収まる
webView.contentMode = .scaleAspectFit
self.view.addSubview(webView)
// はじめに画面が呼ばれた時にwebViewがあるのは今回はだめ
// Hiddenにしておく
webView.isHidden = true
// webViewを表示するのはtableViewのcellを押した時
// 対象のLinkを表示する
// 1つ進むbutton作成
goButton = UIButton()
// frameを決める
goButton.frame = CGRect(x: self.view.frame.size.width - 50, y: self.view.frame.size.height - 128, width: 50, height: 50)
// 画像つける for => どういう状態の時に表示するか
goButton.setImage(UIImage(named: "go.png"), for: .normal)
// .touchUpInside => ボタンを押して離した
goButton.addTarget(self, action: #selector(nextPage), for: .touchUpInside)
// 画面に付ける
self.view.addSubview(goButton)
// 戻るボタンの作成
backButton = UIButton()
backButton.frame = CGRect(x: 10, y: self.view.frame.size.height - 128, width: 50, height: 50)
backButton.setImage(UIImage(named: "back.png"), for: .normal)
backButton.addTarget(self, action: #selector(backPage), for: .touchUpInside)
self.view.addSubview(backButton)
// キャンセルボタンの作成
cancelButton = UIButton()
cancelButton.frame = CGRect(x: 10, y: 80, width: 50, height: 50)
cancelButton.setImage(UIImage(named: "cancel.png"), for: .normal)
cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside)
self.view.addSubview(cancelButton)
// 作成したボタンをisHidden = trueにする
goButton.isHidden = true
backButton.isHidden = true
cancelButton.isHidden = true
// ドッツビューの作成
dotsView.frame = CGRect(x: 0, y: self.view.frame.size.height / 3, width: self.view.frame.size.width, height: 100)
// 個数
dotsView.dotsCount = 5
// 大きさ
dotsView.dotsRadius = 10
// くっつける
self.view.addSubview(dotsView)
// hiddenにする
dotsView.isHidden = true
// XMLを解析する(パース)
// parser
let url: String = "https://www.cnet.com/rss/all/"
let urlToSend: URL = URL(string: url)!
parser = XMLParser(contentsOf: urlToSend)!
totalBox = []
parser.delegate = self
// 解析する
parser.parse()
// 更新がされる
tableView.reloadData()
// Do any additional setup after loading the view.
}
// refresh
// 下から上に引っ張った時呼ばれる
func refresh() {
// どれだけ時間をおいて元に戻すか 2.0 => 2秒後
perform(#selector(delay), with: nil, afterDelay: 2.0)
}
// delay
func delay() {
// XMLを解析する(パース)
// parser
let url: String = "https://www.cnet.com/rss/all/"
let urlToSend: URL = URL(string: url)!
parser = XMLParser(contentsOf: urlToSend)!
totalBox = []
parser.delegate = self
// 解析する
parser.parse()
// 更新がされる
tableView.reloadData()
// リフレッシュを終わらせる
refreshControl.endRefreshing()
}
// nextPage
// webViewを1page進める
func nextPage() {
webView.goForward()
}
// backPage
// webViewを1ページ戻す
func backPage() {
webView.goBack()
}
// cancel
// webViewを隠す
func cancel() {
webView.isHidden = true
goButton.isHidden = true
backButton.isHidden = true
cancelButton.isHidden = true
}
// tableviewのデリゲート
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return totalBox.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
// ハイライトなくす
cell.selectionStyle = .none
cell.backgroundColor = UIColor.clear
cell.textLabel?.text = (totalBox[indexPath.row] as AnyObject).value(forKey: "title") as? String
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 18.0)
//cell.textLabel?.textColor = UIColor.white
cell.textLabel?.textColor = UIColor.darkText
cell.detailTextLabel?.text = (totalBox[indexPath.row] as AnyObject).value(forKey: "link") as? String
cell.detailTextLabel?.font = UIFont.boldSystemFont(ofSize: 12.0)
//cell.detailTextLabel?.textColor = UIColor.white
cell.detailTextLabel?.textColor = UIColor.darkGray
// image add
let urlStr = urlArray[indexPath.row].addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url: URL = URL(string: urlStr)!
cell.imageView?.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholderImage.png"))
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// WebViewを表示する
let linkURL = (totalBox[indexPath.row] as AnyObject).value(forKey: "link") as? String
// let urlStr = linkURL?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url: URL = URL(string: linkURL!)!
let urlRequest = NSURLRequest(url: url)
webView.loadRequest(urlRequest as URLRequest)
}
// webViewDidStartLoad
// load スタート
func webViewDidStartLoad(_ webView: UIWebView) {
dotsView.isHidden = false
dotsView.startAnimating()
}
// webViewDidFinishLoad
// load 終わったら
func webViewDidFinishLoad(_ webView: UIWebView) {
dotsView.isHidden = true
dotsView.stopAnimating()
webView.isHidden = false
goButton.isHidden = false
backButton.isHidden = false
cancelButton.isHidden = false
}
// タグを見つけた時
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
// elementにelementNameを入れて行く
element = elementName
if element == "item" {
elements = NSMutableDictionary()
elements = [:]
titleString = NSMutableString()
titleString = ""
linkString = NSMutableString()
linkString = ""
urlString = String()
} else if element == "media:thumbnail" {
// 画像が入ってるkey => url
urlString = attributeDict["url"]!
urlArray.append(urlString)
}
}
// タグの間にデータがあった時(開始タグと終了タグでくくられた箇所にデータが存在した時に実行されるメソッド)
func parser(_ parser: XMLParser, foundCharacters string: String) {
if element == "title" {
titleString.append(string)
} else if element == "link" {
linkString.append(string)
}
}
// タグの終了を見つけた時
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
// itemという要素の中にあるなら
if elementName == "item" {
// titleString(linkString)の中身が空でないなら
if titleString != "" {
// elementsにkeyを付与しながらtitleString(linkStirng)をセットする
elements.setObject(titleString, forKey: "title" as NSCopying)
}
if linkString != "" {
// elementsにkeyを付与しながらtitleString(linkStirng)をセットする
elements.setObject(linkString, forKey: "link" as NSCopying)
}
// add
elements.setObject(urlString, forKey: "url" as NSCopying)
// totalBoxの中にelementsを入れる
totalBox.add(elements)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| cf59d3ee0072c3bbd68d2fd9efad0a6b | 28.341709 | 179 | 0.576297 | false | false | false | false |
slavapestov/swift | refs/heads/master | stdlib/public/SDK/CoreGraphics/CoreGraphics.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import CoreGraphics
import Darwin
//===----------------------------------------------------------------------===//
// CGGeometry
//===----------------------------------------------------------------------===//
public extension CGPoint {
static var zero: CGPoint {
@_transparent // @fragile
get { return CGPoint(x: 0, y: 0) }
}
@_transparent // @fragile
init(x: Int, y: Int) {
self.init(x: CGFloat(x), y: CGFloat(y))
}
@_transparent // @fragile
init(x: Double, y: Double) {
self.init(x: CGFloat(x), y: CGFloat(y))
}
@available(*, unavailable, renamed="zero")
static var zeroPoint: CGPoint {
fatalError("can't retrieve unavailable property")
}
}
extension CGPoint : CustomReflectable, CustomPlaygroundQuickLookable {
public func customMirror() -> Mirror {
return Mirror(self, children: ["x": x, "y": y], displayStyle: .Struct)
}
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return .Point(Double(x), Double(y))
}
}
extension CGPoint : CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(x), \(y))"
}
}
extension CGPoint : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: CGPoint, rhs: CGPoint) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public extension CGSize {
static var zero: CGSize {
@_transparent // @fragile
get { return CGSize(width: 0, height: 0) }
}
@_transparent // @fragile
init(width: Int, height: Int) {
self.init(width: CGFloat(width), height: CGFloat(height))
}
@_transparent // @fragile
init(width: Double, height: Double) {
self.init(width: CGFloat(width), height: CGFloat(height))
}
@available(*, unavailable, renamed="zero")
static var zeroSize: CGSize {
fatalError("can't retrieve unavailable property")
}
}
extension CGSize : CustomReflectable, CustomPlaygroundQuickLookable {
public func customMirror() -> Mirror {
return Mirror(self, children: ["width": width, "height": height], displayStyle: .Struct)
}
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return .Size(Double(width), Double(height))
}
}
extension CGSize : CustomDebugStringConvertible {
public var debugDescription : String {
return "(\(width), \(height))"
}
}
extension CGSize : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: CGSize, rhs: CGSize) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
public extension CGVector {
static var zero: CGVector {
@_transparent // @fragile
get { return CGVector(dx: 0, dy: 0) }
}
@_transparent // @fragile
init(dx: Int, dy: Int) {
self.init(dx: CGFloat(dx), dy: CGFloat(dy))
}
@_transparent // @fragile
init(dx: Double, dy: Double) {
self.init(dx: CGFloat(dx), dy: CGFloat(dy))
}
@available(*, unavailable, renamed="zero")
static var zeroVector: CGVector {
fatalError("can't retrieve unavailable property")
}
}
extension CGVector : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: CGVector, rhs: CGVector) -> Bool {
return lhs.dx == rhs.dx && lhs.dy == rhs.dy
}
public extension CGRect {
static var zero: CGRect {
@_transparent // @fragile
get { return CGRect(x: 0, y: 0, width: 0, height: 0) }
}
static var null: CGRect {
@_transparent // @fragile
get { return CGRectNull }
}
static var infinite: CGRect {
@_transparent // @fragile
get { return CGRectInfinite }
}
@_transparent // @fragile
init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
@_transparent // @fragile
init(x: Double, y: Double, width: Double, height: Double) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
@_transparent // @fragile
init(x: Int, y: Int, width: Int, height: Int) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
var width: CGFloat {
@_transparent // @fragile
get { return CGRectGetWidth(self) }
}
var height: CGFloat {
@_transparent // @fragile
get { return CGRectGetHeight(self) }
}
var minX: CGFloat {
@_transparent // @fragile
get { return CGRectGetMinX(self) }
}
var midX: CGFloat {
@_transparent // @fragile
get { return CGRectGetMidX(self) }
}
var maxX: CGFloat {
@_transparent // @fragile
get { return CGRectGetMaxX(self) }
}
var minY: CGFloat {
@_transparent // @fragile
get { return CGRectGetMinY(self) }
}
var midY: CGFloat {
@_transparent // @fragile
get { return CGRectGetMidY(self) }
}
var maxY: CGFloat {
@_transparent // @fragile
get { return CGRectGetMaxY(self) }
}
var isNull: Bool {
@_transparent // @fragile
get { return CGRectIsNull(self) }
}
var isEmpty: Bool {
@_transparent // @fragile
get { return CGRectIsEmpty(self) }
}
var isInfinite: Bool {
@_transparent // @fragile
get { return CGRectIsInfinite(self) }
}
var standardized: CGRect {
@_transparent // @fragile
get { return CGRectStandardize(self) }
}
var integral: CGRect {
@_transparent // @fragile
get { return CGRectIntegral(self) }
}
@_transparent // @fragile
mutating func standardizeInPlace() {
self = standardized
}
@_transparent // @fragile
mutating func makeIntegralInPlace() {
self = integral
}
@_transparent // @fragile
@warn_unused_result(mutable_variant="insetInPlace")
func insetBy(dx dx: CGFloat, dy: CGFloat) -> CGRect {
return CGRectInset(self, dx, dy)
}
@_transparent // @fragile
mutating func insetInPlace(dx dx: CGFloat, dy: CGFloat) {
self = insetBy(dx: dx, dy: dy)
}
@_transparent // @fragile
@warn_unused_result(mutable_variant="offsetInPlace")
func offsetBy(dx dx: CGFloat, dy: CGFloat) -> CGRect {
return CGRectOffset(self, dx, dy)
}
@_transparent // @fragile
mutating func offsetInPlace(dx dx: CGFloat, dy: CGFloat) {
self = offsetBy(dx: dx, dy: dy)
}
@_transparent // @fragile
@warn_unused_result(mutable_variant="unionInPlace")
func union(rect: CGRect) -> CGRect {
return CGRectUnion(self, rect)
}
@_transparent // @fragile
mutating func unionInPlace(rect: CGRect) {
self = union(rect)
}
@_transparent // @fragile
@warn_unused_result(mutable_variant="intersectInPlace")
func intersect(rect: CGRect) -> CGRect {
return CGRectIntersection(self, rect)
}
@_transparent // @fragile
mutating func intersectInPlace(rect: CGRect) {
self = intersect(rect)
}
@_transparent // @fragile
@warn_unused_result
func divide(atDistance: CGFloat, fromEdge: CGRectEdge)
-> (slice: CGRect, remainder: CGRect)
{
var slice = CGRect.zero
var remainder = CGRect.zero
CGRectDivide(self, &slice, &remainder, atDistance, fromEdge)
return (slice, remainder)
}
@_transparent // @fragile
@warn_unused_result
func contains(rect: CGRect) -> Bool {
return CGRectContainsRect(self, rect)
}
@_transparent // @fragile
@warn_unused_result
func contains(point: CGPoint) -> Bool {
return CGRectContainsPoint(self, point)
}
@_transparent // @fragile
@warn_unused_result
func intersects(rect: CGRect) -> Bool {
return CGRectIntersectsRect(self, rect)
}
@available(*, unavailable, renamed="zero")
static var zeroRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="infinite")
static var infiniteRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="null")
static var nullRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="standardized")
var standardizedRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="integral")
var integerRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="standardizeInPlace")
mutating func standardize() -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="makeIntegralInPlace")
mutating func integerize() {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="insetBy")
func rectByInsetting(dx dx: CGFloat, dy: CGFloat) -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="insetInPlace")
func inset(dx dx: CGFloat, dy: CGFloat) {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="offsetBy")
func rectByOffsetting(dx dx: CGFloat, dy: CGFloat) -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="offsetInPlace")
func offset(dx dx: CGFloat, dy: CGFloat) {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="unionInPlace")
mutating func union(withRect: CGRect) {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="union")
func rectByUnion(withRect: CGRect) -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="intersectInPlace")
mutating func intersect(withRect: CGRect) {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="intersect")
func rectByIntersecting(withRect: CGRect) -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="divide")
func rectsByDividing(atDistance: CGFloat, fromEdge: CGRectEdge)
-> (slice: CGRect, remainder: CGRect) {
fatalError("can't call unavailable function")
}
}
extension CGRect : CustomReflectable, CustomPlaygroundQuickLookable {
public func customMirror() -> Mirror {
return Mirror(self, children: ["origin": origin, "size": size], displayStyle: .Struct)
}
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return .Rectangle(Double(origin.x), Double(origin.y), Double(size.width), Double(size.height))
}
}
extension CGRect : CustomDebugStringConvertible {
public var debugDescription : String {
return "(\(origin.x), \(origin.y), \(size.width), \(size.height))"
}
}
extension CGRect : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: CGRect, rhs: CGRect) -> Bool {
return CGRectEqualToRect(lhs, rhs)
}
// Overlay the C names of these constants with transparent definitions. The
// C constants are opaque extern globals for no good reason.
public var CGPointZero: CGPoint {
@_transparent // @fragile
get { return CGPoint.zero }
}
public var CGRectZero: CGRect {
@_transparent // @fragile
get { return CGRect.zero }
}
public var CGSizeZero: CGSize {
@_transparent // @fragile
get { return CGSize.zero }
}
public var CGAffineTransformIdentity: CGAffineTransform {
@_transparent // @fragile
get { return CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) }
}
| 8851097f62c85ac50ea97f07affe0d68 | 26.013761 | 98 | 0.650959 | false | false | false | false |
buscarini/Collectionist | refs/heads/master | Collectionist/Classes/DataSources/Collection/CollectionViewDataSource.swift | mit | 1 | //
// CollectionViewDataSource.swift
// Collectionist
//
// Created by Jose Manuel Sánchez Peñarroja on 15/10/15.
// Copyright © 2015 vitaminew. All rights reserved.
//
import UIKit
open class CollectionViewDataSource<T: Equatable, HeaderT: Equatable, FooterT: Equatable>: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
public typealias ListType = List<T,HeaderT, FooterT>
public typealias ListSectionType = ListSection<T,HeaderT, FooterT>
public typealias ListItemType = ListItem<T>
fileprivate var refreshControl: UIRefreshControl?
public init(view: UICollectionView) {
self.view = view
self.refreshControl = UIRefreshControl()
super.init()
self.refreshControl?.addTarget(self, action: #selector(CollectionViewDataSource.refresh(_:)), for: .valueChanged)
self.viewChanged()
}
open var view : UICollectionView {
didSet {
self.viewChanged()
}
}
open var list : ListType? {
didSet {
CollectionViewDataSource.registerViews(self.list, collectionView: self.view)
self.update(oldValue, newList: list)
}
}
fileprivate func viewChanged() {
CollectionViewDataSource.registerViews(self.list, collectionView: self.view)
self.view.dataSource = self
self.view.delegate = self
}
fileprivate func update(_ oldList: ListType?, newList: ListType?) {
self.updateView(oldList, newList: newList)
self.refreshControl?.endRefreshing()
if let refreshControl = self.refreshControl , newList?.configuration?.onRefresh != nil {
self.view.addSubview(refreshControl)
self.view.alwaysBounceVertical = true
}
else {
self.refreshControl?.removeFromSuperview()
}
if let list = newList, let scrollInfo = self.list?.scrollInfo, ListType.indexPathInsideBounds(list, indexPath: scrollInfo.indexPath) {
let indexPath = scrollInfo.indexPath
self.view.scrollToItem(at: indexPath, at: CollectionViewDataSource.scrollPositionWithPosition(scrollInfo.position, collectionView: self.view), animated: scrollInfo.animated)
}
}
fileprivate func updateView(_ oldList: ListType?, newList: ListType?) {
if let oldList = oldList, let newList = newList , ListType.sameItemsCount(oldList, newList) {
let visibleIndexPaths = view.indexPathsForVisibleItems
// let listItems: [ListItem<T>?] = visibleIndexPaths.map { indexPath -> ListItem<T>? in
// guard let item = indexPath.item else { return nil }
// return newList.sections[indexPath.section].items[item]
// }
//
// let cells = visibleIndexPaths.map {
// return view.cellForItem(at: $0)
// }
//
// Zip2Sequence(_sequence1: listItems, _sequence2: cells).map { listItem, cell in
// if let fillableCell = cell as? Fillable, let listItem = listItem {
// fillableCell.fill(listItem)
// }
// return nil
// }
for indexPath in visibleIndexPaths {
let item = indexPath.item
let cell = view.cellForItem(at: indexPath)
let listItem = newList.sections[indexPath.section].items[item]
if let fillableCell = cell as? Fillable {
fillableCell.fill(listItem)
}
}
}
else {
self.view.reloadData()
}
}
static func scrollPositionWithPosition(_ position: ListScrollPosition, collectionView: UICollectionView?) -> UICollectionViewScrollPosition {
guard let collectionView = collectionView else {
return []
}
let scrollDirection : UICollectionViewScrollDirection
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
scrollDirection = flowLayout.scrollDirection
}
else {
scrollDirection = .vertical
}
switch (position,scrollDirection) {
case (.begin,.horizontal):
return .left
case (.begin,.vertical):
return .top
case (.middle,.vertical):
return .centeredVertically
case (.middle,.horizontal):
return .centeredHorizontally
case (.end, .vertical):
return .bottom
case (.end, .horizontal):
return .right
}
}
open static func registerViews(_ list: ListType?, collectionView : UICollectionView?) {
guard let list = list else { return }
let allReusableIds = List.allReusableIds(list)
for reusableId in allReusableIds {
collectionView?.register(CollectionViewCell<T>.self, forCellWithReuseIdentifier: reusableId)
}
}
// MARK: Pull to Refresh
func refresh(_ sender: AnyObject?) {
guard let list = self.list else { return }
guard let configuration = list.configuration else { return }
configuration.onRefresh?()
}
// MARK: UICollectionViewDataSource
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.list?.sections.count ?? 0
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let list = self.list else {
return 0
}
return list.sections[section].items.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let list = self.list else {
fatalError("List is required. We shouldn't be here")
}
let listItem = list.sections[indexPath.section].items[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: listItem.cellId, for: indexPath)
if let fillableCell = cell as? Fillable {
fillableCell.fill(listItem)
}
return cell
}
open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let list = self.list else {
return
}
let listItem = list.sections[(indexPath as NSIndexPath).section].items[(indexPath as NSIndexPath).row]
if let fillableCell = cell as? Fillable {
fillableCell.fill(listItem)
}
}
// MARK : UICollectionViewDelegate
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let list = self.list else {
return
}
let listItem = list.sections[(indexPath as NSIndexPath).section].items[(indexPath as NSIndexPath).row]
if let onSelect = listItem.onSelect {
onSelect(listItem)
}
}
}
| 4fe5f024ac5afbb40da82bc49505b7b8 | 28.955665 | 176 | 0.726525 | false | false | false | false |
Arcovv/CleanArchitectureRxSwift | refs/heads/master | CleanArchitectureRxSwift/Scenes/AllPosts/PostsViewModel.swift | mit | 2 | import Foundation
import Domain
import RxSwift
import RxCocoa
final class PostsViewModel: ViewModelType {
struct Input {
let trigger: Driver<Void>
let createPostTrigger: Driver<Void>
let selection: Driver<IndexPath>
}
struct Output {
let fetching: Driver<Bool>
let posts: Driver<[PostItemViewModel]>
let createPost: Driver<Void>
let selectedPost: Driver<Post>
let error: Driver<Error>
}
private let useCase: PostsUseCase
private let navigator: PostsNavigator
init(useCase: PostsUseCase, navigator: PostsNavigator) {
self.useCase = useCase
self.navigator = navigator
}
func transform(input: Input) -> Output {
let activityIndicator = ActivityIndicator()
let errorTracker = ErrorTracker()
let posts = input.trigger.flatMapLatest {
return self.useCase.posts()
.trackActivity(activityIndicator)
.trackError(errorTracker)
.asDriverOnErrorJustComplete()
.map { $0.map { PostItemViewModel(with: $0) } }
}
let fetching = activityIndicator.asDriver()
let errors = errorTracker.asDriver()
let selectedPost = input.selection
.withLatestFrom(posts) { (indexPath, posts) -> Post in
return posts[indexPath.row].post
}
.do(onNext: navigator.toPost)
let createPost = input.createPostTrigger
.do(onNext: navigator.toCreatePost)
return Output(fetching: fetching,
posts: posts,
createPost: createPost,
selectedPost: selectedPost,
error: errors)
}
}
| a6bd420c5dbe2d193a8dc554384c0155 | 30.803571 | 66 | 0.591802 | false | false | false | false |
gavrix/ImageViewModel | refs/heads/master | Carthage/Checkouts/ReactiveSwift/Tests/ReactiveSwiftTests/SchedulerSpec.swift | mit | 1 | //
// SchedulerSpec.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-07-13.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Dispatch
import Foundation
import Nimble
import Quick
@testable
import ReactiveSwift
#if os(Linux)
import func CoreFoundation._CFIsMainThread
private extension Thread {
// `isMainThread` is not implemented yet in swift-corelibs-foundation.
static var isMainThread: Bool {
return _CFIsMainThread()
}
}
#endif
class SchedulerSpec: QuickSpec {
override func spec() {
describe("ImmediateScheduler") {
it("should run enqueued actions immediately") {
var didRun = false
ImmediateScheduler().schedule {
didRun = true
}
expect(didRun) == true
}
}
describe("UIScheduler") {
func dispatchSyncInBackground(_ action: @escaping () -> Void) {
let group = DispatchGroup()
let globalQueue: DispatchQueue
if #available(*, OSX 10.10) {
globalQueue = DispatchQueue.global()
} else {
globalQueue = DispatchQueue.global(priority: .default)
}
globalQueue.async(group: group, execute: action)
group.wait()
}
it("should run actions immediately when on the main thread") {
let scheduler = UIScheduler()
var values: [Int] = []
expect(Thread.isMainThread) == true
scheduler.schedule {
values.append(0)
}
expect(values) == [ 0 ]
scheduler.schedule {
values.append(1)
}
scheduler.schedule {
values.append(2)
}
expect(values) == [ 0, 1, 2 ]
}
it("should enqueue actions scheduled from the background") {
let scheduler = UIScheduler()
var values: [Int] = []
dispatchSyncInBackground {
scheduler.schedule {
expect(Thread.isMainThread) == true
values.append(0)
}
return
}
expect(values) == []
expect(values).toEventually(equal([ 0 ]))
dispatchSyncInBackground {
scheduler.schedule {
expect(Thread.isMainThread) == true
values.append(1)
}
scheduler.schedule {
expect(Thread.isMainThread) == true
values.append(2)
}
return
}
expect(values) == [ 0 ]
expect(values).toEventually(equal([ 0, 1, 2 ]))
}
it("should run actions enqueued from the main thread after those from the background") {
let scheduler = UIScheduler()
var values: [Int] = []
dispatchSyncInBackground {
scheduler.schedule {
expect(Thread.isMainThread) == true
values.append(0)
}
return
}
scheduler.schedule {
expect(Thread.isMainThread) == true
values.append(1)
}
scheduler.schedule {
expect(Thread.isMainThread) == true
values.append(2)
}
expect(values) == []
expect(values).toEventually(equal([ 0, 1, 2 ]))
}
}
describe("QueueScheduler") {
it("should run enqueued actions on a global queue") {
var didRun = false
let scheduler: QueueScheduler
if #available(OSX 10.10, *) {
scheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
scheduler.schedule {
didRun = true
expect(Thread.isMainThread) == false
}
expect{didRun}.toEventually(beTruthy())
}
describe("on a given queue") {
var scheduler: QueueScheduler!
beforeEach {
if #available(OSX 10.10, *) {
scheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
scheduler.queue.suspend()
}
it("should run enqueued actions serially on the given queue") {
var value = 0
for _ in 0..<5 {
scheduler.schedule {
expect(Thread.isMainThread) == false
value += 1
}
}
expect(value) == 0
scheduler.queue.resume()
expect{value}.toEventually(equal(5))
}
it("should run enqueued actions after a given date") {
var didRun = false
scheduler.schedule(after: Date()) {
didRun = true
expect(Thread.isMainThread) == false
}
expect(didRun) == false
scheduler.queue.resume()
expect{didRun}.toEventually(beTruthy())
}
it("should repeatedly run actions after a given date") {
let disposable = SerialDisposable()
var count = 0
let timesToRun = 3
disposable.innerDisposable = scheduler.schedule(after: Date(), interval: .milliseconds(10), leeway: .seconds(0)) {
expect(Thread.isMainThread) == false
count += 1
if count == timesToRun {
disposable.dispose()
}
}
expect(count) == 0
scheduler.queue.resume()
expect{count}.toEventually(equal(timesToRun))
}
}
}
describe("TestScheduler") {
var scheduler: TestScheduler!
var startDate: Date!
// How much dates are allowed to differ when they should be "equal."
let dateComparisonDelta = 0.00001
beforeEach {
startDate = Date()
scheduler = TestScheduler(startDate: startDate)
expect(scheduler.currentDate) == startDate
}
it("should run immediately enqueued actions upon advancement") {
var string = ""
scheduler.schedule {
string += "foo"
expect(Thread.isMainThread) == true
}
scheduler.schedule {
string += "bar"
expect(Thread.isMainThread) == true
}
expect(string) == ""
scheduler.advance()
expect(scheduler.currentDate).to(beCloseTo(startDate))
expect(string) == "foobar"
}
it("should run actions when advanced past the target date") {
var string = ""
scheduler.schedule(after: .seconds(15)) { [weak scheduler] in
string += "bar"
expect(Thread.isMainThread) == true
expect(scheduler?.currentDate).to(beCloseTo(startDate.addingTimeInterval(15), within: dateComparisonDelta))
}
scheduler.schedule(after: .seconds(5)) { [weak scheduler] in
string += "foo"
expect(Thread.isMainThread) == true
expect(scheduler?.currentDate).to(beCloseTo(startDate.addingTimeInterval(5), within: dateComparisonDelta))
}
expect(string) == ""
scheduler.advance(by: .seconds(10))
expect(scheduler.currentDate).to(beCloseTo(startDate.addingTimeInterval(10), within: TimeInterval(dateComparisonDelta)))
expect(string) == "foo"
scheduler.advance(by: .seconds(10))
expect(scheduler.currentDate).to(beCloseTo(startDate.addingTimeInterval(20), within: dateComparisonDelta))
expect(string) == "foobar"
}
it("should run all remaining actions in order") {
var string = ""
scheduler.schedule(after: .seconds(15)) {
string += "bar"
expect(Thread.isMainThread) == true
}
scheduler.schedule(after: .seconds(5)) {
string += "foo"
expect(Thread.isMainThread) == true
}
scheduler.schedule {
string += "fuzzbuzz"
expect(Thread.isMainThread) == true
}
expect(string) == ""
scheduler.run()
expect(scheduler.currentDate) == NSDate.distantFuture
expect(string) == "fuzzbuzzfoobar"
}
}
}
}
| f9f2d9b01e5b0f7474215f77155e704a | 21.861736 | 124 | 0.633474 | false | false | false | false |
franciscocgoncalves/FastCapture | refs/heads/master | FastCapture/DirectoryManager.swift | mit | 1 | //
// DirectoryManager.swift
// FastCapture
//
// Created by Francisco Gonçalves on 20/04/15.
// Copyright (c) 2015 Francisco Gonçalves. All rights reserved.
//
import Cocoa
private let _DirectoryManager = DirectoryManager()
class DirectoryManager: NSObject {
class var sharedInstance: DirectoryManager {
return _DirectoryManager
}
var url: NSURL?
func createDirectory() {
let userDefaultURL: AnyObject? = NSUserDefaults.standardUserDefaults().URLForKey("screenCaptureDirectory")
let folderDestinationURL: NSURL
if userDefaultURL == nil {
if let picturesURL = NSFileManager.defaultManager().URLsForDirectory(.PicturesDirectory, inDomains: .UserDomainMask).first{
folderDestinationURL = picturesURL.URLByAppendingPathComponent("ScreenCapture")
}
else {
//should alert user
return
}
}
else {
folderDestinationURL = userDefaultURL as! NSURL
}
var isDir = ObjCBool(true)
if !NSFileManager.defaultManager().fileExistsAtPath(folderDestinationURL.path!, isDirectory: &isDir) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(folderDestinationURL.path!, withIntermediateDirectories: true, attributes: nil)
print("sucessfuly created dir")
} catch let error as NSError {
print("Error: \(error.domain)")
//should alert user
return
}
}
setDirectory(folderDestinationURL)
}
func readDirectory(cb: ((fileURL: NSURL) -> Void)?) {
let fileManager = NSFileManager.defaultManager()
let keys = NSArray(objects: NSURLNameKey)
let options: NSDirectoryEnumerationOptions = ([NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants, NSDirectoryEnumerationOptions.SkipsHiddenFiles])
//Get Contents of directory
if(self.url == nil) {
self.url = NSUserDefaults.standardUserDefaults().URLForKey("screenCaptureDirectory")
}
var contents: [NSURL]?
do {
contents = try fileManager.contentsOfDirectoryAtURL(self.url!, includingPropertiesForKeys: keys as? [String], options: options)
} catch let error as NSError {
print(error)
contents = nil
}
ScreenCapture.sharedInstance.addNewFilesToCache(contents, cb: cb)
}
func setDirectory(folderDestinationURL: NSURL) {
NSUserDefaults.standardUserDefaults().setURL(folderDestinationURL, forKey: "screenCaptureDirectory")
self.url = folderDestinationURL
setScreenCaptureDefaultFolder(folderDestinationURL)
}
func setScreenCaptureDefaultFolder(directoryURL: NSURL) {
let task = NSTask()
task.launchPath = "/bin/bash"
task.arguments = ["-c",
"defaults write com.apple.screencapture location \(directoryURL.path!); killall SystemUIServer"]
task.launch()
}
}
| 1bad738ca58baa095fc9d047bcd21d22 | 34.693182 | 163 | 0.633238 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS | refs/heads/master | TruckMuncher/api/RCategory.swift | gpl-2.0 | 1 | //
// RCategory.swift
// TruckMuncher
//
// Created by Josh Ault on 10/27/14.
// Copyright (c) 2014 TruckMuncher. All rights reserved.
//
import UIKit
import Realm
class RCategory: RLMObject {
dynamic var id = ""
dynamic var name = ""
dynamic var notes = ""
dynamic var orderInMenu = 0
dynamic var menuItems = RLMArray(objectClassName: RMenuItem.className())
override init() {
super.init()
}
class func initFromProto(category: [String: AnyObject]) -> RCategory {
let rcategory = RCategory()
rcategory.id = category["id"] as! String
rcategory.name = category["name"] as? String ?? ""
rcategory.notes = category["notes"] as? String ?? ""
rcategory.orderInMenu = category["orderInMenu"] as? Int ?? 0
if let menuItems = category["menuItems"] as? [[String: AnyObject]] {
for menuItem in menuItems {
rcategory.menuItems.addObject(RMenuItem.initFromFullProto(menuItem))
}
}
return rcategory
}
override class func primaryKey() -> String! {
return "id"
}
}
| e12f60baec60e6c8cde9ee2c17a1111c | 27.325 | 84 | 0.606355 | false | false | false | false |
zuoya0820/DouYuZB | refs/heads/master | DouYuZB/DouYuZB/Classes/Main/Model/AnchorModel.swift | mit | 1 | //
// AnchorModel.swift
// DouYuZB
//
// Created by zuoya on 2017/10/22.
// Copyright © 2017年 zuoya. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
/// 房间id
var room_id : Int = 0
/// 房间图片对应的URLstring
var vertical_src : String = ""
/// 判断是手机直播还是电脑直播
/// 0: 电脑直播 1: 手机直播
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 观看人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| 3eda612e3c11d27c37f2e4baf60433c8 | 19.457143 | 73 | 0.553073 | false | false | false | false |
SAP/SAPJamSampleCode | refs/heads/main | iOS_Integrations/mobile-sdk-ios/Swift 2.x/SAPJamSDK/SAPJamSDK/JamSession/JamAuthConfig.swift | apache-2.0 | 1 | //
// JamAuthConfig.swift
// SAPJamSDK
//
// Copyright © 2016 SAP SE. All rights reserved.
//
import Foundation
import OAuthSwift
import KeychainAccess
// Keys for storage of OAuth 1.0a single use access token and secret in keychain
let kAccessToken = "accessToken"
let kAccessSecret = "accessSecret"
public class JamAuthConfig {
// Sets authentication to OAuth 1.0a
public var oauthswift: OAuth1Swift?
// Used by the "configure" method to set the OAuth 1.0a authentication server name
private var serverName = ""
// Sets the keychain domain
private let keychain = Keychain(service: "com.sap.jam")
// Creates a shared instance of the keychain
static let sharedInstance = JamAuthConfig()
// Checks if user is logged in by checking if the OAuth 1.0a token and secret have been set in the keychain
public class func isLoggedIn() -> Bool {
return sharedInstance.keychain[kAccessToken] != nil && sharedInstance.keychain[kAccessSecret] != nil
}
// Provides functions access to a successfully created OAuth 1.0a single use access token
public typealias SingleUseTokenSuccessHandler = (singleUseToken: String) -> Void
// Displays an error message in the console
public typealias ErrorHandler = (error: NSError) -> Void
// Gets the OAuth 1.0a single use access token from the authorization server so the app can access the Jam OData API
public func getSingleUseToken(success: SingleUseTokenSuccessHandler, failure: ErrorHandler?) {
let urlStr = getServerUrl() + "/v1/single_use_tokens"
// Attempts to gets the OAuth 1.0a single use access token from the authorization server
oauthswift!.client.post(urlStr,
success: {
data, response in
// Converts response object into a string
let dataString: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
// Creates a regular expression used to find the single use access token key-value pair in the string
let regex: NSRegularExpression = try! NSRegularExpression(pattern: "(?<=<single_use_token id=\")[^\"]+", options:[.CaseInsensitive])
// Executes the regular expression to determine if the single use access token is in the string
if let match = regex.firstMatchInString(dataString as String, options:[], range: NSMakeRange(0, dataString.length)) {
// Assigns the single use access token value from the key-value pair to a string
let token:String = dataString.substringWithRange(match.range)
// Assigns the OAuth 1.0a single use access token to a publicly accessible property so
// other functions can access the SAP Jam OData API.
success(singleUseToken: token)
}
else {
// Displays error information when a single use access token cannot be found in the string
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Could not get Single Use Token", comment: "Response from /v1/single_use_tokens does not contain a token")]
failure?(error: NSError(domain: "sapjam.error", code: -1, userInfo: errorInfo))
}
},
failure: { error in
print(error)
failure?(error: error)
}
)
}
// Creates the OAuth 1.0a authentication server URL
public func getServerUrl() -> String {
return "https://" + serverName
}
// Configures the URLs required to perform OAuth 1.0a authentication and authorization to get a single use
// access token.
public func configure(server: String, key: String, secret: String, companyDomain: String? = nil) {
serverName = server
let serverUrl = getServerUrl()
validateServer()
// Creates authorization url for normal oauth clients
var authorizeUrl = serverUrl + "/oauth/authorize"
if let domain = companyDomain {
authorizeUrl = serverUrl + "/c/" + domain + "/oauth/authorize"
}
oauthswift = OAuth1Swift(
consumerKey: key,
consumerSecret: secret,
requestTokenUrl: serverUrl + "/oauth/request_token",
authorizeUrl: authorizeUrl,
accessTokenUrl: serverUrl + "/oauth/access_token"
)
// Uses the existing single use token and secret in the keychain if the user is already logged in
if JamAuthConfig.isLoggedIn() {
oauthswift?.client.credential.oauth_token = keychain[kAccessToken]!
oauthswift?.client.credential.oauth_token_secret = keychain[kAccessSecret]!
}
}
// Validates the OAuth 1.0a authentication server domains
private func validateServer() {
// Note: this list may be subject to change (additions) in future.
// Please use the server your company is registered with.
let VALID_JAM_SERVERS = [
"developer.sapjam.com",
"jam4.sapjam.com",
"jam8.sapjam.com",
"jam10.sapjam.com",
"jam12.sapjam.com",
"jam2.sapjam.com",
"jam15.sapsf.cn",
"jam17.sapjam.com",
"jam18.sapjam.com"]
precondition(VALID_JAM_SERVERS.contains(serverName), "Must set a valid Jam server")
}
// Stores OAuth 1.0a single use token and secret in the keychain
public func storeCredentials(credential: OAuthSwiftCredential) {
keychain[kAccessToken] = credential.oauth_token
keychain[kAccessSecret] = credential.oauth_token_secret
}
}
| 8fb6aa1665aac6fcc9402e4f7ac07def | 41.056738 | 196 | 0.622597 | false | false | false | false |
soh335/GetBSDProcessList | refs/heads/master | GetBSDProcessList/GetBSDProcessList.swift | mit | 1 | import Foundation
import Darwin
public func GetBSDProcessList() -> ([kinfo_proc]?) {
var done = false
var result: [kinfo_proc]?
var err: Int32
repeat {
let name = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0];
let namePointer = name.withUnsafeBufferPointer { UnsafeMutablePointer<Int32>($0.baseAddress) }
var length: Int = 0
err = sysctl(namePointer, u_int(name.count), nil, &length, nil, 0)
if err == -1 {
err = errno
}
if err == 0 {
let count = length / strideof(kinfo_proc)
result = [kinfo_proc](count: count, repeatedValue: kinfo_proc())
err = result!.withUnsafeMutableBufferPointer({ (inout p: UnsafeMutableBufferPointer<kinfo_proc>) -> Int32 in
return sysctl(namePointer, u_int(name.count), p.baseAddress, &length, nil, 0)
})
switch err {
case 0:
done = true
case -1:
err = errno
case ENOMEM:
err = 0
default:
fatalError()
}
}
} while err == 0 && !done
return result
} | 6735a1d9f22dd0ae2a2461c31ef08a3b | 28.7 | 120 | 0.518955 | false | false | false | false |
WalterCreazyBear/Swifter30 | refs/heads/master | CollectionDemo/CollectionDemo/SimpleDemoViewController.swift | mit | 1 | //
// SimpleDemoViewController.swift
// CollectionDemo
//
// Created by Bear on 2017/7/6.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class SimpleDemoViewController: UIViewController {
let headerId = "simpleHead"
let footerId = "simpleFooter"
var dataSourceOne : Array<Int> = Array()
var dataSourceTwo : Array<Int> = Array()
var dataSource : Array<Array<Int>> = Array()
lazy var collectionView : UICollectionView = {
let flowLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//滚动方向
flowLayout.scrollDirection = .vertical
//cell的大小
flowLayout.itemSize = CGSize(width: 80, height: 80)
//滚动方向的垂直方向上,单元格之间的间隔
flowLayout.minimumInteritemSpacing = 10
//滚动方向,单元格之间的间隔
flowLayout.minimumLineSpacing = 10
//头部的大小,只会读取滚动方向的值:水平滚动的话,读取宽度;垂直滚动,读取高度;
flowLayout.headerReferenceSize = CGSize(width: 60, height: 40)
//同上
flowLayout.footerReferenceSize = CGSize(width: 60, height: 40)
let view : UICollectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: flowLayout)
view.register(SimpleCellCollectionViewCell.self, forCellWithReuseIdentifier: String.init(describing: SimpleCellCollectionViewCell.self))
view.register(HeaderCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: self.headerId)
view.register(FooterCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: self.footerId)
view.delegate = self
view.dataSource = self
view.backgroundColor = UIColor.orange
let gesture = UILongPressGestureRecognizer.init(target: self, action: #selector(self.handleLongPressGesture(gesture:)))
view.addGestureRecognizer(gesture)
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "Simple Demo"
view.backgroundColor = UIColor.white
for ele in 0...49 {
self.dataSourceOne.append(ele)
self.dataSourceTwo.append(ele)
}
dataSource.append(dataSourceOne)
dataSource.append(dataSourceTwo)
view.addSubview(collectionView)
}
func handleLongPressGesture(gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
let touchItemIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView))
guard touchItemIndexPath != nil else {
return
}
self.collectionView.beginInteractiveMovementForItem(at: touchItemIndexPath!)
case .changed:
self.collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view))
case .ended,.cancelled:
self.collectionView.endInteractiveMovement()
default:
break
}
}
}
extension SimpleDemoViewController : UICollectionViewDelegate,UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.count;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource[section].count
}
//设置head foot视图
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if (kind as NSString).isEqual(to: UICollectionElementKindSectionHeader)
{
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: self.headerId, for: indexPath) as! HeaderCollectionReusableView
header.setupView()
return header
}
else
{
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: self.footerId, for: indexPath) as! FooterCollectionReusableView
footer.setupView()
return footer
}
}
//设置每个单元格
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String.init(describing: SimpleCellCollectionViewCell.self), for: indexPath) as! SimpleCellCollectionViewCell
cell.setupView(num: dataSource[indexPath.section][indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
//设置选中高亮时的颜色
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.red
}
//设置取消高亮时的颜色
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.white
}
//长按是否弹出菜单,和长按移动单元格冲突~!
func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
//单元格是否可以被选中,只对下面的didSelectItemAt进行控件。高亮什么的都不归这货管
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if indexPath.row%2 == 0
{
return false
}
else
{
return true
}
}
//单元格被选中后的事件
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("\(indexPath.row)")
}
//响应哪些菜单项
func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
let selectorStr = NSStringFromSelector(action) as NSString
if selectorStr.isEqual(to: "cut:")
{
return true
}
else if selectorStr.isEqual(to: "copy:")
{
return true
}
else if selectorStr.isEqual(to: "paste")
{
return true
}
else
{
return false
}
}
//响应长按菜单
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
let selectorStr = NSStringFromSelector(action) as NSString
if selectorStr.isEqual(to: "cut:")
{
let array = [indexPath]
dataSource[indexPath.section].remove(at: indexPath.row)
collectionView.deleteItems(at: array)
}
else if selectorStr.isEqual(to: "copy:")
{
}
else if selectorStr.isEqual(to: "paste")
{
}
else
{
}
}
//配合手势移动使用
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let value = dataSource[sourceIndexPath.section][sourceIndexPath.row]
dataSource[sourceIndexPath.section].remove(at: sourceIndexPath.row)
dataSource[destinationIndexPath.section].insert(value, at: destinationIndexPath.row)
}
}
| b50117b9a49ba81a30d506e2a3f7b85b | 31.07563 | 183 | 0.66099 | false | false | false | false |
littlelightwang/firefox-ios | refs/heads/master | Client/Frontend/Browser/BrowserToolbar.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Snappy
protocol BrowserToolbarDelegate {
func didBeginEditing()
func didClickBack()
func didClickForward()
func didClickAddTab()
func didLongPressBack()
func didLongPressForward()
func didClickReaderMode()
func didClickStop()
func didClickReload()
}
class BrowserToolbar: UIView, UITextFieldDelegate, BrowserLocationViewDelegate {
var browserToolbarDelegate: BrowserToolbarDelegate?
private var forwardButton: UIButton!
private var backButton: UIButton!
private var locationView: BrowserLocationView!
private var tabsButton: UIButton!
private var progressBar: UIProgressView!
private var longPressGestureBackButton: UILongPressGestureRecognizer!
private var longPressGestureForwardButton: UILongPressGestureRecognizer!
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
viewDidInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
viewDidInit()
}
private func viewDidInit() {
self.backgroundColor = UIColor(white: 0.80, alpha: 1.0)
backButton = UIButton()
backButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
backButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
backButton.setTitle("<", forState: UIControlState.Normal)
backButton.accessibilityLabel = NSLocalizedString("Back", comment: "")
backButton.addTarget(self, action: "SELdidClickBack", forControlEvents: UIControlEvents.TouchUpInside)
longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBack:")
backButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "")
backButton.addGestureRecognizer(longPressGestureBackButton)
self.addSubview(backButton)
forwardButton = UIButton()
forwardButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
forwardButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
forwardButton.setTitle(">", forState: UIControlState.Normal)
forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "")
forwardButton.addTarget(self, action: "SELdidClickForward", forControlEvents: UIControlEvents.TouchUpInside)
longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressForward:")
forwardButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "")
forwardButton.addGestureRecognizer(longPressGestureForwardButton)
self.addSubview(forwardButton)
locationView = BrowserLocationView(frame: CGRectZero)
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
addSubview(locationView)
progressBar = UIProgressView()
self.progressBar.trackTintColor = self.backgroundColor
self.addSubview(progressBar)
tabsButton = UIButton()
tabsButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
tabsButton.titleLabel?.layer.borderColor = UIColor.blackColor().CGColor
tabsButton.titleLabel?.layer.cornerRadius = 4
tabsButton.titleLabel?.layer.borderWidth = 1
tabsButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 12)
tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
tabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(24)
return
}
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(tabsButton)
self.backButton.snp_remakeConstraints { make in
make.left.equalTo(self)
make.centerY.equalTo(self).offset(10)
make.width.height.equalTo(44)
}
self.forwardButton.snp_remakeConstraints { make in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self).offset(10)
make.width.height.equalTo(44)
}
self.locationView.snp_remakeConstraints { make in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self).offset(10)
}
self.tabsButton.snp_remakeConstraints { make in
make.left.equalTo(self.locationView.snp_right)
make.centerY.equalTo(self).offset(10)
make.width.height.equalTo(44)
make.right.equalTo(self).offset(-8)
}
self.progressBar.snp_remakeConstraints { make in
make.centerY.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
}
func updateURL(url: NSURL?) {
if let url = url {
locationView.url = url
}
}
func updateTabCount(count: Int) {
tabsButton.setTitle(count.description, forState: UIControlState.Normal)
tabsButton.accessibilityValue = count.description
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "")
}
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateFowardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateLoading(loading: Bool) {
locationView.loading = loading
}
func SELdidClickBack() {
browserToolbarDelegate?.didClickBack()
}
func SELdidLongPressBack(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
browserToolbarDelegate?.didLongPressBack()
}
}
func SELdidClickForward() {
browserToolbarDelegate?.didClickForward()
}
func SELdidLongPressForward(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
browserToolbarDelegate?.didLongPressForward()
}
}
func SELdidClickAddTab() {
browserToolbarDelegate?.didClickAddTab()
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: true)
UIView.animateWithDuration(1.5, animations: {self.progressBar.alpha = 0.0},
completion: {_ in self.progressBar.setProgress(0.0, animated: false)})
} else {
self.progressBar.alpha = 1.0
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress))
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
browserToolbarDelegate?.didClickReaderMode()
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
browserToolbarDelegate?.didBeginEditing()
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
browserToolbarDelegate?.didClickReload()
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
browserToolbarDelegate?.didClickStop()
}
}
| 4fb5e64b224652eee80a51f19c26a797 | 36.362745 | 117 | 0.696143 | false | false | false | false |
tschmitz/DateIntervalOperators | refs/heads/master | DateIntervalOperators.swift | mit | 1 | //
// DateIntervalOperators.swift
// SyncTime
//
// Created by Tim Schmitz on 2/2/15.
// Copyright (c) 2015 Tap and Tonic. All rights reserved.
//
import Foundation
public extension Int {
public func day() -> NSDateComponents {
let components = NSDateComponents()
components.day = self
return components
}
public func days() -> NSDateComponents { return self.day() }
public func week() -> NSDateComponents {
let components = NSDateComponents()
components.weekOfYear = self
return components
}
public func weeks() -> NSDateComponents { return self.week() }
public func month() -> NSDateComponents {
let components = NSDateComponents()
components.month = self
return components
}
public func months() -> NSDateComponents { return self.month() }
public func year() -> NSDateComponents {
let components = NSDateComponents()
components.year = self
return components
}
public func years() -> NSDateComponents { return self.year() }
public func second() -> NSDateComponents {
let components = NSDateComponents()
components.second = self
return components
}
public func seconds() -> NSDateComponents { return self.second() }
public func minute() -> NSDateComponents {
let components = NSDateComponents()
components.minute = self
return components
}
public func minutes() -> NSDateComponents { return self.minute() }
public func hour() -> NSDateComponents {
let components = NSDateComponents()
components.hour = self
return components
}
public func hours() -> NSDateComponents { return self.hour() }
}
public func +(lhs: NSDate, rhs: NSDateComponents) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingComponents(rhs, toDate: lhs, options: nil) ?? lhs
}
public func -(lhs: NSDate, rhs: NSDateComponents) -> NSDate {
if rhs.era != Int(NSUndefinedDateComponent) { rhs.era *= -1 }
if rhs.year != Int(NSUndefinedDateComponent) { rhs.year *= -1 }
if rhs.month != Int(NSUndefinedDateComponent) { rhs.month *= -1 }
if rhs.day != Int(NSUndefinedDateComponent) { rhs.day *= -1 }
if rhs.hour != Int(NSUndefinedDateComponent) { rhs.hour *= -1 }
if rhs.minute != Int(NSUndefinedDateComponent) { rhs.minute *= -1 }
if rhs.second != Int(NSUndefinedDateComponent) { rhs.second *= -1 }
if rhs.nanosecond != Int(NSUndefinedDateComponent) { rhs.nanosecond *= -1 }
if rhs.weekday != Int(NSUndefinedDateComponent) { rhs.weekday *= -1 }
if rhs.weekdayOrdinal != Int(NSUndefinedDateComponent) { rhs.weekdayOrdinal *= -1 }
if rhs.quarter != Int(NSUndefinedDateComponent) { rhs.quarter *= -1 }
if rhs.weekOfMonth != Int(NSUndefinedDateComponent) { rhs.weekOfMonth *= -1 }
if rhs.weekOfYear != Int(NSUndefinedDateComponent) { rhs.weekOfYear *= -1 }
if rhs.yearForWeekOfYear != Int(NSUndefinedDateComponent) { rhs.yearForWeekOfYear *= -1 }
return NSCalendar.currentCalendar().dateByAddingComponents(rhs, toDate: lhs, options: nil) ?? lhs
} | f6033c9884ca500edbd6f0e60c204a40 | 34.13253 | 98 | 0.715266 | false | false | false | false |
JohnCoates/Aerial | refs/heads/master | Aerial/Source/Views/PrefPanel/InfoClockView.swift | mit | 1 | //
// InfoClockView.swift
// Aerial
//
// Created by Guillaume Louel on 18/12/2019.
// Copyright © 2019 Guillaume Louel. All rights reserved.
//
import Cocoa
class InfoClockView: NSView {
@IBOutlet var secondsCheckbox: NSButton!
@IBOutlet var hideAmPmCheckbox: NSButton!
@IBOutlet var clockFormat: NSPopUpButton!
@IBOutlet var customTimeFormatField: NSTextField!
// Init(ish)
func setStates() {
secondsCheckbox.state = PrefsInfo.clock.showSeconds ? .on : .off
hideAmPmCheckbox.state = PrefsInfo.clock.hideAmPm ? .on : .off
clockFormat.selectItem(at: PrefsInfo.clock.clockFormat.rawValue)
customTimeFormatField.stringValue = PrefsInfo.customTimeFormat
updateAmPmCheckbox()
}
@IBAction func secondsClick(_ sender: NSButton) {
let onState = sender.state == .on
PrefsInfo.clock.showSeconds = onState
}
@IBAction func hideAmPmCheckboxClick(_ sender: NSButton) {
let onState = sender.state == .on
PrefsInfo.clock.hideAmPm = onState
}
@IBAction func clockFormatChange(_ sender: NSPopUpButton) {
PrefsInfo.clock.clockFormat = InfoClockFormat(rawValue: sender.indexOfSelectedItem)!
updateAmPmCheckbox()
}
// Update the 12/24hr visibility
func updateAmPmCheckbox() {
switch PrefsInfo.clock.clockFormat {
case .tdefault:
hideAmPmCheckbox.isHidden = false // meh
secondsCheckbox.isHidden = false
case .t12hours:
hideAmPmCheckbox.isHidden = false
secondsCheckbox.isHidden = false
case .t24hours:
hideAmPmCheckbox.isHidden = true
secondsCheckbox.isHidden = false
case .custom:
hideAmPmCheckbox.isHidden = true
secondsCheckbox.isHidden = true
}
customTimeFormatField.isHidden = !(PrefsInfo.clock.clockFormat == .custom)
}
@IBAction func customTimeFormatFieldChange(_ sender: NSTextField) {
PrefsInfo.customTimeFormat = sender.stringValue
}
}
| e098fee1b5950345d060b84bca9d46b1 | 30.257576 | 92 | 0.665536 | false | false | false | false |
liufengting/FTChatMessageDemoProject | refs/heads/master | FTChatMessage/FTChatMessageInput/FTChatMessageInputView.swift | mit | 1 | //
// FTChatMessageInputView.swift
// FTChatMessage
//
// Created by liufengting on 16/3/22.
// Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved.
//
import UIKit
enum FTChatMessageInputMode {
case keyboard
case record
case accessory
case none
}
protocol FTChatMessageInputViewDelegate {
func ft_chatMessageInputViewShouldBeginEditing()
func ft_chatMessageInputViewShouldEndEditing()
func ft_chatMessageInputViewShouldUpdateHeight(_ desiredHeight : CGFloat)
func ft_chatMessageInputViewShouldDoneWithText(_ textString : String)
func ft_chatMessageInputViewShouldShowRecordView()
func ft_chatMessageInputViewShouldShowAccessoryView()
}
class FTChatMessageInputView: UIToolbar, UITextViewDelegate{
var inputDelegate : FTChatMessageInputViewDelegate?
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var inputTextView: UITextView!
@IBOutlet weak var accessoryButton: UIButton!
@IBOutlet weak var inputTextViewTopMargin: NSLayoutConstraint! {
didSet {
self.layoutIfNeeded()
}
}
@IBOutlet weak var inputTextViewBottomMargin: NSLayoutConstraint! {
didSet {
self.layoutIfNeeded()
}
}
//MARK: - awakeFromNib -
override func awakeFromNib() {
super.awakeFromNib()
inputTextView.layer.cornerRadius = FTDefaultInputViewTextCornerRadius
inputTextView.layer.borderColor = UIColor.lightGray.cgColor
inputTextView.layer.borderWidth = 0.5
inputTextView.textContainerInset = FTDefaultInputTextViewEdgeInset
inputTextView.delegate = self
}
//MARK: - layoutSubviews -
override func layoutSubviews() {
super.layoutSubviews()
if self.inputTextView.attributedText.length > 0 {
self.inputTextView.scrollRangeToVisible(NSMakeRange(self.inputTextView.attributedText.length - 1, 1))
}
}
//MARK: - recordButtonTapped -
@IBAction func recordButtonTapped(_ sender: UIButton) {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldShowRecordView()
}
}
//MARK: - accessoryButtonTapped -
@IBAction func accessoryButtonTapped(_ sender: UIButton) {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldShowAccessoryView()
}
}
//MARK: - clearText -
func clearText(){
inputTextView.text = ""
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldUpdateHeight(FTDefaultInputViewHeight)
}
}
//MARK: - UITextViewDelegate -
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldBeginEditing()
}
return true
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldEndEditing()
}
return true
}
func textViewDidChange(_ textView: UITextView) {
if let text : NSAttributedString = textView.attributedText {
let textRect = text.boundingRect(with: CGSize(width: textView.bounds.width - textView.textContainerInset.left - textView.textContainerInset.right, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin , .usesFontLeading], context: nil);
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldUpdateHeight(min(max(textRect.height + inputTextViewTopMargin.constant + inputTextViewBottomMargin.constant + textView.textContainerInset.top + textView.textContainerInset.bottom, FTDefaultInputViewHeight), FTDefaultInputViewMaxHeight))
}
}
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n") {
if (textView.text as NSString).length > 0 {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldDoneWithText(textView.text)
self.clearText()
}
}
return false
}
return true
}
}
| fe0095f9efa66351256a9320c20f42ec | 33.674603 | 296 | 0.670405 | false | false | false | false |
yzyzsun/CurriculaTable | refs/heads/master | CurriculaTable/CurriculaTableController.swift | mit | 1 | //
// CurriculaTableController.swift
// CurriculaTable
//
// Created by Sun Yaozhu on 2016-09-10.
// Copyright © 2016 Sun Yaozhu. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class CurriculaTableController: UIViewController {
weak var curriculaTable: CurriculaTable!
weak var collectionView: UICollectionView! {
didSet {
collectionView.register(CurriculaTableCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
}
}
extension CurriculaTableController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (curriculaTable.numberOfPeriods + 1) * 8
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CurriculaTableCell
cell.backgroundColor = curriculaTable.symbolsBgColor
cell.layer.borderWidth = curriculaTable.borderWidth
cell.layer.borderColor = curriculaTable.borderColor.cgColor
cell.textLabel.font = UIFont.systemFont(ofSize: curriculaTable.symbolsFontSize)
if indexPath.row == 0 {
cell.textLabel.text = ""
} else if indexPath.row < 8 {
cell.textLabel.text = curriculaTable.weekdaySymbols[indexPath.row - 1]
} else if indexPath.row % 8 == 0 {
cell.textLabel.text = String(indexPath.row / 8)
} else {
cell.textLabel.text = ""
cell.backgroundColor = UIColor.clear
}
return cell
}
}
extension CurriculaTableController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.row == 0 {
return CGSize(width: curriculaTable.widthOfPeriodSymbols, height: curriculaTable.heightOfWeekdaySymbols)
} else if indexPath.row < 8 {
return CGSize(width: curriculaTable.averageWidth, height: curriculaTable.heightOfWeekdaySymbols)
} else if indexPath.row % 8 == 0 {
return CGSize(width: curriculaTable.widthOfPeriodSymbols, height: curriculaTable.averageHeight)
} else {
return CGSize(width: curriculaTable.averageWidth, height: curriculaTable.averageHeight)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
| b354c2cdb6660d4f1f4a0be49ddfe78b | 38.932432 | 175 | 0.704569 | false | false | false | false |
herrkaefer/CaseAssistant | refs/heads/master | CaseAssistant/PatientViewController.swift | mpl-2.0 | 1 | //
// PatientViewController.swift
// CaseAssistant
//
// Created by HerrKaefer on 15/4/23.
// Copyright (c) 2015年 HerrKaefer. All rights reserved.
//
import UIKit
import Photos
import MobileCoreServices
import QBImagePickerController
class PatientViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, QBImagePickerControllerDelegate
{
// MARK: - Variables
var patient: Patient? {
didSet {
loadData()
}
}
var records = [Record]()
var currentOperatedRecord: Record? // 当前正在操作(add photo, add voice memo, delete)的record
var imagePickerController: UIImagePickerController?
// var qbImagePickerController: QBImagePickerController?
var progressHUD: ProgressHUD!
// MARK: - IBOutlets
@IBOutlet weak var patientInfoLabel: UILabel!
@IBOutlet weak var patientDiagnosisLabel: UILabel!
@IBOutlet weak var tagsLabel: UILabel!
@IBOutlet weak var patientTableView: UITableView!
@IBOutlet weak var infoView: UIView! {
didSet {
let singleFingerTap = UITapGestureRecognizer(target: self, action: #selector(PatientViewController.handleSingleTapOnInfoView(_:)))
infoView.addGestureRecognizer(singleFingerTap)
}
}
@IBOutlet weak var starBarButtonItem: UIBarButtonItem!
// @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
// MARK: - Helper Functions
func loadData() {
records.removeAll()
records.append(contentsOf: patient!.recordsSortedDescending)
}
func updateInfoView() {
let name = patient!.g("name")
let gender = patient!.g("gender")
patientInfoLabel.text! = "\(name), \(gender), \(patient!.treatmentAge)岁"
if patient!.firstDiagnosis != nil {
patientDiagnosisLabel.text = "\(patient!.firstDiagnosis!)"
} else {
patientDiagnosisLabel.text = patient!.g("diagnosis")
}
let tagNames = patient!.tagNames
if tagNames.count > 0 {
tagsLabel.text! = " " + tagNames.joined(separator: " ") + " "
} else {
tagsLabel.text! = ""
}
tagsLabel.layer.cornerRadius = 3.0
tagsLabel.layer.masksToBounds = true
}
func updateStarBarButtonItemDisplay() {
if patient?.starred == true {
starBarButtonItem.image = UIImage(named: "star-29")
starBarButtonItem.tintColor = CaseApp.starredColor
} else {
starBarButtonItem.image = UIImage(named: "star-outline-29")
starBarButtonItem.tintColor = UIColor.white
}
}
func addLastPhotoInLibraryToPhotoMemo() {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if let lastAsset = fetchResult.lastObject {
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.resizeMode = .fast
PHImageManager.default().requestImage(for: lastAsset, targetSize: PhotoMemo.imageSize, contentMode: .aspectFit, options: options, resultHandler: { (image, info) -> Void in
let result = self.currentOperatedRecord!.addPhotoMemo(image!, creationDate: lastAsset.creationDate!, shouldScaleDown: false)
if result == true {
self.patientTableView.reloadData()
// 弹出保存成功提示
popupPrompt("照片已添加", inView: self.view)
} else {
popupPrompt("照片添加失败,请再试一次", inView: self.view)
}
})
}
}
func takeOrImportPhotoForRecord() {
if currentOperatedRecord == nil {
return
}
let alert = UIAlertController(
title: nil,
message: nil,
preferredStyle: .actionSheet
)
alert.addAction(UIAlertAction(
title: "相册中最新一张照片",
style: .default,
handler: {action in
// self.progressHUD.show()
self.addLastPhotoInLibraryToPhotoMemo()
// self.progressHUD.hide()
}
))
alert.addAction(UIAlertAction(
title: "拍摄照片",
style: .default,
handler: {action in
if self.imagePickerController != nil {
self.present(self.imagePickerController!, animated: true, completion: nil)
}
}
))
alert.addAction(UIAlertAction(
title: "从相册中选择",
style: .default,
handler: {action in
let qbImagePickerController = QBImagePickerController()
qbImagePickerController.mediaType = .image
qbImagePickerController.allowsMultipleSelection = true
qbImagePickerController.prompt = "选择照片(可多选)"
qbImagePickerController.showsNumberOfSelectedAssets = true
qbImagePickerController.delegate = self
self.present(qbImagePickerController, animated: true, completion: nil)
}
))
alert.addAction(UIAlertAction(
title: "取消",
style: .cancel,
handler: nil
))
alert.modalPresentationStyle = .popover
let ppc = alert.popoverPresentationController
ppc?.barButtonItem = starBarButtonItem
present(alert, animated: true, completion: nil)
}
// MARK: - IBActions
func handleSingleTapOnInfoView(_ gesture: UITapGestureRecognizer) {
performSegue(withIdentifier: "showPatientInfo", sender: self)
}
@IBAction func showMorePatientInfo(_ sender: UIButton) {
performSegue(withIdentifier: "showPatientInfo", sender: self)
}
@IBAction func starPatient(_ sender: UIBarButtonItem) {
patient!.toggleStar()
updateStarBarButtonItemDisplay()
}
// MARK: - QBImagePickerViewController Delegate
// 从相册多选时使用
func qb_imagePickerController(_ imagePickerController: QBImagePickerController!, didFinishPickingAssets assets: [Any]!) {
// activityIndicatorView.startAnimating()
progressHUD.show()
var addCnt: Int = 0
var gotCnt: Int = 0
// save images
for asset in (assets as! [PHAsset]) {
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.resizeMode = .fast
PHImageManager.default().requestImage(
for: asset,
targetSize: PhotoMemo.imageSize,
contentMode: .aspectFit,
options: options,
resultHandler: { (image, info) -> Void in
gotCnt += 1
let result = self.currentOperatedRecord!.addPhotoMemo(image!, creationDate: asset.creationDate!, shouldScaleDown: false)
if result == true {
addCnt += 1
}
if gotCnt == assets.count {
self.patientTableView.reloadData()
// self.activityIndicatorView.stopAnimating()
self.progressHUD.hide()
popupPrompt("\(addCnt)张照片已添加", inView: self.view)
}
})
}
imagePickerController.dismiss(animated: true, completion: nil)
}
func qb_imagePickerControllerDidCancel(_ imagePickerController: QBImagePickerController!) {
imagePickerController.dismiss(animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate
// 使用相机拍摄照片时使用
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var result = false
var image = info[UIImagePickerControllerEditedImage] as? UIImage
if image == nil {
image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
if image != nil {
result = currentOperatedRecord!.addPhotoMemo(image!, creationDate: Date(), shouldScaleDown: true)
if result == true {
// also save photo to camera roll
if picker.sourceType == .camera {
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}
}
} else {
result = false
}
var message: String
if result == true {
message = "照片已添加"
} else {
message = "照片添加失败,请再次尝试"
}
picker.dismiss(animated: true, completion: {popupPrompt(message, inView: self.view)})
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
// MARK: - ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
patientTableView.rowHeight = 58
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController = UIImagePickerController()
imagePickerController!.sourceType = .camera
imagePickerController!.mediaTypes = [kUTTypeImage as String]
imagePickerController!.allowsEditing = false // 如果允许编辑,总是得到正方形照片
imagePickerController!.delegate = self
}
progressHUD = ProgressHUD(text: "照片添加中")
self.view.addSubview(progressHUD)
progressHUD.hide()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
title = "" + patient!.g("name")
loadData()
updateInfoView()
updateStarBarButtonItemDisplay()
patientTableView.reloadData()
}
// MARK: - TableView Data Source
func numberOfSections(in tableView: UITableView) -> Int {
return 2 // records + summary (行医心得)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return records.count
case 1:
return 1
default:
return 0
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
if patient != nil {
let cnt = records.count
return cnt > 0 ? "\(cnt)次就诊记录" : "尚无就诊记录"
} else {
return ""
}
default:
return ""
}
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 0 && records.count > 0 {
return "左滑可以删除记录或快速添加照片"
} else {
return ""
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 { // records
// use SWTableViewCell
let cell = patientTableView.dequeueReusableCell(withIdentifier: "recordCell", for: indexPath) as! RecordTableViewCell
let r = records[indexPath.row]
cell.titleLabel.text = DateFormatter.localizedString(from: r.date as Date, dateStyle: .medium, timeStyle: .none)
var detailText = ""
if indexPath.row == records.count-1 {
detailText += "首诊"
} else {
detailText += "首诊后\(r.daysAfterFirstTreatment)天"
}
if let daysAfterLastOp = r.daysAfterLastOperation {
if daysAfterLastOp == 0 {
detailText += ",当天手术"
} else {
detailText += ",术后\(daysAfterLastOp)天"
}
}
cell.subtitleLabel.text = detailText
if r.photoMemos.count > 0 {
cell.photoMemoStatusImageView.image = UIImage(named: "image-20")
} else {
cell.photoMemoStatusImageView.image = nil
}
return cell
} else { // summary
let cell = patientTableView.dequeueReusableCell(withIdentifier: "summaryCell", for: indexPath)
return cell
}
}
// MARK: - TabelView Delegate
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 0 {
return true
} else {
return false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
// 实现Swipe Cell的多个Control:使用Apple内置方法 (>iOS 8.0).
// 需要实现两个delegate:commitEditingStyle和editActionsForRowAtIndexPath
// 放弃SWTableViewCell因为显示太多layout warnings
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
if indexPath.section == 0 { // record
currentOperatedRecord = records[indexPath.row]
// 添加照片
let cameraAction = UITableViewRowAction(style: .normal, title: "添加照片") { (action, indexPath) -> Void in
self.takeOrImportPhotoForRecord()
}
cameraAction.backgroundColor = UIColor.gray
// shareAction.backgroundColor = UIColor(patternImage: UIImage(named:"star-toolbar")!)
// 删除记录
let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "删除") { (action, indexPath) -> Void in
let alert = UIAlertController(
title: nil,
message: nil,
preferredStyle: .actionSheet
)
alert.addAction(UIAlertAction(
title: "删除检查记录",
style: .destructive,
handler: { (action) -> Void in
// print("deleting record with id: \(self.currentOperatedRecord!.date)")
self.currentOperatedRecord!.removeFromDB()
print("record deleted")
self.loadData()
self.patientTableView.reloadData()
}
))
alert.addAction(UIAlertAction(
title: "取消",
style: .cancel,
handler: nil
))
self.present(alert, animated: true, completion: nil)
}
deleteAction.backgroundColor = UIColor.red
return [deleteAction, cameraAction]
} else {
return []
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch identifier {
case "showRecord":
let cell = sender as! UITableViewCell
if let indexPath = patientTableView.indexPath(for: cell) {
let recordVC = segue.destination as! RecordTableViewController
recordVC.setShowRecord(records[indexPath.row])
}
case "addRecord":
if patient != nil {
let recordVC = segue.destination as! RecordTableViewController
recordVC.setNewRecord(patient!)
}
case "showSummary":
if patient != nil {
let patientSummaryVC = segue.destination as! PatientSummaryViewController
patientSummaryVC.patient = patient!
}
case "showPatientInfo":
let patientInfoVC = segue.destination as! PatientInfoTableViewController
patientInfoVC.setShowPatient(patient!)
case "showChart":
let chartVC = segue.destination as! ChartViewController
chartVC.patient = self.patient
case "showReport":
let reportVC = segue.destination as! ReportViewController
reportVC.patient = self.patient
default: break
}
}
}
}
| ea91734f24b22b05fa5bae641ed78ddb | 34.295597 | 187 | 0.561654 | false | false | false | false |
tensorflow/examples | refs/heads/master | lite/examples/classification_by_retrieval/ios/ImageClassifierBuilder/ModelTrainer.swift | apache-2.0 | 1 | // Copyright 2021 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Photos
import ios_ImageClassifierBuilderLibObjC
struct ModelTrainer {
/// Trains a new classification model based on user-selected Photos Library albums. Every image is
/// labeled after its album name.
///
/// - Parameters:
/// - metadata: The metadata of the model to create.
/// - albums: The user-selected Photos Library albums.
/// - Returns: The Model object associated to the newly trained TFLite model.
func trainModel(metadata: ModelMetadata, on albums: [Album]) -> Model {
precondition(metadata.isValid)
precondition(!albums.isEmpty)
// Copy all images to a reasonable format in tmp.
let (labels, imagePaths) = prepareImages(from: albums)
// Create the file URL where the new model will be saved.
let modelURL = Model.makeURLForNewModel(named: metadata.name)
// Train the model.
ModelTrainingUtils.trainModel(
name: metadata.name, description: metadata.description, author: metadata.author,
version: metadata.version, license: metadata.license, labels: labels, imagePaths: imagePaths,
outputModelPath: modelURL.path)
// Get the number of distinct labels in the labelmap.
let labelsCount = Classifier(modelURL: modelURL).labels().count
let size = (try? modelURL.resourceValues(forKeys: [.fileSizeKey]))?.fileSize.map(Int64.init)
return Model(name: metadata.name, labelsCount: labelsCount, size: size)
}
/// Converts albums to a list of labels (the albums names, repeated as many times as there are
/// images in it) and an equally long list of image paths on disk (typically prepared copies
/// stored in the tmp directory).
///
/// - Parameter albums: The user-selected Photos Library albums.
/// - Returns: The pair of lists of labels and image paths on disk.
private func prepareImages(from albums: [Album]) -> (labels: [String], imagePaths: [String]) {
var labels: [String] = []
var imagePaths: [String] = []
let dispatchGroup = DispatchGroup()
for album in albums {
// Iterate over the images.
let fetchResult = PHAsset.fetchAssets(in: album.collection, options: nil)
fetchResult.enumerateObjects { (asset, index, stop) in
guard asset.mediaType == .image else { return }
// Get the image URL.
dispatchGroup.enter()
asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) {
(input, _) in
defer { dispatchGroup.leave() }
guard let input = input,
let imageURLInLibrary = input.fullSizeImageURL,
let label = album.collection.localizedTitle
else {
return
}
// Copy the image as resized JPEG to the temporary directory.
let tmpDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
let options = PHImageRequestOptions()
options.isSynchronous = true
dispatchGroup.enter()
PHImageManager.default().requestImage(
for: asset, targetSize: CGSize(width: 640, height: 480), contentMode: .aspectFill,
options: options
) { (image, _) in
defer { dispatchGroup.leave() }
if let data = image?.jpegData(compressionQuality: 1) {
var imageURL =
tmpDirectory.appendingPathComponent(imageURLInLibrary.lastPathComponent)
imageURL.deletePathExtension()
imageURL.appendPathExtension(for: .jpeg)
do {
try data.write(to: imageURL, options: .atomic)
} catch {
fatalError("Couldn't save training image to \(imageURL): \(error)")
}
labels.append(label)
imagePaths.append(imageURL.path)
}
}
}
}
}
dispatchGroup.wait()
return (labels, imagePaths)
}
}
| 987c8e413ee8b283940c6dfd3a10bd9d | 40.953271 | 100 | 0.663399 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Extensions/DateExtension.swift | mit | 1 | //
// DateExtension.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/11/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
extension Date {
public static func dateFromInterval(_ interval: Double) -> Date? {
return Date(timeIntervalSince1970: interval / 1000)
}
public static func intervalFromDate(_ date: Date) -> Double {
return date.timeIntervalSince1970 * 1000
}
var weekday: String {
return self.formatted("EEE")
}
var day: String {
return self.formatted("dd")
}
var month: String {
return self.formatted("MM")
}
var monthString: String {
return self.formatted("MMMM")
}
var year: String {
return self.formatted("YYYY")
}
func formatted(_ format: String = "dd/MM/yyyy HH:mm:ss ZZZ") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
var dayOfWeek: Int {
let calendar = NSCalendar.current
let comp: DateComponents = (calendar as NSCalendar).components(.weekday, from: self)
return comp.weekday ?? -1
}
}
| a816de929be5f2c1afbe70c0b5e8439a | 21.867925 | 92 | 0.619637 | false | false | false | false |
nickqiao/NKBill | refs/heads/master | NKBill/Controller/NKTabBarController.swift | apache-2.0 | 1 | //
// NKBaseTabBarController.swift
// NKBill
//
// Created by nick on 16/1/30.
// Copyright © 2016年 NickChen. All rights reserved.
//
import UIKit
class NKTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.delegate = self
self.tabBar.items![0].selectedImage = UIImage(named: "index")
}
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
if item.title == "记一笔" {
performSegueWithIdentifier("compose", sender: nil)
}
}
}
extension NKTabBarController: UITabBarControllerDelegate {
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
if viewController == tabBarController.viewControllers![2] {
return false
}else {
return true
}
}
}
| 62a501ce610bd479221485c0f97b964a | 22.465116 | 134 | 0.635282 | false | false | false | false |
dps923/winter2017 | refs/heads/edits | notes/week_11/WhereAmI/Classes/MyLocation.swift | mit | 2 | //
// MyLocation.swift
// Location
//
// Copyright (c) 2017 School of ICT, Seneca College. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class Pin: NSObject, MKAnnotation {
let _coordinate: CLLocationCoordinate2D
init(coordinate: CLLocationCoordinate2D) {
self._coordinate = coordinate
super.init()
}
public var coordinate: CLLocationCoordinate2D {
return _coordinate
}
public var title: String? {
return "location"
}
public var subtitle: String? {
return "subtitle"
}
}
class MyLocation: UIViewController {
var lm: CLLocationManager!
// MARK: - User interface
@IBOutlet weak var toggleLocationButton: UIButton!
@IBOutlet weak var latitude: UILabel!
@IBOutlet weak var longitude: UILabel!
@IBOutlet weak var myMap: MKMapView!
// MARK: - UI interactions
@IBAction func toggleLocation(_ sender: UIButton) {
if myMap.showsUserLocation {
lm.stopUpdatingLocation()
} else {
lm.startUpdatingLocation()
}
myMap.showsUserLocation = !myMap.showsUserLocation
}
@IBAction func onPinDrop(_ sender: UIButton) {
let pin = Pin(coordinate: myMap.centerCoordinate)
myMap.addAnnotation(pin)
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.configureLocationObjects()
}
fileprivate func configureLocationObjects() {
myMap.delegate = self
// Initialize and configure the location manager
lm = CLLocationManager()
lm.delegate = self
// Change these values to affect the update frequency
lm.distanceFilter = 100
lm.desiredAccuracy = kCLLocationAccuracyHundredMeters
lm.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
print("Location services enabled\n")
lm.startUpdatingLocation()
myMap.showsUserLocation = true
}
}
}
extension MyLocation : CLLocationManagerDelegate {
// CLLocationManagerDelegate has many methods, all are optional.
// We only need these three.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
manager.startUpdatingLocation()
myMap.showsUserLocation = true
} else {
print("User didn't authorize location services, status: \(status)")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Most recent location is the last item in the 'locations' array
// The array has CLLocation objects, 'coordinate' property has lat and long
// Other properties are 'altitude' and 'timestamp'
if let l = locations.last {
// Display the latitude and longitude
latitude.text = "Lat: \(l.coordinate.latitude)"
longitude.text = "Long: \(l.coordinate.longitude)"
print("location update \(latitude.text!) \(longitude.text!)")
// When the map first loads, it is zoomed out to show country or world level, let's detect that
// and zoom in to 2km x 2km
let kmPerDegreeLat = 111.325 // roughly!
let maxKmSpanToShow = 100.0
// If more than 100km from top-to-bottom is being shown, zoom in to 2km x 2km
if myMap.region.span.latitudeDelta * kmPerDegreeLat > maxKmSpanToShow {
// Set the display region of the map
myMap.setRegion(MKCoordinateRegionMakeWithDistance(l.coordinate, 2000, 2000), animated: true)
}
}
myMap.userTrackingMode = .follow
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error: \(error)")
let nserr = error as NSError
if nserr.domain == "kCLErrorDomain" && nserr.code == 0 {
print("(If you are in simulator: Go to Simulator app menu Debug>Location and enable a location.")
}
}
}
extension MyLocation: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotationView")
annotationView.canShowCallout = true
annotationView.rightCalloutAccessoryView = UIButton.init(type: UIButtonType.detailDisclosure)
return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
guard let annotation = view.annotation else{
return
}
print("calloutAccessoryControlTapped: \(annotation.coordinate.latitude),\(annotation.coordinate.longitude)")
}
}
| 22a58e33cdc18fc45e476e94cf9218fb | 31.211538 | 129 | 0.649154 | false | false | false | false |
MilanNosal/InteractiveTransitioningContainer | refs/heads/master | InteractiveTransitioningContainer/InteractiveTransitioningContainerLayerBasedPercentDrivenInteractiveTransition.swift | mit | 1 | //
// InteractiveTransitioningContainerPercentDrivenInteractiveTransition.swift
// InteractiveTransitioningContainer
//
// Created by Milan Nosáľ on 22/01/2017.
// Copyright © 2017 Svagant. All rights reserved.
//
import UIKit
// Custom percent driven interactive transition object - should be inherited from when used with InteractiveTransitioningContainer
// I've had some problems with the original implementation of Alek Akstrom, so I use this slight modification
// This is NOT the recommended approach, left only for backward compatibility with animation
// controllers that do not provide interruptibleAnimator
// If it is possible, please use InteractiveTransitionContainerAnimatorBasedPercentDrivenInteractiveTransition instead
//
// Credits also to Alek Akstrom
// - http://www.iosnomad.com/blog/2014/5/12/interactive-custom-container-view-controller-transitions
public class InteractiveTransitionContainerLayerBasedPercentDrivenInteractiveTransition: InteractiveTransitionContainerPercentDrivenInteractiveTransition {
open override var percentComplete: CGFloat {
didSet {
let offset = TimeInterval(percentComplete * duration)
self.timeOffset = offset
}
}
// MARK: Internal fields
fileprivate var timeOffset: TimeInterval {
set {
transitionContext!.containerView.layer.timeOffset = newValue
}
get {
return transitionContext!.containerView.layer.timeOffset
}
}
fileprivate var displayLink: CADisplayLink?
open override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
guard state == .isInactive else {
return
}
super.startInteractiveTransition(transitionContext)
transitionContext.containerView.layer.speed = 0
self.animator!.animateTransition(using: transitionContext)
}
open override func cancelInteractiveTransition() {
guard state == .isInteracting else {
return
}
super.cancelInteractiveTransition()
self.completeTransition()
}
open override func finishInteractiveTransition() {
guard state == .isInteracting else {
return
}
super.finishInteractiveTransition()
self.completeTransition()
}
// MARK: Internal methods
fileprivate func completeTransition() {
displayLink = CADisplayLink(target: self, selector: #selector(InteractiveTransitionContainerLayerBasedPercentDrivenInteractiveTransition.tickAnimation))
displayLink!.add(to: RunLoop.main, forMode: .commonModes)
}
@objc fileprivate func tickAnimation() {
var timeOffset = self.timeOffset
let tick = displayLink!.duration * CFTimeInterval(self.completionSpeed)
timeOffset = timeOffset + (transitionContext!.transitionWasCancelled ? -tick : tick)
if timeOffset < 0 || timeOffset > TimeInterval(self.duration) {
self.transitionFinished()
} else {
self.timeOffset = timeOffset
}
}
fileprivate func transitionFinished() {
displayLink!.invalidate()
let layer = transitionContext!.containerView.layer
layer.speed = 1
if transitionContext!.transitionWasCancelled {
// TODO: Test for glitch
} else {
layer.timeOffset = 0
layer.beginTime = 0
}
super.interactiveTransitionCompleted()
}
}
| ae3829182678e9bcd710d9c80b485825 | 34.176471 | 160 | 0.683389 | false | false | false | false |
NoodleOfDeath/PastaParser | refs/heads/master | runtime/swift/Example/GrammarKit_Tests/SampleTests.swift | mit | 1 | //
// GrammarKit
//
// Copyright © 2020 NoodleOfDeath. All rights reserved.
//
import XCTest
import SwiftyUTType
import GrammarKit
/// Runs GrammarLooder and GrammaticalScanner tests.
class SampleTests: XCTestCase {
var resourcePath: String = ""
var grammarsDirectory: String { return resourcePath +/ "grammars" }
var samplesDirectory: String { return resourcePath +/ "samples" }
lazy var grammarLoader: GrammarLoader = GrammarLoader(searchPaths: grammarsDirectory)
enum Expectation: String {
case lexerRuleCount
}
override func setUp() {
super.setUp()
guard let resourcePath = Bundle(for: type(of: self)).resourcePath else { XCTFail(); return }
self.resourcePath = resourcePath
}
func testXML() {
test(sample: "Sample.xml", expectations: [
.lexerRuleCount: 18,
])
}
func testHTML() {
test(sample: "Sample.html", expectations: [
.lexerRuleCount: 18,
])
}
func testSwift() {
test(sample: "Sample.swift", expectations: [
.lexerRuleCount: 48,
])
}
func testJava() {
test(sample: "Sample.java", expectations: [
.lexerRuleCount: 44,
])
}
fileprivate func test(sample: String, expectations: [Expectation: Any] = [:]) {
let sampleFile = samplesDirectory +/ sample
do {
print("----- Testing \(sampleFile.fileURL.uttype.rawValue) -----")
guard let grammar = grammarLoader.loadGrammar(for: sampleFile.fileURL.uttype.rawValue) else { XCTFail(); return }
//print(grammar)
print("------------")
let text = try String(contentsOfFile: sampleFile)
// Run GrammarLoader tests.
XCTAssertEqual(expectations[.lexerRuleCount] as? Int, grammar.lexerRules.count)
// Run ExampleScanner tests.
let scanner = ExampleScanner(grammar: grammar)
scanner.scan(text)
} catch {
print(error)
XCTFail()
}
}
}
| 25829d04c48755b7bbd9c8b2ab4582ff | 25.782051 | 125 | 0.591671 | false | true | false | false |
weiyanwu84/MLSwiftBasic | refs/heads/master | MLSwiftBasic/Classes/Base/MBNavigationBarView.swift | mit | 1 | // github: https://github.com/MakeZL/MLSwiftBasic
// author: @email <[email protected]>
//
// MBNavigationBarView.swift
// MakeBolo
//
// Created by 张磊 on 15/6/22.
// Copyright (c) 2015年 MakeZL. All rights reserved.
//
import UIKit
protocol MBNavigationBarViewDelegate:NSObjectProtocol{
func goBack()
}
class MBNavigationBarView: UIView {
var titleImage,leftImage,rightImage:String!
var rightTitleBtns:NSMutableArray = NSMutableArray()
var delegate:MBNavigationBarViewDelegate!
var rightItemWidth:CGFloat{
set{
if (self.rightTitleBtns.count > 0 || self.rightImgs.count > 0) {
var count = self.rightTitleBtns.count ?? self.rightImgs.count
for (var i = 0; i < count; i++){
if var button = self.rightTitleBtns[i] as? UIButton ?? self.rightImgs[i] as? UIButton {
button.frame.size.width = newValue
var x = self.frame.size.width - newValue * CGFloat(i) - newValue
button.frame = CGRectMake(x, NAV_BAR_Y, newValue, NAV_BAR_HEIGHT) ;
}
}
}else {
self.rightButton.frame.size.width = newValue
self.rightButton.frame.origin.x = self.frame.size.width - newValue
}
}
get{
return self.rightItemWidth
}
}
var leftItemWidth:CGFloat {
set{
}
get{
return self.leftItemWidth
}
}
var title:String{
set {
self.titleButton.setTitle(newValue, forState: .Normal)
}
get {
if (self.titleButton.currentTitle != nil) {
return self.titleButton.currentTitle!
}else{
return ""
}
}
}
var leftStr:String{
set {
self.leftButton.setTitle(newValue, forState: .Normal)
}
get {
if (self.leftButton.currentTitle != nil) {
return self.leftButton.currentTitle!
}else{
return ""
}
}
}
var rightImgs:NSArray{
set{
var allImgs = newValue.reverseObjectEnumerator().allObjects
for (var i = 0; i < allImgs.count; i++){
var rightButton = UIButton.buttonWithType(.Custom) as! UIButton
rightButton.tag = i
rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
var x = self.frame.size.width - CGFloat(NAV_ITEM_RIGHT_W) * CGFloat(i) - NAV_ITEM_LEFT_W
rightButton.setImage(UIImage(named: allImgs[i] as! String), forState: .Normal)
rightButton.frame = CGRectMake(x, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ;
rightButton.titleLabel?.font = NAV_ITEM_FONT
self.addSubview(rightButton)
rightTitleBtns.addObject(rightButton)
}
if (newValue.count > 1){
self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + newValue.count))
}
}
get{
return ( rightTitleBtns != false && rightTitleBtns.count > 0) ? rightTitleBtns: []
}
}
var rightTitles:NSArray{
set{
for (var i = 0; i < newValue.count; i++){
var rightButton = UIButton.buttonWithType(.Custom) as! UIButton
rightButton.tag = i
rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
var x = self.frame.size.width - CGFloat(NAV_ITEM_LEFT_W) * CGFloat(i) - NAV_ITEM_RIGHT_W
rightButton.setTitle(newValue[i] as! NSString as String, forState: .Normal)
rightButton.frame = CGRectMake(x, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ;
rightButton.titleLabel?.font = NAV_ITEM_FONT
self.addSubview(rightButton)
self.rightTitleBtns.addObject(rightButton)
}
if (newValue.count > 1){
self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + newValue.count))
}
}
get{
return ( rightTitleBtns != false && rightTitleBtns.count > 0) ? rightTitleBtns: []
}
}
var rightStr:String{
set {
self.rightButton.setTitle(newValue, forState: .Normal)
}
get {
if (self.rightButton.currentTitle != nil) {
return self.rightButton.currentTitle!
}else{
return ""
}
}
}
lazy var titleButton:UIButton = {
var titleButton = UIButton.buttonWithType(.Custom) as! UIButton
titleButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
titleButton.frame = CGRectMake(NAV_ITEM_LEFT_W, NAV_BAR_Y, self.frame.size.width - NAV_ITEM_RIGHT_W - NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT);
if (self.rightTitles.count > 1){
titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + self.rightTitles.count))
titleButton.frame.origin.x = CGFloat(self.frame.size.width - titleButton.frame.size.width) * 0.5
}
titleButton.titleLabel?.font = NAV_TITLE_FONT
self.addSubview(titleButton)
return titleButton
}()
lazy var leftButton:UIButton = {
var leftButton = UIButton.buttonWithType(.Custom) as! UIButton
leftButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
leftButton.frame = CGRectMake(0, NAV_BAR_Y, NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT);
leftButton.titleLabel?.font = NAV_ITEM_FONT
self.addSubview(leftButton)
return leftButton
}()
lazy var rightButton:UIButton = {
var rightButton = UIButton.buttonWithType(.Custom) as! UIButton
rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
rightButton.frame = CGRectMake(self.frame.size.width - NAV_ITEM_RIGHT_W, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ;
rightButton.titleLabel?.font = NAV_ITEM_FONT
self.addSubview(rightButton)
return rightButton
}()
var back:Bool{
set{
if (newValue && (count(self.leftStr) <= 0 && self.leftStr.isEmpty)) {
var backBtn = UIButton.buttonWithType(.Custom) as! UIButton
backBtn.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
backBtn.setImage(UIImage(named: BACK_NAME), forState: .Normal)
backBtn.titleLabel!.textAlignment = .Left
backBtn.frame = CGRectMake(0, NAV_BAR_Y, NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT);
backBtn.addTarget(self, action:"goBack", forControlEvents: .TouchUpInside)
self.addSubview(backBtn)
}
}
get{
return self.back
}
}
func goBack(){
if self.delegate.respondsToSelector(Selector("goBack")) {
self.delegate.goBack()
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
required override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
func setup(){
}
} | 4b12047ec644d41bec3fe7e8d1da9b42 | 32.995536 | 143 | 0.548726 | false | false | false | false |
ProfileCreator/ProfileCreator | refs/heads/master | ProfileCreator/ProfileCreator/Profile Editor TableView CellViews/PayloadCellViewTableView.swift | mit | 1 | //
// TableCellViewTextField.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
import ProfilePayloads
class PayloadCellViewTableView: PayloadCellView, ProfileCreatorCellView, TableViewCellView {
// MARK: -
// MARK: Instance Variables
var scrollView: NSScrollView?
var tableView: NSTableView?
var progressIndicator = NSProgressIndicator()
var textFieldProgress = NSTextField()
var imageViewDragDrop = NSImageView()
var buttonImport: NSSegmentedControl?
var isImporting = false
var tableViewContent = [Any]()
var tableViewColumns = [PayloadSubkey]()
var tableViewContentSubkey: PayloadSubkey?
var tableViewContentType: PayloadValueType = .undefined
var valueDefault: Any?
let buttonAddRemove = NSSegmentedControl()
private var dragDropType = NSPasteboard.PasteboardType(rawValue: "private.table-row")
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(subkey: PayloadSubkey, payloadIndex: Int, enabled: Bool, required: Bool, editor: ProfileEditor) {
super.init(subkey: subkey, payloadIndex: payloadIndex, enabled: enabled, required: required, editor: editor)
// ---------------------------------------------------------------------
// Set Value Type
// ---------------------------------------------------------------------
if subkey.typeInput == .dictionary {
self.tableViewContentSubkey = subkey
} else if subkey.typeInput == .array {
self.tableViewContentSubkey = subkey.subkeys.first
}
self.tableViewContentType = self.tableViewContentSubkey?.type ?? .undefined
// ---------------------------------------------------------------------
// Setup Custom View Content
// ---------------------------------------------------------------------
self.scrollView = EditorTableView.scrollView(height: 100.0, constraints: &self.cellViewConstraints, target: self, cellView: self)
if let tableView = self.scrollView?.documentView as? NSTableView {
tableView.allowsMultipleSelection = true
tableView.registerForDraggedTypes([dragDropType])
self.tableView = tableView
}
self.setupScrollView()
// ---------------------------------------------------------------------
// Setup Table View Content
// ---------------------------------------------------------------------
if let aTableView = self.tableView {
self.setupContent(forTableView: aTableView, subkey: subkey)
}
// ---------------------------------------------------------------------
// Setup Button Add/Remove
// ---------------------------------------------------------------------
self.setupButtonAddRemove()
// ---------------------------------------------------------------------
// Setup Footer
// ---------------------------------------------------------------------
super.setupFooter(belowCustomView: self.buttonAddRemove)
// ---------------------------------------------------------------------
// Set Default Value
// ---------------------------------------------------------------------
if let valueDefault = subkey.defaultValue() {
self.valueDefault = valueDefault
}
// ---------------------------------------------------------------------
// Set Drag n Drop support
// ---------------------------------------------------------------------
if self.valueImportProcessor != nil {
self.tableView?.registerForDraggedTypes([.backwardsCompatibleFileURL])
self.setupButtonImport()
self.setupProgressIndicator()
self.setupTextFieldProgress()
self.setupImageViewDragDrop()
}
// ---------------------------------------------------------------------
// Set Value
// ---------------------------------------------------------------------
self.tableViewContent = self.getTableViewContent()
// ---------------------------------------------------------------------
// Setup KeyView Loop Items
// ---------------------------------------------------------------------
self.leadingKeyView = self.buttonAddRemove
self.trailingKeyView = self.buttonAddRemove
// ---------------------------------------------------------------------
// Activate Layout Constraints
// ---------------------------------------------------------------------
NSLayoutConstraint.activate(self.cellViewConstraints)
// ---------------------------------------------------------------------
// Reload TableView
// ---------------------------------------------------------------------
self.tableView?.reloadData()
}
private func getTableViewContent() -> [Any] {
var valueTableView: Any?
if let value = self.profile.settings.value(forSubkey: self.subkey, payloadIndex: self.payloadIndex) {
valueTableView = value
} else if let valueDefault = self.valueDefault {
valueTableView = valueDefault
}
if let value = valueTableView, let tableViewContent = self.tableViewContent(fromValue: value) {
return tableViewContent
} else {
return [Any]()
}
}
private func tableViewReloadData() {
self.tableViewContent = self.getTableViewContent()
self.tableView?.reloadData()
}
private func tableViewContent(fromValue value: Any) -> [Any]? {
if subkey.typeInput == .dictionary, let valueDict = value as? [String: Any] {
var newValueArray = [[String: Any]]()
if let subkeyKey = subkey.subkeys.first(where: { $0.key == ManifestKeyPlaceholder.key }), let subkeyValue = subkey.subkeys.first(where: { $0.key == ManifestKeyPlaceholder.value }) {
for (key, value) in valueDict {
var newValue = [String: Any]()
newValue[subkeyKey.key] = key
newValue[subkeyValue.key] = value
newValueArray.append(newValue)
}
}
return newValueArray
} else if subkey.typeInput == .array, let valueArray = value as? [Any] {
return valueArray
} else {
Log.shared.debug(message: "Input type: \(subkey.typeInput) is not currently handled by CellViewTableView", category: String(describing: self))
}
return nil
}
private func tableViewContentSave() {
switch self.subkey.type {
case .dictionary:
guard let tableViewContent = self.tableViewContent as? [[String: Any]] else {
return
}
var valueSave = [String: Any]()
for rowValue in tableViewContent {
let key = rowValue[ManifestKeyPlaceholder.key] as? String ?? ""
if let value = rowValue[ManifestKeyPlaceholder.value] {
valueSave[key] = value
}
}
self.profile.settings.setValue(valueSave, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
case .array:
self.profile.settings.setValue(self.tableViewContent, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
default:
Log.shared.debug(message: "Type: \(subkey.typeInput) is not currently handled by CellViewTableView", category: String(describing: self))
}
}
// MARK: -
// MARK: PayloadCellView Functions
override func enable(_ enable: Bool) {
self.isEnabled = enable
self.tableView?.isEnabled = enable
self.buttonAddRemove.isEnabled = enable
if let buttonImport = self.buttonImport {
buttonImport.isEnabled = enable
}
}
// MARK: -
// MARK: Button Actions
@objc private func clickedImport(_ segmentedControl: NSSegmentedControl) {
guard let window = self.window else { return }
// ---------------------------------------------------------------------
// Setup open dialog
// ---------------------------------------------------------------------
let openPanel = NSOpenPanel()
// FIXME: Should use the name from file import as the prompt
openPanel.prompt = NSLocalizedString("Select File", comment: "")
openPanel.canChooseFiles = true
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.allowsMultipleSelection = true
if let allowedFileTypes = subkey.allowedFileTypes {
openPanel.allowedFileTypes = allowedFileTypes
}
// ---------------------------------------------------------------------
// Get open dialog allowed file types
// ---------------------------------------------------------------------
if let allowedFileTypes = self.subkey.allowedFileTypes {
openPanel.allowedFileTypes = allowedFileTypes
}
openPanel.beginSheetModal(for: window) { response in
if response == .OK {
_ = self.importURLs(openPanel.urls)
}
}
}
@objc private func clicked(_ segmentedControl: NSSegmentedControl) {
if segmentedControl.selectedSegment == 0 { // Add
self.addRow()
} else if segmentedControl.selectedSegment == 1 { // Remove
if let rowIndexes = self.tableView?.selectedRowIndexes {
self.removeRow(indexes: rowIndexes)
}
}
}
private func addRow() {
// Verify there isn't a limit on maximum number or items in the array.
if let repetitionMax = self.subkey.repetitionMax {
if repetitionMax <= self.tableViewContent.count {
// FIXME: This must be notified to the user
Log.shared.info(message: "Only \(repetitionMax) rows are allowd in the array for subkey: \(self.subkey.keyPath)", category: String(describing: self))
return
}
}
// Verify the values unique is set and if all values are already set
if self.tableViewContentType != .dictionary, self.tableViewContentSubkey?.valueUnique ?? false {
if let subkey = self.tableViewContentSubkey, let rangeList = subkey.rangeList, self.tableViewContent.contains(values: rangeList, ofType: subkey.type, sorted: true) {
Log.shared.info(message: "All supported values are already in the array, cannot create another row because values must be unique", category: String(describing: self))
return
}
}
var newRow: Any
if self.tableViewContentType == .dictionary {
var newRowDict = [String: Any]()
for tableViewColumn in self.tableViewColumns {
// Do not set a default value for keys that will copy their values
if tableViewColumn.valueCopy != nil || tableViewColumn.valueDefaultCopy != nil { continue }
let relativeKeyPath = tableViewColumn.valueKeyPath.deletingPrefix(self.subkey.valueKeyPath + ".")
guard let newRowValue = tableViewColumn.defaultValue() ?? PayloadUtility.emptyValue(valueType: tableViewColumn.type) else { continue }
newRowDict.setValue(value: newRowValue, forKeyPath: relativeKeyPath)
}
newRow = newRowDict
} else {
if let rangeList = self.tableViewContentSubkey?.rangeList, let newRowValue = rangeList.first(where: { !self.tableViewContent.containsAny(value: $0, ofType: self.tableViewContentType) }) {
newRow = newRowValue
} else {
guard let newRowValue = self.tableViewContentSubkey?.defaultValue() ?? PayloadUtility.emptyValue(valueType: self.tableViewContentType) else { return }
newRow = newRowValue
}
}
var newIndex: Int
if let index = self.tableView?.selectedRowIndexes.last, (index + 1) <= self.tableViewContent.count {
self.tableViewContent.insert(newRow, at: (index + 1))
newIndex = index + 1
} else {
self.tableViewContent.append(newRow)
newIndex = self.tableViewContent.count - 1
}
self.tableViewContentSave()
self.tableViewReloadData()
self.tableView?.selectRowIndexes(IndexSet(integer: newIndex), byExtendingSelection: false)
}
private func removeRow(indexes: IndexSet) {
guard 0 <= indexes.count, let indexMax = indexes.max(), indexMax < self.tableViewContent.count else {
Log.shared.error(message: "Index too large: \(String(describing: indexes.max())). self.tableViewContent.count: \(self.tableViewContent.count)", category: String(describing: self))
return
}
self.tableViewContent.remove(at: indexes)
self.tableView?.removeRows(at: indexes, withAnimation: .slideDown)
self.tableViewContentSave()
let rowCount = self.tableViewContent.count
if 0 < rowCount {
if indexMax < rowCount {
self.tableView?.selectRowIndexes(IndexSet(integer: indexMax), byExtendingSelection: false)
} else {
self.tableView?.selectRowIndexes(IndexSet(integer: (rowCount - 1)), byExtendingSelection: false)
}
}
}
private func tableColumn(forSubkey subkey: PayloadSubkey, profile: Profile) -> NSTableColumn {
let tableColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(subkey.keyPath))
tableColumn.isEditable = true
tableColumn.title = profile.settings.titleString(forSubkey: subkey)
tableColumn.headerToolTip = subkey.description
tableColumn.isHidden = profile.settings.showHiddenKeys ? false : subkey.hidden == .all
if subkey.type == .bool {
tableColumn.sizeToFit()
tableColumn.maxWidth = tableColumn.headerCell.cellSize.width + 1
tableColumn.minWidth = 17.0
}
return tableColumn
}
func setValue(_ value: Any?, forSubkey subkey: PayloadSubkey, row: Int) {
if self.subkey.type != .dictionary {
let subkeyValueKeyPath = PayloadUtility.expandKeyPath(subkey.valueKeyPath, withRootKeyPath: self.subkey.valueKeyPath + ".\(row)")
guard let newValue = value else { return }
self.profile.settings.setValue(newValue, forValueKeyPath: subkeyValueKeyPath, subkey: subkey, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: self.payloadIndex)
self.tableViewContent = self.getTableViewContent()
} else {
// ---------------------------------------------------------------------
// Get the current row settings
// ---------------------------------------------------------------------
var tableViewContent = self.tableViewContent
// ---------------------------------------------------------------------
// Update the current row settings
// ---------------------------------------------------------------------
var rowContent: Any?
if let newValue = value {
if self.tableViewContentType == .dictionary {
guard var rowContentDict = tableViewContent[row] as? [String: Any] else { return }
// Calculate relative key path and use KeyPath adding
let relativeKeyPath = subkey.valueKeyPath.deletingPrefix(self.subkey.valueKeyPath + ".")
rowContentDict.setValue(value: newValue, forKeyPath: relativeKeyPath)
rowContent = rowContentDict
} else {
rowContent = newValue
}
} else if self.tableViewContentType == .dictionary {
guard var rowContent = tableViewContent[row] as? [String: Any] else { return }
rowContent.removeValue(forKey: subkey.key)
} else {
rowContent = PayloadUtility.emptyValue(valueType: subkey.type)
}
guard let newRowContent = rowContent else { return }
tableViewContent[row] = newRowContent
// ---------------------------------------------------------------------
// Save the changes internally and to the payloadSettings
// ---------------------------------------------------------------------
self.tableViewContent = tableViewContent
self.tableViewContentSave()
}
}
func setupContent(forTableView tableView: NSTableView, subkey: PayloadSubkey) {
// FIXME: Highly temporary implementation
if let tableViewSubkey = self.tableViewContentSubkey {
if self.tableViewContentSubkey?.rangeList != nil {
let tableColumnReorder = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Reorder"))
tableColumnReorder.isEditable = false
tableColumnReorder.title = ""
tableColumnReorder.sizeToFit()
tableColumnReorder.maxWidth = 4.0
tableColumnReorder.minWidth = 4.0
tableView.addTableColumn(tableColumnReorder)
}
switch tableViewSubkey.typeInput {
case .dictionary:
if subkey.subkeys.contains(where: { $0.key == ManifestKeyPlaceholder.key }) {
var subkeys = [PayloadSubkey]()
if let subkeyKey = subkey.subkeys.first(where: { $0.key == ManifestKeyPlaceholder.key }) {
subkeys.append(subkeyKey)
}
if let subkeyValue = subkey.subkeys.first(where: { $0.key == ManifestKeyPlaceholder.value }) {
if subkeyValue.type == .dictionary, subkeyValue.hidden == .container {
subkeys.append(contentsOf: self.columnSubkeys(forSubkeys: subkeyValue.subkeys))
} else {
subkeys.append(subkeyValue)
}
}
for tableViewColumnSubkey in subkeys {
if !self.profile.settings.isAvailableForSelectedPlatform(subkey: tableViewColumnSubkey) { continue }
self.tableViewColumns.append(tableViewColumnSubkey)
// ---------------------------------------------------------------------
// Setup TableColumn
// ---------------------------------------------------------------------
tableView.addTableColumn(self.tableColumn(forSubkey: tableViewColumnSubkey, profile: self.profile))
}
} else {
for tableViewColumnSubkey in self.columnSubkeys(forSubkeys: tableViewSubkey.subkeys) {
if !profile.settings.isAvailableForSelectedPlatform(subkey: tableViewColumnSubkey) { continue }
self.tableViewColumns.append(tableViewColumnSubkey)
// ---------------------------------------------------------------------
// Setup TableColumn
// ---------------------------------------------------------------------
tableView.addTableColumn(self.tableColumn(forSubkey: tableViewColumnSubkey, profile: profile))
}
}
if tableViewSubkey.subkeys.count < 2 {
self.tableView?.headerView = nil
self.tableView?.toolTip = tableViewSubkey.subkeys.first?.description
}
case .array:
// FIXME: Handle arrays in arrays
for tableViewColumnSubkey in tableViewSubkey.subkeys where tableViewColumnSubkey.type == .array {
for nextSubkey in tableViewColumnSubkey.subkeys {
if !self.profile.settings.isAvailableForSelectedPlatform(subkey: nextSubkey) { continue }
self.tableViewColumns.append(nextSubkey)
// ---------------------------------------------------------------------
// Setup TableColumn
// ---------------------------------------------------------------------
tableView.addTableColumn(self.tableColumn(forSubkey: nextSubkey, profile: self.profile))
}
}
case .bool,
.string,
.integer:
if !self.profile.settings.isAvailableForSelectedPlatform(subkey: tableViewSubkey) { return }
self.tableViewColumns.append(tableViewSubkey)
// ---------------------------------------------------------------------
// Setup TableColumn
// ---------------------------------------------------------------------
tableView.addTableColumn(self.tableColumn(forSubkey: tableViewSubkey, profile: self.profile))
default:
Log.shared.error(message: "Unhandled PayloadValueType in TableView: \(tableViewSubkey.typeInput)", category: String(describing: self))
}
} else {
Log.shared.error(message: "Subkey: \(subkey.keyPath) subkey count is: \(subkey.subkeys.count). Only 1 subkey is currently supported", category: "")
}
self.tableView?.columnAutoresizingStyle = .uniformColumnAutoresizingStyle
}
private func columnSubkeys(forSubkeys subkeys: [PayloadSubkey]) -> [PayloadSubkey] {
var columnSubkeys = [PayloadSubkey]()
for subkey in subkeys {
if subkey.typeInput == .dictionary, subkey.hidden == .container {
columnSubkeys.append(contentsOf: self.columnSubkeys(forSubkeys: subkey.subkeys))
} else {
columnSubkeys.append(subkey)
}
}
return columnSubkeys
}
func rowValue(forColumnSubkey subkey: PayloadSubkey, row: Int) -> Any? {
let rowContent = self.tableViewContent[row]
var rowValue: Any?
if self.tableViewContentType == .dictionary, let rowContentDict = rowContent as? [String: Any] {
let relativeKeyPath = subkey.valueKeyPath.deletingPrefix(self.subkey.valueKeyPath + ".")
rowValue = rowContentDict.valueForKeyPath(keyPath: relativeKeyPath)
} else {
rowValue = rowContent
}
if let valueProcessorIdentifier = subkey.valueProcessor, let value = rowValue {
let valueProcessor = PayloadValueProcessors.shared.processor(withIdentifier: valueProcessorIdentifier, subkey: subkey, inputType: subkey.type, outputType: subkey.typeInput)
if let valueProcessed = valueProcessor.process(value: value) {
rowValue = valueProcessed
}
}
return rowValue
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard
let keyPath = menuItem.identifier?.rawValue,
let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == keyPath }) else {
// FIXME: Correct Error
return false
}
guard let selectedValue = PayloadUtility.value(forRangeListTitle: menuItem.title, subkey: tableColumnSubkey) else {
Log.shared.error(message: "Subkey: \(self.subkey.keyPath) Failed to get value for selected title: \(String(describing: menuItem.title)) ", category: String(describing: self))
return false
}
if menuItem.tag < self.tableViewContent.count, valueIsEqual(payloadValueType: tableColumnSubkey.type, a: selectedValue, b: self.tableViewContent[menuItem.tag]) {
return true
} else {
return !self.tableViewContent.containsAny(value: selectedValue, ofType: tableColumnSubkey.type)
}
}
}
// MARK: -
// MARK: EditorTableViewProtocol Functions
extension PayloadCellViewTableView: EditorTableViewProtocol {
@objc func select(_ menuItem: NSMenuItem) {
guard
let keyPath = menuItem.identifier?.rawValue,
let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == keyPath }) else {
// FIXME: Correct Error
return
}
guard let selectedValue = PayloadUtility.value(forRangeListTitle: menuItem.title, subkey: tableColumnSubkey) else {
Log.shared.error(message: "Subkey: \(self.subkey.keyPath) Failed to get value for selected title: \(String(describing: menuItem.title)) ", category: String(describing: self))
return
}
self.setValue(selectedValue, forSubkey: tableColumnSubkey, row: menuItem.tag)
}
@objc func selected(_ popUpButton: NSPopUpButton) {
guard
let keyPath = popUpButton.identifier?.rawValue,
let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == keyPath }) else {
// FIXME: Correct Error
return
}
guard let selectedTitle = popUpButton.titleOfSelectedItem,
let selectedValue = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: tableColumnSubkey) else {
Log.shared.error(message: "Subkey: \(self.subkey.keyPath) Failed to get value for selected title: \(String(describing: popUpButton.titleOfSelectedItem)) ", category: String(describing: self))
return
}
self.setValue(selectedValue, forSubkey: tableColumnSubkey, row: popUpButton.tag)
}
}
// MARK: -
// MARK: NSButton Functions
extension PayloadCellViewTableView {
@objc func buttonClicked(_ button: NSButton) {
// ---------------------------------------------------------------------
// Get all required objects
// ---------------------------------------------------------------------
guard
let keyPath = button.identifier?.rawValue,
let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == keyPath }) else {
// FIXME: Correct Error
return
}
self.setValue(button.state == .on ? true : false, forSubkey: tableColumnSubkey, row: button.tag)
}
}
// MARK: -
// MARK: NSTextFieldDelegate Functions
extension PayloadCellViewTableView {
internal func controlTextDidChange(_ notification: Notification) {
self.isEditing = true
if (notification.object as? NSComboBox) != nil {
self.saveCurrentComboBoxEdit(notification)
} else {
self.saveCurrentEdit(notification)
}
}
internal func controlTextDidEndEditing(_ notification: Notification) {
if self.isEditing {
self.isEditing = false
if (notification.object as? NSComboBox) != nil {
self.saveCurrentComboBoxEdit(notification)
} else {
self.saveCurrentEdit(notification)
}
}
}
private func saveCurrentEdit(_ notification: Notification) {
// ---------------------------------------------------------------------
// Verify we are editing and get the current value
// ---------------------------------------------------------------------
guard
let userInfo = notification.userInfo,
let fieldEditor = userInfo["NSFieldEditor"] as? NSTextView,
let stringValue = fieldEditor.textStorage?.string else { return }
// ---------------------------------------------------------------------
// Get the keyPath assigned the TextField being edited
// ---------------------------------------------------------------------
guard let textField = notification.object as? NSTextField, let keyPath = textField.identifier?.rawValue else { return }
// ---------------------------------------------------------------------
// Get the subkey using the keyPath assigned the TextField being edited
// ---------------------------------------------------------------------
guard let textFieldSubkey = ProfilePayloads.shared.payloadSubkey(forKeyPath: keyPath, domainIdentifier: self.subkey.domainIdentifier, type: self.subkey.payloadType) else {
Log.shared.error(message: "Found no subkey that matches TextField identifier keyPath: \(keyPath)", category: String(describing: self))
return
}
// ---------------------------------------------------------------------
// Set TextColor (red if not matching format)
// ---------------------------------------------------------------------
textField.highlighSubstrings(for: textFieldSubkey)
// ---------------------------------------------------------------------
// Update Value
// ---------------------------------------------------------------------
self.setValue(stringValue, forSubkey: textFieldSubkey, row: textField.tag)
}
private func saveCurrentComboBoxEdit(_ notification: Notification) {
guard let comboBox = notification.object as? NSComboBox, let keyPath = comboBox.identifier?.rawValue else { return }
guard let comboBoxSubkey = self.subkey.subkeys.first(where: { $0.keyPath == keyPath }) ?? self.subkey.subkeys.first(where: { $0.subkeys.contains(where: { $0.keyPath == keyPath }) }) else {
Log.shared.error(message: "Found no subkey that matches ComboBox identifier keyPath: \(keyPath)", category: String(describing: self))
return
}
if let selectedValue = comboBox.objectValue {
var newValue: Any?
if
comboBox.objectValues.contains(value: selectedValue, ofType: self.subkey.type),
let selectedTitle = selectedValue as? String,
let value = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: self.subkey) {
newValue = value
} else {
newValue = selectedValue
}
comboBox.highlighSubstrings(for: self.subkey)
self.setValue(newValue, forSubkey: comboBoxSubkey, row: comboBox.tag)
}
}
}
// MARK: -
// MARK: NSComboBoxDelegate Functions
extension PayloadCellViewTableView: NSComboBoxDelegate {
func comboBoxSelectionDidChange(_ notification: Notification) {
guard let comboBox = notification.object as? NSComboBox, let keyPath = comboBox.identifier?.rawValue else { return }
guard let comboBoxSubkey = self.subkey.subkeys.first(where: { $0.keyPath == keyPath }) ?? self.subkey.subkeys.first(where: { $0.subkeys.contains(where: { $0.keyPath == keyPath }) }) else {
Log.shared.error(message: "Found no subkey that matches ComboBox identifier keyPath: \(keyPath)", category: String(describing: self))
return
}
if let selectedValue = comboBox.objectValueOfSelectedItem {
var newValue: Any?
if
comboBox.objectValues.contains(value: selectedValue, ofType: self.subkey.type),
let selectedTitle = selectedValue as? String,
let value = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: self.subkey) {
newValue = value
} else {
newValue = selectedValue
}
comboBox.highlighSubstrings(for: self.subkey)
self.setValue(newValue, forSubkey: comboBoxSubkey, row: comboBox.tag)
}
}
}
// MARK: -
// MARK: NSTableViewDataSource Functions
extension PayloadCellViewTableView: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
self.tableViewContent.count
}
func allowedUTIs() -> [String]? {
var allowedUTIs = [String]()
guard let allowedFileTypes = self.allowedFileTypes else {
return nil
}
for type in allowedFileTypes {
if type.contains(".") {
allowedUTIs.append(type)
} else if let typeUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, "kext" as CFString, nil)?.takeUnretainedValue() as String? {
allowedUTIs.append(typeUTI)
}
}
return allowedUTIs
}
// -------------------------------------------------------------------------
// Drag/Drop Support
// -------------------------------------------------------------------------
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
let item = NSPasteboardItem()
item.setString(String(row), forType: self.dragDropType)
return item
}
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
guard !self.isImporting else { return NSDragOperation() }
if info.draggingPasteboard.availableType(from: [dragDropType]) != nil, dropOperation == .above {
return .move
} else if info.draggingPasteboard.availableType(from: [.backwardsCompatibleFileURL]) != nil {
if let allowedFileTypes = self.allowedUTIs() {
if info.draggingPasteboard.canReadObject(forClasses: [NSURL.self], options: [.urlReadingContentsConformToTypes: allowedFileTypes]) {
tableView.setDropRow(-1, dropOperation: .on)
return .copy
}
} else {
tableView.setDropRow(-1, dropOperation: .on)
return .copy
}
}
return NSDragOperation()
}
func importURLs(_ urls: [URL]) -> Bool {
guard let valueImportProcessor = self.valueImportProcessor else { return false }
self.isImporting = true
self.progressIndicator.startAnimation(self)
let dispatchQueue = DispatchQueue(label: "serial")
let dispatchGroup = DispatchGroup()
let dispatchSemaphore = DispatchSemaphore(value: 0)
dispatchQueue.async {
for url in urls {
dispatchGroup.enter()
DispatchQueue.main.async {
self.textFieldProgress.stringValue = "Processing \(url.lastPathComponent)…"
}
do {
try valueImportProcessor.addValue(forFile: url, toCurrentValue: self.tableViewContent, subkey: self.subkey, cellView: self) { updatedValue in
if let updatedTableViewContent = updatedValue as? [Any] {
self.tableViewContent = updatedTableViewContent
self.tableViewContentSave()
DispatchQueue.main.async {
self.tableView?.reloadData()
}
}
dispatchSemaphore.signal()
dispatchGroup.leave()
}
} catch {
DispatchQueue.main.async {
self.showAlert(withMessage: error.localizedDescription)
dispatchSemaphore.signal()
dispatchGroup.leave()
}
}
dispatchSemaphore.wait()
}
}
dispatchGroup.notify(queue: dispatchQueue) {
DispatchQueue.main.async {
self.isImporting = false
self.progressIndicator.stopAnimation(self)
self.textFieldProgress.stringValue = ""
self.tableViewReloadData()
}
}
return true
}
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
guard !self.isImporting else { return false }
if info.draggingPasteboard.availableType(from: [dragDropType]) != nil {
var oldIndexes = [Int]()
info.enumerateDraggingItems(options: [], for: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) { dragItem, _, _ in
// swiftlint:disable:next force_cast
if let str = (dragItem.item as! NSPasteboardItem).string(forType: self.dragDropType), let index = Int(str) {
oldIndexes.append(index)
}
}
var oldIndexOffset = 0
var rowsToMoveIndex = row
var rowsToMove = [Any]()
for oldIndex in oldIndexes {
rowsToMove.append(self.tableViewContent.remove(at: oldIndex + oldIndexOffset))
// Decrease the index for the next item by 1 each time one is removed as the indexes are in ascending order.
oldIndexOffset -= 1
if oldIndex < row {
rowsToMoveIndex -= 1
}
}
self.tableViewContent.insert(contentsOf: rowsToMove, at: rowsToMoveIndex)
self.tableViewContentSave()
self.tableViewReloadData()
return true
} else if let allowedFileTypes = self.allowedUTIs(), let urls = info.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingContentsConformToTypes: allowedFileTypes]) as? [URL] {
return self.importURLs(urls)
}
return false
}
}
// MARK: -
// MARK: NSTableViewDelegate Functions
extension PayloadCellViewTableView: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
21.0
}
func tableView(_ tableView: NSTableView, viewFor column: NSTableColumn?, row: Int) -> NSView? {
guard
row <= self.tableViewContent.count,
let tableColumn = column,
let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == tableColumn.identifier.rawValue }) else { return nil }
let rowValue = self.rowValue(forColumnSubkey: tableColumnSubkey, row: row)
if let rangeList = tableColumnSubkey.rangeList, rangeList.count <= ProfilePayloads.rangeListConvertMax {
if tableColumnSubkey.rangeListAllowCustomValue {
return EditorTableViewCellViewComboBox(cellView: self,
keyPath: tableColumnSubkey.keyPath,
value: rowValue,
subkey: tableColumnSubkey,
row: row)
} else {
return EditorTableViewCellViewPopUpButton(cellView: self,
keyPath: tableColumnSubkey.keyPath,
value: rowValue,
subkey: tableColumnSubkey,
row: row)
}
}
switch tableColumnSubkey.typeInput {
case .array:
return EditorTableViewCellViewArray(cellView: self,
subkey: tableColumnSubkey,
keyPath: tableColumnSubkey.keyPath,
value: rowValue as? [Any] ?? [Any](),
row: row)
case .bool:
return EditorTableViewCellViewCheckbox(cellView: self,
keyPath: tableColumnSubkey.keyPath,
value: rowValue as? Bool ?? false,
row: row)
case .integer:
return EditorTableViewCellViewTextFieldNumber(cellView: self,
keyPath: tableColumnSubkey.keyPath,
value: rowValue as? NSNumber,
placeholderValue: tableColumnSubkey.valuePlaceholder as? NSNumber,
type: tableColumnSubkey.type,
row: row)
case .string:
return EditorTableViewCellViewTextField(cellView: self,
keyPath: tableColumnSubkey.keyPath,
value: rowValue as? String,
placeholderString: tableColumnSubkey.valuePlaceholder as? String ?? tableColumn.title,
row: row)
default:
Log.shared.error(message: "Unknown TableColumn Subkey Type: \(tableColumnSubkey.type)", category: String(describing: self))
}
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
if let tableView = notification.object as? NSTableView {
self.buttonAddRemove.setEnabled((tableView.selectedRowIndexes.count) == 0 ? false : true, forSegment: 1)
}
}
}
// MARK: -
// MARK: Setup NSLayoutConstraints
extension PayloadCellViewTableView {
private func setupScrollView() {
guard let scrollView = self.scrollView else { return }
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Below
self.addConstraints(forViewBelow: scrollView)
// Leading
self.addConstraints(forViewLeading: scrollView)
// Trailing
self.addConstraints(forViewTrailing: scrollView)
}
private func setupProgressIndicator() {
self.progressIndicator.translatesAutoresizingMaskIntoConstraints = false
self.progressIndicator.style = .spinning
self.progressIndicator.controlSize = .small
self.progressIndicator.isIndeterminate = true
self.progressIndicator.isDisplayedWhenStopped = false
// ---------------------------------------------------------------------
// Add ProgressIndicator to TableCellView
// ---------------------------------------------------------------------
self.addSubview(self.progressIndicator)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Leading
self.cellViewConstraints.append(NSLayoutConstraint(item: self.progressIndicator,
attribute: .leading,
relatedBy: .equal,
toItem: self.buttonImport ?? self.buttonAddRemove,
attribute: .trailing,
multiplier: 1.0,
constant: 6.0))
// Center
self.cellViewConstraints.append(NSLayoutConstraint(item: self.buttonAddRemove,
attribute: .centerY,
relatedBy: .equal,
toItem: self.progressIndicator,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
}
private func setupImageViewDragDrop() {
self.imageViewDragDrop.translatesAutoresizingMaskIntoConstraints = false
self.imageViewDragDrop.image = NSImage(named: "DragDrop")
self.imageViewDragDrop.imageScaling = .scaleProportionallyUpOrDown
self.imageViewDragDrop.setContentHuggingPriority(.required, for: .horizontal)
self.imageViewDragDrop.toolTip = NSLocalizedString("This payload key supports Drag and Drop", comment: "")
self.imageViewDragDrop.isHidden = self.valueImportProcessor == nil
// ---------------------------------------------------------------------
// Add ImageView to TableCellView
// ---------------------------------------------------------------------
self.addSubview(self.imageViewDragDrop)
// Height
self.cellViewConstraints.append(NSLayoutConstraint(item: self.imageViewDragDrop,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 20.0))
// Width
self.cellViewConstraints.append(NSLayoutConstraint(item: self.imageViewDragDrop,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 30.0))
// Center
self.cellViewConstraints.append(NSLayoutConstraint(item: self.progressIndicator,
attribute: .centerY,
relatedBy: .equal,
toItem: self.imageViewDragDrop,
attribute: .centerY,
multiplier: 1.0,
constant: 2.0))
// Leading
self.cellViewConstraints.append(NSLayoutConstraint(item: self.imageViewDragDrop,
attribute: .leading,
relatedBy: .greaterThanOrEqual,
toItem: self.textFieldProgress,
attribute: .trailing,
multiplier: 1.0,
constant: 6.0))
// Trailing
self.cellViewConstraints.append(NSLayoutConstraint(item: self.imageViewDragDrop,
attribute: .trailing,
relatedBy: .equal,
toItem: self.scrollView,
attribute: .trailing,
multiplier: 1.0,
constant: 2.0))
}
private func setupTextFieldProgress() {
self.textFieldProgress.translatesAutoresizingMaskIntoConstraints = false
self.textFieldProgress.lineBreakMode = .byWordWrapping
self.textFieldProgress.isBordered = false
self.textFieldProgress.isBezeled = false
self.textFieldProgress.drawsBackground = false
self.textFieldProgress.isEditable = false
self.textFieldProgress.isSelectable = false
self.textFieldProgress.textColor = .secondaryLabelColor
self.textFieldProgress.font = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: .regular), weight: .regular)
self.textFieldProgress.preferredMaxLayoutWidth = kEditorTableViewColumnPayloadWidth
self.textFieldProgress.stringValue = ""
self.textFieldProgress.setContentHuggingPriority(.defaultLow, for: .horizontal)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.addSubview(self.textFieldProgress)
// Leading
self.cellViewConstraints.append(NSLayoutConstraint(item: self.textFieldProgress,
attribute: .leading,
relatedBy: .equal,
toItem: self.progressIndicator,
attribute: .trailing,
multiplier: 1.0,
constant: 6.0))
// Trailing
// self.addConstraints(forViewTrailing: self.textFieldProgress)
// Center
self.cellViewConstraints.append(NSLayoutConstraint(item: self.textFieldProgress,
attribute: .centerY,
relatedBy: .equal,
toItem: self.progressIndicator,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
}
private func setupButtonAddRemove() {
guard let scrollView = self.scrollView else { return }
self.buttonAddRemove.translatesAutoresizingMaskIntoConstraints = false
self.buttonAddRemove.segmentStyle = .roundRect
self.buttonAddRemove.segmentCount = 2
self.buttonAddRemove.trackingMode = .momentary
self.buttonAddRemove.setImage(NSImage(named: NSImage.addTemplateName), forSegment: 0)
self.buttonAddRemove.setImage(NSImage(named: NSImage.removeTemplateName), forSegment: 1)
self.buttonAddRemove.setEnabled(false, forSegment: 1)
self.buttonAddRemove.action = #selector(clicked(_:))
self.buttonAddRemove.target = self
// ---------------------------------------------------------------------
// Add Button to TableCellView
// ---------------------------------------------------------------------
self.addSubview(self.buttonAddRemove)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Leading
self.addConstraints(forViewLeading: self.buttonAddRemove)
// Top
self.cellViewConstraints.append(NSLayoutConstraint(item: self.buttonAddRemove,
attribute: .top,
relatedBy: .equal,
toItem: scrollView,
attribute: .bottom,
multiplier: 1.0,
constant: 8.0))
self.updateHeight((8 + self.buttonAddRemove.intrinsicContentSize.height))
}
private func setupButtonImport() {
let buttonImport = NSSegmentedControl()
buttonImport.translatesAutoresizingMaskIntoConstraints = false
buttonImport.segmentStyle = .roundRect
buttonImport.segmentCount = 1
buttonImport.trackingMode = .momentary
buttonImport.setLabel(NSLocalizedString("Import", comment: ""), forSegment: 0)
buttonImport.action = #selector(self.clickedImport(_:))
buttonImport.target = self
// ---------------------------------------------------------------------
// Add Button to TableCellView
// ---------------------------------------------------------------------
self.addSubview(buttonImport)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Center
self.cellViewConstraints.append(NSLayoutConstraint(item: self.buttonAddRemove,
attribute: .centerY,
relatedBy: .equal,
toItem: buttonImport,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
// Leading
self.cellViewConstraints.append(NSLayoutConstraint(item: buttonImport,
attribute: .leading,
relatedBy: .equal,
toItem: self.buttonAddRemove,
attribute: .trailing,
multiplier: 1.0,
constant: 6.0))
self.buttonImport = buttonImport
}
}
| ac8be5719124fcd136c3e168fae864c8 | 46.800175 | 214 | 0.506307 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/rank-transform-of-an-array.swift | mit | 2 | /**
* https://leetcode.com/problems/rank-transform-of-an-array/
*
*
*/
// Date: Mon Aug 9 16:53:13 PDT 2021
class Solution {
func arrayRankTransform(_ arr: [Int]) -> [Int] {
let sorted = arr.sorted()
var map: [Int : Int] = [:]
var rank = 1
for n in sorted {
if map[n] == nil {
map[n] = rank
rank += 1
}
}
var result = [Int]()
for n in arr {
result.append(map[n, default: -1])
}
return result
}
} | 04712f5137212fd85cbad2c9521c81c8 | 21.44 | 60 | 0.433929 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/Welcome/WelcomeReducer.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BlockchainNamespace
import Combine
import ComposableArchitecture
import ComposableNavigation
import DIKit
import FeatureAuthenticationDomain
import ToolKit
import WalletPayloadKit
// MARK: - Type
public enum WelcomeAction: Equatable, NavigationAction {
// MARK: - Start Up
case start
// MARK: - Deep link
case deeplinkReceived(URL)
// MARK: - Wallet
case requestedToCreateWallet(String, String)
case requestedToDecryptWallet(String)
case requestedToRestoreWallet(WalletRecovery)
// MARK: - Navigation
case route(RouteIntent<WelcomeRoute>?)
// MARK: - Local Action
case createWallet(CreateAccountStepOneAction)
case emailLogin(EmailLoginAction)
case restoreWallet(SeedPhraseAction)
case setManualPairingEnabled // should only be on internal build
case manualPairing(CredentialsAction) // should only be on internal build
case informSecondPasswordDetected
case informForWalletInitialization
case informWalletFetched(WalletFetchedContext)
case triggerAuthenticate // needed for legacy wallet flow
case triggerCancelAuthenticate // needed for legacy wallet flow
// MARK: - Utils
case none
}
// MARK: - Properties
/// The `master` `State` for the Single Sign On (SSO) Flow
public struct WelcomeState: Equatable, NavigationState {
public var buildVersion: String
public var route: RouteIntent<WelcomeRoute>?
public var createWalletState: CreateAccountStepOneState?
public var emailLoginState: EmailLoginState?
public var restoreWalletState: SeedPhraseState?
public var manualPairingEnabled: Bool
public var manualCredentialsState: CredentialsState?
public init() {
buildVersion = ""
route = nil
createWalletState = nil
restoreWalletState = nil
emailLoginState = nil
manualPairingEnabled = false
manualCredentialsState = nil
}
}
public struct WelcomeEnvironment {
let app: AppProtocol
let mainQueue: AnySchedulerOf<DispatchQueue>
let passwordValidator: PasswordValidatorAPI
let sessionTokenService: SessionTokenServiceAPI
let deviceVerificationService: DeviceVerificationServiceAPI
let buildVersionProvider: () -> String
let featureFlagsService: FeatureFlagsServiceAPI
let errorRecorder: ErrorRecording
let externalAppOpener: ExternalAppOpener
let analyticsRecorder: AnalyticsEventRecorderAPI
let walletRecoveryService: WalletRecoveryService
let walletCreationService: WalletCreationService
let walletFetcherService: WalletFetcherService
let accountRecoveryService: AccountRecoveryServiceAPI
let recaptchaService: GoogleRecaptchaServiceAPI
let checkReferralClient: CheckReferralClientAPI
let nativeWalletEnabled: () -> AnyPublisher<Bool, Never>
public init(
app: AppProtocol,
mainQueue: AnySchedulerOf<DispatchQueue>,
passwordValidator: PasswordValidatorAPI = resolve(),
sessionTokenService: SessionTokenServiceAPI = resolve(),
deviceVerificationService: DeviceVerificationServiceAPI,
featureFlagsService: FeatureFlagsServiceAPI,
recaptchaService: GoogleRecaptchaServiceAPI,
buildVersionProvider: @escaping () -> String,
errorRecorder: ErrorRecording = resolve(),
externalAppOpener: ExternalAppOpener = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
walletRecoveryService: WalletRecoveryService = DIKit.resolve(),
walletCreationService: WalletCreationService = DIKit.resolve(),
walletFetcherService: WalletFetcherService = DIKit.resolve(),
accountRecoveryService: AccountRecoveryServiceAPI = DIKit.resolve(),
checkReferralClient: CheckReferralClientAPI = DIKit.resolve(),
nativeWalletEnabled: @escaping () -> AnyPublisher<Bool, Never>
) {
self.app = app
self.mainQueue = mainQueue
self.passwordValidator = passwordValidator
self.sessionTokenService = sessionTokenService
self.deviceVerificationService = deviceVerificationService
self.buildVersionProvider = buildVersionProvider
self.featureFlagsService = featureFlagsService
self.errorRecorder = errorRecorder
self.externalAppOpener = externalAppOpener
self.analyticsRecorder = analyticsRecorder
self.walletRecoveryService = walletRecoveryService
self.walletCreationService = walletCreationService
self.walletFetcherService = walletFetcherService
self.accountRecoveryService = accountRecoveryService
self.checkReferralClient = checkReferralClient
self.nativeWalletEnabled = nativeWalletEnabled
self.recaptchaService = recaptchaService
}
}
public let welcomeReducer = Reducer.combine(
createAccountStepOneReducer
.optional()
.pullback(
state: \.createWalletState,
action: /WelcomeAction.createWallet,
environment: {
CreateAccountStepOneEnvironment(
mainQueue: $0.mainQueue,
passwordValidator: $0.passwordValidator,
externalAppOpener: $0.externalAppOpener,
analyticsRecorder: $0.analyticsRecorder,
walletRecoveryService: $0.walletRecoveryService,
walletCreationService: $0.walletCreationService,
walletFetcherService: $0.walletFetcherService,
featureFlagsService: $0.featureFlagsService,
recaptchaService: $0.recaptchaService,
checkReferralClient: $0.checkReferralClient,
app: $0.app
)
}
),
emailLoginReducer
.optional()
.pullback(
state: \.emailLoginState,
action: /WelcomeAction.emailLogin,
environment: {
EmailLoginEnvironment(
app: $0.app,
mainQueue: $0.mainQueue,
sessionTokenService: $0.sessionTokenService,
deviceVerificationService: $0.deviceVerificationService,
featureFlagsService: $0.featureFlagsService,
errorRecorder: $0.errorRecorder,
externalAppOpener: $0.externalAppOpener,
analyticsRecorder: $0.analyticsRecorder,
walletRecoveryService: $0.walletRecoveryService,
walletCreationService: $0.walletCreationService,
walletFetcherService: $0.walletFetcherService,
accountRecoveryService: $0.accountRecoveryService,
recaptchaService: $0.recaptchaService
)
}
),
seedPhraseReducer
.optional()
.pullback(
state: \.restoreWalletState,
action: /WelcomeAction.restoreWallet,
environment: {
SeedPhraseEnvironment(
mainQueue: $0.mainQueue,
externalAppOpener: $0.externalAppOpener,
analyticsRecorder: $0.analyticsRecorder,
walletRecoveryService: $0.walletRecoveryService,
walletCreationService: $0.walletCreationService,
walletFetcherService: $0.walletFetcherService,
accountRecoveryService: $0.accountRecoveryService,
errorRecorder: $0.errorRecorder,
recaptchaService: $0.recaptchaService,
featureFlagsService: $0.featureFlagsService
)
}
),
credentialsReducer
.optional()
.pullback(
state: \.manualCredentialsState,
action: /WelcomeAction.manualPairing,
environment: {
CredentialsEnvironment(
mainQueue: $0.mainQueue,
deviceVerificationService: $0.deviceVerificationService,
errorRecorder: $0.errorRecorder,
featureFlagsService: $0.featureFlagsService,
analyticsRecorder: $0.analyticsRecorder,
walletRecoveryService: $0.walletRecoveryService,
walletCreationService: $0.walletCreationService,
walletFetcherService: $0.walletFetcherService,
accountRecoveryService: $0.accountRecoveryService,
recaptchaService: $0.recaptchaService
)
}
),
Reducer<
WelcomeState,
WelcomeAction,
WelcomeEnvironment
// swiftlint:disable closure_body_length
> { state, action, environment in
switch action {
case .route(let route):
guard let routeValue = route?.route else {
state.createWalletState = nil
state.emailLoginState = nil
state.restoreWalletState = nil
state.manualCredentialsState = nil
state.route = route
return .none
}
switch routeValue {
case .createWallet:
state.createWalletState = .init(context: .createWallet)
case .emailLogin:
state.emailLoginState = .init()
case .restoreWallet:
state.restoreWalletState = .init(context: .restoreWallet)
case .manualLogin:
state.manualCredentialsState = .init()
}
state.route = route
return .none
case .start:
state.buildVersion = environment.buildVersionProvider()
if BuildFlag.isInternal {
return environment.app
.publisher(for: blockchain.app.configuration.manual.login.is.enabled, as: Bool.self)
.prefix(1)
.replaceError(with: false)
.flatMap { isEnabled -> Effect<WelcomeAction, Never> in
guard isEnabled else {
return .none
}
return Effect(value: .setManualPairingEnabled)
}
.eraseToEffect()
}
return .none
case .setManualPairingEnabled:
state.manualPairingEnabled = true
return .none
case .deeplinkReceived(let url):
// handle deeplink if we've entered verify device flow
guard let loginState = state.emailLoginState,
loginState.verifyDeviceState != nil
else {
return .none
}
return Effect(value: .emailLogin(.verifyDevice(.didReceiveWalletInfoDeeplink(url))))
case .requestedToCreateWallet,
.requestedToDecryptWallet,
.requestedToRestoreWallet:
// handled in core coordinator
return .none
case .createWallet(.triggerAuthenticate):
return Effect(value: .triggerAuthenticate)
case .createWallet(.informWalletFetched(let context)):
return Effect(value: .informWalletFetched(context))
case .emailLogin(.verifyDevice(.credentials(.seedPhrase(.informWalletFetched(let context))))):
return Effect(value: .informWalletFetched(context))
// TODO: refactor this by not relying on access lower level reducers
case .emailLogin(.verifyDevice(.credentials(.walletPairing(.decryptWalletWithPassword(let password))))),
.emailLogin(.verifyDevice(.upgradeAccount(.skipUpgrade(.credentials(.walletPairing(.decryptWalletWithPassword(let password))))))):
return Effect(value: .requestedToDecryptWallet(password))
case .emailLogin(.verifyDevice(.credentials(.seedPhrase(.restoreWallet(let walletRecovery))))):
return Effect(value: .requestedToRestoreWallet(walletRecovery))
case .restoreWallet(.restoreWallet(let walletRecovery)):
return Effect(value: .requestedToRestoreWallet(walletRecovery))
case .restoreWallet(.importWallet(.createAccount(.importAccount))):
return Effect(value: .requestedToRestoreWallet(.importRecovery))
case .manualPairing(.walletPairing(.decryptWalletWithPassword(let password))):
return Effect(value: .requestedToDecryptWallet(password))
case .emailLogin(.verifyDevice(.credentials(.secondPasswordNotice(.returnTapped)))),
.manualPairing(.secondPasswordNotice(.returnTapped)):
return .dismiss()
case .manualPairing(.seedPhrase(.informWalletFetched(let context))):
return Effect(value: .informWalletFetched(context))
case .manualPairing(.seedPhrase(.importWallet(.createAccount(.walletFetched(.success(.right(let context))))))):
return Effect(value: .informWalletFetched(context))
case .manualPairing:
return .none
case .restoreWallet(.triggerAuthenticate):
return Effect(value: .triggerAuthenticate)
case .emailLogin(.verifyDevice(.credentials(.seedPhrase(.triggerAuthenticate)))):
return Effect(value: .triggerAuthenticate)
case .restoreWallet(.restored(.success(.right(let context)))),
.emailLogin(.verifyDevice(.credentials(.seedPhrase(.restored(.success(.right(let context))))))):
return Effect(value: .informWalletFetched(context))
case .restoreWallet(.importWallet(.createAccount(.walletFetched(.success(.right(let context)))))):
return Effect(value: .informWalletFetched(context))
case .restoreWallet(.restored(.success(.left(.noValue)))),
.emailLogin(.verifyDevice(.credentials(.seedPhrase(.restored(.success(.left(.noValue))))))):
return environment.nativeWalletEnabled()
.eraseToEffect()
.map { isEnabled -> WelcomeAction in
guard isEnabled else {
return .none
}
return .informForWalletInitialization
}
case .restoreWallet(.restored(.failure)),
.emailLogin(.verifyDevice(.credentials(.seedPhrase(.restored(.failure))))):
return Effect(value: .triggerCancelAuthenticate)
case .createWallet(.accountCreation(.failure)):
return Effect(value: .triggerCancelAuthenticate)
case .informSecondPasswordDetected:
switch state.route?.route {
case .emailLogin:
return Effect(value: .emailLogin(.verifyDevice(.credentials(.navigate(to: .secondPasswordDetected)))))
case .manualLogin:
return Effect(value: .manualPairing(.navigate(to: .secondPasswordDetected)))
case .restoreWallet:
return Effect(value: .restoreWallet(.setSecondPasswordNoticeVisible(true)))
default:
return .none
}
case .triggerAuthenticate,
.triggerCancelAuthenticate,
.informForWalletInitialization,
.informWalletFetched:
// handled in core coordinator
return .none
case .createWallet,
.emailLogin,
.restoreWallet:
return .none
case .none:
return .none
}
}
)
.analytics()
extension Reducer where
Action == WelcomeAction,
State == WelcomeState,
Environment == WelcomeEnvironment
{
func analytics() -> Self {
combined(
with: Reducer<
WelcomeState,
WelcomeAction,
WelcomeEnvironment
> { _, action, environment in
switch action {
case .route(let route):
guard let routeValue = route?.route else {
return .none
}
switch routeValue {
case .emailLogin:
environment.analyticsRecorder.record(
event: .loginClicked()
)
case .restoreWallet:
environment.analyticsRecorder.record(
event: .recoveryOptionSelected
)
default:
break
}
return .none
default:
return .none
}
}
)
}
}
| b1da7257c3b4a651bf37e6c5b8c1cca2 | 38.738095 | 143 | 0.619233 | false | false | false | false |
blokadaorg/blokada | refs/heads/main | ios/App/UI/Payment/PaymentListView.swift | mpl-2.0 | 1 | //
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import SwiftUI
struct PaymentListView: View {
@ObservedObject var vm: PaymentGatewayViewModel
let showType: String
@State var showLocationSheet = false
var body: some View {
VStack {
ForEach(self.vm.options.filter({ it in it.product.type == self.showType}), id: \.self) { option in
Button(action: {
withAnimation {
self.vm.buy(option.product)
}
}) {
PaymentView(vm: option)
}
}
}
.padding(.bottom, 8)
}
}
struct PaymentListView_Previews: PreviewProvider {
static var previews: some View {
let working = PaymentGatewayViewModel()
working.working = true
let error = PaymentGatewayViewModel()
error.error = "Bad error"
return Group {
PaymentListView(vm: PaymentGatewayViewModel(), showType: "plus")
.previewLayout(.sizeThatFits)
PaymentListView(vm: error, showType: "plus")
.previewLayout(.sizeThatFits)
PaymentListView(vm: working, showType: "cloud")
.previewLayout(.sizeThatFits)
}
}
}
| 39c9a9404ada6ae454156f065e04e63c | 26.103448 | 110 | 0.571247 | false | false | false | false |
ktmswzw/jwtSwiftDemoClient | refs/heads/master | TempTests/TempTests.swift | apache-2.0 | 1 | //
// TempTests.swift
// TempTests
//
// Created by vincent on 7/2/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import JWT
import XCTest
class TempTests: 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 testExample() {
let jwt = JWT.encode(.HS256("secret")) { builder in
builder.issuer = "fuller.li"
builder.audience = "123123"
builder["custom"] = "Hi"
}
print("\(jwt)")
}
func testDecode() {
do {
let payload = try JWT.decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmdWxsZXIubGkiLCJhdWQiOiIxMjMxMjMiLCJvb29vb28iOiIxMTExMTExMTExMTExIn0.K00sztVpajtv3rKBr-4uJzTnG2RHLeM0vkpI7RKBblg", algorithm: .HS256("secret"))
print(payload)
} catch {
print("Failed to decode JWT: \(error)")
}
}
}
| 32f4682e2ca19e3381c8f2412cc49696 | 27.829268 | 233 | 0.609983 | false | true | false | false |
jverdi/Gramophone | refs/heads/master | Source/Client/DecodingUtils.swift | mit | 1 | //
// Array.swift
// Gramophone
//
// Copyright (c) 2017 Jared Verdi. All Rights Reserved
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import protocol Decodable.Decodable
import protocol Decodable.DynamicDecodable
import Decodable
public struct Array<T: Decodable>: Decodable {
/// The resources which are part of the given array
public let items: [T]
internal static func parseItems(json: Any) throws -> [T] {
return try (json as! [AnyObject]).flatMap {
return try T.decode($0)
}
}
public static func decode(_ json: Any) throws -> Array<T> {
return try Array(items: parseItems(json: json).flatMap{ $0 })
}
}
extension UInt: Decodable, DynamicDecodable {
public static var decoder: (Any) throws -> UInt = { try cast($0) }
}
extension Data: Decodable, DynamicDecodable {
public static var decoder: (Any) throws -> Data = { try cast($0) }
}
extension URL {
public static var decoder: (Any) throws -> URL = { object in
let string = try String.decode(object)
guard let url = URL(string: string) else {
let metadata = DecodingError.Metadata(object: object)
throw DecodingError.rawRepresentableInitializationError(rawValue: string, metadata)
}
return url
}
}
| 1f564d6cf47ab112c1bb5723f5a15d41 | 36.603175 | 95 | 0.700295 | false | false | false | false |
tevelee/CodeGenerator | refs/heads/master | output/swift/RecordLenses.swift | mit | 1 | import Foundation
extension Record {
struct Lenses {
static let name: Lens<Record, String> = Lens(
get: { $0.name },
set: { (record, name) in
var builder = RecordBuilder(existingRecord: record)
return builder.withName(name).build()
}
)
static let creator: Lens<Record, Person> = Lens(
get: { $0.creator },
set: { (record, creator) in
var builder = RecordBuilder(existingRecord: record)
return builder.withCreator(creator).build()
}
)
static let date: Lens<Record, Date> = Lens(
get: { $0.date },
set: { (record, date) in
var builder = RecordBuilder(existingRecord: record)
return builder.withDate(date).build()
}
)
}
}
struct BoundLensToRecord<Whole>: BoundLensType {
typealias Part = Record
let storage: BoundLensStorage<Whole, Part>
var name: BoundLens<Whole, String> {
return BoundLens<Whole, String>(parent: self, sublens: Record.Lenses.name)
}
var creator: BoundLensToPerson<Whole> {
return BoundLensToPerson<Whole>(parent: self, sublens: Record.Lenses.creator)
}
var date: BoundLens<Whole, Date> {
return BoundLens<Whole, Date>(parent: self, sublens: Record.Lenses.date)
}
}
extension Record {
var lens: BoundLensToRecord<Record> {
return BoundLensToRecord<Record>(instance: self, lens: createIdentityLens())
}
}
| 778628fbe3d7204c0b5e59a6e850097d | 30.22 | 85 | 0.58296 | false | false | false | false |
xuephil/Perfect | refs/heads/master | PerfectLib/Routing.swift | agpl-3.0 | 1 | //
// Routing.swift
// PerfectLib
//
// Created by Kyle Jessup on 2015-12-11.
// Copyright © 2015 PerfectlySoft. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
public typealias RequestHandlerGenerator = PageHandlerRegistry.RequestHandlerGenerator
/// Holds the registered routes.
public struct RouteMap: CustomStringConvertible {
/// Pretty prints all route information.
public var description: String {
var s = self.root.description
for (method, root) in self.methodRoots {
s.appendContentsOf("\n" + method + ":\n" + root.description)
}
return s
}
private var root = RouteNode() // root node for any request method
private var methodRoots = [String:RouteNode]() // by convention, use all upper cased method names for inserts/lookups
/// Lookup a route based on the URL path.
/// Returns the handler generator if found.
subscript(path: String, webResponse: WebResponse) -> RequestHandlerGenerator? {
get {
let components = path.lowercaseString.pathComponents
var g = components.generate()
let _ = g.next() // "/"
let method = webResponse.request.requestMethod().uppercaseString
if let root = self.methodRoots[method] {
if let handler = root.findHandler("", generator: g, webResponse: webResponse) {
return handler
}
}
return self.root.findHandler("", generator: g, webResponse: webResponse)
}
}
/// Add a route to the system.
/// `Routing.Routes["/foo/*/baz"] = { _ in return ExampleHandler() }`
public subscript(path: String) -> RequestHandlerGenerator? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
self.root.addPathSegments(path.lowercaseString.pathComponents.generate(), h: newValue!)
}
}
/// Add an array of routes for a given handler.
/// `Routing.Routes[ ["/", "index.html"] ] = { _ in return ExampleHandler() }`
public subscript(paths: [String]) -> RequestHandlerGenerator? {
get {
return nil
}
set {
for path in paths {
self[path] = newValue
}
}
}
/// Add a route to the system using the indicated HTTP request method.
/// `Routing.Routes["GET", "/foo/*/baz"] = { _ in return ExampleHandler() }`
public subscript(method: String, path: String) -> RequestHandlerGenerator? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
let uppered = method.uppercaseString
if let root = self.methodRoots[uppered] {
root.addPathSegments(path.lowercaseString.pathComponents.generate(), h: newValue!)
} else {
let root = RouteNode()
self.methodRoots[uppered] = root
root.addPathSegments(path.lowercaseString.pathComponents.generate(), h: newValue!)
}
}
}
/// Add an array of routes for a given handler using the indicated HTTP request method.
/// `Routing.Routes["GET", ["/", "index.html"] ] = { _ in return ExampleHandler() }`
public subscript(method: String, paths: [String]) -> RequestHandlerGenerator? {
get {
return nil // Swift does not currently allow set-only subscripts
}
set {
for path in paths {
self[method, path] = newValue
}
}
}
}
/// This wraps up the routing related functionality.
/// Enable the routing system by calling:
/// ```
/// Routing.Handler.registerGlobally()
/// ```
/// This should be done in your `PerfectServerModuleInit` function.
/// The system supports HTTP method based routing, wildcards and variables.
///
/// Add routes in the following manner:
/// ```
/// Routing.Routes["GET", ["/", "index.html"] ] = { (_:WebResponse) in return IndexHandler() }
/// Routing.Routes["/foo/*/baz"] = { _ in return EchoHandler() }
/// Routing.Routes["/foo/bar/baz"] = { _ in return EchoHandler() }
/// Routing.Routes["GET", "/user/{id}/baz"] = { _ in return Echo2Handler() }
/// Routing.Routes["POST", "/user/{id}/baz"] = { _ in return Echo3Handler() }
/// ```
/// The closure you provide should return an instance of `PageHandler`. It is provided the WebResponse object to permit further customization.
/// Variables set by the routing process can be accessed through the `WebRequest.urlVariables` dictionary.
/// Note that a PageHandler *MUST* call `WebResponse.requestCompletedCallback()` when the request has completed.
/// This does not need to be done within the `handleRequest` method.
public class Routing {
/// The routes which have been configured.
static public var Routes = RouteMap()
private init() {}
/// This is the main handler for the logic of the URL routing system.
/// If must be enabled by calling `Routing.Handler.registerGlobally`
public class Handler: RequestHandler {
/// Install the URL routing system.
/// This is required if this system is to be utilized, otherwise it will not be available.
static public func registerGlobally() {
PageHandlerRegistry.addRequestHandler { (_:WebResponse) -> RequestHandler in
return Routing.Handler()
}
}
/// Handle the request, triggering the routing system.
/// If a route is discovered the request is sent to the new handler.
public func handleRequest(request: WebRequest, response: WebResponse) {
let pathInfo = request.requestURI().characters.split("?").map { String($0) }.first ?? "/"
if let handler = Routing.Routes[pathInfo, response] {
handler(response).handleRequest(request, response: response)
} else {
response.setStatus(404, message: "NOT FOUND")
response.appendBodyString("The file \(pathInfo) was not found.")
response.requestCompletedCallback()
}
}
}
}
class RouteNode: CustomStringConvertible {
typealias ComponentGenerator = IndexingGenerator<[String]>
var description: String {
return self.descriptionTabbed(0)
}
private func putTabs(count: Int) -> String {
var s = ""
for _ in 0..<count {
s.appendContentsOf("\t")
}
return s
}
func descriptionTabbedInner(tabCount: Int) -> String {
var s = ""
for (_, node) in self.subNodes {
s.appendContentsOf("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
for node in self.variables {
s.appendContentsOf("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
if let node = self.wildCard {
s.appendContentsOf("\(self.putTabs(tabCount))\(node.descriptionTabbed(tabCount+1))")
}
return s
}
func descriptionTabbed(tabCount: Int) -> String {
var s = ""
if let _ = self.handlerGenerator {
s.appendContentsOf("/+h\n")
}
s.appendContentsOf(self.descriptionTabbedInner(tabCount))
return s
}
var handlerGenerator: RequestHandlerGenerator?
var wildCard: RouteNode?
var variables = [RouteNode]()
var subNodes = [String:RouteNode]()
func findHandler(currentComponent: String, generator: ComponentGenerator, webResponse: WebResponse) -> RequestHandlerGenerator? {
var m = generator
if let p = m.next() where p != "/" {
// variables
for node in self.variables {
if let h = node.findHandler(p, generator: m, webResponse: webResponse) {
return self.successfulRoute(currentComponent, handler: node.successfulRoute(p, handler: h, webResponse: webResponse), webResponse: webResponse)
}
}
// paths
if let node = self.subNodes[p] {
if let h = node.findHandler(p, generator: m, webResponse: webResponse) {
return self.successfulRoute(currentComponent, handler: node.successfulRoute(p, handler: h, webResponse: webResponse), webResponse: webResponse)
}
}
// wildcards
if let node = self.wildCard {
if let h = node.findHandler(p, generator: m, webResponse: webResponse) {
return self.successfulRoute(currentComponent, handler: node.successfulRoute(p, handler: h, webResponse: webResponse), webResponse: webResponse)
}
}
} else if self.handlerGenerator != nil {
return self.handlerGenerator
} else {
// wildcards
if let node = self.wildCard {
if let h = node.findHandler("", generator: m, webResponse: webResponse) {
return self.successfulRoute(currentComponent, handler: node.successfulRoute("", handler: h, webResponse: webResponse), webResponse: webResponse)
}
}
}
return nil
}
func successfulRoute(currentComponent: String, handler: RequestHandlerGenerator, webResponse: WebResponse) -> RequestHandlerGenerator {
return handler
}
func addPathSegments(g: ComponentGenerator, h: RequestHandlerGenerator) {
var m = g
if let p = m.next() {
if p == "/" {
self.addPathSegments(m, h: h)
} else {
self.addPathSegment(p, g: m, h: h)
}
} else {
self.handlerGenerator = h
}
}
private func addPathSegment(component: String, g: ComponentGenerator, h: RequestHandlerGenerator) {
if let node = self.nodeForComponent(component) {
node.addPathSegments(g, h: h)
}
}
private func nodeForComponent(component: String) -> RouteNode? {
guard !component.isEmpty else {
return nil
}
if component == "*" {
if self.wildCard == nil {
self.wildCard = RouteWildCard()
}
return self.wildCard
}
if component.characters.count >= 3 && component[component.startIndex] == "{" && component[component.endIndex.predecessor()] == "}" {
let node = RouteVariable(name: component.substringWith(Range(start: component.startIndex.successor(), end: component.endIndex.predecessor())))
self.variables.append(node)
return node
}
if let node = self.subNodes[component] {
return node
}
let node = RoutePath(name: component)
self.subNodes[component] = node
return node
}
}
class RoutePath: RouteNode {
override func descriptionTabbed(tabCount: Int) -> String {
var s = "/\(self.name)"
if let _ = self.handlerGenerator {
s.appendContentsOf("+h\n")
} else {
s.appendContentsOf("\n")
}
s.appendContentsOf(self.descriptionTabbedInner(tabCount))
return s
}
var name = ""
init(name: String) {
self.name = name
}
// RoutePaths don't need to perform any special checking.
// Their path is validated by the fact that they exist in their parent's `subNodes` dict.
}
class RouteWildCard: RouteNode {
override func descriptionTabbed(tabCount: Int) -> String {
var s = "/*"
if let _ = self.handlerGenerator {
s.appendContentsOf("+h\n")
} else {
s.appendContentsOf("\n")
}
s.appendContentsOf(self.descriptionTabbedInner(tabCount))
return s
}
}
class RouteVariable: RouteNode {
override func descriptionTabbed(tabCount: Int) -> String {
var s = "/{\(self.name)}"
if let _ = self.handlerGenerator {
s.appendContentsOf("+h\n")
} else {
s.appendContentsOf("\n")
}
s.appendContentsOf(self.descriptionTabbedInner(tabCount))
return s
}
var name = ""
init(name: String) {
self.name = name
}
override func successfulRoute(currentComponent: String, handler: RequestHandlerGenerator, webResponse: WebResponse) -> RequestHandlerGenerator {
webResponse.request.urlVariables[self.name] = currentComponent
return handler
}
}
| 609b06d9b7bc7d1a7003d8e5ee0aaa0e | 30.324468 | 149 | 0.696468 | false | false | false | false |
dropbox/PhotoWatch | refs/heads/master | PhotoWatch/PhotoViewController.swift | mit | 1 | //
// PhotoViewController.swift
// PhotoWatch
//
// Created by Leah Culver on 5/14/15.
// Copyright (c) 2015 Dropbox. All rights reserved.
//
import UIKit
import ImageIO
import SwiftyDropbox
class PhotoViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var noPhotosLabel: UILabel!
var filename: String?
override func viewDidLoad() {
// Display photo for page
if let filename = self.filename {
// Get app group shared by phone and watch
let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.Dropbox.DropboxPhotoWatch")
if let fileURL = containerURL?.appendingPathComponent(filename) {
print("Finding file at URL: \(fileURL)")
if let data = try? Data(contentsOf: fileURL) {
print("Image found in cache.")
// Display image
self.imageView.image = UIImage(data: data)
} else {
print("Image not cached!")
let destination : (URL, HTTPURLResponse) -> URL = { temporaryURL, response in
let fileManager = FileManager.default
let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
// generate a unique name for this file in case we've seen it before
let UUID = Foundation.UUID().uuidString
let pathComponent = "\(UUID)-\(response.suggestedFilename!)"
return directoryURL.appendingPathComponent(pathComponent)
}
_ = DropboxClientsManager.authorizedClient!.files.getThumbnail(path: "/\(filename)", format: .png, size: .w640h480, destination: destination).response { response, error in
if let (metadata, url) = response {
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
print("Dowloaded file name: \(metadata.name)")
// Resize image for watch (so it's not huge)
let resizedImage = self.resizeImage(image)
// Display image
self.imageView.image = resizedImage
// Save image to local filesystem app group - allows us to access in the watch
let resizedImageData = resizedImage.jpegData(compressionQuality: 1.0)
try? resizedImageData!.write(to: fileURL)
}
}
} else {
print("Error downloading file from Dropbox: \(error!)")
}
}
}
}
} else {
// No photos in the folder to display.
print("No photos to display")
self.activityIndicator.isHidden = true
self.noPhotosLabel.isHidden = false
}
}
fileprivate func resizeImage(_ image: UIImage) -> UIImage {
// Resize and crop to fit Apple watch (square for now, because it's easy)
let maxSize: CGFloat = 200.0
var size: CGSize?
if image.size.width >= image.size.height {
size = CGSize(width: (maxSize / image.size.height) * image.size.width, height: maxSize)
} else {
size = CGSize(width: maxSize, height: (maxSize / image.size.width) * image.size.height)
}
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(size!, !hasAlpha, scale)
let rect = CGRect(origin: CGPoint.zero, size: size!)
UIRectClip(rect)
image.draw(in: rect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
}
| 9a88af324be8e57ddd034ddcfb9e5040 | 40.8 | 191 | 0.50696 | false | false | false | false |
thedistance/TheDistanceForms | refs/heads/master | FormsDemo/EventFormViewController.swift | mit | 1 | //
// FormsTableViewController.swift
// TheDistanceForms
//
// Created by Josh Campion on 26/04/2016.
// Copyright © 2016 The Distance. All rights reserved.
//
import UIKit
import SwiftyJSON
import TheDistanceForms
import TheDistanceCore
import KeyboardResponder
class EventFormViewController: UIViewController, FormContainer {
@IBOutlet weak var scrollContainer:UIScrollView!
@IBOutlet weak var formContainer:UIView!
var form:Form?
var buttonTargets: [ObjectTarget<UIButton>] = []
var keyboardResponder:KeyboardResponder?
override func viewDidLoad() {
super.viewDidLoad()
guard let jsonURL = Bundle.main.url(forResource: "EventForm", withExtension: "json"),
let form = addFormFromURL(jsonURL, ofType: EventForm.self, toContainerView: formContainer, withInsets: UIEdgeInsets.zero)
else { return }
self.form = form
keyboardResponder = setUpKeyboardResponder(onForm: form, withScrollView: scrollContainer)
}
func buttonTappedForQuestion(_ question: FormQuestion) {
}
}
| ba75123700e4dbc8540dac27c6795632 | 26.45 | 133 | 0.708561 | false | false | false | false |
Quaggie/Quaggify | refs/heads/master | Quaggify/API.swift | mit | 1 | //
// API.swift
// Quaggify
//
// Created by Jonathan Bijos on 31/01/17.
// Copyright © 2017 Quaggie. All rights reserved.
//
struct API {
static func fetchCurrentUser (service: SpotifyService = SpotifyService.shared, completion: @escaping (User?, Error?) -> Void) {
service.fetchCurrentUser(completion: completion)
}
static func requestToken (code: String, service: SpotifyService = SpotifyService.shared, completion: @escaping (Error?) -> Void) {
service.requestToken(code: code, completion: completion)
}
static func fetchSearchResults (query: String, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifySearchResponse?, Error?) -> Void) {
service.fetchSearchResults(query: query, completion: completion)
}
static func fetchAlbums (query: String, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Album>?, Error?) -> Void) {
service.fetchAlbums(query: query, limit: limit, offset: offset, completion: completion)
}
static func fetchAlbumTracks (album: Album?, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Track>?, Error?) -> Void) {
service.fetchAlbumTracks(album: album, limit: limit, offset: offset, completion: completion)
}
static func fetchArtist (artist: Artist?, service: SpotifyService = SpotifyService.shared, completion: @escaping (Artist?, Error?) -> Void) {
service.fetchArtist(artist: artist, completion: completion)
}
static func fetchArtists (query: String, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Artist>?, Error?) -> Void) {
service.fetchArtists(query: query, limit: limit, offset: offset, completion: completion)
}
static func fetchArtistAlbums (artist: Artist?, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Album>?, Error?) -> Void) {
service.fetchArtistAlbums(artist: artist, limit: limit, offset: offset, completion: completion)
}
static func fetchTrack (track: Track?, service: SpotifyService = SpotifyService.shared, completion: @escaping (Track?, Error?) -> Void) {
service.fetchTrack(track: track, completion: completion)
}
static func fetchTracks (query: String, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Track>?, Error?) -> Void) {
service.fetchTracks(query: query, limit: limit, offset: offset, completion: completion)
}
static func fetchNewReleases (limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Album>?, Error?) -> Void) {
service.fetchNewReleases(limit: limit, offset: offset, completion: completion)
}
static func fetchPlaylists (query: String, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Playlist>?, Error?) -> Void) {
service.fetchPlaylists(query: query, limit: limit, offset: offset, completion: completion)
}
static func fetchPlaylistTracks (playlist: Playlist?, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<PlaylistTrack>?, Error?) -> Void) {
service.fetchPlaylistTracks(playlist: playlist, limit: limit, offset: offset, completion: completion)
}
static func removePlaylistTrack (track: Track?, position: Int?, playlist: Playlist?, service: SpotifyService = SpotifyService.shared, completion: @escaping(String?, Error?) -> Void) {
service.removePlaylistTrack(track: track, position: position, playlist: playlist, completion: completion)
}
static func addTrackToPlaylist (track: Track?, playlist: Playlist?, service: SpotifyService = SpotifyService.shared, completion: @escaping (String?, Error?) -> Void) {
service.addTrackToPlaylist(track: track, playlist: playlist, completion: completion)
}
static func fetchCurrentUsersPlaylists (limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Playlist>?, Error?) -> Void) {
service.fetchCurrentUsersPlaylists(limit: limit, offset: offset, completion: completion)
}
static func createNewPlaylist (name: String, service: SpotifyService = SpotifyService.shared, completion: @escaping (Playlist?, Error?) -> Void) {
service.createNewPlaylist(name: name, completion: completion)
}
}
| 7df166134ce3dc12c8f29e4b7d499d63 | 58.628205 | 211 | 0.732316 | false | false | false | false |
bgayman/bikeServer | refs/heads/master | Sources/Kitura-Starter/GBFSStationInformation.swift | apache-2.0 | 1 | //
// GBFSStationInformation.swift
// BikeShare
//
// Created by Brad G. on 2/15/17.
// Copyright © 2017 B Gay. All rights reserved.
//
import Foundation
struct GBFSStationInformation
{
let stationID: String
let name: String
let coordinates: Coordinates
let shortName: String?
let address: String?
let crossStreet: String?
let regionID: String?
let postCode: String?
let rentalMethods: [String]?
let capacity: Int?
var stationStatus: GBFSStationStatus? = nil
var jsonDict: JSONDictionary
{
return [
"station_id": self.stationID,
"name": self.name,
"short_name": self.shortName ?? "",
"lat": self.coordinates.latitude,
"lon": self.coordinates.longitude,
"address": self.address ?? "",
"cross_street": self.crossStreet ?? "",
"region_id": self.regionID ?? "",
"post_code": self.postCode ?? "",
"rental_methods": self.rentalMethods ?? [String](),
"capacity": self.capacity ?? 0,
"stationStatus": self.stationStatus?.jsonDict ?? JSONDictionary()
]
}
}
extension GBFSStationInformation
{
init?(json: JSONDictionary)
{
guard let stationID = json["station_id"] as? String,
let name = json["name"] as? String,
let lat = json["lat"] as? Double,
let lon = json["lon"] as? Double else { return nil}
self.stationID = stationID
self.name = name
self.coordinates = Coordinates(latitude: lat, longitude: lon)
self.shortName = json["short_name"] as? String
self.address = json["address"] as? String
self.crossStreet = json["cross_street"] as? String
self.regionID = json["region_id"] as? String
self.postCode = json["post_code"] as? String
self.rentalMethods = json["rental_methods"] as? [String]
self.capacity = json["capacity"] as? Int
}
}
| db6a5566135252b9464bf88c9a6a93e6 | 30.68254 | 77 | 0.587675 | false | false | false | false |
BellAppLab/swift-sodium | refs/heads/master | Examples/OSX/AppDelegate.swift | isc | 3 | //
// AppDelegate.swift
// Example OSX
//
// Created by RamaKrishna Mallireddy on 19/04/15.
// Copyright (c) 2015 Frank Denis. All rights reserved.
//
import Cocoa
import Sodium
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
let sodium = Sodium()!
let aliceKeyPair = sodium.box.keyPair()!
let bobKeyPair = sodium.box.keyPair()!
let message: NSData = "My Test Message".toData()!
println("Original Message:\(message.toString())")
let encryptedMessageFromAliceToBob: NSData =
sodium.box.seal(message,
recipientPublicKey: bobKeyPair.publicKey,
senderSecretKey: aliceKeyPair.secretKey)!
println("Encrypted Message:\(encryptedMessageFromAliceToBob)")
let messageVerifiedAndDecryptedByBob =
sodium.box.open(encryptedMessageFromAliceToBob,
senderPublicKey: bobKeyPair.publicKey,
recipientSecretKey: aliceKeyPair.secretKey)
println("Decrypted Message:\(messageVerifiedAndDecryptedByBob!.toString())")
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| e1614774ce290a4c4cc9deb3022447fe | 27.8 | 84 | 0.666667 | false | false | false | false |
mownier/photostream | refs/heads/master | Photostream/UI/User Timeline/UserTimelineView.swift | mit | 1 | //
// UserTimelineView.swift
// Photostream
//
// Created by Mounir Ybanez on 12/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
class UserTimelineView: UIView {
var userPostView: UICollectionView?
var header: UserTimelineHeader!
override init(frame: CGRect) {
super.init(frame: frame)
initSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSetup()
}
override func addSubview(_ view: UIView) {
super.addSubview(view)
if view.subviews.count > 0 && view.subviews[0] is UICollectionView {
userPostView = view.subviews[0] as? UICollectionView
} else if view is UserProfileView {
let userProfileView = view as! UserProfileView
header.addSubview(userProfileView)
}
}
override func layoutSubviews() {
guard let postView = userPostView, header.userProfileView != nil else {
return
}
var rect = header.frame
rect.size.width = frame.width
rect.size.height = header.dynamicHeight
header.frame = rect
postView.frame = bounds
postView.scrollIndicatorInsets.top = rect.maxY
postView.contentInset.top = rect.maxY
bringSubview(toFront: header)
}
func initSetup() {
backgroundColor = UIColor.white
header = UserTimelineHeader()
addSubview(header)
}
}
extension UserTimelineView {
var spacing: CGFloat {
return 4
}
}
| 86e022c557e746bf40a1a817573afdb8 | 22.7 | 79 | 0.589512 | false | false | false | false |
macostea/SpotifyWrapper | refs/heads/master | SpotifyWrapper/SWWebView.swift | mit | 1 | //
// SWWebView.swift
// SpotifyWrapper
//
// Created by Mihai Costea on 13/04/15.
// Copyright (c) 2015 Skobbler. All rights reserved.
//
import Cocoa
import WebKit
class SWWebView: WebView {
private var warnedAboutPlugin = false
override func webView(sender: WebView!, plugInFailedWithError error: NSError!, dataSource: WebDataSource!) {
if (!self.warnedAboutPlugin) {
self.warnedAboutPlugin = true;
let pluginName = error.userInfo![WebKitErrorPlugInNameKey] as! String
let pluginUrl = NSURL(string: error.userInfo![WebKitErrorPlugInPageURLStringKey] as! String)
let reason = error.userInfo![NSLocalizedDescriptionKey] as! String
let alert = NSAlert()
alert.messageText = reason
alert.addButtonWithTitle("Download plug-in update...")
alert.addButtonWithTitle("OK")
alert.informativeText = "\(pluginName) plug-in could not be loaded and may be out-of-date. You will need to download the latest plug-in update from within Safari, and restart Spotify Wrapper once it is installed."
let response = alert.runModal()
if (response == NSAlertFirstButtonReturn) {
NSWorkspace.sharedWorkspace().openURL(pluginUrl!)
}
}
}
}
| 97ee8e292d9d9652ca65a9c77496e45d | 36.944444 | 225 | 0.636896 | false | false | false | false |
Melon-IT/base-view-controller-swift | refs/heads/master | MelonBaseViewController/MelonBaseViewController/MBFTransition.swift | mit | 1 | //
// MBFTransition.swift
// MelonBaseViewController
//
// Created by Tomasz Popis on 15/06/16.
// Copyright © 2016 Melon. All rights reserved.
//
import UIKit
open class MBFTransition: UIPercentDrivenInteractiveTransition,
UIViewControllerTransitioningDelegate {
open var animator: MBFBaseTransitionAnimator?
public override init() {
super.init()
}
public init(animator: MBFBaseTransitionAnimator) {
self.animator = animator
super.init()
}
//MARK: - UIViewControllerTransitioningDelegate
open func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.animator?.presented = true
return self.animator
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.animator?.presented = false
return self.animator
}
open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
var result: UIViewControllerInteractiveTransitioning?
if self.animator?.interaction == true {
result = self
}
return result
}
open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
var result: UIViewControllerInteractiveTransitioning?
if self.animator?.interaction == true {
result = self
}
return result
}
}
| e588e5132508a40e4dfe0896409e70e7 | 26.344262 | 150 | 0.714628 | false | false | false | false |
peferron/algo | refs/heads/master | EPI/Sorting/Merge two sorted arrays/swift/main.swift | mit | 1 | public func mergeInPlace(target a: inout [Int?], source b: [Int]) {
// ai is the index of the last non-nil element in a.
var ai = -1
for av in a {
if av == nil {
break
}
ai += 1
}
// bi is the index of the last element in b.
var bi = b.count - 1
// We can stop iterating after all elements in b have been processed, since the remaining
// elements in a are already sorted.
while bi >= 0 {
// ti is the index at which the max of a[ai] and b[bi] should be copied.
let ti = ai + bi + 1
if (ai >= 0 && a[ai]! > b[bi]) {
a[ti] = a[ai]!
ai -= 1
} else {
a[ti] = b[bi]
bi -= 1
}
}
}
| 70440d3ad3e26755ee19b00b2c795ea1 | 25.535714 | 93 | 0.477793 | false | false | false | false |
toggl/superday | refs/heads/develop | teferi/Interactors/GetSingleTimeSlotForDate.swift | bsd-3-clause | 1 | import Foundation
import RxSwift
class GetSingleTimeSlotForDate: Interactor
{
let repositoryService: RepositoryService
let appLifecycleService: AppLifecycleService
let date: Date
init(repositoryService: RepositoryService, appLifecycleService: AppLifecycleService, date: Date)
{
self.repositoryService = repositoryService
self.appLifecycleService = appLifecycleService
self.date = date
}
func execute() -> Observable<TimeSlotEntity?>
{
let refresh = Observable.merge([
NotificationCenter.default.rx.typedNotification(OnTimeSlotCreated.self).mapTo(()),
NotificationCenter.default.rx.typedNotification(OnTimeSlotDeleted.self).mapTo(()),
NotificationCenter.default.rx.typedNotification(OnTimeSlotStartTimeEdited.self).mapTo(()),
NotificationCenter.default.rx.typedNotification(OnTimeSlotCategoriesEdited.self).mapTo(()),
appLifecycleService.movedToForegroundObservable.mapTo(())
])
.startWith(())
.throttle(0.3, latest: false, scheduler: MainScheduler.instance)
return refresh
.flatMapLatest(fetchTimeSlot)
}
private func fetchTimeSlot() -> Observable<TimeSlotEntity?>
{
return repositoryService.getTimeSlots(forDay: date)
.map { [unowned self] timeSlots in
return timeSlots
.filter{ $0.startTime == self.date }
.first
}
}
}
// Free functions (Might be moved to static functions on TimeSlot)
fileprivate func belongs(to date: Date) -> (TimeSlot) -> Bool
{
return { timeSlot in
return timeSlot.belongs(toDate: date)
}
}
fileprivate func allBelong(to date: Date) -> ([TimeSlot]) -> Bool
{
return { timeSlots in
return timeSlots.filter(belongs(to: date)).count == timeSlots.count
}
}
| a269b8ad8fdd89cc998d7b90b7e1a538 | 31.583333 | 107 | 0.645013 | false | false | false | false |
SafeCar/iOS | refs/heads/master | Pods/CameraEngine/CameraEngine/CameraEngineDeviceInput.swift | mit | 1 | //
// CameraEngineDeviceInput.swift
// CameraEngine2
//
// Created by Remi Robert on 01/02/16.
// Copyright © 2016 Remi Robert. All rights reserved.
//
import UIKit
import AVFoundation
public enum CameraEngineDeviceInputErrorType: ErrorType {
case UnableToAddCamera
case UnableToAddMic
}
class CameraEngineDeviceInput {
private var cameraDeviceInput: AVCaptureDeviceInput?
private var micDeviceInput: AVCaptureDeviceInput?
func configureInputCamera(session: AVCaptureSession, device: AVCaptureDevice) throws {
let possibleCameraInput: AnyObject? = try AVCaptureDeviceInput(device: device)
if let cameraInput = possibleCameraInput as? AVCaptureDeviceInput {
if let currentDeviceInput = self.cameraDeviceInput {
session.removeInput(currentDeviceInput)
}
self.cameraDeviceInput = cameraInput
if session.canAddInput(self.cameraDeviceInput) {
session.addInput(self.cameraDeviceInput)
}
else {
throw CameraEngineDeviceInputErrorType.UnableToAddCamera
}
}
}
func configureInputMic(session: AVCaptureSession, device: AVCaptureDevice) throws {
if self.micDeviceInput != nil {
return
}
try self.micDeviceInput = AVCaptureDeviceInput(device: device)
if session.canAddInput(self.micDeviceInput) {
session.addInput(self.micDeviceInput)
}
else {
throw CameraEngineDeviceInputErrorType.UnableToAddMic
}
}
} | 7dd0dbbd18c4bbde1371ce5e957a6189 | 30.8 | 90 | 0.67275 | false | false | false | false |
snowpunch/AppLove | refs/heads/develop | App Love/UI/ViewControllers/HelpVC.swift | mit | 1 | //
// HelpVC.swift
// App Love
//
// Created by Woodie Dovich on 2016-03-28.
// Copyright © 2016 Snowpunch. All rights reserved.
//
// Help info (includes number of territories selected).
//
import UIKit
import SpriteKit
import SwiftyGlyphs
class HelpVC: ElasticModalViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var skview: SKView!
var glyphSprites:SpriteGlyphs? = nil
override func viewDidLoad() {
super.viewDidLoad()
populateHelpText()
}
func populateHelpText() {
let territoriesSelected = TerritoryMgr.sharedInst.getSelectedCountryCodes().count
let allTerritories = TerritoryMgr.sharedInst.getTerritoryCount()
let helpText = "TIPS:\n\nCurrently there are \(territoriesSelected) territories selected out of a possible \(allTerritories).\n\nWhen selecting territories manually, the ALL button toggles between ALL and CLEAR.\n\nAfter viewing a translation, return back to this app by tapping the top left corner.\n"
textView.backgroundColor = .clearColor()
textView.text = helpText
textView.userInteractionEnabled = false
textView.selectable = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
showAnimatedText()
}
func fixCutOffTextAfterRotation() {
textView.scrollEnabled = false
textView.scrollEnabled = true
}
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
fixCutOffTextAfterRotation()
}
func showAnimatedText() {
if glyphSprites == nil {
glyphSprites = SpriteGlyphs(fontName: "HelveticaNeue-Light", size:24)
}
if let glyphs = glyphSprites {
glyphs.text = "At Your Service!"
glyphs.setLocation(skview, pos: CGPoint(x:0,y:20))
glyphs.centerTextToView()
HelpAnimation().startAnimation(glyphs, viewWidth:skview.frame.width)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
dismissViewControllerAnimated(true, completion: nil)
}
}
| 3e830041bdcf9a6d0366affba68d27a8 | 32.014706 | 310 | 0.681514 | false | false | false | false |
Ribeiro/Swifter | refs/heads/master | SwifterCommon/SwifterHTTPRequest.swift | mit | 3 | //
// SwifterHTTPRequest.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
#if os(iOS)
import UIKit
#else
import AppKit
#endif
class SwifterHTTPRequest: NSObject, NSURLConnectionDataDelegate {
typealias UploadProgressHandler = (bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) -> Void
typealias DownloadProgressHandler = (data: NSData, totalBytesReceived: Int, totalBytesExpectedToReceive: Int, response: NSHTTPURLResponse) -> Void
typealias SuccessHandler = (data: NSData, response: NSHTTPURLResponse) -> Void
typealias FailureHandler = (error: NSError) -> Void
struct DataUpload {
var data: NSData
var parameterName: String
var mimeType: String?
var fileName: String?
}
var URL: NSURL
var HTTPMethod: String
var request: NSMutableURLRequest?
var connection: NSURLConnection!
var headers: Dictionary<String, String>
var parameters: Dictionary<String, AnyObject>
var uploadData: DataUpload[]
var dataEncoding: NSStringEncoding
var timeoutInterval: NSTimeInterval
var HTTPShouldHandleCookies: Bool
var response: NSHTTPURLResponse!
var responseData: NSMutableData
var uploadProgressHandler: UploadProgressHandler?
var downloadProgressHandler: DownloadProgressHandler?
var successHandler: SuccessHandler?
var failureHandler: FailureHandler?
convenience init(URL: NSURL) {
self.init(URL: URL, method: "GET", parameters: [:])
}
init(URL: NSURL, method: String, parameters: Dictionary<String, AnyObject>) {
self.URL = URL
self.HTTPMethod = method
self.headers = [:]
self.parameters = parameters
self.uploadData = []
self.dataEncoding = NSUTF8StringEncoding
self.timeoutInterval = 60
self.HTTPShouldHandleCookies = false
self.responseData = NSMutableData()
}
init(request: NSURLRequest) {
self.request = request as? NSMutableURLRequest
self.URL = request.URL
self.HTTPMethod = request.HTTPMethod
self.headers = [:]
self.parameters = [:]
self.uploadData = []
self.dataEncoding = NSUTF8StringEncoding
self.timeoutInterval = 60
self.HTTPShouldHandleCookies = false
self.responseData = NSMutableData()
}
func start() {
if !request {
self.request = NSMutableURLRequest(URL: self.URL)
self.request!.HTTPMethod = self.HTTPMethod
self.request!.timeoutInterval = self.timeoutInterval
self.request!.HTTPShouldHandleCookies = self.HTTPShouldHandleCookies
for (key, value) in headers {
self.request!.setValue(value, forHTTPHeaderField: key)
}
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.dataEncoding))
var nonOAuthParameters = self.parameters.filter { key, _ in !key.hasPrefix("oauth_") }
if self.uploadData.count > 0 {
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
self.request!.setValue(contentType, forHTTPHeaderField:"Content-Type")
var body = NSMutableData();
for dataUpload: DataUpload in self.uploadData {
let multipartData = SwifterHTTPRequest.mulipartContentWithBounday(boundary, data: dataUpload.data, fileName: dataUpload.fileName, parameterName: dataUpload.parameterName, mimeType: dataUpload.mimeType)
body.appendData(multipartData)
}
for (key, value : AnyObject) in nonOAuthParameters {
body.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding))
body.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding))
body.appendData("\(value)".dataUsingEncoding(NSUTF8StringEncoding))
}
body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding))
self.request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
self.request!.HTTPBody = body
}
else if nonOAuthParameters.count > 0 {
if self.HTTPMethod == "GET" || self.HTTPMethod == "HEAD" || self.HTTPMethod == "DELETE" {
let queryString = nonOAuthParameters.urlEncodedQueryStringWithEncoding(self.dataEncoding)
self.request!.URL = self.URL.URLByAppendingQueryString(queryString)
self.request!.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type")
}
else {
var error: NSError?
if let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(nonOAuthParameters, options: nil, error: &error) {
self.request!.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
self.request!.HTTPBody = jsonData
}
else {
println(error!.localizedDescription)
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.connection = NSURLConnection(request: self.request!, delegate: self)
self.connection.start()
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
#endif
}
}
func addMultipartData(data: NSData, parameterName: String, mimeType: String?, fileName: String?) -> Void {
let dataUpload = DataUpload(data: data, parameterName: parameterName, mimeType: mimeType, fileName: fileName)
self.uploadData.append(dataUpload)
}
class func mulipartContentWithBounday(boundary: String, data: NSData, fileName: String?, parameterName: String, mimeType mimeTypeOrNil: String?) -> NSData {
let mimeType = mimeTypeOrNil ? mimeTypeOrNil! : "application/octet-stream"
let tempData = NSMutableData()
tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding))
let fileNameContentDisposition = fileName ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding))
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding))
tempData.appendData(data)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding))
return tempData
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
self.response = response as? NSHTTPURLResponse
self.responseData.length = 0
}
func connection(connection: NSURLConnection!, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) {
self.uploadProgressHandler?(bytesWritten: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
self.responseData.appendData(data)
let expectedContentLength = Int(self.response!.expectedContentLength)
let totalBytesReceived = self.responseData.length
if data {
self.downloadProgressHandler?(data: data, totalBytesReceived: totalBytesReceived, totalBytesExpectedToReceive: expectedContentLength, response: self.response)
}
}
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
#endif
self.failureHandler?(error: error)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
#endif
if self.response.statusCode >= 400 {
let responseString = NSString(data: self.responseData, encoding: self.dataEncoding)
let localizedDescription = SwifterHTTPRequest.descriptionForHTTPStatus(self.response.statusCode, responseString: responseString)
let userInfo = [NSLocalizedDescriptionKey: localizedDescription, "Response-Headers": self.response.allHeaderFields]
let error = NSError(domain: NSURLErrorDomain, code: self.response.statusCode, userInfo: userInfo)
self.failureHandler?(error: error)
return
}
self.successHandler?(data: self.responseData, response: self.response)
}
class func stringWithData(data: NSData, encodingName: String?) -> String {
var encoding: UInt = NSUTF8StringEncoding
if encodingName {
let encodingNameString = encodingName!.bridgeToObjectiveC() as CFStringRef
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingNameString))
if encoding == UInt(kCFStringEncodingInvalidId) {
encoding = NSUTF8StringEncoding; // by default
}
}
return NSString(data: data, encoding: encoding)
}
class func descriptionForHTTPStatus(status: Int, responseString: String) -> String {
var s = "HTTP Status \(status)"
var description: String?
// http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
if status == 400 { description = "Bad Request" }
if status == 401 { description = "Unauthorized" }
if status == 402 { description = "Payment Required" }
if status == 403 { description = "Forbidden" }
if status == 404 { description = "Not Found" }
if status == 405 { description = "Method Not Allowed" }
if status == 406 { description = "Not Acceptable" }
if status == 407 { description = "Proxy Authentication Required" }
if status == 408 { description = "Request Timeout" }
if status == 409 { description = "Conflict" }
if status == 410 { description = "Gone" }
if status == 411 { description = "Length Required" }
if status == 412 { description = "Precondition Failed" }
if status == 413 { description = "Payload Too Large" }
if status == 414 { description = "URI Too Long" }
if status == 415 { description = "Unsupported Media Type" }
if status == 416 { description = "Requested Range Not Satisfiable" }
if status == 417 { description = "Expectation Failed" }
if status == 422 { description = "Unprocessable Entity" }
if status == 423 { description = "Locked" }
if status == 424 { description = "Failed Dependency" }
if status == 425 { description = "Unassigned" }
if status == 426 { description = "Upgrade Required" }
if status == 427 { description = "Unassigned" }
if status == 428 { description = "Precondition Required" }
if status == 429 { description = "Too Many Requests" }
if status == 430 { description = "Unassigned" }
if status == 431 { description = "Request Header Fields Too Large" }
if status == 432 { description = "Unassigned" }
if status == 500 { description = "Internal Server Error" }
if status == 501 { description = "Not Implemented" }
if status == 502 { description = "Bad Gateway" }
if status == 503 { description = "Service Unavailable" }
if status == 504 { description = "Gateway Timeout" }
if status == 505 { description = "HTTP Version Not Supported" }
if status == 506 { description = "Variant Also Negotiates" }
if status == 507 { description = "Insufficient Storage" }
if status == 508 { description = "Loop Detected" }
if status == 509 { description = "Unassigned" }
if status == 510 { description = "Not Extended" }
if status == 511 { description = "Network Authentication Required" }
if description {
s = s + ": " + description! + ", Response: " + responseString
}
return s
}
}
| 49ef3fb7b979637b16c23aed822b222c | 43.372168 | 221 | 0.655313 | false | false | false | false |
IngmarStein/swift | refs/heads/master | validation-test/compiler_crashers_fixed/02127-swift-modulefile-maybereadpattern.swift | apache-2.0 | 11 | // 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: not %target-swift-frontend %s -parse
extension String {
func f: d = Swift.Type
func b<1 {
struct c<T>()).C) -> {
class d) -> Int {
}
return b() {
self.c == j> T> ((({
extension String {
var b {
}
}
}
case b {
class c {
}
class B {
class func f(bytes: Array) -> Void>() -> {
}
}
}
}
}
var f == {
class A {
}
})
}
protocol d {
self.b.Iterator.dynamicType.Iterator.Element == {
}
func g: b = a
typealias B : Boolean, f
| 37b6008d9f74e57021c4794264f5e7d1 | 17.804878 | 78 | 0.656291 | false | false | false | false |
linchaosheng/CSSwiftWB | refs/heads/master | SwiftCSWB 3/SwiftCSWB/Class/Home/C/WBQRcodeViewController.swift | apache-2.0 | 1 | //
// WBQRcodeViewController.swift
// SwiftCSWB
//
// Created by LCS on 16/4/24.
// Copyright © 2016年 Apple. All rights reserved.
//
import UIKit
import AVFoundation
class WBQRcodeViewController: UIViewController {
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var scanLineView: UIImageView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var containerViewHeight: NSLayoutConstraint!
@IBOutlet weak var tabBar: UITabBar!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var resultLabel: UILabel!
// 会话对象
lazy var session : AVCaptureSession = AVCaptureSession()
// 输入对象
lazy var input : AVCaptureInput? = {
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do{
let inputDevice = try AVCaptureDeviceInput(device: device)
return inputDevice
}catch{
print(error)
return nil
}
}()
// 输出对象
lazy var output : AVCaptureMetadataOutput = AVCaptureMetadataOutput()
// 预览图层
lazy var previewLayer : AVCaptureVideoPreviewLayer = {
let preview = AVCaptureVideoPreviewLayer(session: self.session)
preview?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
return preview!
}()
// 用于添加二维码定位边线的图层
fileprivate lazy var drawLayer : CALayer = {
let layer = CALayer()
layer.frame = UIScreen.main.bounds
return layer
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.done, target: self, action: #selector(WBQRcodeViewController.closeVC))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: UIBarButtonItemStyle.done, target: self, action: #selector(WBQRcodeViewController.save))
self.navigationController?.navigationBar.barTintColor = UIColor.black
tabBar.selectedItem = tabBar.items![0]
tabBar.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 1. 开始扫描动画
startAnimation()
// 2. 开始扫描二维码
startScan()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func closeVC(){
dismiss(animated: true, completion: nil)
}
func save(){
}
func startAnimation(){
topConstraint.constant = -containerViewHeight.constant
self.scanLineView.layoutIfNeeded()
// 执行动画
UIView.animate(withDuration: 2.0, animations: { () -> Void in
UIView.setAnimationRepeatCount(MAXFLOAT)
self.topConstraint.constant = self.containerViewHeight.constant
// 如果动画是通过约束实现的则需要加上layoutIfNeeded
self.scanLineView.layoutIfNeeded()
})
}
func startScan(){
// 2.1 判断是否能够将输入添加到会话中
if (!session.canAddInput(input)){
return
}
// 2.2 判断是否能够将输出添加到会话中
if (!session.canAddOutput(output)){
return
}
// 2.3 将输入输出添加到会话
session.addInput(input)
session.addOutput(output)
// 2.4 设置输出能够解析的数据类型(iOS系统所支持的所有类型) 可支持类型在AVMetadataObject.h
output.metadataObjectTypes = output.availableMetadataObjectTypes
// 2.5 设置可扫描区域(需要自己研究一下,默认0,0,1,1)
output.rectOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1)
// 2.6 设置输出对象的代理, 只要解析成功就会通知代理
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
// 2.7 设置预览图层
mainView.layer.insertSublayer(previewLayer, at: 0)
// 2.8 告诉session开始扫描
session.startRunning()
}
@IBAction func QRcodeCardOnClick(_ sender: AnyObject) {
let QRcodeCardVC = WBQRCodeCardViewController()
navigationController?.pushViewController(QRcodeCardVC, animated: true)
}
}
extension WBQRcodeViewController : UITabBarDelegate{
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if item.tag == 1{
containerViewHeight.constant = 300
}else{
containerViewHeight.constant = 150
}
// 停止动画
self.scanLineView.layer.removeAllAnimations()
// 重新开始动画
startAnimation()
}
}
extension WBQRcodeViewController : AVCaptureMetadataOutputObjectsDelegate{
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!){
// 0.清空drawLayer上的shapeLayer
clearCorners()
// 1.获取扫描到的数据
resultLabel.text = (metadataObjects.last as AnyObject).stringValue
// 2.获取二维码位置
// 2.1 转换坐标
for object in metadataObjects{
// 2.1.1 判断数据是否是机器可识别类型
if object is AVMetadataMachineReadableCodeObject{
// 2.1.2 将坐标转换成界面可识别坐标
let codeObject = previewLayer.transformedMetadataObject(for: object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
// 2.1.3绘制图形
drawCorners(codeObject)
}
}
}
// (根据corner中的4个点绘制图形)绘制图形
func drawCorners(_ codeObject : AVMetadataMachineReadableCodeObject){
if codeObject.corners.isEmpty{
return
}
// 1. 创建绘图图层
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.red.cgColor
// 2. 创建路径
let path = UIBezierPath()
var point = CGPoint.zero
var index : Int = 0
// 从corners数组中取出第一个点,将字典中的X/Y赋值给point
index = index + 1;
point = CGPoint.init(dictionaryRepresentation: (codeObject.corners[index] as! CFDictionary))!
path.move(to: point)
// 移动到其它点
while index < codeObject.corners.count{
index = index + 1;
point = CGPoint.init(dictionaryRepresentation: (codeObject.corners[index] as! CFDictionary))!
path.addLine(to: point)
}
// 关闭路径
path.close()
// 绘制路径
shapeLayer.path = path.cgPath
// 3. 将图层添加到drawLayer图层
drawLayer.addSublayer(shapeLayer)
}
func clearCorners(){
if drawLayer.sublayers == nil || drawLayer.sublayers?.count == 0{
return
}
for subLayer in drawLayer.sublayers!{
subLayer.removeFromSuperlayer()
}
}
}
| d021c58d1f150be4bd6c2de5cc3d5ac2 | 30.198157 | 170 | 0.614476 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/Utility/EmailTypoChecker.swift | gpl-2.0 | 1 | import Foundation
private let knownDomains = Set([
/* Default domains included */
"aol.com", "att.net", "comcast.net", "facebook.com", "gmail.com", "gmx.com", "googlemail.com",
"google.com", "hotmail.com", "hotmail.co.uk", "mac.com", "me.com", "msn.com",
"live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk",
/* Other global domains */
"games.com" /* AOL */, "gmx.net", "hush.com", "hushmail.com", "icloud.com", "inbox.com",
"lavabit.com", "love.com" /* AOL */, "outlook.com", "pobox.com", "rocketmail.com" /* Yahoo */,
"safe-mail.net", "wow.com" /* AOL */, "ygm.com" /* AOL */, "ymail.com" /* Yahoo */, "zoho.com", "fastmail.fm",
"yandex.com",
/* United States ISP domains */
"bellsouth.net", "charter.net", "comcast.com", "cox.net", "earthlink.net", "juno.com",
/* British ISP domains */
"btinternet.com", "virginmedia.com", "blueyonder.co.uk", "freeserve.co.uk", "live.co.uk",
"ntlworld.com", "o2.co.uk", "orange.net", "sky.com", "talktalk.co.uk", "tiscali.co.uk",
"virgin.net", "wanadoo.co.uk", "bt.com",
/* Domains used in Asia */
"sina.com", "qq.com", "naver.com", "hanmail.net", "daum.net", "nate.com", "yahoo.co.jp", "yahoo.co.kr", "yahoo.co.id", "yahoo.co.in", "yahoo.com.sg", "yahoo.com.ph",
/* French ISP domains */
"hotmail.fr", "live.fr", "laposte.net", "yahoo.fr", "wanadoo.fr", "orange.fr", "gmx.fr", "sfr.fr", "neuf.fr", "free.fr",
/* German ISP domains */
"gmx.de", "hotmail.de", "live.de", "online.de", "t-online.de" /* T-Mobile */, "web.de", "yahoo.de",
/* Russian ISP domains */
"mail.ru", "rambler.ru", "yandex.ru", "ya.ru", "list.ru",
/* Belgian ISP domains */
"hotmail.be", "live.be", "skynet.be", "voo.be", "tvcablenet.be", "telenet.be",
/* Argentinian ISP domains */
"hotmail.com.ar", "live.com.ar", "yahoo.com.ar", "fibertel.com.ar", "speedy.com.ar", "arnet.com.ar",
/* Domains used in Mexico */
"hotmail.com", "gmail.com", "yahoo.com.mx", "live.com.mx", "yahoo.com", "hotmail.es", "live.com", "hotmail.com.mx", "prodigy.net.mx", "msn.com"
])
/// Provides suggestions to fix common typos on email addresses.
///
/// It tries to match the email domain with a list of popular hosting providers,
/// and suggest a correction if it looks like a typo.
///
open class EmailTypoChecker: NSObject {
/// Suggest a correction to a typo in the given email address.
///
/// If it doesn't detect any typo, it returns the given email.
///
@objc(guessCorrectionForEmail:)
open static func guessCorrection(email: String) -> String {
let components = email.components(separatedBy: "@")
guard components.count == 2 else {
return email
}
let (account, domain) = (components[0], components[1])
// If the domain name is empty, don't try to suggest anything
guard !domain.isEmpty else {
return email
}
// If the domain name is too long, don't try suggestion (resource consuming and useless)
guard domain.characters.count < lengthOfLongestKnownDomain() + 1 else {
return email
}
let suggestedDomain = suggest(domain)
return account + "@" + suggestedDomain
}
}
private func suggest(_ word: String) -> String {
if knownDomains.contains(word) {
return word
}
let candidates = edits(word).filter({ knownDomains.contains($0) })
return candidates.first ?? word
}
private func edits(_ word: String) -> [String] {
// deletes
let deleted = deletes(word)
let transposed = transposes(word)
let replaced = alphabet.characters.flatMap({ character in
return replaces(character, ys: word.characters)
})
let inserted = alphabet.characters.flatMap({ character in
return between(character, ys: word.characters)
})
return deleted + transposed + replaced + inserted
}
private func deletes(_ word: String) -> [String] {
return word.characters.indices.map({ word.removing(at: $0) })
}
private func transposes(_ word: String) -> [String] {
return word.characters.indices.flatMap({ index in
let (i, j) = (index, word.index(after: index))
guard j < word.endIndex else {
return nil
}
var copy = word
copy.replaceSubrange(i...j, with: String(word[j]) + String(word[i]))
return copy
})
}
private func replaces(_ x: Character, ys: String.CharacterView) -> [String] {
guard let head = ys.first else {
return [String(x)]
}
let tail = ys.dropFirst()
return [String(x) + String(tail)] + replaces(x, ys: tail).map({ String(head) + $0 })
}
private func between(_ x: Character, ys: String.CharacterView) -> [String] {
guard let head = ys.first else {
return [String(x)]
}
let tail = ys.dropFirst()
return [String(x) + String(ys)] + between(x, ys: tail).map({ String(head) + $0 })
}
private let alphabet = "abcdefghijklmnopqrstuvwxyz"
private func lengthOfLongestKnownDomain() -> Int {
return knownDomains.map({ $0.characters.count }).max() ?? 0
}
| 156a745f479182abae8ca4b06e0950c6 | 36.467153 | 169 | 0.612507 | false | false | false | false |
einsteinx2/iSub | refs/heads/master | Classes/Server Loading/Loaders/New Model/StatusLoader.swift | gpl-3.0 | 1 | //
// StatusLoader.swift
// Pods
//
// Created by Benjamin Baron on 2/12/16.
//
//
import Foundation
final class StatusLoader: ApiLoader {
fileprivate(set) var server: Server?
fileprivate(set) var url: String
fileprivate(set) var username: String
fileprivate(set) var password: String
fileprivate(set) var basicAuth: Bool
fileprivate(set) var versionString: String?
fileprivate(set) var majorVersion: Int?
fileprivate(set) var minorVersion: Int?
convenience init(server: Server) {
let password = server.password ?? ""
self.init(url: server.url, username: server.username, password: password, basicAuth: server.basicAuth)
self.server = server
}
init(url: String, username: String, password: String, basicAuth: Bool = false, serverId: Int64? = nil) {
self.url = url
self.username = username
self.password = password
self.basicAuth = basicAuth
if let serverId = serverId {
super.init(serverId: serverId)
} else {
super.init()
}
}
override func createRequest() -> URLRequest? {
return URLRequest(subsonicAction: .ping, baseUrl: url, username: username, password: password, basicAuth: basicAuth)
}
override func processResponse(root: RXMLElement) -> Bool {
if root.tag == "subsonic-response" {
self.versionString = root.attribute("version")
if let versionString = self.versionString {
let splitVersion = versionString.components(separatedBy: ".")
let count = splitVersion.count
if count > 0 {
self.majorVersion = Int(splitVersion[0])
if count > 1 {
self.minorVersion = Int(splitVersion[1])
}
}
}
return true
} else {
// This is not a Subsonic server, so fail
DispatchQueue.main.async {
self.failed(error: NSError(iSubCode: .notSubsonicServer))
}
return false
}
}
override func failed(error: Error?) {
if let error = error {
if error.code == 40 {
// Incorrect credentials, so fail
super.failed(error: NSError(iSubCode: .invalidCredentials))
return
} else if error.code == 60 {
// Subsonic trial ended
super.failed(error: NSError(iSubCode: .subsonicTrialExpired))
return
}
}
super.failed(error: error)
}
}
| f15cf752717303397d475b1c2e166815 | 30.821429 | 124 | 0.561167 | false | false | false | false |
frootloops/swift | refs/heads/master | test/SILGen/objc_thunks.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
import ansible
class Hoozit : Gizmo {
@objc func typical(_ x: Int, y: Gizmo) -> Gizmo { return y }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[X:%.*]] : @trivial $Int, [[Y:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[Y_COPY:%.*]] = copy_value [[Y]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.typical
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytF : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[X]], [[Y_COPY]], [[BORROWED_THIS_COPY]]) {{.*}} line:[[@LINE-8]]:14:auto_gen
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit
// CHECK-NEXT: return [[RES]] : $Gizmo{{.*}} line:[[@LINE-11]]:14:auto_gen
// CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo'
// NS_CONSUMES_SELF by inheritance
override func fork() { }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4forkyyFTo : $@convention(objc_method) (@owned Hoozit) -> () {
// CHECK: bb0([[THIS:%.*]] : @owned $Hoozit):
// CHECK-NEXT: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC4forkyyF : $@convention(method) (@guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[BORROWED_THIS]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS]] from [[THIS]]
// CHECK-NEXT: destroy_value [[THIS]]
// CHECK-NEXT: return
// CHECK-NEXT: }
// NS_CONSUMED 'gizmo' argument by inheritance
override class func consume(_ gizmo: Gizmo?) { }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZTo : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () {
// CHECK: bb0([[GIZMO:%.*]] : @owned $Optional<Gizmo>, [[THIS:%.*]] : @trivial $@objc_metatype Hoozit.Type):
// CHECK-NEXT: [[THICK_THIS:%[0-9]+]] = objc_to_thick_metatype [[THIS]] : $@objc_metatype Hoozit.Type to $@thick Hoozit.Type
// CHECK: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZ : $@convention(method) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[GIZMO]], [[THICK_THIS]])
// CHECK-NEXT: return
// CHECK-NEXT: }
// NS_RETURNS_RETAINED by family (-copy)
@objc func copyFoo() -> Gizmo { return self }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// Override the normal family conventions to make this non-consuming and
// returning at +0.
@objc func initFoo() -> Gizmo { return self }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7initFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7initFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
@objc var typicalProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[SELF:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.typicalProperty.getter
// CHECK-NEXT: [[GETIMPL:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvg
// CHECK-NEXT: [[RES:%.*]] = apply [[GETIMPL]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RES]] : $Gizmo
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK: bb0(%0 : @guaranteed $Hoozit):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.typicalProperty
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Gizmo
// CHECK-NEXT: [[RES:%.*]] = load [copy] [[READ]] {{.*}}
// CHECK-NEXT: end_access [[READ]] : $*Gizmo
// CHECK-NEXT: return [[RES]]
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Gizmo
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Hoozit
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: // function_ref objc_thunks.Hoozit.typicalProperty.setter
// CHECK: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs
// CHECK: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: return [[RES]] : $(), loc {{.*}}, scope {{.*}} // id: {{.*}} line:[[@LINE-34]]:13:auto_gen
// CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvsTo'
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs
// CHECK: bb0([[ARG0:%.*]] : @owned $Gizmo, [[ARG1:%.*]] : @guaranteed $Hoozit):
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[ARG0_COPY:%.*]] = copy_value [[BORROWED_ARG0]]
// CHECK: [[ADDR:%.*]] = ref_element_addr [[ARG1]] : {{.*}}, #Hoozit.typicalProperty
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Gizmo
// CHECK: assign [[ARG0_COPY]] to [[WRITE]] : $*Gizmo
// CHECK: end_access [[WRITE]] : $*Gizmo
// CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK: destroy_value [[ARG0]]
// CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs'
// NS_RETURNS_RETAINED getter by family (-copy)
@objc var copyProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo {
// CHECK: bb0([[SELF:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.getter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvg
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvg
// CHECK: bb0(%0 : @guaranteed $Hoozit):
// CHECK: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.copyProperty
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Gizmo
// CHECK-NEXT: [[RES:%.*]] = load [copy] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Gizmo
// CHECK-NEXT: return [[RES]]
// -- setter is normal
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.setter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs
// CHECK: bb0([[ARG1:%.*]] : @owned $Gizmo, [[SELF:%.*]] : @guaranteed $Hoozit):
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK: [[ADDR:%.*]] = ref_element_addr [[SELF]] : {{.*}}, #Hoozit.copyProperty
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Gizmo
// CHECK: assign [[ARG1_COPY]] to [[WRITE]]
// CHECK: end_access [[WRITE]] : $*Gizmo
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: } // end sil function '_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs'
@objc var roProperty: Gizmo { return self }
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit
// CHECK-NEXT: return [[RES]] : $Gizmo
// CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC10roPropertySo5GizmoCvgTo'
// -- no setter
// CHECK-NOT: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvsTo
@objc var rwProperty: Gizmo {
get {
return self
}
set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
@objc var copyRWProperty: Gizmo {
get {
return self
}
set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo {
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NOT: return
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter is normal
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
@objc var initProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
@objc var propComputed: Gizmo {
@objc(initPropComputedGetter) get { return self }
@objc(initPropComputedSetter:) set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
// Don't export generics to ObjC yet
func generic<T>(_ x: T) {}
// CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7generic{{.*}}
// Constructor.
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSi7bellsOn_tcfc : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[GIZMO:%[0-9]+]] = upcast [[SELF:%[0-9]+]] : $Hoozit to $Gizmo
// CHECK: [[BORROWED_GIZMO:%.*]] = begin_borrow [[GIZMO]]
// CHECK: [[CAST_BORROWED_GIZMO:%.*]] = unchecked_ref_cast [[BORROWED_GIZMO]] : $Gizmo to $Hoozit
// CHECK: [[SUPERMETHOD:%[0-9]+]] = objc_super_method [[CAST_BORROWED_GIZMO]] : $Hoozit, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK-NEXT: end_borrow [[BORROWED_GIZMO]] from [[GIZMO]]
// CHECK-NEXT: [[SELF_REPLACED:%[0-9]+]] = apply [[SUPERMETHOD]](%0, [[X:%[0-9]+]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK-NOT: unconditional_checked_cast downcast [[SELF_REPLACED]] : $Gizmo to $Hoozit
// CHECK: unchecked_ref_cast
// CHECK: return
override init(bellsOn x : Int) {
super.init(bellsOn: x)
other()
}
// Subscript
@objc subscript (i: Int) -> Hoozit {
// Getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicigTo : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit
// CHECK: bb0([[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicig : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RESULT]] : $Hoozit
get {
return self
}
// Setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicisTo : $@convention(objc_method) (Hoozit, Int, Hoozit) -> ()
// CHECK: bb0([[VALUE:%[0-9]+]] : @unowned $Hoozit, [[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Hoozit
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicis : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[VALUE_COPY]], [[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
// CHECK: } // end sil function '_T011objc_thunks6HoozitCACSicisTo'
set {}
}
}
class Wotsit<T> : Gizmo {
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC5plainyyFTo : $@convention(objc_method) <T> (Wotsit<T>) -> () {
// CHECK: bb0([[SELF:%.*]] : @unowned $Wotsit<T>):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T>
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC5plainyyF : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> ()
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T>
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
@objc func plain() { }
func generic<U>(_ x: U) {}
var property : T
init(t: T) {
self.property = t
super.init()
}
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC11descriptionSSvgTo : $@convention(objc_method) <T> (Wotsit<T>) -> @autoreleased NSString {
// CHECK: bb0([[SELF:%.*]] : @unowned $Wotsit<T>):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T>
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC11descriptionSSvg : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String
// CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE:%.*]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T>
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK-NEXT: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]]
// CHECK-NEXT: [[NSRESULT:%.*]] = apply [[BRIDGE]]([[BORROWED_RESULT]]) : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK-NEXT: end_borrow [[BORROWED_RESULT]] from [[RESULT]]
// CHECK-NEXT: destroy_value [[RESULT]]
// CHECK-NEXT: return [[NSRESULT]] : $NSString
// CHECK-NEXT: }
override var description : String {
return "Hello, world."
}
// Ivar destroyer
// CHECK: sil hidden @_T011objc_thunks6WotsitCfETo
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGycfcTo : $@convention(objc_method) <T> (@owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGSi7bellsOn_tcfcTo : $@convention(objc_method) <T> (Int, @owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
}
// CHECK-NOT: sil hidden [thunk] @_TToF{{.*}}Wotsit{{.*}}
// Extension initializers, properties and methods need thunks too.
extension Hoozit {
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSi3int_tcfcTo : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
@objc dynamic convenience init(int i: Int) { self.init(bellsOn: i) }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSd6double_tcfc : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit
convenience init(double d: Double) {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[X_BOX:%[0-9]+]] = alloc_box ${ var X }
var x = X()
// CHECK: [[CTOR:%[0-9]+]] = objc_method [[SELF:%[0-9]+]] : $Hoozit, #Hoozit.init!initializer.1.foreign : (Hoozit.Type) -> (Int) -> Hoozit, $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
// CHECK: [[NEW_SELF:%[0-9]+]] = apply [[CTOR]]
// CHECK: store [[NEW_SELF]] to [init] [[PB_BOX]] : $*Hoozit
// CHECK: return
self.init(int:Int(d))
other()
}
func foof() {}
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4foofyyFTo : $@convention(objc_method) (Hoozit) -> () {
var extensionProperty: Int { return 0 }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC17extensionPropertySivg : $@convention(method) (@guaranteed Hoozit) -> Int
}
// Calling objc methods of subclass should go through native entry points
func useHoozit(_ h: Hoozit) {
// sil @_T011objc_thunks9useHoozityAA0D0C1h_tF
// In the class decl, overrides importd method, 'dynamic' was inferred
h.fork()
// CHECK: objc_method {{%.*}} : {{.*}}, #Hoozit.fork!1.foreign
// In an extension, 'dynamic' was inferred.
h.foof()
// CHECK: objc_method {{%.*}} : {{.*}}, #Hoozit.foof!1.foreign
}
func useWotsit(_ w: Wotsit<String>) {
// sil @_T011objc_thunks9useWotsitySo0D0CySSG1w_tF
w.plain()
// CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.plain!1 :
w.generic(2)
// CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.generic!1 :
// Inherited methods only have objc entry points
w.clone()
// CHECK: objc_method {{%.*}} : {{.*}}, #Gizmo.clone!1.foreign
}
func other() { }
class X { }
// CHECK-LABEL: sil hidden @_T011objc_thunks8propertySiSo5GizmoCF
func property(_ g: Gizmo) -> Int {
// CHECK: bb0([[ARG:%.*]] : @owned $Gizmo):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.count!getter.1.foreign
return g.count
}
// CHECK-LABEL: sil hidden @_T011objc_thunks13blockPropertyySo5GizmoCF
func blockProperty(_ g: Gizmo) {
// CHECK: bb0([[ARG:%.*]] : @owned $Gizmo):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!setter.1.foreign
g.block = { }
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!getter.1.foreign
g.block()
}
class DesignatedStubs : Gizmo {
var i: Int
override init() { i = 5 }
// CHECK-LABEL: sil hidden @_T011objc_thunks15DesignatedStubsCSQyACGSi7bellsOn_tcfc
// CHECK: string_literal utf8 "objc_thunks.DesignatedStubs"
// CHECK: string_literal utf8 "init(bellsOn:)"
// CHECK: string_literal utf8 "{{.*}}objc_thunks.swift"
// CHECK: function_ref @_T0s25_unimplementedInitializers5NeverOs12StaticStringV9className_AE04initG0AE4fileSu4lineSu6columntF
// CHECK: return
// CHECK-NOT: sil hidden @_TFCSo15DesignatedStubsc{{.*}}
}
class DesignatedOverrides : Gizmo {
var i: Int = 5
// CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGycfc
// CHECK-NOT: return
// CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int
// CHECK: objc_super_method [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> () -> Gizmo!, $@convention(objc_method) (@owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: return
// CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGSi7bellsOn_tcfc
// CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int
// CHECK: objc_super_method [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: return
}
// Make sure we copy blocks passed in as IUOs - <rdar://problem/22471309>
func registerAnsible() {
// CHECK: function_ref @_T011objc_thunks15registerAnsibleyyFyyycSgcfU_
Ansible.anseAsync({ completion in completion!() })
}
| 5d84943484bbd2074f244936fab57bbc | 54.618321 | 231 | 0.627917 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/Common/Recents/Views/RootTabEmptyView.swift | apache-2.0 | 1 | //
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Reusable
/// `RootTabEmptyView` is a view to display when there is no UI item to display on a screen.
@objcMembers
final class RootTabEmptyView: UIView, NibLoadable {
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var imageView: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var informationLabel: UILabel!
@IBOutlet private(set) weak var contentView: UIView!
// MARK: Private
private var theme: Theme!
// MARK: Public
// MARK: - Setup
class func instantiate() -> RootTabEmptyView {
let view = RootTabEmptyView.loadFromNib()
view.theme = ThemeService.shared().theme
return view
}
// MARK: - Life cycle
override func awakeFromNib() {
super.awakeFromNib()
self.informationLabel.text = VectorL10n.homeEmptyViewInformation
}
// MARK: - Public
func fill(with image: UIImage, title: String, informationText: String) {
self.imageView.image = image
self.titleLabel.text = title
self.informationLabel.text = informationText
}
}
// MARK: - Themable
extension RootTabEmptyView: Themable {
func update(theme: Theme) {
self.theme = theme
self.backgroundColor = theme.backgroundColor
self.titleLabel.textColor = theme.textPrimaryColor
self.informationLabel.textColor = theme.textSecondaryColor
}
}
| 2e42c9cbb10cda8d4c987d804e0ea9c3 | 27.333333 | 92 | 0.671059 | false | false | false | false |
mackoj/GOTiPad | refs/heads/master | GOTIpad/GameLogic/Game.swift | mit | 1 | //
// Game.swift
// GOTIpad
//
// Created by jeffreymacko on 29/12/2015.
// Copyright © 2015 jeffreymacko. All rights reserved.
//
import Foundation
class Game {
var turn : UInt
var wildingTrack : UInt
let players : [Player]
var startTime : Date
let lands : [Land]
let westerosCardDeck1 : EventCardDeck
let westerosCardDeck2 : EventCardDeck
let westerosCardDeck3 : EventCardDeck
let wildingsCardDeck : WildingsCardDeck
// utiliser un pointeur ?
var ironThroneTrack : [Player]
var valerianSwordTrack : [Player]
var kingsCourtTrack : [Player]
let bank : Bank
var gamePhase : GamePhase = .globaleGameStateInit
func setGamePhase(actualGamePhase : GamePhase) {
gamePhase = actualGamePhase
self.executeNextGamePhase(gamePhase: actualGamePhase)
}
// var delegate : GameProtocol
init(players inputPlayer : [Player]) {
players = inputPlayer
ironThroneTrack = inputPlayer
valerianSwordTrack = inputPlayer
kingsCourtTrack = inputPlayer
bank = Bank()
turn = 0
startTime = Current.date()
// filling decks
westerosCardDeck1 = EventCardDeck(deckType: .deck1)
westerosCardDeck2 = EventCardDeck(deckType: .deck2)
westerosCardDeck3 = EventCardDeck(deckType: .deck3)
wildingsCardDeck = WildingsCardDeck(cards: [])
// Fill Lands
self.lands = LandFactory.fillLands(seed: Current.seed)
// Position on wildings Track
wildingTrack = 0;
// Suffle Decks
setGamePhase(actualGamePhase: .globaleGameStateInit)
}
func pause() {}
func stop() {}
func restart() {
turn = 0
setGamePhase(actualGamePhase: .globaleGameStateInit)
}
func processNextTurn() {}
// + (instancetype)sharedGOTGame;
// + (void)killInstance;
// + (instancetype)getInstance;
func executeNextGamePhase(gamePhase : GamePhase) {
switch gamePhase {
case .globaleGameStateInit:
// Allows Player to Select Familys
// Set Defaut Pawns
// Set Defaut power token
// Position on influence Track
// Position on supply Track
// Position on victory Track
// Set Game Limit & misc Parameters
setGamePhase(actualGamePhase: .globaleGameStateStartFirstTurn)
case .globaleGameStateStartFirstTurn: break
case .gamePhaseStartWesteros:
break
case .gameStateForWesterosGamePhaseAdvanceGameRoundMarker:
if self.turn == Current.endGameTurn {
setGamePhase(actualGamePhase: .gamePhaseWinningResolution) // fin du jeu
} else {
self.turn += 1
setGamePhase(actualGamePhase: .gameStateForWesterosGamePhaseDrawEventCards)
}
case .gameStateForWesterosGamePhaseDrawEventCards:
break
case .gameStateForWesterosGamePhaseAdvanceWildlingsTrack:
break
case .gameStateForWesterosGamePhaseWildlingsAttack:
break
case .gameStateForWesterosGamePhaseResolveEventCards:
break
case .gamePhaseEndWesteros:
break
case .gamePhaseStartPlanning:
// Dis a l'UI que la phase X commande si elle veut jouer une animation ou quoi
setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseAssignOrders)
case .gameStateForPlanningGamePhaseAssignOrders:
// demander aux joueurs de positionner leur pions d'action
// player in order + completion ?
for player in self.ironThroneTrack {
self.assignOrders(player: player) // future ???
}
// une fois que tout les joueurs on jouer
if self.allOrdersHasBeenPlayed() {
setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseRevealOrders)
}
case .gameStateForPlanningGamePhaseRevealOrders:
// player in order + completion ?
for player in self.ironThroneTrack {
for orderToken in player.house.orderTokens {
if orderToken.isOnBoard {
orderToken.isFold
}
}
}
self.revealOrders() // future ???
setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseUseMessengerRaven)
case .gameStateForPlanningGamePhaseUseMessengerRaven:
self.useMessageRaven(player: self.kingsCourtTrack.first!) // useNonEmptyArray
let ravenAction = RavenMessengerAction.changeOrder
switch ravenAction {
case .nothing: break
case .changeOrder: break
case .lookIntoWildingsDeck: break
}
setGamePhase(actualGamePhase: .gamePhaseEndPlanning)
case .gamePhaseEndPlanning:
self.endPlanningPhase()
setGamePhase(actualGamePhase: .gamePhaseStartAction)
case .gamePhaseStartAction:
break
case .gameStateForActionGamePhaseResolveRaidOrders:
break
case .gameStateForActionGamePhaseResolveMarchOrders:
break
case .gamePhaseStartCombat:
break
case .gamePhaseCombatCallForSupport:
break
case .gamePhaseCombatCalculateInitialCombatStrength:
break
case .gamePhaseCombatChooseandRevealHouseCards:
break
case .gamePhaseCombatUseValyrianSteelBlade:
break
case .gamePhaseCombatCalculateFinalCombatStrength:
break
case .gamePhaseCombatResolution:
break
case .gamePhaseCombatResolutionDetermineVictor:
break
case .gamePhaseCombatResolutionCasualties:
break
case .gamePhaseCombatResolutionRetreatsandRouting:
break
case .gamePhaseCombatResolutionCombatCleanUp:
break
case .gamePhaseEndCombat:
break
case .gameStateForActionGamePhaseResolveConsolidatePowerOrders:
break
case .gameStateForActionGameCleanUp:
break
case .gamePhaseEndAction:
break
case .gamePhaseWinningResolution:
break
case .globaleGameStateFinish:
break
}
}
}
| d6ec528d654d566d054648cdc5408b23 | 27.173267 | 84 | 0.710596 | false | false | false | false |
miradesne/gamepoll | refs/heads/master | gamepoll/GPGamerProfileViewController.swift | mit | 1 | //
// GPGameProfileViewController.swift
//
//
// Created by Mira Chen on 1/12/16.
//
//
import UIKit
import Charts
class GPGamerProfileViewController: UIViewController {
var traits: [String]!
@IBOutlet weak var parentScrollView: UIScrollView!
@IBOutlet weak var radarChartView: RadarChartView!
@IBAction func dismissSelf(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//round up scoll view corners
parentScrollView.layer.cornerRadius = 10
parentScrollView.layer.masksToBounds = true
radarChartView.noDataText = "no data"
//offscreen
radarChartView.setDescriptionTextPosition(x: 1000, y: 1000)
traits = ["Graphics", "Story", "Sound", "Learning Curve", "Novelty"]
let scores = [3.9, 4.0, 1.0, 3.5, 5.0]
setData(traits, scores: scores)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setData(traits: [String], scores: [Double]) {
var yAxisScores: [ChartDataEntry] = [ChartDataEntry]()
var xAxisTraits: [String] = [String]()
for var i = 0; i < scores.count; i++ {
yAxisScores.append(ChartDataEntry(value: scores[i], xIndex: i))
}
for var i = 0; i < traits.count; i++ {
xAxisTraits.append(traits[i])
}
let dataset: RadarChartDataSet = RadarChartDataSet(yVals: yAxisScores, label: "Traits")
dataset.drawFilledEnabled = true
dataset.lineWidth = 2.0
dataset.colors = [UIColor.flatGreenSeaColor()]
dataset.setDrawHighlightIndicators(false)
dataset.drawValuesEnabled = false
// Configure Radar Chart
radarChartView.yAxis.customAxisMax = 5.0
radarChartView.yAxis.customAxisMin = 0
radarChartView.yAxis.startAtZeroEnabled = false
radarChartView.yAxis.drawLabelsEnabled = false
radarChartView.userInteractionEnabled = false
let data: RadarChartData = RadarChartData(xVals: xAxisTraits, dataSets: [dataset])
radarChartView.data = data
let bgColor = UIColor(red: 239.0/255.0, green: 239.0/255.0, blue: 244.0/255.0, alpha: 1)
radarChartView.backgroundColor = bgColor
}
/*
// 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.
}
*/
}
| 43ec6383424aefb0abf8eb7809fb28a3 | 32.352941 | 106 | 0.643739 | false | false | false | false |
Zverik/omim | refs/heads/master | iphone/Maps/UI/Search/Filters/FilterCollectionHolderCell.swift | apache-2.0 | 1 | @objc(MWMFilterCollectionHolderCell)
final class FilterCollectionHolderCell: MWMTableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet private weak var collectionViewHeight: NSLayoutConstraint!
private weak var tableView: UITableView?
override var frame: CGRect {
didSet {
guard #available(iOS 10, *) else {
if (frame.size.height < 1 /* minimal correct height */) {
frame.size.height = collectionViewHeight.constant
tableView?.refresh()
}
return
}
}
}
private func layout() {
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()
collectionViewHeight.constant = collectionView.contentSize.height
}
func config(tableView: UITableView?) {
layout()
collectionView.allowsMultipleSelection = true;
isSeparatorHidden = true
backgroundColor = UIColor.pressBackground()
guard #available(iOS 10, *) else {
self.tableView = tableView
return
}
}
override func layoutSubviews() {
super.layoutSubviews()
layout()
}
}
| d68c8ae66be7a23d0ca5c6272caaaf24 | 25.463415 | 70 | 0.688479 | false | false | false | false |
bringg/customer-sdk-ios-demo | refs/heads/master | Pods/Socket.IO-Client-Swift/Source/SocketIO/Ack/SocketAckEmitter.swift | apache-2.0 | 5 | //
// SocketAckEmitter.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 9/16/15.
//
// 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 Dispatch
import Foundation
/// A class that represents a waiting ack call.
///
/// **NOTE**: You should not store this beyond the life of the event handler.
public final class SocketAckEmitter : NSObject {
private unowned let socket: SocketIOClient
private let ackNum: Int
/// A view into this emitter where emits do not check for binary data.
///
/// Usage:
///
/// ```swift
/// ack.rawEmitView.with(myObject)
/// ```
///
/// **NOTE**: It is not safe to hold on to this view beyond the life of the socket.
@objc
public private(set) lazy var rawEmitView = SocketRawAckView(socket: socket, ackNum: ackNum)
// MARK: Properties
/// If true, this handler is expecting to be acked. Call `with(_: SocketData...)` to ack.
public var expected: Bool {
return ackNum != -1
}
// MARK: Initializers
/// Creates a new `SocketAckEmitter`.
///
/// - parameter socket: The socket for this emitter.
/// - parameter ackNum: The ack number for this emitter.
public init(socket: SocketIOClient, ackNum: Int) {
self.socket = socket
self.ackNum = ackNum
}
// MARK: Methods
/// Call to ack receiving this event.
///
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
/// will be emitted. The structure of the error data is `[ackNum, items, theError]`
///
/// - parameter items: A variable number of items to send when acking.
public func with(_ items: SocketData...) {
guard ackNum != -1 else { return }
do {
socket.emitAck(ackNum, with: try items.map({ try $0.socketRepresentation() }))
} catch {
socket.handleClientEvent(.error, data: [ackNum, items, error])
}
}
/// Call to ack receiving this event.
///
/// - parameter items: An array of items to send when acking. Use `[]` to send nothing.
@objc
public func with(_ items: [Any]) {
guard ackNum != -1 else { return }
socket.emitAck(ackNum, with: items)
}
}
/// A class that represents an emit that will request an ack that has not yet been sent.
/// Call `timingOut(after:callback:)` to complete the emit
/// Example:
///
/// ```swift
/// socket.emitWithAck("myEvent").timingOut(after: 1) {data in
/// ...
/// }
/// ```
public final class OnAckCallback : NSObject {
private let ackNumber: Int
private let binary: Bool
private let items: [Any]
private weak var socket: SocketIOClient?
init(ackNumber: Int, items: [Any], socket: SocketIOClient, binary: Bool = true) {
self.ackNumber = ackNumber
self.items = items
self.socket = socket
self.binary = binary
}
/// :nodoc:
deinit {
DefaultSocketLogger.Logger.log("OnAckCallback for \(ackNumber) being released", type: "OnAckCallback")
}
// MARK: Methods
/// Completes an emitWithAck. If this isn't called, the emit never happens.
///
/// - parameter seconds: The number of seconds before this emit times out if an ack hasn't been received.
/// - parameter callback: The callback called when an ack is received, or when a timeout happens.
/// To check for timeout, use `SocketAckStatus`'s `noAck` case.
@objc
public func timingOut(after seconds: Double, callback: @escaping AckCallback) {
guard let socket = self.socket, ackNumber != -1 else { return }
socket.ackHandlers.addAck(ackNumber, callback: callback)
socket.emit(items, ack: ackNumber, binary: binary)
guard seconds != 0 else { return }
socket.manager?.handleQueue.asyncAfter(deadline: DispatchTime.now() + seconds) {[weak socket] in
guard let socket = socket else { return }
socket.ackHandlers.timeoutAck(self.ackNumber)
}
}
}
| 11c37144229c37905dd3d851806e6f56 | 33.972603 | 116 | 0.656483 | false | false | false | false |
bastienFalcou/FindMyContacts | refs/heads/master | Missed Contacts Widget/TodayViewModel.swift | mit | 1 | //
// TodayViewModel.swift
// FindMyContacts
//
// Created by Bastien Falcou on 7/15/17.
// Copyright © 2017 Bastien Falcou. All rights reserved.
//
import Foundation
import ReactiveSwift
import DataSource
final class TodayViewModel: NSObject {
var syncedPhoneContacts = MutableProperty<Set<PhoneContact>>([])
var dataSource = MutableProperty<DataSource>(EmptyDataSource())
func updateDataSource() {
let existingContacts = self.syncedPhoneContacts.value.filter { !$0.hasBeenSeen }
var sections: [DataSourceSection<ContactTableViewCellModel>] = existingContacts
.splitBetween {
return floor($0.0.dateAdded.timeIntervalSince1970 / (60 * 60 * 24)) != floor($0.1.dateAdded.timeIntervalSince1970 / (60 * 60 * 24))
}.map { contacts in
return DataSourceSection(items: contacts.map { ContactTableViewCellModel(contact: $0) })
}
let newContacts = self.syncedPhoneContacts.value.filter { $0.hasBeenSeen }
if !newContacts.isEmpty {
sections.append(DataSourceSection(items: newContacts.map { ContactTableViewCellModel(contact: $0) }))
}
self.dataSource.value = StaticDataSource(sections: sections)
}
}
| 60d7bddf42e3ca93ab7ee67dd18a0e4b | 34.40625 | 135 | 0.750221 | false | false | false | false |
RemyDCF/tpg-offline | refs/heads/master | tpg offline/Departures/Cells/AddToSiriTableViewCell.swift | mit | 1 | //
// AddToSiriTableViewCell.swift
// tpg offline
//
// Created by Rémy on 30/08/2018.
// Copyright © 2018 Remy. All rights reserved.
//
import UIKit
import IntentsUI
@available(iOS 12.0, *)
class AddToSiriTableViewCell: UITableViewCell,
INUIAddVoiceShortcutViewControllerDelegate {
// swiftlint:disable:next line_length
func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController,
didFinishWith voiceShortcut: INVoiceShortcut?,
error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) {
// swiftlint:disable:previous line_length
controller.dismiss(animated: true, completion: nil)
}
@IBOutlet weak var stackView: UIStackView!
override func awakeFromNib() {
super.awakeFromNib()
}
var shortcut: INShortcut?
var parent: UIViewController? = nil {
didSet {
for x in stackView.subviews {
x.removeFromSuperview()
}
let textLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
textLabel.textColor = App.textColor
textLabel.text =
"Do you want to see the departures of this stop at a glance?".localized
textLabel.numberOfLines = 0
textLabel.textAlignment = .center
self.stackView.addArrangedSubview(textLabel)
self.backgroundColor = App.cellBackgroundColor
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = App.cellBackgroundColor
self.selectedBackgroundView = selectedBackgroundView
if INPreferences.siriAuthorizationStatus() != .authorized {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
button.setTitle("Enable Siri in the settings".localized, for: .normal)
self.stackView.addArrangedSubview(button)
} else {
let button = INUIAddVoiceShortcutButton(style:
App.darkMode ? .blackOutline : .whiteOutline)
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 150).isActive = true
button.heightAnchor.constraint(equalToConstant: 50).isActive = true
button.addTarget(self, action: #selector(addToSiri), for: .touchUpInside)
stackView.addArrangedSubview(button)
}
}
}
@objc func addToSiri() {
if let shortcut = self.shortcut, let parent = self.parent {
let viewController = INUIAddVoiceShortcutViewController(shortcut: shortcut)
viewController.modalPresentationStyle = .formSheet
viewController.delegate = self
parent.present(viewController, animated: true, completion: nil)
}
}
}
| 82219f3a92fccfbdd59f5efffd31c93e | 36.972973 | 98 | 0.693238 | false | false | false | false |
wenghengcong/Coderpursue | refs/heads/master | BeeFun/BeeFun/View/Event/EventCell/BFEventBaseCell.swift | mit | 1 | //
// BFEventBaseCell.swift
// BeeFun
//
// Created by WengHengcong on 23/09/2017.
// Copyright © 2017 JungleSong. All rights reserved.
//
import UIKit
class BFEventBaseCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// for view in self.subviews where view.isKind(of: UIScrollView.self) {
// let scroll = view as? UIScrollView
// scroll?.canCancelContentTouches = true
// scroll?.delaysContentTouches = false
// break
// }
selectionStyle = .none
backgroundView?.backgroundColor = .clear
contentView.backgroundColor = .clear
backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 2204840fb31965bd817d3c87965d0acd | 27.709677 | 78 | 0.646067 | false | false | false | false |
mlilback/rc2SwiftClient | refs/heads/master | Networking/Rc2FileManager.swift | isc | 1 | //
// Rc2FileManager.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Rc2Common
import Foundation
import MJLLogger
import ReactiveSwift
let FileAttrVersion = "io.rc2.FileAttr.Version"
let FileAttrChecksum = "io.rc2.FileAttr.SHA256"
public enum FileError: Error, Rc2DomainError {
case failedToSave
case failedToDownload
}
///Protocol for functions of NSFileManager that we use so we can inject a mock version in unit tests
public protocol Rc2FileManager {
func Url(for directory: Foundation.FileManager.SearchPathDirectory, domain: Foundation.FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool) throws -> URL
func moveItem(at: URL, to: URL) throws
func copyItem(at: URL, to: URL) throws
func removeItem(at: URL) throws
// func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [String : Any]?) throws
func createDirectoryHierarchy(at url: URL) throws
/// synchronously move the file setting xattrs
func move(tempFile: URL, to toUrl: URL, file: AppFile?) throws
}
open class Rc2DefaultFileManager: Rc2FileManager {
let fm: FileManager
public init(fileManager: FileManager = FileManager.default) {
fm = fileManager
}
public func moveItem(at: URL, to: URL) throws {
do {
try fm.moveItem(at: at, to: to)
} catch {
throw Rc2Error(type: .file, nested: error)
}
}
public func copyItem(at: URL, to: URL) throws {
do {
try fm.copyItem(at: at, to: to)
} catch {
throw Rc2Error(type: .file, nested: error, severity: .error, explanation: "failed to copy \(to.lastPathComponent)")
}
}
public func removeItem(at: URL) throws {
do {
try fm.removeItem(at: at)
} catch {
throw Rc2Error(type: .file, nested: error)
}
}
public func createDirectoryHierarchy(at url: URL) throws {
do {
try fm.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch {
throw Rc2Error(type: .file, nested: error)
}
}
public func Url(for directory: FileManager.SearchPathDirectory, domain: FileManager.SearchPathDomainMask, appropriateFor url: URL? = nil, create shouldCreate: Bool = false) throws -> URL
{
do {
return try fm.url(for: directory, in: domain, appropriateFor: url, create: shouldCreate)
} catch {
throw Rc2Error(type: .file, nested: error)
}
}
///copies url to a new location in a temporary directory that can be passed to the user or another application
/// (i.e. it is not in our sandbox/app support/cache directories)
public func copyURLToTemporaryLocation(_ url: URL) throws -> URL {
//all errors are already wrapped since we only call internal methods
let tmpDir = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("Rc2", isDirectory: true)
_ = try createDirectoryHierarchy(at: tmpDir)
let destUrl = URL(fileURLWithPath: url.lastPathComponent, relativeTo: tmpDir)
_ = try? removeItem(at: destUrl)
try copyItem(at: url, to: destUrl)
return destUrl
}
///Synchronously moves the tmpFile downloaded via NSURLSession (or elsewhere) to toUrl, setting the appropriate
/// metadata including xattributes for validating cached File objects
public func move(tempFile: URL, to toUrl: URL, file: AppFile?) throws {
do {
if let _ = try? toUrl.checkResourceIsReachable() {
try self.removeItem(at: toUrl)
}
try self.moveItem(at: tempFile, to: toUrl)
//if a File, set mod/creation date, ignoring any errors
if let fileRef = file {
var fileUrl = toUrl
var resourceValues = URLResourceValues()
resourceValues.creationDate = fileRef.dateCreated
resourceValues.contentModificationDate = fileRef.lastModified
try fileUrl.setResourceValues(resourceValues)
let attrs: [FileAttributeKey: Any] = [.posixPermissions: fileRef.fileType.isExecutable ? 0o775 : 0o664]
try fm.setAttributes(attrs, ofItemAtPath: fileUrl.path)
fileRef.writeXAttributes(fileUrl)
}
} catch {
Log.warn("got error downloading file \(tempFile.lastPathComponent): \(error.localizedDescription)", .network)
throw Rc2Error(type: .cocoa, nested: error, explanation: tempFile.lastPathComponent)
}
}
}
public extension AppFile {
/// checks to see if the file at url has the same version information as this file
func versionXAttributesMatch(url: URL) -> Bool {
if let versionData = dataForXAttributeNamed(FileAttrVersion, atURL: url).data,
let readString = String(data: versionData, encoding: .utf8),
let readVersion = Int(readString)
{
return readVersion == version
}
return false
}
/// checks to see if file at url is the file we represent
func urlXAttributesMatch(_ url: URL) -> Bool {
if let versionData = dataForXAttributeNamed(FileAttrVersion, atURL: url).data,
let readString = String(data: versionData, encoding: .utf8),
let readVersion = Int(readString),
let shaData = dataForXAttributeNamed(FileAttrChecksum, atURL: url).data,
let readShaData = dataForXAttributeNamed(FileAttrChecksum, atURL: url).data
{
return readVersion == version && shaData == readShaData
}
return false
}
/// writes data to xattributes to later validate if a url points to a file reprsented this object
func writeXAttributes(_ toUrl: URL) {
let versionData = String(version).data(using: String.Encoding.utf8)
setXAttributeWithName(FileAttrVersion, data: versionData!, atURL: toUrl)
if let fileData = try? Data(contentsOf: toUrl)
{
let shaData = fileData.sha256()
setXAttributeWithName(FileAttrChecksum, data: shaData, atURL: toUrl)
} else {
Log.error("failed to create sha256 checksum for \(toUrl.path)", .network)
}
}
}
| 02186eade4b5f909a79116ab5ff2a2e7 | 35.541935 | 188 | 0.735876 | false | false | false | false |
alex-d-fox/iDoubtIt | refs/heads/master | iDoubtIt/Code/PlayScene.swift | gpl-3.0 | 1 | //
// GameScene.swift
// iDoubtIt
//
// Created by Alexander Fox on 8/30/16.
// Copyright © 2016
//
import Foundation
import SpriteKit
enum CardLevel :CGFloat {
case board = 20
case moving = 40
case enlarged = 60
}
class PlayScene: SKScene {
override init() {
super.init(size: screenSize.size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
let deck = Deck(wacky: isWacky)
let bg = SKSpriteNode(imageNamed: background)
bg.anchorPoint = CGPoint.zero
bg.position = CGPoint.zero
bg.size = CGSize(width: screenWidth, height: screenHeight)
addChild(bg)
let infoButton = button(image: "outerCircle", name:"Info", color: .white, label: "i")
infoButton.colorBlendFactor = 0.75
infoButton.position = CGPoint(x: screenWidth - 50, y: screenHeight - 50)
addChild(infoButton)
let human = Player(human: true, playerName: "Human", level: Difficulty.easy)
let ai1 = Player(human: false, playerName: "AI 1", level: Difficulty.easy)
let ai2 = Player(human: false, playerName: "AI 2", level: Difficulty.easy)
let ai3 = Player(human: false, playerName: "AI 3", level: Difficulty.easy)
let players = [human,ai1,ai2,ai3]
// let aiplayers = [ai1,ai2,ai3]
deck.naturalShuffle()
deck.randShuffle()
deck.naturalShuffle()
var p = 0
for card in deck.gameDeck {
players[p%4].addCard(card: card)
card.position = CGPoint(x: p * 10, y: 0)
p += 1
}
for player in players {
print(player.name!)
for c in 0...12 {
print(player.playerHand[c].getIcon())
}
player.color = .red
player.colorBlendFactor = 1
addChild(player)
}
let texture = SKTexture(imageNamed: "invisible")
let discardPile = SKSpriteNode(texture: texture, color: .yellow, size: CGSize.init(width: 140, height: 190))
discardPile.blendMode = .subtract
discardPile.colorBlendFactor = 1
discardPile.position = CGPoint(x: screenWidth/2, y: screenHeight/2)
addChild(discardPile)
players[0].position = CGPoint(x: screenWidth/4, y: screenHeight/2 - players[0].size.height)
players[1].position = CGPoint(x: screenWidth/4, y: screenHeight/2)
players[2].position = CGPoint(x: screenWidth/4, y: screenHeight/2)
players[3].position = CGPoint(x: screenWidth/4, y: screenHeight/2)
players[0].zRotation = CGFloat(0 * Double.pi/2 / 360)
players[1].zRotation = CGFloat(90 * Double.pi/2 / 360)
players[2].zRotation = CGFloat(180 * Double.pi/2 / 360)
players[3].zRotation = CGFloat(270 * Double.pi/2 / 360)
for p in 0..<players.count {
for card in players[p].playHand(currValue: .Ace) {
let moveCard = SKAction.move(to: discardPile.position, duration: 1)
card.run(moveCard)
card.move(toParent: discardPile)
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if let card = atPoint(location) as? Card {
card.zPosition = CardLevel.moving.rawValue
if touch.tapCount == 2 {
card.flipOver()
return
}
let rotR = SKAction.rotate(byAngle: 0.15, duration: 0.2)
let rotL = SKAction.rotate(byAngle: -0.15, duration: 0.2)
let cycle = SKAction.sequence([rotR, rotL, rotL, rotR])
let wiggle = SKAction.repeatForever(cycle)
card.run(wiggle, withKey: "wiggle")
card.removeAction(forKey: "drop")
card.run(SKAction.scale(to: 1.3, duration: 0.25), withKey: "pickup")
print(card.getIcon())
print(card.cardName)
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if let card = atPoint(location) as? Card {
card.position = location
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let node = atPoint(location)
if let card = node as? Card {
card.zPosition = CardLevel.board.rawValue
card.removeAction(forKey: "wiggle")
card.run(SKAction.rotate(toAngle: 0, duration: 0.2), withKey:"rotate")
card.removeAction(forKey: "pickup")
card.run(SKAction.scale(to: 1.0, duration: 0.25), withKey: "drop")
// let parent = card.parent
card.removeFromParent()
addChild(card)
}
if (node.name == "Infobtn" || node.name == "Infolabel") {
let scene = MainMenu()
view?.showsFPS = true
view?.showsNodeCount = true
view?.ignoresSiblingOrder = false
scene.scaleMode = .aspectFill
view?.presentScene(scene)
}
}
}
}
| 9e6142fc8ddb2d62141fca4c832d68c8 | 31.576923 | 112 | 0.612554 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.