repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ontouchstart/swift3-playground
|
Learn to Code 1.playgroundbook/Contents/Chapters/Document6.playgroundchapter/Pages/Exercise1.playgroundpage/Sources/Assessments.swift
|
1
|
2347
|
//
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let solution = "```swift\nfor i in 1 ... 4 {\n moveForward()\n if !isOnGem {\n turnLeft()\n moveForward()\n moveForward()\n collectGem()\n turnLeft()\n turnLeft()\n moveForward()\n moveForward()\n turnLeft()\n } else {\n collectGem()\n }\n}\n```"
import PlaygroundSupport
public func assessmentPoint() -> AssessmentResults {
let checker = ContentsChecker(contents: PlaygroundPage.current.text)
pageIdentifier = "Using_the_NOT_operator"
var success = "### You're amazing! \nUsing the [logical NOT operator](glossary://logical%20NOT%20operator), you reversed a [Boolean](glossary://Boolean) value, allowing you to check the opposite of a condition like `isOnGem` or `isOnClosedSwitch`. What you're saying is that \"if NOT on a gem, do this.\" \n\n[**Next Page**](@next)"
var hints = [
"When there is **not** a gem on the top platform, a stairway extends from that tile. Use the condition \"if Byte is NOT on a gem\" to determine what to do in that situation.",
"Use a condition that looks like this: `!isOnGem`",
]
let runCount = currentPageRunCount
if checker.didUseConditionalStatement && runCount > 3 {
hints[0] = "Add an `if` statement that looks like this:\n\n```swift\n if !isOnGem {\n CODE\n } else {\n collectGem()\n }```"
} else if !checker.didUseConditionalStatement {
hints[0] = "First, add an `if` statement inside your `for` loop that checks whether Byte is NOT on a gem."
success = "### Use conditional code. \nAlthough you solved the puzzle this time, if you rerun your code, it probably won't work again! /nTry using conditional code that will work in many different situations."
}
let contents = checker.conditionalNodes.map { $0.condition }
for element in contents {
if !element.contains("!") && checker.didUseConditionalStatement {
hints[0] = "Make sure your condition looks like this, with no spaces between the ! and `isOnGem`: \n\n`!isOnGem`."
}
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
|
mit
|
416c16995ae53b72967baf82140eb4a4
| 56.243902 | 336 | 0.634001 | 4.183601 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/Models/Base/ModelMappeable.swift
|
1
|
960
|
//
// ModelMappeable.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 13/01/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
import Realm
public typealias UpdateBlock<T> = (_ object: T?) -> Void
protocol ModelMappeable {
func map(_ values: JSON, realm: Realm?)
}
extension ModelMappeable where Self: BaseModel {
static func getOrCreate(realm: Realm, values: JSON?, updates: UpdateBlock<Self>?) -> Self {
var object: Self!
if let primaryKey = values?["_id"].string {
if let newObject = realm.object(ofType: Self.self, forPrimaryKey: primaryKey as AnyObject) {
object = newObject
}
}
if object == nil {
object = Self()
}
if let values = values {
object.map(values, realm: realm)
}
updates?(object)
return object
}
}
|
mit
|
c416cb59a783a3d6a95eec19446d7064
| 21.302326 | 104 | 0.604797 | 4.151515 | false | false | false | false |
rockbruno/swiftshield
|
Sources/SwiftShieldCore/SourceKit/SourceKit.swift
|
1
|
38879
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import sourcekitd
// Adapted from SourceKit-LSP.
/// A wrapper for accessing the API of a sourcekitd library loaded via `dlopen`.
class SourceKit {
/// The path to the sourcekitd dylib.
public let path: String
/// The handle to the dylib.
let dylib: DLHandle!
/// The sourcekitd API functions.
public let api: sourcekitd_functions_t!
/// Convenience for accessing known keys.
public let keys: sourcekitd_keys!
/// Convenience for accessing known keys.
public let requests: sourcekitd_requests!
/// Convenience for accessing known keys.
public let values: sourcekitd_values!
let logger: LoggerProtocol?
enum Error: Swift.Error {
case missingRequiredSymbol(String)
}
static func getToolchainPath() -> String {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", "xcode-select -p"]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard let developer = String(data: data, encoding: .utf8), developer.isEmpty == false else {
preconditionFailure("Xcode toolchain path not found. (xcode-select -p)")
}
let oneLined = developer.replacingOccurrences(of: "\n", with: "")
return oneLined + "/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/sourcekitd"
}
public init(logger: LoggerProtocol?) {
self.logger = logger
path = Self.getToolchainPath()
dylib = try! dlopen(path, mode: [.lazy, .local, .first, .deepBind])
func dlsym_required<T>(_ handle: DLHandle, symbol: String) throws -> T {
guard let sym: T = dlsym(handle, symbol: symbol) else {
throw Error.missingRequiredSymbol(symbol)
}
return sym
}
// Workaround rdar://problem/43656704 by not constructing the value directly.
// self.api = sourcekitd_functions_t(
let ptr = UnsafeMutablePointer<sourcekitd_functions_t>.allocate(capacity: 1)
bzero(UnsafeMutableRawPointer(ptr), MemoryLayout<sourcekitd_functions_t>.stride)
var api = ptr.pointee
ptr.deallocate()
// The following crashes the compiler rdar://43658464
// api.variant_dictionary_apply = try dlsym_required(dylib, symbol: "sourcekitd_variant_dictionary_apply")
// api.variant_array_apply = try dlsym_required(dylib, symbol: "sourcekitd_variant_array_apply")
api.initialize = try! dlsym_required(dylib, symbol: "sourcekitd_initialize")
api.shutdown = try! dlsym_required(dylib, symbol: "sourcekitd_shutdown")
api.uid_get_from_cstr = try! dlsym_required(dylib, symbol: "sourcekitd_uid_get_from_cstr")
api.uid_get_from_buf = try! dlsym_required(dylib, symbol: "sourcekitd_uid_get_from_buf")
api.uid_get_length = try! dlsym_required(dylib, symbol: "sourcekitd_uid_get_length")
api.uid_get_string_ptr = try! dlsym_required(dylib, symbol: "sourcekitd_uid_get_string_ptr")
api.request_retain = try! dlsym_required(dylib, symbol: "sourcekitd_request_retain")
api.request_release = try! dlsym_required(dylib, symbol: "sourcekitd_request_release")
api.request_dictionary_create = try! dlsym_required(dylib, symbol: "sourcekitd_request_dictionary_create")
api.request_dictionary_set_value = try! dlsym_required(dylib, symbol: "sourcekitd_request_dictionary_set_value")
api.request_dictionary_set_string = try! dlsym_required(dylib, symbol: "sourcekitd_request_dictionary_set_string")
api.request_dictionary_set_stringbuf = try! dlsym_required(dylib, symbol: "sourcekitd_request_dictionary_set_stringbuf")
api.request_dictionary_set_int64 = try! dlsym_required(dylib, symbol: "sourcekitd_request_dictionary_set_int64")
api.request_dictionary_set_uid = try! dlsym_required(dylib, symbol: "sourcekitd_request_dictionary_set_uid")
api.request_array_create = try! dlsym_required(dylib, symbol: "sourcekitd_request_array_create")
api.request_array_set_value = try! dlsym_required(dylib, symbol: "sourcekitd_request_array_set_value")
api.request_array_set_string = try! dlsym_required(dylib, symbol: "sourcekitd_request_array_set_string")
api.request_array_set_stringbuf = try! dlsym_required(dylib, symbol: "sourcekitd_request_array_set_stringbuf")
api.request_array_set_int64 = try! dlsym_required(dylib, symbol: "sourcekitd_request_array_set_int64")
api.request_array_set_uid = try! dlsym_required(dylib, symbol: "sourcekitd_request_array_set_uid")
api.request_int64_create = try! dlsym_required(dylib, symbol: "sourcekitd_request_int64_create")
api.request_string_create = try! dlsym_required(dylib, symbol: "sourcekitd_request_string_create")
api.request_uid_create = try! dlsym_required(dylib, symbol: "sourcekitd_request_uid_create")
api.request_create_from_yaml = try! dlsym_required(dylib, symbol: "sourcekitd_request_create_from_yaml")
api.request_description_dump = try! dlsym_required(dylib, symbol: "sourcekitd_request_description_dump")
api.request_description_copy = try! dlsym_required(dylib, symbol: "sourcekitd_request_description_copy")
api.response_dispose = try! dlsym_required(dylib, symbol: "sourcekitd_response_dispose")
api.response_is_error = try! dlsym_required(dylib, symbol: "sourcekitd_response_is_error")
api.response_error_get_kind = try! dlsym_required(dylib, symbol: "sourcekitd_response_error_get_kind")
api.response_error_get_description = try! dlsym_required(dylib, symbol: "sourcekitd_response_error_get_description")
api.response_get_value = try! dlsym_required(dylib, symbol: "sourcekitd_response_get_value")
api.variant_get_type = try! dlsym_required(dylib, symbol: "sourcekitd_variant_get_type")
api.variant_dictionary_get_value = try! dlsym_required(dylib, symbol: "sourcekitd_variant_dictionary_get_value")
api.variant_dictionary_get_string = try! dlsym_required(dylib, symbol: "sourcekitd_variant_dictionary_get_string")
api.variant_dictionary_get_int64 = try! dlsym_required(dylib, symbol: "sourcekitd_variant_dictionary_get_int64")
api.variant_dictionary_get_bool = try! dlsym_required(dylib, symbol: "sourcekitd_variant_dictionary_get_bool")
api.variant_dictionary_get_uid = try! dlsym_required(dylib, symbol: "sourcekitd_variant_dictionary_get_uid")
api.variant_array_get_count = try! dlsym_required(dylib, symbol: "sourcekitd_variant_array_get_count")
api.variant_array_get_value = try! dlsym_required(dylib, symbol: "sourcekitd_variant_array_get_value")
api.variant_array_get_string = try! dlsym_required(dylib, symbol: "sourcekitd_variant_array_get_string")
api.variant_array_get_int64 = try! dlsym_required(dylib, symbol: "sourcekitd_variant_array_get_int64")
api.variant_array_get_bool = try! dlsym_required(dylib, symbol: "sourcekitd_variant_array_get_bool")
api.variant_array_get_uid = try! dlsym_required(dylib, symbol: "sourcekitd_variant_array_get_uid")
api.variant_int64_get_value = try! dlsym_required(dylib, symbol: "sourcekitd_variant_int64_get_value")
api.variant_bool_get_value = try! dlsym_required(dylib, symbol: "sourcekitd_variant_bool_get_value")
api.variant_string_get_length = try! dlsym_required(dylib, symbol: "sourcekitd_variant_string_get_length")
api.variant_string_get_ptr = try! dlsym_required(dylib, symbol: "sourcekitd_variant_string_get_ptr")
api.variant_data_get_size = dlsym(dylib, symbol: "sourcekitd_variant_data_get_size") // Optional
api.variant_data_get_ptr = dlsym(dylib, symbol: "sourcekitd_variant_data_get_ptr") // Optional
api.variant_uid_get_value = try! dlsym_required(dylib, symbol: "sourcekitd_variant_uid_get_value")
api.response_description_dump = try! dlsym_required(dylib, symbol: "sourcekitd_response_description_dump")
api.response_description_dump_filedesc = try! dlsym_required(dylib, symbol: "sourcekitd_response_description_dump_filedesc")
api.response_description_copy = try! dlsym_required(dylib, symbol: "sourcekitd_response_description_copy")
api.variant_description_dump = try! dlsym_required(dylib, symbol: "sourcekitd_variant_description_dump")
api.variant_description_dump_filedesc = try! dlsym_required(dylib, symbol: "sourcekitd_variant_description_dump_filedesc")
api.variant_description_copy = try! dlsym_required(dylib, symbol: "sourcekitd_variant_description_copy")
api.send_request_sync = try! dlsym_required(dylib, symbol: "sourcekitd_send_request_sync")
api.send_request = try! dlsym_required(dylib, symbol: "sourcekitd_send_request")
api.cancel_request = try! dlsym_required(dylib, symbol: "sourcekitd_cancel_request")
api.set_notification_handler = try! dlsym_required(dylib, symbol: "sourcekitd_set_notification_handler")
api.set_uid_handlers = try! dlsym_required(dylib, symbol: "sourcekitd_set_uid_handlers")
self.api = api
keys = sourcekitd_keys(api: self.api)
requests = sourcekitd_requests(api: self.api)
values = sourcekitd_values(api: self.api)
api.initialize()
}
deinit {
// FIXME: is it safe to dlclose() sourcekitd? If so, do that here. For now, let the handle leak.
guard dylib != nil else {
return
}
dylib.leak()
}
}
public enum SKResult<T> {
case success(T)
case failure(String)
}
extension SourceKit {
// MARK: - Convenience API for requests.
/// Send the given request and synchronously receive a reply dictionary (or error).
public func sendSync(_ req: SKRequestDictionary) throws -> SKResponseDictionary {
logger?.log(req.description, sourceKit: true)
let resp = SKResponse(api.send_request_sync(req.dict), sourcekitd: self)
logger?.log(resp.description, sourceKit: true)
guard let dict = resp.value else {
throw (logger ?? Logger()).fatalError(forMessage: resp.error!)
}
return dict
}
}
public struct sourcekitd_keys {
let request: sourcekitd_uid_t
let compilerargs: sourcekitd_uid_t
let offset: sourcekitd_uid_t
let length: sourcekitd_uid_t
let sourcefile: sourcekitd_uid_t
let sourcetext: sourcekitd_uid_t
let results: sourcekitd_uid_t
let description: sourcekitd_uid_t
let name: sourcekitd_uid_t
let kind: sourcekitd_uid_t
let notification: sourcekitd_uid_t
let diagnostics: sourcekitd_uid_t
let severity: sourcekitd_uid_t
let line: sourcekitd_uid_t
let column: sourcekitd_uid_t
let endline: sourcekitd_uid_t
let endcolumn: sourcekitd_uid_t
let filepath: sourcekitd_uid_t
let ranges: sourcekitd_uid_t
let usr: sourcekitd_uid_t
let typename: sourcekitd_uid_t
let annotated_decl: sourcekitd_uid_t
let doc_full_as_xml: sourcekitd_uid_t
let syntactic_only: sourcekitd_uid_t
let substructure: sourcekitd_uid_t
let bodyoffset: sourcekitd_uid_t
let bodylength: sourcekitd_uid_t
let syntaxmap: sourcekitd_uid_t
let retrieve_refactor_actions: sourcekitd_uid_t
let refactor_actions: sourcekitd_uid_t
let actionname: sourcekitd_uid_t
let actionuid: sourcekitd_uid_t
let categorizededits: sourcekitd_uid_t
let edits: sourcekitd_uid_t
let text: sourcekitd_uid_t
let entities: sourcekitd_uid_t
let receiver: sourcekitd_uid_t
let attributes: sourcekitd_uid_t
let attribute: sourcekitd_uid_t
let related: sourcekitd_uid_t
init(api: sourcekitd_functions_t) {
request = api.uid_get_from_cstr("key.request")!
compilerargs = api.uid_get_from_cstr("key.compilerargs")!
offset = api.uid_get_from_cstr("key.offset")!
length = api.uid_get_from_cstr("key.length")!
sourcefile = api.uid_get_from_cstr("key.sourcefile")!
sourcetext = api.uid_get_from_cstr("key.sourcetext")!
results = api.uid_get_from_cstr("key.results")!
description = api.uid_get_from_cstr("key.description")!
name = api.uid_get_from_cstr("key.name")!
kind = api.uid_get_from_cstr("key.kind")!
notification = api.uid_get_from_cstr("key.notification")!
diagnostics = api.uid_get_from_cstr("key.diagnostics")!
severity = api.uid_get_from_cstr("key.severity")!
line = api.uid_get_from_cstr("key.line")!
column = api.uid_get_from_cstr("key.column")!
endline = api.uid_get_from_cstr("key.endline")!
endcolumn = api.uid_get_from_cstr("key.endcolumn")!
filepath = api.uid_get_from_cstr("key.filepath")!
ranges = api.uid_get_from_cstr("key.ranges")!
usr = api.uid_get_from_cstr("key.usr")!
typename = api.uid_get_from_cstr("key.typename")!
annotated_decl = api.uid_get_from_cstr("key.annotated_decl")!
doc_full_as_xml = api.uid_get_from_cstr("key.doc.full_as_xml")!
syntactic_only = api.uid_get_from_cstr("key.syntactic_only")!
substructure = api.uid_get_from_cstr("key.substructure")!
bodyoffset = api.uid_get_from_cstr("key.bodyoffset")!
bodylength = api.uid_get_from_cstr("key.bodylength")!
syntaxmap = api.uid_get_from_cstr("key.syntaxmap")!
retrieve_refactor_actions = api.uid_get_from_cstr("key.retrieve_refactor_actions")!
refactor_actions = api.uid_get_from_cstr("key.refactor_actions")!
actionname = api.uid_get_from_cstr("key.actionname")!
actionuid = api.uid_get_from_cstr("key.actionuid")!
categorizededits = api.uid_get_from_cstr("key.categorizededits")!
edits = api.uid_get_from_cstr("key.edits")!
text = api.uid_get_from_cstr("key.text")!
entities = api.uid_get_from_cstr("key.entities")!
receiver = api.uid_get_from_cstr("key.receiver_usr")!
attributes = api.uid_get_from_cstr("key.attributes")!
attribute = api.uid_get_from_cstr("key.attribute")!
related = api.uid_get_from_cstr("key.related")!
}
}
public struct sourcekitd_requests {
let editor_open: sourcekitd_uid_t
let editor_close: sourcekitd_uid_t
let editor_replacetext: sourcekitd_uid_t
let codecomplete: sourcekitd_uid_t
let cursorinfo: sourcekitd_uid_t
let relatedidents: sourcekitd_uid_t
let semantic_refactoring: sourcekitd_uid_t
let indexsource: sourcekitd_uid_t
let typecontextinfo: sourcekitd_uid_t
let conformingmethods: sourcekitd_uid_t
init(api: sourcekitd_functions_t) {
editor_open = api.uid_get_from_cstr("source.request.editor.open")!
editor_close = api.uid_get_from_cstr("source.request.editor.close")!
editor_replacetext = api.uid_get_from_cstr("source.request.editor.replacetext")!
codecomplete = api.uid_get_from_cstr("source.request.codecomplete")!
cursorinfo = api.uid_get_from_cstr("source.request.cursorinfo")!
relatedidents = api.uid_get_from_cstr("source.request.relatedidents")!
semantic_refactoring = api.uid_get_from_cstr("source.request.semantic.refactoring")!
indexsource = api.uid_get_from_cstr("source.request.indexsource")!
typecontextinfo = api.uid_get_from_cstr("source.request.typecontextinfo")!
conformingmethods = api.uid_get_from_cstr("source.request.conformingmethods")!
}
}
public struct sourcekitd_values {
let notification_documentupdate: sourcekitd_uid_t
let diag_error: sourcekitd_uid_t
let diag_warning: sourcekitd_uid_t
let diag_note: sourcekitd_uid_t
// MARK: Symbol Kinds
let decl_function_free: sourcekitd_uid_t
let ref_function_free: sourcekitd_uid_t
let decl_function_method_instance: sourcekitd_uid_t
let ref_function_method_instance: sourcekitd_uid_t
let decl_function_method_static: sourcekitd_uid_t
let ref_function_method_static: sourcekitd_uid_t
let decl_function_method_class: sourcekitd_uid_t
let ref_function_method_class: sourcekitd_uid_t
let decl_function_accessor_getter: sourcekitd_uid_t
let ref_function_accessor_getter: sourcekitd_uid_t
let decl_function_accessor_setter: sourcekitd_uid_t
let ref_function_accessor_setter: sourcekitd_uid_t
let decl_function_accessor_willset: sourcekitd_uid_t
let ref_function_accessor_willset: sourcekitd_uid_t
let decl_function_accessor_didset: sourcekitd_uid_t
let ref_function_accessor_didset: sourcekitd_uid_t
let decl_function_accessor_address: sourcekitd_uid_t
let ref_function_accessor_address: sourcekitd_uid_t
let decl_function_accessor_mutableaddress: sourcekitd_uid_t
let ref_function_accessor_mutableaddress: sourcekitd_uid_t
let decl_function_accessor_read: sourcekitd_uid_t
let ref_function_accessor_read: sourcekitd_uid_t
let decl_function_accessor_modify: sourcekitd_uid_t
let ref_function_accessor_modify: sourcekitd_uid_t
let decl_function_constructor: sourcekitd_uid_t
let ref_function_constructor: sourcekitd_uid_t
let decl_function_destructor: sourcekitd_uid_t
let ref_function_destructor: sourcekitd_uid_t
let decl_function_operator_prefix: sourcekitd_uid_t
let decl_function_operator_postfix: sourcekitd_uid_t
let decl_function_operator_infix: sourcekitd_uid_t
let ref_function_operator_prefix: sourcekitd_uid_t
let ref_function_operator_postfix: sourcekitd_uid_t
let ref_function_operator_infix: sourcekitd_uid_t
let decl_precedencegroup: sourcekitd_uid_t
let ref_precedencegroup: sourcekitd_uid_t
let decl_function_subscript: sourcekitd_uid_t
let ref_function_subscript: sourcekitd_uid_t
let decl_var_global: sourcekitd_uid_t
let ref_var_global: sourcekitd_uid_t
let decl_var_instance: sourcekitd_uid_t
let ref_var_instance: sourcekitd_uid_t
let decl_var_static: sourcekitd_uid_t
let ref_var_static: sourcekitd_uid_t
let decl_var_class: sourcekitd_uid_t
let ref_var_class: sourcekitd_uid_t
let decl_var_local: sourcekitd_uid_t
let ref_var_local: sourcekitd_uid_t
let decl_var_parameter: sourcekitd_uid_t
let decl_module: sourcekitd_uid_t
let decl_class: sourcekitd_uid_t
let ref_class: sourcekitd_uid_t
let decl_struct: sourcekitd_uid_t
let ref_struct: sourcekitd_uid_t
let decl_enum: sourcekitd_uid_t
let ref_enum: sourcekitd_uid_t
let decl_enumcase: sourcekitd_uid_t
let decl_enumelement: sourcekitd_uid_t
let ref_enumelement: sourcekitd_uid_t
let decl_protocol: sourcekitd_uid_t
let ref_protocol: sourcekitd_uid_t
let decl_extension: sourcekitd_uid_t
let decl_extension_struct: sourcekitd_uid_t
let decl_extension_class: sourcekitd_uid_t
let decl_extension_enum: sourcekitd_uid_t
let decl_extension_protocol: sourcekitd_uid_t
let decl_associatedtype: sourcekitd_uid_t
let ref_associatedtype: sourcekitd_uid_t
let decl_typealias: sourcekitd_uid_t
let ref_typealias: sourcekitd_uid_t
let decl_generic_type_param: sourcekitd_uid_t
let ref_generic_type_param: sourcekitd_uid_t
let ref_module: sourcekitd_uid_t
let syntaxtype_comment: sourcekitd_uid_t
let syntaxtype_comment_marker: sourcekitd_uid_t
let syntaxtype_comment_url: sourcekitd_uid_t
let syntaxtype_doccomment: sourcekitd_uid_t
let syntaxtype_doccomment_field: sourcekitd_uid_t
let kind_keyword: sourcekitd_uid_t
init(api: sourcekitd_functions_t) {
notification_documentupdate = api.uid_get_from_cstr("source.notification.editor.documentupdate")!
diag_error = api.uid_get_from_cstr("source.diagnostic.severity.error")!
diag_warning = api.uid_get_from_cstr("source.diagnostic.severity.warning")!
diag_note = api.uid_get_from_cstr("source.diagnostic.severity.note")!
// MARK: Symbol Kinds
decl_function_free = api.uid_get_from_cstr("source.lang.swift.decl.function.free")!
ref_function_free = api.uid_get_from_cstr("source.lang.swift.ref.function.free")!
decl_function_method_instance = api.uid_get_from_cstr("source.lang.swift.decl.function.method.instance")!
ref_function_method_instance = api.uid_get_from_cstr("source.lang.swift.ref.function.method.instance")!
decl_function_method_static = api.uid_get_from_cstr("source.lang.swift.decl.function.method.static")!
ref_function_method_static = api.uid_get_from_cstr("source.lang.swift.ref.function.method.static")!
decl_function_method_class = api.uid_get_from_cstr("source.lang.swift.decl.function.method.class")!
ref_function_method_class = api.uid_get_from_cstr("source.lang.swift.ref.function.method.class")!
decl_function_accessor_getter = api.uid_get_from_cstr("source.lang.swift.decl.function.accessor.getter")!
ref_function_accessor_getter = api.uid_get_from_cstr("source.lang.swift.ref.function.accessor.getter")!
decl_function_accessor_setter = api.uid_get_from_cstr("source.lang.swift.decl.function.accessor.setter")!
ref_function_accessor_setter = api.uid_get_from_cstr("source.lang.swift.ref.function.accessor.setter")!
decl_function_accessor_willset = api.uid_get_from_cstr("source.lang.swift.decl.function.accessor.willset")!
ref_function_accessor_willset = api.uid_get_from_cstr("source.lang.swift.ref.function.accessor.willset")!
decl_function_accessor_didset = api.uid_get_from_cstr("source.lang.swift.decl.function.accessor.didset")!
ref_function_accessor_didset = api.uid_get_from_cstr("source.lang.swift.ref.function.accessor.didset")!
decl_function_accessor_address = api.uid_get_from_cstr("source.lang.swift.decl.function.accessor.address")!
ref_function_accessor_address = api.uid_get_from_cstr("source.lang.swift.ref.function.accessor.address")!
decl_function_accessor_mutableaddress = api.uid_get_from_cstr("source.lang.swift.decl.function.accessor.mutableaddress")!
ref_function_accessor_mutableaddress = api.uid_get_from_cstr("source.lang.swift.ref.function.accessor.mutableaddress")!
decl_function_accessor_read = api.uid_get_from_cstr("source.lang.swift.decl.function.accessor.read")!
ref_function_accessor_read = api.uid_get_from_cstr("source.lang.swift.ref.function.accessor.read")!
decl_function_accessor_modify = api.uid_get_from_cstr("source.lang.swift.decl.function.accessor.modify")!
ref_function_accessor_modify = api.uid_get_from_cstr("source.lang.swift.ref.function.accessor.modify")!
decl_function_constructor = api.uid_get_from_cstr("source.lang.swift.decl.function.constructor")!
ref_function_constructor = api.uid_get_from_cstr("source.lang.swift.ref.function.constructor")!
decl_function_destructor = api.uid_get_from_cstr("source.lang.swift.decl.function.destructor")!
ref_function_destructor = api.uid_get_from_cstr("source.lang.swift.ref.function.destructor")!
decl_function_operator_prefix = api.uid_get_from_cstr("source.lang.swift.decl.function.operator.prefix")!
decl_function_operator_postfix = api.uid_get_from_cstr("source.lang.swift.decl.function.operator.postfix")!
decl_function_operator_infix = api.uid_get_from_cstr("source.lang.swift.decl.function.operator.infix")!
ref_function_operator_prefix = api.uid_get_from_cstr("source.lang.swift.ref.function.operator.prefix")!
ref_function_operator_postfix = api.uid_get_from_cstr("source.lang.swift.ref.function.operator.postfix")!
ref_function_operator_infix = api.uid_get_from_cstr("source.lang.swift.ref.function.operator.infix")!
decl_precedencegroup = api.uid_get_from_cstr("source.lang.swift.decl.precedencegroup")!
ref_precedencegroup = api.uid_get_from_cstr("source.lang.swift.ref.precedencegroup")!
decl_function_subscript = api.uid_get_from_cstr("source.lang.swift.decl.function.subscript")!
ref_function_subscript = api.uid_get_from_cstr("source.lang.swift.ref.function.subscript")!
decl_var_global = api.uid_get_from_cstr("source.lang.swift.decl.var.global")!
ref_var_global = api.uid_get_from_cstr("source.lang.swift.ref.var.global")!
decl_var_instance = api.uid_get_from_cstr("source.lang.swift.decl.var.instance")!
ref_var_instance = api.uid_get_from_cstr("source.lang.swift.ref.var.instance")!
decl_var_static = api.uid_get_from_cstr("source.lang.swift.decl.var.static")!
ref_var_static = api.uid_get_from_cstr("source.lang.swift.ref.var.static")!
decl_var_class = api.uid_get_from_cstr("source.lang.swift.decl.var.class")!
ref_var_class = api.uid_get_from_cstr("source.lang.swift.ref.var.class")!
decl_var_local = api.uid_get_from_cstr("source.lang.swift.decl.var.local")!
ref_var_local = api.uid_get_from_cstr("source.lang.swift.ref.var.local")!
decl_var_parameter = api.uid_get_from_cstr("source.lang.swift.decl.var.parameter")!
decl_module = api.uid_get_from_cstr("source.lang.swift.decl.module")!
decl_class = api.uid_get_from_cstr("source.lang.swift.decl.class")!
ref_class = api.uid_get_from_cstr("source.lang.swift.ref.class")!
decl_struct = api.uid_get_from_cstr("source.lang.swift.decl.struct")!
ref_struct = api.uid_get_from_cstr("source.lang.swift.ref.struct")!
decl_enum = api.uid_get_from_cstr("source.lang.swift.decl.enum")!
ref_enum = api.uid_get_from_cstr("source.lang.swift.ref.enum")!
decl_enumcase = api.uid_get_from_cstr("source.lang.swift.decl.enumcase")!
decl_enumelement = api.uid_get_from_cstr("source.lang.swift.decl.enumelement")!
ref_enumelement = api.uid_get_from_cstr("source.lang.swift.ref.enumelement")!
decl_protocol = api.uid_get_from_cstr("source.lang.swift.decl.protocol")!
ref_protocol = api.uid_get_from_cstr("source.lang.swift.ref.protocol")!
decl_extension = api.uid_get_from_cstr("source.lang.swift.decl.extension")!
decl_extension_struct = api.uid_get_from_cstr("source.lang.swift.decl.extension.struct")!
decl_extension_class = api.uid_get_from_cstr("source.lang.swift.decl.extension.class")!
decl_extension_enum = api.uid_get_from_cstr("source.lang.swift.decl.extension.enum")!
decl_extension_protocol = api.uid_get_from_cstr("source.lang.swift.decl.extension.protocol")!
decl_associatedtype = api.uid_get_from_cstr("source.lang.swift.decl.associatedtype")!
ref_associatedtype = api.uid_get_from_cstr("source.lang.swift.ref.associatedtype")!
decl_typealias = api.uid_get_from_cstr("source.lang.swift.decl.typealias")!
ref_typealias = api.uid_get_from_cstr("source.lang.swift.ref.typealias")!
decl_generic_type_param = api.uid_get_from_cstr("source.lang.swift.decl.generic_type_param")!
ref_generic_type_param = api.uid_get_from_cstr("source.lang.swift.ref.generic_type_param")!
ref_module = api.uid_get_from_cstr("source.lang.swift.ref.module")!
syntaxtype_comment = api.uid_get_from_cstr("source.lang.swift.syntaxtype.comment")!
syntaxtype_comment_marker = api.uid_get_from_cstr("source.lang.swift.syntaxtype.comment.mark")!
syntaxtype_comment_url = api.uid_get_from_cstr("source.lang.swift.syntaxtype.comment.url")!
syntaxtype_doccomment = api.uid_get_from_cstr("source.lang.swift.syntaxtype.doccomment")!
syntaxtype_doccomment_field = api.uid_get_from_cstr("source.lang.swift.syntaxtype.doccomment.field")!
kind_keyword = api.uid_get_from_cstr("source.lang.swift.keyword")!
}
}
final class SKRequestDictionary {
let dict: sourcekitd_object_t?
let sourcekitd: SourceKit
init(_ dict: sourcekitd_object_t? = nil, sourcekitd: SourceKit) {
self.dict = dict ?? sourcekitd.api.request_dictionary_create(nil, nil, 0)
self.sourcekitd = sourcekitd
}
deinit {
sourcekitd.api.request_release(dict)
}
public subscript(key: sourcekitd_uid_t?) -> String {
get { fatalError("request is set-only") }
set { sourcekitd.api.request_dictionary_set_string(dict, key, newValue) }
}
public subscript(key: sourcekitd_uid_t?) -> Int {
get { fatalError("request is set-only") }
set { sourcekitd.api.request_dictionary_set_int64(dict, key, Int64(newValue)) }
}
public subscript(key: sourcekitd_uid_t?) -> sourcekitd_uid_t? {
get { fatalError("request is set-only") }
set { sourcekitd.api.request_dictionary_set_uid(dict, key, newValue) }
}
public subscript(key: sourcekitd_uid_t?) -> SKRequestDictionary {
get { fatalError("request is set-only") }
set { sourcekitd.api.request_dictionary_set_value(dict, key, newValue.dict) }
}
public subscript<S>(key: sourcekitd_uid_t?) -> S where S: Sequence, S.Element == String {
get { fatalError("request is set-only") }
set {
let array = SKRequestArray(sourcekitd: sourcekitd)
newValue.forEach { array.append($0) }
sourcekitd.api.request_dictionary_set_value(dict, key, array.array)
}
}
subscript(key: sourcekitd_uid_t?) -> SKRequestArray {
get { fatalError("request is set-only") }
set { sourcekitd.api.request_dictionary_set_value(dict, key, newValue.array) }
}
}
final class SKRequestArray {
let array: sourcekitd_object_t?
let sourcekitd: SourceKit
init(_ array: sourcekitd_object_t? = nil, sourcekitd: SourceKit) {
self.array = array ?? sourcekitd.api.request_array_create(nil, 0)
self.sourcekitd = sourcekitd
}
deinit {
sourcekitd.api.request_release(array)
}
func append(_ value: String) {
sourcekitd.api.request_array_set_string(array, -1, value)
}
}
final class SKResponse {
let response: sourcekitd_response_t?
let sourcekitd: SourceKit
init(_ response: sourcekitd_response_t?, sourcekitd: SourceKit) {
self.response = response
self.sourcekitd = sourcekitd
}
deinit {
sourcekitd.api.response_dispose(response)
}
var error: String? {
if !sourcekitd.api.response_is_error(response) {
return nil
}
return description
}
var value: SKResponseDictionary? {
if sourcekitd.api.response_is_error(response) {
return nil
}
return SKResponseDictionary(sourcekitd.api.response_get_value(response), response: self)
}
}
final class SKResponseDictionary {
let dict: sourcekitd_variant_t
let resp: SKResponse
let parent: SKResponseDictionary!
var sourcekitd: SourceKit { resp.sourcekitd }
init(_ dict: sourcekitd_variant_t, response: SKResponse, parent: SKResponseDictionary! = nil) {
self.dict = dict
self.parent = parent
resp = response
}
subscript(key: sourcekitd_uid_t?) -> String? {
sourcekitd.api.variant_dictionary_get_string(dict, key).map(String.init(cString:))
}
subscript(key: sourcekitd_uid_t?) -> Int? {
Int(sourcekitd.api.variant_dictionary_get_int64(dict, key))
}
subscript(key: sourcekitd_uid_t?) -> SKUID? {
guard let uid = sourcekitd.api.variant_dictionary_get_uid(dict, key) else {
return nil
}
return SKUID(uid: uid, sourcekitd: sourcekitd)
}
subscript(key: sourcekitd_uid_t?) -> SKResponseArray? {
SKResponseArray(sourcekitd.api.variant_dictionary_get_value(dict, key), response: resp)
}
func recurseEntities(block: @escaping (SKResponseDictionary) throws -> Void) rethrows {
try recurse(uid: sourcekitd.keys.entities, block: block)
}
func recurse(uid: sourcekitd_uid_t, block: @escaping (SKResponseDictionary) throws -> Void) rethrows {
guard let array: SKResponseArray = self[uid] else {
return
}
try array.forEach(parent: self) { (_, dict) -> Bool in
try block(dict)
try dict.recurseEntities(block: block)
return true
}
}
}
final class SKResponseArray {
let array: sourcekitd_variant_t
let resp: SKResponse
var sourcekitd: SourceKit { resp.sourcekitd }
init(_ array: sourcekitd_variant_t, response: SKResponse) {
self.array = array
resp = response
}
var count: Int { sourcekitd.api.variant_array_get_count(array) }
subscript(i: Int) -> SKResponseDictionary {
return get(i, parent: nil)
}
private func get(_ i: Int, parent: SKResponseDictionary!) -> SKResponseDictionary {
SKResponseDictionary(sourcekitd.api.variant_array_get_value(array, i), response: resp, parent: parent)
}
/// If the `applier` returns `false`, iteration terminates.
@discardableResult
func forEach(parent: SKResponseDictionary, _ applier: (Int, SKResponseDictionary) throws -> Bool) rethrows -> Bool {
for i in 0 ..< count {
if try applier(i, get(i, parent: parent)) == false {
return false
}
}
return true
}
}
extension SKRequestDictionary: CustomStringConvertible {
public var description: String {
let ptr = sourcekitd.api.request_description_copy(dict)!
defer { free(ptr) }
return String(cString: ptr)
}
}
extension SKRequestArray: CustomStringConvertible {
var description: String {
let ptr = sourcekitd.api.request_description_copy(array)!
defer { free(ptr) }
return String(cString: ptr)
}
}
extension SKResponse: CustomStringConvertible {
public var description: String {
let ptr = sourcekitd.api.response_description_copy(response)!
defer { free(ptr) }
return String(cString: ptr)
}
}
extension SKResponseDictionary: CustomStringConvertible {
public var description: String {
let ptr = sourcekitd.api.variant_description_copy(dict)!
defer { free(ptr) }
return String(cString: ptr)
}
}
extension SKResponseArray: CustomStringConvertible {
var description: String {
let ptr = sourcekitd.api.variant_description_copy(array)!
defer { free(ptr) }
return String(cString: ptr)
}
}
struct Variant: CustomStringConvertible {
// The lifetime of this sourcekitd_variant_t is tied to the response it came
// from, so keep a reference to the response too.
let val: sourcekitd_variant_t
let context: SKResponse
var sourcekitd: SourceKit { context.sourcekitd }
fileprivate init(val: sourcekitd_variant_t, context: SKResponse) {
self.val = val
self.context = context
}
func getString() -> String {
let value = sourcekitd.api.variant_string_get_ptr(val)!
let length = sourcekitd.api.variant_string_get_length(val)
return fromCStringLen(value, length: length)!
}
func getStringBuffer() -> UnsafeBufferPointer<Int8> {
UnsafeBufferPointer(start: sourcekitd.api.variant_string_get_ptr(val),
count: sourcekitd.api.variant_string_get_length(val))
}
func getInt() -> Int {
let value = sourcekitd.api.variant_int64_get_value(val)
return Int(value)
}
func getBool() -> Bool {
let value = sourcekitd.api.variant_bool_get_value(val)
return value
}
func getArray() -> SKResponseArray {
SKResponseArray(val, response: context)
}
func getDictionary() -> SKResponseDictionary {
SKResponseDictionary(val, response: context)
}
var description: String {
let utf8Str = sourcekitd.api.variant_description_copy(val)!
let result = String(cString: utf8Str)
free(utf8Str)
return result
}
func recurseOver(uid: sourcekitd_uid_t, block: @escaping (Variant) -> Void) {
let children = sourcekitd.api.variant_dictionary_get_value(val, uid)
guard sourcekitd.api.variant_get_type(children) == SOURCEKITD_VARIANT_TYPE_ARRAY else {
return
}
_ = sourcekitd.api.variant_array_apply(children) { _, val in
let variant = Variant(val: val, context: self.context)
block(variant)
variant.recurseOver(uid: uid, block: block)
return true
}
}
}
private func fromCStringLen(_ ptr: UnsafePointer<Int8>, length: Int) -> String? {
String(decoding: Array(UnsafeBufferPointer(start: ptr, count: length)).map {
UInt8(bitPattern: $0)
}, as: UTF8.self)
}
public struct SKUID: CustomStringConvertible {
public let uid: sourcekitd_uid_t
let sourcekitd: SourceKit
init(uid: sourcekitd_uid_t, sourcekitd: SourceKit) {
self.uid = uid
self.sourcekitd = sourcekitd
}
public var description: String {
String(cString: sourcekitd.api.uid_get_string_ptr(uid)!)
}
public var asString: String {
String(cString: sourcekitd.api.uid_get_string_ptr(uid)!)
}
func referenceType() -> SourceKit.DeclarationType? {
declarationType(firstSuffix: ".ref.")
}
func declarationType() -> SourceKit.DeclarationType? {
declarationType(firstSuffix: ".decl.")
}
func declarationType(firstSuffix: String) -> SourceKit.DeclarationType? {
let kind = description
let prefix = "source.lang.swift" + firstSuffix
guard kind.hasPrefix(prefix) else {
return nil
}
let prefixIndex = kind.index(kind.startIndex, offsetBy: prefix.count)
let kindSuffix = String(kind[prefixIndex...])
switch kindSuffix {
case "class",
"struct":
return .object
case "protocol":
return .protocol
case "var.instance",
"var.static",
"var.global",
"var.class":
return .property
case "function.free",
"function.method.instance",
"function.method.static",
"function.method.class":
return .method
case "enum":
return .enum
case "enumelement":
return .enumelement
default:
return nil
}
}
}
|
gpl-3.0
|
8b21964ff02c85766ece0cb4745a48dd
| 46.704294 | 132 | 0.680264 | 3.750265 | false | false | false | false |
blstream/AugmentedSzczecin_iOS
|
AugmentedSzczecin/AugmentedSzczecin/ASAboutViewController.swift
|
1
|
2204
|
//
// ASAboutViewController.swift
// AugmentedSzczecin
//
// Created by Grzegorz Pawlowicz on 31.05.2015.
// Copyright (c) 2015 BLStream. All rights reserved.
//
import UIKit
class ASAboutViewController: UIViewController {
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var logoImage: UIImageView!
@IBOutlet weak var applicationNameAndVersionLabel: UILabel!
@IBOutlet weak var aboutTextView: UITextView!
@IBOutlet weak var closeButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
backgroundImage.image = UIImage(named: "szczecin_bg")
logoImage.image = UIImage(named: "logo_as_vert")
let applicationName: AnyObject? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName")
let applicationVersion: AnyObject? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString")
let applicationBuild: AnyObject? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion")
applicationNameAndVersionLabel.text = "\(applicationName!) \(applicationVersion!)(\(applicationBuild!))"
applicationNameAndVersionLabel.textColor = UIColor.blackAugmentedColor()
closeButton.setTitle("Close".localized, forState: UIControlState.Normal)
closeButton.setTitleColor(UIColor.mediumBlueAugmentedColor(), forState: UIControlState.Normal)
aboutTextView.textColor = UIColor.dodgerBlueAugmentedColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func closeButtonTap(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}
/*
// 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.
}
*/
}
|
apache-2.0
|
891fb46f17354c8d358c7e179e25a3f8
| 37 | 123 | 0.708258 | 5.401961 | false | false | false | false |
mvoong/MVStaticSectionKit
|
Pod/Classes/StaticDataSource.swift
|
1
|
9229
|
//
// StaticDataSource.swift
// MVStaticSectionKit
//
// Created by Michael Voong on 12/11/2015.
// Copyright © 2015 Michael Voong. All rights reserved.
//
import Foundation
import CoreData
// MARK: StaticDataSource
public class StaticDataSource<S: Section> : NSObject {
/**
The static sections
*/
private lazy var sections = [S]()
private lazy var resultsControllerDelegates = [NSFetchedResultsController: NSFetchedResultsControllerDelegate]()
/**
Add an empty `Section` to the receiver
- returns: The empty `Section` that has been added
*/
public func addSection(title: String? = nil) -> S {
let section = S()
section.title = title
self.addSection(section)
return section
}
/**
Add a `Section` to the receiver
- returns: The `Section` that has been added
*/
public func addSection(section: S) -> S {
self.sections.append(section)
section.resultsControllerChanged = { [unowned self] in
self.updateResultsControllerDelegates()
}
return section
}
/**
Inserts a `Section` to the receiver
- returns: The `Section` that has been inserted
*/
public func insertSection(section: S, atIndex: Int) -> S {
self.sections.insert(section, atIndex: atIndex)
section.resultsControllerChanged = { [unowned self] in
self.updateResultsControllerDelegates()
}
return section
}
/**
Deletes a section from the receiver
*/
public func deleteSection(section: S, atIndex: Int) {
if let resultsController = section.fetchedResultsController {
resultsController.delegate = nil
self.resultsControllerDelegates.removeValueForKey(resultsController)
}
self.sections.removeObject(section)
}
/**
Finds the `Section` for the given index
- returns: The `Section`, or nil if no section exists at that index
*/
func sectionForIndex(index: Int) -> S? {
return self.sections[index]
}
/**
Finds the index of the section that has the given `NSFetchedResultsController` assigned
- parameter resultsController: The results controller to search the sections for
- returns: The index of the found `Section`
*/
func sectionIndexForFetchedResultsController(resultsController: NSFetchedResultsController) -> Int? {
if let section = self.sectionForFetchedResultsController(resultsController) {
return self.sectionIndexForSection(section)
}
return nil
}
/**
Finds the `Section` for the given fetched results controller
- parameter resultsController: The results controller to search the sections for
- returns: The found `Section`
*/
func sectionForFetchedResultsController(resultsController: NSFetchedResultsController) -> S? {
for section in self.sections {
if section.fetchedResultsController == resultsController {
return section
}
}
return nil
}
/**
Finds the index for a given `Section`
- parameter section: The `Section` to search for
*/
func sectionIndexForSection(section: S) -> Int? {
return self.sections.indexOf(section)
}
func updateResultsControllerDelegates() {
fatalError("updateResultsControllerDelegates not implemented")
}
}
extension StaticDataSource : DataSource {
/**
- returns: The number of `Section` objects
*/
public func numberOfSections() -> Int {
return self.sections.count
}
/**
- parameter index: The index of the `Section`
- returns: The number of items in a given `Section`
*/
public func numberOfItemsInSection(index: Int) -> Int {
return self.sections[index].numberOfItems()
}
/**
- returns: The total number of `Item` objects across all sections
*/
public func numberOfItems() -> Int {
var count = 0
for section in self.sections {
count += section.numberOfItems()
}
return count
}
/**
Finds the object at a given index path. For convenience, if the object is a subclass of `Item` and the item has an assigned `object`,
that object will be returned. Otherwise, the item is returned.
- returns: The object, or nil if there is no object at the specified index path
*/
public func objectAtIndexPath(indexPath: NSIndexPath) -> Any? {
return self.sections[indexPath.section].objectAtIndex(indexPath.row)
}
public func titleForSection(index: Int) -> String? {
return self.sectionForIndex(index)?.title
}
public func footerTitleForSection(index: Int) -> String? {
return self.sectionForIndex(index)?.footerTitle
}
/**
Maps the section for the results controller to the actual UITableView section
*/
public func convertSectionForResultsController(resultsController: NSFetchedResultsController, sectionIndex: Int) -> Int {
return self.sectionIndexForFetchedResultsController(resultsController)!
}
}
// MARK: StaticTableDataSource
public class StaticTableDataSource : StaticDataSource<TableSection> {
weak var tableView: UITableView?
var tableViewAdapter: TableViewAdapter!
/**
Initialises the data source with a given table. A weak reference is made to the table view.
- parameter view: The table view
*/
public init(tableView: UITableView) {
super.init()
self.tableView = tableView
self.tableViewAdapter = TableViewAdapter(tableView: tableView, dataSource: self)
}
/**
Returns the selected object, or nil if there is no selection
- returns: The selected object or nil
*/
public func selectedObject() -> Any? {
guard let indexPath = self.tableView?.indexPathForSelectedRow else {
return nil
}
return self.objectAtIndexPath(indexPath)
}
override func updateResultsControllerDelegates() {
for section in self.sections {
if let tableView = self.tableView, resultsController = section.fetchedResultsController {
if self.resultsControllerDelegates[resultsController] == nil {
self.resultsControllerDelegates[resultsController] = TableFetchedResultsControllerDelegate(tableView: tableView, resultsController: resultsController, dataSource: self)
}
}
}
}
}
extension StaticTableDataSource : TableDataSource {
public func cellFactoryForSection(sectionIndex: Int) -> TableCellFactoryType {
return (self.sectionForIndex(sectionIndex)?.cellFactory!)!
}
public func configureCellForSection(sectionIndex: Int) -> TableConfigureCellType? {
return self.sectionForIndex(sectionIndex)?.configureCell
}
public func sectionViewFactoryForSection(sectionIndex: Int) -> TableSectionViewFactoryType? {
return self.sectionForIndex(sectionIndex)?.sectionViewFactory
}
public func reuseIdentifierForSection(sectionIndex: Int) -> String? {
return self.sectionForIndex(sectionIndex)?.reuseIdentifier
}
}
// MARK: StaticCollectionDataSource
public class StaticCollectionDataSource : StaticDataSource<CollectionSection> {
weak var collectionView: UICollectionView?
var collectionViewAdapter: CollectionViewAdapter!
public init(collectionView: UICollectionView) {
super.init()
self.collectionView = collectionView
self.collectionViewAdapter = CollectionViewAdapter(collectionView: collectionView, dataSource: self)
}
override func updateResultsControllerDelegates() {
for section in self.sections {
if let collectionView = self.collectionView, resultsController = section.fetchedResultsController {
if self.resultsControllerDelegates[resultsController] == nil {
self.resultsControllerDelegates[resultsController] = CollectionFetchedResultsControllerDelegate(collectionView: collectionView, resultsController: resultsController, dataSource: self)
}
}
}
}
}
extension StaticCollectionDataSource : CollectionDataSource {
public func cellFactoryForSection(sectionIndex: Int) -> CollectionCellFactoryType {
return (self.sectionForIndex(sectionIndex)?.cellFactory!)!
}
public func configureCellForSection(sectionIndex: Int) -> CollectionConfigureCellType? {
return self.sectionForIndex(sectionIndex)?.configureCell
}
public func emptyCellFactoryForSection(sectionIndex: Int) -> CollectionEmptyCellFactoryType? {
return self.sectionForIndex(sectionIndex)?.emptyCellFactory
}
public func sectionViewFactoryForSection(sectionIndex: Int) -> CollectionSectionViewFactoryType? {
return self.sectionForIndex(sectionIndex)?.sectionViewFactory
}
}
|
mit
|
92b91d5ca17ef0a547b4ec9b74f2c1f3
| 31.723404 | 203 | 0.664391 | 5.460355 | false | false | false | false |
mrdepth/Neocom
|
Legacy/Neocom/Neocom/NCDatabaseCertificateRequirementsViewController.swift
|
2
|
3725
|
//
// NCDatabaseCertificateRequirementsViewController.swift
// Neocom
//
// Created by Artem Shimanski on 15.06.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import EVEAPI
import Futures
class NCDatabaseCertTypeRow: NCFetchedResultsObjectNode<NCDBInvType> {
var character: NCCharacter?
var subtitle: String?
required init(object: NCDBInvType) {
super.init(object: object)
cellIdentifier = Prototype.NCDefaultTableViewCell.default.reuseIdentifier
}
override func configure(cell: UITableViewCell) {
let cell = cell as! NCDefaultTableViewCell
cell.titleLabel?.text = object.typeName
cell.iconView?.image = object.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image
cell.object = object
cell.accessoryType = .disclosureIndicator
if let subtitle = subtitle {
cell.subtitleLabel?.text = subtitle
}
else {
cell.subtitleLabel?.text = nil
if let character = character {
NCDatabase.sharedDatabase?.performBackgroundTask { managedObjectContext in
let type = try! managedObjectContext.existingObject(with: self.object.objectID) as! NCDBInvType
let trainingQueue = NCTrainingQueue(character: character)
trainingQueue.addRequiredSkills(for: type)
let trainingTime = trainingQueue.trainingTime(characterAttributes: character.attributes)
let subtitle = trainingTime > 0 ? NCTimeIntervalFormatter.localizedString(from: trainingTime, precision: .seconds) : ""
DispatchQueue.main.async {
self.subtitle = subtitle
if (cell.object as? NCDBInvType) == self.object {
cell.subtitleLabel?.text = subtitle
}
}
}
}
}
}
}
class NCDatabaseCertificateRequirementsViewController: NCTreeViewController {
var certificate: NCDBCertCertificate?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCDefaultTableViewCell.default,
Prototype.NCHeaderTableViewCell.default,
])
}
override func content() -> Future<TreeNode?> {
guard let certificate = certificate else {return .init(nil)}
let progress = Progress(totalUnitCount: 1)
let request = NSFetchRequest<NCDBInvType>(entityName: "InvType")
request.predicate = NSPredicate(format: "published = TRUE AND ANY certificates == %@", certificate)
request.sortDescriptors = [NSSortDescriptor(key: "group.groupName", ascending: true), NSSortDescriptor(key: "typeName", ascending: true)]
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: NCDatabase.sharedDatabase!.viewContext, sectionNameKeyPath: "group.groupName", cacheName: nil)
let root = FetchedResultsNode(resultsController: results, sectionNode: NCDefaultFetchedResultsSectionNode<NCDBInvType>.self, objectNode: NCDatabaseCertTypeRow.self)
progress.perform { NCCharacter.load(account: NCAccount.current) }.then(on: .main) { character in
root.children.forEach {
$0.children.forEach { row in
(row as? NCDatabaseCertTypeRow)?.character = character
}
}
}.catch(on: .main) { _ in
let character = NCCharacter()
root.children.forEach {
$0.children.forEach { row in
(row as? NCDatabaseCertTypeRow)?.character = character
}
}
}.finally(on: .main) {
self.tableView.reloadData()
}
return .init(root)
}
// MARK: TreeControllerDelegate
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
guard let row = node as? NCDatabaseCertTypeRow else {return}
Router.Database.TypeInfo(row.object).perform(source: self, sender: treeController.cell(for: node))
}
}
|
lgpl-2.1
|
c13f4da110b2fe7f3d3bcc941b00ab06
| 34.132075 | 182 | 0.738722 | 4.26087 | false | false | false | false |
strawberrycode/RealmPagination
|
realmPagination/CollectionViewController.swift
|
1
|
6818
|
//
// CollectionViewController.swift
// realmPagination
//
// Created by Catherine Schwartz on 25/10/2015.
// Copyright © 2015 Catherine Schwartz. All rights reserved.
//
import UIKit
import RealmSwift
private let reuseIdentifier = "CollectionCell"
class CollectionViewController: UICollectionViewController {
let realm = try! Realm()
let translator = Translator()
var notificationToken: NotificationToken?
// var countries = try! Realm().objects(Country).sorted("id") // if used, no need to do the query in refreshData()
var countries = Results<Country>?()
let preloadMargin = 5
var lastLoadedPage = 0
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
// Register cell classes
// self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// self.collectionView!.registerNib(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
if let cvl = self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
let cellWidth = UIScreen.mainScreen().bounds.width / 2
cvl.estimatedItemSize = CGSize(width: cellWidth, height: cellWidth)
cvl.minimumInteritemSpacing = 0
cvl.minimumLineSpacing = 0
}
// clean DB
try! realm.write {
self.realm.deleteAll()
}
notificationToken = realm.addNotificationBlock { [unowned self] note, realm in
self.reloadData()
}
getData()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.collectionView?.layer.borderColor = UIColor.redColor().CGColor
self.collectionView?.layer.borderWidth = 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Data stuff
func getData(page: Int = 0) {
lastLoadedPage = page
let countriesToSave = translator.getJsonDataForPage(page)
// print("countries - page: \(page) \n\(countriesToSave) \n----------")
translator.saveCountries(countriesToSave)
}
func reloadData() {
countries = realm.objects(Country).sorted("id")
// print("savedCountries: \(countries)")
collectionView?.reloadSections(NSIndexSet(index: 0))
// self.collectionView?.reloadData()
}
// 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.
if (segue.identifier == "showCountryDetails") {
let cvc = segue.destinationViewController as! CountryViewController
if let countries = self.countries,
tag = sender!.tag {
cvc.country = countries[tag]
}
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
if let countries = countries {
print("countries.count: \(countries.count)")
return countries.count
}
return 0
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
// Configure the cell
let nextPage: Int = Int(indexPath.item / pageSize) + 1
let preloadIndex = nextPage * pageSize - preloadMargin
// print("indexPath.row: \(indexPath.item) - nextPage: \(nextPage) - lastLoadedPage: \(lastLoadedPage) - preloadIndex: \(preloadIndex)")
if (indexPath.item >= preloadIndex && lastLoadedPage < nextPage) {
print("get next page : \(nextPage)")
getData(nextPage)
}
if let countries = self.countries {
let country = countries[indexPath.item] //as Country
// cell.index!.text = "\(indexPath.item)"
// cell.configureCellForCountryAtIndexPath(country, indexPath: indexPath)
print("index: \(indexPath.item) - country: \(country.name) - \(country.code) - \(cell.frame)")
cell.indexLabel.text = "\(indexPath.item)"
cell.countryLabel.text = country.name
cell.codeLabel.text = country.code
cell.tag = indexPath.item
}
cell.setBorder(UIColor.blueColor())
cell.backgroundColor = UIColor.whiteColor()
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
|
mit
|
59df87d016830db50257af6c47b3220e
| 35.068783 | 185 | 0.657914 | 5.555827 | false | false | false | false |
andrewlowson/Visiocast
|
Visucast/DictationManager.swift
|
1
|
1450
|
//
// DictationManager.swift
// Visiocast
//
// Created by Andrew Lowson on 13/08/2015.
// Copyright (c) 2015 Andrew Lowson. All rights reserved.
//
import Foundation
class DictationManager {
// This entire class has been commented out due to code signing issues and a timing constraint.
// var lmGenerator = ["thing","other thing","third thing"]
//
//
// init() {
// var lmGenerator = OELanguageModelGenerator()
// var words: NSArray = ["SEARCH", "FOR", "TECHNOLOGY", "WEATHER", ""]
// var name = "LanguageModel"
//
// // Objective C header
// // - (NSError *) generateLanguageModelFromArray:(NSArray *)languageModelArray withFilesNamed:(NSString *)fileName forAcousticModelAtPath:(NSString *)acousticModelPath; OEAcousticModel()
// var error = lmGenerator.generateLanguageModelFromArray(words as [AnyObject], withFilesNamed:name, forAcousticModelAtPath:"AcousticModelEnglish")
//
// var lmPath: String?
// var dicPath:String?
//
// if error == nil {
// lmPath = lmGenerator.pathToSuccessfullyGeneratedLanguageModelWithRequestedName("LanguageModel");
// dicPath = lmGenerator.pathToSuccessfullyGeneratedDictionaryWithRequestedName("LanguageModel");
// } else {
// println("Error: \(error.localizedDescription)");
// }
// }
//
// var test = lmGenerator as OELanguageModelGenerator
}
|
gpl-2.0
|
871b3ed0843451eb3d8ab1f5499ba0d1
| 36.205128 | 195 | 0.656552 | 3.940217 | false | false | false | false |
manuelCarlos/AutoLayout-park
|
alternateViews/alternateViews/Views/LandscapeView.swift
|
1
|
2951
|
//
// LandscapeView.swift
// alternateViews
//
// Created by Manuel Lopes on 11/05/16.
//
import UIKit
class LandscapeView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
convenience init() {
self.init(frame: CGRect.zero)
}
private func setup() {
let margins = self.layoutMarginsGuide
backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
let title: UILabel = setupTitle()
let pic = setUpProfilePic()
let plus = makeButtonWithTitle("+", fontSize: 20)
let back = makeButtonWithTitle("<", fontSize: 20)
addSubview(title)
addSubview(pic)
addSubview(plus)
addSubview(back)
NSLayoutConstraint.activate([
title.centerXAnchor.constraint(equalTo: centerXAnchor),
title.centerYAnchor.constraint(equalTo: centerYAnchor),
pic.centerXAnchor.constraint(equalTo: centerXAnchor),
pic.topAnchor.constraint(equalTo: title.bottomAnchor,constant: 10),
pic.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -50),
plus.topAnchor.constraint(equalTo: margins.topAnchor, constant: 20),
plus.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -20),
back.topAnchor.constraint(equalTo: margins.topAnchor, constant: 20),
back.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20)
])
}
// equivalent to viweWillAppear()
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
// nothing here for now
}
// equivalente to viewWillLayoutSubviews() and viewDidLayoutSubviews()
override func layoutSubviews() {
super.layoutSubviews()
// nothing here for now
}
private func setUpProfilePic() -> UIImageView {
let pic = UIImageView(image: UIImage(named: "me"))
pic.translatesAutoresizingMaskIntoConstraints = false
pic.contentMode = .scaleAspectFit
return pic
}
private func setupTitle() -> UILabel {
let lab = UILabel()
lab.text = "Mr. Fox in Landscape"
lab.font = UIFont.systemFont(ofSize: 60)
lab.translatesAutoresizingMaskIntoConstraints = false
return lab
}
private func makeButtonWithTitle(_ title: String, fontSize: Int) -> UIButton {
let button = UIButton(type: .system)
button.tintColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)
button.setTitle(title, for: UIControlState())
button.titleLabel?.font = .boldSystemFont(ofSize: CGFloat(fontSize))
button.translatesAutoresizingMaskIntoConstraints = false
return button
}
}
|
mit
|
59561988383fd768921df46b1fdb1629
| 30.393617 | 87 | 0.639444 | 4.91015 | false | false | false | false |
DanijelHuis/HDAugmentedReality
|
Example/HDAugmentedRealityDemo/ViewController.swift
|
1
|
9794
|
//
// ViewController.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 21/04/15.
// Copyright (c) 2015 Danijel Huis. All rights reserved.
//
import UIKit
import CoreLocation
import HDAugmentedReality
import MapKit
class ViewController: UIViewController
{
/// Creates random annotations around predefined center point and presents ARViewController modally
func showARViewController()
{
//===== Create random annotations around center point
//FIXME: set your initial position here, this is used to generate random POIs
let lat = 45.554864
let lon = 18.695441
//let lat = 45.681177
//let lon = 18.401508
let deltaLat = 0.2 // Area in which to generate annotations
let deltaLon = 0.2 // Area in which to generate annotations
let altitudeDelta: Double = 0
let annotationCount = 200
let dummyAnnotations = ViewController.getDummyAnnotations(centerLatitude: lat, centerLongitude: lon, deltaLat: deltaLat, deltaLon: deltaLon, altitudeDelta: altitudeDelta, count: annotationCount)
//===== ARViewController
// Creating ARViewController. You can use ARViewController(nibName:bundle:) if you have custom xib.
let arViewController = ARViewController()
//===== Presenter - handles visual presentation of annotations
let presenter = arViewController.presenter!
// Vertical offset by distance
presenter.distanceOffsetMode = .manual
presenter.distanceOffsetMultiplier = 0.05 // Pixels per meter
presenter.distanceOffsetMinThreshold = 1000 // Tell it to not raise annotations that are nearer than this
// Limiting number of annotations shown for performance
presenter.maxDistance = 5000 // Don't show annotations if they are farther than this
presenter.maxVisibleAnnotations = 100 // Max number of annotations on the screen
// Telling it to stack vertically.
presenter.presenterTransform = ARPresenterStackTransform()
//===== Tracking manager - handles location tracking, heading, pitch, calculations etc.
// Location precision
let trackingManager = arViewController.trackingManager
trackingManager.userDistanceFilter = 15
trackingManager.reloadDistanceFilter = 50
//trackingManager.filterFactor = 0.05
//trackingManager.headingSource = .deviceMotion // Read headingSource property description before changing.
//===== ARViewController
// Ui
arViewController.dataSource = self
// Debugging
arViewController.uiOptions.debugLabel = false
arViewController.uiOptions.debugMap = true
arViewController.uiOptions.simulatorDebugging = Platform.isSimulator
arViewController.uiOptions.setUserLocationToCenterOfAnnotations = Platform.isSimulator
// Interface orientation
arViewController.interfaceOrientationMask = .all
// Failure handling
arViewController.onDidFailToFindLocation =
{
[weak self, weak arViewController] elapsedSeconds, acquiredLocationBefore in
self?.handleLocationFailure(elapsedSeconds: elapsedSeconds, acquiredLocationBefore: acquiredLocationBefore, arViewController: arViewController)
}
// Setting annotations
arViewController.setAnnotations(dummyAnnotations)
arViewController.modalPresentationStyle = .fullScreen
//===== Radar
var safeArea = UIEdgeInsets.zero
if #available(iOS 11.0, *) { safeArea = UIApplication.shared.delegate?.window??.safeAreaInsets ?? UIEdgeInsets.zero }
let radar = RadarMapView()
radar.startMode = .centerUser(span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
radar.trackingMode = .none
//radar.configuration... Use it to customize
radar.indicatorRingType = .segmented(segmentColor: nil, userSegmentColor: nil)
//radar.indicatorRingType = .precise(indicatorColor: nil, userIndicatorColor: .white)
//radar.maxDistance = 5000 // Limit bcs it drains battery if lots of annotations (>200), especially if indicatorRingType is .precise
arViewController.addAccessory(radar, leading: 15, trailing: nil, top: nil, bottom: 15 + safeArea.bottom / 4, width: nil, height: 150)
//===== Presenting controller
self.present(arViewController, animated: true, completion: nil)
}
@IBAction func buttonTap(_ sender: AnyObject)
{
self.showARViewController()
}
func handleLocationFailure(elapsedSeconds: TimeInterval, acquiredLocationBefore: Bool, arViewController: ARViewController?)
{
guard let arViewController = arViewController else { return }
guard !Platform.isSimulator else { return }
NSLog("Failed to find location after: \(elapsedSeconds) seconds, acquiredLocationBefore: \(acquiredLocationBefore)")
// Example of handling location failure
if elapsedSeconds >= 20 && !acquiredLocationBefore
{
// Stopped bcs we don't want multiple alerts
arViewController.trackingManager.stopTracking()
let alert = UIAlertController(title: "Problems", message: "Cannot find location, use Wi-Fi if possible!", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Close", style: .cancel)
{
(action) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(okAction)
self.presentedViewController?.present(alert, animated: true, completion: nil)
}
}
}
//==========================================================================================================================================================
// MARK: ARDataSource
//==========================================================================================================================================================
extension ViewController: ARDataSource
{
/// This method is called by ARViewController, make sure to set dataSource property.
func ar(_ arViewController: ARViewController, viewForAnnotation annotation: ARAnnotation) -> ARAnnotationView
{
// Annotation views should be lightweight views, try to avoid xibs and autolayout all together.
let annotationView = TestAnnotationView()
annotationView.frame = CGRect(x: 0,y: 0,width: 150,height: 50)
return annotationView;
}
/// This can currently only be called because of camera error.
func ar(_ arViewController: ARViewController, didFailWithError error: Error)
{
if let _ = error as? CameraViewError
{
let alert = UIAlertController(title: "Error", message: "Failed to initialize camera.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Close", style: .cancel)
{
(action) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(okAction)
self.presentedViewController?.present(alert, animated: true, completion: nil)
}
}
}
//==========================================================================================================================================================
// MARK: Dummy data
//==========================================================================================================================================================
extension ViewController
{
public class func getDummyAnnotations(centerLatitude: Double, centerLongitude: Double, deltaLat: Double, deltaLon: Double, altitudeDelta: Double, count: Int) -> Array<ARAnnotation>
{
var annotations: [ARAnnotation] = []
srand48(2)
for i in stride(from: 0, to: count, by: 1)
{
let location = self.getRandomLocation(centerLatitude: centerLatitude, centerLongitude: centerLongitude, deltaLat: deltaLat, deltaLon: deltaLon, altitudeDelta: altitudeDelta)
if let annotation = TestAnnotation(identifier: nil, title: "POI \(i)", location: location, type: TestAnnotationType.allCases.randomElement()!)
{
annotations.append(annotation)
}
}
return annotations
}
func addDummyAnnotation(_ lat: Double,_ lon: Double, altitude: Double, title: String, annotations: inout [ARAnnotation])
{
let location = CLLocation(coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lon), altitude: altitude, horizontalAccuracy: 0, verticalAccuracy: 0, course: 0, speed: 0, timestamp: Date())
if let annotation = ARAnnotation(identifier: nil, title: title, location: location)
{
annotations.append(annotation)
}
}
public class func getRandomLocation(centerLatitude: Double, centerLongitude: Double, deltaLat: Double, deltaLon: Double, altitudeDelta: Double) -> CLLocation
{
var lat = centerLatitude
var lon = centerLongitude
let latDelta = -(deltaLat / 2) + drand48() * deltaLat
let lonDelta = -(deltaLon / 2) + drand48() * deltaLon
lat = lat + latDelta
lon = lon + lonDelta
let altitude = drand48() * altitudeDelta
return CLLocation(coordinate: CLLocationCoordinate2D(latitude: lat, longitude: lon), altitude: altitude, horizontalAccuracy: 1, verticalAccuracy: 1, course: 0, speed: 0, timestamp: Date())
}
}
|
mit
|
bf81591c68b7d9221adf2961bd24ed8e
| 47.97 | 204 | 0.6165 | 5.590183 | false | false | false | false |
aijaz/icw1502
|
Week11/Week11TabBar/Week11TabBar/HypnoViewController.swift
|
1
|
1754
|
//
// ViewController.swift
// HypnoRect
//
// Created by Aijaz Ansari on 11/7/15.
// Copyright © 2015 Euclid Software, LLC. All rights reserved.
//
import UIKit
class HypnoViewController: UIViewController, RaterDelegate {
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var hypnoView: HypnoView!
@IBOutlet weak var raterView: Rater!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
raterView.delegate = self
self.raterView.stencil = Circle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func handleSlider(sender: AnyObject) {
hypnoView.lineWidth = CGFloat(Int(slider.value))
}
func ratingSetTo(rating rating: Int) {
if rating > 0 {
hypnoView.lineWidth = CGFloat(rating * 2)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showNumericEntry" {
let dest = segue.destinationViewController as! NumericInputViewController
let currentWidth = Int(hypnoView.lineWidth)
dest.initialWidth = currentWidth
dest.textHandler = { text in
var width = 5
if let text = text {
if let intWidth = Int(text) {
if intWidth > 0 && intWidth <= 20 {
width = intWidth
}
}
}
self.hypnoView.lineWidth = CGFloat(width)
}
}
}
}
|
mit
|
ab158282ed20e0d0d7160bed647449b7
| 28.216667 | 85 | 0.574444 | 4.750678 | false | false | false | false |
jcfausto/transit-app
|
TransitApp/TransitAppTests/RoutesSpecs.swift
|
1
|
2975
|
//
// RoutesSpecs.swift
// TransitApp
//
// Created by Julio Cesar Fausto on 25/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import Quick
import Nimble
@testable import TransitApp
class RoutesSpecs: QuickSpec {
//MARK: Support routines
func createSegmentOne() -> Segment {
let stopOne = Stop(name: "", latitude: 52.530227, longitude: 52.530227, time: NSDate(datetimeString: "2015-04-17T13:30:00+02:00"))
let stopTwo = Stop(name: "U Rosa-Luxemburg-Platz", latitude: 52.528187, longitude: 13.410404, time: NSDate(datetimeString: "2015-04-17T13:38:00+02:00"))
let stops = [stopOne, stopTwo]
let travelMode = "Walking"
//Used an extension here
let color = UIColor(hexString: "#b1ecc")
let iconUrl = "https://d3m2tfu2xpiope.cloudfront.net/vehicles/walking.svg"
let polyline = "uvr_I{yxpABuAFcAp@yHvAwNr@iGPwAh@a@jAg@"
return Segment(name: "", numStops: 0, description: "", stops: stops, travelMode: travelMode, color: color, iconUrl: iconUrl, polyline: polyline)
}
func createSegmentTwo() -> Segment {
let stopOne = Stop(name: "U Rosa-Luxemburg-Platz", latitude: 52.528187, longitude: 13.410404, time: NSDate(datetimeString: "2015-04-17T13:38:00+02:00"))
let stopTwo = Stop(name: "S+U Alexanderplatz", latitude: 52.522074, longitude: 13.413595, time: NSDate(datetimeString: "2015-04-17T13:40:00+02:00"))
let stops = [stopOne, stopTwo]
let travelMode = "Subway"
//Used an extension here
let color = UIColor(hexString: "#d64820")
let iconUrl = "https://d3m2tfu2xpiope.cloudfront.net/vehicles/subway.svg"
let polyline = "elr_I_fzpAfe@_Sf]dFr_@~UjCbg@yKvj@lFfb@`C|c@hNjc@"
return Segment(name: "U2", numStops: 2, description: "S+U Potsdamer Platz", stops: stops, travelMode: travelMode, color: color, iconUrl: iconUrl, polyline: polyline)
}
override func spec() {
describe("Routes"){
var routes: Routes!
beforeEach {
let segmentOne = self.createSegmentOne()
let segmentTwo = self.createSegmentTwo()
let price = Price(amount: 10.50, currency: "EUR")
let routeOne = Route(type: "public_transport", provider: "vbb", segments: [segmentOne, segmentTwo], price: price)
let routeTwo = Route(type: "public_transport", provider: "taxi", segments: [segmentOne, segmentTwo], price: price)
routes = Routes(withRoutes: [routeOne, routeTwo])
}
it("has more than one route"){
expect(routes.routes.count).to(beGreaterThan(1))
}
}
}
}
|
mit
|
7cc4e59510839c161e210c1fd7f7ea8b
| 34.831325 | 173 | 0.578682 | 3.769328 | false | false | false | false |
stormpath/stormpath-swift-example
|
Pods/Stormpath/Stormpath/Account.swift
|
1
|
4575
|
//
// Account.swift
// Stormpath
//
// Created by Edward Jiang on 2/11/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
/**
Account represents an account object from the Stormpath database.
*/
@objc(SPHAccount)
public class Account: NSObject {
/// Stormpath resource URL for the account
internal(set) public var href: URL!
/// Username of the user. Separate from the email, but is often set to the email
/// address.
internal(set) public var username: String!
/// Email address of the account.
internal(set) public var email: String!
/**
Given (first) name of the user. Will appear as "UNKNOWN" on platforms
that do not require `givenName`
*/
internal(set) public var givenName: String!
/// Middle name of the user. Optional.
internal(set) public var middleName: String?
/**
Sur (last) name of the user. Will appear as "UNKNOWN" on platforms that do not require `surname`
*/
internal(set) public var surname: String!
/// Full name of the user.
public var fullName: String {
return "\(givenName ?? "") \((middleName ?? "") + " ")\(surname ?? "")"
}
/// Date the account was created in the Stormpath database.
internal(set) public var createdAt: Date!
/// Date the account was last modified in the Stormpath database.
internal(set) public var modifiedAt: Date!
/// Status of the account. Useful if email verification is needed.
internal(set) public var status: AccountStatus
/// A string of JSON representing the custom data for the account. Cannot be updated in the current version of the SDK.
internal(set) public var customData: String?
/// Initializer for the JSON object for the account. Expected to be wrapped in `{account: accountObject}`
init?(fromJSON jsonData: Data) {
self.status = .enabled //will be overridden below; hack to allow obj-c to access property since primitive types can't be optional
super.init()
guard let rootJSON = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [String: Any],
let json = rootJSON["account"] as? [String: AnyObject],
let hrefString = json["href"] as? String,
let href = URL(string: hrefString),
let username = json["username"] as? String,
let email = json["email"] as? String,
let givenName = json["givenName"] as? String,
let surname = json["surname"] as? String,
let createdAt = (json["createdAt"] as? String)?.dateFromISO8601Format,
let modifiedAt = (json["modifiedAt"] as? String)?.dateFromISO8601Format,
let status = json["status"] as? String else {
return nil
}
self.href = href
self.username = username
self.email = email
self.givenName = givenName
self.middleName = json["middleName"] as? String
self.surname = surname
self.createdAt = createdAt
self.modifiedAt = modifiedAt
switch status {
case "ENABLED":
self.status = AccountStatus.enabled
case "UNVERIFIED":
self.status = AccountStatus.unverified
case "DISABLED":
self.status = AccountStatus.disabled
default:
return nil
}
if let customDataObject = json["customData"] as? [String: AnyObject],
let customDataData = try? JSONSerialization.data(withJSONObject: customDataObject, options: []),
let customDataString = String(data: customDataData, encoding: String.Encoding.utf8) {
self.customData = customDataString
}
}
}
/// Stormpath Account Status
@objc(SPHAccountStatus)
public enum AccountStatus: Int {
//It's an int for Obj-C compatibility
/// Enabled means that we can login to this account
case enabled
/// Unverified is the same as disabled, but a user can enable it by
/// clicking on the activation email.
case unverified
/// Disabled means that users cannot log in to the account.
case disabled
}
/// Helper extension to make optional chaining easier.
private extension String {
var dateFromISO8601Format: Date? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return dateFormatter.date(from: self)
}
}
|
mit
|
7fd0945e90be467eb3f0f4e9550ec622
| 34.734375 | 137 | 0.633144 | 4.653103 | false | false | false | false |
noppoMan/aws-sdk-swift
|
Sources/Soto/Services/Macie/Macie_Error.swift
|
1
|
2466
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Macie
public struct MacieErrorType: AWSErrorType {
enum Code: String {
case accessDeniedException = "AccessDeniedException"
case internalException = "InternalException"
case invalidInputException = "InvalidInputException"
case limitExceededException = "LimitExceededException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Macie
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// You do not have required permissions to access the requested resource.
public static var accessDeniedException: Self { .init(.accessDeniedException) }
/// Internal server error.
public static var internalException: Self { .init(.internalException) }
/// The request was rejected because an invalid or out-of-range value was supplied for an input parameter.
public static var invalidInputException: Self { .init(.invalidInputException) }
/// The request was rejected because it attempted to create resources beyond the current AWS account limits. The error code describes the limit exceeded.
public static var limitExceededException: Self { .init(.limitExceededException) }
}
extension MacieErrorType: Equatable {
public static func == (lhs: MacieErrorType, rhs: MacieErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension MacieErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
|
apache-2.0
|
dbca91a0866573ea60590ad2b9c990df
| 36.363636 | 157 | 0.663423 | 5.053279 | false | false | false | false |
programersun/HiChongSwift
|
HiChongSwift/WikiesViewController.swift
|
1
|
6971
|
//
// WikiesViewController.swift
// HiChongSwift
//
// Created by eagle on 15/1/4.
// Copyright (c) 2015年 多思科技. All rights reserved.
//
import UIKit
class WikiesViewController: UITableViewController {
var childCate: LCYPetSubTypeChildStyle?
private var infoData: WikiMoreBase?
private var currentType = 2
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationItem.title = childCate?.name
reload()
tableView.backgroundColor = UIColor.LCYTableLightBlue()
addRightButton("详细", action: "rightButtonPressed:")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Actions
func rightButtonPressed(sender: AnyObject) {
performSegueWithIdentifier("wikiWeb", sender: nil)
}
private func reload() {
if let child = childCate {
LCYNetworking.sharedInstance.POSTAndGET(LCYApi.WikiMore, GETParameters: ["cate_id": child.catId], POSTParameters: nil,
success: { [weak self](object) -> Void in
let retrived = WikiMoreBase.modelObjectWithDictionary(object as [NSObject : AnyObject])
if let data = retrived {
self?.infoData = data
self?.tableView.reloadSections(NSIndexSet(index: 2), withRowAnimation: UITableViewRowAnimation.Automatic)
}
},
failure: { [weak self](error) -> Void in
self?.alert("加载失败")
return
})
} else {
alert("信息加载失败")
}
}
@IBAction func segmentedChanged(sender: UISegmentedControl) {
currentType = sender.selectedSegmentIndex + 1
tableView.reloadSections(NSIndexSet(index: 2), withRowAnimation: UITableViewRowAnimation.Automatic)
}
// 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.
if let identifier = segue.identifier {
switch identifier {
case "showArticle":
let destination = segue.destinationViewController as! WikiArticleViewController
var info: WikiMoreData?
for ps in (infoData!.data as! [WikiMoreData]) {
if ps.typeId == "\(currentType)" {
info = ps
break
}
}
if let myData = info {
destination.wikiArticleID = myData.encyId
var data = info
var readInt : Int = 0
var readString : NSString = NSString(format: "%@", myData.encyRead)
readInt = readString.integerValue + 1
data?.encyRead = "\(readInt)"
var indexPath : NSIndexPath = tableView.indexPathForSelectedRow()!
tableView.reloadRowsAtIndexPaths([tableView.indexPathForSelectedRow()!], withRowAnimation: UITableViewRowAnimation.None)
destination.afterCollection = {[weak self] (isadd) -> Void in
var collectString : NSString = NSString(format: "%@", data!.encyCollect)
var collectInt : Int = collectString.integerValue
if(!isadd)
{
data?.encyCollect = "\(collectInt + 1)"
self?.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
else
{
data?.encyCollect = "\(collectInt - 1)"
self?.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
}
}
case "wikiWeb":
let destination = segue.destinationViewController as! WikiWebViewController
destination.wikiTitle = childCate?.name
destination.wikiID = childCate?.catId
default:
break
}
}
}
// MARK: - Outlets
// MARK: - TableView
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 1
case 2:
if infoData != nil {
return 1
} else {
return 0
}
default:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
switch indexPath.section {
case 0:
cell = tableView.dequeueReusableCellWithIdentifier(WikiesHeadCell.identifier()) as! UITableViewCell
let cell = cell as! WikiesHeadCell
cell.imagePath = childCate?.headImg.toAbsolutePath()
case 1:
cell = tableView.dequeueReusableCellWithIdentifier(WikiesMidCell.identifier()) as! UITableViewCell
case 2:
cell = tableView.dequeueReusableCellWithIdentifier(WikiInfoCell.identifier()) as! UITableViewCell
let cell = cell as! WikiInfoCell
var info: WikiMoreData?
for ps in (infoData!.data as! [WikiMoreData]) {
if ps.typeId == "\(currentType)" {
info = ps
break
}
}
if let myData = info {
cell.icyTitle = myData.title
cell.keyWord = myData.keyword
cell.readCount = myData.encyRead
cell.collectCount = myData.encyCollect
cell.imagePath = myData.headImg.toAbsolutePath()
}
default:
break
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.section {
case 0:
return 80.0
case 1:
return 44.0
case 2:
return 65.0
default:
return 0.0
}
}
}
|
apache-2.0
|
e88b4fea63f9b9339f2b47d0e4236581
| 35.319372 | 140 | 0.543751 | 5.780833 | false | false | false | false |
sugawaray/tools
|
tools/Term.swift
|
1
|
2414
|
//
// Term.swift
// tools
//
// Created by Yutaka Sugawara on 2016/09/11.
// Copyright © 2016 Yutaka Sugawara. All rights reserved.
//
import Foundation
func getlastline(_ txt:String) -> String? {
if txt.hasSuffix("\n") {
let rs = txt.characters.reversed();
var s = ""
var fnd = false
var i = rs.startIndex
while true {
let bi = i.base
let be = txt.characters.index(bi, offsetBy: 2, limitedBy: txt.characters.endIndex)
if be != nil {
s = txt.substring(with: bi..<be!)
if s == "$ " {
fnd = true
s = txt.substring(
with: txt.characters.index(bi, offsetBy: 2)..<txt.characters.index(txt.characters.endIndex, offsetBy: -1))
break;
}
}
if i == rs.endIndex {
break;
}
i = rs.index(i, offsetBy: 1)
}
if fnd {
return s
} else {
return String(txt.characters.dropLast())
}
} else {
return nil
}
}
class Termtxt {
func append(_ v:String) -> Void {
s += v
}
func get() -> String {
return s + input
}
func getinput() -> String {
return input
}
func replace(_ rng:NSRange, _ v:String) -> Bool {
let l = s.characters.count
let atend = rng.location >= l
if (atend) {
let be = rng.location - l
var en = be + rng.length
if (en > input.characters.count) {
en = input.characters.count
}
let beit = input.index(input.startIndex, offsetBy: be)
let enit = input.index(input.startIndex, offsetBy: en)
let r: Range<String.Index> = Range<String.Index>(uncheckedBounds: (lower: beit, upper: enit))
input.replaceSubrange(r, with: v)
} else {
let be = s.index(s.startIndex, offsetBy: rng.location)
let en = s.index(s.startIndex, offsetBy: rng.location + rng.length)
let r: Range<String.Index> = Range<String.Index>(uncheckedBounds: (lower: be, upper: en))
s.replaceSubrange(r, with: v)
}
return true
}
func fix() {
s += input
input = ""
}
var s = ""
var input = ""
}
|
gpl-2.0
|
32090ed086ac5cf6621115da4fa99924
| 26.11236 | 130 | 0.486946 | 4.021667 | false | false | false | false |
Sharelink/Bahamut
|
Bahamut/MainNavigationController.swift
|
1
|
9065
|
//
// MainNavigationController.swift
// Bahamut
//
// Created by AlexChow on 15/7/29.
// Copyright (c) 2015年 GStudio. All rights reserved.
//
import UIKit
@objc
class MainNavigationController: UINavigationController,HandleBahamutCmdDelegate
{
struct SegueIdentifier
{
static let ShowSignView = "Show Sign View"
static let ShowMainView = "Show Main Navigation"
}
override func viewDidLoad() {
super.viewDidLoad()
ServiceContainer.instance.initContainer("Sharelink", services: ServiceConfig.Services)
setWaitingScreen()
BahamutRFKit.sharedInstance.addObserver(self, selector: #selector(MainNavigationController.onAppTokenInvalid(_:)), name: BahamutRFKit.onTokenInvalidated, object: nil)
ChicagoClient.sharedInstance.addObserver(self, selector: #selector(MainNavigationController.onAppTokenInvalid(_:)), name: AppTokenInvalided, object: nil)
ChicagoClient.sharedInstance.addObserver(self, selector: #selector(MainNavigationController.onOtherDeviceLogin(_:)), name: OtherDeviceLoginChicagoServer, object: nil)
}
private var launchScr:UIView!
private func setWaitingScreen()
{
self.view.backgroundColor = UIColor.whiteColor()
launchScr = MainNavigationController.getLaunchScreen(self.view.bounds)
self.view.addSubview(launchScr)
}
static func getLaunchScreen(frame:CGRect) -> UIView
{
let launchScr = Sharelink.mainBundle().loadNibNamed("LaunchScreen", owner: nil, options: nil).filter{$0 is UIView}.first as! UIView
launchScr.frame = frame
if let indicator = launchScr.viewWithTag(1) as? UIActivityIndicatorView
{
indicator.hidden = false
}
if let mottoLabel = launchScr.viewWithTag(2) as? UILabel
{
mottoLabel.text = SharelinkConfig.SharelinkMotto
mottoLabel.hidden = false
}
return launchScr
}
func deInitController(){
ServiceContainer.instance.removeObserver(self)
ChicagoClient.sharedInstance.removeObserver(self)
BahamutRFKit.sharedInstance.removeObserver(self)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
go()
}
func allServicesReady(_:AnyObject)
{
ServiceContainer.instance.removeObserver(self)
if let _ = self.presentedViewController
{
let notiService = ServiceContainer.getService(NotificationService)
notiService.setMute(false)
notiService.setVibration(true)
MainNavigationController.start()
}else
{
showMainView()
}
}
func initServicesFailed(a:AnyObject)
{
ServiceContainer.instance.removeObserver(self)
let reason = a.userInfo![InitServiceFailedReason] as! String
let action = UIAlertAction(title: "OK".localizedString(), style: .Cancel) { (action) -> Void in
MainNavigationController.start()
}
self.showAlert(nil, msg: reason, actions: [action])
}
func onOtherDeviceLogin(_:AnyObject)
{
let alert = UIAlertController(title: nil, message: "OTHER_DEVICE_HAD_LOGIN".localizedString() , preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "I_SEE".localizedString(), style: .Default, handler: { (action) -> Void in
ServiceContainer.instance.userLogout()
MainNavigationController.start()
}))
self.showAlert(alert)
}
func onAppTokenInvalid(_:AnyObject)
{
let alert = UIAlertController(title: nil, message: "USER_APP_TOKEN_TIMEOUT".localizedString() , preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "I_SEE".localizedString(), style: .Default, handler: { (action) -> Void in
ServiceContainer.instance.userLogout()
MainNavigationController.start()
}))
self.showAlert(alert)
}
private func go()
{
ServiceContainer.instance.addObserver(self, selector: #selector(MainNavigationController.allServicesReady(_:)), name: ServiceContainer.OnAllServicesReady, object: nil)
ServiceContainer.instance.addObserver(self, selector: #selector(MainNavigationController.initServicesFailed(_:)), name: ServiceContainer.OnServiceInitFailed, object: nil)
if UserSetting.isUserLogined
{
if ServiceContainer.isAllServiceReady
{
ServiceContainer.instance.removeObserver(self)
showMainView()
}else
{
ServiceContainer.instance.userLogin(UserSetting.userId)
}
}else
{
showSignView()
}
}
let screenWaitTimeInterval = 0.3
private func showSignView()
{
NSTimer.scheduledTimerWithTimeInterval(screenWaitTimeInterval, target: self, selector: #selector(MainNavigationController.waitTimeShowSignView(_:)), userInfo: nil, repeats: false)
}
func waitTimeShowSignView(_:AnyObject?)
{
performSegueWithIdentifier(SegueIdentifier.ShowSignView, sender: self)
}
private func showMainView()
{
NSTimer.scheduledTimerWithTimeInterval(screenWaitTimeInterval, target: self, selector: #selector(MainNavigationController.waitTimeShowMainView(_:)), userInfo: nil, repeats: false)
}
func waitTimeShowMainView(_:AnyObject?)
{
BahamutCmdManager.sharedInstance.registHandler(self)
self.performSegueWithIdentifier(SegueIdentifier.ShowMainView, sender: self)
if self.launchScr != nil
{
self.launchScr.removeFromSuperview()
}
}
//MARK: handle sharelinkMessage
let linkMeParameterCount = 3
func linkMe(method: String, args: [String],object:AnyObject?)
{
if args.count < linkMeParameterCount
{
self.showAlert("Sharelink", msg: "UNKNOW_SHARELINK_CMD".localizedString() )
return
}
let sharelinkerId = args[0]
let sharelinkerNick = args[1]
let expriedAt = args[2].dateTimeOfString
if expriedAt.timeIntervalSince1970 < NSDate().timeIntervalSince1970
{
self.showAlert("Sharelink", msg: "SHARELINK_CMD_TIMEOUT".localizedString())
return
}
let userService = ServiceContainer.getService(UserService)
if userService.isSharelinkerLinked(sharelinkerId)
{
if let navc = UIApplication.currentNavigationController
{
userService.showUserProfileViewController(navc, userId: sharelinkerId)
}
}else
{
let title = "SHARELINK".localizedString()
let msg = String(format: "SEND_LINK_REQUEST_TO".localizedString(),sharelinkerNick)
let alertController = UIAlertController(title: title, message: msg, preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler({ (textfield) -> Void in
textfield.placeholder = "YOUR_SHOW_NAME".localizedString()
textfield.borderStyle = .None
textfield.text = userService.myUserModel.nickName
})
let yes = UIAlertAction(title: "YES".localizedString() , style: .Default, handler: { (action) -> Void in
var askNick = alertController.textFields?[0].text ?? ""
if String.isNullOrEmpty(askNick)
{
askNick = userService.myUserModel.nickName
}
userService.askSharelinkForLink(sharelinkerId, askNick:askNick, callback: { (isSuc) -> Void in
if isSuc
{
self.showAlert("Sharelink" ,msg:"LINK_REQUEST_SENDED".localizedString() )
}
})
})
let no = UIAlertAction(title: "NO".localizedString(), style: .Cancel,handler:nil)
alertController.addAction(no)
alertController.addAction(yes)
self.showAlert(alertController)
}
}
func handleBahamutCmd(method: String, args: [String],object:AnyObject?) {
switch method
{
case "linkMe":linkMe(method, args: args, object: object)
default:break
}
}
private static func instanceFromStoryBoard() -> MainNavigationController
{
return instanceFromStoryBoard("SharelinkMain", identifier: "mainNavigationController",bundle: Sharelink.mainBundle()) as! MainNavigationController
}
static func start()
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let mnc = UIApplication.sharedApplication().delegate?.window!?.rootViewController as? MainNavigationController{
mnc.deInitController()
}
UIApplication.sharedApplication().delegate?.window!?.rootViewController = instanceFromStoryBoard()
})
}
}
|
mit
|
30b3c83fa5d5a5cc746855f3b11f2dab
| 37.896996 | 187 | 0.641178 | 5.046214 | false | false | false | false |
a2/arex-7
|
ArexKit/Models/Pistachio/MessagePackValueTransformers.swift
|
1
|
10898
|
import Foundation
import MessagePack
import Monocle
import Pistachio
import Result
import ValueTransformer
public enum MessagePackValueTransformersError: ErrorType {
case InvalidType(String)
case IncorrectExtendedType
case ExpectedStringKey
}
public struct MessagePackValueTransformers {
public static let bool: ReversibleValueTransformer<Bool, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .Success(.Bool(value))
}, reverseTransformClosure: { value in
if let value = value.boolValue {
return .Success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Bool"))
}
})
public static func int<S: SignedIntegerType>() -> ReversibleValueTransformer<S, MessagePackValue, ErrorType> {
return ReversibleValueTransformer(transformClosure: { value in
return .Success(.Int(numericCast(value)))
}, reverseTransformClosure: { value in
if let value = value.integerValue {
return .Success(numericCast(value))
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Int"))
}
})
}
public static func uint<U: UnsignedIntegerType>() -> ReversibleValueTransformer<U, MessagePackValue, ErrorType> {
return ReversibleValueTransformer(transformClosure: { value in
return .Success(.UInt(numericCast(value)))
}, reverseTransformClosure: { value in
if let value = value.unsignedIntegerValue {
return .Success(numericCast(value))
} else {
return .failure(MessagePackValueTransformersError.InvalidType("UInt"))
}
})
}
public static let float: ReversibleValueTransformer<Float32, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .Success(.Float(value))
}, reverseTransformClosure: { value in
if let value = value.floatValue {
return .Success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Float"))
}
})
public static let double: ReversibleValueTransformer<Float64, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .Success(.Double(value))
}, reverseTransformClosure: { value in
if let value = value.doubleValue {
return .Success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Double"))
}
})
public static let string: ReversibleValueTransformer<String, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .Success(.String(value))
}, reverseTransformClosure: { value in
if let value = value.stringValue {
return .Success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("String"))
}
})
public static let binary: ReversibleValueTransformer<Data, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .Success(.Binary(value))
}, reverseTransformClosure: { value in
if let value = value.dataValue {
return .Success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Binary"))
}
})
public static let array: ReversibleValueTransformer<[MessagePackValue], MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .Success(.Array(value))
}, reverseTransformClosure: { value in
if let value = value.arrayValue {
return .Success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Array"))
}
})
public static let map: ReversibleValueTransformer<[MessagePackValue : MessagePackValue], MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .Success(.Map(value))
}, reverseTransformClosure: { value in
if let value = value.dictionaryValue {
return .Success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Map"))
}
})
public static func extended(type: Int8) -> ReversibleValueTransformer<Data, MessagePackValue, ErrorType> {
return ReversibleValueTransformer(transformClosure: { value in
return .Success(.Extended(type, value))
}, reverseTransformClosure: { value in
if let (decodedType, data) = value.extendedValue {
if decodedType == type {
return .Success(data)
} else {
return .failure(MessagePackValueTransformersError.IncorrectExtendedType)
}
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Extended"))
}
})
}
}
public func messagePackBool<A>(lens: Lens<A, Bool>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.bool)
}
public func messagePackBool<A>(lens: Lens<A, Bool?>, defaultTransformedValue: MessagePackValue = .Bool(false)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.bool, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackInt<A, S: SignedIntegerType>(lens: Lens<A, S>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.int())
}
public func messagePackInt<A, S: SignedIntegerType>(lens: Lens<A, S?>, defaultTransformedValue: MessagePackValue = .Int(0)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.int(), defaultTransformedValue: defaultTransformedValue))
}
public func messagePackUInt<A, U: UnsignedIntegerType>(lens: Lens<A, U>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.uint())
}
public func messagePackUInt<A, U: UnsignedIntegerType>(lens: Lens<A, U?>, defaultTransformedValue: MessagePackValue = .UInt(0)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.uint(), defaultTransformedValue: defaultTransformedValue))
}
public func messagePackFloat<A>(lens: Lens<A, Float32>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.float)
}
public func messagePackFloat<A>(lens: Lens<A, Float32?>, defaultTransformedValue: MessagePackValue = .Float(0)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.float, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackDouble<A>(lens: Lens<A, Float64>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.double)
}
public func messagePackDouble<A>(lens: Lens<A, Float64?>, defaultTransformedValue: MessagePackValue = .Double(0)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.double, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackString<A>(lens: Lens<A, String>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.string)
}
public func messagePackString<A>(lens: Lens<A, String?>, defaultTransformedValue: MessagePackValue = .String("")) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.string, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackBinary<A>(lens: Lens<A, Data>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.binary)
}
public func messagePackBinary<A>(lens: Lens<A, Data?>, defaultTransformedValue: MessagePackValue = .Binary([])) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.binary, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackArray<A, T: AdapterType where T.TransformedValueType == MessagePackValue, T.ErrorType == ErrorType>(lens: Lens<A, [T.ValueType]>) -> (adapter: T) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter in
return map(lens, lift(adapter) >>> MessagePackValueTransformers.array)
}
}
public func messagePackArray<A, T: AdapterType where T.TransformedValueType == MessagePackValue, T.ErrorType == ErrorType>(lens: Lens<A, [T.ValueType]?>, defaultTransformedValue: MessagePackValue = .Nil) -> (adapter: T) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter in
return map(lens, lift(lift(adapter) >>> MessagePackValueTransformers.array, defaultTransformedValue: defaultTransformedValue))
}
}
public func messagePackMap<A, T: AdapterType where T.TransformedValueType == MessagePackValue, T.ErrorType == ErrorType>(lens: Lens<A, T.ValueType>) -> (adapter: T) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter in
return map(lens, adapter)
}
}
public func messagePackMap<A, T: AdapterType where T.TransformedValueType == MessagePackValue, T.ErrorType == ErrorType>(lens: Lens<A, T.ValueType?>, defaultTransformedValue: MessagePackValue = .Nil) -> (adapter: T) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter in
return map(lens, lift(adapter, defaultTransformedValue: defaultTransformedValue))
}
}
public func messagePackExtended<A, T: AdapterType where T.TransformedValueType == Data, T.ErrorType == ErrorType>(lens: Lens<A, T.ValueType>) -> (adapter: T, type: Int8) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter, type in
return map(map(lens, adapter), MessagePackValueTransformers.extended(type))
}
}
public func messagePackExtended<A, T: AdapterType where T.TransformedValueType == Data, T.ErrorType == ErrorType>(lens: Lens<A, T.ValueType?>, defaultTransformedValue: Data = Data()) -> (adapter: T, type: Int8) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter, type in
return map(map(lens, lift(adapter, defaultTransformedValue: defaultTransformedValue)), MessagePackValueTransformers.extended(type))
}
}
|
mit
|
454d82bd3c985fd5408e94a9baaab90e
| 49.453704 | 288 | 0.711415 | 4.679261 | false | false | false | false |
yunhan0/ChineseChess
|
ChineseChess/Model/Pieces/Rook.swift
|
1
|
2422
|
//
// Rook.swift
// ChineseChess
//
// Created by Yunhan Li on 5/15/17.
// Copyright © 2017 Yunhan Li. All rights reserved.
//
import Foundation
class Rook : Piece {
private var obstacleNumber: Int = 0
override func nextPossibleMoves(boardStates: [[Piece?]]) -> [Vector2] {
var ret: [Vector2] = []
// The same row
obstacleNumber = 0
for _x in stride(from: position.x - 1, through: 0, by: -1) {
if (obstacleNumber == 1) {
break
}
if isValidMove(Vector2(x: _x, y: position.y), boardStates) {
ret.append(Vector2(x: _x, y: position.y))
}
}
obstacleNumber = 0
for _x in stride(from: position.x + 1, to: Board.rows, by: +1) {
if (obstacleNumber == 1) {
break
}
if isValidMove(Vector2(x: _x, y: position.y), boardStates) {
ret.append(Vector2(x: _x, y: position.y))
}
}
// The same column
obstacleNumber = 0
for _y in stride(from: position.y - 1, through: 0, by: -1) {
if (obstacleNumber == 1) {
break
}
if isValidMove(Vector2(x: position.x, y: _y), boardStates) {
ret.append(Vector2(x: position.x, y: _y))
}
}
obstacleNumber = 0
for _y in stride(from: position.y + 1, to: Board.columns, by: +1) {
if (obstacleNumber == 1) {
break
}
if isValidMove(Vector2(x: position.x, y: _y), boardStates) {
ret.append(Vector2(x: position.x, y: _y))
}
}
return ret
}
override func isValidMove(_ move: Vector2, _ boardStates: [[Piece?]]) -> Bool {
if Board.isOutOfBoard(move) {
return false
}
if (obstacleNumber >= 1) {
return false
}
if let nextstate = boardStates[move.x][move.y] {
obstacleNumber += 1
if nextstate.owner == self.owner {
return false
} else {
return true
}
}
return true
}
}
|
mit
|
bc6ace911c52ad1986026a702f667976
| 25.032258 | 83 | 0.434944 | 4.195841 | false | false | false | false |
kamimura/swift-stdio
|
stdio/stdio.swift
|
1
|
1227
|
//
// stdio.swift
// stdio
//
// Created by kamimura on 8/21/14.
// Copyright (c) 2014 kamimura. All rights reserved.
//
import Foundation
// 標準入力(STDIN)から読み込む
func input(msg:String = "") -> String {
print(msg)
var in_fh = NSFileHandle.fileHandleWithStandardInput()
var data = in_fh.availableData
in_fh.closeFile()
var s = NSString(data: data, encoding: NSUTF8StringEncoding)
s = s?.substringToIndex(s!.length - 1)
return s!
}
func read(path:String) -> String? {
var fh = NSFileHandle(forReadingAtPath: path)
let data = fh?.readDataToEndOfFile()
if fh == nil {
error("file(\(path)) can't open.")
}
fh?.closeFile()
return NSString(data: data!, encoding: NSUTF8StringEncoding)
}
func print(s:String, path:String, end:String = "\n") {
(s + end).writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
}
func error(msg:String) {
let stderr = NSFileHandle.fileHandleWithStandardError()
stderr.writeData((msg + "\n").dataUsingEncoding(NSUTF8StringEncoding)!)
exit(1)
}
// コマンドライン引数
let argv:[String] = NSProcessInfo.processInfo().arguments.map({(x:AnyObject) -> String in x as String})
|
mit
|
da08f0606e0bb8e42e14ae96fdec7bc5
| 26.674419 | 103 | 0.672834 | 3.466472 | false | false | false | false |
MadAppGang/SmartLog
|
iOS/Pods/CoreStore/Sources/SchemaHistory.swift
|
2
|
10395
|
//
// SchemaHistory.swift
// CoreStore
//
// Copyright © 2017 John Rommel Estropia
//
// 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 CoreData
import Foundation
// MARK: - SchemaHistory
/**
The `SchemaHistory` encapsulates multiple `DynamicSchema` across multiple model versions. It contains all model history and is used by the `DataStack` to
*/
public final class SchemaHistory: ExpressibleByArrayLiteral {
/**
The version string for the current model version. The `DataStack` will try to migrate all `StorageInterface`s added to itself to this version, following the version steps provided by the `migrationChain`.
*/
public let currentModelVersion: ModelVersion
/**
The schema for the current model version. The `DataStack` will try to migrate all `StorageInterface`s added to itself to this version, following the version steps provided by the `migrationChain`.
*/
public var currentSchema: DynamicSchema {
return self.schema(for: self.currentModelVersion)!
}
/**
The version string for the current model version. The `DataStack` will try to migrate all `StorageInterface`s added to itself to this version, following the version steps provided by the `migrationChain`.
*/
public let migrationChain: MigrationChain
/**
Convenience initializer for a `SchemaHistory` created from a single xcdatamodeld file.
- parameter xcodeDataModeld: a tuple returned from the `XcodeDataModelSchema.from(modelName:bundle:migrationChain:)` method.
- parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack.
*/
public convenience init(_ xcodeDataModeld: (allSchema: [XcodeDataModelSchema], currentModelVersion: ModelVersion), migrationChain: MigrationChain = nil) {
self.init(
allSchema: xcodeDataModeld.allSchema,
migrationChain: migrationChain,
exactCurrentModelVersion: xcodeDataModeld.currentModelVersion
)
}
/**
Initializes a `SchemaHistory` with a list of `DynamicSchema` and a `MigrationChain` to describe the order of progressive migrations.
- parameter schema: a `DynamicSchema` that represents a model version
- parameter otherSchema: a list of `DynamicSchema` that represent other model versions
- parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack.
- parameter exactCurrentModelVersion: an optional string to explicitly select the current model version string. This is useful if the `DataStack` should load a non-latest model version (usually to prepare data before migration). If not provided, the current model version will be computed from the `MigrationChain`.
*/
public convenience init(_ schema: DynamicSchema, _ otherSchema: DynamicSchema..., migrationChain: MigrationChain = nil, exactCurrentModelVersion: String? = nil) {
self.init(
allSchema: [schema] + otherSchema,
migrationChain: migrationChain,
exactCurrentModelVersion: exactCurrentModelVersion
)
}
/**
Initializes a `SchemaHistory` with a list of `DynamicSchema` and a `MigrationChain` to describe the order of progressive migrations.
- parameter allSchema: a list of `DynamicSchema` that represent model versions
- parameter migrationChain: the `MigrationChain` that indicates the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack.
- parameter exactCurrentModelVersion: an optional string to explicitly select the current model version string. This is useful if the `DataStack` should load a non-latest model version (usually to prepare data before migration). If not provided, the current model version will be computed from the `MigrationChain`.
*/
public required init(allSchema: [DynamicSchema], migrationChain: MigrationChain = nil, exactCurrentModelVersion: String? = nil) {
if allSchema.isEmpty {
CoreStore.abort("The \"allSchema\" argument of the \(cs_typeName(SchemaHistory.self)) initializer cannot be empty.")
}
CoreStore.assert(
migrationChain.isValid,
"Invalid migration chain passed to the \(cs_typeName(SchemaHistory.self)). Check that the model versions' order are correct and that no repetitions or ambiguities exist."
)
var schemaByVersion: [ModelVersion: DynamicSchema] = [:]
for schema in allSchema {
let modelVersion = schema.modelVersion
CoreStore.assert(
schemaByVersion[modelVersion] == nil,
"Multiple model schema found for model version \"\(modelVersion)\"."
)
schemaByVersion[modelVersion] = schema
}
let modelVersions = Set(schemaByVersion.keys)
let currentModelVersion: ModelVersion
if let exactCurrentModelVersion = exactCurrentModelVersion {
if !migrationChain.isEmpty && !migrationChain.contains(exactCurrentModelVersion) {
CoreStore.abort("An \"exactCurrentModelVersion\" argument was provided to \(cs_typeName(SchemaHistory.self)) initializer but a matching schema could not be found from the provided \(cs_typeName(MigrationChain.self)).")
}
if schemaByVersion[exactCurrentModelVersion] == nil {
CoreStore.abort("An \"exactCurrentModelVersion\" argument was provided to \(cs_typeName(SchemaHistory.self)) initializer but a matching schema could not be found from the \(cs_typeName(DynamicSchema.self)) list.")
}
currentModelVersion = exactCurrentModelVersion
}
else if migrationChain.isEmpty && schemaByVersion.count == 1 {
currentModelVersion = schemaByVersion.keys.first!
}
else {
let candidateVersions = modelVersions.intersection(migrationChain.leafVersions)
switch candidateVersions.count {
case 0:
CoreStore.abort("None of the \(cs_typeName(MigrationChain.self)) leaf versions provided to the \(cs_typeName(SchemaHistory.self)) initializer matches any scheme from the \(cs_typeName(DynamicSchema.self)) list.")
case 1:
currentModelVersion = candidateVersions.first!
default:
CoreStore.abort("Could not resolve the \(cs_typeName(SchemaHistory.self)) current model version because the \(cs_typeName(MigrationChain.self)) have ambiguous leaf versions: \(candidateVersions)")
}
}
self.schemaByVersion = schemaByVersion
self.migrationChain = migrationChain
self.currentModelVersion = currentModelVersion
self.rawModel = schemaByVersion[currentModelVersion]!.rawModel()
}
// MARK: ExpressibleByArrayLiteral
public typealias Element = DynamicSchema
public convenience init(arrayLiteral elements: DynamicSchema...) {
self.init(
allSchema: elements,
migrationChain: MigrationChain(elements.map({ $0.modelVersion })),
exactCurrentModelVersion: nil
)
}
// MARK: Internal
internal let schemaByVersion: [ModelVersion: DynamicSchema]
internal let rawModel: NSManagedObjectModel
internal private(set) lazy var entityDescriptionsByEntityIdentifier: [EntityIdentifier: NSEntityDescription] = cs_lazy { [unowned self] in
var mapping: [EntityIdentifier: NSEntityDescription] = [:]
self.rawModel.entities.forEach { (entityDescription) in
let entityIdentifier = EntityIdentifier(entityDescription)
mapping[entityIdentifier] = entityDescription
}
return mapping
}
internal func rawModel(for modelVersion: ModelVersion) -> NSManagedObjectModel? {
if modelVersion == self.currentModelVersion {
return self.rawModel
}
return self.schemaByVersion[modelVersion]?.rawModel()
}
internal func schema(for modelVersion: ModelVersion) -> DynamicSchema? {
return self.schemaByVersion[modelVersion]
}
internal func schema(for storeMetadata: [String: Any]) -> DynamicSchema? {
guard let modelHashes = storeMetadata[NSStoreModelVersionHashesKey] as! [String: Data]? else {
return nil
}
for (_, schema) in self.schemaByVersion {
let rawModel = schema.rawModel()
if modelHashes == rawModel.entityVersionHashesByName {
return schema
}
}
return nil
}
internal func mergedModels() -> [NSManagedObjectModel] {
return self.schemaByVersion.values.map({ $0.rawModel() })
}
}
|
mit
|
9884a3001aa45bac4705da67db13a326
| 46.898618 | 320 | 0.681258 | 5.343959 | false | false | false | false |
Bruno-Furtado/holt_winters
|
HoltWinters/Classes/Helper/String+ToDouble.swift
|
1
|
859
|
//
// String+ToDouble.swift
// HoltWinters
//
// Created by Bruno Tortato Furtado on 04/05/16.
// Copyright © 2016 Bruno Tortato Furtado. All rights reserved.
//
import Foundation
extension String {
func toNumber() -> NSNumber {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.groupingSeparator = "."
formatter.decimalSeparator = ","
if let result = formatter.numberFromString(self) {
return result
}
formatter.groupingSeparator = ","
formatter.decimalSeparator = "."
if let result = formatter.numberFromString(self) {
return result
}
print("[WARNING] \(#file):\(#function):\(#line) - convert string to number with failure")
return 0
}
}
|
mit
|
480c4fc041357419ca5d9f32c51676e3
| 23.542857 | 97 | 0.582751 | 5.017544 | false | false | false | false |
codingTheHole/BuildingAppleWatchProjectsBook
|
Xcode Projects by Chapter/5086_Code_Ch05_OnQ/On Q completed/On Q WatchKit Extension/WatchData.swift
|
1
|
2018
|
//
// WatchData.swift
// On Q
//
// Created by Stuart Grimshaw on 17/10/15.
// Copyright © 2015 Stuart Grimshaw. All rights reserved.
//
import WatchKit
let kPromptsArchive = "promptsArchive"
class WatchDataManager {
static let sharedManager = WatchDataManager()
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentationDirectory, inDomains: .UserDomainMask).first!
static let PromptsArchive = DocumentsDirectory.URLByAppendingPathComponent(kPromptsArchive)
private var currentPromptIndex = -1
private var prompts: [Prompt] = []
private init(){
if let storedPrompts = NSUserDefaults.standardUserDefaults().objectForKey(kPromptsKey) as! [Prompt]? {
self.prompts = storedPrompts
}
}
func nextPrompt() -> Prompt? {
if currentPromptIndex >= prompts.count - 1 {
return nil
} else {
currentPromptIndex += 1
return prompts[currentPromptIndex]
}
}
func previousPrompt() -> Prompt? {
if currentPromptIndex <= 0 {
return nil
} else {
currentPromptIndex -= 1
return prompts[currentPromptIndex]
}
}
func isFirstPrompt() -> Bool {
return currentPromptIndex <= 0
}
func isLastPrompt() -> Bool {
return currentPromptIndex >= prompts.count - 1
}
func lastSelectedPrompt() -> Prompt? {
if currentPromptIndex >= 0 && currentPromptIndex < prompts.count {
return prompts[currentPromptIndex]
} else {
return nil
}
}
func lastSelectedPromptIndex() -> Int {
return currentPromptIndex
}
func promptsCount() -> Int {
return prompts.count
}
func updatePrompts(prompts: [Prompt]) {
NSUserDefaults.standardUserDefaults().setObject(prompts, forKey: kPromptsKey)
self.prompts = prompts
WKInterfaceDevice.currentDevice().playHaptic(.Success)
}
func reset() {
currentPromptIndex = -1
}
}
|
cc0-1.0
|
bdb6bea8d1befd778e6395219928c24a
| 27.408451 | 128 | 0.638076 | 4.679814 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/WordPressTest/Extensions/UIView+ExistingConstraints.swift
|
2
|
2185
|
import XCTest
@testable import WordPress
class UIView_ExistingConstraints: XCTestCase {
/// Tests that constraint(for:withRelation:) returns an existing constraint if there's one.
///
func testConstraintReturnsExistingConstraint() {
let parentView = UIView()
let childView = UIView()
parentView.addSubview(childView)
let expectedConstraint = childView.heightAnchor.constraint(equalToConstant: 10)
expectedConstraint.isActive = true
XCTAssertEqual(childView.constraint(for: .height, withRelation: .equal), expectedConstraint)
}
/// Tests that constraint(for:withRelation:) returns `nil` when there's no existing constraint.
///
func testConstraintReturnsNilWhenNoConstraintExists() {
let parentView = UIView()
let childView = UIView()
parentView.addSubview(childView)
XCTAssertNil(childView.constraint(for: .height, withRelation: .equal))
}
/// Tests that updateConstraint(for:withRelation:constant:active) works.
///
func testUpdateConstraintWorks() {
let parentView = UIView()
let childView = UIView()
parentView.addSubview(childView)
let expectedConstraint = childView.heightAnchor.constraint(equalToConstant: 10)
expectedConstraint.isActive = true
XCTAssertEqual(expectedConstraint.constant, 10)
childView.updateConstraint(for: .height, withRelation: .equal, setConstant: 20, setActive: true)
XCTAssertEqual(childView.constraint(for: .height, withRelation: .equal)!.constant, 20)
}
/// Tests that updateConstraint(for:withRelation:constant:active) works even if no previous constraint exists.
///
func testUpdateConstraintWorksEvenIfNoPreviousConstraintExists() {
let parentView = UIView()
let childView = UIView()
parentView.addSubview(childView)
XCTAssertNil(childView.constraint(for: .height, withRelation: .equal))
childView.updateConstraint(for: .height, withRelation: .equal, setConstant: 20, setActive: true)
XCTAssertEqual(childView.constraint(for: .height, withRelation: .equal)!.constant, 20)
}
}
|
gpl-2.0
|
a05d09594bd07626dd2589528c349597
| 33.68254 | 114 | 0.705263 | 4.977221 | false | true | false | false |
ewhitley/CDAKit
|
CDAKit/health-data-standards/lib/import/cda/cda_medication_importer.swift
|
1
|
9215
|
//
// allergy_importer.swift
// CDAKit
//
// Created by Eric Whitley on 1/13/16.
// Copyright © 2016 Eric Whitley. All rights reserved.
//
import Foundation
import Fuzi
//TODO: Coded Product Name, Free Text Product Name, Coded Brand Name and Free Text Brand name need to be pulled out separatelty This would mean overriding extract_codes
//TODO: Patient Instructions needs to be implemented. Will likely be a reference to the narrative section
//TODO: Couldn't find an example medication reaction. Isn't clear to me how it should be implemented from the specs, so reaction is not implemented.
//TODO: Couldn't find an example dose indicator. Isn't clear to me how it should be implemented from the specs, so dose indicator is not implemented.
//TODO: Fill Status is not implemented. Couldn't figure out which entryRelationship it should be nested in
class CDAKImport_CDA_MedicationImporter: CDAKImport_CDA_SectionImporter {
var type_of_med_xpath: String? = "./cda:entryRelationship[@typeCode='SUBJ']/cda:observation[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.8.1']/cda:code"
// var indication_xpath = "./cda:entryRelationship[@typeCode='RSON']/cda:observation[cda:templateId/@root='2.16.840.1.113883.10.20.1.28']/cda:code"
var indication_xpath = "./cda:entryRelationship[@typeCode='RSON']/cda:observation[cda:templateId/@root='2.16.840.1.113883.10.20.1.28']"
var vehicle_xpath = "cda:participant/cda:participantRole[cda:code/@code='412307009' and cda:code/@codeSystem='2.16.840.1.113883.6.96']/cda:playingEntity/cda:code"
var fill_number_xpath = "./cda:entryRelationship[@typeCode='COMP']/cda:sequenceNumber/@value"
var precondition_xpath = "./cda:precondition[@typeCode='PRCN' and cda:templateId/@root='2.16.840.1.113883.10.20.22.4.25']/cda:criterion"
var reaction_xpath = "./cda:entryRelationship[@typeCode='MFST']/cda:observation[cda:templateId/@root='2.16.840.1.113883.10.20.1.54']"
var severity_xpath = "./cda:entryRelationship[@typeCode='SUBJ']/cda:observation[cda:templateId/@root='2.16.840.1.113883.10.20.1.55']"
override init(entry_finder: CDAKImport_CDA_EntryFinder = CDAKImport_CDA_EntryFinder(entry_xpath: "//cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.112']/cda:entry/cda:substanceAdministration")) {
super.init(entry_finder: entry_finder)
code_xpath = "./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code"
description_xpath = "./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code/cda:originalText/cda:reference[@value]"
entry_class = CDAKMedication.self
}
override func create_entry(entry_element: XMLElement, nrh: CDAKImport_CDA_NarrativeReferenceHandler = CDAKImport_CDA_NarrativeReferenceHandler()) -> CDAKMedication? {
if let medication = super.create_entry(entry_element, nrh: nrh) as? CDAKMedication {
extract_administration_timing(entry_element, medication: medication)
medication.route.addCodes(CDAKImport_CDA_SectionImporter.extract_code(entry_element, code_xpath: "./cda:routeCode"))
if let a_dose = extract_scalar(entry_element, scalar_xpath: "./cda:doseQuantity") {
medication.dose = a_dose
}
if let a_rate = extract_scalar(entry_element, scalar_xpath: "./cda:rateQuantity") {
medication.rate = a_rate
}
medication.anatomical_approach.addCodes(CDAKImport_CDA_SectionImporter.extract_code(entry_element, code_xpath: "./cda:approachSiteCode", code_system: "SNOMED-CT"))
extract_dose_restriction(entry_element, medication: medication)
medication.product_form.addCodes(CDAKImport_CDA_SectionImporter.extract_code(entry_element, code_xpath: "./cda:administrationUnitCode", code_system: "NCI Thesaurus"))
medication.delivery_method.addCodes(CDAKImport_CDA_SectionImporter.extract_code(entry_element, code_xpath: "./cda:code", code_system: "SNOMED-CT"))
if let type_of_med_xpath = type_of_med_xpath {
medication.type_of_medication.addCodes(CDAKImport_CDA_SectionImporter.extract_code(entry_element, code_xpath: type_of_med_xpath, code_system: "SNOMED-CT"))
}
// if let indication_entry = extract_indication(entry_element, entry: medication, indication_xpath: indication_xpath) {
// medication.indication = indication_entry
// }
medication.indication = extract_entry_detail(entry_element, xpath: indication_xpath)
medication.indication?.codes.preferred_code_sets = ["SNOMED-CT"]
if let precondition_entry = entry_element.xpath(precondition_xpath).first {
if let codes = CDAKImport_CDA_SectionImporter.extract_codes(precondition_entry, code_xpath: "cda:value") {
medication.precondition = codes
medication.precondition.preferred_code_sets = ["SNOMED-CT"]
}
}
medication.reaction = extract_entry_detail(entry_element, xpath: reaction_xpath)
medication.reaction?.codes.preferred_code_sets = ["SNOMED-CT"]
medication.severity = extract_entry_detail(entry_element, xpath: severity_xpath)
medication.severity?.codes.preferred_code_sets = ["SNOMED-CT"]
medication.vehicle.addCodes(CDAKImport_CDA_SectionImporter.extract_code(entry_element, code_xpath: vehicle_xpath, code_system: "SNOMED-CT"))
extract_order_information(entry_element, medication: medication)
extract_fulfillment_history(entry_element, medication: medication)
extract_negation(entry_element, entry: medication)
return medication
}
return nil
}
private func extract_fulfillment_history(parent_element: XMLElement, medication: CDAKMedication) {
let fhs = parent_element.xpath("./cda:entryRelationship/cda:supply[@moodCode='EVN']")
for fh_element in fhs {
let fulfillment_history = CDAKFulfillmentHistory()
fulfillment_history.prescription_number = fh_element.xpath("./cda:id").first?["root"]
if let actor_element = fh_element.xpath("./cda:performer").first {
fulfillment_history.provider = import_actor(actor_element)
}
if let hl7_timestamp = fh_element.xpath("./cda:effectiveTime").first?["value"] {
fulfillment_history.dispense_date = CDAKHL7Helper.timestamp_to_integer(hl7_timestamp)
}
if let quantity_dispensed = extract_scalar(fh_element, scalar_xpath: "./cda:quantity") {
fulfillment_history.quantity_dispensed = quantity_dispensed
}
if let fill_number = fh_element.xpath(fill_number_xpath).first?.stringValue, fill_number_int = Int(fill_number) {
fulfillment_history.fill_number = fill_number_int
}
medication.fulfillment_history.append(fulfillment_history)
}
}
private func extract_order_information(parent_element: XMLElement, medication: CDAKMedication) {
let order_elements = parent_element.xpath("./cda:entryRelationship[@typeCode='REFR']/cda:supply[@moodCode='INT']")
for order_element in order_elements {
let order_information = CDAKOrderInformation()
if let actor_element = order_element.xpath("./cda:author").first {
//this looks like it might explode
order_information.provider = CDAKImport_ProviderImportUtils.extract_provider(actor_element, element_name: "assignedAuthor")
}
order_information.order_number = order_element.xpath("./cda:id").first?["root"]
if let fills = order_element.xpath("./cda:repeatNumber").first?["value"], fills_int = Int(fills) {
order_information.fills = fills_int
}
if let quantity_ordered = extract_scalar(order_element, scalar_xpath: "./cda:quantity") {
order_information.quantity_ordered = quantity_ordered
}
medication.order_information.append(order_information)
}
}
private func extract_administration_timing(parent_element: XMLElement, medication: CDAKMedication) {
if let administration_timing_element = parent_element.xpath("./cda:effectiveTime[2]").first {
if let institutionSpecified = administration_timing_element["institutionSpecified"] {
let inst = institutionSpecified.lowercaseString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
switch inst {
case "true": medication.administration_timing.institution_specified = true
case "false": medication.administration_timing.institution_specified = false
default: print("CDA importer - extract_administration_timing() - institutionSpecified - found uknown value \(inst)")
}
}
if let period = extract_scalar(administration_timing_element, scalar_xpath: "./cda:period") {
medication.administration_timing.period = period
}
}
}
private func extract_dose_restriction(parent_element: XMLElement, medication: CDAKMedication) {
if let dre = parent_element.xpath("./cda:maxDoseQuantity").first {
if let numerator = extract_scalar(dre, scalar_xpath: "./cda:numerator") {
medication.dose_restriction.numerator = numerator
}
if let denominator = extract_scalar(dre, scalar_xpath: "./cda:denominator") {
medication.dose_restriction.denominator = denominator
}
}
}
}
|
mit
|
fe19f7b5f382f1e241a83b989d2a6287
| 52.575581 | 213 | 0.715976 | 3.93929 | false | false | false | false |
openaphid/PureLayout
|
PureLayout/Example-iOS/Demos/iOSDemo6ViewController.swift
|
5
|
2221
|
//
// iOSDemo6ViewController.swift
// PureLayout Example-iOS
//
// Copyright (c) 2015 Tyler Fox
// https://github.com/smileyborg/PureLayout
//
import UIKit
import PureLayout
@objc(iOSDemo6ViewController)
class iOSDemo6ViewController: UIViewController {
let blueView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .blueColor()
return view
}()
var didSetupConstraints = false
override func loadView() {
view = UIView()
view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
view.addSubview(blueView)
view.setNeedsUpdateConstraints() // bootstrap Auto Layout
}
override func updateViewConstraints() {
if (!didSetupConstraints) {
// Center the blueView in its superview, and match its width to its height
blueView.autoCenterInSuperview()
blueView.autoMatchDimension(.Width, toDimension: .Height, ofView: blueView)
// Make sure the blueView is always at least 20 pt from any edge
blueView.autoPinToTopLayoutGuideOfViewController(self, withInset: 20.0, relation: .GreaterThanOrEqual)
blueView.autoPinToBottomLayoutGuideOfViewController(self, withInset: 20.0, relation: .GreaterThanOrEqual)
blueView.autoPinEdgeToSuperviewEdge(.Left, withInset: 20.0, relation: .GreaterThanOrEqual)
blueView.autoPinEdgeToSuperviewEdge(.Right, withInset: 20.0, relation: .GreaterThanOrEqual)
// Add constraints that set the size of the blueView to a ridiculously large size, but set the priority of these constraints
// to a lower value than Required. This allows the Auto Layout solver to let these constraints be broken if one or both of
// them conflict with higher-priority constraint(s), such as the above 4 edge constraints.
NSLayoutConstraint.autoSetPriority(UILayoutPriorityDefaultHigh) {
blueView.autoSetDimensionsToSize(CGSize(width: 10000.0, height: 10000.0))
}
didSetupConstraints = true
}
super.updateViewConstraints()
}
}
|
mit
|
dbff57c3ee9597a05cf56139758fc7b2
| 38.660714 | 136 | 0.663215 | 5.338942 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios
|
MobilePeopleDirectory/ServerSync.swift
|
1
|
2014
|
//
// ServerSync.swift
// MobilePeopleDirectory
//
// Created by alejandro soto on 2/1/15.
// Copyright (c) 2015 Rivet Logic. All rights reserved.
//
import UIKit
import CoreData
class ServerSync {
private var _syncable:ServerSyncableProtocol
private var _primaryKey:String
private var _itemsCountKey:String
private var _listKey:String
private var _errorHandler:((ServerFetchResult!) -> Void)
var appHelper = AppHelper()
init(syncable:ServerSyncableProtocol, primaryKey:String, itemsCountKey:String, listKey:String, errorHandler: ((ServerFetchResult!) -> Void)!) {
self._syncable = syncable
self._primaryKey = primaryKey
self._itemsCountKey = itemsCountKey
self._listKey = listKey
self._errorHandler = errorHandler
}
// starts the local storage sync against liferay server
func syncData() -> ServerFetchResult {
if !SessionContext.hasSession {
if !SessionContext.loadSessionFromStore() { // creates a new session using creds from keychain. Returns false if no creds in keychain.
return ServerFetchResult.CredIssue
}
}
var lastModifiedDate = self._syncable.getLastModifiedDate() // returns the last item modified date
var timestamp = lastModifiedDate.timeIntervalSince1970 * 1000
self._requestServerData(timestamp)
return ServerFetchResult.Success
}
// requests server data and process it
private func _requestServerData(timestamp:Double) {
var asyncCallback = ServerAsyncCallback(syncable: self._syncable,
primaryKey: self._primaryKey,
itemsCountKey: self._itemsCountKey,
listKey: self._listKey,
errorHandler: self._errorHandler)
var session = SessionContext.createSessionFromCurrentSession()
session?.callback = asyncCallback
self._syncable.getServerData(timestamp, session: &session!)
}
}
|
gpl-3.0
|
50a2e87ad3f052bcfa92bcc96a8f9ad4
| 32.566667 | 148 | 0.671797 | 4.806683 | false | false | false | false |
inaka/Jolly
|
Sources/CommandRouter.swift
|
1
|
7708
|
// CommandRouter.swift
// Jolly
//
// Copyright 2016 Erlang Solutions, Ltd. - http://erlang-solutions.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
typealias Command = (String, String)
class CommandRouter {
let cache: Cache
let notificationSender: NotificationSender
let repoSpecProvider: RepoSpecProvider
var roomId: String {
return self.notificationSender.roomId
}
init(notificationSender: NotificationSender, repoSpecProvider: RepoSpecProvider = RepoSpecProvider(), cache: Cache = Cache()) {
self.notificationSender = notificationSender
self.repoSpecProvider = repoSpecProvider
self.cache = cache
}
func handle(_ message: String) -> Future<Void, Error> {
guard message == "/jolly" || message.hasPrefix("/jolly ") else {
return Future() { completion in
completion(.failure(.notSlashJollyCommand))
}
}
return self.notification(for: message)
.andThen {
self.notificationSender.send($0)
.map { _ in return }
.mapError { _ in return .errorSendingNotification }
}
}
// swiftlint:disable cyclomatic_complexity
// We want to preserve all the possible paths at this level in this function. If you find a neater way to write it, feel free to collaborate.
private func notification(for message: String) -> Future<Notification, Error> {
let command = message.commandValue
let notification: Notification
switch command {
case ("", ""):
notification = Notification(message: Messages.welcome, color: .purple, shouldNotify: true)
case ("about", _):
notification = Notification(message: Messages.about, color: .gray, shouldNotify: false)
case ("ping", _):
notification = Notification(message: Messages.pong, color: .green, shouldNotify: true)
case ("list", _):
let repos = self.cache.repos(forRoomWithId: self.roomId)
notification = Notification(message: Messages.list(with: repos), color: .green, shouldNotify: true)
case ("report", _):
return self.notificationForReport()
case ("clear", _):
let repos = self.cache.repos(forRoomWithId: self.roomId)
for repo in repos {
self.cache.remove(repo, fromRoomWithId: self.roomId)
}
notification = Notification(message: Messages.cleared, color: .gray, shouldNotify: false)
case ("watch", let argument):
return self.notificationForWatching(argument)
case ("unwatch", let argument):
return self.notificationForUnwatching(argument)
case ("jolly", _), ("/jolly", _):
notification = Notification(message: Messages.yoDawg, color: .gray, shouldNotify: true)
default:
notification = Notification(message: Messages.unknown(message: message), color: .red, shouldNotify: true)
}
return Future() { completion in completion(.success(notification)) }
}
private func notificationForWatching(_ argument: String) -> Future<Notification, Error> {
let notification: Notification
switch argument {
case "":
notification = Notification(message: Messages.watchHelp, color: .yellow, shouldNotify: true)
default:
guard let repo = Repo(fullName: argument) else {
notification = Notification(message: Messages.wrongRepoFormat(argument), color: .red, shouldNotify: true)
break
}
if let existentRepo = self.cache.repos(forRoomWithId: self.roomId)
.filter({ $0.fullName == argument })
.first {
notification = Notification(message: Messages.alreadyWatching(repo: existentRepo), color: .green, shouldNotify: true)
break
}
return Future() { completion in
self.repoSpecProvider.fetchSpec(for: repo).start() { result in
let notification: Notification
switch result {
case .success(_):
self.cache.add(repo, toRoomWithId: self.roomId)
notification = Notification(message: Messages.watchingWithSuccess(repo: repo), color: .green, shouldNotify: true)
case .failure(_):
notification = Notification(message: Messages.couldNotWatch(repo: repo), color: .red, shouldNotify: true)
}
completion(.success(notification))
}
}
}
return Future() { completion in completion(.success(notification)) }
}
private func notificationForUnwatching(_ argument: String) -> Future<Notification, Error> {
let notification: Notification
switch argument {
case "":
notification = Notification(message: Messages.unwatchHelp, color: .yellow, shouldNotify: true)
default:
guard let repo = Repo(fullName: argument) else {
notification = Notification(message: Messages.wrongRepoFormat(argument), color: .red, shouldNotify: true)
break
}
guard let existentRepo = self.cache.repos(forRoomWithId: self.roomId)
.filter({ $0.fullName == argument })
.first else {
notification = Notification(message: Messages.wasntWatching(repo: repo), color: .red, shouldNotify: true)
break
}
self.cache.remove(existentRepo, fromRoomWithId: self.roomId)
notification = Notification(message: Messages.unwatchingWithSuccess(repo: repo), color: .green, shouldNotify: true)
}
return Future() { completion in completion(.success(notification)) }
}
private func notificationForReport() -> Future<Notification, Error> {
let repos = self.cache.repos(forRoomWithId: self.roomId)
return Future() { completion in
self.repoSpecProvider.fetchSpecs(for: repos).start() { result in
switch result {
case .success(let specs):
let notification = Notification(message: Messages.report(with: specs), color: .purple, shouldNotify: true)
completion(.success(notification))
case .failure(_):
completion(.failure(.errorFetchingRepoSpecs))
}
}
}
}
enum Error: Swift.Error {
case errorFetchingRepoSpecs
case errorSendingNotification
case notSlashJollyCommand
}
}
fileprivate extension String {
var commandValue: Command {
let components = self.components(separatedBy: " ")
return (components.count > 1 ? components[1] : "",
components.count > 2 ? components[2] : "")
}
}
|
apache-2.0
|
56bc6a823a392b537ca61d01a0989995
| 40.664865 | 145 | 0.598599 | 5.12841 | false | false | false | false |
looker-open-source/sdk-examples
|
swift/sample-swift-sdk/sample-swift-sdk/SceneDelegate.swift
|
3
|
2658
|
//
// SceneDelegate.swift
// sample-swift-sdk
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let mainView = MainView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: mainView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
|
mit
|
e55725604d8e49d9ed3cebf238a87e3e
| 43.3 | 147 | 0.703536 | 5.402439 | false | false | false | false |
globelabs/globe-connect-swift
|
Sources/LocationQuery.swift
|
1
|
1412
|
import Foundation
public struct LocationQuery {
let accessToken: String
public typealias SuccessHandler = (JSON) -> Void
public typealias ErrorHandler = (_ error: Error) -> Void
public init(accessToken: String) {
self.accessToken = accessToken
}
public func getLocation(
address: String,
accuracy: Int = 10,
success: SuccessHandler? = nil,
failure: ErrorHandler? = nil
) -> Void {
// set the url
let url = "https://devapi.globelabs.com.ph/location/v1/queries/location?access_token=\(self.accessToken)&address=\(address)&requestedAccuracy=\(accuracy)"
// set the header
let headers = [
"Content-Type" : "application/json; charset=utf-8"
]
// send the request
Request().get(
url: url,
headers: headers,
callback: { data, _, _ in
DispatchQueue.global(qos: .utility).async {
do {
let jsonResult = try JSON.parse(jsonData: data!)
DispatchQueue.main.async {
success?(jsonResult)
}
} catch {
DispatchQueue.main.async {
failure?(error)
}
}
}
}
)
}
}
|
mit
|
346316b0febaa3aa7b0ab49b68302682
| 29.042553 | 162 | 0.486544 | 5.210332 | false | false | false | false |
JakeLin/iOSAnimationSample
|
iOSAnimationSample/LoginViewController.swift
|
1
|
6686
|
//
// LoginViewController.swift
// iOSAnimationSample
//
// Created by Jake Lin on 5/17/15.
// Copyright (c) 2015 JakeLin. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var bubble1: UIImageView!
@IBOutlet weak var bubble2: UIImageView!
@IBOutlet weak var bubble3: UIImageView!
@IBOutlet weak var bubble4: UIImageView!
@IBOutlet weak var bubble5: UIImageView!
@IBOutlet weak var logo: UIImageView!
@IBOutlet weak var dot: UIImageView!
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var login: UIButton!
// Customer UI
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
let warningMessage = UIImageView(image: UIImage(named: "Warning"))
var loginPosition = CGPoint.zero
override func viewDidLoad() {
super.viewDidLoad()
self.bubble1.transform = CGAffineTransformMakeScale(0, 0)
self.bubble2.transform = CGAffineTransformMakeScale(0, 0)
self.bubble3.transform = CGAffineTransformMakeScale(0, 0)
self.bubble4.transform = CGAffineTransformMakeScale(0, 0)
self.bubble5.transform = CGAffineTransformMakeScale(0, 0)
self.logo.center.x -= self.view.bounds.width
self.dot.center.x -= self.view.bounds.width/2
let paddingViewForUsername = UIView(frame: CGRectMake(0, 0, 44, self.username.frame.height))
self.username.leftView = paddingViewForUsername
self.username.leftViewMode = .Always
let paddingViewForPassword = UIView(frame: CGRectMake(0, 0, 44, self.password.frame.height))
self.password.leftView = paddingViewForPassword
self.password.leftViewMode = .Always
let userImageView = UIImageView(image: UIImage(named: "User"))
userImageView.frame.origin = CGPoint(x: 13, y: 10)
self.username.addSubview(userImageView)
let passwordImageView = UIImageView(image: UIImage(named: "Key"))
passwordImageView.frame.origin = CGPoint(x: 12, y: 9)
self.password.addSubview(passwordImageView)
self.username.center.x -= self.view.bounds.width
self.password.center.x -= self.view.bounds.width
self.loginPosition = self.login.center
self.login.center.x -= self.view.bounds.width
self.view.addSubview(self.warningMessage)
self.warningMessage.hidden = true
self.warningMessage.center = self.loginPosition
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIView.animateWithDuration(0.3, delay: 0.3, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: {
self.bubble1.transform = CGAffineTransformMakeScale(1, 1)
self.bubble4.transform = CGAffineTransformMakeScale(1, 1)
self.bubble5.transform = CGAffineTransformMakeScale(1, 1)
}, completion: nil)
UIView.animateWithDuration(0.3, delay: 0.4, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: {
self.bubble2.transform = CGAffineTransformMakeScale(1, 1)
self.bubble3.transform = CGAffineTransformMakeScale(1, 1)
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.5, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.5, options: [], animations: {
self.logo.center.x += self.view.bounds.width
}, completion: nil)
// UIView.animateWithDuration(0.5, delay: 0.5, options: .CurveEaseOut, animations: {
// self.logo.center.x += self.view.bounds.width
// }, completion: nil)
//
UIView.animateWithDuration(5, delay: 1, usingSpringWithDamping: 0.1, initialSpringVelocity: 1, options: [], animations: {
self.dot.center.x += self.view.bounds.width/2
}, completion: nil)
UIView.animateWithDuration(0.4, delay: 0.6, options: .CurveEaseOut, animations: {
self.username.center.x += self.view.bounds.width
}, completion: nil)
UIView.animateWithDuration(0.4, delay: 0.7, options: .CurveEaseOut, animations: {
self.password.center.x += self.view.bounds.width
}, completion: nil)
UIView.animateWithDuration(0.4, delay: 0.8, options: .CurveEaseOut, animations: {
self.login.center.x += self.view.bounds.width
}, completion: nil)
}
@IBAction func loginTapped(sender: AnyObject) {
self.login.addSubview(self.spinner)
self.spinner.frame.origin = CGPointMake(12, 12)
self.spinner.startAnimating()
UIView.transitionWithView(self.warningMessage,
duration: 0.3,
options: .TransitionFlipFromTop,
animations: {
self.warningMessage.hidden = true
}, completion: nil)
UIView.animateWithDuration(0.3, animations: {
self.login.center = self.loginPosition
}, completion: { _ in
self.login.center.x -= 30
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: {
self.login.center.x += 30
}, completion: {finished in
UIView.animateWithDuration(0.3, animations: {
self.login.center.y += 90
self.spinner.removeFromSuperview()
}, completion: { _ in
UIView.transitionWithView(self.warningMessage,
duration: 0.3,
options: [.TransitionFlipFromTop, .CurveEaseOut],
animations: {
self.warningMessage.hidden = false
}, completion: nil)
})
})
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
bff5c1d9486d937677e66d5a687db844
| 41.858974 | 139 | 0.616662 | 4.789398 | false | false | false | false |
kitoko552/clrpalette
|
Sources/Result.swift
|
1
|
569
|
//
// Result.swift
// ColorPaletteGenarator
//
// Created by Kosuke Kito on 2016/05/22.
// Copyright © 2016年 Kosuke Kito. All rights reserved.
//
enum Result {
case Success(message: Message)
case Failure(message: Message)
enum Message: String {
case Usage = "Usage: $ clr CLR_FILE_NAME COLOR_JSON_FILE"
case Success = "SUCCESS: clr file has created."
case NoSuchFile = "No such file."
case SerializationFailed = "Failed to serialize from data."
case WriteToFileFailed = "Failed to write to file."
}
}
|
mit
|
8f70d268bf1584da08551f4622197c39
| 27.35 | 67 | 0.64841 | 3.824324 | false | false | false | false |
radubozga/Freedom
|
speech/Swift/Speech-gRPC-Streaming/Pods/DynamicButton/Sources/DynamicButtonStyles/DynamicButtonStylePause.swift
|
2
|
1894
|
/*
* DynamicButton
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
/// Pause symbol style: ‖
struct DynamicButtonStylePause: DynamicButtonBuildableStyle {
let pathVector: DynamicButtonPathVector
init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) {
let size = size / 3
let leftOffset = CGPoint(x: size / -2, y: 0)
let rightOffset = CGPoint(x: size / 2, y: 0)
let p12 = PathHelper.line(atCenter: center, radius: size, angle: .pi / 2, offset: leftOffset)
let p34 = PathHelper.line(atCenter: center, radius: size, angle: .pi / 2, offset: rightOffset)
pathVector = DynamicButtonPathVector(p1: p12, p2: p12, p3: p34, p4: p34)
}
/// "Pause" style.
static var styleName: String {
return "Player - Pause"
}
}
|
apache-2.0
|
d156661d689767d81c87fbe785c814c1
| 37.612245 | 98 | 0.72833 | 4.113043 | false | false | false | false |
chinesemanbobo/PPDemo
|
Pods/Down/Source/AST/Styling/Stylers/DownStyler.swift
|
3
|
10142
|
//
// DownStyler.swift
// Down
//
// Created by John Nguyen on 22.06.19.
// Copyright © 2016-2019 Down. All rights reserved.
//
#if !os(watchOS) && !os(Linux)
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
/// A default `Styler` implementation that supports a variety of configurable
/// properties for font, text color and paragraph styling, as well as formatting
/// of nested lists and quotes.
open class DownStyler: Styler {
// MARK: - Properties
public let fonts: FontCollection
public let colors: ColorCollection
public let paragraphStyles: ParagraphStyleCollection
public let quoteStripeOptions: QuoteStripeOptions
public let thematicBreakOptions: ThematicBreakOptions
public let codeBlockOptions: CodeBlockOptions
private let itemParagraphStyler: ListItemParagraphStyler
private var listPrefixAttributes: [NSAttributedString.Key : Any] {[
.font: fonts.listItemPrefix,
.foregroundColor: colors.listItemPrefix]
}
// MARK: - Init
public init(configuration: DownStylerConfiguration = DownStylerConfiguration()) {
fonts = configuration.fonts
colors = configuration.colors
paragraphStyles = configuration.paragraphStyles
quoteStripeOptions = configuration.quoteStripeOptions
thematicBreakOptions = configuration.thematicBreakOptions
codeBlockOptions = configuration.codeBlockOptions
itemParagraphStyler = ListItemParagraphStyler(options: configuration.listItemOptions, prefixFont: fonts.listItemPrefix)
}
// MARK: - Styling
open func style(document str: NSMutableAttributedString) {
}
open func style(blockQuote str: NSMutableAttributedString, nestDepth: Int) {
let stripeAttribute = QuoteStripeAttribute(level: nestDepth + 1, color: colors.quoteStripe, options: quoteStripeOptions)
str.updateExistingAttributes(for: .paragraphStyle) { (style: NSParagraphStyle) in
style.indented(by: stripeAttribute.layoutWidth)
}
str.addAttributeInMissingRanges(for: .quoteStripe, value: stripeAttribute)
str.addAttribute(for: .foregroundColor, value: colors.quote)
}
open func style(list str: NSMutableAttributedString, nestDepth: Int) {
}
open func style(listItemPrefix str: NSMutableAttributedString) {
str.setAttributes(listPrefixAttributes)
}
open func style(item str: NSMutableAttributedString, prefixLength: Int) {
let paragraphRanges = str.paragraphRanges()
guard let leadingParagraphRange = paragraphRanges.first else { return }
indentListItemLeadingParagraph(in: str, prefixLength: prefixLength, inRange: leadingParagraphRange)
paragraphRanges.dropFirst().forEach {
indentListItemTrailingParagraph(in: str, inRange: $0)
}
}
open func style(codeBlock str: NSMutableAttributedString, fenceInfo: String?) {
styleGenericCodeBlock(in: str)
}
open func style(htmlBlock str: NSMutableAttributedString) {
styleGenericCodeBlock(in: str)
}
open func style(customBlock str: NSMutableAttributedString) {
}
open func style(paragraph str: NSMutableAttributedString) {
str.addAttribute(for: .paragraphStyle, value: paragraphStyles.body)
}
open func style(heading str: NSMutableAttributedString, level: Int) {
let (font, color, paragraphStyle) = headingAttributes(for: level)
str.updateExistingAttributes(for: .font) { (currentFont: DownFont) in
var newFont = font
if (currentFont.isMonospace) {
newFont = newFont.monospace
}
if (currentFont.isEmphasized) {
newFont = newFont.emphasis
}
if (currentFont.isStrong) {
newFont = newFont.strong
}
return newFont
}
str.addAttributes([
.foregroundColor: color,
.paragraphStyle: paragraphStyle])
}
open func style(thematicBreak str: NSMutableAttributedString) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = thematicBreakOptions.indentation
let attr = ThematicBreakAttribute(thickness: thematicBreakOptions.thickness, color: colors.thematicBreak)
str.addAttribute(for: .thematicBreak, value: attr)
str.addAttribute(for: .paragraphStyle, value: paragraphStyle)
}
open func style(text str: NSMutableAttributedString) {
str.setAttributes([
.font: fonts.body,
.foregroundColor: colors.body])
}
open func style(softBreak str: NSMutableAttributedString) {
}
open func style(lineBreak str: NSMutableAttributedString) {
}
open func style(code str: NSMutableAttributedString) {
styleGenericInlineCode(in: str)
}
open func style(htmlInline str: NSMutableAttributedString) {
styleGenericInlineCode(in: str)
}
open func style(customInline str: NSMutableAttributedString) {
}
open func style(emphasis str: NSMutableAttributedString) {
str.updateExistingAttributes(for: .font) { (font: DownFont) in
font.emphasis
}
}
open func style(strong str: NSMutableAttributedString) {
str.updateExistingAttributes(for: .font) { (font: DownFont) in
font.strong
}
}
open func style(link str: NSMutableAttributedString, title: String?, url: String?) {
guard let url = url else { return }
styleGenericLink(in: str, url: url)
}
open func style(image str: NSMutableAttributedString, title: String?, url: String?) {
guard let url = url else { return }
styleGenericLink(in: str, url: url)
}
// MARK: - Common Styling
private func styleGenericCodeBlock(in str: NSMutableAttributedString) {
let blockBackgroundAttribute = BlockBackgroundColorAttribute(
color: colors.codeBlockBackground,
inset: codeBlockOptions.containerInset)
let adjustedParagraphStyle = paragraphStyles.code.inset(by: blockBackgroundAttribute.inset)
str.setAttributes([
.font: fonts.code,
.foregroundColor: colors.code,
.paragraphStyle: adjustedParagraphStyle,
.blockBackgroundColor: blockBackgroundAttribute])
}
private func styleGenericInlineCode(in str: NSMutableAttributedString) {
str.setAttributes([
.font: fonts.code,
.foregroundColor: colors.code])
}
private func styleGenericLink(in str: NSMutableAttributedString, url: String) {
str.addAttributes([
.link: url,
.foregroundColor: colors.link])
}
// MARK: - Helpers
private func headingAttributes(for level: Int) -> (DownFont, DownColor, NSParagraphStyle) {
switch level {
case 1: return (fonts.heading1, colors.heading1, paragraphStyles.heading1)
case 2: return (fonts.heading2, colors.heading2, paragraphStyles.heading2)
case 3: return (fonts.heading3, colors.heading3, paragraphStyles.heading3)
case 4: return (fonts.heading4, colors.heading4, paragraphStyles.heading4)
case 5: return (fonts.heading5, colors.heading5, paragraphStyles.heading5)
case 6: return (fonts.heading6, colors.heading6, paragraphStyles.heading6)
default: return (fonts.heading1, colors.heading1, paragraphStyles.heading1)
}
}
private func indentListItemLeadingParagraph(in str: NSMutableAttributedString, prefixLength: Int, inRange range: NSRange) {
str.updateExistingAttributes(for: .paragraphStyle, in: range) { (existingStyle: NSParagraphStyle) in
existingStyle.indented(by: itemParagraphStyler.indentation)
}
let attributedPrefix = str.prefix(with: prefixLength)
let prefixWidth = attributedPrefix.size().width
let defaultStyle = itemParagraphStyler.leadingParagraphStyle(prefixWidth: prefixWidth)
str.addAttributeInMissingRanges(for: .paragraphStyle, value: defaultStyle, within: range)
}
private func indentListItemTrailingParagraph(in str: NSMutableAttributedString, inRange range: NSRange) {
str.updateExistingAttributes(for: .paragraphStyle, in: range) { (existingStyle: NSParagraphStyle) in
existingStyle.indented(by: itemParagraphStyler.indentation)
}
let defaultStyle = itemParagraphStyler.trailingParagraphStyle
str.addAttributeInMissingRanges(for: .paragraphStyle, value: defaultStyle, within: range)
indentListItemQuotes(in: str, inRange: range)
}
private func indentListItemQuotes(in str: NSMutableAttributedString, inRange range: NSRange) {
str.updateExistingAttributes(for: .quoteStripe, in: range) { (stripe: QuoteStripeAttribute) in
stripe.indented(by: itemParagraphStyler.indentation)
}
}
}
// MARK: - Helper Extensions
private extension NSParagraphStyle {
func indented(by indentation: CGFloat) -> NSParagraphStyle {
let result = mutableCopy() as! NSMutableParagraphStyle
result.firstLineHeadIndent += indentation
result.headIndent += indentation
result.tabStops = tabStops.map {
NSTextTab(textAlignment: $0.alignment, location: $0.location + indentation, options: $0.options)
}
return result
}
func inset(by amount: CGFloat) -> NSParagraphStyle {
let result = mutableCopy() as! NSMutableParagraphStyle
result.paragraphSpacingBefore += amount
result.paragraphSpacing += amount
result.firstLineHeadIndent += amount
result.headIndent += amount
result.tailIndent = -amount
return result
}
}
private extension NSAttributedString {
func prefix(with length: Int) -> NSAttributedString {
guard length <= self.length else { return self }
guard length > 0 else { return NSAttributedString() }
return attributedSubstring(from: NSMakeRange(0, length))
}
}
#endif
|
mit
|
94beae5f4a3e021b89eda055ab28fc08
| 32.916388 | 128 | 0.688788 | 4.884875 | false | false | false | false |
Alua-Kinzhebayeva/iOS-PDF-Reader
|
Sources/Classes/PDFDocument.swift
|
2
|
8509
|
//
// PDFDocument.swift
// PDFReader
//
// Created by ALUA KINZHEBAYEVA on 4/19/15.
// Copyright (c) 2015 AK. All rights reserved.
//
import CoreGraphics
import UIKit
/// PDF Document on the system to be interacted with
public struct PDFDocument {
/// Number of pages document contains
public let pageCount: Int
/// Name of the PDF file, used to display on navigation titles
public let fileName: String
/// File url where this document resides
let fileURL: URL?
/// File data of the document
let fileData: Data
/// Core Graphics representation of the document
let coreDocument: CGPDFDocument
/// Password of the document
let password: String?
/// Image cache with the page index and and image of the page
let images = NSCache<NSNumber, UIImage>()
/// Returns a newly initialized document which is located on the file system.
///
/// - parameter url: file or remote URL of the PDF document
/// - parameter password: password for the locked PDF
///
/// - returns: A newly initialized `PDFDocument`
public init?(url: URL, password: String? = nil) {
guard let fileData = try? Data(contentsOf: url) else { return nil }
self.init(fileData: fileData, fileURL: url, fileName: url.lastPathComponent, password: password)
}
/// Returns a newly initialized document from data representing a PDF
///
/// - parameter fileData: data of the PDF document
/// - parameter fileName: name of the PDF file
/// - parameter password: password for the locked pdf
///
/// - returns: A newly initialized `PDFDocument`
public init?(fileData: Data, fileName: String, password: String? = nil) {
self.init(fileData: fileData, fileURL: nil, fileName: fileName, password: password)
}
/// Returns a newly initialized document
///
/// - parameter fileData: data of the PDF document
/// - parameter fileURL: file URL where the PDF document exists on the file system
/// - parameter fileName: name of the PDF file
/// - parameter password: password for the locked PDF
///
/// - returns: A newly initialized `PDFDocument`
private init?(fileData: Data, fileURL: URL?, fileName: String, password: String?) {
guard let provider = CGDataProvider(data: fileData as CFData) else { return nil }
guard let coreDocument = CGPDFDocument(provider) else { return nil }
self.fileData = fileData
self.fileURL = fileURL
self.fileName = fileName
if let password = password, let cPasswordString = password.cString(using: .utf8) {
// Try a blank password first, per Apple's Quartz PDF example
if coreDocument.isEncrypted && !coreDocument.unlockWithPassword("") {
// Nope, now let's try the provided password to unlock the PDF
if !coreDocument.unlockWithPassword(cPasswordString) {
print("CGPDFDocumentCreateX: Unable to unlock \(fileName)")
}
self.password = password
} else {
self.password = nil
}
} else {
self.password = nil
}
self.coreDocument = coreDocument
self.pageCount = coreDocument.numberOfPages
self.loadPages()
}
/// Extracts image representations of each page in a background thread and stores them in the cache
func loadPages() {
DispatchQueue.global(qos: .background).async {
for pageNumber in 1...self.pageCount {
self.imageFromPDFPage(at: pageNumber, callback: { backgroundImage in
guard let backgroundImage = backgroundImage else { return }
self.images.setObject(backgroundImage, forKey: NSNumber(value: pageNumber))
})
}
}
}
/// Image representations of all the document pages
func allPageImages(callback: ([UIImage]) -> Void) {
var images = [UIImage]()
var pagesCompleted = 0
for pageNumber in 0..<pageCount {
pdfPageImage(at: pageNumber+1, callback: { (image) in
if let image = image {
images.append(image)
}
pagesCompleted += 1
if pagesCompleted == pageCount {
callback(images)
}
})
}
}
/// Image representation of the document page, first looking at the cache, calculates otherwise
///
/// - parameter pageNumber: page number index of the page
/// - parameter callback: callback to execute when finished
///
/// - returns: Image representation of the document page
func pdfPageImage(at pageNumber: Int, callback: (UIImage?) -> Void) {
if let image = images.object(forKey: NSNumber(value: pageNumber)) {
callback(image)
} else {
imageFromPDFPage(at: pageNumber, callback: { image in
guard let image = image else {
callback(nil)
return
}
images.setObject(image, forKey: NSNumber(value: pageNumber))
callback(image)
})
}
}
/// Grabs the raw image representation of the document page from the document reference
///
/// - parameter pageNumber: page number index of the page
/// - parameter callback: callback to execute when finished
///
/// - returns: Image representation of the document page
private func imageFromPDFPage(at pageNumber: Int, callback: (UIImage?) -> Void) {
guard let page = coreDocument.page(at: pageNumber) else {
callback(nil)
return
}
let originalPageRect = page.originalPageRect
let scalingConstant: CGFloat = 240
let pdfScale = min(scalingConstant/originalPageRect.width, scalingConstant/originalPageRect.height)
let scaledPageSize = CGSize(width: originalPageRect.width * pdfScale, height: originalPageRect.height * pdfScale)
let scaledPageRect = CGRect(origin: originalPageRect.origin, size: scaledPageSize)
// Create a low resolution image representation of the PDF page to display before the TiledPDFView renders its content.
UIGraphicsBeginImageContextWithOptions(scaledPageSize, true, 1)
guard let context = UIGraphicsGetCurrentContext() else {
callback(nil)
return
}
// First fill the background with white.
context.setFillColor(red: 1, green: 1, blue: 1, alpha: 1)
context.fill(scaledPageRect)
context.saveGState()
// Flip the context so that the PDF page is rendered right side up.
let rotationAngle: CGFloat
switch page.rotationAngle {
case 90:
rotationAngle = 270
context.translateBy(x: scaledPageSize.width, y: scaledPageSize.height)
case 180:
rotationAngle = 180
context.translateBy(x: 0, y: scaledPageSize.height)
case 270:
rotationAngle = 90
context.translateBy(x: scaledPageSize.width, y: scaledPageSize.height)
default:
rotationAngle = 0
context.translateBy(x: 0, y: scaledPageSize.height)
}
context.scaleBy(x: 1, y: -1)
context.rotate(by: rotationAngle.degreesToRadians)
// Scale the context so that the PDF page is rendered at the correct size for the zoom level.
context.scaleBy(x: pdfScale, y: pdfScale)
context.drawPDFPage(page)
context.restoreGState()
defer { UIGraphicsEndImageContext() }
guard let backgroundImage = UIGraphicsGetImageFromCurrentImageContext() else {
callback(nil)
return
}
callback(backgroundImage)
}
}
extension CGPDFPage {
/// original size of the PDF page.
var originalPageRect: CGRect {
switch rotationAngle {
case 90, 270:
let originalRect = getBoxRect(.mediaBox)
let rotatedSize = CGSize(width: originalRect.height, height: originalRect.width)
return CGRect(origin: originalRect.origin, size: rotatedSize)
default:
return getBoxRect(.mediaBox)
}
}
}
|
mit
|
b960ba7b23b4238d904cab36f8421224
| 36.986607 | 127 | 0.608885 | 5.101319 | false | false | false | false |
gustavoavena/BandecoUnicamp
|
BandecoUnicamp/PageViewController.swift
|
1
|
7059
|
//
// PageViewController.swift
// BandecoUnicamp
//
// Created by Gustavo Avena on 24/07/17.
// Copyright © 2017 Gustavo Avena. All rights reserved.
//
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
var errorUpdating: Bool = false
var cardapios: [Cardapio] = CardapioServices.shared.getAllCardapios()
var vegetariano: Bool = UserDefaults(suiteName: "group.bandex.shared")!.bool(forKey: "vegetariano") {
didSet {
vegetarianoChanged()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
// Setting up the page indicator
// Uncomment later to enable the page indicator
let appearance = UIPageControl.appearance()
appearance.backgroundColor = UIColor.groupTableViewBackground
appearance.isOpaque = false
appearance.pageIndicatorTintColor = UIColor.lightGray
appearance.currentPageIndicatorTintColor = UIColor.gray
loadData()
}
func alertarErro() {
guard let controller = storyboard?.instantiateViewController(withIdentifier: "ErroViewController") else {
fatalError("Unable to instantiate a ErroViewController.")
}
// Colocar mensagem de erro na label de data de todos os view controllers (caso haja cardapios). Caso nao haja cardapios, instanciar ErroViewController.
setViewControllers([controller], direction: .forward, animated: false, completion: nil)
}
func alertarErroNovo() {
if let vcs = self.viewControllers as? [CardapioTableViewController], vcs.count > 0 {
for vc in vcs {
vc.errorUpdating = true
}
} else {
alertarErro()
}
}
func vegetarianoChanged() {
if let _ = viewControllers?.first as? CardapioTableViewController {
let index = presentationIndex(for: self)
let newVC = cardapioItemViewController(forCardapio: index)
setViewControllers([newVC], direction: .forward, animated: false, completion: nil)
} else {
print("Nenhum view controller exibido")
}
}
fileprivate func setupAppearance(_ show: Bool) {
let appearance = UIPageControl.appearance()
appearance.isHidden = !show
}
func loadData() {
if let _ = cardapios.first {
let vc = cardapioItemViewController(forCardapio: 0)
self.setViewControllers([vc], direction: .forward, animated: false, completion: nil)
setupAppearance(true)
} else {
print("Sem cardapios no page view controller")
alertarErro()
setupAppearance(false)
}
}
func reloadCardapios(completionHandler: (Bool)->Void) {
let newCardapios = CardapioServices.shared.getAllCardapios()
if newCardapios.count > 0 {
self.cardapios = newCardapios
self.errorUpdating = false
loadData()
completionHandler(true)
} else {
self.errorUpdating = true
alertarErroNovo()
print("Cardapios nao atualizados devido a erro.")
completionHandler(false)
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let index = indexOfDataItem(forViewController: viewController)
let previousIndex = index - 1
guard previousIndex >= 0 else {return nil}
guard cardapios.count > previousIndex else {return nil}
return cardapioItemViewController(forCardapio: previousIndex)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let vcIndex = indexOfDataItem(forViewController: viewController)
let nextIndex = vcIndex + 1
guard cardapios.count != nextIndex else { return nil}
guard cardapios.count > nextIndex else { return nil }
return cardapioItemViewController(forCardapio: nextIndex)
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let currentViewController = pageViewController.viewControllers?.first else { fatalError("Unable to get the page controller's current view controller.") }
return indexOfDataItem(forViewController: currentViewController)
}
// Uncomment to enable the page indicator
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return self.cardapios.count
}
func indexOfCardapio(cardapio: Cardapio) -> Int? {
for i in 0..<cardapios.count {
if cardapios[i].data == cardapio.data {
return i
}
}
return nil
}
private func indexOfDataItem(forViewController viewController: UIViewController) -> Int {
guard let viewController = viewController as? CardapioTableViewController else {
print("Unexpected view controller type in page view controller.")
return 0
}
guard let cardapio = viewController.cardapio,
let viewControllerIndex = indexOfCardapio(cardapio: cardapio) else {
fatalError("View controller's data item not found.")
}
return viewControllerIndex
}
private func cardapioItemViewController(forCardapio pageIndex: Int) -> CardapioTableViewController {
// var cardapio: Cardapio! = nil
// Instantiate and configure a `DataItemViewController` for the `DataItem`.
guard let controller = storyboard?.instantiateViewController(withIdentifier: CardapioTableViewController.storyboardIdentifier) as? CardapioTableViewController else {
fatalError("Unable to instantiate a CardapioTableViewController.")
}
guard pageIndex >= 0, pageIndex < self.cardapios.count else {
fatalError("Index out of range in cardapios.")
}
let cardapio = self.cardapios[pageIndex]
controller.cardapio = cardapio
controller.vegetariano = self.vegetariano
controller.errorUpdating = self.errorUpdating
controller.parentPageViewController = self
return controller
}
/*
// 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.
}
*/
}
|
mit
|
366e99e40718768d1641d41edec64b75
| 32.932692 | 173 | 0.634599 | 5.375476 | false | false | false | false |
VaneCGo/TableViewWithSearchBar
|
TableViewWithSearchBar/TVSBTableViewController.swift
|
1
|
3683
|
//
// TVSBTableViewController.swift
// TableViewWithSearchBar
//
// Created by Vanessa Cantero Gómez on 02/06/15.
// Copyright (c) 2015 VCG. All rights reserved.
//
import UIKit
class TVSBTableViewResult: UITableViewController {
private var filteredProducts = [String]()
private let kCellIdentifier = "cell"
override func viewDidLoad() {
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: kCellIdentifier)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredProducts.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = filteredProducts[indexPath.row]
return cell
}
}
class TVSBTableViewController: UITableViewController, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating {
private let dataModel = ["Hello", "Bye", "Meh", "Wowo", "Bored", "Borked", "Vanessa"]
private let kCellIdentifier = "cell"
internal var searchBarInNavController = false
lazy var resultsTableController: TVSBTableViewResult = {
let rResult = TVSBTableViewResult()
return rResult
}()
lazy var searchController: UISearchController = {
let sController = UISearchController(searchResultsController: self.resultsTableController)
sController.searchBar.placeholder = "Search something"
sController.searchResultsUpdater = self
sController.searchBar.sizeToFit()
sController.searchBar.searchBarStyle = .Default
return sController
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "This is funny"
navigationController?.navigationBar.topItem?.title = ""
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: kCellIdentifier)
if searchBarInNavController {
searchController.hidesNavigationBarDuringPresentation = false
navigationItem.titleView = searchController.searchBar
} else {
tableView.tableHeaderView = searchController.searchBar
}
resultsTableController.tableView.delegate = self
searchController.delegate = self
searchController.searchBar.delegate = self
definesPresentationContext = true
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataModel.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = dataModel[indexPath.row]
return cell
}
// MARK: UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchTableController: TVSBTableViewResult = searchController.searchResultsController as! TVSBTableViewResult
searchTableController.filteredProducts = dataModel.filter({ $0.uppercaseString.rangeOfString(searchController.searchBar.text.uppercaseString) != nil })
searchTableController.tableView.reloadData()
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
|
mit
|
64e371875c3c9cbec98bb0f6f216cddb
| 34.747573 | 159 | 0.733026 | 5.789308 | false | false | false | false |
chrisjmendez/swift-exercises
|
Advertising/DoubleClick/Interstitial/Interstitial/ViewController.swift
|
1
|
3388
|
//
// ViewController.swift
// Interstitial
//
// Created by Tommy Trojan on 10/28/15.
// Copyright © 2015 Chris Mendez. All rights reserved.
//
import UIKit
import GoogleMobileAds
class ViewController: UIViewController, GADInterstitialDelegate {
var interstitial: GADInterstitial?
var timer:Timer?
func createAndLoadInterstitial() -> DFPInterstitial {
let request = DFPRequest()
//This shows AdMob ads
request.testDevices = [kGADSimulatorID]
let ads = ["/181024612/2015_fall_320x480"]
//let randomNumber = Int.random(0...1)
let interstitial = DFPInterstitial(adUnitID: ads[0])
//Register the Interstitial events
interstitial.delegate = self
interstitial.load(request)
return interstitial
}
func showInterstitial(){
let timestamp = DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .long)
print("showInterstitial \(timestamp)")
if (interstitial!.isReady) {
interstitial!.present(fromRootViewController: self)
}
}
// /////////////////////////////////////////////
// Events
// /////////////////////////////////////////////
//Tells the delegate that the full screen view has been dismissed.
func interstitialDidDismissScreen(_ ad: GADInterstitial!) {
print("User closed AD")
//Create a new Interstitial
interstitial = createAndLoadInterstitial()
}
//Tells the delegate an ad request loaded an ad.
func interstitialDidReceiveAd(_ ad: GADInterstitial!) {
print("Ad was received")
//Delay the presentation by a few seconds
startTimer(0.5)
}
//Tells the delegate that a user click will open another app
func interstitialWillLeaveApplication(_ ad: GADInterstitial!) {
print("User will leave app")
}
//The screen will present the ad
func interstitialWillPresentScreen(_ ad: GADInterstitial!) {
print("Ad is being presented")
}
// /////////////////////////////////////////////
// Simple Timer
// /////////////////////////////////////////////
func startTimer(_ delay:Double){
let delayTime = delay
timer = Timer.scheduledTimer(timeInterval: delayTime, target: self, selector: #selector(ViewController.showInterstitial), userInfo: nil, repeats: false)
}
func stopTimer(){
timer = nil
}
// /////////////////////////////////////////////
// On Load
// /////////////////////////////////////////////
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
interstitial = createAndLoadInterstitial()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension Int
{
static func random(_ range: Range<Int> ) -> Int
{
var offset = 0
if range.lowerBound < 0 // allow negative ranges
{
offset = abs(range.lowerBound)
}
let mini = UInt32(range.lowerBound + offset)
let maxi = UInt32(range.upperBound + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
|
mit
|
1eeadc9c875da34b5789bf1526d3f425
| 30.654206 | 160 | 0.574255 | 5.275701 | false | false | false | false |
airspeedswift/swift
|
test/IRGen/prespecialized-metadata/enum-inmodule-5argument-1distinct_use.swift
|
3
|
7157
|
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueOyS5iGWV" = linkonce_odr hidden constant %swift.enum_vwtable {
// CHECK-SAME: i8* bitcast ({{([^@]+@"\$s4main5ValueOyS5iGwCP+[^\)]+ to i8\*|[^@]+@__swift_memcpy[0-9]+_[0-9]+[^)]+ to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_noop_void_return{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS5iGwet{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS5iGwst{{[^)]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS5iGwug{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS5iGwup{{[^)]+}} to i8*),
// CHECK-SAME i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS5iGwui{{[^)]+}} to i8*)
// CHECK-SAME: }, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueOyS5iGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOyS5iGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: [[INT]] {{40|20}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Value<First, Second, Third, Fourth, Fifth> {
case first(First)
case second(First, Second)
case third(First, Second, Third)
case fourth(First, Second, Third, Fourth)
case fifth(First, Second, Third, Fourth, Fifth)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOyS5iGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.fifth(13, 14, 15, 16, 17) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, i8** %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_BUFFER:%[0-9]+]] = bitcast i8** %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[ERASED_TYPE_ADDRESS_1:%[0-9]+]] = getelementptr i8*, i8** %1, i64 0
// CHECK: [[ERASED_TYPE_1:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_1]]
// CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]]
// CHECK: [[ERASED_TYPE_ADDRESS_2:%[0-9]+]] = getelementptr i8*, i8** %1, i64 1
// CHECK: [[ERASED_TYPE_2:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_2]]
// CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]]
// CHECK: [[ERASED_TYPE_ADDRESS_3:%[0-9]+]] = getelementptr i8*, i8** %1, i64 2
// CHECK: [[ERASED_TYPE_3:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_3]]
// CHECK: [[EQUAL_TYPE_1_3:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_3]]
// CHECK: [[EQUAL_TYPES_1_3:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_2]], [[EQUAL_TYPE_1_3]]
// CHECK: [[ERASED_TYPE_ADDRESS_4:%[0-9]+]] = getelementptr i8*, i8** %1, i64 3
// CHECK: [[ERASED_TYPE_4:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_4]]
// CHECK: [[EQUAL_TYPE_1_4:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_4]]
// CHECK: [[EQUAL_TYPES_1_4:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_3]], [[EQUAL_TYPE_1_4]]
// CHECK: [[ERASED_TYPE_ADDRESS_5:%[0-9]+]] = getelementptr i8*, i8** %1, i64 4
// CHECK: [[ERASED_TYPE_5:%\".*\"]] = load i8*, i8** [[ERASED_TYPE_ADDRESS_5]]
// CHECK: [[EQUAL_TYPE_1_5:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_5]]
// CHECK: [[EQUAL_TYPES_1_5:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_4]], [[EQUAL_TYPE_1_5]]
// CHECK: br i1 [[EQUAL_TYPES_1_5]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED_1]]:
// CHECK: ret %swift.metadata_response {
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOyS5iGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 0
// CHECK-SAME: }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @swift_getGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_BUFFER]],
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
|
apache-2.0
|
11efa6ebec1bb95f2e798567ac090568
| 48.358621 | 157 | 0.546458 | 2.789166 | false | false | false | false |
kiliankoe/catchmybus
|
catchmybus/MenuController.swift
|
1
|
3668
|
//
// MenuBarController.swift
// catchmybus
//
// Created by Kilian Költzsch on 11/05/15.
// Copyright (c) 2015 Kilian Koeltzsch. All rights reserved.
//
import Cocoa
import Sparkle
class MenuController: NSMenu {
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
var isConnectionSelected = false
var stopMenuItems = [NSMenuItem]()
var numRowsToShow = 5
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("Initialized NSMenu through init(coder:). Wat?")
}
init() {
// FIXME: Why is this not throwing errors with init(title:), but init() is not ok?
super.init(title: "")
setupMainMenuItems()
// TODO: Check if it might be better to send the value as the notification object instead of telling this when to load from NSUserDefaults
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateNumRowsToShowValue", name: kUpdatedNumRowsToShowNotification, object: nil)
}
/**
Sets up the main NSMenuItems for the menu, so it'll look like this:
[Connections will be listed here]
-----
[Stops will be listed here]
-----
Settings...
Check for updates...
About...
Quit
*/
private func setupMainMenuItems() {
// Connections will be listed here
self.addItem(NSMenuItem.separatorItem())
// Stops will be listed here
self.addItem(NSMenuItem.separatorItem())
self.addItem(ClosureMenuItem(title: "Settings...", keyEquivalent: ",", action: { () -> () in
self.appDelegate.settingsWindowController.display()
}))
self.addItem(ClosureMenuItem(title: "Check for updates...", keyEquivalent: "", action: { () -> () in
let updater = SUUpdater(forBundle: NSBundle.mainBundle())
updater.checkForUpdates(updater)
}))
self.addItem(ClosureMenuItem(title: "About...", keyEquivalent: "", action: { () -> () in
self.appDelegate.aboutWindowController.display()
}))
self.addItem(NSMenuItem(title: "Quit", action: "terminate:", keyEquivalent: "q"))
}
/**
Sets up the NSMenuItems for all saved stops
*/
private func setupStopMenuItems() {
for stop in ConnectionManager.shared().stopDict {
let stopMenuItem = NSMenuItem(title: stop.0, action: "selectStop:", keyEquivalent: "")
stopMenuItems.append(stopMenuItem)
self.insertItem(stopMenuItem, atIndex: 1)
if (stop.0 == ConnectionManager.shared().selectedStop) {
stopMenuItem.state = NSOnState
}
}
}
// MARK: -
func updateMenu() {
// TODO: Remove all rows that are now outdated and add in correct number of new ones
}
func updateNumRowsToShowValue() {
numRowsToShow = NSUserDefaults.standardUserDefaults().integerForKey(kNumRowsToShowKey)
// TODO: Probably reload the menu here to display the changed value?
}
// MARK: - Selections
func selectConnection(sender: ConnectionMenuItem) {
// clear a possible previous notification
// show a notification about the upcoming notification
// schedule notification for time when bus comes - 15 minutes
// set statusitem for the selected connection
}
func selectStop(sender: NSMenuItem) {
ConnectionManager.shared().selectedStop = sender.title
for stop in stopMenuItems {
stop.state = NSOffState
}
sender.state = NSOnState
isConnectionSelected = false
ConnectionManager.shared().nuke()
ConnectionManager.shared().saveDefaults()
update()
}
// MARK: - Actions
// TODO: Remove me in favor of removing the notification by clicking on the selected connection again
func clearNotificationButtonPressed(sender: NSMenuItem) {
NotificationController.shared().removeScheduledNotification()
ConnectionManager.shared().deselectAll()
isConnectionSelected = false
update()
}
}
|
mit
|
6ceb98caadebff212910dac6abd28e77
| 27.874016 | 148 | 0.727298 | 4.003275 | false | false | false | false |
ello/ello-ios
|
Sources/Networking/DateFormatting.swift
|
1
|
1232
|
////
/// DateFormatting.swift
//
let ServerDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter
}()
let ServerDateBackupFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter
}()
let HTTPDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "eee, dd MMM yyyy HH:mm:ss zzz"
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter
}()
let MonthDayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "MMMM dd"
return formatter
}()
let MonthDayYearFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "MMM dd, yyyy"
return formatter
}()
|
mit
|
105d5b69b75cc7d035fea3aa82db4c4f
| 29.8 | 58 | 0.69724 | 4.039344 | false | false | false | false |
dmitriy-shmilo/portfolio-app
|
ios/Portfolio App/Portfolio App/ViewControllers/PortfolioItemDetailsViewController.swift
|
1
|
5669
|
//
// PortfolioItemDetailsViewController.swift
// Portfolio App
//
// Created by Dmitriy Shmilo on 10/17/17.
// Copyright © 2017 Dmitriy Shmilo. All rights reserved.
//
import UIKit
class PortfolioItemDetailsViewController : UIViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
navigationItem.title = "Details";
}
required init?(coder aDecoder: NSCoder) {
fatalError("Unimplemented");
}
override func viewDidLoad() {
super.viewDidLoad();
setupViews();
setupLayout();
let formatter = DateFormatter();
formatter.dateStyle = .medium;
formatter.timeStyle = .none;
navigationItem.title = portfolioItem.title;
titleLabel.text = portfolioItem.title;
subtitleLabel.text = portfolioItem.place;
dateRangeLabel.text = "\(formatter.string(from: portfolioItem.startDate))"
+ " - "
+ "\(portfolioItem.endDate != nil ? formatter.string(from: portfolioItem.endDate!) : "now")"; // FIXME: localize
summaryTextLabel.text = portfolioItem.summary;
iconImage.image = getIcon();
}
func setEntity(item:PortfolioItem) {
portfolioItem = item;
}
func getIcon() -> UIImage{
preconditionFailure("Unimplemented");
}
private func setupViews() {
view.backgroundColor = .white;
scrollView = UIScrollView();
scrollView.translatesAutoresizingMaskIntoConstraints = false;
view.addSubview(scrollView);
headerGroupView = UIView();
headerGroupView.translatesAutoresizingMaskIntoConstraints = false;
scrollView.addSubview(headerGroupView);
iconImage = UIImageView();
iconImage.translatesAutoresizingMaskIntoConstraints = false;
headerGroupView.addSubview(iconImage);
titleLabel = UILabel();
titleLabel.translatesAutoresizingMaskIntoConstraints = false;
titleLabel.font = UIFont.boldSystemFont(ofSize: 16);
headerGroupView.addSubview(titleLabel);
subtitleLabel = UILabel();
subtitleLabel.translatesAutoresizingMaskIntoConstraints = false;
subtitleLabel.font = UIFont.systemFont(ofSize: 14);
subtitleLabel.textColor = .gray;
headerGroupView.addSubview(subtitleLabel);
dateRangeLabel = UILabel();
dateRangeLabel.translatesAutoresizingMaskIntoConstraints = false;
dateRangeLabel.font = UIFont.systemFont(ofSize: 12);
dateRangeLabel.textColor = .gray;
headerGroupView.addSubview(dateRangeLabel);
summaryTextLabel = UILabel();
summaryTextLabel.translatesAutoresizingMaskIntoConstraints = false;
summaryTextLabel.font = UIFont.systemFont(ofSize: 14);
summaryTextLabel.numberOfLines = 0;
scrollView.addSubview(summaryTextLabel);
}
private func setupLayout() {
let guide = view.layoutMarginsGuide;
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: guide.topAnchor),
scrollView.rightAnchor.constraint(equalTo: guide.rightAnchor),
scrollView.bottomAnchor.constraint(equalTo: guide.bottomAnchor),
scrollView.leftAnchor.constraint(equalTo: guide.leftAnchor),
headerGroupView.topAnchor.constraint(equalTo: scrollView.topAnchor),
headerGroupView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
iconImage.leftAnchor.constraint(equalTo: headerGroupView.leftAnchor),
iconImage.widthAnchor.constraint(equalTo:iconImage.heightAnchor),
iconImage.heightAnchor.constraint(equalToConstant: 65),
iconImage.topAnchor.constraint(equalTo: headerGroupView.topAnchor),
titleLabel.topAnchor.constraintLessThanOrEqualToSystemSpacingBelow(headerGroupView.topAnchor, multiplier: 1),
titleLabel.leftAnchor.constraintEqualToSystemSpacingAfter(iconImage.rightAnchor, multiplier: 1),
titleLabel.rightAnchor.constraint(equalTo: headerGroupView.rightAnchor),
subtitleLabel.topAnchor.constraintLessThanOrEqualToSystemSpacingBelow(titleLabel.bottomAnchor, multiplier: 1),
subtitleLabel.leftAnchor.constraint(equalTo: titleLabel.leftAnchor),
subtitleLabel.rightAnchor.constraint(equalTo: titleLabel.rightAnchor),
dateRangeLabel.topAnchor.constraintLessThanOrEqualToSystemSpacingBelow(subtitleLabel.bottomAnchor, multiplier: 1),
dateRangeLabel.leftAnchor.constraint(equalTo: subtitleLabel.leftAnchor),
dateRangeLabel.rightAnchor.constraint(equalTo: subtitleLabel.rightAnchor),
dateRangeLabel.bottomAnchor.constraint(lessThanOrEqualTo: headerGroupView.bottomAnchor),
summaryTextLabel.leftAnchor.constraintEqualToSystemSpacingAfter(guide.leftAnchor, multiplier: 1),
summaryTextLabel.rightAnchor.constraintEqualToSystemSpacingAfter(guide.rightAnchor, multiplier: -1),
summaryTextLabel.topAnchor.constraintEqualToSystemSpacingBelow(dateRangeLabel.bottomAnchor, multiplier: 2)
]);
}
var portfolioItem:PortfolioItem!;
var headerGroupView:UIView!;
var scrollView:UIScrollView!;
var iconImage:UIImageView!;
var titleLabel:UILabel!;
var subtitleLabel:UILabel!;
var dateRangeLabel:UILabel!;
var summaryTextLabel:UILabel!;
}
|
mit
|
d1933a0284d222903eab9009c181f9ed
| 41.616541 | 126 | 0.687897 | 5.898023 | false | false | false | false |
dfuerle/kuroo
|
kuroo/ContactTableViewController.swift
|
1
|
5934
|
//
// ContactTableViewController.swift
// kuroo
//
// Copyright © 2016 Dmitri Fuerle. All rights reserved.
//
import UIKit
import CoreData
import Contacts
protocol CustomContactPickerDelegate: class {
func customContactPicker(contact: Contact)
}
class ContactTableViewController: UITableViewController, SectionTableHelperDelegate, SupportsContext {
struct Constants {
static let cellIdentifier = "ContactTableViewCell"
static let rowHeight: CGFloat = 44.0
static let detailSegueIdentifier = "ContactDetailViewController"
}
var sectionTableHelper = SectionTableHelper()
var context: Context!
var selectType: MessageType = .panic
var currentColor: UIColor = UIColor.black
var delegate: CustomContactPickerDelegate?
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
debugPrint("viewDidLoad \(self)")
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = Constants.rowHeight
sectionTableHelper.delegate = self
sectionTableHelper.tableView = tableView
sectionTableHelper.setup(fetchedResultsController: context.dataController.fetchedResultsController(searchKeyword: nil))
debugPrint("fetchedResultsController \(sectionTableHelper.fetchedResultsController) delgate \(sectionTableHelper.fetchedResultsController.delegate)")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
debugPrint("viewDidAppear \(self)")
switch self.selectType {
case .panic:
currentColor = context.kuRed
self.title = "All Contacts"
case .whereAreYou:
currentColor = context.kuYellow
self.title = "Where-RU"
case .checkIn:
currentColor = context.kuGreen
self.title = "Check-IN"
}
tableView.sectionIndexBackgroundColor = currentColor
navigationController?.navigationBar.barTintColor = currentColor
sectionTableHelper.fetch() //TODO fix fetchedresults controller so this is not needed
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if var contextViewController = segue.destination as? SupportsContext {
contextViewController.context = context
}
// Apples suggestion regarding using prepare
switch segue.identifier! {
case Constants.detailSegueIdentifier:
let destination = segue.destination as! ContactDetailViewController
let indexPath = tableView.indexPathForSelectedRow!
if let person = sectionTableHelper.fetchedResultsController.object(at: indexPath) as? Person {
let cnContact = context.addressBook.cnContactForIdentifier(identifier: person.identifier!)
destination.cnContact = cnContact
destination.delegate = delegate
}
default:
print("Unknown segue: \(segue.identifier)")
}
}
// MARK: - Actions
@IBAction func cancelTouched(_ sender: UIBarButtonItem) {
debugPrint("cancelTouched \(self)")
dismiss(animated: true, completion: nil)
}
// MARK: - SectionTableHelperDelegate
func configureCell(cell: UITableViewCell, indexPath: IndexPath) {
if let personCell = cell as? ContactTableViewCell {
let person = sectionTableHelper.fetchedResultsController.object(at: indexPath) as! Person
personCell.nameLabel.text = person.displayName
personCell.hasPhoneImageView.isHidden = !person.hasPhoneNumber
personCell.hasEmailImageView.isHidden = !person.hasEmail
}
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sections = sectionTableHelper.fetchedResultsController.sections else {
fatalError("No sections in fetchedResultsController")
}
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.cellIdentifier) as! ContactTableViewCell
configureCell(cell: cell, indexPath: indexPath)
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTableHelper.fetchedResultsController.sections!.count
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let indexPath = NSIndexPath(row: 0, section: section) as IndexPath
let person = sectionTableHelper.fetchedResultsController.object(at: indexPath) as! Person
return person.firstLetterOfName
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
var sectionIndexTitles = [String]()
for sectionInfo in sectionTableHelper.fetchedResultsController.sections! {
let person = sectionInfo.objects?.first as! Person
sectionIndexTitles.append(person.firstLetterOfName!)
}
return sectionIndexTitles
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return index
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: Constants.detailSegueIdentifier, sender: self)
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = currentColor
}
}
|
gpl-2.0
|
4185967e8696d3a8ce72e537544c23bf
| 38.818792 | 157 | 0.688185 | 5.704808 | false | false | false | false |
bcattle/AudioLogger-iOS
|
AudioLogger-iOS/FullscreenCell.swift
|
1
|
1115
|
//
// FullscreenCell.swift
// AudioLogger-iOS
//
// Created by Bryan on 1/6/17.
// Copyright © 2017 bcattle. All rights reserved.
//
import UIKit
import Cartography
class FullscreenCell<T:UIView>: UITableViewCell {
var fullscreenView: T? {
didSet {
if let oldView = oldValue {
oldView.removeFromSuperview()
}
if let newView = fullscreenView {
addSubview(newView)
constrain(newView) { view in
view.left == view.superview!.left
view.right == view.superview!.right
view.top == view.superview!.top
view.bottom == view.superview!.bottom
}
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
fullscreenView = T.init()
}
}
|
mit
|
3e35baebe59882457ea192ad486fdb0a
| 24.906977 | 74 | 0.54219 | 4.801724 | false | false | false | false |
apple/swift
|
test/Driver/parseable_output.swift
|
5
|
6048
|
// RUN: %swiftc_driver_plain -emit-executable %s -o %t.out -emit-module -emit-module-path %t.swiftmodule -emit-objc-header-path %t.h -serialize-diagnostics -emit-dependencies -parseable-output -driver-skip-execution 2>&1 | %FileCheck %s
// XFAIL: OS=freebsd, OS=openbsd, OS=linux-gnu, OS=linux-android, OS=linux-androideabi
// CHECK: {{[1-9][0-9]*}}
// CHECK-NEXT: {
// CHECK-NEXT: "kind": "began",
// CHECK-NEXT: "name": "compile",
// CHECK-NEXT: "command": "{{.*[\\/]}}swift{{(-frontend|c)?(\.exe)?(\\")?}} -frontend -c -primary-file {{.*[\\/]}}parseable_output.swift{{(\\")?}} {{.*}} -o {{.*[\\/]}}parseable_output-[[OUTPUT:.*]].o{{(\\")?}}",
// CHECK-NEXT: "command_executable": "{{.*[\\/]}}swift{{(-frontend|c)?(\.exe)?}}",
// CHECK-NEXT: "command_arguments": [
// CHECK-NEXT: "-frontend",
// CHECK-NEXT: "-c",
// CHECK-NEXT: "-primary-file",
// CHECK-NEXT: "{{.*[\\/]}}parseable_output.swift",
// CHECK: "-o",
// CHECK-NEXT: "{{.*[\\/]}}parseable_output-[[OUTPUT:.*]].o"
// CHECK-NEXT: ],
// CHECK-NEXT: "inputs": [
// CHECK-NEXT: "{{.*[\\/]}}parseable_output.swift"
// CHECK-NEXT: ],
// CHECK-NEXT: "outputs": [
// CHECK-NEXT: {
// CHECK-NEXT: "type": "object",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output-[[OUTPUT]].o"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "type": "dependencies",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output-[[OUTPUT]].d"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "type": "swiftmodule",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output-[[OUTPUT]].swiftmodule"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "type": "swiftdoc",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output-[[OUTPUT]].swiftdoc"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "type": "swiftsourceinfo",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output-[[OUTPUT]].swiftsourceinfo"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "type": "diagnostics",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output-[[OUTPUT]].dia"
// CHECK-NEXT: }
// CHECK-NEXT: ],
// CHECK-NEXT: "pid": 1
// CHECK-NEXT: "process": {
// CHECK-NEXT: "real_pid": 1
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: {{[1-9][0-9]*}}
// CHECK-NEXT: {
// CHECK-NEXT: "kind": "finished",
// CHECK-NEXT: "name": "compile",
// CHECK-NEXT: "pid": 1,
// CHECK-NEXT: "output": "Output placeholder\n",
// CHECK-NEXT: "process": {
// CHECK-NEXT: "real_pid": 1
// CHECK-NEXT: },
// CHECK-NEXT: "exit-status": 0
// CHECK-NEXT: }
// CHECK-NEXT: {{[1-9][0-9]*}}
// CHECK-NEXT: {
// CHECK-NEXT: "kind": "began",
// CHECK-NEXT: "name": "merge-module",
// CHECK-NEXT: "command": "{{.*[\\/]}}swift{{(-frontend|c)?(\.exe)?(\\")?}} -frontend -merge-modules -emit-module {{.*[\\/]}}parseable_output-[[OUTPUT]].swiftmodule{{(\\")?}} {{.*}} -o {{.*[\\/]}}parseable_output.swift.tmp.swiftmodule{{(\\")?}}",
// CHECK-NEXT: "command_executable": "{{.*[\\/]}}swift{{(-frontend|c)?(\.exe)?}}",
// CHECK-NEXT: "command_arguments": [
// CHECK-NEXT: "-frontend",
// CHECK-NEXT: "-merge-modules",
// CHECK-NEXT: "-emit-module",
// CHECK-NEXT: "{{.*[\\/]}}parseable_output-[[OUTPUT]].swiftmodule",
// CHECK: "-o",
// CHECK-NEXT: "{{.*[\\/]}}parseable_output.swift.tmp.swiftmodule"
// CHECK-NEXT: ],
// CHECK-NEXT: "inputs": [
// CHECK-NEXT: "{{.*[\\/]}}parseable_output-[[OUTPUT]].o"
// CHECK-NEXT: ],
// CHECK-NEXT: "outputs": [
// CHECK-NEXT: {
// CHECK-NEXT: "type": "swiftmodule",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output.swift.tmp.swiftmodule"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "type": "swiftdoc",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output.swift.tmp.swiftdoc"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "type": "swiftsourceinfo",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output.swift.tmp.swiftsourceinfo"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "type": "clang-header",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output.swift.tmp.h"
// CHECK-NEXT: }
// CHECK-NEXT: ],
// CHECK-NEXT: "pid": 2,
// CHECK-NEXT: "process": {
// CHECK-NEXT: "real_pid": 2
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: {{[1-9][0-9]*}}
// CHECK-NEXT: {
// CHECK-NEXT: "kind": "finished",
// CHECK-NEXT: "name": "merge-module",
// CHECK-NEXT: "pid": 2,
// CHECK-NEXT: "output": "Output placeholder\n",
// CHECK-NEXT: "process": {
// CHECK-NEXT: "real_pid": 2
// CHECK-NEXT: },
// CHECK-NEXT: "exit-status": 0
// CHECK-NEXT: }
// CHECK-NEXT: {{[1-9][0-9]*}}
// CHECK-NEXT: {
// CHECK-NEXT: "kind": "began",
// CHECK-NEXT: "name": "link",
// CHECK-NEXT: "command": "{{.*[\\/](ld|clang)(\.exe)?(\\")?.*}}parseable_output-[[OUTPUT]].o{{(\\")?}} {{.*}}-o {{.*[\\/]}}parseable_output.swift.tmp.out{{(\\")?}}",
// CHECK-NEXT: "command_executable": "{{.*[\\/](ld|clang)(\.exe)?}}",
// CHECK-NEXT: "command_arguments": [
// CHECK: "{{.*[\\/]}}parseable_output-[[OUTPUT]].o",
// CHECK: "-o",
// CHECK-NEXT: "{{.*[\\/]}}parseable_output.swift.tmp.out"
// CHECK-NEXT: ],
// CHECK-NEXT: "inputs": [
// CHECK-NEXT: "{{.*[\\/]}}parseable_output-[[OUTPUT]].o"
// CHECK-NEXT: ],
// CHECK-NEXT: "outputs": [
// CHECK-NEXT: {
// CHECK-NEXT: "type": "image",
// CHECK-NEXT: "path": "{{.*[\\/]}}parseable_output.swift.tmp.out"
// CHECK-NEXT: }
// CHECK-NEXT: ],
// CHECK-NEXT: "pid": 3,
// CHECK-NEXT: "process": {
// CHECK-NEXT: "real_pid": 3
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: {{[1-9][0-9]*}}
// CHECK-NEXT: {
// CHECK-NEXT: "kind": "finished",
// CHECK-NEXT: "name": "link",
// CHECK-NEXT: "pid": 3,
// CHECK-NEXT: "output": "Output placeholder\n",
// CHECK-NEXT: "process": {
// CHECK-NEXT: "real_pid": 3
// CHECK-NEXT: },
// CHECK-NEXT: "exit-status": 0
// CHECK-NEXT: }
|
apache-2.0
|
d7eca75929865dc27a7d786efefcbff6
| 38.019355 | 248 | 0.522321 | 2.88 | false | false | true | false |
ben-ng/swift
|
validation-test/compiler_crashers_fixed/00873-no-stacktrace.swift
|
1
|
677
|
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func compose<U, T) {
class a: e)
struct c {
typealias e : A>(e: X<H : Sequence> S<h.Type) -> String {
d(Range())) {
}
var f == b<U {
}
}
static let end = a(f):Any, e: l) {
return self.f = [Byte](a(e? = B<d(v: c<T : b("\() -> String = T> d<T where T: Int = [1
func f.init(x, end)
|
apache-2.0
|
bacceaa78495ea156d7b3818d524752f
| 32.85 | 86 | 0.661743 | 2.969298 | false | false | false | false |
tardieu/swift
|
test/stdlib/RuntimeObjC.swift
|
4
|
26152
|
// RUN: rm -rf %t && mkdir -p %t
//
// RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g
// RUN: %target-build-swift -parse-stdlib -Xfrontend -disable-access-control -module-name a -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o %s -o %t.out
// RUN: %target-run %t.out
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Swift
import StdlibUnittest
import Foundation
import CoreGraphics
import SwiftShims
import MirrorObjC
var nsObjectCanaryCount = 0
@objc class NSObjectCanary : NSObject {
override init() {
nsObjectCanaryCount += 1
}
deinit {
nsObjectCanaryCount -= 1
}
}
struct NSObjectCanaryStruct {
var ref = NSObjectCanary()
}
var swiftObjectCanaryCount = 0
class SwiftObjectCanary {
init() {
swiftObjectCanaryCount += 1
}
deinit {
swiftObjectCanaryCount -= 1
}
}
struct SwiftObjectCanaryStruct {
var ref = SwiftObjectCanary()
}
@objc class ClassA {
init(value: Int) {
self.value = value
}
var value: Int
}
struct BridgedValueType : _ObjectiveCBridgeable {
init(value: Int) {
self.value = value
}
func _bridgeToObjectiveC() -> ClassA {
return ClassA(value: value)
}
static func _forceBridgeFromObjectiveC(
_ x: ClassA,
result: inout BridgedValueType?
) {
assert(x.value % 2 == 0, "not bridged to Objective-C")
result = BridgedValueType(value: x.value)
}
static func _conditionallyBridgeFromObjectiveC(
_ x: ClassA,
result: inout BridgedValueType?
) -> Bool {
if x.value % 2 == 0 {
result = BridgedValueType(value: x.value)
return true
}
result = nil
return false
}
static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?)
-> BridgedValueType {
var result: BridgedValueType?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
var value: Int
var canaryRef = SwiftObjectCanary()
}
struct BridgedLargeValueType : _ObjectiveCBridgeable {
init(value: Int) {
value0 = value
value1 = value
value2 = value
value3 = value
value4 = value
value5 = value
value6 = value
value7 = value
}
func _bridgeToObjectiveC() -> ClassA {
assert(value == value0)
return ClassA(value: value0)
}
static func _forceBridgeFromObjectiveC(
_ x: ClassA,
result: inout BridgedLargeValueType?
) {
assert(x.value % 2 == 0, "not bridged to Objective-C")
result = BridgedLargeValueType(value: x.value)
}
static func _conditionallyBridgeFromObjectiveC(
_ x: ClassA,
result: inout BridgedLargeValueType?
) -> Bool {
if x.value % 2 == 0 {
result = BridgedLargeValueType(value: x.value)
return true
}
result = nil
return false
}
static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?)
-> BridgedLargeValueType {
var result: BridgedLargeValueType?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
var value: Int {
let x = value0
assert(value0 == x && value1 == x && value2 == x && value3 == x &&
value4 == x && value5 == x && value6 == x && value7 == x)
return x
}
var (value0, value1, value2, value3): (Int, Int, Int, Int)
var (value4, value5, value6, value7): (Int, Int, Int, Int)
var canaryRef = SwiftObjectCanary()
}
class BridgedVerbatimRefType {
var value: Int = 42
var canaryRef = SwiftObjectCanary()
}
func withSwiftObjectCanary<T>(
_ createValue: () -> T,
_ check: (T) -> Void,
file: String = #file, line: UInt = #line
) {
let stackTrace = SourceLocStack(SourceLoc(file, line))
swiftObjectCanaryCount = 0
autoreleasepool {
var valueWithCanary = createValue()
expectEqual(1, swiftObjectCanaryCount, stackTrace: stackTrace)
check(valueWithCanary)
}
expectEqual(0, swiftObjectCanaryCount, stackTrace: stackTrace)
}
var Runtime = TestSuite("Runtime")
func _isClassOrObjCExistential_Opaque<T>(_ x: T.Type) -> Bool {
return _isClassOrObjCExistential(_opaqueIdentity(x))
}
Runtime.test("_isClassOrObjCExistential") {
expectTrue(_isClassOrObjCExistential(NSObjectCanary.self))
expectTrue(_isClassOrObjCExistential_Opaque(NSObjectCanary.self))
expectFalse(_isClassOrObjCExistential(NSObjectCanaryStruct.self))
expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanaryStruct.self))
expectTrue(_isClassOrObjCExistential(SwiftObjectCanary.self))
expectTrue(_isClassOrObjCExistential_Opaque(SwiftObjectCanary.self))
expectFalse(_isClassOrObjCExistential(SwiftObjectCanaryStruct.self))
expectFalse(_isClassOrObjCExistential_Opaque(SwiftObjectCanaryStruct.self))
typealias SwiftClosure = () -> ()
expectFalse(_isClassOrObjCExistential(SwiftClosure.self))
expectFalse(_isClassOrObjCExistential_Opaque(SwiftClosure.self))
typealias ObjCClosure = @convention(block) () -> ()
expectTrue(_isClassOrObjCExistential(ObjCClosure.self))
expectTrue(_isClassOrObjCExistential_Opaque(ObjCClosure.self))
expectTrue(_isClassOrObjCExistential(CFArray.self))
expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self))
expectTrue(_isClassOrObjCExistential(CFArray.self))
expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self))
expectTrue(_isClassOrObjCExistential(AnyObject.self))
expectTrue(_isClassOrObjCExistential_Opaque(AnyObject.self))
// AnyClass == AnyObject.Type
expectFalse(_isClassOrObjCExistential(AnyClass.self))
expectFalse(_isClassOrObjCExistential_Opaque(AnyClass.self))
expectFalse(_isClassOrObjCExistential(AnyObject.Protocol.self))
expectFalse(_isClassOrObjCExistential_Opaque(AnyObject.Protocol.self))
expectFalse(_isClassOrObjCExistential(NSObjectCanary.Type.self))
expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanary.Type.self))
}
Runtime.test("_canBeClass") {
expectEqual(1, _canBeClass(NSObjectCanary.self))
expectEqual(0, _canBeClass(NSObjectCanaryStruct.self))
typealias ObjCClosure = @convention(block) () -> ()
expectEqual(1, _canBeClass(ObjCClosure.self))
expectEqual(1, _canBeClass(CFArray.self))
}
Runtime.test("bridgeToObjectiveC") {
expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedValueType(value: 42)) as! ClassA).value)
expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedLargeValueType(value: 42)) as! ClassA).value)
var bridgedVerbatimRef = BridgedVerbatimRefType()
expectTrue(_bridgeAnythingToObjectiveC(bridgedVerbatimRef) === bridgedVerbatimRef)
}
Runtime.test("bridgeToObjectiveC/NoLeak") {
withSwiftObjectCanary(
{ BridgedValueType(value: 42) },
{ expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) })
withSwiftObjectCanary(
{ BridgedLargeValueType(value: 42) },
{ expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) })
withSwiftObjectCanary(
{ BridgedVerbatimRefType() },
{ expectTrue(_bridgeAnythingToObjectiveC($0) === $0) })
}
Runtime.test("forceBridgeFromObjectiveC") {
// Bridge back using BridgedValueType.
expectNil(_conditionallyBridgeFromObjectiveC(
ClassA(value: 21), BridgedValueType.self))
expectEqual(42, _forceBridgeFromObjectiveC(
ClassA(value: 42), BridgedValueType.self).value)
expectEqual(42, _conditionallyBridgeFromObjectiveC(
ClassA(value: 42), BridgedValueType.self)!.value)
expectNil(_conditionallyBridgeFromObjectiveC(
BridgedVerbatimRefType(), BridgedValueType.self))
// Bridge back using BridgedLargeValueType.
expectNil(_conditionallyBridgeFromObjectiveC(
ClassA(value: 21), BridgedLargeValueType.self))
expectEqual(42, _forceBridgeFromObjectiveC(
ClassA(value: 42), BridgedLargeValueType.self).value)
expectEqual(42, _conditionallyBridgeFromObjectiveC(
ClassA(value: 42), BridgedLargeValueType.self)!.value)
expectNil(_conditionallyBridgeFromObjectiveC(
BridgedVerbatimRefType(), BridgedLargeValueType.self))
// Bridge back using BridgedVerbatimRefType.
expectNil(_conditionallyBridgeFromObjectiveC(
ClassA(value: 21), BridgedVerbatimRefType.self))
expectNil(_conditionallyBridgeFromObjectiveC(
ClassA(value: 42), BridgedVerbatimRefType.self))
var bridgedVerbatimRef = BridgedVerbatimRefType()
expectTrue(_forceBridgeFromObjectiveC(
bridgedVerbatimRef, BridgedVerbatimRefType.self) === bridgedVerbatimRef)
expectTrue(_conditionallyBridgeFromObjectiveC(
bridgedVerbatimRef, BridgedVerbatimRefType.self)! === bridgedVerbatimRef)
}
Runtime.test("isBridgedToObjectiveC") {
expectTrue(_isBridgedToObjectiveC(BridgedValueType))
expectTrue(_isBridgedToObjectiveC(BridgedVerbatimRefType))
}
Runtime.test("isBridgedVerbatimToObjectiveC") {
expectFalse(_isBridgedVerbatimToObjectiveC(BridgedValueType))
expectTrue(_isBridgedVerbatimToObjectiveC(BridgedVerbatimRefType))
}
//===----------------------------------------------------------------------===//
class SomeClass {}
@objc class SomeObjCClass {}
class SomeNSObjectSubclass : NSObject {}
Runtime.test("typeName") {
expectEqual("a.SomeObjCClass", _typeName(SomeObjCClass.self))
expectEqual("a.SomeNSObjectSubclass", _typeName(SomeNSObjectSubclass.self))
expectEqual("NSObject", _typeName(NSObject.self))
var a : Any = SomeObjCClass()
expectEqual("a.SomeObjCClass", _typeName(type(of: a)))
a = SomeNSObjectSubclass()
expectEqual("a.SomeNSObjectSubclass", _typeName(type(of: a)))
a = NSObject()
expectEqual("NSObject", _typeName(type(of: a)))
}
class GenericClass<T> {}
class MultiGenericClass<T, U> {}
struct GenericStruct<T> {}
enum GenericEnum<T> {}
struct PlainStruct {}
enum PlainEnum {}
protocol ProtocolA {}
protocol ProtocolB {}
Runtime.test("Generic class ObjC runtime names") {
expectEqual("_TtGC1a12GenericClassSi_",
NSStringFromClass(GenericClass<Int>.self))
expectEqual("_TtGC1a12GenericClassVS_11PlainStruct_",
NSStringFromClass(GenericClass<PlainStruct>.self))
expectEqual("_TtGC1a12GenericClassOS_9PlainEnum_",
NSStringFromClass(GenericClass<PlainEnum>.self))
expectEqual("_TtGC1a12GenericClassTVS_11PlainStructOS_9PlainEnumS1___",
NSStringFromClass(GenericClass<(PlainStruct, PlainEnum, PlainStruct)>.self))
expectEqual("_TtGC1a12GenericClassMVS_11PlainStruct_",
NSStringFromClass(GenericClass<PlainStruct.Type>.self))
expectEqual("_TtGC1a12GenericClassFMVS_11PlainStructS1__",
NSStringFromClass(GenericClass<(PlainStruct.Type) -> PlainStruct>.self))
expectEqual("_TtGC1a12GenericClassFzMVS_11PlainStructS1__",
NSStringFromClass(GenericClass<(PlainStruct.Type) throws -> PlainStruct>.self))
expectEqual("_TtGC1a12GenericClassFTVS_11PlainStructROS_9PlainEnum_Si_",
NSStringFromClass(GenericClass<(PlainStruct, inout PlainEnum) -> Int>.self))
expectEqual("_TtGC1a12GenericClassPS_9ProtocolA__",
NSStringFromClass(GenericClass<ProtocolA>.self))
expectEqual("_TtGC1a12GenericClassPS_9ProtocolAS_9ProtocolB__",
NSStringFromClass(GenericClass<ProtocolA & ProtocolB>.self))
expectEqual("_TtGC1a12GenericClassPMPS_9ProtocolAS_9ProtocolB__",
NSStringFromClass(GenericClass<(ProtocolA & ProtocolB).Type>.self))
expectEqual("_TtGC1a12GenericClassMPS_9ProtocolAS_9ProtocolB__",
NSStringFromClass(GenericClass<(ProtocolB & ProtocolA).Protocol>.self))
expectEqual("_TtGC1a12GenericClassCSo7CFArray_",
NSStringFromClass(GenericClass<CFArray>.self))
expectEqual("_TtGC1a12GenericClassVSC7Decimal_",
NSStringFromClass(GenericClass<Decimal>.self))
expectEqual("_TtGC1a12GenericClassCSo8NSObject_",
NSStringFromClass(GenericClass<NSObject>.self))
expectEqual("_TtGC1a12GenericClassCSo8NSObject_",
NSStringFromClass(GenericClass<NSObject>.self))
expectEqual("_TtGC1a12GenericClassPSo9NSCopying__",
NSStringFromClass(GenericClass<NSCopying>.self))
expectEqual("_TtGC1a12GenericClassPSo9NSCopyingS_9ProtocolAS_9ProtocolB__",
NSStringFromClass(GenericClass<ProtocolB & NSCopying & ProtocolA>.self))
expectEqual("_TtGC1a17MultiGenericClassGVS_13GenericStructSi_GOS_11GenericEnumGS2_Si___",
NSStringFromClass(MultiGenericClass<GenericStruct<Int>,
GenericEnum<GenericEnum<Int>>>.self))
}
Runtime.test("typeByName") {
// Make sure we don't crash if we have foreign classes in the
// table -- those don't have NominalTypeDescriptors
print(CFArray.self)
expectTrue(_typeByName("a.SomeClass") == SomeClass.self)
expectTrue(_typeByName("DoesNotExist") == nil)
}
Runtime.test("casting AnyObject to class metatypes") {
do {
var ao: AnyObject = SomeClass.self
expectTrue(ao as? Any.Type == SomeClass.self)
expectTrue(ao as? AnyClass == SomeClass.self)
expectTrue(ao as? SomeClass.Type == SomeClass.self)
}
do {
var ao : AnyObject = SomeNSObjectSubclass()
expectTrue(ao as? Any.Type == nil)
expectTrue(ao as? AnyClass == nil)
ao = SomeNSObjectSubclass.self
expectTrue(ao as? Any.Type == SomeNSObjectSubclass.self)
expectTrue(ao as? AnyClass == SomeNSObjectSubclass.self)
expectTrue(ao as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self)
}
do {
var a : Any = SomeNSObjectSubclass()
expectTrue(a as? Any.Type == nil)
expectTrue(a as? AnyClass == nil)
}
do {
var nso: NSObject = SomeNSObjectSubclass()
expectTrue(nso as? AnyClass == nil)
nso = (SomeNSObjectSubclass.self as AnyObject) as! NSObject
expectTrue(nso as? Any.Type == SomeNSObjectSubclass.self)
expectTrue(nso as? AnyClass == SomeNSObjectSubclass.self)
expectTrue(nso as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self)
}
}
var RuntimeFoundationWrappers = TestSuite("RuntimeFoundationWrappers")
RuntimeFoundationWrappers.test("_stdlib_NSObject_isEqual/NoLeak") {
nsObjectCanaryCount = 0
autoreleasepool {
let a = NSObjectCanary()
let b = NSObjectCanary()
expectEqual(2, nsObjectCanaryCount)
_stdlib_NSObject_isEqual(a, b)
}
expectEqual(0, nsObjectCanaryCount)
}
var nsStringCanaryCount = 0
@objc class NSStringCanary : NSString {
override init() {
nsStringCanaryCount += 1
super.init()
}
required init(coder: NSCoder) {
fatalError("don't call this initializer")
}
deinit {
nsStringCanaryCount -= 1
}
@objc override var length: Int {
return 0
}
@objc override func character(at index: Int) -> unichar {
fatalError("out-of-bounds access")
}
}
RuntimeFoundationWrappers.test(
"_stdlib_compareNSStringDeterministicUnicodeCollation/NoLeak"
) {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
let b = NSStringCanary()
expectEqual(2, nsStringCanaryCount)
_stdlib_compareNSStringDeterministicUnicodeCollation(a, b)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test(
"_stdlib_compareNSStringDeterministicUnicodeCollationPtr/NoLeak"
) {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
let b = NSStringCanary()
expectEqual(2, nsStringCanaryCount)
let ptrA = unsafeBitCast(a, to: OpaquePointer.self)
let ptrB = unsafeBitCast(b, to: OpaquePointer.self)
_stdlib_compareNSStringDeterministicUnicodeCollationPointer(ptrA, ptrB)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringHashValue/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_NSStringHashValue(a, true)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringHashValueNonASCII/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_NSStringHashValue(a, false)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringHashValuePointer/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
let ptrA = unsafeBitCast(a, to: OpaquePointer.self)
_stdlib_NSStringHashValuePointer(ptrA, true)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringHashValuePointerNonASCII/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
let ptrA = unsafeBitCast(a, to: OpaquePointer.self)
_stdlib_NSStringHashValuePointer(ptrA, false)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringHasPrefixNFDPointer/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
let b = NSStringCanary()
expectEqual(2, nsStringCanaryCount)
let ptrA = unsafeBitCast(a, to: OpaquePointer.self)
let ptrB = unsafeBitCast(b, to: OpaquePointer.self)
_stdlib_NSStringHasPrefixNFDPointer(ptrA, ptrB)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringHasSuffixNFDPointer/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
let b = NSStringCanary()
expectEqual(2, nsStringCanaryCount)
let ptrA = unsafeBitCast(a, to: OpaquePointer.self)
let ptrB = unsafeBitCast(b, to: OpaquePointer.self)
_stdlib_NSStringHasSuffixNFDPointer(ptrA, ptrB)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringHasPrefixNFD/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
let b = NSStringCanary()
expectEqual(2, nsStringCanaryCount)
_stdlib_NSStringHasPrefixNFD(a, b)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringHasSuffixNFD/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
let b = NSStringCanary()
expectEqual(2, nsStringCanaryCount)
_stdlib_NSStringHasSuffixNFD(a, b)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringLowercaseString/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_NSStringLowercaseString(a)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_NSStringUppercaseString/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_NSStringUppercaseString(a)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_CFStringCreateCopy/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_binary_CFStringCreateCopy(a)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_CFStringGetLength/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_binary_CFStringGetLength(a)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("_stdlib_CFStringGetCharactersPtr/NoLeak") {
nsStringCanaryCount = 0
autoreleasepool {
let a = NSStringCanary()
expectEqual(1, nsStringCanaryCount)
_stdlib_binary_CFStringGetCharactersPtr(a)
}
expectEqual(0, nsStringCanaryCount)
}
RuntimeFoundationWrappers.test("bridgedNSArray") {
var c = [NSObject]()
autoreleasepool {
let a = [NSObject]()
let b = a as NSArray
c = b as! [NSObject]
}
c.append(NSObject())
// expect no crash.
}
var Reflection = TestSuite("Reflection")
class SwiftFooMoreDerivedObjCClass : FooMoreDerivedObjCClass {
let first: Int = 123
let second: String = "abc"
}
Reflection.test("Class/ObjectiveCBase/Default") {
do {
let value = SwiftFooMoreDerivedObjCClass()
var output = ""
dump(value, to: &output)
let expected =
"▿ This is FooObjCClass #0\n" +
" - super: FooMoreDerivedObjCClass\n" +
" - super: FooDerivedObjCClass\n" +
" - super: FooObjCClass\n" +
" - super: NSObject\n" +
" - first: 123\n" +
" - second: \"abc\"\n"
expectEqual(expected, output)
}
}
protocol SomeNativeProto {}
@objc protocol SomeObjCProto {}
extension SomeClass: SomeObjCProto {}
Reflection.test("MetatypeMirror") {
do {
let concreteClassMetatype = SomeClass.self
let expectedSomeClass = "- a.SomeClass #0\n"
let objcProtocolMetatype: SomeObjCProto.Type = SomeClass.self
var output = ""
dump(objcProtocolMetatype, to: &output)
expectEqual(expectedSomeClass, output)
let objcProtocolConcreteMetatype = SomeObjCProto.self
let expectedObjCProtocolConcrete = "- a.SomeObjCProto #0\n"
output = ""
dump(objcProtocolConcreteMetatype, to: &output)
expectEqual(expectedObjCProtocolConcrete, output)
let compositionConcreteMetatype = (SomeNativeProto & SomeObjCProto).self
let expectedComposition = "- a.SomeObjCProto & a.SomeNativeProto #0\n"
output = ""
dump(compositionConcreteMetatype, to: &output)
expectEqual(expectedComposition, output)
let objcDefinedProtoType = NSObjectProtocol.self
expectEqual(String(describing: objcDefinedProtoType), "NSObject")
}
}
Reflection.test("CGPoint") {
var output = ""
dump(CGPoint(x: 1.25, y: 2.75), to: &output)
let expected =
"▿ (1.25, 2.75)\n" +
" - x: 1.25\n" +
" - y: 2.75\n"
expectEqual(expected, output)
}
Reflection.test("CGSize") {
var output = ""
dump(CGSize(width: 1.25, height: 2.75), to: &output)
let expected =
"▿ (1.25, 2.75)\n" +
" - width: 1.25\n" +
" - height: 2.75\n"
expectEqual(expected, output)
}
Reflection.test("CGRect") {
var output = ""
dump(
CGRect(
origin: CGPoint(x: 1.25, y: 2.25),
size: CGSize(width: 10.25, height: 11.75)),
to: &output)
let expected =
"▿ (1.25, 2.25, 10.25, 11.75)\n" +
" ▿ origin: (1.25, 2.25)\n" +
" - x: 1.25\n" +
" - y: 2.25\n" +
" ▿ size: (10.25, 11.75)\n" +
" - width: 10.25\n" +
" - height: 11.75\n"
expectEqual(expected, output)
}
Reflection.test("Unmanaged/nil") {
var output = ""
var optionalURL: Unmanaged<CFURL>?
dump(optionalURL, to: &output)
let expected = "- nil\n"
expectEqual(expected, output)
}
Reflection.test("Unmanaged/not-nil") {
var output = ""
var optionalURL: Unmanaged<CFURL>? =
Unmanaged.passRetained(CFURLCreateWithString(nil, "http://llvm.org/" as CFString, nil))
dump(optionalURL, to: &output)
let expected =
"▿ Optional(Swift.Unmanaged<__ObjC.CFURL>(_value: http://llvm.org/))\n" +
" ▿ some: Swift.Unmanaged<__ObjC.CFURL>\n" +
" - _value: http://llvm.org/ #0\n" +
" - super: NSObject\n"
expectEqual(expected, output)
optionalURL!.release()
}
Reflection.test("TupleMirror/NoLeak") {
do {
nsObjectCanaryCount = 0
autoreleasepool {
var tuple = (1, NSObjectCanary())
expectEqual(1, nsObjectCanaryCount)
var output = ""
dump(tuple, to: &output)
}
expectEqual(0, nsObjectCanaryCount)
}
do {
nsObjectCanaryCount = 0
autoreleasepool {
var tuple = (1, NSObjectCanaryStruct())
expectEqual(1, nsObjectCanaryCount)
var output = ""
dump(tuple, to: &output)
}
expectEqual(0, nsObjectCanaryCount)
}
do {
swiftObjectCanaryCount = 0
autoreleasepool {
var tuple = (1, SwiftObjectCanary())
expectEqual(1, swiftObjectCanaryCount)
var output = ""
dump(tuple, to: &output)
}
expectEqual(0, swiftObjectCanaryCount)
}
do {
swiftObjectCanaryCount = 0
autoreleasepool {
var tuple = (1, SwiftObjectCanaryStruct())
expectEqual(1, swiftObjectCanaryCount)
var output = ""
dump(tuple, to: &output)
}
expectEqual(0, swiftObjectCanaryCount)
}
}
class TestArtificialSubclass: NSObject {
dynamic var foo = "foo"
}
var KVOHandle = 0
Reflection.test("Name of metatype of artificial subclass") {
let obj = TestArtificialSubclass()
expectEqual("\(type(of: obj))", "TestArtificialSubclass")
expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass")
expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass")
// Trigger the creation of a KVO subclass for TestArtificialSubclass.
obj.addObserver(obj, forKeyPath: "foo", options: [.new], context: &KVOHandle)
expectEqual("\(type(of: obj))", "TestArtificialSubclass")
expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass")
expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass")
obj.removeObserver(obj, forKeyPath: "foo")
expectEqual("\(type(of: obj))", "TestArtificialSubclass")
expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass")
expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass")
}
@objc class StringConvertibleInDebugAndOtherwise : NSObject {
override var description: String { return "description" }
override var debugDescription: String { return "debugDescription" }
}
Reflection.test("NSObject is properly CustomDebugStringConvertible") {
let object = StringConvertibleInDebugAndOtherwise()
expectEqual(String(reflecting: object), object.debugDescription)
}
Reflection.test("NSRange QuickLook") {
let rng = NSRange(location:Int.min, length:5)
let ql = PlaygroundQuickLook(reflecting: rng)
switch ql {
case .range(let loc, let len):
expectEqual(loc, Int64(Int.min))
expectEqual(len, 5)
default:
expectUnreachable("PlaygroundQuickLook for NSRange did not match Range")
}
}
class SomeSubclass : SomeClass {}
var ObjCConformsToProtocolTestSuite = TestSuite("ObjCConformsToProtocol")
ObjCConformsToProtocolTestSuite.test("cast/instance") {
expectTrue(SomeClass() is SomeObjCProto)
expectTrue(SomeSubclass() is SomeObjCProto)
}
ObjCConformsToProtocolTestSuite.test("cast/metatype") {
expectTrue(SomeClass.self is SomeObjCProto.Type)
expectTrue(SomeSubclass.self is SomeObjCProto.Type)
}
runAllTests()
|
apache-2.0
|
14a35460c40e4d24a2947e85504686f2
| 29.110599 | 149 | 0.716215 | 4.506207 | false | true | false | false |
TG908/iOS
|
TUM Campus App/CardViewController.swift
|
1
|
4969
|
//
// ViewController.swift
// TUM Campus App
//
// Created by Mathias Quintero on 10/28/15.
// Copyright © 2015 LS1 TUM. All rights reserved.
//
import Sweeft
import UIKit
import MCSwipeTableViewCell
class CardViewController: UITableViewController {
var manager: TumDataManager?
var cards = [DataElement]()
var nextLecture: CalendarRow?
var refresh = UIRefreshControl()
func refresh(_ sender: AnyObject?) {
manager?.getCardItems(self)
}
}
extension CardViewController: ImageDownloadSubscriber, DetailViewDelegate {
func updateImageView() {
tableView.reloadData()
}
func dataManager() -> TumDataManager {
return manager ?? TumDataManager(user: nil)
}
}
extension CardViewController: TumDataReceiver {
func receiveData(_ data: [DataElement]) {
if cards.count <= data.count {
for item in data {
if let movieItem = item as? Movie {
movieItem.subscribeToImage(self)
}
if let lectureItem = item as? CalendarRow {
nextLecture = lectureItem
}
}
cards = data
tableView.reloadData()
}
refresh.endRefreshing()
}
}
extension CardViewController {
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "logo-blue")
let imageView = UIImageView(image:logo)
imageView.contentMode = UIViewContentMode.scaleAspectFit
self.navigationItem.titleView = imageView
if let bounds = imageView.superview?.bounds {
imageView.frame = CGRect(x: bounds.origin.x+10, y: bounds.origin.y+10, width: bounds.width-20, height: bounds.height-20)
}
refresh.addTarget(self, action: #selector(CardViewController.refresh(_:)), for: UIControlEvents.valueChanged)
tableView.addSubview(refresh)
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
imageView.clipsToBounds = true
tableView.tableFooterView = UIView(frame: CGRect.zero)
tableView.separatorColor = UIColor.clear
tableView.backgroundColor = Constants.backgroundGray
manager = (self.tabBarController as? CampusTabBarController)?.manager
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cards.removeAll()
refresh(nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if var mvc = segue.destination as? DetailView {
mvc.delegate = self
}
if let mvc = segue.destination as? CalendarViewController {
mvc.nextLectureItem = nextLecture
}
}
}
extension CardViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return max(cards.count, 1)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = cards | indexPath.row ?? EmptyCard()
let cell = tableView.dequeueReusableCell(withIdentifier: item.getCellIdentifier()) as? CardTableViewCell ?? CardTableViewCell()
cell.setElement(item)
let handler = { () -> () in
if let path = self.tableView.indexPath(for: cell) {
PersistentCardOrder.value.remove(cardFor: item)
if !self.cards.isEmpty {
self.cards.remove(at: path.row)
}
if !self.cards.isEmpty {
self.tableView.deleteRows(at: [path], with: UITableViewRowAnimation.top)
} else {
self.tableView.reloadData()
}
}
}
cell.selectionStyle = .none
cell.defaultColor = tableView.backgroundColor
cell.setSwipeGestureWith(UIView(), color: tableView.backgroundColor, mode: MCSwipeTableViewCellMode.exit, state: MCSwipeTableViewCellState.state1) { (void) in handler() }
cell.setSwipeGestureWith(UIView(), color: tableView.backgroundColor, mode: MCSwipeTableViewCellMode.exit, state: MCSwipeTableViewCellState.state2) { (void) in handler() }
cell.setSwipeGestureWith(UIView(), color: tableView.backgroundColor, mode: MCSwipeTableViewCellMode.exit, state: MCSwipeTableViewCellState.state3) { (void) in handler() }
cell.setSwipeGestureWith(UIView(), color: tableView.backgroundColor, mode: MCSwipeTableViewCellMode.exit, state: MCSwipeTableViewCellState.state4) { (void) in handler() }
return cell
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return true
}
}
|
gpl-3.0
|
49d99830dbac78c419695af21e51e9d5
| 34.234043 | 178 | 0.63909 | 4.953141 | false | false | false | false |
treejames/firefox-ios
|
Account/FxALoginStateMachine.swift
|
3
|
9100
|
/* 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 FxA
import Shared
import XCGLogger
// TODO: log to an FxA-only, persistent log file.
private let log = Logger.syncLogger
// TODO: fill this in!
private let KeyUnwrappingError = NSError(domain: "org.mozilla", code: 1, userInfo: nil)
protocol FxALoginClient {
func keyPair() -> Deferred<Result<KeyPair>>
func keys(keyFetchToken: NSData) -> Deferred<Result<FxAKeysResponse>>
func sign(sessionToken: NSData, publicKey: PublicKey) -> Deferred<Result<FxASignResponse>>
}
extension FxAClient10: FxALoginClient {
func keyPair() -> Deferred<Result<KeyPair>> {
let result = RSAKeyPair.generateKeyPairWithModulusSize(2048) // TODO: debate key size and extract this constant.
return Deferred(value: Result(success: result))
}
}
class FxALoginStateMachine {
let client: FxALoginClient
// The keys are used as a set, to prevent cycles in the state machine.
var stateLabelsSeen = [FxAStateLabel: Bool]()
init(client: FxALoginClient) {
self.client = client
}
func advanceFromState(state: FxAState, now: Timestamp) -> Deferred<FxAState> {
stateLabelsSeen.updateValue(true, forKey: state.label)
return self.advanceOneState(state, now: now).bind { (newState: FxAState) in
let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: newState.label) != nil
if labelAlreadySeen {
// Last stop!
return Deferred(value: newState)
}
return self.advanceFromState(newState, now: now)
}
}
private func advanceOneState(state: FxAState, now: Timestamp) -> Deferred<FxAState> {
// For convenience. Without type annotation, Swift complains about types not being exact.
let separated: Deferred<FxAState> = Deferred(value: SeparatedState())
let doghouse: Deferred<FxAState> = Deferred(value: DoghouseState())
let same: Deferred<FxAState> = Deferred(value: state)
log.info("Advancing from state: \(state.label.rawValue)")
switch state.label {
case .Married:
let state = state as! MarriedState
log.debug("Checking key pair freshness.")
if state.isKeyPairExpired(now) {
log.info("Key pair has expired; transitioning to CohabitingBeforeKeyPair.")
return advanceOneState(state.withoutKeyPair(), now: now)
}
log.debug("Checking certificate freshness.")
if state.isCertificateExpired(now) {
log.info("Certificate has expired; transitioning to CohabitingAfterKeyPair.")
return advanceOneState(state.withoutCertificate(), now: now)
}
log.info("Key pair and certificate are fresh; staying Married.")
return same
case .CohabitingBeforeKeyPair:
let state = state as! CohabitingBeforeKeyPairState
log.debug("Generating key pair.")
return self.client.keyPair().bind { result in
if let keyPair = result.successValue {
log.info("Generated key pair! Transitioning to CohabitingAfterKeyPair.")
let newState = CohabitingAfterKeyPairState(sessionToken: state.sessionToken,
kA: state.kA, kB: state.kB,
keyPair: keyPair, keyPairExpiresAt: now + OneMonthInMilliseconds)
return Deferred(value: newState)
} else {
log.error("Failed to generate key pair! Something is horribly wrong; transitioning to Separated in the hope that the error is transient.")
return separated
}
}
case .CohabitingAfterKeyPair:
let state = state as! CohabitingAfterKeyPairState
log.debug("Signing public key.")
return client.sign(state.sessionToken, publicKey: state.keyPair.publicKey).bind { result in
if let response = result.successValue {
log.info("Signed public key! Transitioning to Married.")
let newState = MarriedState(sessionToken: state.sessionToken,
kA: state.kA, kB: state.kB,
keyPair: state.keyPair, keyPairExpiresAt: state.keyPairExpiresAt,
certificate: response.certificate, certificateExpiresAt: now + OneDayInMilliseconds)
return Deferred(value: newState)
} else {
if let error = result.failureValue as? FxAClientError {
switch error {
case let .Remote(remoteError):
if remoteError.isUpgradeRequired {
log.error("Upgrade required: \(error.description)! Transitioning to Doghouse.")
return doghouse
} else if remoteError.isInvalidAuthentication {
log.error("Invalid authentication: \(error.description)! Transitioning to Separated.")
return separated
} else if remoteError.code < 200 || remoteError.code >= 300 {
log.error("Unsuccessful HTTP request: \(error.description)! Assuming error is transient and not transitioning.")
return same
} else {
log.error("Unknown error: \(error.description). Transitioning to Separated.")
return separated
}
default:
break
}
}
log.error("Unknown error: \(result.failureValue!). Transitioning to Separated.")
return separated
}
}
case .EngagedBeforeVerified, .EngagedAfterVerified:
let state = state as! ReadyForKeys
log.debug("Fetching keys.")
return client.keys(state.keyFetchToken).bind { result in
if let response = result.successValue {
if let kB = response.wrapkB.xoredWith(state.unwrapkB) {
log.info("Unwrapped keys response. Transition to CohabitingBeforeKeyPair.")
let newState = CohabitingBeforeKeyPairState(sessionToken: state.sessionToken,
kA: response.kA, kB: kB)
return Deferred(value: newState)
} else {
log.error("Failed to unwrap keys response! Transitioning to Separated in order to fetch new initial datum.")
return separated
}
} else {
if let error = result.failureValue as? FxAClientError {
log.error("Error \(error.description) \(error.description)")
switch error {
case let .Remote(remoteError):
if remoteError.isUpgradeRequired {
log.error("Upgrade required: \(error.description)! Transitioning to Doghouse.")
return doghouse
} else if remoteError.isInvalidAuthentication {
log.error("Invalid authentication: \(error.description)! Transitioning to Separated in order to fetch new initial datum.")
return separated
} else if remoteError.isUnverified {
log.warning("Account is not yet verified; not transitioning.")
return same
} else if remoteError.code < 200 || remoteError.code >= 300 {
log.error("Unsuccessful HTTP request: \(error.description)! Assuming error is transient and not transitioning.")
return same
} else {
log.error("Unknown error: \(error.description). Transitioning to Separated.")
return separated
}
default:
break
}
}
log.error("Unknown error: \(result.failureValue!). Transitioning to Separated.")
return separated
}
}
case .Separated, .Doghouse:
// We can't advance from the separated state (we need user input) or the doghouse (we need a client upgrade).
log.warning("User interaction required; not transitioning.")
return same
}
}
}
|
mpl-2.0
|
19e354e9c50c2748ce57c9b1e1cd176f
| 50.412429 | 159 | 0.556923 | 5.719673 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/View/HomeSplash/VHomeSplash.swift
|
1
|
4484
|
import UIKit
class VHomeSplash:View, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var collectionView:VCollection!
private weak var viewBackground:VHomeSplashBackground!
private let kCollectionBottom:CGFloat = 20
required init(controller:UIViewController)
{
super.init(controller:controller)
guard
let controller:CHomeSplash = controller as? CHomeSplash
else
{
return
}
let viewBackground:VHomeSplashBackground = VHomeSplashBackground(controller:controller)
self.viewBackground = viewBackground
let collectionView:VCollection = VCollection()
collectionView.alwaysBounceVertical = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerCell(cell:VHomeSplashCellOptions.self)
collectionView.registerCell(cell:VHomeSplashCellScore.self)
collectionView.registerCell(cell:VHomeSplashCellDescr.self)
self.collectionView = collectionView
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.sectionInset = UIEdgeInsets(
top:viewBackground.kHeight,
left:0,
bottom:kCollectionBottom,
right:0)
}
addSubview(viewBackground)
addSubview(collectionView)
NSLayoutConstraint.topToTop(
view:viewBackground,
toView:self)
viewBackground.layoutHeight = NSLayoutConstraint.height(
view:viewBackground,
constant:viewBackground.kHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBackground,
toView:self)
NSLayoutConstraint.equals(
view:collectionView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MHomeSplashProtocol
{
let controller:CHomeSplash = self.controller as! CHomeSplash
let item:MHomeSplashProtocol = controller.model.items[index.item]
return item
}
//MARK: public
func refresh()
{
collectionView.reloadData()
}
//MARK: collectionView delegate
func scrollViewDidScroll(_ scrollView:UIScrollView)
{
let offsetY:CGFloat = scrollView.contentOffset.y
var imageScaled:CGFloat = viewBackground.kHeight - offsetY
if imageScaled < 0
{
imageScaled = 0
}
viewBackground.layoutHeight.constant = imageScaled
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let item:MHomeSplashProtocol = modelAtIndex(index:indexPath)
let width:CGFloat = collectionView.bounds.maxX
let height:CGFloat = item.cellHeightFor(width:width)
let size:CGSize = CGSize(width:width, height:height)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let controller:CHomeSplash = self.controller as! CHomeSplash
let count:Int = controller.model.items.count
return count
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let controller:CHomeSplash = self.controller as! CHomeSplash
let item:MHomeSplashProtocol = modelAtIndex(index:indexPath)
let cell:VHomeSplashCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
item.reusableIdentifier,
for:indexPath) as! VHomeSplashCell
cell.config(controller:controller, model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool
{
return false
}
func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool
{
return false
}
}
|
mit
|
f2a35de2a967889345a682cc5e4d7c02
| 30.356643 | 155 | 0.649197 | 5.756098 | false | false | false | false |
zxwWei/SwfitZeng
|
XWWeibo接收数据/XWWeibo/Classes/Model(模型)/Compose(发微博)/View/XWPlacerholderTextView.swift
|
1
|
2520
|
//
// XWPlacerholderTextView.swift
// XWWeibo
//
// Created by apple1 on 15/11/4.
// Copyright © 2015年 ZXW. All rights reserved.
//
import UIKit
// MARK: - 自定义textview 添加隐式文字
class XWPlacerholderTextView: UITextView {
// placehoder
var placerdoler: String? {
didSet {
placeholerlabel.text = placerdoler
placeholerlabel.sizeToFit()
}
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
prepareUI()
// 添加通知事件,当textview里面的内容发生改变的时候,监听通知 object通知的发送者
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange:", name: UITextViewTextDidChangeNotification, object: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - 准备UI
private func prepareUI() {
addSubview(placeholerlabel)
placeholerlabel.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: placeholerlabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
addConstraint(NSLayoutConstraint(item: placeholerlabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
}
// MARK: - bug 私有的属性和方法要加@obj 记得将自己也传过来
func textDidChange(notificition: NSNotification){
// 能到这里来说明是当前这个textView文本改变了
// 判断文本是否为空: hasText()
// 当有文字的时候就隐藏
placeholerlabel.hidden = hasText()
}
// 移除通知
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// placehoderLabel
// 外界要使用 不要私有
private lazy var placeholerlabel: UILabel = {
let label = UILabel()
// 设置字体大小
label.font = UIFont.systemFontOfSize(18)
// 设置文字颜色
label.textColor = UIColor.lightGrayColor()
return label
}()
}
|
apache-2.0
|
a88e542882908df4790db728bc585fb3
| 26.682927 | 211 | 0.624063 | 4.556225 | false | false | false | false |
shinancao/ImageCycleScrollView
|
Demo/ViewController.swift
|
1
|
1739
|
//
// ViewController.swift
// ImageCycleScrollViewDemo
//
// Created by zhangnan on 2017/7/5.
// Copyright © 2017年 ZhangNan. All rights reserved.
//
import UIKit
import ImageCycleScrollView
class ViewController: UIViewController {
let cycleScrollView: ImageCycleScrollView = {
let `self` = ImageCycleScrollView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 177))
self.pageControlShowStyle = .center
self.pageControl?.currentPageIndicatorTintColor = UIColor.purple
return self
}()
@IBOutlet weak var cycleScrollView_sb: ImageCycleScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.addSubview(cycleScrollView)
let testImageUrls = ["http://ojx1pmrk7.bkt.clouddn.com/ALetterToMe.jpg", "http://ojx1pmrk7.bkt.clouddn.com/Me-Pressent-Future.jpg", "http://ojx1pmrk7.bkt.clouddn.com/Not-Always-May.jpg", "http://ojx1pmrk7.bkt.clouddn.com/Reveal-App-Layout.jpg"]
cycleScrollView.imageUrls = testImageUrls
cycleScrollView_sb.pageControlShowStyle = .left
cycleScrollView_sb.changeImageTime = 1.0
cycleScrollView_sb.imageUrls = testImageUrls
cycleScrollView_sb.clickCallback = {[weak self](scrollView: ImageCycleScrollView, imgIndex: Int) -> Void in
if let strongSelf = self {
print(strongSelf)
print("index: \(imgIndex)") //index从1开始
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
273ef7408cadd0583337ca9f1af1516c
| 34.306122 | 252 | 0.668208 | 4.070588 | false | true | false | false |
hooman/swift
|
test/SIL/Distributed/distributed_actor_remote_deinit_sil_normal.swift
|
1
|
1372
|
// RUN: %target-swift-frontend -O -primary-file %s -emit-sil -enable-experimental-distributed | %FileCheck %s --dump-input=fail
// REQUIRES: concurrency
import _Distributed
class SomeClass {}
@available(SwiftStdlib 5.5, *)
actor SimpleActor {
let someFieldInLocalActor: SomeClass
init(field: SomeClass) {
self.someFieldInLocalActor = field
}
}
// ==== ------------------------------------------------------------------------
// ==== Check that a normal local only actor is left unchanged
// CHECK: // SimpleActor.deinit
// CHECK: sil hidden{{.*}} @$s42distributed_actor_remote_deinit_sil_normal11SimpleActorCfd : $@convention(method) (@guaranteed SimpleActor) -> @owned Builtin.NativeObject {
// CHECK: // %0 "self" // users: %6, %5, %2, %1
// CHECK: bb0(%0 : $SimpleActor):
// CHECK: debug_value %0 : $SimpleActor, let, name "self", argno 1, implicit
// CHECK: %2 = ref_element_addr %0 : $SimpleActor, #SimpleActor.someFieldInLocalActor
// CHECK: %3 = load %2 : $*SomeClass // user: %4
// CHECK: strong_release %3 : $SomeClass // id: %4
// CHECK: %5 = builtin "destroyDefaultActor"(%0 : $SimpleActor) : $()
// CHECK: %6 = unchecked_ref_cast %0 : $SimpleActor to $Builtin.NativeObject // user: %7
// CHECK: return %6 : $Builtin.NativeObject // id: %7
// CHECK: } // end sil function '$s42distributed_actor_remote_deinit_sil_normal11SimpleActorCfd'
|
apache-2.0
|
ad377f3c7695e2534f93dbec8d2f56e7
| 41.875 | 172 | 0.645044 | 3.455919 | false | false | false | false |
taxfix/native-navigation
|
lib/ios/native-navigation/SharedElementManager.swift
|
1
|
1684
|
//
// SharedElementManager.swift
// NativeNavigation
//
// Created by Leland Richardson on 8/10/16.
// Copyright © 2016 Airbnb. All rights reserved.
//
import React
import UIKit
// MARK: - SharedElement
final class SharedElement: RCTView {
// MARK: Internal
@objc func setIdentifier(_ identifier: String!) {
self.identifier = identifier
}
@objc func setNativeNavigationInstanceId(_ nativeNavigationInstanceId: String!) {
self.nativeNavigationInstanceId = nativeNavigationInstanceId
}
override func insertReactSubview(_ subview: UIView, at index: Int) {
super.insertReactSubview(subview, at: index)
guard let seid = identifier, let id = nativeNavigationInstanceId else { return }
let vc = ReactNavigationCoordinator.sharedInstance.viewControllerForId(id)
vc?.sharedElementsById[seid] = WeakViewHolder(view: subview)
}
override func removeReactSubview(_ subview: UIView) {
super.removeReactSubview(subview)
guard let seid = identifier, let id = nativeNavigationInstanceId else { return }
let vc = ReactNavigationCoordinator.sharedInstance.viewControllerForId(id)
vc?.sharedElementsById[seid] = nil
}
// MARK: Private
fileprivate var identifier: String?
fileprivate var nativeNavigationInstanceId: String?
}
// MARK: - SharedElementManager
private let VERSION: Int = 1
@objc(SharedElementManager)
final class SharedElementManager: RCTViewManager {
override static func requiresMainQueueSetup() -> Bool {
return true
}
override func view() -> UIView! {
return SharedElement()
}
override func constantsToExport() -> [AnyHashable: Any] {
return [
"VERSION": VERSION
]
}
}
|
mit
|
339f154e7a55e2e387d5ab21ed1850ca
| 24.892308 | 84 | 0.731432 | 4.326478 | false | false | false | false |
5lucky2xiaobin0/PandaTV
|
PandaTV/PandaTV/Classes/Main/VIew/TitleView.swift
|
1
|
4624
|
//
// TitleView.swift
// PandaTV
//
// Created by 钟斌 on 2017/4/1.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
private let GameTitleCellID = "GameTitleCellID"
private let lineH : CGFloat = 2
protocol TitleViewDelegate : class {
func titleViewScrollTo(index : Int)
}
class TitleView: UIView {
weak var delegate : TitleViewDelegate?
var lineOfSetX : CGFloat = 0
var titleArr : [TitleItem]
var selectorBtn : UIButton?
var titleBtnS : [UIButton] = [UIButton]()
lazy var titleContentView : UIScrollView = UIScrollView()
lazy var titleLineView : UIView = {
let lineView = UIView()
lineView.backgroundColor = UIColor.getGreenColor()
return lineView
}()
init(frame: CGRect, titleArr : [TitleItem]) {
self.titleArr = titleArr
super.init(frame: frame)
setUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TitleView {
func setUI() {
//添加内部控件
setTitleContentView()
//添加底部划线
setTitleLineView()
}
func setTitleContentView() {
addSubview(titleContentView)
var index = 0
var x = 0
var width = 0
for title in titleArr {
let length = title.cname?.lengthOfBytes(using: String.Encoding.utf8)
x += width
width = length! * 5 + 20
//创建button
let btn = UIButton()
btn.setTitle(title.cname, for: .normal)
btn.setTitleColor(UIColor.black, for: .normal)
btn.setTitleColor(UIColor.getGreenColor(), for: .selected)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
btn.addTarget(self, action: #selector(titleClick(btn:)), for: .touchUpInside)
btn.sizeToFit()
btn.frame = CGRect(x: x, y: Int(self.bounds.height - 34), width: width, height: 32)
titleContentView.addSubview(btn)
btn.tag = index
if index == 1 {
titleClick(btn: btn)
}
titleBtnS.append(btn)
index += 1
}
titleContentView.delegate = self
titleContentView.isPagingEnabled = true
titleContentView.showsVerticalScrollIndicator = false
titleContentView.showsHorizontalScrollIndicator = false
titleContentView.frame = self.bounds
titleContentView.contentSize = CGSize(width: x + width, height: 0)
}
func setTitleLineView() {
addSubview(titleLineView)
//得到当前选中的按钮
if titleBtnS.count > 1 {
let sButton = titleBtnS[1]
sButton.titleLabel?.sizeToFit()
let x = sButton.getX() + (sButton.getWidth() - (sButton.titleLabel?.getWidth())!)/2
titleLineView.frame = CGRect(x: x, y: bounds.height - lineH, width: (sButton.titleLabel?.getWidth())!, height: 2)
}
}
}
// MARK: - 事件处理
extension TitleView {
func titleClick(btn : UIButton) {
selectorBtn?.isSelected = false
btn.isSelected = true
selectorBtn = btn
//选中按钮滑动到中间
var offsetX = btn.getCenterX() - screenW / 2;
if offsetX < 0 {
offsetX = 0;
}else if offsetX > self.titleContentView.contentSize.width - screenW{
offsetX = self.titleContentView.contentSize.width - screenW;
}
titleContentView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
let Lasttag = selectorBtn?.tag ?? 0
let time = (CGFloat)(btn.tag - Lasttag + 1) * 0.2
UIView.animate(withDuration: TimeInterval(time)) {
self.titleLineView.width(NewWidth: (btn.titleLabel?.getWidth())!)
self.titleLineView.centerX(NewCenterX: btn.getCenterX() - offsetX)
}
//通知代理滑动内容界面
delegate?.titleViewScrollTo(index: btn.tag)
}
func scrollToTitle(index : Int) {
let btn = self.titleBtnS[index]
titleClick(btn: btn)
}
}
// MARK: - 标题栏滑动监听UICollectionViewDelegate
extension TitleView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.titleLineView.centerX(NewCenterX: (selectorBtn?.getCenterX())! - scrollView.contentOffset.x)
}
}
|
mit
|
2398e3f6bafb323c9bf1ae41590fba9c
| 27.371069 | 125 | 0.581468 | 4.52004 | false | false | false | false |
3ph/CollectionPickerView
|
Sources/CollectionPickerView/CollectionPickerViewFlowLayout.swift
|
1
|
10237
|
//
// CollectionPickerFlowLayout.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Akkyie Y, 2017 Tomas Friml
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import UIKit
public class CollectionPickerViewFlowLayout: UICollectionViewFlowLayout {
open var maxAngle : CGFloat = CGFloat.pi / 2
open var isFlat : Bool = true
fileprivate var _isHorizontal : Bool {
get {
return scrollDirection == .horizontal
}
}
fileprivate var _halfDim : CGFloat {
get {
return (_isHorizontal ? _visibleRect.width : _visibleRect.height) / 2
}
}
fileprivate var _mid : CGFloat {
get {
return _isHorizontal ? _visibleRect.midX : _visibleRect.midY
}
}
fileprivate var _visibleRect : CGRect {
get {
if let cv = collectionView {
return CGRect(origin: cv.contentOffset, size: cv.bounds.size)
}
return CGRect.zero
}
}
func initialize() {
sectionInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
minimumLineSpacing = 0.0
}
override init() {
super.init()
self.initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if let attributes = super.layoutAttributesForItem(at: indexPath)?.copy() as? UICollectionViewLayoutAttributes {
if isFlat == false {
let distance = (_isHorizontal ? attributes.frame.midX : attributes.frame.midY) - _mid
let currentAngle = maxAngle * distance / _halfDim / (CGFloat.pi / 2)
var transform = CATransform3DIdentity
if _isHorizontal {
transform = CATransform3DTranslate(transform, -distance, 0, -_halfDim)
transform = CATransform3DRotate(transform, currentAngle, 0, 1, 0)
} else {
transform = CATransform3DTranslate(transform, 0, distance, -_halfDim)
transform = CATransform3DRotate(transform, currentAngle, 1, 0, 0)
}
transform = CATransform3DTranslate(transform, 0, 0, _halfDim)
attributes.transform3D = transform
attributes.alpha = abs(currentAngle) < maxAngle ? 1.0 : 0.0
return attributes;
}
return attributes
}
return nil
}
public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if isFlat == false {
var attributes = [UICollectionViewLayoutAttributes]()
if self.collectionView!.numberOfSections > 0 {
for i in 0 ..< self.collectionView!.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: i, section: 0)
attributes.append(self.layoutAttributesForItem(at: indexPath)!)
}
}
return attributes
}
return super.layoutAttributesForElements(in: rect)
}
// public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// guard let cv = collectionView else { return CGPoint.zero }
//
// let dim = _isHorizontal ? cv.bounds.width : cv.bounds.height
// let halfDim = dim / 2
// var offsetAdjustment: CGFloat = CGFloat.greatestFiniteMagnitude
// var selectedCenter: CGFloat = dim
//
// let center: CGFloat = _isHorizontal ? proposedContentOffset.x + halfDim : proposedContentOffset.y + halfDim
// let targetRect = CGRect(x: _isHorizontal ? proposedContentOffset.x : 0, y: _isHorizontal ? 0 : proposedContentOffset.y, width: cv.bounds.size.width, height: cv.bounds.size.height)
// let array:[UICollectionViewLayoutAttributes] = layoutAttributesForElements(in: targetRect)!
// for layoutAttributes: UICollectionViewLayoutAttributes in array {
// let itemCenter: CGFloat = _isHorizontal ? layoutAttributes.center.x : layoutAttributes.center.y
// if abs(itemCenter - center) < abs(offsetAdjustment) {
// offsetAdjustment = itemCenter - center
// selectedCenter = itemCenter
// NSLog("PropX: \(proposedContentOffset.x), offset: \(offsetAdjustment), itemCenter: \(itemCenter), center: \(center)")
// }
// }
// return CGPoint(x: proposedContentOffset.x - (_isHorizontal ? offsetAdjustment : 0), y: proposedContentOffset.y + (_isHorizontal ? 0 : offsetAdjustment))
// }
var snapToCenter : Bool = true
var mostRecentOffset : CGPoint = CGPoint()
public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// _ = scrollDirection == .horizontal
//
// if snapToCenter == false {
// return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
// }
// guard let collectionView = collectionView else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) }
//
// var offsetAdjustment = CGFloat.greatestFiniteMagnitude
// let offset = isHorizontal ? proposedContentOffset.x + collectionView.contentInset.left : proposedContentOffset.y + collectionView.contentInset.top
//
// let targetRect : CGRect
// if isHorizontal {
// targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
// } else {
// targetRect = CGRect(x: 0, y: proposedContentOffset.y, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
// }
//
// let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect)
//
// layoutAttributesArray?.forEach({ (layoutAttributes) in
// let itemOffset = isHorizontal ? layoutAttributes.frame.origin.x : layoutAttributes.frame.origin.y
// if fabsf(Float(itemOffset - offset)) < fabsf(Float(offsetAdjustment)) {
// offsetAdjustment = itemOffset - offset
// }
// })
//
// if (isHorizontal && velocity.x == 0) || (isHorizontal == false && velocity.y == 0) {
// return mostRecentOffset
// }
//
// if let cv = self.collectionView {
//
// let cvBounds = cv.bounds
// let half = (isHorizontal ? cvBounds.size.width : cvBounds.size.height) * 0.5;
//
// if let attributesForVisibleCells = self.layoutAttributesForElements(in: cvBounds) {
//
// var candidateAttributes : UICollectionViewLayoutAttributes?
// for attributes in attributesForVisibleCells {
//
// // == Skip comparison with non-cell items (headers and footers) == //
// if attributes.representedElementCategory != UICollectionElementCategory.cell {
// continue
// }
//
// if isHorizontal {
// if attributes.center.x == 0 || (attributes.center.x > (cv.contentOffset.x + half) && velocity.x < 0) {
// continue
// }
// } else {
// if attributes.center.y == 0 || (attributes.center.y > (cv.contentOffset.y + half) && velocity.y < 0) {
// continue
// }
// }
//
// candidateAttributes = attributes
// }
//
// // Beautification step , I don't know why it works!
// if (isHorizontal && proposedContentOffset.x == -cv.contentInset.left)
// || (isHorizontal == false && proposedContentOffset.y == -cv.contentInset.top) {
// return proposedContentOffset
// }
//
// guard let _ = candidateAttributes else {
// return mostRecentOffset
// }
//
// if isHorizontal {
// mostRecentOffset = CGPoint(x: floor(candidateAttributes!.center.x - half), y: proposedContentOffset.y)
// } else {
// mostRecentOffset = CGPoint(x: proposedContentOffset.y, y: floor(candidateAttributes!.center.y - half))
// }
//
// return mostRecentOffset
// }
// }
// fallback
mostRecentOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
return mostRecentOffset
}
}
|
mit
|
19a62e2aaa613d42ec5e075f1624a4f8
| 44.90583 | 193 | 0.608674 | 5.077877 | false | false | false | false |
rene-dohan/CS-IOS
|
Renetik/Renetik/Classes/AlamofireCached/URL+CSAlamofireCache.swift
|
1
|
623
|
////
//// Created by Rene Dohan on 1/1/20.
//// Copyright (c) 2020 Renetik. All rights reserved.
////
//
//import Foundation
//import Alamofire
//import RenetikObjc
//import Renetik
//
//public extension URL {
// func clearCache(parameters: [String: Any]? = nil, headers: HTTPHeaders? = nil, urlCache: URLCache = URLCache.shared) {
// if var request = try? URLRequest(url: self, method: HTTPMethod.get, headers: headers) {
// request.cachePolicy = .reloadIgnoringLocalCacheData
// (try? URLEncoding().encode(request, with: parameters))?.clearCache(urlCache: urlCache)
// }
// }
//}
|
mit
|
1076a86bb634165810afbf81ddf5c879
| 33.666667 | 124 | 0.651685 | 3.968153 | false | false | false | false |
gregomni/swift
|
test/Distributed/Runtime/distributed_actor_encode_roundtrip.swift
|
4
|
2392
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeCodableForDistributedTests.swiftmodule -module-name FakeCodableForDistributedTests -disable-availability-checking %S/../Inputs/FakeCodableForDistributedTests.swift
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift
// XXX: %target-build-swift -emit-silgen -module-name main -Xfrontend -enable-experimental-distributed -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeCodableForDistributedTests.swift %S/../Inputs/FakeDistributedActorSystems.swift
// RUN: %target-build-swift -module-name main -Xfrontend -enable-experimental-distributed -Xfrontend -disable-availability-checking -j2 -parse-as-library -I %t %s %S/../Inputs/FakeCodableForDistributedTests.swift %S/../Inputs/FakeDistributedActorSystems.swift -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s --color
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import Distributed
import FakeDistributedActorSystems
import FakeCodableForDistributedTests
distributed actor Worker: CustomStringConvertible {
nonisolated var description: Swift.String {
"Worker(\(id))"
}
}
typealias DefaultDistributedActorSystem = FakeRoundtripActorSystem
// ==== Execute ----------------------------------------------------------------
@main struct Main {
static func main() async {
let system = DefaultDistributedActorSystem()
let actor = Worker(actorSystem: system)
// CHECK: assign id: ActorAddress(address: "<unique-id>") for Worker
// compilation check:
let _: Encodable = actor
let _: Decodable = actor
// round trip check:
let json = FakeEncoder()
let encoded = try! json.encode(actor)
print("encoded = \(encoded)")
// CHECK: encoded = <unique-id>;
let decoder = FakeDecoder()
decoder.userInfo[.actorSystemKey] = system
let back = try! decoder.decode(encoded, as: Worker.self)
// CHECK: | resolve ActorAddress(address: "<unique-id>")
print("back = \(back)")
// CHECK: back = Worker(ActorAddress(address: "<unique-id>"))
}
}
|
apache-2.0
|
c8d0e14e0f5ba6e7524c45c890fb132c
| 43.296296 | 272 | 0.72199 | 4.226148 | false | true | false | false |
MKGitHub/UIPheonix
|
Demo/tvOS/DemoCollectionViewController.swift
|
1
|
12748
|
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 UIKit
final class DemoCollectionViewController:UIPBaseViewController, UIPButtonDelegate,
UICollectionViewDataSource, /*UICollectionViewDataSourcePrefetching,*/ UICollectionViewDelegateFlowLayout
{
// MARK: Public Inner Struct
struct AttributeKeyName
{
static let appDisplayState = "AppDisplayState"
}
// MARK: Public IB Outlet
@IBOutlet private weak var ibCollectionView:UICollectionView!
// MARK: Private Members
private var mAppDisplayStateType:AppDisplayStateType!
private var mUIPheonix:UIPheonix!
private var mViewToFocus:UIView? = nil
// (for demo purpose only)
private var mPersistentDisplayModels:Array<UIPBaseCellModelProtocol>?
override var preferredFocusEnvironments:[UIFocusEnvironment]
{
// the cell view to focus
if (mViewToFocus != nil) {
return [mViewToFocus ?? self]
}
else {
return super.preferredFocusEnvironments
}
}
// MARK:- Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
// init member
mAppDisplayStateType = (newInstanceAttributes[AttributeKeyName.appDisplayState] as! AppDisplayState).value
initUIPheonix()
setupCollectionView()
updateView()
}
// MARK:- UICollectionViewDataSource
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
return mUIPheonix.displayModelsCount(forSection:0)
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let cellModel = mUIPheonix.displayModel(forSection:0, atIndex:indexPath.item)!
// tvOS, focus on the item that wants focus (only buttons in this case)
if (cellModel.nameOfClass == SimpleButtonModel.nameOfClass)
{
let buttonModel = cellModel as! SimpleButtonModel
// wants focus
if (buttonModel.pFocus)
{
let cellView:UIPBaseCollectionViewCell = mUIPheonix.dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
mViewToFocus = cellView
}
}
return mUIPheonix.collectionViewCell(forIndexPath:indexPath)
}
// MARK:- UICollectionViewDataSourcePrefetching
/**
Not used in this example.
*/
/*@available(iOS 10.0, *)
func collectionView(_ collectionView:UICollectionView, prefetchItemsAt indexPaths:[IndexPath])
{
// empty for now
}*/
// MARK:- UICollectionViewDelegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, insetForSectionAt section:Int) -> UIEdgeInsets
{
return UIEdgeInsets(top:10, left:0, bottom:10, right:0)
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, minimumLineSpacingForSectionAt section:Int) -> CGFloat
{
return 10
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
return mUIPheonix.collectionViewCellSize(forIndexPath:indexPath)
}
// MARK:- UIPButtonDelegate
func handleAction(forButtonId buttonId:Int)
{
var isTheAppendModelsDemo = false
var isThePersistentModelsDemo = false
var isTheCustomMadeModelsDemo = false
var shouldAnimateChange = true
// set the display state depending on which button we clicked
switch (buttonId)
{
case ButtonId.startUp.rawValue: mAppDisplayStateType = AppDisplayState.startUp.value; break
case ButtonId.mixed.rawValue: mAppDisplayStateType = AppDisplayState.mixed.value; break
case ButtonId.animations.rawValue: mAppDisplayStateType = AppDisplayState.animations.value; break
case ButtonId.switching.rawValue: mAppDisplayStateType = AppDisplayState.switching.value; break
case ButtonId.appending.rawValue: mAppDisplayStateType = AppDisplayState.appending.value; break
case ButtonId.appendingReload.rawValue:
mAppDisplayStateType = AppDisplayState.appending.value
isTheAppendModelsDemo = true
shouldAnimateChange = false
break
case ButtonId.persistent.rawValue:
mAppDisplayStateType = AppDisplayState.persistent.value
isThePersistentModelsDemo = true
break
case ButtonId.persistentGoBack.rawValue:
mAppDisplayStateType = AppDisplayState.startUp.value
// when we leave the state, store the current display models for later reuse
// so that when we re-enter the state, we can just use them as they were
mPersistentDisplayModels = mUIPheonix.displayModels(forSection:0)
break
case ButtonId.specific.rawValue: mAppDisplayStateType = AppDisplayState.specific.value; break
case ButtonId.customMadeModels.rawValue:
mAppDisplayStateType = AppDisplayState.customMadeModels.value;
isTheCustomMadeModelsDemo = true
break
default: mAppDisplayStateType = AppDisplayState.startUp.value; break
}
// update UI
if (shouldAnimateChange)
{
animateView(animationState:false, completionHandler:
{
[weak self] in
guard let self = self else { fatalError("DemoCollectionViewController buttonAction: `self` does not exist anymore!") }
self.updateView(isTheAppendModelsDemo:isTheAppendModelsDemo,
isThePersistentDemo:isThePersistentModelsDemo,
isTheCustomMadeModelsDemo:isTheCustomMadeModelsDemo)
self.animateView(animationState:true, completionHandler:
{
[weak self] in
guard let self = self else { fatalError("DemoCollectionViewController buttonAction: `self` does not exist anymore!") }
// force update view focus
self.setNeedsFocusUpdate()
self.updateFocusIfNeeded()
})
})
}
else
{
updateView(isTheAppendModelsDemo:isTheAppendModelsDemo,
isThePersistentDemo:isThePersistentModelsDemo,
isTheCustomMadeModelsDemo:isTheCustomMadeModelsDemo)
}
}
// MARK:- Private
private func initUIPheonix()
{
mUIPheonix = UIPheonix(collectionView:ibCollectionView, delegate:self)
}
private func setupCollectionView()
{
/**
Does not seem to work, bug reported to Apple.
*/
/*if #available(tvOS 10.0, *)
{
(ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
//(ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width:ibCollectionView.bounds.width, height:50)
}
else
{
// fallback on earlier versions
(ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width:ibCollectionView.bounds.width, height:50)
}*/
ibCollectionView.delegate = self
ibCollectionView.dataSource = self
/**
Not used in this example.
*/
/*if #available(tvOS 10.0, *)
{
ibCollectionView.prefetchDataSource = self
// ibCollectionView.isPrefetchingEnabled, true by default
}
else {
// fallback on earlier versions
}*/
}
private func setupWithJSON()
{
if let jsonDictionary = DataProvider.loadJSON(inFilePath:mAppDisplayStateType.jsonFileName.rawValue)
{
mUIPheonix.setModelViewRelationships(withDictionary:jsonDictionary[UIPConstants.Collection.modelViewRelationships] as! Dictionary<String, String>)
mUIPheonix.setDisplayModels(jsonDictionary[UIPConstants.Collection.cellModels] as! Array<Any>, forSection:0, append:false)
}
else
{
fatalError("DemoCollectionViewController setupWithJSON: Failed to init with JSON file!")
}
}
private func setupWithModels()
{
mUIPheonix.setModelViewRelationships(withDictionary:[SimpleButtonModel.nameOfClass:SimpleButtonModelCVCell.nameOfClass,
SimpleCounterModel.nameOfClass:SimpleCounterModelCVCell.nameOfClass,
SimpleLabelModel.nameOfClass:SimpleLabelModelCVCell.nameOfClass,
SimpleTextFieldModel.nameOfClass:SimpleTextFieldModelCVCell.nameOfClass,
SimpleVerticalSpaceModel.nameOfClass:SimpleVerticalSpaceModelCVCell.nameOfClass,
SimpleViewAnimationModel.nameOfClass:SimpleViewAnimationModelCVCell.nameOfClass])
var models = [UIPBaseCellModel]()
for i in 1 ... 8
{
let simpleLabelModel = SimpleLabelModel(text:" Label \(i)",
size:(24.0 + CGFloat(i) * 4.0),
alignment:SimpleLabelModel.Alignment.left,
style:SimpleLabelModel.Style.regular,
backgroundColorHue:(CGFloat(i) * 0.10),
notificationId:"")
models.append(simpleLabelModel)
}
let simpleButtonModel = SimpleButtonModel(id:ButtonId.startUp.rawValue,
title:"Enough with the RAINBOW!",
focus:true)
models.append(simpleButtonModel)
mUIPheonix.setDisplayModels(models, forSection:0)
}
private func updateView(isTheAppendModelsDemo:Bool=false, isThePersistentDemo:Bool=false, isTheCustomMadeModelsDemo:Bool=false)
{
if (isTheAppendModelsDemo)
{
// append the current display models list to itself
mUIPheonix.addDisplayModels(mUIPheonix.displayModels(forSection:0), inSection:0)
}
else if (isThePersistentDemo)
{
if (mPersistentDisplayModels == nil) {
setupWithJSON()
}
else
{
// set the persistent display models
mUIPheonix!.setDisplayModels(mPersistentDisplayModels!, forSection:0)
}
}
else if (isTheCustomMadeModelsDemo)
{
setupWithModels()
}
else
{
setupWithJSON()
}
// reload the collection view
ibCollectionView.reloadData()
}
private func animateView(animationState:Bool, completionHandler:(()->Void)?)
{
// do a nice fading animation
UIView.animate(withDuration:0.25, animations:
{
[weak self] in
guard let self = self else { fatalError("DemoCollectionViewController animateView: `self` does not exist anymore!") }
self.ibCollectionView.alpha = animationState ? 1.0 : 0.0
},
completion:
{
(animationCompleted:Bool) in
completionHandler?()
})
}
}
|
apache-2.0
|
38959520f438b48855412693579b8a4a
| 34.310249 | 165 | 0.622107 | 5.688086 | false | false | false | false |
drougojrom/RUCropController
|
RUCropController/Model/RUCropViewControllerTransitioning.swift
|
1
|
5059
|
//
// RUCropViewControllerTransitioning.swift
// RUCropController
//
// Created by Roman Ustiantcev on 06/10/2017.
// Copyright © 2017 Roman Ustiantcev. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
@objc class RUCropViewControllerTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
/* State Tracking */
@objc var isDismissing = false
// Whether this animation is presenting or dismissing
@objc var image: UIImage?
// The image that will be used in this animation
/* Destination/Origin points */
@objc var fromView: UIView?
// The origin view who's frame the image will be animated from
@objc var toView: UIView?
// The destination view who's frame the image will animate to
@objc var fromFrame = CGRect.zero
// An origin frame that the image will be animated from
@objc var toFrame = CGRect.zero
// A destination frame the image will aniamte to
/* A block called just before the transition to perform any last-second UI configuration */
@objc var prepareForTransitionHandler: (() -> Void)?
/* Empties all of the properties in this object */
@objc func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.45 as TimeInterval
}
@objc func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Get the master view where the animation takes place
let containerView: UIView? = transitionContext.containerView
// Get the origin/destination view controllers
let fromViewController: UIViewController? = transitionContext.viewController(forKey: .from)
let toViewController: UIViewController? = transitionContext.viewController(forKey: .to)
// Work out which one is the crop view controller
let cropViewController: UIViewController? = (isDismissing == false) ? toViewController : fromViewController
let previousController: UIViewController? = (isDismissing == false) ? fromViewController : toViewController
// Just in case, match up the frame sizes
cropViewController?.view.frame = containerView?.bounds ?? CGRect.zero
if isDismissing {
previousController?.view.frame = containerView?.bounds ?? CGRect.zero
}
// Add the view layers beforehand as this will trigger the initial sets of layouts
if isDismissing == false {
containerView?.addSubview((cropViewController?.view)!)
//Force a relayout now that the view is in the view hierarchy (so things like the safe area insets are now valid)
cropViewController?.viewDidLayoutSubviews()
} else {
containerView?.insertSubview((previousController?.view)!, belowSubview: (cropViewController?.view)!)
}
// Perform any last UI updates now so we can potentially factor them into our calculations, but after
// the container views have been set up
if (prepareForTransitionHandler != nil) {
prepareForTransitionHandler!()
}
// If origin/destination views were supplied, use them to supplant the
// frames
if !(isDismissing && (fromView != nil)) {
fromFrame = (fromView?.superview?.convert((fromView?.frame)!, to: containerView))!
}
else if isDismissing && (toView != nil) {
toFrame = (toView?.superview?.convert((toView?.frame)!, to: containerView))!
}
var imageView: UIImageView? = nil
if (isDismissing && !toFrame.isEmpty) || (!isDismissing && !fromFrame.isEmpty) {
imageView = UIImageView(image: image)
imageView?.frame = fromFrame
containerView?.addSubview(imageView!)
}
cropViewController?.view.alpha = isDismissing ? 1.0 : 0.0
if imageView != nil {
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.7, options: [], animations: {() -> Void in
imageView?.frame = self.toFrame
}, completion: {(_ complete: Bool) -> Void in
UIView.animate(withDuration: 0.25, animations: {() -> Void in
imageView?.alpha = 0.0
}, completion: {(_ complete: Bool) -> Void in
imageView?.removeFromSuperview()
})
})
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {() -> Void in
cropViewController?.view.alpha = self.isDismissing ? 0.0 : 1.0
}, completion: {(_ complete: Bool) -> Void in
self.reset()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
@objc func reset() {
image = nil
toView = nil
fromView = nil
fromFrame = CGRect.zero
toFrame = CGRect.zero
prepareForTransitionHandler = nil
}
}
|
mit
|
24d3644ec49a1d552d9ca9fe431ffa6d
| 46.716981 | 195 | 0.655991 | 5.26875 | false | false | false | false |
wesj/firefox-ios-1
|
Storage/ThirdParty/SwiftData.swift
|
2
|
20618
|
/* 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/. */
/*
* This is a heavily modified version of SwiftData.swift by Ryan Fowler
* This has been enhanced to support custom files, correct binding, versioning,
* and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and
* to force callers to request a connection before executing commands. Database creation helpers, savepoint
* helpers, image support, and other features have been removed.
*/
// SwiftData.swift
//
// Copyright (c) 2014 Ryan Fowler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import sqlite3
// All database operations actually occur serially on this queue. Careful not to deadlock it!
private let queue = dispatch_queue_create("swiftdata queue", DISPATCH_QUEUE_SERIAL)
// The public interface for the database. This handles dispatching calls synchronously on the correct thread
public class SwiftData {
let filename: String
init(filename: String) {
self.filename = filename
}
//The real meat of all the execute methods. This is used internally to open and close a database connection and
// run a block of code inside it.
public func withConnection(flags: SwiftData.Flags, cb: (db: SQLiteDBConnection) -> NSError?) -> NSError? {
var error: NSError? = nil
let task: () -> Void = {
if let db = SQLiteDBConnection(filename: self.filename, flags: flags.toSQL(), error: &error) {
error = cb(db: db)
}
}
dispatch_sync(queue) { task() }
return error
}
// Helper for opening a connection, starting a transaction, and then running a block of code inside it.
// The code block can return true if the transaction should be commited. False if we should rollback.
public func transaction(transactionClosure: (db: SQLiteDBConnection)->Bool) -> NSError? {
return withConnection(SwiftData.Flags.ReadWriteCreate) { db in
if let err = db.executeChange("BEGIN EXCLUSIVE") {
return err
}
if transactionClosure(db: db) {
if let err = db.executeChange("COMMIT") {
db.executeChange("ROLLBACK")
return err
}
} else {
if let err = db.executeChange("ROLLBACK") {
return err
}
}
return nil
}
}
public enum Flags {
case ReadOnly
case ReadWrite
case ReadWriteCreate
private func toSQL() -> Int32 {
switch self {
case .ReadOnly:
return SQLITE_OPEN_READONLY
case .ReadWrite:
return SQLITE_OPEN_READWRITE
case .ReadWriteCreate:
return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
}
}
}
}
// We open the connection when this is created
public class SQLiteDBConnection {
private var sqliteDB: COpaquePointer = nil
private let filename: String
private let debug_enabled = false
public var version: Int {
get {
var version = 0
let res = executeQuery("PRAGMA user_version", factory: IntFactory)
if let v = res[0] {
version = v as Int
}
return version
}
set {
executeChange("PRAGMA user_version = \(newValue)")
}
}
init?(filename: String, flags: Int32, inout error: NSError?) {
self.filename = filename
if let err = openWithFlags(flags) {
error = err
return nil
}
}
deinit {
closeCustomConnection()
}
var lastInsertedRowID: Int {
return Int(sqlite3_last_insert_rowid(sqliteDB))
}
var numberOfRowsModified: Int {
return Int(sqlite3_changes(sqliteDB))
}
// Creates an error from a sqlite status. Will print to the console if debug_enabled is set.
// (i.e. Do not call this unless you're going to return this error)
private func createErr(description: String, status: Int) -> NSError {
var msg = SDError.errorMessageFromCode(status)
if (debug_enabled) {
println("SwiftData Error -> \(description)")
println(" -> Code: \(status) - \(msg)")
}
if let errMsg = String.fromCString(sqlite3_errmsg(sqliteDB)) {
msg += " " + errMsg
if (debug_enabled) {
println(" -> Details: \(errMsg)")
}
}
return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg])
}
// Open the connection. This is called when the db is created. You should not call it yourself
private func openWithFlags(flags: Int32) -> NSError? {
let status = sqlite3_open_v2(filename.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil)
if status != SQLITE_OK {
return createErr("During: Opening Database with Flags", status: Int(status))
}
return nil
}
// Closes a connection This is called a deinit. Do not call this yourself
private func closeCustomConnection() -> NSError? {
let status = sqlite3_close(sqliteDB)
sqliteDB = nil
if status != SQLITE_OK {
return createErr("During: Closing Database with Flags", status: Int(status))
}
return nil
}
// Executes a change on the datbase
func executeChange(sqlStr: String, withArgs: [AnyObject?]? = nil) -> NSError? {
var err: NSError? = nil
var pStmt: COpaquePointer = nil
var status = sqlite3_prepare_v2(sqliteDB, sqlStr, -1, &pStmt, nil)
if status != SQLITE_OK {
let err = createErr("During: SQL Prepare \(sqlStr)", status: Int(status))
sqlite3_finalize(pStmt)
return err
}
if let args = withArgs {
if let err = bind(args, stmt: pStmt) {
sqlite3_finalize(pStmt)
return err
}
}
status = sqlite3_step(pStmt)
if status != SQLITE_DONE && status != SQLITE_OK {
err = createErr("During: SQL Step \(sqlStr)", status: Int(status))
}
sqlite3_finalize(pStmt)
return err
}
// Execute a query on the database
func executeQuery<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs: [AnyObject?]? = nil) -> Cursor {
var pStmt: COpaquePointer = nil
let status = sqlite3_prepare_v2(sqliteDB, sqlStr, -1, &pStmt, nil)
if status != SQLITE_OK {
let err = createErr("During: SQL Prepare \(sqlStr)", status: Int(status))
sqlite3_finalize(pStmt)
return Cursor(err: err)
}
if let args = withArgs {
if let err = bind(args, stmt: pStmt) {
sqlite3_finalize(pStmt)
return Cursor(err: err)
}
}
return SDCursor(db: self, stmt: pStmt, factory: factory)
}
// Bind objects to a query
private func bind(objects: [AnyObject?], stmt: COpaquePointer) -> NSError? {
let count = Int(sqlite3_bind_parameter_count(stmt))
if (count < objects.count) {
return createErr("During: Bind", status: 202)
} else if (count > objects.count) {
return createErr("During: Bind", status: 201)
}
for (index, obj) in enumerate(objects) {
var status: Int32 = SQLITE_OK
// Double's also pass obj is Int, so order is important here
if obj is Double {
status = sqlite3_bind_double(stmt, Int32(index+1), obj as Double)
} else if obj is Int {
status = sqlite3_bind_int(stmt, Int32(index+1), Int32(obj as Int))
} else if obj is Bool {
status = sqlite3_bind_int(stmt, Int32(index+1), (obj as Bool) ? 1 : 0)
} else if obj is String {
let negativeOne = UnsafeMutablePointer<Int>(bitPattern: -1)
let opaquePointer = COpaquePointer(negativeOne)
let transient = CFunctionPointer<((UnsafeMutablePointer<()>) -> Void)>(opaquePointer)
status = sqlite3_bind_text(stmt, Int32(index+1), (obj as String).cStringUsingEncoding(NSUTF8StringEncoding)!, -1, transient)
} else if obj is NSData {
status = sqlite3_bind_blob(stmt, Int32(index+1), (obj as NSData).bytes, -1, nil)
} else if obj is NSDate {
var timestamp = (obj as NSDate).timeIntervalSince1970
status = sqlite3_bind_double(stmt, Int32(index+1), timestamp)
} else if obj === nil {
status = sqlite3_bind_null(stmt, Int32(index+1))
}
if status != SQLITE_OK {
return createErr("During: Binding", status: Int(status))
}
}
return nil
}
}
// Helper for queries that return a single integer result
func IntFactory(row: SDRow) -> Int {
return row[0] as Int
}
// Helper for queries that return a single String result
func StringFactory(row: SDRow) -> String {
return row[0] as String
}
// Wrapper around a statment for getting data from a row. This provides accessors for subscript indexing
// and a generator for iterating over columns.
public class SDRow : SequenceType {
// The sqlite statement this row came from
private let stmt: COpaquePointer
// The columns of this database. The indicies of these are assumed to match the indicies
// of the statement.
private let columnNames = [String]()
// We hold a reference to the connection to keep it from being closed.
private let db: SQLiteDBConnection
private init(connection: SQLiteDBConnection, stmt: COpaquePointer, columns: [String]) {
db = connection
self.stmt = stmt
self.columnNames = columns
}
// Return the value at this index in the row
private func getValue(index: Int) -> AnyObject? {
let i = Int32(index)
let type = sqlite3_column_type(stmt, i)
var ret: AnyObject? = nil
switch type {
case SQLITE_NULL, SQLITE_INTEGER:
ret = NSNumber(longLong: sqlite3_column_int64(stmt, i))
case SQLITE_TEXT:
let text = UnsafePointer<Int8>(sqlite3_column_text(stmt, i))
ret = String.fromCString(text)
case SQLITE_BLOB:
let blob = sqlite3_column_blob(stmt, i)
if blob != nil {
let size = sqlite3_column_bytes(stmt, i)
ret = NSData(bytes: blob, length: Int(size))
}
case SQLITE_FLOAT:
ret = Double(sqlite3_column_double(stmt, i))
default:
println("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil")
}
return ret
}
// Accessor getting column 'key' in the row
public subscript(key: Int) -> AnyObject? {
return getValue(key)
}
// Accessor getting a named column in the row. This (currently) depends on
// the columns array passed into this Row to find the correct index.
public subscript(key: String) -> AnyObject? {
get {
if let index = find(columnNames, key) {
return getValue(index)
}
return nil
}
}
// Allow iterating through the row. This is currently broken.
public func generate() -> GeneratorOf<Any> {
var nextIndex = 0
return GeneratorOf<Any>() {
// This crashes the compiler. Yay!
if (nextIndex < self.columnNames.count) {
return nil // self.getValue(nextIndex)
}
return nil
}
}
}
// Helper for pretty printing sql (and other custom) error codes
private struct SDError {
private static func errorMessageFromCode(errorCode: Int) -> String {
switch errorCode {
case -1:
return "No error"
// SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html
case 0:
return "Successful result"
case 1:
return "SQL error or missing database"
case 2:
return "Internal logic error in SQLite"
case 3:
return "Access permission denied"
case 4:
return "Callback routine requested an abort"
case 5:
return "The database file is busy"
case 6:
return "A table in the database is locked"
case 7:
return "A malloc() failed"
case 8:
return "Attempt to write a readonly database"
case 9:
return "Operation terminated by sqlite3_interrupt()"
case 10:
return "Some kind of disk I/O error occurred"
case 11:
return "The database disk image is malformed"
case 12:
return "Unknown opcode in sqlite3_file_control()"
case 13:
return "Insertion failed because database is full"
case 14:
return "Unable to open the database file"
case 15:
return "Database lock protocol error"
case 16:
return "Database is empty"
case 17:
return "The database schema changed"
case 18:
return "String or BLOB exceeds size limit"
case 19:
return "Abort due to constraint violation"
case 20:
return "Data type mismatch"
case 21:
return "Library used incorrectly"
case 22:
return "Uses OS features not supported on host"
case 23:
return "Authorization denied"
case 24:
return "Auxiliary database format error"
case 25:
return "2nd parameter to sqlite3_bind out of range"
case 26:
return "File opened that is not a database file"
case 27:
return "Notifications from sqlite3_log()"
case 28:
return "Warnings from sqlite3_log()"
case 100:
return "sqlite3_step() has another row ready"
case 101:
return "sqlite3_step() has finished executing"
// Custom SwiftData errors
// Binding errors
case 201:
return "Not enough objects to bind provided"
case 202:
return "Too many objects to bind provided"
// Custom connection errors
case 301:
return "A custom connection is already open"
case 302:
return "Cannot open a custom connection inside a transaction"
case 303:
return "Cannot open a custom connection inside a savepoint"
case 304:
return "A custom connection is not currently open"
case 305:
return "Cannot close a custom connection inside a transaction"
case 306:
return "Cannot close a custom connection inside a savepoint"
// Index and table errors
case 401:
return "At least one column name must be provided"
case 402:
return "Error extracting index names from sqlite_master"
case 403:
return "Error extracting table names from sqlite_master"
// Transaction and savepoint errors
case 501:
return "Cannot begin a transaction within a savepoint"
case 502:
return "Cannot begin a transaction within another transaction"
// Unknown error
default:
return "Unknown error"
}
}
}
// Wrapper around a statement to help with iterating through the results. This currently
// only fetches items when asked for, and caches (all) old requests. Ideally it will
// at somepoint fetch a window of items to keep in memory
public class SDCursor<T> : Cursor {
private let stmt: COpaquePointer
// Function for generating objects of type T from a row.
private let factory: (SDRow) -> T
// Status of the previous fetch request.
private var sqlStatus: Int32 = 0
// Hold a reference to the connection so that it isn't closed
private let db: SQLiteDBConnection
// Cache of perviously fetched results (and their row numbers)
var cache = [Int: T]()
// Number of rows in the database
// XXX - When Cursor becomes an interface, this should be a normal property, but right now
// we can't override the Cursor getter for count with a stored property.
private let _count: Int
override public var count: Int {
get { return _count }
}
private var _position = -1
private var position: Int {
get {
return _position
}
set {
// If we're already there, shortcut out.
if (newValue == _position) {
return
}
// If we're currently somewhere in the list after this position
// we'll have to jump back to the start.
if (newValue < _position) {
sqlite3_reset(self.stmt)
_position = -1
}
// Now step up through the list to the requested position
while (newValue != _position) {
sqlStatus = sqlite3_step(self.stmt)
_position++
}
}
}
private init(db: SQLiteDBConnection, stmt: COpaquePointer, factory: (SDRow) -> T) {
// We will hold the db open until we're thrown away
self.db = db
self.stmt = stmt
self.factory = factory
// The only way I know to get a count. Walk through the entire statement to see how many rows there are.
var count = 0
self.sqlStatus = sqlite3_step(self.stmt)
while self.sqlStatus != SQLITE_DONE {
count++
self.sqlStatus = sqlite3_step(self.stmt)
}
sqlite3_reset(self.stmt)
self._count = count
super.init(status: .Success, msg: "success")
}
// Helper for finding all the column names in this statement.
lazy var columns: [String] = {
// This untangles all of the columns and values for this row when its created
let columnCount = sqlite3_column_count(self.stmt)
var columns = [String]()
for var i: Int32 = 0; i < columnCount; ++i {
let columnName = String.fromCString(sqlite3_column_name(self.stmt, i))!
columns.append(columnName)
}
return columns
}()
// Finalize the statement when we're destroyed. This will also release our reference
// to the database, which will hopefully close it as well.
deinit {
sqlite3_finalize(self.stmt)
}
override public subscript(index: Int) -> Any? {
get {
if let row = cache[index] {
return row
}
self.position = index
if self.sqlStatus != SQLITE_ROW {
return nil
}
let row = SDRow(connection: db, stmt: self.stmt, columns: self.columns)
let res = self.factory(row)
self.cache[index] = res
sqlite3_reset(self.stmt)
self._position = -1
return res
}
}
}
|
mpl-2.0
|
d59171527bcba46d327cd435d806d299
| 34.548276 | 140 | 0.593559 | 4.652076 | false | false | false | false |
Desgard/Calendouer-iOS
|
Calendouer/Calendouer/Default/AppDefault.swift
|
1
|
11640
|
//
// AppDefault.swift
// Calendouer
//
// Created by 段昊宇 on 2017/3/2.
// Copyright © 2017年 Desgard_Duan. All rights reserved.
//
import UIKit
import Spring
import RealmSwift
// Realm Database
// Log Function
func printLog<T>(message: T,
file: String = #file,
method: String = #function,
line: Int = #line) {
#if DEBUG
print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
#endif
}
// Color Quick Function
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor {
return UIColor(red: r / 255.0,
green: g / 255.0,
blue: b / 255.0,
alpha: a)
}
// Color Quick Constructor
extension UIColor {
convenience init(value: UInt, alpha: CGFloat) {
self.init (
red: CGFloat((value & 0xFF0000) >> 16) / 255.0,
green: CGFloat((value & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(value & 0x0000FF) / 255.0,
alpha: alpha
)
}
}
// Color
let DouRed: UIColor = RGBA(r: 244, g: 48, b: 14, a: 1)
let DouGreen: UIColor = UIColor(value: 0x4CAF50, alpha: 1)
let DouDarkGreen: UIColor = UIColor(value: 0x388E3C, alpha: 1)
let DouCardTextGray: UIColor = RGBA(r: 122, g: 122, b: 122, a: 1)
let DouBackGray: UIColor = UIColor(value: 0xFAFAFA, alpha: 1)
let DouStarYellow: UIColor = UIColor(value: 0xFFD021, alpha: 1)
// Font
let DouDefalutFontName: String = ".PingFangSC-Medium"
let DouIncFontName: String = ".PingFangSC-Regular"
let DouCalendarFontName: String = "Arial-BoldMT"
let DouDefalutFont: UIFont = UIFont(name: DouDefalutFontName, size: 15)!
let DouIncFont: UIFont = UIFont(name: DouIncFontName, size: 14)!
let DouCalendarFont: UIFont = UIFont(name: DouCalendarFontName, size: 90)!
// Identity
let CardTableViewCellId: String = "CardTableViewCell"
let SwitchSettingTableViewCellId: String = "SwitchSettingTableViewCell"
let TextSettingTableViewCellId: String = "TextSettingTableViewCell"
let TitleSettingTableViewCellId: String = "TitleSettingTableViewCell"
let MoviePostTableViewCellId: String = "MoviePostTableViewCell"
let MovieIntroductionTableViewCellId: String = "MovieIntroductionTableViewCell"
let MovieSummaryTableViewCellId: String = "MovieSummaryTableViewCell"
let DownloadCardTableViewCellId: String = "DownloadCardTableViewCell"
let DegreeLineTableViewCellId: String = "DegreeLineTableViewCell"
let DegreeRadarTableViewCellId: String = "DegreeRadarTableViewCell"
let DegreeLifeTableViewCellId: String = "DegreeLifeTableViewCell"
let LogoTableViewCellId: String = "LogoTableViewCell"
let AboutTextTableViewCellId: String = "AboutTextTableViewCell"
let AboutSettingTableViewCellId: String = "AboutSettingTableViewCell"
// Screen Size
let kIsIPhone5Size = (UIScreen.main.bounds.size.height == 568.0)
let kIsIPhone6Size = (UIScreen.main.bounds.size.height == 667.0)
let kIsIphone6PSize = (UIScreen.main.bounds.size.height == 736.0)
// NSObject
extension NSObject {
public func selfType() -> String {
return "\(self.classForCoder)"
}
}
// UITableView
extension UITableView {
public func reloadData(animated: Bool) {
self.reloadData()
if animated {
let animation: CATransition = CATransition()
animation.type = kCATransitionFade
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
animation.duration = 0.3
self.layer.add(animation, forKey: "UITableViewReloadDataAnimationKey")
}
}
}
// UILabel
extension UILabel {
public func changeText(data: String) {
UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseInOut], animations: {
self.alpha = 0
}) { _ in
self.text = data
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseIn], animations: {
self.alpha = 1
}, completion: { (_) in
})
}
}
}
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
let _CalendouerLogo = CalendouerLogoLayer()
public extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone9,1": return "iPhone 7"
case "iPhone9,2": return "iPhone 7 Plus"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,7", "iPad6,8": return "iPad Pro"
case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}
}
// logo
class CalendouerLogoLayer {
class func logoLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
//// Color Declarations
let fillColor = UIColor(red: 0.314, green: 0.694, blue: 0.329, alpha: 1.000)
//// LOGO 2
//// Group 矢量图 5
//// Group 8
//// Combined-Shape Drawing
let combinedShapePath = UIBezierPath()
combinedShapePath.move(to: CGPoint(x: 276.56, y: 68.81))
combinedShapePath.addLine(to: CGPoint(x: 210.06, y: 25.62))
combinedShapePath.addLine(to: CGPoint(x: 160.79, y: 110.96))
combinedShapePath.addCurve(to: CGPoint(x: 149.87, y: 113.89), controlPoint1: CGPoint(x: 158.58, y: 114.78), controlPoint2: CGPoint(x: 153.69, y: 116.09))
combinedShapePath.addLine(to: CGPoint(x: 144.62, y: 110.85))
combinedShapePath.addCurve(to: CGPoint(x: 141.69, y: 99.94), controlPoint1: CGPoint(x: 140.8, y: 108.65), controlPoint2: CGPoint(x: 139.49, y: 103.75))
combinedShapePath.addLine(to: CGPoint(x: 197.02, y: 4.11))
combinedShapePath.addCurve(to: CGPoint(x: 207.93, y: 1.19), controlPoint1: CGPoint(x: 199.22, y: 0.29), controlPoint2: CGPoint(x: 204.11, y: -1.02))
combinedShapePath.addLine(to: CGPoint(x: 208.22, y: 1.35))
combinedShapePath.addCurve(to: CGPoint(x: 214.72, y: 2.36), controlPoint1: CGPoint(x: 210.35, y: 0.76), controlPoint2: CGPoint(x: 212.72, y: 1.06))
combinedShapePath.addLine(to: CGPoint(x: 297.02, y: 55.81))
combinedShapePath.addCurve(to: CGPoint(x: 300.42, y: 60.53), controlPoint1: CGPoint(x: 298.78, y: 56.95), controlPoint2: CGPoint(x: 299.94, y: 58.66))
combinedShapePath.addCurve(to: CGPoint(x: 301.26, y: 69.32), controlPoint1: CGPoint(x: 302.38, y: 62.95), controlPoint2: CGPoint(x: 302.82, y: 66.4))
combinedShapePath.addLine(to: CGPoint(x: 29.2, y: 581))
combinedShapePath.addLine(to: CGPoint(x: 311.98, y: 581))
combinedShapePath.addLine(to: CGPoint(x: 192.07, y: 403.23))
combinedShapePath.addLine(to: CGPoint(x: 156.63, y: 464.63))
combinedShapePath.addCurve(to: CGPoint(x: 145.71, y: 467.56), controlPoint1: CGPoint(x: 154.42, y: 468.46), controlPoint2: CGPoint(x: 149.53, y: 469.77))
combinedShapePath.addLine(to: CGPoint(x: 140.45, y: 464.53))
combinedShapePath.addCurve(to: CGPoint(x: 137.53, y: 453.6), controlPoint1: CGPoint(x: 136.63, y: 462.32), controlPoint2: CGPoint(x: 135.32, y: 457.43))
combinedShapePath.addLine(to: CGPoint(x: 182.18, y: 376.26))
combinedShapePath.addCurve(to: CGPoint(x: 192.96, y: 373.25), controlPoint1: CGPoint(x: 184.36, y: 372.48), controlPoint2: CGPoint(x: 189.16, y: 371.16))
combinedShapePath.addCurve(to: CGPoint(x: 200.77, y: 376.69), controlPoint1: CGPoint(x: 195.91, y: 372.81), controlPoint2: CGPoint(x: 198.99, y: 374.05))
combinedShapePath.addLine(to: CGPoint(x: 336.7, y: 578.21))
combinedShapePath.addCurve(to: CGPoint(x: 337.45, y: 585.77), controlPoint1: CGPoint(x: 338.26, y: 580.53), controlPoint2: CGPoint(x: 338.45, y: 583.37))
combinedShapePath.addCurve(to: CGPoint(x: 338.13, y: 588.99), controlPoint1: CGPoint(x: 337.89, y: 586.76), controlPoint2: CGPoint(x: 338.13, y: 587.85))
combinedShapePath.addLine(to: CGPoint(x: 338.13, y: 595.06))
combinedShapePath.addCurve(to: CGPoint(x: 330.12, y: 603.05), controlPoint1: CGPoint(x: 338.13, y: 599.47), controlPoint2: CGPoint(x: 334.56, y: 603.05))
combinedShapePath.addLine(to: CGPoint(x: 18.01, y: 603.05))
combinedShapePath.addCurve(to: CGPoint(x: 14.79, y: 602.38), controlPoint1: CGPoint(x: 16.87, y: 603.05), controlPoint2: CGPoint(x: 15.78, y: 602.81))
combinedShapePath.addCurve(to: CGPoint(x: 9.15, y: 601.68), controlPoint1: CGPoint(x: 12.96, y: 602.83), controlPoint2: CGPoint(x: 10.95, y: 602.63))
combinedShapePath.addLine(to: CGPoint(x: 3.79, y: 598.83))
combinedShapePath.addCurve(to: CGPoint(x: 0.49, y: 588.01), controlPoint1: CGPoint(x: -0.1, y: 596.75), controlPoint2: CGPoint(x: -1.58, y: 591.92))
combinedShapePath.addLine(to: CGPoint(x: 276.56, y: 68.81))
combinedShapePath.close()
combinedShapePath.usesEvenOddFillRule = true
fillColor.setFill()
combinedShapePath.fill()
layer.path = combinedShapePath.cgPath
layer.bounds = layer.path!.boundingBoxOfPath
return layer
}
}
|
mit
|
2ed1b9304bba6c04b518cf3d693a6e06
| 49.324675 | 161 | 0.609892 | 3.603534 | false | false | false | false |
jacky-ttt/CodingEveryday
|
Day010-Swift and Play video/Project/PlayerTV/ViewController.swift
|
1
|
3950
|
// ViewController.swift
//
// Created by patrick piemonte on 11/26/14.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-present patrick piemonte (http://patrickpiemonte.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
let videoUrl = NSURL(string: "https://v.cdn.vine.co/r/videos/AA3C120C521177175800441692160_38f2cbd1ffb.1.5.13763579289575020226.mp4")!
class ViewController: UIViewController, PlayerDelegate {
private var player: Player!
// MARK: object lifecycle
convenience init() {
self.init(nibName: nil, bundle:nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
// MARK: view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.view.autoresizingMask = ([UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight])
self.player = Player()
self.player.delegate = self
self.player.view.frame = self.view.bounds
self.addChildViewController(self.player)
self.view.addSubview(self.player.view)
self.player.didMoveToParentViewController(self)
self.player.setUrl(videoUrl)
self.player.playbackLoops = true
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGestureRecognizer:")
tapGestureRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.PlayPause.rawValue)];
self.view.addGestureRecognizer(tapGestureRecognizer)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.player.playFromBeginning()
}
// MARK: UIGestureRecognizer
func handleTapGestureRecognizer(gestureRecognizer: UITapGestureRecognizer) {
switch (self.player.playbackState.rawValue) {
case PlaybackState.Stopped.rawValue:
self.player.playFromBeginning()
case PlaybackState.Paused.rawValue:
self.player.playFromCurrentTime()
case PlaybackState.Playing.rawValue:
self.player.pause()
case PlaybackState.Failed.rawValue:
self.player.pause()
default:
self.player.pause()
}
}
// MARK: PlayerDelegate
func playerReady(player: Player) {
}
func playerPlaybackStateDidChange(player: Player) {
}
func playerBufferingStateDidChange(player: Player) {
}
func playerPlaybackWillStartFromBeginning(player: Player) {
}
func playerPlaybackDidEnd(player: Player) {
}
func playerCurrentTimeDidChange(player: Player) {
}
}
|
apache-2.0
|
45237ca6b7173ab2bd563701b63c8add
| 32.760684 | 134 | 0.683544 | 4.680095 | false | false | false | false |
LYM-mg/DemoTest
|
其他功能/SwiftyDemo/Pods/SkeletonView/Sources/SkeletonAnimationBuilder.swift
|
2
|
3125
|
//
// SkeletonAnimationBuilder.swift
// SkeletonView-iOS
//
// Created by Juanpe Catalán on 17/11/2017.
// Copyright © 2017 SkeletonView. All rights reserved.
//
import UIKit
typealias GradientAnimationPoint = (from: CGPoint, to: CGPoint)
public enum GradientDirection {
case leftRight
case rightLeft
case topBottom
case bottomTop
case topLeftBottomRight
case bottomRightTopLeft
public func slidingAnimation(duration: CFTimeInterval = 1.5) -> SkeletonLayerAnimation {
return SkeletonAnimationBuilder().makeSlidingAnimation(withDirection: self, duration: duration)
}
// codebeat:disable[ABC]
var startPoint: GradientAnimationPoint {
switch self {
case .leftRight:
return (from: CGPoint(x:-1, y:0.5), to: CGPoint(x:1, y:0.5))
case .rightLeft:
return (from: CGPoint(x:1, y:0.5), to: CGPoint(x:-1, y:0.5))
case .topBottom:
return (from: CGPoint(x:0.5, y:-1), to: CGPoint(x:0.5, y:1))
case .bottomTop:
return (from: CGPoint(x:0.5, y:1), to: CGPoint(x:0.5, y:-1))
case .topLeftBottomRight:
return (from: CGPoint(x:-1, y:-1), to: CGPoint(x:1, y:1))
case .bottomRightTopLeft:
return (from: CGPoint(x:1, y:1), to: CGPoint(x:-1, y:-1))
}
}
var endPoint: GradientAnimationPoint {
switch self {
case .leftRight:
return (from: CGPoint(x:0, y:0.5), to: CGPoint(x:2, y:0.5))
case .rightLeft:
return ( from: CGPoint(x:2, y:0.5), to: CGPoint(x:0, y:0.5))
case .topBottom:
return ( from: CGPoint(x:0.5, y:0), to: CGPoint(x:0.5, y:2))
case .bottomTop:
return ( from: CGPoint(x:0.5, y:2), to: CGPoint(x:0.5, y:0))
case .topLeftBottomRight:
return ( from: CGPoint(x:0, y:0), to: CGPoint(x:2, y:2))
case .bottomRightTopLeft:
return ( from: CGPoint(x:2, y:2), to: CGPoint(x:0, y:0))
}
}
// codebeat:enable[ABC]
}
public class SkeletonAnimationBuilder {
public init() {
}
public func makeSlidingAnimation(withDirection direction: GradientDirection, duration: CFTimeInterval = 1.5) -> SkeletonLayerAnimation {
return { layer in
let startPointAnim = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.startPoint))
startPointAnim.fromValue = direction.startPoint.from
startPointAnim.toValue = direction.startPoint.to
let endPointAnim = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.endPoint))
endPointAnim.fromValue = direction.endPoint.from
endPointAnim.toValue = direction.endPoint.to
let animGroup = CAAnimationGroup()
animGroup.animations = [startPointAnim, endPointAnim]
animGroup.duration = duration
animGroup.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
animGroup.repeatCount = .infinity
return animGroup
}
}
}
|
mit
|
8acdf761325867f2888e3c0a5ab9013d
| 34.896552 | 140 | 0.607749 | 3.978344 | false | false | false | false |
afaan5556/ToolBelt3.0
|
xcode-toolbelt/ToolBelt/ToolBelt/MyToolTableViewController.swift
|
1
|
2276
|
import UIKit
import Alamofire
class MyToolTableViewController: UITableViewController {
var mytools = [Tool]()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
loadMyTools()
}
override func viewDidLoad() {
super.viewDidLoad()
}
func loadMyTools() {
self.mytools = []
let defaults = NSUserDefaults.standardUserDefaults()
let userid: Int = defaults.objectForKey("toolBeltUserID") as! Int
Alamofire.request(.GET, "http://afternoon-bayou-17340.herokuapp.com/users/\(userid)/tools").responseJSON { response in
if let JSON = response.result.value {
for var i = 0; i < JSON.count; i++ {
let title = (JSON[i]["title"] as? String)!
let distanceToTool = 0.0
var description: String
if let des = JSON[i]["description"] as? NSNull {
description = ""
} else {
description = (JSON[i]["description"] as? String)!
}
let myTool = Tool(title: title, description: description, ownerId: userid, distance: distanceToTool)
self.mytools += [myTool]
}
self.tableView.reloadData()
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mytools.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "MyToolsTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! MyToolsTableViewCell
let mytool = mytools[indexPath.row]
cell.myToolTitle.text = mytool.title
cell.myToolDescription.text = mytool.description
return cell
}
}
|
mit
|
4b263156505446f4ba498e3422352d48
| 32.485294 | 128 | 0.544815 | 5.592138 | false | false | false | false |
roehrdor/diagnoseit-ios-mobile-agent
|
SSIDSniffer.swift
|
1
|
2042
|
/*
Copyright (c) 2017 Oliver Roehrdanz
Copyright (c) 2017 Matteo Sassano
Copyright (c) 2017 Christopher Voelker
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 SystemConfiguration.CaptiveNetwork
public class SSIDSniffer {
class func getSSID() -> String? {
/* Note:
CNCopySupportedInterfaces returns nil while running on the emulator
*/
let interfaces = CNCopySupportedInterfaces()
if(interfaces == nil) {
return "NO SSID"
}
let interfaceArray = interfaces as! [String]
if interfaceArray.count < 1 {
return "NO SSID"
}
let interfaceName = interfaceArray[0] as String
let unsafeInterfaceData = CNCopyCurrentNetworkInfo(interfaceName as CFString)
if(unsafeInterfaceData == nil) {
return "NO SSID"
}
let interfaceData = unsafeInterfaceData as! Dictionary<String, AnyObject>
return interfaceData["SSID"] as? String
}
}
|
mit
|
f9b9dcf7f6206b37cedafb8d42f17200
| 37.528302 | 85 | 0.709109 | 4.827423 | false | false | false | false |
J3D1-WARR10R/WikiRaces
|
WikiRaces/Shared/Menu View Controllers/PlusViewController/ActivityButton.swift
|
2
|
1851
|
//
// ActivityButton.swift
// WikiRaces
//
// Created by Andrew Finke on 5/4/20.
// Copyright © 2020 Andrew Finke. All rights reserved.
//
import UIKit
class ActivityButton: UIButton {
// MARK: - Types -
enum DisplayState {
case label, activity
}
// MARK: - Properties -
var displayState = DisplayState.label {
didSet {
setNeedsLayout()
UIView.animate(withDuration: 0.2) {
self.layoutIfNeeded()
}
}
}
let label: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
return label
}()
let activityIndicatorView: UIActivityIndicatorView = {
let activityIndicatorView = UIActivityIndicatorView(style: .medium)
activityIndicatorView.startAnimating()
return activityIndicatorView
}()
// MARK: - Initalization -
init() {
super.init(frame: .zero)
addSubview(label)
addSubview(activityIndicatorView)
label.isUserInteractionEnabled = false
activityIndicatorView.isUserInteractionEnabled = false
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Life Cycle -
override func layoutSubviews() {
super.layoutSubviews()
label.frame = bounds
activityIndicatorView.center = label.center
activityIndicatorView.color = .wkrActivityIndicatorColor(for: traitCollection)
switch displayState {
case .label:
label.alpha = 1.0
activityIndicatorView.alpha = 0.0
case .activity:
label.alpha = 0.0
activityIndicatorView.alpha = 1.0
}
}
}
|
mit
|
19f103f6a7f6981361f24be8a5f59551
| 23.025974 | 86 | 0.604865 | 5.054645 | false | false | false | false |
Panl/Gank.lu
|
Gank.lu/SwiftUI/GankViews.swift
|
1
|
3897
|
//
// GirlsView.swift
// Gank.lu
//
// Created by Lei Pan on 2020/1/29.
// Copyright © 2020 smartalker. All rights reserved.
//
import SwiftUI
import struct Kingfisher.KFImage
import struct Kingfisher.DownsamplingImageProcessor
extension View {
func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
clipShape( RoundedCorner(radius: radius, corners: corners) )
}
}
struct RoundedCorner: Shape {
var radius: CGFloat = .infinity
var corners: UIRectCorner = .allCorners
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
return Path(path.cgPath)
}
}
struct GirlView: View {
let gank: GankData
init(gank: GankData) {
self.gank = gank
}
var body: some View {
ZStack(alignment: .topLeading) {
KFImage(URL(string: gank.url),options: [
.transition(.fade(0.8)),
.processor(
DownsamplingImageProcessor(size: CGSize(width: 375 * 1.5, height: 340 * 1.5))
),
.cacheOriginalImage
])
.resizable()
.aspectRatio(contentMode: .fill)
.frame(height: 340)
.clipped()
LinearGradient(gradient: Gradient(colors: [Color.black.opacity(0.3), Color.black.opacity(0.3)]), startPoint: .top, endPoint: .bottom)
Text(gank.type)
.foregroundColor(.white)
.font(.custom("", size: 12))
.padding(EdgeInsets(top: 6, leading: 12, bottom: 6, trailing: 8))
.background(Color.blue)
.cornerRadius(8, corners: .bottomRight)
VStack(alignment: .leading) {
Spacer()
Text("\(gank.desc) by \(gank.author)")
.frame(maxWidth: .infinity)
.foregroundColor(.white)
.multilineTextAlignment(.leading)
.padding(12)
.shadow(radius: 4)
HStack {
Text(gank.title).foregroundColor(.white)
Spacer()
Text(DateUtil.stringToRelative(gank.publishedAt)).font(.system(size: 12)).foregroundColor(.white)
}.padding(EdgeInsets(top: 8, leading: 16, bottom: 16, trailing: 16)).shadow(radius: 4)
}
}
.background(Color.white)
.cornerRadius(8)
.shadow(radius: 4)
}
}
struct GankView: View {
let gank: GankData
init(gank: GankData) {
self.gank = gank
}
var body: some View {
HStack {
ZStack(alignment: .topLeading){
KFImage(URL(string: gank.cover),options: [
.transition(.fade(0.2)),
.processor(
DownsamplingImageProcessor(size: CGSize(width: 120 * 3, height: 120 * 3))
),
.cacheOriginalImage
])
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 120, height: 120)
.background(Color.gray)
.clipped()
Text(gank.type)
.foregroundColor(.white)
.font(.custom("", size: 12))
.padding(EdgeInsets(top: 6, leading: 12, bottom: 6, trailing: 8))
.background(Color.blue)
.cornerRadius(8, corners: .bottomRight)
}
VStack(alignment: .leading) {
Text(gank.title).font(.system(size: 16)).padding(EdgeInsets(top: 8, leading: 4, bottom: 8, trailing: 12))
Text(gank.desc)
.font(.system(size: 13))
.foregroundColor(.gray)
.frame(maxWidth: .infinity)
.multilineTextAlignment(.leading)
.padding(EdgeInsets(top: 0, leading: 4, bottom: 4, trailing: 12))
Spacer()
HStack {
Text(gank.author).font(.system(size: 13))
Spacer()
Text(DateUtil.stringToRelative(gank.publishedAt)).font(.system(size: 12)).foregroundColor(.gray)
}.padding(EdgeInsets(top: 0, leading: 4, bottom: 8, trailing: 12))
}
}
.background(Color.white)
.cornerRadius(8)
.shadow(radius: 4)
}
}
|
gpl-3.0
|
dde7bd12e853ad644c710d1f424be63a
| 29.20155 | 139 | 0.601129 | 3.931382 | false | false | false | false |
AlesTsurko/AudioKit
|
Tests/Tests/AKSandPaper.swift
|
2
|
1658
|
//
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/26/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: Float = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let note = SandPaperNote()
let sandPaper = AKSandPaper()
sandPaper.intensity = note.intensity
sandPaper.dampingFactor = note.dampingFactor
setAudioOutput(sandPaper)
enableParameterLog(
"Intensity = ",
parameter: sandPaper.intensity,
timeInterval:1
)
enableParameterLog(
"Damping Factor = ",
parameter: sandPaper.dampingFactor,
timeInterval:1
)
}
}
class SandPaperNote: AKNote {
var intensity = AKNoteProperty()
var dampingFactor = AKNoteProperty()
override init() {
super.init()
addProperty(intensity)
addProperty(dampingFactor)
}
convenience init(intensity: Int, dampingFactor: Float) {
self.init()
self.intensity.value = Float(intensity)
self.dampingFactor.value = dampingFactor
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
let phrase = AKPhrase()
for i in 1...10 {
let note = SandPaperNote(intensity: 40+i*20, dampingFactor: 1.1-Float(i)/10.0)
note.duration.value = 1.0
phrase.addNote(note, atTime: Float(i-1))
}
instrument.playPhrase(phrase)
let manager = AKManager.sharedManager()
while(manager.isRunning) {} //do nothing
println("Test complete!")
|
lgpl-3.0
|
2cd8948d62cc72ee6a37a1cbc25973d4
| 22.352113 | 82 | 0.648975 | 4.306494 | false | true | false | false |
xuephil/Perfect
|
PerfectLib/LibEvent.swift
|
2
|
4597
|
//
// LibEvent.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/5/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// 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>.
//
import LibEvent
#if os(Linux)
import SwiftGlibc
#endif
// I'm unsure why these aren't coming through
/** Indicates that a timeout has occurred. It's not necessary to pass
this flag to event_for new()/event_assign() to get a timeout. */
let EV_TIMEOUT: Int32 = 0x01
/** Wait for a socket or FD to become readable */
let EV_READ: Int32 = 0x02
/** Wait for a socket or FD to become writeable */
let EV_WRITE: Int32 = 0x04
typealias EventCallBack = (Int32, Int16, AnyObject?) -> ()
private typealias PrimEventCallBack = @convention(c) (Int32, Int16, UnsafeMutablePointer<Void>) -> ()
class LibEvent {
internal static let eventBase: LibEventBase = LibEventBase()
private var event: COpaquePointer? = nil
private var userData: AnyObject?
private var cb: EventCallBack?
private var base: LibEventBase?
private static var eventCallBack: PrimEventCallBack {
let c: PrimEventCallBack = {
(a,b,c) in
let evt = Unmanaged<LibEvent>.fromOpaque(COpaquePointer(c)).takeRetainedValue()
let queue = evt.base!.eventDispatchQueue
let userData: AnyObject? = evt.userData
let callBack: EventCallBack = evt.cb!
evt.base = nil
evt.cb = nil
evt.userData = nil
evt.del()
Threading.dispatchBlock(queue) {
callBack(a, b, userData)
}
}
return c
}
init(base: LibEventBase, fd: Int32, what: Int32, userData: AnyObject?, callBack: EventCallBack) {
self.userData = userData
self.cb = callBack
self.base = base
self.event = event_new(base.eventBase, fd, Int16(what), LibEvent.eventCallBack, UnsafeMutablePointer(Unmanaged.passRetained(self).toOpaque()))
}
deinit {
del()
}
func add(inout tv: timeval) {
event_add(event!, &tv)
}
func add(timeout: Double) {
if timeout == -1 {
event_add(event!, nil)
} else {
var tv: timeval = timeval()
let i = floor(timeout)
let f = timeout - i
tv.tv_sec = Int(i)
#if os(Linux)
tv.tv_usec = Int(f * 100000)
#else
tv.tv_usec = Int32(f * 100000)
#endif
event_add(event!, &tv)
}
}
func add() {
event_add(event!, nil)
}
func del() {
if let e = event {
event_free(e)
self.event = nil
}
}
}
let EVLOOP_NO_EXIT_ON_EMPTY = Int32(0/*0x04*/) // not supported until libevent 2.1
class LibEventBase {
var eventBase: COpaquePointer
private var baseDispatchQueue: Threading.ThreadQueue
var eventDispatchQueue: Threading.ThreadQueue
init() {
evthread_use_pthreads()
// !FIX! this is not ideal, but since we are the only ones dispatching to this queue,
// and it only happens from within the singular libevent loop, we can ensure is it not called concurrently.
baseDispatchQueue = Threading.createConcurrentQueue("LibEvent Base") //Threading.createSerialQueue("LibEvent Base")
eventDispatchQueue = Threading.createConcurrentQueue("LibEvent Event")
eventBase = event_base_new()
addDummyEvent()
triggerEventBaseLoop()
}
private func addDummyEvent() {
let event = LibEvent(base: self, fd: -1, what: EV_TIMEOUT, userData: nil) {
[weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in
self?.addDummyEvent()
}
event.add(1_000_000)
}
private func triggerEventBaseLoop() {
Threading.dispatchBlock(baseDispatchQueue) { [weak self] in
self?.eventBaseLoop()
}
}
private func eventBaseLoop() {
let r = event_base_dispatch(self.eventBase) //event_base_loop(self.eventBase, EVLOOP_NO_EXIT_ON_EMPTY)
if r == 1 {
triggerEventBaseLoop()
} else if r == -1 {
print("eventBaseLoop exited because of error")
}
}
}
|
agpl-3.0
|
93562544e9715bde9720fcbacf74e569
| 26.041176 | 144 | 0.700457 | 3.323933 | false | false | false | false |
chris-wood/reveiller
|
reveiller/Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisLabel.swift
|
12
|
802
|
//
// ChartAxisLabel.swift
// swift_charts
//
// Created by ischuetz on 01/03/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartAxisLabel {
public let text: String
let settings: ChartLabelSettings
var hidden: Bool = false
lazy var textSize: CGSize = {
let size = ChartUtils.textSize(self.text, font: self.settings.font)
if self.settings.rotation == 0 {
return size
} else {
return ChartUtils.boundingRectAfterRotatingRect(CGRectMake(0, 0, size.width, size.height), radians: self.settings.rotation * CGFloat(M_PI) / 180.0).size
}
}()
public init(text: String, settings: ChartLabelSettings) {
self.text = text
self.settings = settings
}
}
|
mit
|
c7fe4af24ca2e312e97ba041a4f5801b
| 24.870968 | 164 | 0.634663 | 4.134021 | false | false | false | false |
xu6148152/binea_project_for_ios
|
Trax/Trax/GPXViewController.swift
|
1
|
1224
|
//
// ViewController.swift
// Trax
//
// Created by Binea Xu on 7/18/15.
// Copyright (c) 2015 Binea Xu. All rights reserved.
//
import UIKit
import MapKit
class GPXViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView! {
didSet{
mapView.mapType = .Satellite
mapView.delegate = self
}
}
var gpxURL: NSURL? {
didSet{
if let url = gpxURL{
}
}
}
private func clearWayPoints(){
// if mapView?.annotations != nil {
// mapView.removeAnnotation(mapView.annotations as [MKAnnotation])
// }
}
private func handleWaypoints(){
}
override func viewDidLoad() {
super.viewDidLoad()
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
let appDelete = UIApplication.sharedApplication()
center.addObserverForName(GPXURL.notification, object: appDelete, queue: queue){
notification in
if let url = notification?.userInfo?[GPXURL.key] as? NSURL{
}
}
}
}
|
mit
|
82017d1ef7bc70d68247aff1f53ebb3b
| 21.254545 | 88 | 0.559641 | 4.955466 | false | false | false | false |
toshiapp/toshi-ios-client
|
Toshi/Controllers/Sign In/SignInHeaderView.swift
|
1
|
749
|
import Foundation
import UIKit
import TinyConstraints
final class SignInHeaderView: UIView {
private lazy var titleLabel: UILabel = {
let view = UILabel()
view.text = Localized.passphrase_sign_in_title
view.textAlignment = .center
view.textColor = Theme.darkTextColor
view.font = Theme.preferredTitle1()
view.adjustsFontForContentSizeCategory = true
view.numberOfLines = 0
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
titleLabel.edges(to: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
e8e3e2dc1ffe0da81cd4ee9bad82565b
| 24.827586 | 59 | 0.626168 | 4.960265 | false | false | false | false |
SKrotkih/YTLiveStreaming
|
YTLiveStreaming/HttpBodyEncoding.swift
|
1
|
843
|
//
// HttpBodyEncoding.swift
// YTLiveStreaming
//
// Created by Serhii Krotkykh on 16.03.2021.
// Copyright © 2021 Serhii Krotkykh. All rights reserved.
//
import Foundation
import Alamofire
struct JSONBodyStringEncoding: ParameterEncoding {
private let jsonBody: String
init(jsonBody: String) {
self.jsonBody = jsonBody
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
let dataBody = (jsonBody as NSString).data(using: String.Encoding.utf8.rawValue)
if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest?.httpBody = dataBody
return urlRequest!
}
}
|
mit
|
d07681b9abf8554044d234030919c271
| 29.071429 | 105 | 0.691211 | 4.502674 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/Classes/ViewRelated/Gutenberg/GutenbergWeb/GutenbergWebViewController.swift
|
1
|
6600
|
import UIKit
import WebKit
import Gutenberg
class GutenbergWebViewController: GutenbergWebSingleBlockViewController, WebKitAuthenticatable, NoResultsViewHost {
enum GutenbergWebError: Error {
case wrongEditorUrl(String?)
}
let authenticator: RequestAuthenticator?
private let url: URL
private let progressView = WebProgressView()
private let userId: String
let gutenbergReadySemaphore = DispatchSemaphore(value: 0)
init(with post: AbstractPost, block: Block) throws {
authenticator = GutenbergRequestAuthenticator(blog: post.blog)
userId = "\(post.blog.userID ?? 1)"
guard
let siteURL = post.blog.homeURL,
// Use wp-admin URL since Calypso URL won't work retriving the block content.
let editorURL = URL(string: "\(siteURL)/wp-admin/post-new.php")
else {
throw GutenbergWebError.wrongEditorUrl(post.blog.homeURL as String?)
}
url = editorURL
try super.init(block: block, userId: userId, isWPOrg: !post.blog.isHostedAtWPcom)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
addNavigationBarElements()
showLoadingMessage()
addProgressView()
startObservingWebView()
waitForGutenbergToLoad(fallback: showTroubleshootingInstructions)
}
deinit {
webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard
let object = object as? WKWebView,
object == webView,
let keyPath = keyPath
else {
return
}
switch keyPath {
case #keyPath(WKWebView.estimatedProgress):
progressView.progress = Float(webView.estimatedProgress)
progressView.isHidden = webView.estimatedProgress == 1
default:
assertionFailure("Observed change to web view that we are not handling")
}
}
override func getRequest(for webView: WKWebView, completion: @escaping (URLRequest) -> Void) {
authenticatedRequest(for: url, on: webView) { (request) in
completion(request)
}
}
override func onPageLoadScripts() -> [WKUserScript] {
return [
loadCustomScript(named: "extra-localstorage-entries", with: userId)
].compactMap { $0 }
}
override func onGutenbergReadyScripts() -> [WKUserScript] {
return [
loadCustomScript(named: "remove-nux")
].compactMap { $0 }
}
override func onGutenbergReady() {
super.onGutenbergReady()
navigationItem.rightBarButtonItem?.isEnabled = true
DispatchQueue.main.async { [weak self] in
self?.hideNoResults()
self?.gutenbergReadySemaphore.signal()
}
}
private func loadCustomScript(named name: String, with argument: String? = nil) -> WKUserScript? {
do {
return try SourceFile(name: name, type: .js).jsScript(with: argument)
} catch {
assertionFailure("Failed to load `\(name)` JS script for Unsupported Block Editor: \(error)")
return nil
}
}
private func addNavigationBarElements() {
let buttonTitle = NSLocalizedString("Continue", comment: "Apply changes localy to single block edition in the web block editor")
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: buttonTitle,
style: .done,
target: self,
action: #selector(onSaveButtonPressed)
)
navigationItem.rightBarButtonItem?.isEnabled = false
}
private func showLoadingMessage() {
let title = NSLocalizedString("Loading the block editor.", comment: "Loading message shown while the Unsupported Block Editor is loading.")
let subtitle = NSLocalizedString("Please ensure the block editor is enabled on your site. If it is not enabled, it will not load.", comment: "Message asking users to make sure that the block editor is enabled on their site in order for the Unsupported Block Editor to load properly.")
configureAndDisplayNoResults(on: view, title: title, subtitle: subtitle, accessoryView: NoResultsViewController.loadingAccessoryView())
}
private func waitForGutenbergToLoad(fallback: @escaping () -> Void) {
DispatchQueue.global(qos: .background).async { [weak self] in
let timeout: TimeInterval = 15
// blocking call
if self?.gutenbergReadySemaphore.wait(timeout: .now() + timeout) == .timedOut {
DispatchQueue.main.async {
fallback()
}
}
}
}
private func showTroubleshootingInstructions() {
let title = NSLocalizedString("Unable to load the block editor right now.", comment: "Title message shown when the Unsupported Block Editor fails to load.")
let subtitle = NSLocalizedString("Please ensure the block editor is enabled on your site and try again.", comment: "Subtitle message shown when the Unsupported Block Editor fails to load. It asks users to verify that the block editor is enabled on their site before trying again.")
// This does nothing if the "no results" screen is not currently displayed, which is the intended behavior
updateNoResults(title: title, subtitle: subtitle, image: "cloud")
}
private func startObservingWebView() {
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: [.new], context: nil)
}
private func addProgressView() {
progressView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(progressView)
NSLayoutConstraint.activate([
progressView.topAnchor.constraint(equalTo: view.topAnchor),
progressView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
progressView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
}
}
extension GutenbergWebViewController {
override func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
super.webView(webView, didCommit: navigation)
if webView.url?.absoluteString.contains("reauth=1") ?? false {
hideNoResults()
removeCoverViewAnimated()
}
}
}
|
gpl-2.0
|
46dc173db00affa147a15eac938030aa
| 39.740741 | 292 | 0.661818 | 5.168363 | false | false | false | false |
turbolent/SwiftParserCombinators
|
Sources/ParserCombinators/Chain.swift
|
1
|
3170
|
import Foundation
extension Parser {
/// Creates a new parser that repeatedly applies this parser interleaved with
/// the separating parser, until it fails, and returns all parsed values.
/// The separating parser specifies how the results parsed by this parser should be combined.
///
/// - Parameters:
/// - separator:
/// The parser that separates the occurrences of this parser. The result should
/// be a function that specifies how the results of this parser should be combined.
/// - min:
/// The minumum number of times this parser needs to succeed. If the parser succeeds
/// fewer times, the new parser returns a non-fatal failure, i.e. not an error,
/// and so backtracking is allowed.
/// - max:
/// The maximum number of times this parser is to be applied.
///
public func chainLeft(
separator: @autoclosure @escaping () -> Parser<(T, T) -> T, Element>,
min: Int = 0, max: Int? = nil
)
-> Parser<T?, Element>
{
return ParserCombinators.chainLeft(self,
separator: separator(),
min: min,
max: max)
}
}
/// Creates a new parser that repeatedly applies the given parser interleaved with
/// the separating parser, until it fails, and returns all parsed values.
/// The separating parser specifies how the results parsed by the given parser should be combined.
///
/// - Parameters:
/// - parser:
/// The parser to be applied successively to the input.
/// - separator:
/// The parser that separates the occurrences of the given parser. The result should
/// be a function that specifies how the results of the given parser should be combined.
/// - min:
/// The minumum number of times the given parser needs to succeed.
/// If the parser succeeds fewer times, the new parser returns a non-fatal failure,
/// i.e. not an error, and so backtracking is allowed.
/// - max:
/// The maximum number of times the given parser is to be applied.
///
public func chainLeft<T, Element>(
_ parser: @autoclosure @escaping () -> Parser<T, Element>,
separator: @autoclosure @escaping () -> Parser<(T, T) -> T, Element>,
min: Int = 0,
max: Int? = nil
)
-> Parser<T?, Element>
{
typealias Op = (T, T) -> T
let lazyParser = Lazy(parser)
let lazySeparator = Lazy(separator)
let rest: Parser<[(Op, T)], Element> = lazySeparator.value
.seq(lazyParser.value)
.rep(min: Swift.max(0, min - 1),
max: max.map { $0 - 1})
let all: Parser<T?, Element> =
lazyParser.value
.seq(rest)
.map { (firstAndRest: (T, [(Op, T)])) -> T in
let (first, rest) = firstAndRest
return rest.reduce(first) { result, opAndValue -> T in
let (op, value) = opAndValue
return op(result, value)
}
}
if min > 0 {
return all
}
return all || success(nil)
}
|
mit
|
05c982cf2b51c85204bc7d8ee2380652
| 36.294118 | 98 | 0.581073 | 4.301221 | false | false | false | false |
manfengjun/KYMart
|
Section/Order/View/KYOrderButton.swift
|
1
|
1985
|
//
// KYOrderButton.swift
// KYMart
//
// Created by jun on 2017/7/11.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYOrderButton: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var button: UIButton!
var SelectResultClosure: ResultValueClosure? // 闭包
var textColor:UIColor = UIColor.hexStringColor(hex: "#333333"){
didSet {
button.setTitleColor(textColor, for: .normal)
}
}
var title:String = "取消订单"{
didSet {
button.setTitle(title, for: .normal)
}
}
var bgColor:UIColor = UIColor.white{
didSet {
button.backgroundColor = bgColor
}
}
var borderColor:UIColor = UIColor.hexStringColor(hex: "#333333"){
didSet {
layer.borderColor = borderColor.cgColor
layer.borderWidth = 0.5
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView = Bundle.main.loadNibNamed("KYOrderButton", owner: self, options: nil)?.first as! UIView
contentView.frame = self.bounds
addSubview(contentView)
awakeFromNib()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
layer.masksToBounds = true
layer.cornerRadius = 3.0
button.setTitle(title, for: .normal)
button.setTitleColor(textColor, for: .normal)
button.backgroundColor = bgColor
layer.borderColor = borderColor.cgColor
layer.borderWidth = 0.5
isUserInteractionEnabled = true
}
@IBAction func selectAction(_ sender: UIButton) {
SelectResultClosure?(sender)
}
/**
加减按钮的响应闭包回调
*/
func selectResult(_ finished: @escaping ResultValueClosure) {
SelectResultClosure = finished
}
}
|
mit
|
19f7a2d01dfcaae30e6bb7ef0a5e43ae
| 26.055556 | 108 | 0.60883 | 4.562061 | false | false | false | false |
darthpelo/TimerH2O
|
TimerH2O/Watch Extension/ComplicationController.swift
|
1
|
9100
|
//
// ComplicationController.swift
// test WatchKit Extension
//
// Created by Alessio Roberto on 02/07/2017.
// Copyright © 2017 Alessio Roberto. All rights reserved.
//
import ClockKit
import WatchKit
class ComplicationController: NSObject, CLKComplicationDataSource {
func getNextRequestedUpdateDate(handler: @escaping (Date?) -> Swift.Void) {
// Call the handler with the date when you would next like to be
// given the opportunity to update your complication content
//---update in the next 1 hour---
handler(Date(timeIntervalSinceNow: 3600))
}
func requestedUpdateDidBegin() {
reloadOrExtendData()
}
func requestedUpdateBudgetExhausted() {
reloadOrExtendData()
}
func reloadOrExtendData() {
let server = CLKComplicationServer.sharedInstance()
guard let complications = server.activeComplications,
complications.count > 0 else { return }
// To invalidate the existing data
for complication in complications {
server.reloadTimeline(for: complication)
}
}
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
handler([])
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(nil)
}
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
handler(.showOnLockScreen)
}
// MARK: - Timeline Population
// Call the handler with the current timeline entry
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
var entry: CLKComplicationTimelineEntry?
let now = NSDate()
if let template = complicationTemplate(complication.family) {
entry = CLKComplicationTimelineEntry(date: now as Date, complicationTemplate: template)
}
handler(entry)
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// Call the handler with the timeline entries after to the given date
handler(nil)
}
// MARK: - Placeholder Templates
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
var template: CLKComplicationTemplate?
switch complication.family {
case .modularSmall:
let modularSmallTemplate =
CLKComplicationTemplateModularSmallRingText()
modularSmallTemplate.textProvider =
CLKSimpleTextProvider(text: " 💧")
modularSmallTemplate.fillFraction = 0.75
modularSmallTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularSmallTemplate
case .circularSmall:
let modularSmallTemplate =
CLKComplicationTemplateCircularSmallRingText()
modularSmallTemplate.textProvider =
CLKSimpleTextProvider(text: " 💧")
modularSmallTemplate.fillFraction = 0.75
modularSmallTemplate.ringStyle = CLKComplicationRingStyle.closed
template = modularSmallTemplate
case .utilitarianSmall:
let utilitarianSmallTemplate = CLKComplicationTemplateUtilitarianSmallRingText()
let userdef = UserDefaults.standard
let value = userdef.integer(forKey: DictionaryKey.progress.rawValue)
let progress = Double(Double(value) / 2000.0) * 100
utilitarianSmallTemplate.textProvider =
CLKSimpleTextProvider(text: " 💧")
utilitarianSmallTemplate.fillFraction = Float(progress/100)
utilitarianSmallTemplate.ringStyle = CLKComplicationRingStyle.closed
utilitarianSmallTemplate.tintColor = .blue
template = utilitarianSmallTemplate
case .utilitarianSmallFlat:
let utilitarianSmallFlat = CLKComplicationTemplateUtilitarianSmallFlat()
let userdef = UserDefaults.standard
let value = userdef.integer(forKey: DictionaryKey.progress.rawValue)
utilitarianSmallFlat.textProvider = CLKSimpleTextProvider(text: "\(value)")
template = utilitarianSmallFlat
case .utilitarianLarge:
let utilitarianLarge = CLKComplicationTemplateUtilitarianLargeFlat()
let userdef = UserDefaults.standard
let value = userdef.integer(forKey: DictionaryKey.progress.rawValue)
utilitarianLarge.textProvider = CLKSimpleTextProvider(text: "\(value) ml left")
template = utilitarianLarge
default:
template = nil
}
handler(template)
}
// MARK: - Private
private func complicationTemplate(_ family: CLKComplicationFamily) -> CLKComplicationTemplate? {
logger(object: "Get current time line for complication: \(family)")
var template: CLKComplicationTemplate?
let value = UserDefaults.standard.integer(forKey: DictionaryKey.progress.rawValue)
let progress = self.progress(ofValue: value)
var text: String
if progress < 0 || progress > 1 {
text = WatchText.error.rawValue
} else if progress == 0 {
text = WatchText.ok.rawValue
} else {
text = WatchText.onGoing.rawValue
}
switch family {
case .modularSmall:
template = modularSmallTemplate(text, progress)
case .circularSmall:
template = circularSmallTemplate(text, progress)
case .utilitarianSmall:
template = utilitarianSmallTemplate(text, progress)
case .utilitarianSmallFlat:
let utilitarianSmallFlat = CLKComplicationTemplateUtilitarianSmallFlat()
utilitarianSmallFlat.textProvider = CLKSimpleTextProvider(text: "\(value)💧")
template = utilitarianSmallFlat
case .utilitarianLarge:
let utilitarianLarge = CLKComplicationTemplateUtilitarianLargeFlat()
utilitarianLarge.textProvider = CLKSimpleTextProvider(text: "\(value) ml left")
template = utilitarianLarge
default:
template = nil
}
return template
}
private func progress(ofValue value: Int) -> Double {
var goal = UserDefaults.standard.integer(forKey: DictionaryKey.goal.rawValue)
if goal < 1 { goal = 2000 }
return Double(Double(value) / Double(goal))
}
private func modularSmallTemplate(_ text: String, _ progress: Double) -> CLKComplicationTemplate? {
let modularSmallTemplate =
CLKComplicationTemplateModularSmallRingText()
modularSmallTemplate.textProvider = CLKSimpleTextProvider(text: text)
modularSmallTemplate.fillFraction = Float(progress)
modularSmallTemplate.ringStyle = CLKComplicationRingStyle.closed
modularSmallTemplate.tintColor = .blue
return modularSmallTemplate
}
private func circularSmallTemplate(_ text: String, _ progress: Double) -> CLKComplicationTemplate? {
let circularSmallTemplate =
CLKComplicationTemplateCircularSmallRingText()
circularSmallTemplate.textProvider = CLKSimpleTextProvider(text: text)
circularSmallTemplate.fillFraction = Float(progress)
circularSmallTemplate.ringStyle = CLKComplicationRingStyle.closed
circularSmallTemplate.tintColor = .blue
return circularSmallTemplate
}
private func utilitarianSmallTemplate(_ text: String, _ progress: Double) -> CLKComplicationTemplate? {
let utilitarianSmallTemplate = CLKComplicationTemplateUtilitarianSmallRingText()
utilitarianSmallTemplate.textProvider =
CLKSimpleTextProvider(text: text)
utilitarianSmallTemplate.fillFraction = Float(progress)
utilitarianSmallTemplate.ringStyle = CLKComplicationRingStyle.closed
utilitarianSmallTemplate.tintColor = .blue
return utilitarianSmallTemplate
}
}
|
mit
|
f0bba4032045594314953f840112d921
| 41.265116 | 169 | 0.671069 | 5.747628 | false | false | false | false |
tungthanhnguyen/CSSystemSoundPlayer
|
CSSystemSoundPlayer/CSSystemSoundPlayer.swift
|
1
|
23749
|
//
// Created by Jesse Squires
// http://www.hexedbits.com
//
//
// Documentation
// http://cocoadocs.org/docsets/JSQMessagesViewController
//
//
// GitHub
// https://github.com/jessesquires/JSQMessagesViewController
//
//
// License
// Copyright (c) 2014 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
//
// Converted to Swift by Tung Thanh Nguyen
// Copyright © 2016 Tung Thanh Nguyen.
// Released under an MIT license: http://opensource.org/licenses/MIT
//
// GitHub
// https://github.com/tungthanhnguyen/CSSystemSoundPlayer
//
import AudioToolbox
import Foundation
#if os(iOS)
import UIKit
#endif
public let kCSSystemSoundPlayerUserDefaultsKey: String = "kCSSystemSoundPlayerUserDefaultsKey"
/**
* String constant for .caf audio file extension.
*/
public let kCSSystemSoundTypeCAF: String! = "caf"
/**
* String constant for .aif audio file extension.
*/
public let kCSSystemSoundTypeAIF: String! = "aif"
/**
* String constant for .aiff audio file extension.
*/
public let kCSSystemSoundTypeAIFF: String! = "aiff"
/**
* String constant for .wav audio file extension.
*/
public let kCSSystemSoundTypeWAV: String! = "wav"
/**
* A completion block to be called after a system sound has finished playing.
*/
public typealias CSSystemSoundPlayerCompletionBlock = () -> Void
////////////////////////////////////////////////////////////////////////////////
// Wrapper for sticking non-objects in NSDictionary instances
private class ObjectWrapper<T>
{
public let value: T
init(_ value: T)
{
self.value = value
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
private func systemServicesSoundCompletion(soundID: SystemSoundID, data: UnsafeMutableRawPointer?)
{
let player = CSSystemSoundPlayer.sharedPlayer
let block: CSSystemSoundPlayerCompletionBlock? = player.completionBlockForSoundID(soundID)
block!()
player.removeCompletionBlockForSoundID(soundID)
}
////////////////////////////////////////////////////////////////////////////////
/**
* The `CSSystemSoundPlayer` class enables you to play sound effects, alert sounds, or other short sounds.
* It lazily loads and caches all `SystemSoundID` objects and purges them upon receiving the `UIApplicationDidReceiveMemoryWarningNotification` notification.
*/
open class CSSystemSoundPlayer: NSObject
{
private var sounds: NSMutableDictionary!
private var completionBlocks: NSMutableDictionary!
/**
* Returns whether or not the sound player is on.
* That is, whether the sound player is enabled or disabled.
* If disabled, it will not play sounds.
*
* @see `toggleSoundPlayerOn:`
*/
public var isOn: Bool = false
/**
* The bundle in which the sound player uses to search for sound file resources. You may change this property as needed.
* The default value is the main bundle. This value must not be `nil`.
*/
private var priBundle: Bundle? = nil
public var bundle: Bundle?
{
get { return self.priBundle }
set
{
if newValue != nil { self.priBundle = newValue }
}
}
//////////////////////////////////////////////////////////////////////////////
// MARK: - Init
/**
* Returns the shared `CSSystemSoundPlayer` object. This property always returns the same sound system player object.
*
* @return An initialized `CSSystemSoundPlayer` object if successful, `nil` otherwise.
*
* @warning Completion blocks are only called for sounds played with the shared player.
*/
public static let sharedPlayer = CSSystemSoundPlayer()
override public init()
{
super.init()
initWithBundle(Bundle.main)
}
/**
* Returns a new `CSSystemSoundPlayer` instance with the specified bundle.
*
* @param bundle The bundle in which the sound player uses to search for sound file resources.
*
* @return An initialized `CSSystemSoundPlayer` object.
*
* @warning Completion blocks are only called for sounds played with the shared player.
*/
internal func initWithBundle(_ bundle: Bundle)
{
self.bundle = bundle
self.isOn = readSoundPlayerOnFromUserDefaults()
self.sounds = NSMutableDictionary.init()
self.completionBlocks = NSMutableDictionary.init()
#if os(iOS)
NotificationCenter.default.addObserver(self, selector: #selector(self.didReceiveMemoryWarningNotification(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
#endif
}
deinit
{
unloadSoundIDs()
self.sounds.removeAllObjects()
self.sounds = nil
self.completionBlocks.removeAllObjects()
self.completionBlocks = nil
NotificationCenter.default.removeObserver(self)
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// MARK: - Playing sounds
private func playSoundWith(pathToFile filePath: String, isAlert: Bool, completionBlock completion: @escaping CSSystemSoundPlayerCompletionBlock)
{
if (!self.isOn || filePath.isEmpty) { return }
if sounds.object(forKey: filePath) == nil
{
addSoundIDForAudioFileWith(path: filePath)
}
playSoundWith(file: filePath, isAlert: isAlert, completionBlock: completion)
}
private func playSoundWith(fileName filename: String, extension ext: String, isAlert: Bool, completionBlock completion: @escaping CSSystemSoundPlayerCompletionBlock)
{
if !self.isOn { return }
if filename.isEmpty || ext.isEmpty
{
return
}
if sounds.object(forKey: filename) == nil
{
addSoundIDForAudioFileWith(filename, extension: ext)
}
playSoundWith(file: filename, isAlert: isAlert, completionBlock: completion)
}
private func playSoundWith(file fileKey: String, isAlert: Bool, completionBlock completion: @escaping CSSystemSoundPlayerCompletionBlock)
{
let soundID: SystemSoundID = soundIDFor(file: fileKey)
if soundID != 0
{
if completionBlocks != nil
{
let error: OSStatus = AudioServicesAddSystemSoundCompletion(soundID, nil, nil, systemServicesSoundCompletion, nil)
if error != 0
{
logError(error, withMessage: "Warning! Completion block could not be added to SystemSoundID.")
}
else
{
addCompletionBlock(completion, toSoundID: soundID)
}
}
if isAlert
{
AudioServicesPlayAlertSound(soundID)
}
else
{
AudioServicesPlaySystemSound(soundID)
}
}
}
private func readSoundPlayerOnFromUserDefaults() -> Bool
{
let setting = UserDefaults.standard.object(forKey: kCSSystemSoundPlayerUserDefaultsKey)
if setting == nil
{
toggleSoundPlayerOn(true)
return true
}
return (setting as! NSNumber).boolValue
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// MARK: - Public API
/**
* Toggles the sound player on or off by setting the `SystemSoundPlayerUserDefaultsKey` key in `NSUserDefaults` to the given value.
* This will enable or disable the playing of sounds via `SystemSoundPlayer` globally.
* This setting is persisted across application launches.
*
* @param on A boolean indicating whether or not to enable or disable the sound player settings. Pass `true` to turn sounds on, and `false` to turn sounds off.
*
* @warning Disabling the sound player (passing a value of `false`) will invoke the `stopAllSounds` method.
*/
public func toggleSoundPlayerOn(_ isOn: Bool)
{
self.isOn = isOn
let userDefaults = UserDefaults.standard
userDefaults.set(self.isOn, forKey: kCSSystemSoundPlayerUserDefaultsKey)
userDefaults.synchronize()
if !self.isOn { stopAllSounds() }
}
/**
* Plays a system sound object corresponding to an audio file with the given filename and extension.
* The system sound player will lazily initialize and load the file before playing it, and then cache its corresponding `SystemSoundID`.
* If this file has previously been played, it will be loaded from cache and played immediately.
*
* @param filePath A string containing full path of the audio file to play.
*
* @warning If the system sound object cannot be created, this method does nothing.
*/
public func playSoundWith(pathToFile filePath: String)
{
playSoundWith(pathToFile: filePath, completionBlock: {})
}
/**
* Plays a system sound object corresponding to an audio file with the given filename and extension, and excutes completionBlock when the sound has stopped playing.
* The system sound player will lazily initialize and load the file before playing it, and then cache its corresponding `SystemSoundID`.
* If this file has previously been played, it will be loaded from cache and played immediately.
*
* @param filePath A string containing full path of the audio file to play.
*
* @param completionBlock A block called after the sound has stopped playing.
* This block is retained by `CSSystemSoundPlayer`, temporarily cached, and released after its execution.
*
* @warning If the system sound object cannot be created, this method does nothing.
*/
public func playSoundWith(pathToFile filePath: String, completionBlock completion: @escaping CSSystemSoundPlayerCompletionBlock)
{
playSoundWith(pathToFile: filePath, isAlert: false, completionBlock: completion)
}
/**
* Plays a system sound object *as an alert* corresponding to an audio file with the given filename and extension.
* The system sound player will lazily initialize and load the file before playing it, and then cache its corresponding `SystemSoundID`.
* If this file has previously been played, it will be loaded from cache and played immediately.
*
* @param filePath A string containing full path of the audio file to play.
*
* @warning If the system sound object cannot be created, this method does nothing.
*
* @warning This method performs the same functions as `playSoundWith: pathToFile:`, with the excepion that, depending on the particular iOS device, this method may invoke vibration.
*/
public func playAlertSoundWith(pathToFile filePath: String)
{
playAlertSoundWith(pathToFile: filePath, completionBlock: {})
}
/**
* Plays a system sound object *as an alert* corresponding to an audio file with the given filename and extension, and and excutes completionBlock when the sound has stopped playing.
* The system sound player will lazily initialize and load the file before playing it, and then cache its corresponding `SystemSoundID`.
* If this file has previously been played, it will be loaded from cache and played immediately.
*
* @param filePath A string containing the base name of the audio file to play.
*
* @param completionBlock A block called after the sound has stopped playing.
* This block is retained by `CSSystemSoundPlayer`, temporarily cached, and released after its execution.
*
* @warning If the system sound object cannot be created, this method does nothing.
*
* @warning This method performs the same functions as `playSoundWith: filePath: completion:`, with the excepion that, depending on the particular iOS device, this method may invoke vibration.
*/
public func playAlertSoundWith(pathToFile filePath: String, completionBlock completion: @escaping CSSystemSoundPlayerCompletionBlock)
{
playSoundWith(pathToFile: filePath, isAlert: true, completionBlock: completion)
}
/**
* Plays a system sound object corresponding to an audio file with the given filename and extension.
* The system sound player will lazily initialize and load the file before playing it, and then cache its corresponding `SystemSoundID`.
* If this file has previously been played, it will be loaded from cache and played immediately.
*
* @param fileName A string containing the base name of the audio file to play.
*
* @param extension A string containing the extension of the audio file to play.
* This parameter must be one of `kCSSystemSoundTypeCAF`, `kCSSystemSoundTypeAIF`, `kCSSystemSoundTypeAIFF`, or `kCSSystemSoundTypeWAV`.
*
* @warning If the system sound object cannot be created, this method does nothing.
*/
public func playSoundWith(fileName filename: String, extension ext: String)
{
playSoundWith(fileName: filename, extension: ext, completionBlock: {})
}
/**
* Plays a system sound object corresponding to an audio file with the given filename and extension, and excutes completionBlock when the sound has stopped playing.
* The system sound player will lazily initialize and load the file before playing it, and then cache its corresponding `SystemSoundID`.
* If this file has previously been played, it will be loaded from cache and played immediately.
*
* @param filename A string containing the base name of the audio file to play.
*
* @param extension A string containing the extension of the audio file to play.
* This parameter must be one of `kCSSystemSoundTypeCAF`, `kCSSystemSoundTypeAIF`, `kCSSystemSoundTypeAIFF`, or `kCSSystemSoundTypeWAV`.
*
* @param completionBlock A block called after the sound has stopped playing.
* This block is retained by `CSSystemSoundPlayer`, temporarily cached, and released after its execution.
*
* @warning If the system sound object cannot be created, this method does nothing.
*/
public func playSoundWith(fileName filename: String, extension ext: String, completionBlock completion: @escaping CSSystemSoundPlayerCompletionBlock)
{
playSoundWith(fileName: filename, extension: ext, isAlert: false, completionBlock: completion)
}
/**
* Plays a system sound object *as an alert* corresponding to an audio file with the given filename and extension.
* The system sound player will lazily initialize and load the file before playing it, and then cache its corresponding `SystemSoundID`.
* If this file has previously been played, it will be loaded from cache and played immediately.
*
* @param filename A string containing the base name of the audio file to play.
* @param extension A string containing the extension of the audio file to play.
* This parameter must be one of `kCSSystemSoundTypeCAF`, `kCSSystemSoundTypeAIF`, `kCSSystemSoundTypeAIFF`, or `kCSSystemSoundTypeWAV`.
*
* @warning If the system sound object cannot be created, this method does nothing.
*
* @warning This method performs the same functions as `playSoundWith: fileName: extension:`, with the excepion that, depending on the particular iOS device, this method may invoke vibration.
*/
public func playAlertSoundWith(fileName filename: String, extension ext: String)
{
playAlertSoundWith(fileName: filename, extension: ext, completionBlock: {})
}
/**
* Plays a system sound object *as an alert* corresponding to an audio file with the given filename and extension, and and excutes completionBlock when the sound has stopped playing.
* The system sound player will lazily initialize and load the file before playing it, and then cache its corresponding `SystemSoundID`.
* If this file has previously been played, it will be loaded from cache and played immediately.
*
* @param filename A string containing the base name of the audio file to play.
*
* @param extension A string containing the extension of the audio file to play.
* This parameter must be one of `kCSSystemSoundTypeCAF`, `kCSSystemSoundTypeAIF`, `kCSSystemSoundTypeAIFF`, or `kCSSystemSoundTypeWAV`.
*
* @param completionBlock A block called after the sound has stopped playing.
* This block is retained by `CSSystemSoundPlayer`, temporarily cached, and released after its execution.
*
* @warning If the system sound object cannot be created, this method does nothing.
*
* @warning This method performs the same functions as `playSoundWith: fileName: extension: completion:`, with the excepion that, depending on the particular iOS device, this method may invoke vibration.
*/
public func playAlertSoundWith(fileName filename: String, extension ext: String, completionBlock completion: @escaping CSSystemSoundPlayerCompletionBlock)
{
playSoundWith(fileName: filename, extension: ext, isAlert: true, completionBlock: completion)
}
/**
* On some iOS devices, you can call this method to invoke vibration.
* On other iOS devices this functionaly is not available, and calling this method does nothing.
*/
#if os(iOS)
public func playVibrateSound()
{
if self.isOn { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) }
}
#endif
/**
* Stops playing all sounds immediately.
*
* @warning Any completion blocks attached to any currently playing sound will *not* be executed.
* Also, calling this method will purge all `SystemSoundID` objects from cache, regardless of whether or not they were currently playing.
*/
public func stopAllSounds()
{
unloadSoundIDs()
}
/**
* Stops playing the sound with the given filename immediately.
*
* @param filename The filename of the sound to stop playing.
*
* @warning If a completion block is attached to the given sound, it will *not* be executed.
* Also, calling this method will purge the `SystemSoundID` object for this file from cache, regardless of whether or not it was currently playing.
*/
public func stopSoundWith(fileName: String)
{
let soundID: SystemSoundID = soundIDFor(file: fileName)
let data: NSData = dataWithSoundID(soundID)
unloadSoundIDFor(fileName: fileName)
sounds.removeObject(forKey: fileName)
completionBlocks.removeObject(forKey: data)
}
/**
* Preloads a system sound object corresponding to an audio file with the given filename and extension.
* The system sound player will initialize, load, and cache the corresponding `SystemSoundID`.
*
* @param filename A string containing the base name of the audio file to play.
* @param extension A string containing the extension of the audio file to play.
* This parameter must be one of `kCSSystemSoundTypeCAF`, `kCSSystemSoundTypeAIF`, `kCSSystemSoundTypeAIFF`, or `kCSSystemSoundTypeWAV`.
*/
public func preloadSoundWith(filename: String, extension ext: String)
{
if sounds.object(forKey: filename) != nil
{
addSoundIDForAudioFileWith(filename, extension: ext)
}
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// MARK: - Sound data
private func dataWithSoundID(_ soundID: SystemSoundID) -> NSData
{
var _soundID = soundID
return NSData(bytes: &_soundID, length: MemoryLayout<SystemSoundID>.size)
}
private func soundIDFromData(_ data: NSData) -> SystemSoundID
{
if data.length > 0
{
var soundID: SystemSoundID = 0
data.getBytes(&soundID, length: MemoryLayout<SystemSoundID>.size)
return soundID
}
return 0
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// MARK: - Sound files
private func soundIDFor(file fileKey: String) -> SystemSoundID
{
let soundData: NSData = self.sounds.object(forKey: fileKey) as! NSData
return soundIDFromData(soundData)
}
private func addSoundIDForAudioFileWith(path filePath: String)
{
let soundID: SystemSoundID = createSoundIDWith(pathToFile: filePath)
if soundID != 0
{
let data: NSData = dataWithSoundID(soundID)
sounds.setObject(data, forKey: filePath as NSCopying)
}
}
private func addSoundIDForAudioFileWith(_ filename: String, extension ext: String)
{
let soundID: SystemSoundID = createSoundIDWith(fileName: filename, extension: ext)
if soundID != 0
{
let data: NSData = dataWithSoundID(soundID)
sounds.setObject(data, forKey: filename as NSCopying)
}
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// MARK: - Sound completion blocks
internal func completionBlockForSoundID(_ soundID: SystemSoundID) -> CSSystemSoundPlayerCompletionBlock
{
let data: NSData = dataWithSoundID(soundID)
let objectWrapper: ObjectWrapper<CSSystemSoundPlayerCompletionBlock> = completionBlocks.object(forKey: data) as! ObjectWrapper<CSSystemSoundPlayerCompletionBlock>
return objectWrapper.value
}
private func addCompletionBlock(_ block: @escaping CSSystemSoundPlayerCompletionBlock, toSoundID soundID: SystemSoundID)
{
let data: NSData = dataWithSoundID(soundID)
completionBlocks.setObject(ObjectWrapper(block), forKey: data)
}
internal func removeCompletionBlockForSoundID(_ soundID: SystemSoundID)
{
let key: NSData = dataWithSoundID(soundID)
completionBlocks.removeObject(forKey: key)
AudioServicesRemoveSystemSoundCompletion(soundID)
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// MARK: - Managing sounds
private func createSoundIDWith(pathToFile path: String) -> SystemSoundID
{
return createSoundIDWith(fileURL: URL(string: path)!)
}
private func createSoundIDWith(fileName filename: String, extension ext: String) -> SystemSoundID
{
let fileURL: URL = self.bundle!.url(forResource: filename, withExtension: ext)!
return createSoundIDWith(fileURL: fileURL)
}
private func createSoundIDWith(fileURL: URL) -> SystemSoundID
{
if FileManager.default.fileExists(atPath: fileURL.path)
{
var soundID: SystemSoundID = 0;
let error: OSStatus = AudioServicesCreateSystemSoundID(fileURL as CFURL, &soundID)
if error != 0
{
self.logError(error, withMessage: "Warning! SystemSoundID could not be created.")
return 0;
}
else { return soundID }
}
NSLog("\(self) Error: audio file not found at URL: \(fileURL)")
return 0
}
private func unloadSoundIDs()
{
for eachFilename in self.sounds.allKeys
{
unloadSoundIDFor(fileName: eachFilename as! String)
}
sounds.removeAllObjects()
completionBlocks.removeAllObjects()
}
private func unloadSoundIDFor(fileName filename: String)
{
let soundID: SystemSoundID = soundIDFor(file: filename)
if soundID != 0
{
AudioServicesRemoveSystemSoundCompletion(soundID)
let error: OSStatus = AudioServicesDisposeSystemSoundID(soundID)
if error != 0
{
logError(error, withMessage: "Warning! SystemSoundID could not be disposed.")
}
}
}
private func logError(_ error: OSStatus, withMessage message: String)
{
var errorMessage: String = ""
switch error
{
case kAudioServicesUnsupportedPropertyError:
errorMessage = "The property is not supported."
case kAudioServicesBadPropertySizeError:
errorMessage = "The size of the property data was not correct."
case kAudioServicesBadSpecifierSizeError:
errorMessage = "The size of the specifier data was not correct."
case kAudioServicesSystemSoundUnspecifiedError:
errorMessage = "An unspecified error has occurred."
case kAudioServicesSystemSoundClientTimedOutError:
errorMessage = "System sound client message timed out."
default:
break
}
NSLog("\(self) \(message) Error: (code \(error.bigEndian)) \(errorMessage)")
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// MARK: - Notifications
@objc internal func didReceiveMemoryWarningNotification(_ notification: NSNotification)
{
unloadSoundIDs()
}
//////////////////////////////////////////////////////////////////////////////
}
|
mit
|
2e330974315922ed556d681e62c4adf0
| 36.10625 | 205 | 0.696395 | 4.352639 | false | false | false | false |
pNre/Kingfisher
|
Sources/WKInterfaceImage+Kingfisher.swift
|
4
|
4621
|
//
// WKInterfaceImage+Kingfisher.swift
// Kingfisher
//
// Created by Rodrigo Borges Soares on 04/05/18.
//
// Copyright (c) 2018 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import WatchKit
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: WKInterfaceImage {
/**
Set an image with a resource.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
@discardableResult
public func setImage(_ resource: Resource?,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask {
guard let resource = resource else {
setWebURL(nil)
completionHandler?(nil, nil, .none, nil)
return .empty
}
setWebURL(resource.downloadURL)
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo),
progressBlock: { receivedSize, totalSize in
guard resource.downloadURL == self.webURL else {
return
}
progressBlock?(receivedSize, totalSize)
},
completionHandler: { [weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL else {
completionHandler?(image, error, cacheType, imageURL)
return
}
self.setImageTask(nil)
guard let image = image else {
completionHandler?(nil, error, cacheType, imageURL)
return
}
strongBase.setImage(image)
completionHandler?(image, error, cacheType, imageURL)
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelDownloadTask() {
imageTask?.cancel()
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: WKInterfaceImage {
/// Get the image URL binded to this image view.
public var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL?) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
|
mit
|
874632dfc3b278a818649fdeaafd79da
| 37.190083 | 116 | 0.642718 | 5.251136 | false | false | false | false |
remzr7/Surge
|
Sources/Trigonometric.swift
|
3
|
4875
|
// Trigonometric.swift
//
// Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me)
//
// 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 Accelerate
// MARK: Sine-Cosine
public func sincos(_ x: [Float]) -> (sin: [Float], cos: [Float]) {
var sin = [Float](repeating: 0.0, count: x.count)
var cos = [Float](repeating: 0.0, count: x.count)
vvsincosf(&sin, &cos, x, [Int32(x.count)])
return (sin, cos)
}
public func sincos(_ x: [Double]) -> (sin: [Double], cos: [Double]) {
var sin = [Double](repeating: 0.0, count: x.count)
var cos = [Double](repeating: 0.0, count: x.count)
vvsincos(&sin, &cos, x, [Int32(x.count)])
return (sin, cos)
}
// MARK: Sine
public func sin(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvsinf(&results, x, [Int32(x.count)])
return results
}
public func sin(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvsin(&results, x, [Int32(x.count)])
return results
}
// MARK: Cosine
public func cos(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvcosf(&results, x, [Int32(x.count)])
return results
}
public func cos(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvcos(&results, x, [Int32(x.count)])
return results
}
// MARK: Tangent
public func tan(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvtanf(&results, x, [Int32(x.count)])
return results
}
public func tan(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvtan(&results, x, [Int32(x.count)])
return results
}
// MARK: Arcsine
public func asin(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvasinf(&results, x, [Int32(x.count)])
return results
}
public func asin(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvasin(&results, x, [Int32(x.count)])
return results
}
// MARK: Arccosine
public func acos(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvacosf(&results, x, [Int32(x.count)])
return results
}
public func acos(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvacos(&results, x, [Int32(x.count)])
return results
}
// MARK: Arctangent
public func atan(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvatanf(&results, x, [Int32(x.count)])
return results
}
public func atan(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
vvatan(&results, x, [Int32(x.count)])
return results
}
// MARK: -
// MARK: Radians to Degrees
func rad2deg(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
let divisor = [Float](repeating: Float(M_PI / 180.0), count: x.count)
vvdivf(&results, x, divisor, [Int32(x.count)])
return results
}
func rad2deg(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
let divisor = [Double](repeating: M_PI / 180.0, count: x.count)
vvdiv(&results, x, divisor, [Int32(x.count)])
return results
}
// MARK: Degrees to Radians
func deg2rad(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
let divisor = [Float](repeating: Float(180.0 / M_PI), count: x.count)
vvdivf(&results, x, divisor, [Int32(x.count)])
return results
}
func deg2rad(_ x: [Double]) -> [Double] {
var results = [Double](repeating: 0.0, count: x.count)
let divisor = [Double](repeating: 180.0 / M_PI, count: x.count)
vvdiv(&results, x, divisor, [Int32(x.count)])
return results
}
|
mit
|
857ad7f431b23df21e9ebe29e5ac6fe5
| 26.845714 | 80 | 0.64211 | 3.178735 | false | false | false | false |
wendru/rotten-tomatoes
|
rotten-tomatoes/MoviesViewController.swift
|
1
|
6442
|
//
// MoviesViewController.swift
// rotten-tomatoes
//
// Created by Andrew Wen on 2/4/15.
// Copyright (c) 2015 wendru. All rights reserved.
//
import UIKit
class MoviesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarDelegate, UISearchBarDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var warningView: UIView!
@IBOutlet weak var tabs: UITabBar!
@IBOutlet weak var searchBar: UISearchBar!
var movies = [NSDictionary]()
var filteredMovies = [NSDictionary]()
var destinationController = MovieDetailViewController()
var HUD = JGProgressHUD(style: JGProgressHUDStyle.Dark)
var refreshControl: UIRefreshControl!
var isFiltered = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tabs.selectedItem = tabs.items?.first as? UITabBarItem
tabs.delegate = self
searchBar.delegate = self
createRefreshControl()
loadData()
}
func createRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "onRefresh", forControlEvents: UIControlEvents.ValueChanged)
tableView.insertSubview(refreshControl, atIndex: 0)
}
func loadData() {
HUD.showInView(self.view)
let target = tabs.selectedItem?.title!
let apiKey = "sqcdumcwj9h8wp9a8r8v6smp"
var url: NSURL!
if(target == "Box Office") {
url = NSURL(string: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=" + apiKey)
} else {
url = NSURL(string: "http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?apikey=" + apiKey)
}
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response, data, error) in
if(error != nil) {
self.warningView.hidden = false
} else {
self.warningView.hidden = true
var errorValue: NSError? = nil
let dictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &errorValue) as NSDictionary
self.movies = dictionary["movies"] as [NSDictionary]
self.tableView.reloadData()
}
})
HUD.dismissAfterDelay(0.5, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(isFiltered) {
return filteredMovies.count
} else {
return movies.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("MovieCell") as MovieCell
var movie: NSDictionary
if(isFiltered) {
movie = filteredMovies[indexPath.row] as NSDictionary
} else {
movie = movies[indexPath.row] as NSDictionary
}
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
// NAVBAR HEADER
navigationItem.title = tabs.selectedItem?.title
// TITLE
cell.titleLabel.text = movie["title"] as NSString
// RUNTIME
var runtime = movie["runtime"] as Int
cell.runTime.text = NSString(format: "%d Hours %d Minutes", runtime / 60, runtime % 60)
// MPAA RATING
cell.mpaaRating.text = movie["mpaa_rating"] as NSString
// CRITICS RATING
cell.criticsRating.text = NSString(format: "%d%%", movie["ratings"]?["critics_score"] as Int)
// AUDIENCE RATING
cell.audienceRating.text = NSString(format: "%d%%", movie["ratings"]?["audience_score"] as Int)
// POSTER IMAGE
var posterURL = NSURL(
string: (movie["posters"]?["thumbnail"]? as NSString).stringByReplacingOccurrencesOfString("tmb", withString: "pro")
)
cell.poster.setImageWithURL(posterURL)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if(isFiltered) {
destinationController.movie = filteredMovies[indexPath.row]
} else {
destinationController.movie = movies[indexPath.row]
}
}
func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) {
loadData()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if (searchText == "") {
isFiltered = false
} else {
isFiltered = true
filteredMovies = [NSDictionary]()
for(var i = 0; i < movies.count; i++) {
let title = movies[i]["title"] as String
if(title.lowercaseString.rangeOfString(searchText.lowercaseString) != nil) {
filteredMovies.append(movies[i])
}
}
tableView.reloadData()
}
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
tableView.reloadData()
self.view.endEditing(true)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
isFiltered = false
searchBar.text = ""
tableView.reloadData()
self.view.endEditing(true)
}
func onRefresh() {
loadData()
refreshControl.endRefreshing()
}
// 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?) {
self.destinationController = segue.destinationViewController as MovieDetailViewController
super.prepareForSegue(segue, sender: sender)
}
}
|
gpl-2.0
|
bd7c40d4bd3a5ddeb9c9f0ba4799fbc1
| 33.449198 | 159 | 0.615647 | 5.165998 | false | false | false | false |
studomonly/Pin
|
Pod/Classes/Pin.swift
|
1
|
4683
|
//
// Pin.swift
// studomonly
//
// Pin is an interface into AutoLayout that is simpler than using NSLayoutConstraints, and
// more readable. It uses the Builder Model to construct a Pin object. Calling the constrain()
// method constructs the NSLayoutConstraint and adds the constraints to the parent view.
//
// https://github.com/hellostu/Pin
import UIKit
open class Pin {
fileprivate let rootView:UIView
fileprivate var toView:UIView?
fileprivate var superView:UIView?
fileprivate var rootViewAttribute:NSLayoutAttribute?
fileprivate var toViewAttribute:NSLayoutAttribute?
fileprivate var constant:CGFloat = 0.0
fileprivate var multiplier:CGFloat = 1.0
fileprivate var priority:UILayoutPriority = 1000
fileprivate var relation:NSLayoutRelation = .equal
fileprivate var constraint:NSLayoutConstraint?
//////////////////////////////////////////////////////////////////////////
//MARK: -
//MARK: Lifecycle
//////////////////////////////////////////////////////////////////////////
public init(view:UIView) {
self.rootView = view
}
//////////////////////////////////////////////////////////////////////////
//MARK: -
//MARK: Public Methods
//////////////////////////////////////////////////////////////////////////
open func to(_ view:UIView) -> Pin {
self.toView = view
self.relation = .equal
return self
}
open func height() -> Pin {
setAttribute(.height)
return self
}
open func height(_ height:CGFloat) -> Pin {
setAttribute(.height)
self.constant = height
self.multiplier = 0.0
return self
}
open func width() -> Pin {
setAttribute(.width)
return self
}
open func width(_ width:CGFloat) -> Pin {
setAttribute(.width)
self.constant = width
self.multiplier = 0.0
return self
}
open func left() -> Pin {
setAttribute(.left)
return self
}
open func right() -> Pin {
setAttribute(.right)
return self
}
open func top() -> Pin {
setAttribute(.top)
return self
}
open func bottom() -> Pin {
setAttribute(.bottom)
return self
}
open func baseline() -> Pin {
setAttribute(.lastBaseline)
return self
}
open func centerX() -> Pin {
setAttribute(.centerX)
return self
}
open func centerY() -> Pin {
setAttribute(.centerY)
return self
}
internal func add(_ add:CGFloat) -> Pin {
self.constant = add
return self
}
internal func multiplyBy(_ multiplier:CGFloat) -> Pin {
self.multiplier = multiplier
return self
}
open func priority(_ priority:UILayoutPriority) -> Pin {
self.priority = priority
return self
}
open func relation(_ relation:NSLayoutRelation) -> Pin {
self.relation = relation
return self
}
@discardableResult open func constrain() -> Pin {
if self.superView == nil {
self.superView = rootView.superview
}
return self.constrainOn(self.superView!)
}
@discardableResult open func constrainOn(_ parent:UIView) -> Pin {
if self.toView == nil {
self.toView = self.superView
}
if self.rootViewAttribute == nil {
self.rootViewAttribute = self.toViewAttribute
} else if self.toViewAttribute == nil {
self.toViewAttribute = self.rootViewAttribute
}
self.rootView.translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: self.rootView, attribute: rootViewAttribute!, relatedBy: relation, toItem: toView, attribute: toViewAttribute!, multiplier: multiplier, constant: constant)
constraint.priority = self.priority
parent.addConstraint(constraint)
self.constraint = constraint
return self
}
open func get() -> NSLayoutConstraint? {
return constraint
}
//////////////////////////////////////////////////////////////////////////
//MARK: -
//MARK: Private Methods
//////////////////////////////////////////////////////////////////////////
fileprivate func setAttribute(_ attribute:NSLayoutAttribute) {
if let _ = self.rootViewAttribute {
self.toViewAttribute = attribute
} else {
self.rootViewAttribute = attribute
}
}
}
|
mit
|
9ade320badcb4be0439632a820741024
| 26.547059 | 205 | 0.536622 | 5.568371 | false | false | false | false |
stomp1128/TIY-Assignments
|
22-Dude-Where's-My-Car?/LocationPopoverViewController.swift
|
1
|
3854
|
//
// LocationPopoverViewController.swift
// 22-Dude-Where's-My-Car?
//
// Created by Chris Stomp on 11/3/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreLocation
class LocationPopoverViewController: UIViewController, CLLocationManagerDelegate
{
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var addCurrentLocationButton: UIButton!
var locations = [Location]()
let locationManager = CLLocationManager() //step 3 create objects
let geocoder = CLGeocoder()
var delegate: LocationPopoverViewControllerDelegate?
override func viewDidLoad()
{
super.viewDidLoad()
locationTextField.becomeFirstResponder()
addCurrentLocationButton.enabled = false
configureLocationManager()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(locationTextField: UITextField) -> Bool
{
var rc = false
if locationTextField.text != ""
{
resignFirstResponder()
configureLocationManager()
locationManager.startUpdatingLocation()
rc = true
}
return rc
}
//MARK: - CLLocation related Methods //step 4
func configureLocationManager()
{
if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Restricted //determines if user said its ok to use location
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters //updates when user moves
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined //if not determined we have not asked the user yet, its the first time the app has been run
{
locationManager.requestWhenInUseAuthorization() //ios will take over and ask your user for permission
//requestAlwaysAuthorization will allow it to get users location in background
}
else
{
addCurrentLocationButton.enabled = true
}
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
if status == CLAuthorizationStatus.AuthorizedWhenInUse
{
addCurrentLocationButton.enabled = true
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print(error.localizedDescription)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
geocoder.reverseGeocodeLocation(location!, completionHandler: {(placemark: [CLPlacemark]?, error: NSError?) -> Void in
if error != nil
{
print(error?.localizedDescription)
}
else
{
self.locationManager.stopUpdatingLocation()
let latitude = location?.coordinate.latitude
let longitude = location?.coordinate.longitude
//let aLocation = Location(locationName: locationName, latitude: latitude!, longitude: longitude!)
// self.delegate?.locationWasChosen(aLocation)
}
})
}
@IBAction func addLocationTapped(sender: AnyObject)
{
locationManager.startUpdatingLocation()
resignFirstResponder()
}
}
|
cc0-1.0
|
c68d948ff5fabe4e1178482de27bc9f8
| 30.581967 | 210 | 0.634051 | 6.347611 | false | false | false | false |
WangCrystal/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Main/MainTabViewController.swift
|
1
|
8767
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
import MessageUI
class MainTabViewController : UITabBarController {
// MARK: -
// MARK: Private vars
private var appEmptyContainer = UIView()
private var appIsSyncingPlaceholder = BigPlaceholderView(topOffset: 44 + 20)
private var appIsEmptyPlaceholder = BigPlaceholderView(topOffset: 44 + 20)
// MARK: -
// MARK: Public vars
var centerButton:UIButton? = nil
var isInited = false
var isAfterLogin = false
// MARK: -
// MARK: Constructors
init(isAfterLogin: Bool) {
super.init(nibName: nil, bundle: nil);
self.isAfterLogin = isAfterLogin
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
required init(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
appEmptyContainer.hidden = true
appIsEmptyPlaceholder.hidden = true
appIsEmptyPlaceholder.setImage(
UIImage(named: "contacts_list_placeholder"),
title: NSLocalizedString("Placeholder_Empty_Title", comment: "Placeholder Title"),
subtitle: NSLocalizedString("Placeholder_Empty_Message", comment: "Placeholder Message"),
actionTitle: NSLocalizedString("Placeholder_Empty_Action", comment: "Placeholder Action"),
subtitle2: NSLocalizedString("Placeholder_Empty_Message2", comment: "Placeholder Message2"),
actionTarget: self, actionSelector: Selector("showSmsInvitation"),
action2title: NSLocalizedString("Placeholder_Empty_Action2", comment: "Placeholder Action2"),
action2Selector: Selector("doAddContact"))
appEmptyContainer.addSubview(appIsEmptyPlaceholder)
appIsSyncingPlaceholder.hidden = true
appIsSyncingPlaceholder.setImage(
UIImage(named: "chat_list_placeholder"),
title: NSLocalizedString("Placeholder_Loading_Title", comment: "Placeholder Title"),
subtitle: NSLocalizedString("Placeholder_Loading_Message", comment: "Placeholder Message"))
appEmptyContainer.addSubview(appIsSyncingPlaceholder)
view.addSubview(appEmptyContainer)
view.backgroundColor = UIColor.whiteColor()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (!isInited) {
if (Actor.isLoggedIn()) {
isInited = true
let contactsNavigation = AANavigationController(rootViewController: ContactsViewController())
let dialogsNavigation = AANavigationController(rootViewController: DialogsViewController())
let settingsNavigation = AANavigationController(rootViewController: SettingsViewController())
if Actor.config.enableCommunity {
let exploreNavigation = AANavigationController(rootViewController: DiscoverViewController())
viewControllers = [contactsNavigation, dialogsNavigation, exploreNavigation, settingsNavigation]
} else {
viewControllers = [contactsNavigation, dialogsNavigation, settingsNavigation]
}
selectedIndex = 0;
selectedIndex = 1;
}
}
}
// MARK: -
// MARK: Methods
func centerButtonTap() {
// var actionShit = ABActionShit()
// actionShit.buttonTitles = ["Add Contact", "Create group", "Write to..."];
// actionShit.delegate = self
// actionShit.showWithCompletion(nil)
}
// MARK: -
// MARK: ABActionShit Delegate
// func actionShit(actionShit: ABActionShit!, clickedButtonAtIndex buttonIndex: Int) {
// if (buttonIndex == 1) {
// navigationController?.pushViewController(GroupMembersController(), animated: true)
// }
// }
// MARK: -
// MARK: Placeholder
func showAppIsSyncingPlaceholder() {
appIsEmptyPlaceholder.hidden = true
appIsSyncingPlaceholder.hidden = false
appEmptyContainer.hidden = false
}
func showAppIsEmptyPlaceholder() {
appIsEmptyPlaceholder.hidden = false
appIsSyncingPlaceholder.hidden = true
appEmptyContainer.hidden = false
}
func hidePlaceholders() {
appEmptyContainer.hidden = true
}
func showSmsInvitation(phone: String?) {
if MFMessageComposeViewController.canSendText() {
let messageComposeController = MFMessageComposeViewController()
messageComposeController.messageComposeDelegate = self
if (phone != nil) {
messageComposeController.recipients = [phone!]
}
messageComposeController.body = NSLocalizedString("InviteText", comment: "Invite Text")
messageComposeController.navigationBar.tintColor = MainAppTheme.navigation.titleColor
presentViewController(messageComposeController, animated: true, completion: { () -> Void in
MainAppTheme.navigation.applyStatusBarFast()
})
} else {
UIAlertView(title: "Error", message: "Cannot send SMS", delegate: nil, cancelButtonTitle: "OK").show()
}
}
func showSmsInvitation() {
showSmsInvitation(nil)
}
func doAddContact() {
let alertView = UIAlertView(
title: NSLocalizedString("ContactsAddHeader", comment: "Alert Title"),
message: NSLocalizedString("ContactsAddHint", comment: "Alert Hint"),
delegate: self,
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Alert Cancel"),
otherButtonTitles: NSLocalizedString("AlertNext", comment: "Alert Next"))
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.show()
}
// MARK: -
// MARK: Layout
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
appEmptyContainer.frame = view.bounds
appIsSyncingPlaceholder.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
appIsEmptyPlaceholder.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
}
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
extension MainTabViewController: MFMessageComposeViewControllerDelegate {
func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
extension MainTabViewController: UIAlertViewDelegate {
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
// TODO: Localize
if buttonIndex == 1 {
let textField = alertView.textFieldAtIndex(0)!
if textField.text?.length > 0 {
self.execute(Actor.findUsersCommandWithQuery(textField.text), successBlock: { (val) -> Void in
var user: ACUserVM?
user = val as? ACUserVM
if user == nil {
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.objectAtIndex(0) as? ACUserVM {
user = tempUser
}
}
}
}
if user != nil {
self.execute(Actor.addContactCommandWithUid(user!.getId()), successBlock: { (val) -> () in
// DO Nothing
}, failureBlock: { (val) -> () in
self.showSmsInvitation(textField.text)
})
} else {
self.showSmsInvitation(textField.text)
}
}, failureBlock: { (val) -> Void in
self.showSmsInvitation(textField.text)
})
}
}
}
}
|
mit
|
c27d1cab9bf21052d2bf5f54df36f38f
| 36.95671 | 133 | 0.605909 | 5.538219 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
SwiftGL-Demo/Resources/iOS/PaintViewController.swift
|
1
|
21295
|
//
// PaintViewController.swift
// SwiftGL
//
// Created by jerry on 2015/5/21.
// Copyright (c) 2015年 Jerry Chan. All rights reserved.
//
import AVKit
import GLKit
import SwiftGL
import OpenGLES
import StrokeAnalysis
import SwiftColorPicker
import GLFramework
class PaintViewController:UIViewController, UIGestureRecognizerDelegate,StrokeProgressChangeDelegate
{
static var instance:PaintViewController!
static var appMode:ApplicationMode = ApplicationMode.artWorkCreation
static var courseTitle:String = "none"
var inited:Bool = false
//UI size attributes
var viewWidth:CGFloat!
@IBOutlet weak var colorPicker: ColorPicker!
override var prefersStatusBarHidden : Bool {
return true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: animated)
super.viewWillDisappear(animated)
}
enum AppState{
case viewArtwork
case viewRevision
case drawArtwork
case drawRevision
case editArtwork
case editNote
case selectStroke
}
var fileName:String!
//var paintMode = PaintMode.Artwork
var paintManager:PaintManager!
var lastAppState:AppState!
var appState:AppState = .drawArtwork{
willSet{
lastAppState = appState
}
didSet
{
switch appState
{
case .drawArtwork:
modeText.title = "繪畫模式"
case .editNote:
modeText.title = "編輯註解"
case .viewArtwork:
modeText.title = "觀看模式"
case .drawRevision:
modeText.title = "批改模式"
case .selectStroke:
modeText.title = "選擇繪畫步驟"
default:
break
}
}
}
static let canvasWidth:Int = 1366
static let canvasHeight:Int = 1024
@IBOutlet var panGestureRecognizer: UIPanGestureRecognizer!
@IBOutlet var singlePanGestureRecognizer: UIPanGestureRecognizer!
@IBOutlet var doubleTapSingleTouchGestureRecognizer: UITapGestureRecognizer!
@IBOutlet var singleTapSingleTouchGestureRecognizer: UITapGestureRecognizer!
@IBAction func dragBoundGestureHandler(_ sender: UIPanGestureRecognizer) {
let dis = sender.translation(in: boundBorderView)
canvasBGLeadingConstraint.constant+=dis.x
boundBorderViewLeadingConstraint.constant += dis.x
}
var currentTouchType:String = "None"
var isDrawDone = true
var eaglContext:EAGLContext!
var eaglContext2:EAGLContext!
func pathSetUp()
{
if let path = Bundle.main.resourcePath {
Foundation.FileManager.default.changeCurrentDirectoryPath(path)
}
let path = Bundle.main.bundlePath
let fm = Foundation.FileManager.default
let dirContents: [AnyObject]?
do {
dirContents = try fm.contentsOfDirectory(atPath: path) as [AnyObject]?
} catch _ {
dirContents = nil
}
print(dirContents)
}
override func viewDidLoad() {
PaintViewController.instance = self
strokeSelecter = StrokeSelecter()
pathSetUp()
//the OpenCV
//print(OpenCVWrapper.calculateImgSimilarity(UIImage(named: "img3"), secondImg: UIImage(named: "img2")))
toolBarItems = mainToolBar.items
initAnimateState()
nearbyColorButtons = nearbyColorButtons.sorted(by: {b1,b2 in return (b1 as! UIView).tag > (b2 as! UIView).tag}) as NSArray!
colorPicker.setup(hueView, colorGradientView: colorGradientView)
colorPicker.onColorChange = {[weak self](color, finished) in
if finished {
//self.view.backgroundColor = UIColor.whiteColor() // reset background color to white
DLog("finished")
} else {
//self.view.backgroundColor = color // set background color to current selected color (finger is still down)
self!.paintView.paintBuffer.setBrushDrawSetting(self!.paintView.paintBuffer.paintToolManager.currentTool.toolType)
self!.paintView.paintBuffer.paintToolManager.usePreviousTool()
self!.paintView.paintBuffer.paintToolManager.changeColor(color)
let colors = getNearByColor(color)
for i in 0...8
{
unowned let button = self!.nearbyColorButtons[i] as! UIButton
button.backgroundColor = colors[i]
}
}
}
switch PaintViewController.appMode {
case ApplicationMode.createTutorial:
paintView = PaintView(frame: CGRect(x: 0, y: 0, width: CGFloat(PaintViewController.canvasWidth/2), height: CGFloat(PaintViewController.canvasHeight)))
default:
paintView = PaintView(frame: CGRect(x: 0, y: 0, width: CGFloat(PaintViewController.canvasWidth), height: CGFloat(PaintViewController.canvasHeight)))
}
paintView.paintBuffer.paintToolManager.useCurrentTool()
paintManager = PaintManager(paintView:paintView)
/*1*/
//paintView init
paintView.isMultipleTouchEnabled = true
canvasBGView.addSubview(paintView)
paintView.addGestureRecognizer(singlePanGestureRecognizer)
if(fileName != nil)
{
NoteManager.instance.loadNotes(fileName)
if(!paintManager.loadArtwork(self.fileName,appMode: PaintViewController.appMode))
{
print("load error:");
}
inited = true
paintManager.artwork.currentClip.strokeDelegate = self
//paintManager.artwork.currentClip.onStrokeIDChanged = onStrokeProgressChanged
paintView.glDraw()
//TODO *****
//need to remove the switch in paintManager, temporary have switch both
switch PaintViewController.appMode{
case .practiceCalligraphy:
paintManager.revisionDrawModeSetUp()
appState = .drawRevision
case .instructionTutorial:
setTutorialStepContent()
_ = removeToolBarButton(addNoteButton)
default:
break
}
setup()
/*
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) { // 1
self.isDrawDone = false
dispatch_async(dispatch_get_main_queue()) { // 2
self.paintManager.loadArtwork(self.fileName)
self.paintManager.artwork.currentClip.onStrokeIDChanged = {[weak self](id,count) in
self!.onStrokeProgressChanged(id, totalStrokeCount: count)
}
self.paintView.glDraw()
self.isDrawDone = true
self.setup()
}
}*/
}
else
{
paintManager.newArtwork(PaintViewController.canvasWidth,height: PaintViewController.canvasHeight)
inited = true
//paintManager.artwork.currentClip.onStrokeIDChanged = {[weak self](id,count) in
// self!.onStrokeProgressChanged(id, totalStrokeCount: count)
// }
//paintManager.artwork.currentClip.onStrokeIDChanged = onStrokeProgressChanged
NoteManager.instance.empty()
switch(PaintViewController.courseTitle)
{
case "upsidedown":
paintView.tutorialBuffer.paintCanvas.addImageLayer("chicken180", index: 1)
default:
break;
}
paintView.glDraw()
setup()
}
//initMode(paintMode)
}
public func setup()
{
viewWidth = view.contentScaleFactor * view.frame.width
noteListTableView.reloadData()
noteProgressButtonSetUp()
noteEditSetUp()
replayControlSetup()
gestureHandlerSetUp()
enterDrawMode()
strokeSelecter.originalClip = paintManager.artwork.useMasterClip()
strokeSelecter.selectRectView = selectRectView
}
public override func viewDidAppear(_ animated: Bool) {
colorPicker.setTheColor(UIColor(hue: 0, saturation: 0.0, brightness: 0.2, alpha: 1.0))
//paintManager.playArtworkClip()
}
/*
func initMode(paintMode:PaintMode)
{
switch(paintMode)
{
case .Artwork:
print("------Artwork Draw Mode-------")
appState = .drawArtwork
enterDrawMode()
case .Revision:
print("------Revision View Mode-------")
appState = .viewArtwork
enterViewMode()
}
}
*/
@IBOutlet weak var ToolKnob: UIView!
@IBOutlet weak var canvasBGView: UIView!
@IBOutlet weak var instructionBGView: UIView!
// @IBOutlet weak var paintView: PaintView!
var instructionView:PaintView!
var paintView: PaintView!
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var brushScaleSlider: UISlider!
var last_ori_pos:CGPoint = CGPoint(x: 0, y: 0)
@IBAction func brushScaleSliderChanged(_ sender: UISlider) {
paintView.paintBuffer.paintToolManager.changeSize(sender.value)
}
//note related
@IBOutlet weak var noteButtonView: NoteProgressView!
@IBOutlet weak var noteTitleField: NoteTitleField!
@IBOutlet weak var noteDescriptionTextView: NoteTextArea!
@IBOutlet weak var noteDetailView: NoteTextView!
@IBOutlet weak var editNoteButton: UIBarButtonItem!
@IBAction func editNoteButtonTouched(_ sender: UIBarButtonItem) {
editNote()
noteTitleField.becomeFirstResponder()
}
@IBAction func deleteNoteButtonTouched(_ sender: UIBarButtonItem) {
deleteNote(NoteManager.instance.selectedButtonIndex)
}
var disx:CGFloat = 0
var rect:GLRect!
//var canvasPanGestureHandler:CanvasPanGestureHandler!
//@IBOutlet weak var canvasImageView: UIImageView!
func resetAnchor(_ targetPaintView:PaintView)
{
targetPaintView.rotation = 0
targetPaintView.translation = CGPoint.zero
targetPaintView.scale = 1
targetPaintView.layer.transform = CATransform3DMakeScale(1, 1, 1)
targetPaintView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
//*TODO position needs to change
targetPaintView.layer.position = CGPoint(x:mainView.frame.width/2,y: mainView.frame.height/2)
//imageView.image = GLContextBuffer.instance.image
}
var pinchPoint:CGPoint!
func setAnchorPoint(_ anchorPoint: CGPoint, forView view: UIView) {
var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = newPoint.applying(view.transform)
oldPoint = oldPoint.applying(view.transform)
var position = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
//replay control
@IBOutlet weak var replayProgressBar: UIProgressView!
@IBOutlet weak var progressSlider: UISlider!
@IBOutlet weak var doublePlayBackButton: UIButton!
@IBOutlet weak var playbackControlPanel: PlayBackControlPanel!
@IBOutlet weak var playPauseButton: PlayPauseButton!
let playImage = UIImage(named: "Play-50")
let pauseImage = UIImage(named: "Pause-50")
var isCellSelectedSentbySlider:Bool = false
//var canvasCropView:CanvasCropView!
func getView(_ name:String)->UIView
{
return Bundle.main.loadNibNamed(name, owner: self, options: nil)![0] as! UIView
}
var doubleTap:Bool = false
@IBAction func doubleTapEraserHandler(_ sender: UIButton) {
paintManager.clean()
checkUndoRedo()
paintView.paintBuffer.paintToolManager.usePreviousTool()
paintView.paintBuffer.setBrushDrawSetting(paintView.paintBuffer.paintToolManager.currentTool.toolType)
paintView.paintBuffer.paintToolManager.changeColor(colorPicker.color)
doubleTap = true
}
var isCanvasManipulationEnabled:Bool = true
//Extra Panels--------------------
//Extra Panels-----------.---.----
//Extra Panels-------------.------
//Extra Panels--------------------
//Extra Panels--------------------
@IBOutlet weak var toolView: UIView!
@IBOutlet weak var toolViewLeadingConstraint: NSLayoutConstraint!
var toolViewState:SubViewPanelAnimateState!
@IBOutlet weak var boundBorderView: UIView!
@IBOutlet weak var boundBorderViewLeadingConstraint:NSLayoutConstraint!
@IBOutlet weak var canvasBGLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var noteEditView: UIView!
@IBOutlet weak var noteEditViewTopConstraint: NSLayoutConstraint!
var noteEditViewState:SubViewPanelAnimateState!
@IBOutlet weak var noteListView: UIView!
@IBOutlet weak var noteListTableView: UITableView!
@IBOutlet weak var noteListViewTrailingConstraint: NSLayoutConstraint!
var noteListViewState:SubViewPanelAnimateState!
@IBOutlet weak var playBackToolbar: UIToolbar!
@IBOutlet weak var playBackView: UIView!
@IBOutlet weak var playBackViewBottomConstraint: NSLayoutConstraint!
var playBackViewState:SubViewPanelAnimateState!
enum NoteEditMode{
case edit
case new
}
var noteEditMode:NoteEditMode = .new
//var selectedNote:Int = -1
//var selectedNoteCell:NoteDetailCell!
var selectedPath:IndexPath!
//plus button in note table
@IBOutlet weak var addNoteButton: UIBarButtonItem!
@IBOutlet weak var noteEditTextView: UITextView!
@IBOutlet weak var noteEditTitleTextField: UITextField!
///////////////////////////////////////////
// toolbar buttons
///////////////////////////////////////////
@IBOutlet weak var mainToolBar: UIToolbar!
//add a note, only in
// @IBOutlet var addNoteButton: UIBarButtonItem!
//結束批改,only in revision mode
@IBOutlet var reviseDoneButton: UIBarButtonItem!
//進入觀看模式
@IBOutlet var switchModeButton: UIBarButtonItem!
//進入繪圖模式
@IBOutlet weak var undoButton: UIBarButtonItem!
@IBOutlet weak var redoButton: UIBarButtonItem!
@IBOutlet var dismissButton: UIBarButtonItem!
@IBOutlet weak var modeText: UIBarButtonItem!
@IBOutlet var demoAreaText: UIBarButtonItem!
@IBOutlet var practiceAreaText: UIBarButtonItem!
var toolBarItems:[UIBarButtonItem]!
deinit
{
PaintViewController.instance = nil
//PaintView.instance = nil
//reviseDoneButton = nil
//enterViewModeButton = nil
print("deinit", terminator: "")
}
/////// paint tool
@IBOutlet weak var showToolButton: UIButton!
@IBOutlet var nearbyColorButtons: NSArray!//[UIButton]!
@IBOutlet weak var colorGradientView: ColorGradientView!
@IBOutlet weak var hueView: HueView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var tutorialNextStepButton: UIBarButtonItem!
@IBOutlet weak var tutorialLastStepButton: UIBarButtonItem!
@IBOutlet weak var tutorialDescriptionTextView: UITextView!
@IBOutlet weak var tutorialTitleLabel: UILabel!
@IBOutlet weak var tutorialControlPanel: UIView!
var FeedbackBrushModeOn = false
@IBAction func paperSwitchBtnTouched(_ sender: UIBarButtonItem) {
paintView.paintBuffer.switchBG()
paintView.glDraw()
}
//select tool
@IBOutlet weak var selectRectView: SelectRectView!
var strokeSelecter:StrokeSelecter!
//stroke diagnosis
@IBOutlet weak var strokeDiagnosisForceLabel: UILabel!
@IBOutlet weak var strokeDiagnosisAltitudeLabel: UILabel!
@IBOutlet weak var strokeDiagnosisAzimuthLabel: UILabel!
@IBOutlet weak var strokeDiagnosisSpeedLabel: UILabel!
@IBOutlet weak var feedbackBtn: UIButton!
@IBAction func feedbackBtnTouched(_ sender: UIButton) {
FeedbackBrushModeOn = !FeedbackBrushModeOn
var text = "Feedback Mode: Off"
if FeedbackBrushModeOn
{
text = "Feedback Mode: On"
}
feedbackBtn.setTitle(text, for: UIControlState.normal)
}
@IBOutlet weak var colorPickerModeBtn: UIButton!
var isColorPikerOn = false
@IBAction func colorPickerModeBtnTouched(_ sender: UIButton) {
isColorPikerOn = !isColorPikerOn
var text = "Picker:Off"
if isColorPikerOn
{
text = "Picker:On"
}
colorPickerModeBtn.setTitle(text, for: UIControlState.normal)
}
var pickOrder = 0
var motion1:[CGFloat] = [0,0,0]
var motion2:[CGFloat] = [0,0,0]
func colorPickerPick(color:UIColor)
{
let motion = colorToMotion(color: color)
if pickOrder == 0
{
pickOrder = 1
motion1 = motion
//DLog("\(motion)")
}
else
{
pickOrder = 0
motion2 = motion
//DLog("\(motion)")
}
var speedText = "write slower"
if motion1[0] < motion2[0]
{
speedText = "write quicker"
}
var forceText = "less pressure"
if motion1[1] < motion2[1]
{
forceText = "more pressure"
}
var altText = "strait more"
if motion1[2] < motion2[2]
{
altText = "tilt more"
}
strokeDiagnosisSpeedLabel.text = "Speed: T:\(motion1[0].format(f: ".2")), S:\(motion2[0].format(f: ".2")) \(speedText)"
strokeDiagnosisForceLabel.text = "Force: T:\(motion1[1].format(f: ".2")) S:\(motion2[1].format(f: ".2")) \(forceText)"
strokeDiagnosisAltitudeLabel.text = "Alititude: T:\(motion1[2].format(f: ".2")) S:\(motion2[2].format(f: ".2")) \(altText)"
}
func colorToMotion(color:UIColor)->[CGFloat]
{
let rgba = color.cgColor.components
let r = rgba?[0]
let g = rgba?[1]
let b = rgba?[2]
// let a = rgba?[3]
let speed = r
let force = g
let azimuth = b
return [force!,azimuth!,speed!]
}
@IBOutlet weak var suggestionTextView: UITextView!
let suggestions = ["Try to tilt more when you do shading","Good Job!","You can increase the pressure to draw darker tone","Nice!","Nice!"]
var count = 0
var index = 0
func nextSuggestion()
{
count = count+1
if count > 10
{
if index < suggestions.count
{
suggestionTextView.text = suggestions[index]
index = index + 1
count = 0
}
}
}
}
extension CGFloat {
func format(f: String) -> String {
return String(format: "%\(f)f", Float(self))
}
}
func isPointContain(_ vertices:[CGPoint],test:CGPoint)->Bool{
let nvert = vertices.count;
var c:Bool = false
var i:Int = 0,j:Int = nvert-1
while i < nvert
{
let verti = vertices[i]
let vertj = vertices[j]
if (( (verti.y > test.y) != (vertj.y > test.y) ) &&
( test.x < ( vertj.x - verti.x ) * ( test.y - verti.y ) / ( vertj.y - verti.y ) + verti.x) )
{
c = !c;
}
j = i
i += 1
}
return c;
}
func CGPointToVec4(_ p:CGPoint)->Vec4
{
return Vec4(x:Float(p.x),y: Float(p.y))
}
func CGPointToVec2(_ p:CGPoint)->Vec2
{
return Vec2(x:Float(p.x),y: Float(p.y))
}
|
mit
|
2cee527694b90cc5e9361931b820fd8b
| 29.007072 | 162 | 0.595663 | 4.81284 | false | false | false | false |
richardpiazza/SOSwift
|
Tests/SOSwiftTests/AlignmentObjectOrCourseOrTextTests.swift
|
1
|
3239
|
import XCTest
@testable import SOSwift
class AlignmentObjectOrCourseOrTextTests: XCTestCase {
static var allTests = [
("testDecode", testDecode),
("testEncode", testEncode),
]
fileprivate class TestClass: Codable, Schema {
var alignmentObject: AlignmentObjectOrCourseOrText?
var course: AlignmentObjectOrCourseOrText?
var text: AlignmentObjectOrCourseOrText?
}
func testDecode() throws {
let json = """
{
"alignmentObject" : {
"@type" : "AlignmentObject",
"name" : "Alignment Object",
"alignmentType" : "teaches",
"educationalFramework" : "The Framework",
"targetDescription" : "Target Description",
"targetName" : "Target Name",
"targetUrl" : "https://www.google.com"
},
"course" : {
"@type" : "Course",
"courseCode" : "CS101"
},
"text" : "Random"
}
"""
let testClass = try TestClass.make(with: json)
XCTAssertEqual(testClass.alignmentObject?.alignmentObject?.name, "Alignment Object")
XCTAssertEqual(testClass.alignmentObject?.alignmentObject?.alignmentType, "teaches")
XCTAssertNil(testClass.alignmentObject?.course)
XCTAssertNil(testClass.alignmentObject?.text)
XCTAssertEqual(testClass.course?.course?.courseCode, "CS101")
XCTAssertNil(testClass.course?.alignmentObject)
XCTAssertNil(testClass.course?.text)
XCTAssertEqual(testClass.text?.text, "Random")
XCTAssertNil(testClass.text?.alignmentObject)
XCTAssertNil(testClass.text?.course)
let missingType = """
{
"alignmentObject": {
"name": "Value"
}
}
"""
XCTAssertThrowsError(try TestClass.make(with: missingType))
let invalidType = """
{
"alignmentObject": {
"@type": "AlIgNmEnTObJeCt"
"name": "Value"
}
}
"""
XCTAssertThrowsError(try TestClass.make(with: invalidType))
}
func testEncode() throws {
let alignmentObject = AlignmentObject()
alignmentObject.targetDescription = "I don't know what this is."
let course = Course()
course.courseCode = "123456"
let testClass = TestClass()
testClass.alignmentObject = AlignmentObjectOrCourseOrText(alignmentObject)
testClass.course = AlignmentObjectOrCourseOrText(course)
testClass.text = AlignmentObjectOrCourseOrText("Something")
let dictionary = try testClass.asDictionary()
let target = dictionary["alignmentObject"] as? [String : Any]
let courseCode = dictionary["course"] as? [String : Any]
let something = dictionary["text"] as? String
XCTAssertEqual(target?["targetDescription"] as? String, "I don't know what this is.")
XCTAssertEqual(courseCode?["courseCode"] as? String, "123456")
XCTAssertEqual(something, "Something")
}
}
|
mit
|
99f8b59282f3230a790911462f81e1d5
| 33.827957 | 93 | 0.578265 | 5.029503 | false | true | false | false |
wikimedia/wikipedia-ios
|
Wikipedia/Code/ArticleFullWidthImageCollectionViewCell.swift
|
1
|
5736
|
import UIKit
@objc(WMFArticleFullWidthImageCollectionViewCell)
open class ArticleFullWidthImageCollectionViewCell: ArticleCollectionViewCell {
public let saveButton = SaveButton()
fileprivate let headerBackgroundView = UIView()
public var headerBackgroundColor: UIColor? {
get {
return headerBackgroundView.backgroundColor
}
set {
headerBackgroundView.backgroundColor = newValue
titleLabel.backgroundColor = newValue
descriptionLabel.backgroundColor = newValue
}
}
public var isHeaderBackgroundViewHidden: Bool {
get {
return headerBackgroundView.superview == nil
}
set {
if newValue {
headerBackgroundView.removeFromSuperview()
} else {
contentView.insertSubview(headerBackgroundView, at: 0)
}
}
}
var saveButtonObservation: NSKeyValueObservation?
override open func setup() {
let extractLabel = UILabel()
extractLabel.isOpaque = true
extractLabel.numberOfLines = 4
addSubview(extractLabel)
self.extractLabel = extractLabel
super.setup()
descriptionLabel.numberOfLines = 2
titleLabel.numberOfLines = 0
saveButton.isOpaque = true
contentView.addSubview(saveButton)
saveButton.verticalPadding = 8
saveButton.rightPadding = 16
saveButton.leftPadding = 12
saveButton.saveButtonState = .longSave
saveButton.titleLabel?.numberOfLines = 0
saveButtonObservation = saveButton.observe(\.titleLabel?.text) { [weak self] (saveButton, change) in
self?.setNeedsLayout()
}
}
deinit {
saveButtonObservation?.invalidate()
}
open override func reset() {
super.reset()
spacing = 6
imageViewDimension = 150
}
open override func updateBackgroundColorOfLabels() {
super.updateBackgroundColorOfLabels()
if !isHeaderBackgroundViewHidden {
titleLabel.backgroundColor = headerBackgroundColor
descriptionLabel.backgroundColor = headerBackgroundColor
}
saveButton.backgroundColor = labelBackgroundColor
saveButton.titleLabel?.backgroundColor = labelBackgroundColor
}
open override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
saveButton.titleLabel?.font = UIFont.wmf_font(saveButtonTextStyle, compatibleWithTraitCollection: traitCollection)
}
public var isSaveButtonHidden = false {
didSet {
saveButton.isHidden = isSaveButtonHidden
setNeedsLayout()
}
}
open override var isSwipeEnabled: Bool {
return isSaveButtonHidden
}
open override func updateAccessibilityElements() {
super.updateAccessibilityElements()
if !isSaveButtonHidden {
var updatedAccessibilityElements = accessibilityElements ?? []
updatedAccessibilityElements.append(saveButton)
accessibilityElements = updatedAccessibilityElements
}
}
open override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let widthMinusMargins = layoutWidth(for: size)
var origin = CGPoint(x: layoutMargins.left, y: 0)
if !isImageViewHidden {
if apply {
imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: imageViewDimension)
}
origin.y += imageViewDimension
}
origin.y += layoutMargins.top + spacing
origin.y += titleLabel.wmf_preferredHeight(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, spacing: spacing, apply: apply)
origin.y += descriptionLabel.wmf_preferredHeight(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, spacing: spacing, apply: apply)
if apply {
titleLabel.isHidden = !titleLabel.wmf_hasText
descriptionLabel.isHidden = !descriptionLabel.wmf_hasText
}
if !isHeaderBackgroundViewHidden && apply {
headerBackgroundView.frame = CGRect(x: 0, y: 0, width: size.width, height: origin.y)
}
if let extractLabel = extractLabel, extractLabel.wmf_hasText {
origin.y += spacing // double spacing before extract
origin.y += extractLabel.wmf_preferredHeight(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, spacing: spacing, apply: apply)
if apply {
extractLabel.isHidden = false
}
} else if apply {
extractLabel?.isHidden = true
}
if !isSaveButtonHidden {
origin.y += spacing - 1
let saveButtonFrame = saveButton.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, horizontalAlignment: isDeviceRTL ? .right : .left, apply: apply)
origin.y += saveButtonFrame.height - 2 * saveButton.verticalPadding
} else {
origin.y += spacing
}
origin.y += layoutMargins.bottom
return CGSize(width: size.width, height: origin.y)
}
}
public class ArticleFullWidthImageExploreCollectionViewCell: ArticleFullWidthImageCollectionViewCell {
override open func apply(theme: Theme) {
super.apply(theme: theme)
setBackgroundColors(theme.colors.cardBackground, selected: theme.colors.selectedCardBackground)
}
}
|
mit
|
9a160ea6884b0a5be91f098037346285
| 35.303797 | 177 | 0.641911 | 5.817444 | false | false | false | false |
JoeHolt/Pong
|
Pong/ViewController.swift
|
1
|
990
|
//
// ViewController.swift
// Pong
//
// Created by Joe Holt on 8/27/17.
// Copyright © 2017 Joe Holt. All rights reserved.
//
import Cocoa
import SpriteKit
import GameplayKit
class ViewController: NSViewController {
@IBOutlet var skView: SKView!
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.skView {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override func viewDidAppear() {
super.viewDidAppear()
self.view.window?.styleMask.remove(.resizable)
}
}
|
apache-2.0
|
f8e92e9d82bd4e2b31030a1cf776e6b8
| 22.547619 | 64 | 0.555106 | 5.020305 | false | false | false | false |
mrketchup/cooldown
|
Core/UIColor+Cooldown.swift
|
1
|
2980
|
//
// Copyright © 2018 Matt Jones. All rights reserved.
//
// This file is part of Cooldown.
//
// Cooldown is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Cooldown is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Cooldown. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public extension UIColor {
// swiftlint:disable identifier_name
struct RGBA {
var r: CGFloat
var g: CGFloat
var b: CGFloat
var a: CGFloat
}
// swiftlint:enable identifier_name
static let cooldownGreen = UIColor(red: 0.1, green: 0.8, blue: 0.1, alpha: 1)
static let cooldownYellow = UIColor(red: 1, green: 0.7, blue: 0, alpha: 1)
static let cooldownRed = UIColor(red: 0.8, green: 0.1, blue: 0.1, alpha: 1)
var rgba: RGBA {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return RGBA(r: red, g: green, b: blue, a: alpha)
}
func blended(with color: UIColor, percent: CGFloat) -> UIColor {
let rgba1 = rgba
let rgba2 = color.rgba
let red = rgba1.r * (1 - percent) + rgba2.r * percent
let green = rgba1.g * (1 - percent) + rgba2.g * percent
let blue = rgba1.b * (1 - percent) + rgba2.b * percent
let alpha = rgba1.a * (1 - percent) + rgba2.a * percent
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
#if os(iOS)
static func textColor(from color: UIColor, for interfaceStyle: UIUserInterfaceStyle) -> UIColor {
switch interfaceStyle {
case .dark: return color
case .light, .unspecified: return .white
@unknown default: return .white
}
}
@available(iOS 12.0, *)
static func backgroundColor(
from color: UIColor,
for interfaceStyle: UIUserInterfaceStyle,
withPreferredDarkBackground darkBackground: UIColor = .darkBackground
) -> UIColor {
switch interfaceStyle {
case .dark:
return darkBackground
case .light, .unspecified:
return color
@unknown default:
return color
}
}
static var darkBackground: UIColor {
if #available(iOSApplicationExtension 13.0, *) {
return .tertiarySystemBackground
} else {
return UIColor(red: 0.17, green: 0.17, blue: 0.18, alpha: 1)
}
}
#endif
}
|
gpl-3.0
|
d9acf86b9ef259240d000cca053b7b0a
| 32.1 | 101 | 0.616314 | 4.036585 | false | false | false | false |
CoderST/DYZB
|
DYZB/DYZB/Class/Main/Model/BaseGameModel.swift
|
1
|
826
|
//
// BaseGameModel.swift
// DYZB
//
// Created by xiudou on 16/10/26.
// Copyright © 2016年 xiudo. All rights reserved.
//
import UIKit
class BaseGameModel: BaseModel {
// MARK:- 定义属性
var tag_name : String = ""
var icon_url : String = ""
var tag_id : String = ""
override func setValue(_ value: Any?, forKey key: String) {
if key == "tag_id" {
if value is Int { // Int
guard let tag_idInt = value as? Int else { return }
let tag_idString = "\(tag_idInt)"
tag_id = tag_idString
}else{ // String
guard let tag_idString = value as? String else { return }
tag_id = tag_idString
}
}else {
super.setValue(value, forKey: key)
}
}
}
|
mit
|
d19dfc4ad3ffa52df02629a2c19f2985
| 23.69697 | 73 | 0.507975 | 3.937198 | false | false | false | false |
B-Lach/PocketCastsKit
|
SharedSource/API/PCKClientProtocol.swift
|
1
|
7971
|
//
// PCKClientProtocol.swift
// PocketCastsKit
//
// Created by Benny Lach on 18.08.17.
// Copyright © 2017 Benny Lach. All rights reserved.
//
import Foundation
/// Enum representing the PlayingStatus of an Episode
///
/// - unplayed: The Episode was never player
/// - playing: The Episode is currently playing
/// - played: The Episode was played to the end
public enum PlayingStatus: Int {
case unplayed = 0
case playing = 2
case played = 3
}
/// Enum representing the Sort Order
///
/// - ascending: Sort old to new
/// - descending: Sort new to old
public enum SortOrder: Int {
case ascending = 2
case descending = 3
}
protocol PCKClientProtocol {
// MARK: - Authentication
/// Authenticate as a valid User
///
/// - Parameters:
/// - username: The Username
/// - password: The Password
/// - completion: The CompletionHandler called after the request finished
func authenticate(username: String, password: String, completion: @escaping completion<Bool>)
/// Check if the User is authenticated
///
/// - Parameter completion: The CompletionHandler called after the request finished
func isAuthenticated(completion: @escaping completion<Bool>)
// MARK: - User Feeds
/// Get all subscribed Podcasts for the authenticated User
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getSubscriptions(completion: @escaping completion<[PCKPodcast]>)
/// Get all new Episodes for the authenticated User
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getNewEpisodes(completion: @escaping completion<[PCKEpisode]>)
/// Get all Episodes with progress for the authenticated User
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getEpisodesInProgress(completion: @escaping completion<[PCKEpisode]>)
/// Get all starred Episodes for the authenticated User
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getStarredEpisodes(completion: @escaping completion<[PCKEpisode]>)
// MARK: - Episode Actions
/// Set the starred option of an Episode
///
/// - Parameters:
/// - episode: The UUID of the Episode
/// - podcast: The UUID of the Podcast
/// - starred: Bool indicating if the Episode is starred or not
/// - completion: The CompletionHandler called after the request finished
func setStarred(for episode: UUID, podcast: UUID, starred: Bool, completion: @escaping completion<Bool>)
/// Set the PlayingStatus of an Episode
///
/// - Parameters:
/// - episode: The UUID of the Episode
/// - podcast: The UUID of the Podcast
/// - status: The Status to set
/// - completion: The CompletionHandler called after the request finished
func setPlayingStatus(for episode: UUID, podcast: UUID, status: PlayingStatus, completion: @escaping completion<Bool>)
/// Set the current position of a playing Episode
///
/// - Parameters:
/// - episode: The UUID of the Episode
/// - podcast: The UUID of the Podcast
/// - position: The Position to set as Int
/// - completion: The CompletionHandler called after the request finished
func setPlayingPosition(for episode: UUID, podcast: UUID, position: Int, completion: @escaping completion<Bool>)
/// Get the Show Notes of an Episode
///
/// - Parameters:
/// - episode: The UUID of the Episode
/// - completion: The CompletionHandler called after the request finished
func getShowNotes(for episode: UUID, completion: @escaping completion<String>)
/// Get a specific Episode of a given Podcast
///
/// - Parameters:
/// - uuid: The UUID of the Episode
/// - podcast: the UUID of the Podcast
/// - completion: The CompletionHandler called after the request finished
func getEpisode(with uuid: UUID, of podcast: UUID, completion: @escaping completion<PCKEpisode>)
// MARK: - Podcast Actions
/// Subscribe to a Podcast
///
/// - Parameters:
/// - podcast: The UUID of the Podcast
/// - completion: The CompletionHandler called after the request finished
func subscribe(podcast: UUID, completion: @escaping completion<Bool>)
/// Unsubscribe from a Podcast
///
/// - Parameters:
/// - podcast: The UUID of the Podcast
/// - completion: The CompletionHandler called after the request finished
func unsubscribe(podcast: UUID, completion: @escaping completion<Bool>)
/// Get Episodes of a given Podcast
///
/// - Parameters:
/// - podcast: The UUID of the Podcast
/// - page: <b>optaional</b> If paging is available, use this parameter to define the page you want to fetch
/// - order: <b>optaional</b> Sepcifies if you want to fetch newes or oldes first. Default is descending
/// - completion: The CompletionHandler called after the request finished
func getEpisodes(for podcast: UUID,
page: Int, order: SortOrder,
completion: @escaping completion<(episodes:[PCKEpisode], order: SortOrder, nextPage: Int)>)
/// Get a Podcast by a specific UUID
///
/// - Parameters:
/// - uuid: The UUID of the Podcast
/// - completion: The CompletionHandler called after the request finished
func getPodcast(with uuid: UUID, completion: @escaping completion<PCKPodcast>)
/// Search a Podcast by a given String
///
/// - Parameters:
/// - string: The String to search for
/// - completion: The CompletionHandler called after the request finished
func searchPodcasts(by string: String, completion: @escaping completion<[PCKPodcast]>)
// MARK: - Global Actions
/// Get the Top 100 Podcasts in Pocket Casts - Authentication is not required
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getTop100(completion: @escaping completion<[PCKPodcast]>)
/// Get all featured Podcasts in Pocket Casts - Authentication is not required
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getFeatured(completion: @escaping completion<[PCKPodcast]>)
/// Get all trending Podcasts in Pocket Casts - Authentication is not required
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getTrending(completion: @escaping completion<[PCKPodcast]>)
/// Get all Categories and Countries available in Pocket Casts - Authentication is not required
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getCategoriesAndCountries(completion: @escaping completion<(categories: [PCKCategory], countries: [PCKCountry])>)
/// Get all Networks available in Pocket Casts - Authentication is not required
///
/// - Parameter completion: The CompletionHandler called after the request finished
func getNetworks(completion: @escaping completion<[PCKNetwork]>)
/// Get all Groups of specific Network - Authentication is not required
///
/// - Parameters:
/// - networkId: The Id of the Network
/// - completion: The CompletionHandler called after the request finished
func getNetworkGroups(networkId: Int, completion: @escaping completion<[PCKNetworkGroup]>)
/// Get the Content (Array of PCKCategoryContent objects) of a Category for a specific Country - Authentication is not required
///
/// - Parameters:
/// - categoryId: The Id of the category
/// - countryCode: The Code of the country
/// - completion: The CompletionHandler called after the request finished
func getCategoryContent(categoryId: Int, countryCode: String, completion: @escaping completion<[PCKCategoryContent]>)
}
|
mit
|
36bfa7926f08d258fc566db9ce47333d
| 45.882353 | 131 | 0.687453 | 4.836165 | false | false | false | false |
sseitov/v-Chess-Swift
|
v-Chess/EatController.swift
|
1
|
2599
|
//
// EatController.swift
// v-Chess
//
// Created by Сергей Сейтов on 20.03.17.
// Copyright © 2017 V-Channel. All rights reserved.
//
import UIKit
class EatController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var figures:[UIImageView] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.setupBorder(UIColor.white, radius: 5, width: 2)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
collectionView?.reloadData()
}
@objc func eat(_ figure:UIImageView) {
figures.append(figure)
collectionView?.reloadData()
}
@objc func retrive() -> UIImageView? {
let figure = figures.last
figures.removeLast()
collectionView?.reloadData()
return figure
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) in
}) { (context: UIViewControllerTransitionCoordinatorContext) in
self.collectionView?.reloadData()
}
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return figures.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "figure", for: indexPath) as! EatCell
cell.figureView.image = figures[indexPath.row].image
return cell
}
// MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if self.collectionView!.frame.width > self.collectionView!.frame.height {
let width = self.collectionView!.frame.width / 8
let height = self.collectionView!.frame.height / 2
return CGSize(width: width, height: height)
} else {
let width = self.collectionView!.frame.width / 2
let height = self.collectionView!.frame.height / 8
return CGSize(width: width, height: height)
}
}
}
|
gpl-3.0
|
7e925d6d8c3afec3f0da5e9537bf6191
| 33.48 | 160 | 0.678654 | 5.331959 | false | false | false | false |
jholsapple/TheIronYard-Assignments
|
30 -- HighVoltage -- John Holsapple/30 -- HighVoltage -- John Holsapple/PopoverTableViewController.swift
|
2
|
2169
|
//
// PopoverTableViewController.swift
// 30 -- HighVoltage -- John Holsapple
//
// Created by John Holsapple on 7/24/15.
// Copyright (c) 2015 John Holsapple -- The Iron Yard. All rights reserved.
//
import UIKit
class PopoverTableViewController: UITableViewController
{
var selectedIndex: Int = 0
var dataTypes = [String]()
var delegate: PopoverVCDelegate?
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// Return the number of rows in the section.
return dataTypes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("DataTypeCell", forIndexPath: indexPath)
cell.textLabel!.text = dataTypes[indexPath.row]
if indexPath.row == self.selectedIndex
{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else
{
cell.accessoryType = UITableViewCellAccessoryType.None
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
delegate?.valueTypeWasChosen(dataTypes[indexPath.row])
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
// Delete the row
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
else if editingStyle == .Insert
{
}
}
}
|
cc0-1.0
|
6073dbd5f62c808fe899810f2c4f828c
| 26.455696 | 155 | 0.645459 | 5.633766 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS
|
Aztec/Classes/Extensions/String+Paragraph.swift
|
2
|
2572
|
import Foundation
// MARK: - Paragraph Analysis Helpers
//
public extension String {
/// This methods verifies if the receiver string contains a new paragraph at the specified index.
///
/// - Parameter index: the index to check
///
/// - Returns: `true` if the receiver contains a new paragraph at the specified Index.
///
func isStartOfParagraph(at index: String.Index) -> Bool {
guard index != startIndex else {
return true
}
return isEndOfParagraph(before: index)
}
/// This methods verifies if the receiver string contains an End of Paragraph at the specified index.
///
/// - Parameter index: the index to check
///
/// - Returns: `true` if the receiver contains an end-of-paragraph character at the specified Index.
///
func isEndOfParagraph(at index: String.Index) -> Bool {
guard index != endIndex else {
return true
}
let endingRange = index ..< self.index(after: index)
let endingString = compatibleSubstring(with: endingRange)
let paragraphSeparators = [String(.carriageReturn), String(.lineFeed), String(.paragraphSeparator)]
return paragraphSeparators.contains(endingString)
}
/// This methods verifies if the receiver string contains an End of Paragraph before the specified index.
///
/// - Parameter index: the index to check
///
/// - Returns: `true` if the receiver contains an end-of-paragraph character before the specified Index.
///
func isEndOfParagraph(before index: String.Index) -> Bool {
assert(index != startIndex)
return isEndOfParagraph(at: self.index(before: index))
}
/// Checks if the receiver has an empty paragraph at the specified index.
///
/// - Parameter index: the receiver's index to check
///
/// - Returns: `true` if the specified index is in an empty paragraph, `false` otherwise.
///
func isEmptyParagraph(at index: String.Index) -> Bool {
return isStartOfParagraph(at: index) && isEndOfParagraph(at: index)
}
/// Checks if the receiver has an empty paragraph at the specified offset.
///
/// - Parameter offset: the receiver's offset to check
///
/// - Returns: `true` if the specified offset is in an empty line, `false` otherwise.
///
func isEmptyParagraph(at offset: Int) -> Bool {
guard let index = self.indexFromLocation(offset) else {
return true
}
return isEmptyParagraph(at: index)
}
}
|
gpl-2.0
|
907dfb6922744618d34a49d96413e233
| 31.974359 | 109 | 0.643468 | 4.650995 | false | false | false | false |
malaonline/iOS
|
mala-ios/Model/Other/CommentModel.swift
|
1
|
1291
|
//
// CommentModel.swift
// mala-ios
//
// Created by 王新宇 on 3/21/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
open class CommentModel: BaseObjectModel {
// MARK: - Property
/// 课时数
var timeslot: Int = 0
/// 评分
var score: Int = 0
/// 评价内容
var content: String = ""
// MARK: - Constructed
override init() {
super.init()
}
override init(dict: [String: Any]) {
super.init(dict: dict)
setValuesForKeys(dict)
}
convenience init(id: Int, timeslot: Int, score: Int, content: String) {
self.init()
self.id = id
self.timeslot = timeslot
self.score = score
self.content = content
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Override
override open func setValue(_ value: Any?, forUndefinedKey key: String) {
println("CommentModel - Set for UndefinedKey: \(key)")
}
// MARK: - Description
override open var description: String {
let keys = ["id", "timeslot", "score", "content"]
return "\n"+dictionaryWithValues(forKeys: keys).description+"\n"
}
}
|
mit
|
f77cdb2ce9369190d17babb61f1a5c7c
| 22.018182 | 77 | 0.57188 | 3.981132 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/Authentication/Event Handlers/Post-Login/UserChange/UserEmailChangeEventHandler.swift
|
1
|
1755
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
/**
* Handles the change of email of the user when logging in.
*/
class UserEmailChangeEventHandler: AuthenticationEventHandler {
weak var statusProvider: AuthenticationStatusProvider?
func handleEvent(currentStep: AuthenticationFlowStep, context: UserChangeInfo) -> [AuthenticationCoordinatorAction]? {
let changeInfo = context
// Only execute actions if the profile has changed.
guard changeInfo.profileInformationChanged else {
return nil
}
// Only look for email changes in the email link step
guard case .pendingEmailLinkVerification = currentStep else {
return nil
}
// Verify state
guard let selfUser = statusProvider?.selfUser else {
return nil
}
guard selfUser.emailAddress?.isEmpty == false else {
return nil
}
// Complete the login flow when the user finished adding email
return [.hideLoadingView, .completeLoginFlow]
}
}
|
gpl-3.0
|
fcda9c5f560c58332b6af113e3a25e27
| 30.339286 | 122 | 0.694587 | 4.915966 | false | false | false | false |
burla69/PayDay
|
PayDay/BurgerMenuTableViewController.swift
|
1
|
3414
|
//
// BurgerMenuTableViewController.swift
// PayDay
//
// Created by Oleksandr Burla on 4/19/16.
// Copyright © 2016 Oleksandr Burla. All rights reserved.
//
import UIKit
protocol BurgerMenuTableViewControllerDelegate {
func selectedFromBurgerMenuTableViewController(string: String)
}
class BurgerMenuTableViewController: UITableViewController {
var delegate: BurgerMenuTableViewControllerDelegate!
var userOption = 0
var dataSource: NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
print("User OPTION: \(userOption)")
//
// if self.userOption == 0 {
// print("user option = 0")
// } else if self.userOption == 1 {
// print("user option = 1")
// dropDown.dataSource = ["Break"]
// //self.navigationItem.setRightBarButtonItem(rightMenuButton, animated: false);
// } else if self.userOption == 2 {
// print("user option = 2")
// dropDown.dataSource = ["Call Back Duty"]
// //self.navigationItem.setRightBarButtonItem(rightMenuButton, animated: false);
// } else if self.userOption == 3 {
// print("user option = 3")
// dropDown.dataSource = ["Break", "Call Back Duty"]
// //self.navigationItem.setRightBarButtonItem(rightMenuButton, animated: false);
// }
if userOption == 0 {
dataSource = ["Support"]
} else if self.userOption == 1 {
dataSource = ["Break", "Support"]
} else if self.userOption == 2 {
dataSource = ["Call Back Duty", "Support"]
} else if self.userOption == 3 {
dataSource = ["Break", "Call Back Duty", "Support"]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.dataSource.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = dataSource[indexPath.row] as? String
cell.textLabel?.textColor = UIColor.whiteColor()
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath)
self.delegate.selectedFromBurgerMenuTableViewController((cell?.textLabel?.text)!)
dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
89ecd7e0e883784fdeaa50df7fd1027f
| 30.601852 | 118 | 0.627893 | 5.063798 | false | false | false | false |
toggl/superday
|
teferi/Interactors/MigrateLocationsFromLogs.swift
|
1
|
2461
|
import Foundation
import RxSwift
class MigrateLocationsFromLogs: Interactor
{
private let repositoryService: RepositoryService
private var logURL : URL?
{
let fileManager = FileManager.default
var logURL : URL?
if let cacheDir = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first
{
logURL = cacheDir.appendingPathComponent("swiftybeaver.log")
}
return logURL
}
private lazy var dateFormatter: DateFormatter =
{
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
init(repositoryService: RepositoryService)
{
self.repositoryService = repositoryService
}
func execute() -> Observable<Void>
{
guard let logURL = logURL, let data = try? String(contentsOf: logURL) else { return Observable.just(()) }
let locations = splitToRows(data)
.filter(isLocationRow)
.map(tokenize)
.map(toLocationEntities)
return repositoryService.saveLocationEntities(locationEntities: locations)
}
private func splitToRows(_ data: String) -> [String]
{
return data.components(separatedBy: "\n")
}
private func isLocationRow(_ row: String) -> Bool
{
return row.contains("DEBUG => Received a valid location")
}
private func tokenize(_ row: String) -> [String]
{
return row
.replacingOccurrences(of: ".: DEBUG => Received a valid location <", with: "$")
.replacingOccurrences(of: ",", with: "$")
.replacingOccurrences(of: "> ~", with: "$")
.replacingOccurrences(of: "m (speed: ", with: "$")
.replacingOccurrences(of: "/s course: ", with: "$")
.replacingOccurrences(of: "/s course: ", with: "$")
.replacingOccurrences(of: ") at ", with: "$")
.components(separatedBy: "$")
}
private func toLocationEntities(_ tokens: [String]) -> LocationEntity
{
return LocationEntity(timeStamp: dateFormatter.date(from: tokens[6])!,
latitude: Double(tokens[1])!,
longitude: Double(tokens[2])!,
altitude: 0.0,
accuracy: Double(tokens[3])!)
}
}
|
bsd-3-clause
|
f9557e5c3ead44ac97cf71b08e763246
| 31.813333 | 113 | 0.557903 | 4.931864 | false | false | false | false |
OscarSwanros/swift
|
test/PrintAsObjC/accessibility.swift
|
13
|
2456
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -parse-as-library %s -typecheck -emit-objc-header-path %t/accessibility.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-PUBLIC %s < %t/accessibility.h
// RUN: %check-in-clang %t/accessibility.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -typecheck -emit-objc-header-path %t/accessibility-internal.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-internal.h
// RUN: %check-in-clang %t/accessibility-internal.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -import-objc-header %S/../Inputs/empty.h -emit-objc-header-path %t/accessibility-imported-header.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-imported-header.h
// RUN: %check-in-clang %t/accessibility-imported-header.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -DMAIN -emit-objc-header-path %t/accessibility-main.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-main.h
// RUN: %check-in-clang %t/accessibility-main.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -application-extension -emit-objc-header-path %t/accessibility-appext.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-appext.h
// RUN: %check-in-clang %t/accessibility-appext.h
// REQUIRES: objc_interop
// CHECK-LABEL: @interface A_Public{{$}}
// CHECK-INTERNAL-NEXT: init
// CHECK-NEXT: @end
@objc public class A_Public {}
// CHECK-PUBLIC-NOT: B_Internal
// CHECK-INTERNAL-LABEL: @interface B_Internal{{$}}
// CHECK-INTERNAL-NEXT: init
// CHECK-INTERNAL-NEXT: @end
@objc internal class B_Internal {}
// CHECK-NOT: C_Private
@objc private class C_Private {}
#if MAIN
#if os(OSX)
import AppKit
@NSApplicationMain
@objc class AppDelegate : NSApplicationDelegate {}
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
@UIApplicationMain
@objc class AppDelegate : NSObject, UIApplicationDelegate {}
#else
// Uh oh, this test depends on having an app delegate.
#endif
#endif
|
apache-2.0
|
56f1fa90e6419ae2d0d04f5df1cec215
| 43.654545 | 238 | 0.745114 | 3.181347 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.