hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
fc26f7e0548b8c3b62e77a6d43008f06094256be | 6,912 | import XCTest
import JsonInflator
class Tests: XCTestCase {
// ---
// MARK: Test array conversion
// ---
func testAsStringArray() {
XCTAssertEqual([ "first", "second" ], convUtilInstance().asStringArray(value: [ "first", "second" ]))
XCTAssertEqual([ "10", "12", "99", "24" ], convUtilInstance().asStringArray(value: [ 10, 12, 99, 24 ]))
}
func testAsDoubleArray() {
XCTAssertEqual([ 4.22, 8.9, 19.1, 11 ], convUtilInstance().asDoubleArray(value: [ "4.22", "8.9", "19.1", "11" ]))
XCTAssertEqual([ 3.11, 16 ], convUtilInstance().asDoubleArray(value: [ 3.11, 16 ]))
}
func testAsFloatArray() {
XCTAssertEqual([ 1.1, 5, 89.16, 2 ], convUtilInstance().asFloatArray(value: [ 1.1, 5, 89.16, 2 ]))
XCTAssertEqual([ 67, 11 ], convUtilInstance().asFloatArray(value: [ 67, 11 ]))
}
func testAsIntArray() {
XCTAssertEqual([ 325, -23 ], convUtilInstance().asIntArray(value: [ 325, -23 ]))
XCTAssertEqual([ 6, 3, 12, 2150 ], convUtilInstance().asIntArray(value: [ "6.1", "3", "12", "2150.654" ]))
}
func testAsBoolArray() {
XCTAssertEqual([ true, true, false, true ], convUtilInstance().asBoolArray(value: [ "true", "true", "false", "true" ]))
XCTAssertEqual([ true, false, true ], convUtilInstance().asBoolArray(value: [ 12, 0, 1 ]))
XCTAssertEqual([ false, true ], convUtilInstance().asBoolArray(value: [ false, true ]))
}
// ---
// MARK: Test view related data conversion
// ---
func testAsPointValueArray() {
let pixel = 1 / UIScreen.main.scale
let widthPoint = CGFloat(UIScreen.main.bounds.width / 100)
let heightPoint = CGFloat(UIScreen.main.bounds.height / 100)
XCTAssertEqual(
[ pixel, 10, 4, 9, CGFloat(Float(10)) * widthPoint, CGFloat(Float(5.2)) * heightPoint, CGFloat(Float(1.94)) * min(widthPoint, heightPoint), CGFloat(Float(-2.4)) * max(widthPoint, heightPoint)],
convUtilInstance().asDimensionArray(value: [ "1px", "10dp", "4sp", "9dp", "10wp", "5.2hp", "1.94minp", "-2.4maxp" ])
)
}
func testAsColor() {
XCTAssertEqual(UIColor.red, convUtilInstance().asColor(value: "#ff0000"))
XCTAssertEqual(UIColor(red: 0, green: 0, blue: 0, alpha: 0), convUtilInstance().asColor(value: "#00000000"))
XCTAssertEqual(UIColor(red: 0, green: 0, blue: 0, alpha: 176.0 / 255), convUtilInstance().asColor(value: "#b0000000"))
XCTAssertEqual(UIColor.yellow, convUtilInstance().asColor(value: "#ff0"))
XCTAssertEqual(UIColor(red: 1, green: 1, blue: 1, alpha: 0), convUtilInstance().asColor(value: "#0fff"))
XCTAssertEqual(UIColor(hue: 259.0 / 360, saturation: 99.0 / 100, brightness: 10.0 / 100, alpha: 1), convUtilInstance().asColor(value: "h259s99v10"))
XCTAssertEqual(UIColor(hue: 164.0 / 360, saturation: 83.0 / 100, brightness: 95.0 / 100, alpha: 0.5), convUtilInstance().asColor(value: "h164s83v95a50"))
XCTAssertEqual(UIColor(red: 0.3159, green: 0.40976, blue: 0.4641, alpha: 0.25), convUtilInstance().asColor(value: "H202 S19 L39 A25"))
}
func testAsPointValue() {
let pixel = 1 / UIScreen.main.scale
let widthPoint = UIScreen.main.bounds.width / 100
let heightPoint = UIScreen.main.bounds.height / 100
XCTAssertEqual(pixel, convUtilInstance().asDimension(value: "1px"))
XCTAssertEqual(20, convUtilInstance().asDimension(value: "20dp"))
XCTAssertEqual(12, convUtilInstance().asDimension(value: "12sp"))
XCTAssertEqual(8, convUtilInstance().asDimension(value: 8))
XCTAssertEqual(widthPoint * 12.5, convUtilInstance().asDimension(value: "12.5wp"))
XCTAssertEqual(heightPoint * 99, convUtilInstance().asDimension(value: "99hp"))
XCTAssertEqual(min(widthPoint, heightPoint) * 45, convUtilInstance().asDimension(value: "45minp"))
XCTAssertEqual(max(widthPoint, heightPoint) * 3, convUtilInstance().asDimension(value: "3maxp"))
}
// ---
// MARK: Test basic value conversion
// ---
func testAsDate() {
XCTAssertEqual(dateFrom(year: 2016, month: 8, day: 19), convUtilInstance().asDate(value: "2016-08-19"))
XCTAssertEqual(dateFrom(year: 2016, month: 5, day: 16, hour: 1, minute: 10, second: 28), convUtilInstance().asDate(value: "2016-05-16T01:10:28"))
XCTAssertEqual(utcDateFrom(year: 2016, month: 2, day: 27, hour: 12, minute: 24, second: 11), convUtilInstance().asDate(value: "2016-02-27T12:24:11Z"))
XCTAssertEqual(utcDateFrom(year: 2016, month: 2, day: 27, hour: 17, minute: 0, second: 0), convUtilInstance().asDate(value: "2016-02-27T19:00:00+02:00"))
}
func testAsString() {
XCTAssertEqual("test", convUtilInstance().asString(value: "test"))
XCTAssertEqual("12", convUtilInstance().asString(value: 12))
XCTAssertEqual("14.42", convUtilInstance().asString(value: 14.42))
XCTAssertEqual("true", convUtilInstance().asString(value: true))
}
func testAsDouble() {
XCTAssertEqual(89.213, convUtilInstance().asDouble(value: "89.213"))
XCTAssertEqual(31, convUtilInstance().asDouble(value: 31))
}
func testAsFloat() {
XCTAssertEqual(21.3, convUtilInstance().asFloat(value: 21.3))
XCTAssertEqual(1, convUtilInstance().asFloat(value: true))
}
func testAsInt() {
XCTAssertEqual(3, convUtilInstance().asInt(value: "3"))
XCTAssertEqual(45, convUtilInstance().asInt(value: 45.75))
}
func testAsBool() {
XCTAssertEqual(false, convUtilInstance().asBool(value: "false"))
XCTAssertEqual(true, convUtilInstance().asBool(value: 2))
}
// ---
// MARK: Helper
// ---
func dateFrom(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) -> Date {
let calendar = Calendar(identifier: .gregorian)
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
return calendar.date(from: components)!
}
func utcDateFrom(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) -> Date {
var calendar = Calendar(identifier: .gregorian)
var components = DateComponents()
calendar.timeZone = TimeZone(identifier: "UTC")!
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
return calendar.date(from: components)!
}
func convUtilInstance() -> InflatorConvUtil {
return InflatorConvUtil()
}
}
| 46.08 | 205 | 0.626447 |
9c60ab52b71959f930bdfb98594485fce6015884 | 1,397 |
//
// 150. 逆波兰表达式求值
//
// 根据逆波兰表示法,求表达式的值。
//
// 题目链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
// 标签:栈、
// 要点:操作数压栈、操作符出栈
// 时间复杂度:O(N)
// 空间复杂度:O(<N),最大不会超过 N
//
import Foundation
class Solution {
func evalRPN(_ tokens: [String]) -> Int {
enum Operator: String {
case add = "+"
case minus = "-"
case multiply = "*"
case divide = "/"
func exec(left: Int, right: Int) -> Int {
switch self {
case .add: return left + right
case .minus: return left - right
case .multiply: return left * right
case .divide: return left / right
}
}
}
var stack = [Int]()
for token in tokens {
if let op = Operator(rawValue: token) {
guard let right = stack.popLast(), let left = stack.popLast() else { break }
stack.append(op.exec(left: left, right: right))
} else if let num = Int(token) {
stack.append(num)
}
}
return stack.first!
}
}
/// Tests
let s = Solution()
s.evalRPN(["2", "1", "+", "3", "*"]) == 9
s.evalRPN(["4", "13", "5", "/", "+"]) == 6
s.evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22
| 25.87037 | 92 | 0.444524 |
ef11e8051dd9b9ac5dc110dad6423648c22856dd | 2,209 | import Workflow
/// A set of expectations for use with the `WorkflowRenderTester`. All of the expectations must be fulfilled
/// for a `render` test to pass.
public struct RenderExpectations<WorkflowType: Workflow> {
var expectedState: ExpectedState<WorkflowType>?
var expectedWorkers: [ExpectedWorker]
public init(
expectedState: ExpectedState<WorkflowType>? = nil,
expectedWorkers: [ExpectedWorker] = []) {
self.expectedState = expectedState
self.expectedWorkers = expectedWorkers
}
}
public struct ExpectedState<WorkflowType: Workflow> {
var state: WorkflowType.State
var isEquivalent: (WorkflowType.State, WorkflowType.State) -> Bool
/// Create a new expected state from a state with an equivalence block. `isEquivalent` will be
/// called to validate that the expected state matches the actual state after a render pass.
public init<State>(state: State, isEquivalent: @escaping (State, State) -> Bool) where State == WorkflowType.State {
self.state = state
self.isEquivalent = isEquivalent
}
public init<State>(state: State) where WorkflowType.State == State, State: Equatable {
self.init(state: state, isEquivalent: { (expected, actual) in
return expected == actual
})
}
}
public struct ExpectedWorker {
var worker: Any
private var output: Any?
/// Create a new expected worker with an optional output. If `output` is not nil, it will be emitted
/// when this worker is declared in the render pass.
public init<WorkerType: Worker>(worker: WorkerType, output: WorkerType.Output? = nil) {
self.worker = worker
self.output = output
}
func isEquivalent<WorkerType: Worker>(to actual: WorkerType) -> Bool {
guard let expectedWorker = self.worker as? WorkerType else {
return false
}
return expectedWorker.isEquivalent(to: actual)
}
func outputAction<Output, ActionType>(outputMap: (Output) -> ActionType) -> ActionType? where ActionType: WorkflowAction {
guard let output = output as? Output else {
return nil
}
return outputMap(output)
}
}
| 33.469697 | 126 | 0.677682 |
5b33303cdc3591c2dd8a5ca51e317dbe511b134f | 35,724 | import Foundation
import TSCBasic
import TuistCore
import TuistSupport
import XcodeProj
/// Protocol that defines the interface of the schemes generation.
protocol SchemeDescriptorsGenerating {
/// Generates the schemes for the workspace targets.
///
/// - Parameters:
/// - workspace: Workspace model.
/// - xcworkspacePath: Path to the workspace.
/// - generatedProject: Generated Xcode project.
/// - graphTraverser: Graph traverser.
/// - Throws: A FatalError if the generation of the schemes fails.
func generateWorkspaceSchemes(workspace: Workspace,
generatedProjects: [AbsolutePath: GeneratedProject],
graphTraverser: GraphTraversing) throws -> [SchemeDescriptor]
/// Generates the schemes for the project targets.
///
/// - Parameters:
/// - project: Project manifest.
/// - xcprojectPath: Path to the Xcode project.
/// - generatedProject: Generated Xcode project.
/// - graphTraverser: Graph traverser.
/// - Throws: A FatalError if the generation of the schemes fails.
func generateProjectSchemes(project: Project,
generatedProject: GeneratedProject,
graphTraverser: GraphTraversing) throws -> [SchemeDescriptor]
}
// swiftlint:disable:next type_body_length
final class SchemeDescriptorsGenerator: SchemeDescriptorsGenerating {
private struct Constants {
/// Default last upgrade version for generated schemes.
static let defaultLastUpgradeVersion = "1010"
/// Default version for generated schemes.
static let defaultVersion = "1.3"
struct LaunchAction {
var debugger: String
var launcher: String
var askForAppToLaunch: Bool?
var launchAutomaticallySubstyle: String?
static var `default`: LaunchAction {
LaunchAction(debugger: XCScheme.defaultDebugger,
launcher: XCScheme.defaultLauncher,
askForAppToLaunch: nil,
launchAutomaticallySubstyle: nil)
}
static var `extension`: LaunchAction {
LaunchAction(debugger: "",
launcher: "Xcode.IDEFoundation.Launcher.PosixSpawn",
askForAppToLaunch: true,
launchAutomaticallySubstyle: "2")
}
}
}
func generateWorkspaceSchemes(workspace: Workspace,
generatedProjects: [AbsolutePath: GeneratedProject],
graphTraverser: GraphTraversing) throws -> [SchemeDescriptor]
{
let schemes = try workspace.schemes.map { scheme in
try generateScheme(scheme: scheme,
path: workspace.path,
graphTraverser: graphTraverser,
generatedProjects: generatedProjects)
}
return schemes
}
func generateProjectSchemes(project: Project,
generatedProject: GeneratedProject,
graphTraverser: GraphTraversing) throws -> [SchemeDescriptor]
{
try project.schemes.map { scheme in
try generateScheme(scheme: scheme,
path: project.path,
graphTraverser: graphTraverser,
generatedProjects: [project.path: generatedProject])
}
}
/// Wipes shared and user schemes at a workspace or project path. This is needed
/// currently to support the workspace scheme generation case where a workspace that
/// already exists on disk is being regenerated. Wiping the schemes directory prevents
/// older custom schemes from persisting after regeneration.
///
/// - Parameter at: Path to the workspace or project.
func wipeSchemes(at path: AbsolutePath) throws {
let fileHandler = FileHandler.shared
let userPath = schemeDirectory(path: path, shared: false)
let sharedPath = schemeDirectory(path: path, shared: true)
if fileHandler.exists(userPath) { try fileHandler.delete(userPath) }
if fileHandler.exists(sharedPath) { try fileHandler.delete(sharedPath) }
}
/// Generate schemes for a project or workspace.
///
/// - Parameters:
/// - scheme: Project scheme.
/// - xcPath: Path to workspace's .xcworkspace or project's .xcodeproj.
/// - path: Path to workspace or project folder.
/// - graphTraverser: Graph traverser.
/// - generatedProjects: Project paths mapped to generated projects.
private func generateScheme(scheme: Scheme,
path: AbsolutePath,
graphTraverser: GraphTraversing,
generatedProjects: [AbsolutePath: GeneratedProject]) throws -> SchemeDescriptor
{
let generatedBuildAction = try schemeBuildAction(scheme: scheme,
graphTraverser: graphTraverser,
rootPath: path,
generatedProjects: generatedProjects)
let generatedTestAction = try schemeTestAction(scheme: scheme,
graphTraverser: graphTraverser,
rootPath: path,
generatedProjects: generatedProjects)
let generatedLaunchAction = try schemeLaunchAction(scheme: scheme,
graphTraverser: graphTraverser,
rootPath: path,
generatedProjects: generatedProjects)
let generatedProfileAction = try schemeProfileAction(scheme: scheme,
graphTraverser: graphTraverser,
rootPath: path,
generatedProjects: generatedProjects)
let generatedAnalyzeAction = try schemeAnalyzeAction(scheme: scheme,
graphTraverser: graphTraverser,
rootPath: path,
generatedProjects: generatedProjects)
let generatedArchiveAction = try schemeArchiveAction(scheme: scheme,
graphTraverser: graphTraverser,
rootPath: path,
generatedProjects: generatedProjects)
let wasCreatedForAppExtension = isSchemeForAppExtension(scheme: scheme, graphTraverser: graphTraverser)
let xcscheme = XCScheme(name: scheme.name,
lastUpgradeVersion: Constants.defaultLastUpgradeVersion,
version: Constants.defaultVersion,
buildAction: generatedBuildAction,
testAction: generatedTestAction,
launchAction: generatedLaunchAction,
profileAction: generatedProfileAction,
analyzeAction: generatedAnalyzeAction,
archiveAction: generatedArchiveAction,
wasCreatedForAppExtension: wasCreatedForAppExtension)
return SchemeDescriptor(xcScheme: xcscheme, shared: scheme.shared)
}
/// Generates the scheme build action.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - graphTraverser: Graph traverser.
/// - rootPath: Path to the project or workspace.
/// - generatedProjects: Project paths mapped to generated projects.
/// - Returns: Scheme build action.
func schemeBuildAction(scheme: Scheme,
graphTraverser: GraphTraversing,
rootPath: AbsolutePath,
generatedProjects: [AbsolutePath: GeneratedProject]) throws -> XCScheme.BuildAction?
{
guard let buildAction = scheme.buildAction else { return nil }
let buildFor: [XCScheme.BuildAction.Entry.BuildFor] = [
.analyzing, .archiving, .profiling, .running, .testing,
]
var entries: [XCScheme.BuildAction.Entry] = []
var preActions: [XCScheme.ExecutionAction] = []
var postActions: [XCScheme.ExecutionAction] = []
try buildAction.targets.forEach { buildActionTarget in
guard let buildActionGraphTarget = graphTraverser.target(path: buildActionTarget.projectPath, name: buildActionTarget.name) else { return }
guard let buildableReference = try createBuildableReference(graphTarget: buildActionGraphTarget,
graphTraverser: graphTraverser,
rootPath: rootPath,
generatedProjects: generatedProjects) else { return }
entries.append(XCScheme.BuildAction.Entry(buildableReference: buildableReference, buildFor: buildFor))
}
preActions = try buildAction.preActions.map {
try schemeExecutionAction(action: $0, graphTraverser: graphTraverser, generatedProjects: generatedProjects, rootPath: rootPath)
}
postActions = try buildAction.postActions.map {
try schemeExecutionAction(action: $0, graphTraverser: graphTraverser, generatedProjects: generatedProjects, rootPath: rootPath)
}
return XCScheme.BuildAction(buildActionEntries: entries,
preActions: preActions,
postActions: postActions,
parallelizeBuild: true,
buildImplicitDependencies: true)
}
/// Generates the scheme test action.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - graphTraverser: Graph traverser.
/// - rootPath: Root path to either project or workspace.
/// - generatedProjects: Project paths mapped to generated projects.
/// - Returns: Scheme test action.
// swiftlint:disable:next function_body_length
func schemeTestAction(scheme: Scheme,
graphTraverser: GraphTraversing,
rootPath: AbsolutePath,
generatedProjects: [AbsolutePath: GeneratedProject]) throws -> XCScheme.TestAction?
{
guard let testAction = scheme.testAction else { return nil }
var testables: [XCScheme.TestableReference] = []
var preActions: [XCScheme.ExecutionAction] = []
var postActions: [XCScheme.ExecutionAction] = []
let testPlans: [XCScheme.TestPlanReference]? = testAction.testPlans?.map {
XCScheme.TestPlanReference(reference: "container:\($0.path.relative(to: rootPath))",
default: $0.isDefault)
}
try testAction.targets.forEach { testableTarget in
guard let testableGraphTarget = graphTraverser.target(path: testableTarget.target.projectPath, name: testableTarget.target.name) else { return }
guard let reference = try createBuildableReference(graphTarget: testableGraphTarget,
graphTraverser: graphTraverser,
rootPath: rootPath,
generatedProjects: generatedProjects) else { return }
let testable = XCScheme.TestableReference(skipped: testableTarget.isSkipped,
parallelizable: testableTarget.isParallelizable,
randomExecutionOrdering: testableTarget.isRandomExecutionOrdering,
buildableReference: reference)
testables.append(testable)
}
preActions = try testAction.preActions.map { try schemeExecutionAction(action: $0,
graphTraverser: graphTraverser,
generatedProjects: generatedProjects,
rootPath: rootPath) }
postActions = try testAction.postActions.map { try schemeExecutionAction(action: $0,
graphTraverser: graphTraverser,
generatedProjects: generatedProjects,
rootPath: rootPath) }
var args: XCScheme.CommandLineArguments?
var environments: [XCScheme.EnvironmentVariable]?
if let arguments = testAction.arguments {
args = XCScheme.CommandLineArguments(arguments: commandlineArgruments(arguments.launchArguments))
environments = environmentVariables(arguments.environment)
}
let codeCoverageTargets = try testAction.codeCoverageTargets.compactMap { (target: TargetReference) -> XCScheme.BuildableReference? in
guard let graphTarget = graphTraverser.target(path: target.projectPath, name: target.name) else { return nil }
return try testCoverageTargetReferences(graphTarget: graphTarget,
graphTraverser: graphTraverser,
generatedProjects: generatedProjects,
rootPath: rootPath)
}
let onlyGenerateCoverageForSpecifiedTargets = codeCoverageTargets.count > 0 ? true : nil
let disableMainThreadChecker = !testAction.diagnosticsOptions.contains(.mainThreadChecker)
let shouldUseLaunchSchemeArgsEnv: Bool = args == nil && environments == nil
let language = testAction.language
let region = testAction.region
return XCScheme.TestAction(buildConfiguration: testAction.configurationName,
macroExpansion: nil,
testables: testables,
testPlans: testPlans,
preActions: preActions,
postActions: postActions,
shouldUseLaunchSchemeArgsEnv: shouldUseLaunchSchemeArgsEnv,
codeCoverageEnabled: testAction.coverage,
codeCoverageTargets: codeCoverageTargets,
onlyGenerateCoverageForSpecifiedTargets: onlyGenerateCoverageForSpecifiedTargets,
disableMainThreadChecker: disableMainThreadChecker,
commandlineArguments: args,
environmentVariables: environments,
language: language,
region: region)
}
/// Generates the scheme launch action.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - graphTraverser: Graph traverser.
/// - rootPath: Root path to either project or workspace.
/// - generatedProjects: Project paths mapped to generated projects.
/// - Returns: Scheme launch action.
func schemeLaunchAction(scheme: Scheme,
graphTraverser: GraphTraversing,
rootPath: AbsolutePath,
generatedProjects: [AbsolutePath: GeneratedProject]) throws -> XCScheme.LaunchAction?
{
let specifiedExecutableTarget = scheme.runAction?.executable
let defaultTarget = defaultTargetReference(scheme: scheme)
guard let target = specifiedExecutableTarget ?? defaultTarget else { return nil }
var buildableProductRunnable: XCScheme.BuildableProductRunnable?
var macroExpansion: XCScheme.BuildableReference?
var pathRunnable: XCScheme.PathRunnable?
var defaultBuildConfiguration = BuildConfiguration.debug.name
if let filePath = scheme.runAction?.filePath {
pathRunnable = XCScheme.PathRunnable(filePath: filePath.pathString)
} else {
guard let graphTarget = graphTraverser.target(path: target.projectPath, name: target.name) else { return nil }
defaultBuildConfiguration = graphTarget.project.defaultDebugBuildConfigurationName
guard let buildableReference = try createBuildableReference(graphTarget: graphTarget,
graphTraverser: graphTraverser,
rootPath: rootPath,
generatedProjects: generatedProjects) else { return nil }
if graphTarget.target.product.runnable {
buildableProductRunnable = XCScheme.BuildableProductRunnable(buildableReference: buildableReference, runnableDebuggingMode: "0")
} else {
macroExpansion = buildableReference
}
}
var commandlineArguments: XCScheme.CommandLineArguments?
var environments: [XCScheme.EnvironmentVariable]?
if let arguments = scheme.runAction?.arguments {
commandlineArguments = XCScheme.CommandLineArguments(arguments: commandlineArgruments(arguments.launchArguments))
environments = environmentVariables(arguments.environment)
}
let buildConfiguration = scheme.runAction?.configurationName ?? defaultBuildConfiguration
let disableMainThreadChecker = scheme.runAction?.diagnosticsOptions.contains(.mainThreadChecker) == false
let isSchemeForAppExtension = self.isSchemeForAppExtension(scheme: scheme, graphTraverser: graphTraverser)
let launchActionConstants: Constants.LaunchAction = isSchemeForAppExtension == true ? .extension : .default
return XCScheme.LaunchAction(runnable: buildableProductRunnable,
buildConfiguration: buildConfiguration,
macroExpansion: macroExpansion,
selectedDebuggerIdentifier: launchActionConstants.debugger,
selectedLauncherIdentifier: launchActionConstants.launcher,
askForAppToLaunch: launchActionConstants.askForAppToLaunch,
pathRunnable: pathRunnable,
disableMainThreadChecker: disableMainThreadChecker,
commandlineArguments: commandlineArguments,
environmentVariables: environments,
launchAutomaticallySubstyle: launchActionConstants.launchAutomaticallySubstyle)
}
/// Generates the scheme profile action for a given target.
///
/// - Parameters:
/// - scheme: Target manifest.
/// - graphTraverser: Graph traverser.
/// - rootPath: Root path to either project or workspace.
/// - generatedProjects: Project paths mapped to generated projects.
/// - Returns: Scheme profile action.
func schemeProfileAction(scheme: Scheme,
graphTraverser: GraphTraversing,
rootPath: AbsolutePath,
generatedProjects: [AbsolutePath: GeneratedProject]) throws -> XCScheme.ProfileAction?
{
guard var target = defaultTargetReference(scheme: scheme) else { return nil }
var commandlineArguments: XCScheme.CommandLineArguments?
var environments: [XCScheme.EnvironmentVariable]?
if let action = scheme.profileAction, let executable = action.executable {
target = executable
if let arguments = action.arguments {
commandlineArguments = XCScheme.CommandLineArguments(arguments: commandlineArgruments(arguments.launchArguments))
environments = environmentVariables(arguments.environment)
}
} else if let action = scheme.runAction, let executable = action.executable {
target = executable
// arguments are inherited automatically from Launch Action (via `shouldUseLaunchSchemeArgsEnv`)
}
let shouldUseLaunchSchemeArgsEnv: Bool = commandlineArguments == nil && environments == nil
guard let graphTarget = graphTraverser.target(path: target.projectPath, name: target.name) else { return nil }
guard let buildableReference = try createBuildableReference(graphTarget: graphTarget,
graphTraverser: graphTraverser,
rootPath: rootPath,
generatedProjects: generatedProjects) else { return nil }
var buildableProductRunnable: XCScheme.BuildableProductRunnable?
var macroExpansion: XCScheme.BuildableReference?
if graphTarget.target.product.runnable {
buildableProductRunnable = XCScheme.BuildableProductRunnable(buildableReference: buildableReference, runnableDebuggingMode: "0")
} else {
macroExpansion = buildableReference
}
let buildConfiguration = scheme.profileAction?.configurationName ?? defaultReleaseBuildConfigurationName(in: graphTarget.project)
return XCScheme.ProfileAction(buildableProductRunnable: buildableProductRunnable,
buildConfiguration: buildConfiguration,
macroExpansion: macroExpansion,
shouldUseLaunchSchemeArgsEnv: shouldUseLaunchSchemeArgsEnv,
commandlineArguments: commandlineArguments,
environmentVariables: environments)
}
/// Returns the scheme analyze action.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - graphTraverser: Graph traverser.
/// - rootPath: Root path to either project or workspace.
/// - generatedProjects: Project paths mapped to generated projects.
/// - Returns: Scheme analyze action.
func schemeAnalyzeAction(scheme: Scheme,
graphTraverser: GraphTraversing,
rootPath _: AbsolutePath,
generatedProjects _: [AbsolutePath: GeneratedProject]) throws -> XCScheme.AnalyzeAction?
{
guard let target = defaultTargetReference(scheme: scheme),
let graphTarget = graphTraverser.target(path: target.projectPath, name: target.name) else { return nil }
let buildConfiguration = scheme.analyzeAction?.configurationName ?? graphTarget.project.defaultDebugBuildConfigurationName
return XCScheme.AnalyzeAction(buildConfiguration: buildConfiguration)
}
/// Generates the scheme archive action.
///
/// - Parameters:
/// - scheme: Scheme manifest.
/// - graphTraverser: Graph traverser.
/// - rootPath: Root path to either project or workspace.
/// - generatedProjects: Project paths mapped to generated projects.
/// - Returns: Scheme archive action.
func schemeArchiveAction(scheme: Scheme,
graphTraverser: GraphTraversing,
rootPath: AbsolutePath,
generatedProjects: [AbsolutePath: GeneratedProject]) throws -> XCScheme.ArchiveAction?
{
guard let target = defaultTargetReference(scheme: scheme),
let graphTarget = graphTraverser.target(path: target.projectPath, name: target.name) else { return nil }
guard let archiveAction = scheme.archiveAction else {
return defaultSchemeArchiveAction(for: graphTarget.project)
}
let preActions = try archiveAction.preActions.map {
try schemeExecutionAction(action: $0, graphTraverser: graphTraverser, generatedProjects: generatedProjects, rootPath: rootPath)
}
let postActions = try archiveAction.postActions.map {
try schemeExecutionAction(action: $0, graphTraverser: graphTraverser, generatedProjects: generatedProjects, rootPath: rootPath)
}
return XCScheme.ArchiveAction(buildConfiguration: archiveAction.configurationName,
revealArchiveInOrganizer: archiveAction.revealArchiveInOrganizer,
customArchiveName: archiveAction.customArchiveName,
preActions: preActions,
postActions: postActions)
}
func schemeExecutionAction(action: ExecutionAction,
graphTraverser: GraphTraversing,
generatedProjects: [AbsolutePath: GeneratedProject],
rootPath _: AbsolutePath) throws -> XCScheme.ExecutionAction
{
guard let targetReference = action.target,
let graphTarget = graphTraverser.target(path: targetReference.projectPath, name: targetReference.name),
let generatedProject = generatedProjects[targetReference.projectPath]
else {
return schemeExecutionAction(action: action)
}
return schemeExecutionAction(action: action,
target: graphTarget.target,
generatedProject: generatedProject)
}
private func schemeExecutionAction(action: ExecutionAction) -> XCScheme.ExecutionAction {
XCScheme.ExecutionAction(scriptText: action.scriptText,
title: action.title,
environmentBuildable: nil)
}
/// Returns the scheme pre/post actions.
///
/// - Parameters:
/// - action: pre/post action manifest.
/// - target: Project manifest.
/// - generatedProject: Generated Xcode project.
/// - Returns: Scheme actions.
private func schemeExecutionAction(action: ExecutionAction,
target: Target,
generatedProject: GeneratedProject) -> XCScheme.ExecutionAction
{
/// Return Buildable Reference for Scheme Action
func schemeBuildableReference(target: Target, generatedProject: GeneratedProject) -> XCScheme.BuildableReference? {
guard let pbxTarget = generatedProject.targets[target.name] else { return nil }
return targetBuildableReference(target: target,
pbxTarget: pbxTarget,
projectPath: generatedProject.name)
}
let schemeAction = XCScheme.ExecutionAction(scriptText: action.scriptText,
title: action.title,
environmentBuildable: nil)
schemeAction.environmentBuildable = schemeBuildableReference(target: target,
generatedProject: generatedProject)
return schemeAction
}
// MARK: - Helpers
private func resolveRelativeProjectPath(graphTarget: ValueGraphTarget,
generatedProject: GeneratedProject,
rootPath: AbsolutePath) -> RelativePath
{
let xcodeProjectPath = graphTarget.project.path.appending(component: generatedProject.name)
return xcodeProjectPath.relative(to: rootPath)
}
/// Creates a target buildable refernece for a target
///
/// - Parameters:
/// - graphTarget: The graph target.
/// - graph: Tuist graph.
/// - rootPath: Path to the project or workspace.
/// - generatedProjects: Project paths mapped to generated projects.
private func createBuildableReference(graphTarget: ValueGraphTarget,
graphTraverser: GraphTraversing,
rootPath: AbsolutePath,
generatedProjects: [AbsolutePath: GeneratedProject]) throws -> XCScheme.BuildableReference?
{
let projectPath = graphTarget.project.path
guard let target = graphTraverser.target(path: graphTarget.project.path, name: graphTarget.target.name) else { return nil }
guard let generatedProject = generatedProjects[projectPath] else { return nil }
guard let pbxTarget = generatedProject.targets[graphTarget.target.name] else { return nil }
let relativeXcodeProjectPath = resolveRelativeProjectPath(graphTarget: graphTarget,
generatedProject: generatedProject,
rootPath: rootPath)
return targetBuildableReference(target: target.target,
pbxTarget: pbxTarget,
projectPath: relativeXcodeProjectPath.pathString)
}
/// Generates the array of BuildableReference for targets that the
/// coverage report should be generated for them.
///
/// - Parameters:
/// - target: test actions.
/// - graph: tuist graph.
/// - generatedProjects: Generated Xcode projects.
/// - rootPath: Root path to workspace or project.
/// - Returns: Array of buildable references.
private func testCoverageTargetReferences(graphTarget: ValueGraphTarget,
graphTraverser: GraphTraversing,
generatedProjects: [AbsolutePath: GeneratedProject],
rootPath: AbsolutePath) throws -> XCScheme.BuildableReference?
{
try createBuildableReference(graphTarget: graphTarget,
graphTraverser: graphTraverser,
rootPath: rootPath,
generatedProjects: generatedProjects)
}
/// Creates the directory where the schemes are stored inside the project.
/// If the directory exists it does not re-create it.
///
/// - Parameters:
/// - path: Path to the Xcode workspace or project.
/// - shared: Scheme should be shared or not
/// - Returns: Path to the schemes directory.
/// - Throws: A FatalError if the creation of the directory fails.
private func createSchemesDirectory(path: AbsolutePath, shared: Bool = true) throws -> AbsolutePath {
let schemePath = schemeDirectory(path: path, shared: shared)
if !FileHandler.shared.exists(schemePath) {
try FileHandler.shared.createFolder(schemePath)
}
return schemePath
}
private func schemeDirectory(path: AbsolutePath, shared: Bool = true) -> AbsolutePath {
if shared {
return path.appending(RelativePath("xcshareddata/xcschemes"))
} else {
let username = NSUserName()
return path.appending(RelativePath("xcuserdata/\(username).xcuserdatad/xcschemes"))
}
}
/// Returns the scheme commandline argument passed on launch
///
/// - Parameters:
/// - environments: commandline argument keys.
/// - Returns: XCScheme.CommandLineArguments.CommandLineArgument.
private func commandlineArgruments(_ arguments: [LaunchArgument]) -> [XCScheme.CommandLineArguments.CommandLineArgument] {
arguments.map {
XCScheme.CommandLineArguments.CommandLineArgument(name: $0.name, enabled: $0.isEnabled)
}
}
/// Returns the scheme environment variables
///
/// - Parameters:
/// - environments: environment variables
/// - Returns: XCScheme.EnvironmentVariable.
private func environmentVariables(_ environments: [String: String]) -> [XCScheme.EnvironmentVariable] {
environments.map { key, value in
XCScheme.EnvironmentVariable(variable: key, value: value, enabled: true)
}.sorted { $0.variable < $1.variable }
}
/// Returns the scheme buildable reference for a given target.
///
/// - Parameters:
/// - target: Target manifest.
/// - pbxTarget: Xcode native target.
/// - projectPath: Project name with the .xcodeproj extension.
/// - Returns: Buildable reference.
private func targetBuildableReference(target: Target,
pbxTarget: PBXNativeTarget,
projectPath: String) -> XCScheme.BuildableReference
{
XCScheme.BuildableReference(referencedContainer: "container:\(projectPath)",
blueprint: pbxTarget,
buildableName: target.productNameWithExtension,
blueprintName: target.name,
buildableIdentifier: "primary")
}
/// Returns the scheme archive action
///
/// - Returns: Scheme archive action.
func defaultSchemeArchiveAction(for project: Project) -> XCScheme.ArchiveAction {
let buildConfiguration = defaultReleaseBuildConfigurationName(in: project)
return XCScheme.ArchiveAction(buildConfiguration: buildConfiguration,
revealArchiveInOrganizer: true)
}
private func defaultReleaseBuildConfigurationName(in project: Project) -> String {
let releaseConfiguration = project.settings.defaultReleaseBuildConfiguration()
let buildConfiguration = releaseConfiguration ?? project.settings.configurations.keys.first
return buildConfiguration?.name ?? BuildConfiguration.release.name
}
private func defaultTargetReference(scheme: Scheme) -> TargetReference? {
scheme.buildAction?.targets.first
}
private func isSchemeForAppExtension(scheme: Scheme, graphTraverser: GraphTraversing) -> Bool? {
guard let defaultTarget = defaultTargetReference(scheme: scheme),
let graphTarget = graphTraverser.target(path: defaultTarget.projectPath, name: defaultTarget.name)
else {
return nil
}
switch graphTarget.target.product {
case .appExtension, .messagesExtension:
return true
default:
return nil
}
}
}
| 53.081724 | 156 | 0.582158 |
5d9a66353d53af2c68037c238f410f72c38f5bcc | 5,165 | import PromiseKit
import XCTest
class Test224: XCTestCase {
// 2.2.4: `onFulfilled` or `onRejected` must not be called until
// the execution context stack contains only platform code
func test2241() {
// `then` returns before the promise becomes fulfilled or rejected
suiteFulfilled(1) { (promise, exes, dummy)->() in
var thenHasReturned = false
promise.then { _->() in
XCTAssert(thenHasReturned)
exes[0].fulfill()
}
thenHasReturned = true
}
suiteRejected(1) { (promise, exes, memo)->() in
var catchHasReturned = false
promise.catch { _->() in
XCTAssert(catchHasReturned)
exes[0].fulfill()
}
catchHasReturned = true
}
}
// Clean-stack execution ordering tests (fulfillment case)
func test2242_1() {
// when `onFulfilled` is added immediately before the promise is fulfilled
let (promise, fulfiller, _) = Promise<Int>.defer()
var onFulfilledCalled = false
fulfiller(dummy)
promise.then{ _->() in
onFulfilledCalled = true
}
XCTAssertFalse(onFulfilledCalled)
}
func test2242_2() {
// when one `onFulfilled` is added inside another `onFulfilled`
let promise = Promise(dummy)
var firstOnFulfilledFinished = false
let ex = expectationWithDescription("")
promise.then { _->() in
promise.then { _->() in
XCTAssert(firstOnFulfilledFinished)
ex.fulfill()
}
firstOnFulfilledFinished = true
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test2242_3() {
// when `onFulfilled` is added inside an `onRejected`
let err = NSError(domain: "a", code: 1, userInfo: nil)
let resolved = Promise(dummy)
let rejected = Promise<Int>(dammy)
var firstOnRejectedFinished = false
let ex = expectationWithDescription("")
rejected.catch { _->() in
resolved.then { _->() in
XCTAssert(firstOnRejectedFinished)
ex.fulfill()
}
firstOnRejectedFinished = true
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test2242_4() {
// when the promise is fulfilled asynchronously
let (promise, fulfiller, _) = Promise<Int>.defer()
var firstStackFinished = false
let ex = expectationWithDescription("")
later {
fulfiller(dummy)
firstStackFinished = true
}
promise.then { _->() in
XCTAssert(firstStackFinished)
ex.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
// Clean-stack execution ordering tests (rejection case)
func test2243() {
// when `onRejected` is added immediately before the promise is rejected
let (promise, _, rejecter) = Promise<Int>.defer()
var onRejectedCalled = false
promise.catch{ _->() in
onRejectedCalled = true
}
rejecter(dammy)
XCTAssertFalse(onRejectedCalled)
}
func test2244() {
// when `onRejected` is added immediately after the promise is rejected
let (promise, _, rejecter) = Promise<Int>.defer()
var onRejectedCalled = false
rejecter(dammy)
promise.catch{ _->() in
onRejectedCalled = true
}
XCTAssertFalse(onRejectedCalled)
}
func test2245() {
// when `onRejected` is added inside an `onFulfilled`
let resolved = Promise(dummy)
let rejected = Promise<Int>(dammy)
var firstOnFulfilledFinished = false
let ex = expectationWithDescription("")
resolved.then{ _->() in
rejected.catch{ _->() in
XCTAssert(firstOnFulfilledFinished)
ex.fulfill()
}
firstOnFulfilledFinished = true
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test2246() {
// when one `onRejected` is added inside another `onRejected`
let promise = Promise<Int>(dammy)
var firstOnRejectedFinished = false
let ex = expectationWithDescription("")
promise.catch{ _->() in
promise.catch{ _->() in
XCTAssertTrue(firstOnRejectedFinished)
ex.fulfill()
}
firstOnRejectedFinished = true
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test2247() {
// when the promise is rejected asynchronously
let (promise, _, rejecter) = Promise<Int>.defer()
var firstStackFinished = false
let ex = expectationWithDescription("")
later {
rejecter(dammy)
firstStackFinished = true
}
promise.catch{ _->() in
XCTAssert(firstStackFinished)
ex.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
}
| 29.683908 | 82 | 0.571346 |
e21a410b8f2fcecbc7b902b0083728533d31a4b6 | 1,141 | //
// IntTests.swift
// JSONHelper
//
// Created by Baris Sencan on 6/29/15.
// Copyright (c) 2015 Baris Sencan. All rights reserved.
//
import Foundation
import XCTest
import JSONHelper
class IntTests: XCTestCase {
let testInt = 1
let testFloat = Float(1)
let testDouble = Double(1)
let testNSNumber = NSNumber(value: 1 as Int)
let testNSDecimalNumber = NSDecimalNumber(value: 1 as Int)
let testString = "1"
var value = 0
override func setUp() {
value = 0
}
func testIntConversion() {
value <-- (testInt as Any)
XCTAssertEqual(value, testInt)
}
func testFloatConversion() {
value <-- (testFloat as Any)
XCTAssertEqual(value, testInt)
}
func testDoubleConversion() {
value <-- (testDouble as Any)
XCTAssertEqual(value, testInt)
}
func testNSNumberConversion() {
value <-- (testNSNumber as Any)
XCTAssertEqual(value, testInt)
}
func testNSDecimalNumberConversion() {
value <-- (testNSDecimalNumber as Any)
XCTAssertEqual(value, testInt)
}
func testStringConversion() {
value <-- (testString as Any)
XCTAssertEqual(value, testInt)
}
}
| 20.017544 | 60 | 0.674847 |
6101cacc1a65f8cd5c2b56cb9824ae6a3e846c7a | 72 | struct EmptyParameters: Encodable {}
struct EmptyResponse: Decodable {}
| 24 | 36 | 0.805556 |
2faeb1ab988462944591293a5a1d9ba1eb8a6cbb | 2,299 | import Foundation
import Capacitor
import FirebaseAuth
class TwitterProviderHandler: NSObject, ProviderHandler {
var provider: OAuthProvider? = nil
var plugin: CapacitorFirebaseAuth? = nil
func initialize(plugin: CapacitorFirebaseAuth) {
print("Initializing Twitter Provider Handler")
self.plugin = plugin
self.provider = OAuthProvider(providerID: "twitter.com")
self.provider?.customParameters = [
"lang": self.plugin?.languageCode ?? "en"
]
}
func signIn(call: CAPPluginCall) {
DispatchQueue.main.async {
self.provider?.getCredentialWith(nil) { credential, error in
if error != nil {
print(error?.localizedDescription ?? "A failure occurs in Twitter sign in.")
self.plugin!.handleError(message: "A failure occurs in Twitter sign in.")
return
}
if credential != nil {
Auth.auth().signIn(with: credential!) { (authResult, error) in
if error != nil {
print(error?.localizedDescription ?? "A failure occurs in Twitter sign in.")
self.plugin!.handleError(message: "A failure occurs in Twitter sign in.")
return
}
self.plugin?.handleAuthCredentials(credential: (authResult?.credential!)!);
}
}
}
}
}
func isAuthenticated() -> Bool {
return false
}
func fillResult(credential: AuthCredential?, data: PluginResultData) -> PluginResultData {
var jsResult: PluginResultData = [:]
data.map { (key, value) in
jsResult[key] = value
}
let twitterCredential = credential as! OAuthCredential
print(twitterCredential.accessToken)
print(twitterCredential.idToken)
print(twitterCredential.secret)
jsResult["idToken"] = twitterCredential.accessToken
jsResult["secret"] = twitterCredential.secret
return jsResult
}
func signOut() {
// there is nothing to do here
print("TwitterProviderHandler.signOut called.");
}
}
| 33.318841 | 98 | 0.570248 |
560333a78bdcf72d4f264539d293bb5593de1490 | 512 | //
// GTFSCalendarDates.swift
// sptransAPI
//
// Created by resource on 8/2/16.
// Copyright © 2016 bienemann. All rights reserved.
//
import Foundation
import RealmSwift
class GTFSCalendarDates: GTFSBaseModel {
@objc dynamic var service_id : String = ""
@objc dynamic var date : String = ""
@objc dynamic var exception_type : Int = 0
// Specify properties to ignore (Realm won't persist these)
// override static func ignoredProperties() -> [String] {
// return []
// }
}
| 21.333333 | 59 | 0.664063 |
f730a11e6cfb848c9e8fe6b57de181e4865a6c1c | 2,024 | import Foundation
import XCTest
@testable import HaishinKit
final class AMF0SerializerTests: XCTestCase {
static let connectionChunk: ASObject = [
"tcUrl": "rtmp://localhost:1935/live",
"flashVer": "FMLE/3.0 (compatible; FMSc/1.0)",
"swfUrl": nil,
"app": "live",
"fpad": false,
"audioCodecs": Double(1024),
"videoCodecs": Double(128),
"videoFunction": Double(1),
"capabilities": Double(239),
"pageUrl": nil,
"objectEncoding": Double(0)
]
func testConnectionChunk() {
var amf: AMFSerializer = AMF0Serializer()
amf.serialize(AMF0SerializerTests.connectionChunk)
amf.position = 0
let result: ASObject = try! amf.deserialize()
for key in AMF0SerializerTests.connectionChunk.keys {
let value: Any? = result[key]! as Any?
switch key {
case "tcUrl":
XCTAssertEqual(value as? String, "rtmp://localhost:1935/live")
case "flashVer":
XCTAssertEqual(value as? String, "FMLE/3.0 (compatible; FMSc/1.0)")
case "swfUrl":
//XCTAssertNil(value!)
break
case "app":
XCTAssertEqual(value as? String, "live")
case "fpad":
XCTAssertEqual(value as? Bool, false)
case "audioCodecs":
XCTAssertEqual(value as? Double, Double(1024))
case "videoCodecs":
XCTAssertEqual(value as? Double, Double(128))
case "videoFunction":
XCTAssertEqual(value as? Double, Double(1))
case "capabilities":
XCTAssertEqual(value as? Double, Double(239))
case "pageUrl":
//XCTAssertNil(value!)
break
case "objectEncoding":
XCTAssertEqual(value as? Double, Double(0))
default:
XCTFail(key.debugDescription)
}
}
}
}
| 33.733333 | 83 | 0.541008 |
754d1ef06bd819bbc4f466e27e164c6bf6862ee6 | 962 | //
// p5AppTests.swift
// p5AppTests
//
// Created by Abel Fernandez on 20/05/2017.
// Copyright © 2017 Daferpi. All rights reserved.
//
import XCTest
@testable import p5App
class p5AppTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26 | 111 | 0.629938 |
5dae7436e332cf10dadf7e795903728042182e16 | 1,056 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "StompClient",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "StompClient",
targets: ["StompClient"]),
],
dependencies: [
.package(url: "https://github.com/daltoniam/Starscream", .upToNextMinor(from: "3.1.0")),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "StompClient",
dependencies: ["Starscream"],
path: "Sources"),
.testTarget(
name: "StompClientTests",
dependencies: ["StompClient"],
path: "Tests"),
]
)
| 35.2 | 117 | 0.616477 |
bfdeb4814691a8b48d009c280778667a585f3e12 | 3,057 | //
// ViewController.swift
// viewControllerTransition_Prac
//
// Created by Daisy on 02/04/2019.
// Copyright © 2019 고정아. All rights reserved.
//
/***********************************************************************************************
// [ 과제 ]
// 1.
// 위와 같이 task1 이라는 변수가 있을 때
/ task1 + task1 의 결과가 제대로 출력되도록 할 것
func addTwoValues(a: Int, b: Int) -> Int {
return a + b
}
let task1: Any = addTwoValues(a: 2, b: 3)
if let result = task1 as? Int{
result + result
}
***********************************************************************************************/
import UIKit
class ViewController: UIViewController {
var dogCount = 0
var catCount = 0
var flogCount = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func unwindToFirstVC(_ unwindSegue: UIStoryboardSegue) {
guard let vc = unwindSegue.source as? SecondViewController else { return }
dogCount += vc.count
catCount += vc.count
flogCount += vc.count
print(dogCount,catCount,flogCount)
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "개" {
return dogCount < 3
} else if identifier == "개구리" {
return flogCount < 4
} else {
return catCount < 5
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let second = segue.destination as! SecondViewController
if let id = segue.identifier {
if id == "개" {
second.image = UIImage(named: "개")!
dogCount += 1
} else if id == "개구리" {
second.image = UIImage(named: "개구리")!
flogCount += 1
} else if id == "고양이" {
second.image = UIImage(named: "고양이")!
catCount += 1
}
}
}
}
/********************************************************************************************
2. 스토리보드 이용할 것
- FirstVC 에 개, 고양이, 새 라는 이름의 UIButton 3개 생성
- SecondVC 에 UIImageView 하나와 Dismiss 를 위한 버튼 하나 생성
- FirstVC에 있는 버튼 3개 중 하나를 누르면 그 타이틀에 맞는 이미지를 SecondVC의 ImageView 에 넣기
(이미지는 구글링 등을 통해 활용)
- 각 버튼별로 전환 횟수를 세서 개는 8회, 고양이는 10회, 새는 15회가 넘어서면 화면이 전환되지 않도록 막기
- 그리고 SecondVC 에 추가로 UIButton 을 하나 더 생성하여 그 버튼을 누를 때마다 전환 횟수를 계산하는 값이 개와 고양이, 새 모두에 대해 1회씩 추가되도록 구현
3. 클래스 매니저 과제
- 첫번째 뷰에 레이블과 버튼을 생성하고 버튼을 통해 두번쨰 뷰로 이동.
- 두번째 뷰에는 segmentedController 를 생성하고 선택한값을 첫번째 뷰의 레이블에 띄우세요.
[ 도전 과제 ]
1.
let task2: Any = addTwoValues
위와 같이 task2 라는 변수가 있을 때
task2 + task2 의 결과가 제대로 출력되도록 할 것 (addTwoValues의 각 파라미터에는 2와 3 입력)
2.
class Car {}
let values: [Any] = [0, 0.0, (2.0, Double.pi), Car(), { (str: String) -> Int in str.count }]
위 values 변수의 각 값을 switch 문과 타입캐스팅을 이용해 출력하기
*******************************************************************************************/
| 24.853659 | 100 | 0.503435 |
f7b7ecb7764f4e83c6fb65e3cc8d7333ca781677 | 921 | //
// NewFeatureXcodeTests.swift
// NewFeatureXcodeTests
//
// Created by WENBO on 2021/11/18.
//
import XCTest
@testable import NewFeatureXcode
class NewFeatureXcodeTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.088235 | 111 | 0.673181 |
38104f24551679051546957a89e70c83784af3a0 | 9,320 | // RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify -enable-ownership-stripping-after-serialization
//
// REQUIRES: PTRSIZE=64
//
// This file tests diagnostics for arithmetic and bitwise operations on `Int`
// and `UInt` types for 64 bit architectures.
//
// FIXME: This test should be merged back into
// diagnostic_constant_propagation.swift when we have fixed:
// <rdar://problem/19434979> -verify does not respect #if
//
// FIXME: <rdar://problem/29937936> False negatives when using integer initializers
//
// FIXME: <rdar://problem/39193272> A false negative that happens only in REPL
import StdlibUnittest
func testArithmeticOverflow_Int_64bit() {
do {
// Literals.
var _: Int = 0x7fff_ffff_ffff_ffff // OK
var _: Int = 0x8000_0000_0000_0000 // expected-error {{integer literal '9223372036854775808' overflows when stored into 'Int'}}
var _: Int = -0x8000_0000_0000_0000 // OK
var _: Int = -0x8000_0000_0000_0001 // expected-error {{integer literal '-9223372036854775809' overflows when stored into 'Int'}}
}
do {
// Negation.
var _: Int = -(-0x7fff_ffff_ffff_ffff) // OK
var _: Int = -(-0x8000_0000_0000_0000) // expected-error {{arithmetic operation '0 - -9223372036854775808' (on signed 64-bit integer type) results in an overflow}}
// FIXME: Missing diagnostic in REPL:
// <rdar://problem/39193272> Overflow in arithmetic negation is not detected
// at compile time when running in REPL
}
do {
// Addition.
var _: Int = 0x7fff_ffff_ffff_fffe + 1 // OK
var _: Int = 0x7fff_ffff_ffff_fffe + 2 // expected-error {{arithmetic operation '9223372036854775806 + 2' (on type 'Int') results in an overflow}}
var _: Int = -0x7fff_ffff_ffff_ffff + (-1) // OK
var _: Int = -0x7fff_ffff_ffff_ffff + (-2) // expected-error {{arithmetic operation '-9223372036854775807 + -2' (on type 'Int') results in an overflow}}
}
do {
// Subtraction.
var _: Int = 0x7fff_ffff_ffff_fffe - (-1) // OK
var _: Int = 0x7fff_ffff_ffff_fffe - (-2) // expected-error {{arithmetic operation '9223372036854775806 - -2' (on type 'Int') results in an overflow}}
var _: Int = -0x7fff_ffff_ffff_ffff - 1 // OK
var _: Int = -0x7fff_ffff_ffff_ffff - 2 // expected-error {{arithmetic operation '-9223372036854775807 - 2' (on type 'Int') results in an overflow}}
}
do {
// Multiplication.
var _: Int = 0x7fff_ffff_ffff_fffe * 1 // OK
var _: Int = 0x7fff_ffff_ffff_fffe * 2 // expected-error {{arithmetic operation '9223372036854775806 * 2' (on type 'Int') results in an overflow}}
var _: Int = -0x7fff_ffff_ffff_ffff * 1 // OK
var _: Int = -0x7fff_ffff_ffff_ffff * 2 // expected-error {{arithmetic operation '-9223372036854775807 * 2' (on type 'Int') results in an overflow}}
}
do {
// Division.
var _: Int = 0x7fff_ffff_ffff_fffe / 2 // OK
var _: Int = 0x7fff_ffff_ffff_fffe / 0 // expected-error {{division by zero}}
var _: Int = -0x7fff_ffff_ffff_ffff / 2 // OK
var _: Int = -0x7fff_ffff_ffff_ffff / 0 // expected-error {{division by zero}}
var _: Int = -0x8000_0000_0000_0000 / -1 // expected-error {{division '-9223372036854775808 / -1' results in an overflow}}
}
do {
// Remainder.
var _: Int = 0x7fff_ffff_ffff_fffe % 2 // OK
var _: Int = 0x7fff_ffff_ffff_fffe % 0 // expected-error {{division by zero}}
var _: Int = -0x7fff_ffff_ffff_ffff % 2 // OK
var _: Int = -0x7fff_ffff_ffff_ffff % 0 // expected-error {{division by zero}}
var _: Int = -0x8000_0000_0000_0000 % -1 // expected-error {{division '-9223372036854775808 % -1' results in an overflow}}
}
do {
// Right shift.
// Due to "smart shift" introduction, there can be no overflows errors
// during shift operations
var _: Int = 0 >> 0
var _: Int = 0 >> 1
var _: Int = 0 >> (-1)
var _: Int = 123 >> 0
var _: Int = 123 >> 1
var _: Int = 123 >> (-1)
var _: Int = (-1) >> 0
var _: Int = (-1) >> 1
var _: Int = 0x7fff_ffff_ffff_ffff >> 63
var _ :Int = 0x7fff_ffff_ffff_ffff >> 64
var _ :Int = 0x7fff_ffff_ffff_ffff >> 65
}
do {
// Left shift.
// Due to "smart shift" introduction, there can be no overflows errors
// during shift operations
var _: Int = 0 << 0
var _: Int = 0 << 1
var _: Int = 0 << (-1)
var _: Int = 123 << 0
var _: Int = 123 << 1
var _: Int = 123 << (-1)
var _: Int = (-1) << 0
var _: Int = (-1) << 1
var _: Int = 0x7fff_ffff_ffff_ffff << 63
var _ :Int = 0x7fff_ffff_ffff_ffff << 64
var _ :Int = 0x7fff_ffff_ffff_ffff << 65
}
do {
var _ : Int = ~0
var _ : Int = (0x7fff_ffff_ffff_fff) | (0x4000_0000_0000_0000 << 1)
var _ : Int = (0x7fff_ffff_ffff_ffff) | 0x8000_0000_0000_0000 // expected-error {{integer literal '9223372036854775808' overflows when stored into 'Int'}}
}
}
func testArithmeticOverflow_UInt_64bit() {
do {
// Literals.
var _: UInt = 0x7fff_ffff_ffff_ffff // OK
var _: UInt = 0x8000_0000_0000_0000
var _: UInt = 0xffff_ffff_ffff_ffff
var _: UInt = -1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = -0xffff_ffff_ffff_ffff // expected-error {{negative integer '-18446744073709551615' overflows when stored into unsigned type 'UInt'}}
}
do {
// Addition.
var _: UInt = 0 + 0 // OK
var _: UInt = 0xffff_ffff_ffff_ffff + 0 // OK
var _: UInt = 0xffff_ffff_ffff_ffff + 1 // expected-error {{arithmetic operation '18446744073709551615 + 1' (on type 'UInt') results in an overflow}}
var _: UInt = 0xffff_ffff_ffff_fffe + 1 // OK
var _: UInt = 0xffff_ffff_ffff_fffe + 2 // expected-error {{arithmetic operation '18446744073709551614 + 2' (on type 'UInt') results in an overflow}}
}
do {
// Subtraction.
var _: UInt = 0xffff_ffff_ffff_fffe - 1 // OK
var _: UInt = 0xffff_ffff_ffff_fffe - 0xffff_ffff_ffff_ffff // expected-error {{arithmetic operation '18446744073709551614 - 18446744073709551615' (on type 'UInt') results in an overflow}}
var _: UInt = 0 - 0 // OK
var _: UInt = 0 - 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt') results in an overflow}}
}
do {
// Multiplication.
var _: UInt = 0xffff_ffff_ffff_ffff * 0 // OK
var _: UInt = 0xffff_ffff_ffff_ffff * 1 // OK
var _: UInt = 0xffff_ffff_ffff_ffff * 2 // expected-error {{arithmetic operation '18446744073709551615 * 2' (on type 'UInt') results in an overflow}}
var _: UInt = 0xffff_ffff_ffff_ffff * 0xffff_ffff_ffff_ffff // expected-error {{arithmetic operation '18446744073709551615 * 18446744073709551615' (on type 'UInt') results in an overflow}}
var _: UInt = 0x7fff_ffff_ffff_fffe * 0 // OK
var _: UInt = 0x7fff_ffff_ffff_fffe * 1 // OK
var _: UInt = 0x7fff_ffff_ffff_fffe * 2 // OK
var _: UInt = 0x7fff_ffff_ffff_fffe * 3 // expected-error {{arithmetic operation '9223372036854775806 * 3' (on type 'UInt') results in an overflow}}
}
do {
// Division.
var _: UInt = 0x7fff_ffff_ffff_fffe / 2 // OK
var _: UInt = 0x7fff_ffff_ffff_fffe / 0 // expected-error {{division by zero}}
var _: UInt = 0xffff_ffff_ffff_ffff / 2 // OK
var _: UInt = 0xffff_ffff_ffff_ffff / 0 // expected-error {{division by zero}}
}
do {
// Remainder.
var _: UInt = 0x7fff_ffff_ffff_fffe % 2 // OK
var _: UInt = 0x7fff_ffff_ffff_fffe % 0 // expected-error {{division by zero}}
var _: UInt = 0xffff_ffff_ffff_ffff % 2 // OK
var _: UInt = 0xffff_ffff_ffff_ffff % 0 // expected-error {{division by zero}}
}
do {
// Shift operations don't result in overflow errors but note that
// one cannot use negative values while initializing of an unsigned value
var _: UInt = 0 >> 0
var _: UInt = 0 >> 1
var _: UInt = 123 >> 0
var _: UInt = 123 >> 1
var _: UInt = (-1) >> 0 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = (-1) >> 1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = 0x7fff_ffff_ffff_ffff >> 63
var _: UInt = 0x7fff_ffff_ffff_ffff >> 64
var _: UInt = 0x7fff_ffff_ffff_ffff >> 65
}
do {
// Shift operations don't result in overflow errors but note that
// one cannot use negative values while initializing of an unsigned value
var _: UInt = 0 << 0
var _: UInt = 0 << 1
var _: UInt = 123 << 0
var _: UInt = 123 << 1
var _: UInt = (-1) << 0 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = (-1) << 1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = 0x7fff_ffff_ffff_ffff << 63
var _: UInt = 0x7fff_ffff_ffff_ffff << 64
var _: UInt = 0x7fff_ffff_ffff_ffff << 65
}
do {
// bitwise operations. No overflows can happen during these operations
var _ : UInt = ~0
var _ : UInt = (0x7fff_ffff_ffff_ffff) | (0x4000_0000_0000_0000 << 1)
var _ : UInt = (0x7fff_ffff) | 0x8000_0000_0000_0000
}
}
func testIntToFloatConversion() {
// No warnings are emitted for conversion through explicit constructor calls.
_blackHole(Double(9_007_199_254_740_993))
}
| 38.353909 | 192 | 0.658047 |
760f1d7a3b28947113055e70ab47482d3bd54f45 | 3,698 | import Foundation
class RefTokenView: NSView
{
var text: String = ""
var type: RefType = .unknown
override var intrinsicContentSize: NSSize
{
let size = (text as NSString).size(withAttributes:
[.font: NSFont.refLabelFont])
return NSSize(width: size.width + 12, height: 17)
}
override func contentHuggingPriority(
for orientation: NSLayoutConstraint.Orientation)
-> NSLayoutConstraint.Priority
{
return .required
}
override func contentCompressionResistancePriority(
for orientation: NSLayoutConstraint.Orientation)
-> NSLayoutConstraint.Priority
{
return .required
}
override func draw(_ dirtyRect: NSRect)
{
let path = self.makePath()
let gradient = type.gradient
let transform = NSAffineTransform()
gradient.draw(in: path, angle: 270)
NSGraphicsContext.saveGraphicsState()
path.addClip()
transform.translateX(by: 0, yBy: -1)
transform.concat()
NSColor.refTokenStroke(.shine).set()
path.stroke()
NSGraphicsContext.restoreGraphicsState()
let active = type == .activeBranch
let fgColor: NSColor = .refTokenText(active ? .active : .normal)
let shadow = NSShadow()
let paragraphStyle = NSParagraphStyle.default.mutableCopy()
as! NSMutableParagraphStyle
shadow.shadowBlurRadius = 1.0
shadow.shadowOffset = NSSize(width: 0, height: -1)
shadow.shadowColor = .refTokenText(active ? .activeEmboss : .normalEmboss)
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byTruncatingMiddle
let attributes: [NSAttributedString.Key: Any] = [
.font: NSFont.refLabelFont,
.paragraphStyle: paragraphStyle,
.foregroundColor: fgColor,
.shadow: shadow]
let attrText = NSMutableAttributedString(string: text,
attributes: attributes)
if let slashIndex = text.lastIndex(of: "/") {
let pathRange = NSRange(text.startIndex...slashIndex, in: text)
attrText.addAttribute(.foregroundColor,
value: fgColor.withAlphaComponent(0.6),
range: pathRange)
attrText.removeAttribute(.shadow, range: pathRange)
}
attrText.draw(in: bounds)
type.strokeColor.set()
path.stroke()
}
private func makePath() -> NSBezierPath
{
// Inset because the stroke will be centered on the path border
var rect = bounds.insetBy(dx: 0.5, dy: 1.5)
rect.origin.y += 1
rect.size.height -= 1
switch type {
case .branch, .activeBranch:
let radius = rect.size.height / 2
return NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius)
case .tag:
let path = NSBezierPath()
let cornerInset: CGFloat = 5
let top = rect.origin.y
let left = rect.origin.x
let bottom = top + rect.size.height
let right = left + rect.size.width
let leftInset = left + cornerInset
let rightInset = right - cornerInset
let middle = top + rect.size.height / 2
path.move(to: NSPoint(x: leftInset, y: top))
path.line(to: NSPoint(x: rightInset, y: top))
path.line(to: NSPoint(x: right, y: middle))
path.line(to: NSPoint(x: rightInset, y: bottom))
path.line(to: NSPoint(x: leftInset, y: bottom))
path.line(to: NSPoint(x: left, y: middle))
path.close()
return path
default:
return NSBezierPath(rect: rect)
}
}
}
extension NSFont
{
static var refLabelFont: NSFont { return labelFont(ofSize: 11) }
}
| 30.065041 | 80 | 0.627096 |
1aeac1606f4eff6dcc11d0af5da028028713afd4 | 1,330 | //
// FPCentralManager.swift
// flashprint
//
// Created by yulong mei on 2021/2/26.
//
import Foundation
import CoreBluetooth
import UIKit
class FPCentralManager: FPServiceProtocol {
static let shared = FPCentralManager()
/// 当前打印机的服务SDK
var service: FPServiceBase? {
get {
switch type {
case .Alison:
return alisonService
default:
return nil
}
}
}
/// 当前PrinterSDK类型
var type: FPPrinterType = .Unknown
/// Alison SDK
private var alisonService = FPAlisonService()
var currentPeripheral: FPPeripheral?
/// 需要将SDK的扫描统一管理,每个SDK扫描的设备不能通用,所以需要所有的打印机SDK来扫描,依据选择的设置来判断使用哪个SDK服务;
public func scan() {
alisonService.fpScan()
}
public func stopScan() {
alisonService.fpStopScan()
}
public func connect(peripheral: FPPeripheral) {
type = peripheral.type
service?.fpConnect(peripheral.cbPeripheral)
}
}
//MARK: FPServiceProtocol
extension FPCentralManager {
func start() {
// 需要提前将SDK初始化,因为CBCentralManager需要先去检测蓝牙状态才能扫描设备
alisonService.start()
}
func stop() {
alisonService.stop()
type = .Unknown
currentPeripheral = nil
}
}
| 19.558824 | 74 | 0.593985 |
753e43c8a0ab061848701175047eba9632a6fdf8 | 3,315 | //
// ScrapmdUITests.swift
// ScrapmdUITests
//
// Created by Atsushi Nagase on 2020/06/04.
// Copyright © 2020 LittleApps Inc. All rights reserved.
//
import XCTest
class ScrapmdUITests: XCTestCase {
override func setUpWithError() throws {
continueAfterFailure = false
}
override func tearDownWithError() throws {
}
func test01Launch() throws {
let app = XCUIApplication()
setupSnapshot(app)
app.launch()
if !app.otherElements["DirectoryBrowser"].exists {
XCUIDevice.shared.orientation = .landscapeLeft
}
app.terminate()
}
func test02ActionExtension() throws {
let domain = locale == "ja" ? "ja.ngs.io" : "ngs.io"
let safari = XCUIApplication(bundleIdentifier: "com.apple.mobilesafari")
// setupSnapshot(safari)
safari.launch()
goToURL(safari, url: "https://\(domain)/2019/02/08/go-release-action/")
safari.buttons["ShareButton"].tap()
safari.buttons["Edit Actions…"].tap()
if safari.buttons["Delete Copy"].exists {
safari.buttons["Delete Copy"].tap()
safari.buttons["Remove"].tap()
}
if safari.buttons["Insert Activity"].exists {
safari.buttons["Insert Activity"].tap()
}
safari.buttons["Done"].tap()
if safari.buttons["Close"].exists {
safari.buttons["Close"].tap()
} else if safari.otherElements["PopoverDismissRegion"].exists {
safari.otherElements["PopoverDismissRegion"].tap()
}
doScrap(safari)
goToURL(safari, url: "https://\(domain)/2020/05/15/ci2go-maccatalyst/")
sleep(5)
doScrap(safari, takeSnapshot: true)
safari.terminate()
}
func test03App() {
let app = XCUIApplication()
setupSnapshot(app)
app.launch()
snapshot("0-home")
app.cells.firstMatch.tap()
snapshot("1-read")
app.terminate()
}
func test04DarkApp() {
let app = XCUIApplication()
app.launchArguments = ["UITestingDarkModeEnabled"]
setupSnapshot(app)
app.launch()
snapshot("4-home-dark")
app.cells.firstMatch.tap()
snapshot("5-read-dark")
app.terminate()
}
func goToURL(_ safari: XCUIApplication, url: String) {
let addressBar = safari.otherElements["TopBrowserBar"]
addressBar.tap()
if safari.buttons["Continue"].exists && safari.buttons["Continue"].isHittable {
safari.buttons["Continue"].tap()
}
addressBar.tap()
addressBar.typeText(url)
safari.keyboards.buttons["Go"].tap()
}
func doScrap(_ safari: XCUIApplication, takeSnapshot: Bool = false) {
safari.buttons["ShareButton"].tap()
if takeSnapshot {
snapshot("2-share", waitForLoadingIndicator: false)
}
safari.cells.firstMatch.tap()
if !safari.buttons["Save"].waitForExistence(timeout: 5000) {
fatalError()
}
if takeSnapshot {
snapshot("3-save", waitForLoadingIndicator: false)
}
safari.buttons["Save"].tap()
_ = safari.buttons["View Scrap"].waitForExistence(timeout: 5000)
safari.buttons["Done"].tap()
}
}
| 29.864865 | 87 | 0.59457 |
de1f19d666c62572d8b5a4a22204a3cc7e55eba4 | 279 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
class d<true
func b<d-> d { class d:b class b
| 27.9 | 87 | 0.74552 |
e9a37181fb407e2a13a91d1043fd0241de035732 | 657 | //
// emojiMemoryGame.swift
// LectureMemorize
//
// view model
//
// Created by sun on 2021/09/28.
//
import Foundation
class EmojiMemoryGame {
static let emojis = ["🚗", "🛴", "✈️", "🛵", "⛵️", "🚎", "🚐", "🚛", "🛻", "🏎", "🚂", "🚊", "🚀", "🚁", "🚢", "🛶", "🛥", "🚞", "🚟", "🚃"]
static func createMemoryGame() -> MemoryGame<String> {
MemoryGame(numberOfPairsOfCards: 4) { pairIndex in emojis[pairIndex] }
}
// each Model-View creates its own Model
private(set) var model = createMemoryGame()
// and make public, parts that need to be so
var cards: [MemoryGame<String>.Card] {
return model.cards
}
}
| 24.333333 | 126 | 0.543379 |
d63ee96e5d8d767cc9722a275265d1f7177d7594 | 2,167 | //
// EXTAttributeKey.swift
// M3U
//
// Created by 刘栋 on 2022/3/21.
// Copyright © 2022 anotheren.com. All rights reserved.
//
import Foundation
public struct EXTAttributeKey: RawRepresentable, Hashable {
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
}
extension EXTAttributeKey: CustomStringConvertible {
public var description: String {
rawValue
}
}
extension EXTAttributeKey {
public static let type = EXTAttributeKey(rawValue: "TYPE")
public static let groupID = EXTAttributeKey(rawValue: "GROUP-ID")
public static let language = EXTAttributeKey(rawValue: "LANGUAGE")
public static let name = EXTAttributeKey(rawValue: "NAME")
public static let `default` = EXTAttributeKey(rawValue: "DEFAULT")
public static let autoselect = EXTAttributeKey(rawValue: "AUTOSELECT")
public static let instreamID = EXTAttributeKey(rawValue: "INSTREAM-ID")
public static let channels = EXTAttributeKey(rawValue: "CHANNELS")
public static let uri = EXTAttributeKey(rawValue: "URI")
public static let forced = EXTAttributeKey(rawValue: "FORCED")
public static let averageBandwidth = EXTAttributeKey(rawValue: "AVERAGE-BANDWIDTH")
public static let bandwidth = EXTAttributeKey(rawValue: "BANDWIDTH")
public static let codecs = EXTAttributeKey(rawValue: "CODECS")
public static let resolution = EXTAttributeKey(rawValue: "RESOLUTION")
public static let frameRate = EXTAttributeKey(rawValue: "FRAME-RATE")
public static let closedCaptions = EXTAttributeKey(rawValue: "CLOSED-CAPTIONS")
public static let audio = EXTAttributeKey(rawValue: "AUDIO")
public static let subtitles = EXTAttributeKey(rawValue: "SUBTITLES")
public static let byterange = EXTAttributeKey(rawValue: "BYTERANGE")
public static let method = EXTAttributeKey(rawValue: "METHOD")
public static let iv = EXTAttributeKey(rawValue: "IV")
}
| 42.490196 | 88 | 0.667282 |
4644c717e4da9abb306f8c096630664d1b4b104c | 3,049 | //
// Created by Christoph Muck on 23.02.18.
// Copyright (c) 2018 Christoph Muck. All rights reserved.
//
func calculateComponentBuilders() -> [ComponentBuilder] {
let allComponents = calculateComponents()
return getBuilderTypes()
.map { (type: Type) -> ComponentBuilder in
let componentType = getComponentType(for: type)
guard let component = allComponents.first(where: { $0.name == componentType.name }) else {
fatalError("No component with type \(componentType.name) found!")
}
return ComponentBuilder(component: component, name: type.name)
}
}
func getComponentType(for type: Type) -> Type {
guard let buildMethod = type.methods.first(where: { $0.shortName == "build" }) else {
fatalError("\(type.name) has no build() method")
}
guard let componentType = buildMethod.returnType else {
fatalError("No accessible component type in \(type.name) build() method")
}
return componentType
}
func getBuilderTypes() -> [Type] {
return types.protocols.filter { $0.annotations.keys.contains("Builder") }
}
func builderName(forComponent componentName: String) -> String? {
return getBuilderTypes().filter { type in
let componentType = getComponentType(for: type)
return componentType.name == componentName
}.map { $0.name }.first
}
func getAllComponentBuildersSeparatedByModule() -> [String: [ComponentBuilder]] {
return calculateComponentBuilders().reduce(into: [String: [ComponentBuilder]]()) { dict, element in
var factories: [ComponentBuilder]
if let arr = dict[element.module] {
factories = arr
} else {
factories = [ComponentBuilder]()
}
factories.append(element)
dict[element.module] = factories
}
}
func dependenciesForComponentBuilders() -> [Dependency] {
return calculateComponentBuilders().map { builder -> Dependency in
Dependency(
typeName: builder.name + "Impl",
type: nil,
module: builder.module,
dependencies: getDependencyDeclarations(from: builder),
createdBy: .initializer,
trait: .unscoped,
accessLevel: "")
}
}
func getDependencyDeclarations(from builder: ComponentBuilder) -> [DependencyDeclaration] {
guard let subcomponent = builder.component as? Subcomponent else {
return []
}
return [
DependencyDeclaration(
name: "parentComponent",
dependency: Dependency(
typeName: subcomponent.parent.name + "Impl",
type: nil,
module: subcomponent.parent.module,
dependencies: [],
createdBy: .initializer,
trait: .unscoped,
accessLevel: ""
),
injectMethod: .initializer,
isProvider: false,
declaredTypeName: subcomponent.parent.name + "Impl",
declaredType: nil
)
]
}
| 34.258427 | 103 | 0.615284 |
9bba2cb74a0ad1c656859c56fd7e47da041e0c18 | 2,190 | //
// String+MatchQuery.swift
// SearchTextHighlighter
//
// Created by Maxim on 28/09/2019.
// Copyright © 2019 Maxim Ivunin. All rights reserved.
//
import Foundation
extension String {
func matchesQuery(for searchWords: [String]) -> Bool {
var mutableElements = searchWords
let queryWordList = lowercased()
.toLatin()
.components(separatedBy: " ")
.sorted { $0.count > $1.count }
for queryWord in queryWordList {
if let indexFound = mutableElements.firstIndex(where: { $0.hasPrefix(queryWord) }) {
mutableElements.remove(at: indexFound)
} else {
return false
}
}
return true
}
var cyrillicToLatinMap: [Character: String] {
return ["щ":"shch", "ш":"sh", "а": "a", "б": "b", "в": "v", "г":"g", "д":"d", "е":"e", "ё":"yo", "ж":"zh", "з":"z", "и":"i", "й":"j",
"к":"k", "л":"l", "м":"m", "н":"n", "о":"o", "п":"p", "р":"r", "с":"s",
"т":"t", "у":"u", "ф":"f", "х":"h", "ц":"ts",
"ч":"ch", "ъ":"'", "ы":"y", "ь":"'", "э":"e", "ю":"yu", "я":"ya"]
}
private var latinToCyrillicMap: [String: String] {
return ["shch": "щ", "zh": "ж", "ts": "ц", "ch": "ч",
"sh": "ш", "yu": "ю", "ya": "я", "yo": "ё",
"ye": "ъе", "a": "а", "b": "б", "c": "к",
"d": "д", "e": "е", "f": "ф", "g": "г",
"h": "х", "i": "и", "j": "й", "k": "к",
"l": "л", "m": "м", "n": "н", "o": "о",
"p": "п", "q": "к", "r": "р", "s": "с",
"t": "т", "u": "у", "v": "в", "w": "в",
"x": "кс", "y": "ы", "z": "з", "'": "ь"]
}
func toLatin() -> String {
return lowercased().map { cyrillicToLatinMap[$0] ?? String($0) }.joined()
}
func toCyrillic() -> String {
var tmp = lowercased()
let keys: [String] = latinToCyrillicMap.keys.sorted(by: { $0.count > $1.count})
keys.forEach { tmp = tmp.replacingOccurrences(of: $0, with: latinToCyrillicMap[$0] ?? $0) }
return tmp
}
}
| 35.322581 | 141 | 0.413699 |
203901560737646d40632ee593fdef3c2f46321d | 2,119 | //
// RetryableHostTests.swift
//
//
// Created by Vladislav Fitc on 17/03/2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
class RetryableHostTests: XCTestCase {
func testConstruction() {
let host = RetryableHost(url: URL(string: "algolia.com")!, callType: .read)
XCTAssertEqual(host.url.absoluteString, "algolia.com")
XCTAssertTrue(host.isUp)
XCTAssertEqual(host.supportedCallTypes, .read)
XCTAssertEqual(host.retryCount, 0)
}
func testFail() {
var host = RetryableHost(url: URL(string: "algolia.com")!, callType: .read)
let previouslyUpdated = host.lastUpdated
sleep(1)
host.hasFailed()
XCTAssertFalse(host.isUp)
XCTAssertGreaterThan(host.lastUpdated.timeIntervalSince1970, previouslyUpdated.timeIntervalSince1970)
}
func testTimeout() {
var host = RetryableHost(url: URL(string: "algolia.com")!, callType: .read)
var previouslyUpdated: Date
previouslyUpdated = host.lastUpdated
sleep(1)
host.hasTimedOut()
XCTAssertTrue(host.isUp)
XCTAssertEqual(host.retryCount, 1)
XCTAssertGreaterThan(host.lastUpdated.timeIntervalSince1970, previouslyUpdated.timeIntervalSince1970)
previouslyUpdated = host.lastUpdated
sleep(1)
host.hasTimedOut()
XCTAssertTrue(host.isUp)
XCTAssertEqual(host.retryCount, 2)
XCTAssertGreaterThan(host.lastUpdated.timeIntervalSince1970, previouslyUpdated.timeIntervalSince1970)
}
func testReset() {
var host = RetryableHost(url: URL(string: "algolia.com")!, callType: .read)
var previouslyUpdated: Date
previouslyUpdated = host.lastUpdated
sleep(1)
host.hasTimedOut()
host.hasFailed()
XCTAssertFalse(host.isUp)
XCTAssertEqual(host.retryCount, 1)
XCTAssertGreaterThan(host.lastUpdated.timeIntervalSince1970, previouslyUpdated.timeIntervalSince1970)
previouslyUpdated = host.lastUpdated
sleep(1)
host.reset()
XCTAssertTrue(host.isUp)
XCTAssertEqual(host.retryCount, 0)
XCTAssertGreaterThan(host.lastUpdated.timeIntervalSince1970, previouslyUpdated.timeIntervalSince1970)
}
//
}
| 28.635135 | 105 | 0.742803 |
8f4095570194869190512a69d665857c64879ed7 | 1,629 | //
// Version.swift
// Device
//
// Created by Lucas Ortis on 30/10/2015.
// Copyright © 2015 Ekhoo. All rights reserved.
//
public enum Version: String {
/*** iPhone ***/
case iPhone4
case iPhone4S
case iPhone5
case iPhone5C
case iPhone5S
case iPhone6
case iPhone6Plus
case iPhone6S
case iPhone6SPlus
case iPhoneSE
case iPhone7
case iPhone7Plus
case iPhone8
case iPhone8Plus
case iPhoneX
case iPhoneXS
case iPhoneXS_Max
case iPhoneXR
case iPhone11
case iPhone11Pro
case iPhone11Pro_Max
case iPhoneSE2
case iPhone12Mini
case iPhone12
case iPhone12Pro
case iPhone12Pro_Max
case iPhone13Mini
case iPhone13
case iPhone13Pro
case iPhone13Pro_Max
/*** iPad ***/
case iPad1
case iPad2
case iPad3
case iPad4
case iPad5
case iPad6
case iPad7
case iPad8
case iPad9
case iPadAir
case iPadAir2
case iPadAir3
case iPadAir4
case iPadMini
case iPadMini2
case iPadMini3
case iPadMini4
case iPadMini5
case iPadMini6
/*** iPadPro ***/
case iPadPro9_7Inch
case iPadPro12_9Inch
case iPadPro10_5Inch
case iPadPro12_9Inch2
case iPadPro11_0Inch
case iPadPro12_9Inch3
case iPadPro11_0Inch2
case iPadPro12_9Inch4
case iPadPro12_9Inch5
/*** iPod ***/
case iPodTouch1Gen
case iPodTouch2Gen
case iPodTouch3Gen
case iPodTouch4Gen
case iPodTouch5Gen
case iPodTouch6Gen
case iPodTouch7Gen
/*** simulator ***/
case simulator
/*** unknown ***/
case unknown
}
| 18.303371 | 48 | 0.659914 |
8f0fe9029111b5a10605cf2e7f2061b06e02030a | 615 | //
// Numerical.swift
// PaletteKnife
//
// Created by JENNIFER MARY JACOBS on 5/26/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import Foundation
class Numerical{
static let TRIGONOMETRIC_EPSILON = Float(1e-7)
static let EPSILON = Float(1e-12)
static let MACHINE_EPSILON = Float(1.12e-16)
static func isZero (val:Float)->Bool {
return val >= -EPSILON && val <= EPSILON;
}
static func map (value:Float, istart:Float, istop:Float, ostart:Float, ostop:Float)->Float {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}
}
| 24.6 | 96 | 0.643902 |
01cf701e6943f3bf67886f47fdfff7039aa32d40 | 1,137 | //
// ProfileManager.swift
// MyJWPChatApp
//
// Created by Amitai Blickstein on 11/5/20.
//
import Foundation
import Firebase
import FirebaseDatabase
import FirebaseAuth
import CodableFirebase
class ProfileManager {
static let dbRef = Database.database().reference()
private static var cachedUsers = [String: User]()
static func getCachedUser(forId uid: String?) -> User? {
guard let uid = uid else { return nil }
return cachedUsers[uid]
}
static func cache(user: User) {
cachedUsers[user.uid] = user
}
static var users: [User] {Array(cachedUsers.values)}
static func fillUsers(completion: @escaping () -> Void) {
dbRef.child(L10n.DbPath.users)
.observe(.childAdded)
{
guard let userData = $0.value else { return }
do {
let user = try FirebaseDecoder().decode(User.self, from: userData)
self.cache(user: user)
}
catch { print(error.localizedDescription) }
completion()
}
}
}
| 26.44186 | 86 | 0.573439 |
72956453b8cb86d1e082b8e467e8befbe5e62a0e | 774 | ////
/// AnnouncementCellPresenter.swift
//
struct AnnouncementCellPresenter {
static func configure(
_ cell: UICollectionViewCell,
streamCellItem: StreamCellItem,
streamKind: StreamKind,
indexPath: IndexPath,
currentUser: User?
) {
guard
let cell = cell as? AnnouncementCell,
let announcement = streamCellItem.jsonable as? Announcement
else { return }
var config = AnnouncementCell.Config()
config.title = announcement.header
config.body = announcement.body
config.callToAction = announcement.ctaCaption
config.imageURL = announcement.imageURL
config.isStaffPreview = announcement.isStaffPreview
cell.config = config
}
}
| 27.642857 | 71 | 0.649871 |
87d3cd98f7959b0151cd3de7e7af4dbed342b55a | 1,585 | //
// BoardView.swift
// Minigames
//
// Created by Tomer Israeli on 02/06/2021.
//
import SwiftUI
struct BoardView: View {
@ObservedObject var board: BoardViewModel
var body: some View {
HexagonStack(board) { row, column, size in
tileView(row: row, column: column, size: size)
}
.buildingsOverlay(board)
// .zoomable()
}
@ViewBuilder
private func tileView(row: Int, column: Int, size: CGFloat) -> some View {
if let tile = board.tileAt(row, column){
TileView(tile)
.environmentObject(board)
.frame(width: size, height: size)
.clipShape(Hexagon())
.shadow(color: tileShadow(for: tile), radius: board.shadowRadius)
} else {
Image(systemName: "exclamationmark.triangle")
}
}
private func tileShadow(for tile: Tile) -> Color {
if tile == board.knightHoveringTile {
return tile.knightIsIn ? .red : .green
} else {
return .clear
}
}
}
struct BoardView_Previews: PreviewProvider {
static var previews: some View {
let vm = BoardViewModel(gameVM: mocGameViewModel)
return Group {
BoardView(board: vm)
.previewLayout(.fixed(width: 1000, height: 1000))
BoardView(board: vm)
.preferredColorScheme(.dark)
.previewLayout(.fixed(width: 1000, height: 1000))
}
.padding()
}
}
| 24.765625 | 81 | 0.538801 |
7928c29a08277b314885d7ed1fd65f6376901405 | 253 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let h = 0
protocol a {
struct A {
var d = [ {
{
var d { func a
{
class
case c,
case
| 16.866667 | 87 | 0.70751 |
d6c6051967d409fa5a2317329ba32da38b8ac22c | 342 | //
// DirectionDetailViewController.swift
// PGTransitionKit_Example
//
// Created by ipagong on 19/09/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
import PGTransitionKit
class DirectionDetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| 18 | 55 | 0.710526 |
8a58d844fd47202a46276a8a79018358557d8af1 | 865 | //
// UIView.swift
// EventsBy
//
// Created by Alexander Tereshkov on 7/2/18.
// Copyright © 2018 Events-By. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set (newRadius) {
self.layer.cornerRadius = newRadius
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set (newWidth) {
self.layer.borderWidth = newWidth
}
}
@IBInspectable var borderColor: UIColor? {
get {
return (self.layer.borderColor != nil) ? UIColor(cgColor: self.layer.borderColor!) : nil
}
set (newColor) {
self.layer.borderColor = newColor?.cgColor
}
}
}
| 21.097561 | 100 | 0.547977 |
def99ca3510d7456959e53657d4b60c1d3b770bc | 9,642 | //
// YoutubeViewController.swift
// table_template
//
// Created by Shuchen Du on 2015/09/26.
// Copyright (c) 2015年 Shuchen Du. All rights reserved.
//
import UIKit
class YoutubeViewController: UIViewController, NSURLSessionDelegate,
NSURLSessionDownloadDelegate, NSURLSessionTaskDelegate {
let myCell = "cell_id"
var session: NSURLSession!
var url: NSURL!
var selectedVideoIndex: Int!
var apiKey = "AIzaSyDqxwQmV1UcawuR6C4hWP5iBlZY7WqqHAI"
var videosArray: Array<Dictionary<NSObject, AnyObject>> = []
// youtube text field
@IBOutlet weak var yttf: UITextField!
@IBOutlet weak var videoTable: UITableView!
// perform request task
func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) {
let request = NSMutableURLRequest(URL: targetURL)
request.HTTPMethod = "GET"
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfiguration)
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(data: data, HTTPStatusCode: (response as! NSHTTPURLResponse).statusCode, error: error)
})
})
task.resume()
}
/* Just a little method to help us display alert dialogs to the user */
func displayAlertWithTitle(title: String, message: String) {
let controller = UIAlertController(title: title,
message: message, preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: "OK",
style: .Default, handler: {
(alert: UIAlertAction!) in
dispatch_async(dispatch_get_main_queue()) {
self.yttf.text = ""
}
}))
presentViewController(controller,
animated: true, completion: nil)
}
/* We now get to know that the download procedure finished */
func URLSession(session: NSURLSession, task: NSURLSessionTask,
didCompleteWithError error: NSError?) {
print("Finished ")
// error occurs
if let err = error {
println("with an error = \(err)")
self.displayAlertWithTitle("download error occurs", message: "\(err)")
}
/* Release the delegate */
session.finishTasksAndInvalidate()
}
// download finished, save the data to file system
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
// file manager
let manager = NSFileManager()
// path to Document folder
var error: NSError?
var destinationPath = manager.URLForDirectory(.DocumentDirectory,
inDomain: .UserDomainMask,
appropriateForURL: url,
create: true,
error: &error)!
// downloaded file name
let componentsOfUrl = url.absoluteString!.componentsSeparatedByString("/")
let fileNameFromUrl = componentsOfUrl[componentsOfUrl.count - 1]
// append file name to Document folder
destinationPath =
destinationPath.URLByAppendingPathComponent(fileNameFromUrl)
// move the file
manager.moveItemAtURL(url, toURL: destinationPath, error: nil)
// alert success message
let message = "Saved the downloaded data to = \(destinationPath)"
self.displayAlertWithTitle("Success", message: message)
}
// identifier for session configuration
var configurationIdentifier: String {
let userDefaults = NSUserDefaults.standardUserDefaults()
let key = "configurationIdentifier"
let previousValue = userDefaults.stringForKey(key) as String?
if let thePreviousValue = previousValue {
return previousValue!
} else {
let newValue = NSDate().description
userDefaults.setObject(newValue, forKey: key)
userDefaults.synchronize()
return newValue
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
/* Create our configuration first */
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(
configurationIdentifier)
configuration.timeoutIntervalForRequest = 15.0
/* Now create a session that allows us to create the tasks */
session = NSURLSession(configuration: configuration, delegate: self,
delegateQueue: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension YoutubeViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.videosArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = self.videoTable.dequeueReusableCellWithIdentifier(myCell,
forIndexPath: indexPath) as! MyCell
let videoDetails = videosArray[indexPath.row]
cell.vidTitleLabel.text = videoDetails["title"] as? String
cell.imgView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: (videoDetails["thumbnail"] as? String)!)!)!)
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let id = segue.identifier {
switch id {
case "seg_music":
let nvc = segue.destinationViewController as! UINavigationController
let dvc = nvc.childViewControllers[0] as! MusicViewController
let id = self.videoTable.indexPathForCell(sender as! MyCell)!
dvc.videoID = videosArray[id.row]["videoID"] as! String
default:
break
}
}
}
}
extension YoutubeViewController: UITextFieldDelegate {
// called when return is typed
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.yttf.resignFirstResponder()
var type = "video"
// Form the request URL string.
var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(textField.text)&type=\(type)&key=\(apiKey)"
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
// Create a NSURL object based on the above string.
let targetURL = NSURL(string: urlString)
// Get the results.
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
// Convert the JSON data to a dictionary object.
let resultsDict = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! Dictionary<NSObject, AnyObject>
// Get all search result items ("items" array).
let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>
// remove old data
self.videosArray.removeAll(keepCapacity: false)
// Loop through all search results and keep just the necessary data.
for var i=0; i<items.count; ++i {
let snippetDict = items[i]["snippet"] as! Dictionary<NSObject, AnyObject>
// Create a new dictionary to store the video details.
var videoDetailsDict = Dictionary<NSObject, AnyObject>()
videoDetailsDict["title"] = snippetDict["title"]
videoDetailsDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"]
videoDetailsDict["videoID"] = (items[i]["id"] as! Dictionary<NSObject, AnyObject>)["videoId"]
// Append the desiredPlaylistItemDataDict dictionary to the videos array.
self.videosArray.append(videoDetailsDict)
// Reload the tableview.
self.videoTable.reloadData()
}
} else {
println("HTTP Status Code = \(HTTPStatusCode)")
println("Error while loading channel videos: \(error)")
}
})
return true
}
} | 37.96063 | 171 | 0.609106 |
f9cfe24d629d718f9549f8da24d9977b02d72957 | 25,886 |
//
// ArvatoProductViewController.swift
// IngenicoConnectExample
//
// Created for Ingenico ePayments on 07/07/2017.
// Copyright © 2017 Ingenico. All rights reserved.
//
import UIKit
import IngenicoConnectKit
class ArvatoProductViewController: PaymentProductViewController {
var failCount: Int = 0
var didFind: Bool = false
var fullData: Bool = false
var hasLookup = false
var errorMessageText = ""
var installmentPlanFields = 0
func reload() {
self.initializeFormRows()
self.addExtraRows()
CATransaction.begin()
CATransaction.setCompletionBlock {
self.tableView.reloadData()
}
self.tableView.beginUpdates()
self.tableView.endUpdates()
CATransaction.commit()
}
override init(paymentItem: PaymentItem, session: Session, context: PaymentContext, viewFactory: ViewFactory, accountOnFile: AccountOnFile?) {
super.init(paymentItem: paymentItem, session: session, context: context, viewFactory: viewFactory, accountOnFile: accountOnFile)
self.hasLookup = paymentItem.fields.paymentProductFields.map { (field) -> Bool in
return field.usedForLookup
}.reduce(false) { (result, bool) -> Bool in
return result || bool
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let row = formRows[indexPath.row]
if !row.isEnabled {
return 0
}
if let row = row as? FormRowList {
var max: CGFloat = 0;
max = CGFloat(row.items[row.selectedRow].displayElements.filter{ $0.id != "displayName" }.count) * (UIFont.systemFontSize + 2)
// Add distance between error message and description
if max > 0 {
max += 10
}
let width = min(320, tableView.bounds.width - 20)
var errorHeight: CGFloat = 0
if let firstError = row.paymentProductField.errors.first, validation {
let str = NSAttributedString(string: FormRowsConverter.errorMessage(for: firstError, withCurrency: false))
errorHeight = str.boundingRect(with: CGSize.init(width: width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, context: nil).height + 10
}
return max + DetailedPickerViewTableViewCell.pickerHeight + errorHeight
}
if let fieldRow = row as? FormRowReadonlyReview {
return ReadonlyReviewCell.cellHeight(for: fieldRow.data, in: tableView.frame.size.width)
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
super.pickerView(pickerView, didSelectRow: row, inComponent: component)
if validation {
validateData()
}
// Update row height for picker
tableView.beginUpdates()
tableView.endUpdates()
}
@objc func searchButtonTapped() {
//let enabledRows = self.formRows.filter { (fr) -> Bool in
// fr.isEnabled
//}
let values = self.inputData.paymentItem.fields.paymentProductFields.filter { (field) -> Bool in
field.usedForLookup
}.map { (field) -> (String,String) in
(field.identifier, self.inputData.value(forField: field.identifier))
}
var params: [[String:String]] = []
for (key, value) in values {
var param: [String:String] = [:]
param["key"] = key
param["value"] = value
params.append(param)
}
self.session.customerDetails(forProductId: self.initialPaymentProduct?.identifier ?? "", withLookupValues: params, countryCode: self.context.countryCode, success: { (cd: CustomerDetails) in
self.didFind = true
self.validation = true
let installmentId = self.inputData.fieldValues["installmentId"]
let termsAndConditions = self.inputData.fieldValues["termsAndConditions"]
let lookupIdentifiers = self.initialPaymentProduct?.fields.paymentProductFields.first(where: {$0.usedForLookup}).map({$0.identifier})
let lookupFields = self.inputData.fieldValues.filter{ lookupIdentifiers?.contains($0.key) ?? false }
self.inputData.fieldValues.removeAll();
for (id, val) in lookupFields {
self.inputData.setValue(value: val, forField: id)
}
self.inputData.setValue(value: installmentId ?? "", forField: "installmentId")
self.inputData.setValue(value: termsAndConditions ?? "", forField: "termsAndConditions")
for (key, value) in cd.values {
self.inputData.setValue(value: value, forField: key)
}
self.inputData.validateExcept(fieldNames: Set(["termsAndConditions", "installmentId"]))
if self.inputData.errors.count == 0 {
self.fullData = true
}
self.reload()
}) { (err) in
if let err = err as? CustomerDetailsError {
let details = err.responseValues[0]
let id = details["id"] as? String ?? ""
if self.failCount >= 10 {
self.errorMessageText = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.result.failed.tooMuch", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "No result found. You have reached the maximum amount of tries. Please enter your details manually.", comment: "Title of the search button on the payment product screen.")
}
else if id == "PARAMETER_NOT_FOUND_IN_REQUEST" {
self.errorMessageText = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.result.failed.errors.missingValue", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "No result found. You have reached the maximum amount of tries. Please enter your details manually.", comment: "Title of the search button on the payment product screen.")
let propertyString = details["propertyName"] as? String ?? ""
var stringRange = propertyString.range(of: "'", options: .backwards)
guard let range1 = stringRange else {
self.failCount += 1
self.didFind = false
self.reload()
return
}
let restRange = propertyString.startIndex ..< (range1.lowerBound)
stringRange = propertyString.substring(with: restRange).range(of: "'", options: .backwards)
guard let range2 = stringRange else {
self.failCount += 1
self.didFind = false
self.reload()
return
}
let propertyRange = range2.upperBound ..< range1.lowerBound
let property = propertyString.substring(with: propertyRange)
var labelKey = "gc.general.paymentProducts.\(self.paymentItem.identifier).paymentProductFields.\(property).label"
var labelValue = NSLocalizedString(labelKey, tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: labelKey, comment: "Title of the search button on the payment product screen.")
if labelKey == labelValue {
labelKey = "gc.general.paymentProductFields.\(property).label"
labelValue = NSLocalizedString(labelKey, tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "No result found. You have reached the maximum amount of tries. Please enter your details manually.", comment: "Title of the search button on the payment product screen.")
}
self.errorMessageText = self.errorMessageText.replacingOccurrences(of: "{propertyName}", with: labelValue)
}
else {
self.errorMessageText = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.result.failed.invalidData", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "No result found. You have reached the maximum amount of tries. Please enter your details manually.", comment: "Title of the search button on the payment product screen.")
}
}
self.failCount += 1
self.didFind = false
self.reload()
}
}
@objc func enterManuallyButtonTapped() {
didFind = true
reload()
}
@objc func editInformationButtonTapped() {
fullData = false
reload()
}
@objc func searchAgainButtonTapped() {
didFind = false
fullData = false
failCount = 0
self.reload()
}
override func updatePickerCell(_ cell: PickerViewTableViewCell, row: FormRowList) {
guard let cell = cell as? DetailedPickerViewTableViewCell else {
return
}
let field = row.paymentProductField
if let error = field.errors.first {
cell.errorMessage = FormRowsConverter.errorMessage(for: error, withCurrency: false)
} else {
cell.errorMessage = nil
}
}
override func addExtraRows() {
// 'Edit information' and 'Search Again' button
let labelText = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.label", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "Your billing details", comment: "")
let label = FormRowLabel(text: labelText)
label.isEnabled = self.hasLookup
label.isBold = true
self.formRows.insert(label, at: self.installmentPlanFields)
let labelFormRowTooltip = FormRowTooltip()
labelFormRowTooltip.text = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.tooltipText", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "", comment: "")
label.tooltip = labelFormRowTooltip
self.formRows.insert(labelFormRowTooltip, at: self.installmentPlanFields + 1)
let separator = FormRowSeparator(text: nil)
separator.isEnabled = self.installmentPlanFields > 0
self.formRows.insert(separator, at: self.installmentPlanFields)
let reviewRow = FormRowReadonlyReview()
var filteredData: [String:String] = [:]
for (key, value) in self.inputData.fieldValues where key != "installmentPlan" && paymentItem.fields.paymentProductFields.contains(where: {$0.identifier == key}) {
filteredData[key] = value
}
reviewRow.data = filteredData
reviewRow.isEnabled = fullData
self.formRows.append(reviewRow)
let searchAgainButtonTitle = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.buttons.searchAgain", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "Enter manually", comment: "Title of the enter manually button on the payment product screen.")
let searchAgainButtonFormRow = FormRowButton(title: searchAgainButtonTitle, target: self, action: #selector(searchAgainButtonTapped))
searchAgainButtonFormRow.buttonType = .primary
let _ = paymentItem.fields.paymentProductFields.map { (field) -> Bool in
return field.usedForLookup
}.reduce(false) { (result, bool) -> Bool in
return result || bool
}
searchAgainButtonFormRow.isEnabled = hasLookup && fullData && failCount < 10
self.formRows.append(searchAgainButtonFormRow)
let editInformationButtonTitle = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.buttons.editInformation", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "Search", comment: "Title of the search button on the payment product screen.")
let editInformationButtonFormRow = FormRowButton(title: editInformationButtonTitle, target: self, action: #selector(editInformationButtonTapped))
editInformationButtonFormRow.isEnabled = fullData && (failCount < 10 || didFind)
editInformationButtonFormRow.buttonType = .secondary
self.formRows.append(editInformationButtonFormRow)
var lastLookupIndex = 0
var i = -1
for fr in self.formRows {
i += 1
switch fr {
case let sr as FormRowSwitch:
if sr.field?.usedForLookup ?? false {
lastLookupIndex = i
}
case let sr as FormRowList:
if sr.paymentProductField.usedForLookup {
lastLookupIndex = i
}
case let sr as FormRowDate:
if sr.paymentProductField.usedForLookup {
lastLookupIndex = i
}
case let sr as FormRowTextField:
if sr.paymentProductField.usedForLookup {
lastLookupIndex = i
}
case let sr as FormRowCurrency:
if sr.paymentProductField.usedForLookup {
lastLookupIndex = i
}
default: break
}
if fr is FormRowWithInfoButton {
if self.formRows[i + 1] is FormRowTooltip {
lastLookupIndex += 1
}
}
}
let badMessageTitleEarly = self.errorMessageText
let badMessageEarlyRow = FormRowLabel(text: badMessageTitleEarly)
badMessageEarlyRow.isEnabled = hasLookup && !didFind && !fullData && failCount > 0 && failCount < 10
self.formRows.insert(badMessageEarlyRow, at: lastLookupIndex + 1)
// Add search and 'enter manually' button
let searchButtonTitle = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.buttons.search", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "Search", comment: "Title of the search button on the payment product screen.")
let searchButtonFormRow = FormRowButton(title: searchButtonTitle, target: self, action: #selector(searchButtonTapped))
searchButtonFormRow.isEnabled = self.hasLookup && self.failCount < 10 && !self.fullData
self.formRows.insert(searchButtonFormRow, at: lastLookupIndex + 2)
let enterManuallyButtonTitle = NSLocalizedString("gc.app.paymentProductDetails.searchConsumer.buttons.enterInformation", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "Enter manually", comment: "Title of the enter manually button on the payment product screen.")
let enterManuallyButtonFormRow = FormRowButton(title: enterManuallyButtonTitle, target: self, action: #selector(enterManuallyButtonTapped))
enterManuallyButtonFormRow.buttonType = .secondary
enterManuallyButtonFormRow.isEnabled = self.hasLookup && !self.didFind && !self.fullData
self.formRows.insert(enterManuallyButtonFormRow, at: lastLookupIndex + 3)
let paymentSeparator = FormRowSeparator(text: nil)
paymentSeparator.isEnabled = true
self.formRows.append(paymentSeparator)
let termsAndConditionsIndex = self.formRows.index { (fr) -> Bool in
if let switchRow = fr as? FormRowSwitch {
return switchRow.field?.identifier == "termsAndConditions"
}
return false
}
if let termsAndConditionsIndex = termsAndConditionsIndex {
let termsAndConditionsRow = self.formRows[termsAndConditionsIndex]
termsAndConditionsRow.isEnabled = true
self.formRows.remove(at: termsAndConditionsIndex)
self.formRows.append(termsAndConditionsRow)
}
super.addExtraRows()
let enumerator = (self.formRows as NSArray).reverseObjectEnumerator()
enumerator.nextObject()
//(enumerator.nextObject() as! FormRow).isEnabled = (!self.hasLookup || self.didFind || self.fullData);
}
override func initializeFormRows() {
super.initializeFormRows()
var propertyNum = 0
let enumerator = (self.formRows as NSArray).objectEnumerator()
var row = enumerator.nextObject()
var newFormRows: [FormRow] = []
self.installmentPlanFields = 0;
var labels: [FormRow] = []
while (row != nil) {
if (!(row is FormRowLabel || row is FormRowSwitch)) {
row = enumerator.nextObject();
continue;
}
var propertyRows: [FormRow] = []
var label = row as! FormRow;
labels.append(label)
row = enumerator.nextObject()
while row != nil && !(row is FormRowLabel || row is FormRowSwitch) {
propertyRows.append(row as! FormRow)
row = enumerator.nextObject()
}
var item = self.inputData.paymentItem.fields.paymentProductFields[propertyNum]
if item.identifier == "installmentId" {
installmentPlanFields = propertyRows.count + 1
let separator = FormRowSeparator(text: nil)
separator.isEnabled = true
newFormRows.insert(contentsOf: propertyRows, at: 0)
newFormRows.insert(label, at: 0)
}
else if (item.usedForLookup) {
newFormRows.insert(contentsOf: propertyRows, at: installmentPlanFields)
newFormRows.insert(label, at: installmentPlanFields)
}
else {
newFormRows.append(label)
newFormRows.append(contentsOf: propertyRows.lazy.reversed())
}
if hasLookup && !didFind {
let isVisible = item.usedForLookup && !self.fullData || item.identifier == "installmentId"
label.isEnabled = isVisible
for nonLabelRow in propertyRows {
nonLabelRow.isEnabled = isVisible;
}
}
else {
let isVisible = !fullData || item.identifier == "installmentId"
label.isEnabled = isVisible
for nonLabelRow in propertyRows {
nonLabelRow.isEnabled = isVisible
}
if item.identifier == "termsAndConditions" {
if fullData {
label.isEnabled = true
}
}
}
propertyNum += 1
}
for row in newFormRows {
if let row = row as? FormRowList, row.items[0].value != "-1" && row.paymentProductField.identifier == "installmentId" {
let placeHolderText = NSLocalizedString("gc.general.paymentProductFields.installmentId.placeholder", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "Choose one", comment: "")
let placeHolderItem = ValueMappingItem(json: ["displayName":placeHolderText, "value": "-1", "displayElements": []])!
row.items.insert(placeHolderItem, at: 0)
row.selectedRow = row.items.map({ $0.value }).index(of: inputData.value(forField: "installmentId")) ?? 0
self.inputData.setValue(value: row.items[row.selectedRow].value, forField: "installmentId")
}
}
if self.inputData.unmaskedValue(forField: "termsAndConditions").isEmpty {
self.inputData.setValue(value: "false", forField: "termsAndConditions")
}
formRows = newFormRows
}
override func updateSwitchCell(_ cell: SwitchTableViewCell, row: FormRowSwitch) {
guard let field = row.field else {
return
}
if let error = field.errors.first {
var customError: ValidationError = error
if (field.identifier == "termsAndConditions") {
for err in field.errors {
if err is ValidationErrorTermsAndConditions {
customError = err
break
}
}
//customError = field.errors.first(where: { (err) -> Bool in (err is ValidationErrorTermsAndConditions) }) ?? error
}
else {
customError = error
}
cell.errorMessage = FormRowsConverter.errorMessage(for: customError, withCurrency: false)
} else {
cell.errorMessage = nil
}
}
override func registerReuseIdentifiers() {
super.registerReuseIdentifiers()
tableView.register(DetailedPickerViewTableViewCell.self, forCellReuseIdentifier: DetailedPickerViewTableViewCell.reuseIdentifier)
tableView.register(ReadonlyReviewCell.self, forCellReuseIdentifier: ReadonlyReviewCell.reuseIdentifier)
tableView.register(SeparatorTableViewCell.self, forCellReuseIdentifier: SeparatorTableViewCell.reuseIdentifier)
}
override func cell(for row: FormRowList, tableView: UITableView) -> PickerViewTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DetailedPickerViewTableViewCell.reuseIdentifier) as! DetailedPickerViewTableViewCell
cell.delegate = self
cell.dataSource = self
if let error = row.paymentProductField.errors.first, validation {
cell.errorMessage = FormRowsConverter.errorMessage(for: error, withCurrency: false)
}
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.currencyCode = context.amountOfMoney.currencyCode.rawValue
for m in row.items {
guard let amount = m.displayElements.first(where: { $0.id == "installmentAmount" })?.value else {
continue
}
guard let numberOfInstallments = m.displayElements.first(where: { $0.id == "numberOfInstallments" })?.value else {
continue;
}
guard let amountAsDouble = Double(amount) else {
continue
}
guard let amountAsString = currencyFormatter.string(from: NSNumber(value:amountAsDouble/100.0)) else {
continue
}
let selectionTextWithPlaceholders = NSLocalizedString("gc.general.paymentProductFields.installmentPlan.selectionTextTemplate", tableName: SDKConstants.kSDKLocalizable, bundle: AppConstants.sdkBundle, value: "{installmentAmount} in {numberOfInstallments} installments", comment: "")
let selectionTextWithPlaceholder = selectionTextWithPlaceholders.replacingOccurrences(of: "{installmentAmount}", with: "%@")
let selectionTextValue = selectionTextWithPlaceholder.replacingOccurrences(of: "{numberOfInstallments}", with: "%@")
let selectionMessage = String(format: selectionTextValue, amountAsString,numberOfInstallments)
m.displayName = selectionMessage
if let displayElementIndex = m.displayElements.index(where: { $0.id == "displayName" }) {
m.displayElements[displayElementIndex].value = selectionMessage
}
}
cell.items = row.items
cell.fieldIdentifier = row.paymentProductField.identifier
cell.currencyFormatter = currencyFormatter
let percentFormatter = NumberFormatter()
percentFormatter.numberStyle = .percent
percentFormatter.locale = Locale(identifier: context.locale!)
percentFormatter.minimumFractionDigits = 0
percentFormatter.maximumFractionDigits = 3
cell.percentFormatter = percentFormatter
cell.selectedRow = row.selectedRow
return cell
}
func cell(for row: FormRowReadonlyReview, tableView: UITableView) -> ReadonlyReviewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ReadonlyReviewCell.reuseIdentifier) as! ReadonlyReviewCell
cell.data = row.data
return cell
}
func cell(for row: FormRowSeparator, tableView: UITableView) -> SeparatorTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SeparatorTableViewCell.reuseIdentifier) as! SeparatorTableViewCell
cell.separatorText = row.text as NSString?
return cell
}
override func formRowCell(for row: FormRow, indexPath: IndexPath) -> UITableViewCell {
var cell: TableViewCell?
if let formRow = row as? FormRowReadonlyReview {
cell = self.cell(for: formRow, tableView: tableView) as TableViewCell
}
else if let formRow = row as? FormRowSeparator {
cell = self.cell(for: formRow, tableView: tableView)
}
else {
cell = super.formRowCell(for: row, indexPath: indexPath) as? TableViewCell
}
return cell!
}
}
| 49.306667 | 394 | 0.626903 |
5b9e8a39d86f58d5742ff0321423f6d0859b156b | 15,365 | /*
* Copyright 2015-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
import NIO
import NIOExtras
@testable import RSocketCore
import RSocketTestUtilities
protocol NIOServerTCPBootstrapProtocol {
/// Bind the `ServerSocketChannel` to `host` and `port`.
///
/// - parameters:
/// - host: The host to bind on.
/// - port: The port to bind on.
func bind(host: String, port: Int) -> EventLoopFuture<Channel>
}
extension ServerBootstrap: NIOServerTCPBootstrapProtocol{}
class EndToEndTests: XCTestCase {
static let defaultClientSetup = ClientSetupConfig(
timeBetweenKeepaliveFrames: 500,
maxLifetime: 5000,
metadataEncodingMimeType: "utf8",
dataEncodingMimeType: "utf8"
)
let host = "127.0.0.1"
var clientEventLoopGroup: EventLoopGroup { clientMultiThreadedEventLoopGroup as EventLoopGroup }
private var clientMultiThreadedEventLoopGroup: MultiThreadedEventLoopGroup!
private var serverMultiThreadedEventLoopGroup: MultiThreadedEventLoopGroup!
override func setUp() {
clientMultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
serverMultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
}
override func tearDownWithError() throws {
try clientMultiThreadedEventLoopGroup.syncShutdownGracefully()
try serverMultiThreadedEventLoopGroup.syncShutdownGracefully()
}
func makeServerBootstrap(
responderSocket: RSocket = TestRSocket(),
shouldAcceptClient: ClientAcceptorCallback? = nil,
file: StaticString = #file,
line: UInt = #line
) -> NIOServerTCPBootstrapProtocol {
return ServerBootstrap(group: serverMultiThreadedEventLoopGroup)
.childChannelInitializer { (channel) -> EventLoopFuture<Void> in
channel.pipeline.addHandlers([
ByteToMessageHandler(LengthFieldBasedFrameDecoder(lengthFieldBitLength: .threeBytes)),
LengthFieldPrepender(lengthFieldBitLength: .threeBytes),
]).flatMap {
channel.pipeline.addRSocketServerHandlers(
shouldAcceptClient: shouldAcceptClient,
makeResponder: { _ in responderSocket },
requesterLateFrameHandler: { XCTFail("server requester did receive late frame \($0)", file: file, line: line) },
responderLateFrameHandler: { XCTFail("server responder did receive late frame \($0)", file: file, line: line) }
)
}
}
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
}
func makeClientBootstrap(
responderSocket: RSocket = TestRSocket(),
config: ClientSetupConfig = EndToEndTests.defaultClientSetup,
connectedPromise: EventLoopPromise<RSocket>? = nil,
file: StaticString = #file,
line: UInt = #line
) -> NIOClientTCPBootstrapProtocol {
return ClientBootstrap(group: clientMultiThreadedEventLoopGroup)
.channelInitializer { (channel) -> EventLoopFuture<Void> in
channel.pipeline.addHandlers([
ByteToMessageHandler(LengthFieldBasedFrameDecoder(lengthFieldBitLength: .threeBytes)),
LengthFieldPrepender(lengthFieldBitLength: .threeBytes),
]).flatMap {
channel.pipeline.addRSocketClientHandlers(
config: config,
responder: responderSocket,
connectedPromise: connectedPromise,
requesterLateFrameHandler: { XCTFail("client requester did receive late frame \($0)", file: file, line: line) },
responderLateFrameHandler: { XCTFail("client responder did receive late frame \($0)", file: file, line: line) }
)
}
}
}
/// Bootstraps and connects a new server and client
/// - Returns: requester socket of the connected client
func setupAndConnectServerAndClient(
serverResponderSocket: RSocket = TestRSocket(),
shouldAcceptClient: ClientAcceptorCallback? = nil,
clientResponderSocket: RSocket = TestRSocket(),
clientConfig: ClientSetupConfig = EndToEndTests.defaultClientSetup,
file: StaticString = #file,
line: UInt = #line
) throws -> RSocket {
let server = makeServerBootstrap(
responderSocket: serverResponderSocket,
shouldAcceptClient: shouldAcceptClient
)
let serverChannel = try server.bind(host: host, port: 0).wait()
let port = try XCTUnwrap(serverChannel.localAddress?.port)
let clientConnected = clientEventLoopGroup.next().makePromise(of: RSocket.self)
return try makeClientBootstrap(responderSocket: clientResponderSocket, config: clientConfig, connectedPromise: clientConnected)
.connect(host: host, port: port)
.flatMap({ _ in clientConnected.futureResult })
.wait()
}
func testClientServerSetup() throws {
let setup = ClientSetupConfig(
timeBetweenKeepaliveFrames: 500,
maxLifetime: 5000,
metadataEncodingMimeType: "utf8",
dataEncodingMimeType: "utf8")
let clientDidConnect = self.expectation(description: "client did connect to server")
let server = makeServerBootstrap(shouldAcceptClient: { clientInfo in
XCTAssertEqual(clientInfo.timeBetweenKeepaliveFrames, setup.timeBetweenKeepaliveFrames)
XCTAssertEqual(clientInfo.maxLifetime, setup.maxLifetime)
XCTAssertEqual(clientInfo.metadataEncodingMimeType, setup.metadataEncodingMimeType)
XCTAssertEqual(clientInfo.dataEncodingMimeType, setup.dataEncodingMimeType)
clientDidConnect.fulfill()
return .accept
})
let port = try XCTUnwrap(try server.bind(host: host, port: 0).wait().localAddress?.port)
let channel = try makeClientBootstrap(config: setup)
.connect(host: host, port: port)
.wait()
XCTAssertTrue(channel.isActive)
self.wait(for: [clientDidConnect], timeout: 1)
}
func testMetadataPush() throws {
let request = self.expectation(description: "receive request")
let requester = try setupAndConnectServerAndClient(
serverResponderSocket: TestRSocket(metadataPush: { metadata in
request.fulfill()
XCTAssertEqual(metadata, Data("Hello World".utf8))
})
)
requester.metadataPush(metadata: Data("Hello World".utf8))
self.wait(for: [request], timeout: 1)
}
func testFireAndForget() throws {
let request = self.expectation(description: "receive request")
let requester = try setupAndConnectServerAndClient(
serverResponderSocket: TestRSocket(fireAndForget: { payload in
request.fulfill()
XCTAssertEqual(payload, "Hello World")
})
)
requester.fireAndForget(payload: "Hello World")
self.wait(for: [request], timeout: 1)
}
func testRequestResponseEcho() throws {
let request = self.expectation(description: "receive request")
let requester = try setupAndConnectServerAndClient(
serverResponderSocket: TestRSocket(requestResponse: { payload, output in
request.fulfill()
// just echo back
output.onNext(payload, isCompletion: true)
return TestUnidirectionalStream()
})
)
let response = self.expectation(description: "receive response")
let helloWorld: Payload = "Hello World"
let input = TestUnidirectionalStream { payload, isCompletion in
XCTAssertEqual(payload, helloWorld)
XCTAssertTrue(isCompletion)
response.fulfill()
}
_ = requester.requestResponse(payload: helloWorld, responderStream: input)
self.wait(for: [request, response], timeout: 1)
}
func testRequestResponseError() throws {
let request = self.expectation(description: "receive request")
let requester = try setupAndConnectServerAndClient(
serverResponderSocket: TestRSocket(requestResponse: { payload, output in
request.fulfill()
output.onError(.applicationError(message: "I don't like your request"))
return TestUnidirectionalStream()
})
)
let response = self.expectation(description: "receive response")
let helloWorld: Payload = "Hello World"
let input = TestUnidirectionalStream(onError: { error in
XCTAssertEqual(error, .applicationError(message: "I don't like your request"))
response.fulfill()
})
_ = requester.requestResponse(payload: helloWorld, responderStream: input)
self.wait(for: [request, response], timeout: 1)
}
func testChannelEcho() throws {
let request = self.expectation(description: "receive request")
var echo: TestUnidirectionalStream?
let requester = try setupAndConnectServerAndClient(
serverResponderSocket: TestRSocket(channel: { payload, initialRequestN, isCompletion, output in
request.fulfill()
XCTAssertEqual(initialRequestN, .max)
XCTAssertFalse(isCompletion)
echo = TestUnidirectionalStream.echo(to: output)
// just echo back
output.onNext(payload, isCompletion: false)
return echo!
})
)
let response = self.expectation(description: "receive response")
let input = TestUnidirectionalStream(onComplete: {
response.fulfill()
})
input.failOnUnexpectedEvent = false
let output = requester.channel(payload: "Hello", initialRequestN: .max, isCompleted: false, responderStream: input)
output.onNext(" ", isCompletion: false)
output.onNext("W", isCompletion: false)
output.onNext("o", isCompletion: false)
output.onNext("r", isCompletion: false)
output.onNext("l", isCompletion: false)
output.onNext("d", isCompletion: false)
output.onComplete()
self.wait(for: [request, response], timeout: 1)
XCTAssertEqual(["Hello", " ", "W", "o", "r", "l", "d", .complete], input.events)
}
func testChannelResponderError() throws {
let request = self.expectation(description: "receive request")
let requester = try setupAndConnectServerAndClient(
serverResponderSocket: TestRSocket(channel: { payload, initialRequestN, isCompletion, output in
request.fulfill()
XCTAssertEqual(initialRequestN, .max)
XCTAssertFalse(isCompletion)
output.onNext(payload, isCompletion: false)
output.onError(.applicationError(message: "enough is enough"))
return TestUnidirectionalStream()
})
)
let receivedOnNext = self.expectation(description: "receive onNext")
let receivedOnError = self.expectation(description: "receive onError")
let input = TestUnidirectionalStream(
onNext: { _, _ in receivedOnNext.fulfill() },
onError: { _ in receivedOnError.fulfill() })
let output = requester.channel(payload: "Hello", initialRequestN: .max, isCompleted: false, responderStream: input)
self.wait(for: [request, receivedOnNext, receivedOnError], timeout: 1)
XCTAssertEqual(input.events, ["Hello", .error(.applicationError(message: "enough is enough"))])
output.onComplete() // should not send a late frame (late frames will automatically fail)
}
func testStream() throws {
let request = self.expectation(description: "receive request")
let requester = try setupAndConnectServerAndClient(
serverResponderSocket: TestRSocket(stream: { payload, initialRequestN, output in
request.fulfill()
XCTAssertEqual(initialRequestN, .max)
XCTAssertEqual(payload, "Hello World!")
output.onNext("Hello", isCompletion: false)
output.onNext(" ", isCompletion: false)
output.onNext("W", isCompletion: false)
output.onNext("o", isCompletion: false)
output.onNext("r", isCompletion: false)
output.onNext("l", isCompletion: false)
output.onNext("d", isCompletion: true)
return TestUnidirectionalStream()
})
)
let response = self.expectation(description: "receive response")
let input = TestUnidirectionalStream(onNext: { _, isCompletion in
guard isCompletion else { return }
response.fulfill()
})
_ = requester.stream(payload: "Hello World!", initialRequestN: .max, responderStream: input)
self.wait(for: [request, response], timeout: 1)
XCTAssertEqual(input.events, ["Hello", " ", "W", "o", "r", "l", .next("d", isCompletion: true)])
}
func testStreamError() throws {
let request = self.expectation(description: "receive request")
let requester = try setupAndConnectServerAndClient(
serverResponderSocket: TestRSocket(stream: { payload, initialRequestN, output in
request.fulfill()
XCTAssertEqual(initialRequestN, .max)
XCTAssertEqual(payload, "Hello World!")
output.onNext("Hello", isCompletion: false)
output.onError(.applicationError(message: "enough for today"))
return TestUnidirectionalStream()
})
)
let response = self.expectation(description: "receive response")
let responseError = self.expectation(description: "receive error")
let input = TestUnidirectionalStream(onNext: { payload, isCompletion in
response.fulfill()
XCTAssertEqual(payload, "Hello")
}, onError: { error in
responseError.fulfill()
XCTAssertEqual(error, .applicationError(message: "enough for today"))
})
_ = requester.stream(payload: "Hello World!", initialRequestN: .max, responderStream: input)
self.wait(for: [request, response, responseError], timeout: 1)
}
}
| 46.702128 | 136 | 0.636121 |
b9750bb33427b6c2ef9caee693ec0037cc4b37a8 | 6,552 | //
// SensorCoreDataStorage.swift
// BLEMeteo
//
// Created by Sergey Kultenko on 09/11/2018.
// Copyright © 2018 Sergey Kultenko. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class SensorCoreDataStorage: ISensorDataStorage {
var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
// MARK: - ISensorDataStorage
func save(sensorDataUnit: SensorDataUnit, completion: @escaping (Error?) -> ()) {
container?.performBackgroundTask { context in
do {
_ = SensorDataEntity.saveDTOToSensorDataEntity(sensorData: sensorDataUnit, in: context)
try context.save()
} catch {
completion(error)
return
}
completion(nil)
}
}
func findSensorData(withType type: SensorDataType, from: Date?, till: Date?, completion: @escaping ([SensorDataUnit]) -> ()) {
container?.performBackgroundTask { [weak self] context in
let request: NSFetchRequest<SensorDataEntity> = SensorDataEntity.fetchRequest()
request.predicate = self?.getPredicateForConditions(type: type, from: from, till: till)
var foundSensorData = [SensorDataUnit]()
do {
let requestResult = try context.fetch(request)
if requestResult.count > 0 {
for sensorDataEntity in requestResult {
try foundSensorData.append(sensorDataEntity.createDTO())
}
}
} catch {
completion([])
}
completion(foundSensorData)
}
}
func findSensorData(withType type: SensorDataType, from: Date?, till: Date?, pointsMaxCount: Int, completion: @escaping ([SensorDataUnit]) -> ()) {
container?.performBackgroundTask { [weak self] context in
let request: NSFetchRequest<SensorDataEntity> = SensorDataEntity.fetchRequest()
request.predicate = self?.getPredicateForConditions(type: type, from: from, till: till)
request.sortDescriptors = [
NSSortDescriptor(key: "timestamp", ascending: true),
]
var foundSensorData = [SensorDataUnit]()
do {
let requestResult = try context.fetch(request)
if requestResult.count > 0 {
if requestResult.count > pointsMaxCount {
foundSensorData = self?.reduceSensorData(sensorData: requestResult, datefrom: from, datetill: till, pointsMaxCount: pointsMaxCount) ?? []
} else {
for sensorDataEntity in requestResult {
try foundSensorData.append(sensorDataEntity.createDTO())
}
}
}
} catch {
completion([])
}
completion(foundSensorData)
}
}
// Counting
func countSensorData(withType type: SensorDataType, from: Date?, till: Date?, completion: @escaping (Int?, Error?) -> ()) {
container?.performBackgroundTask { [weak self ] context in
let request: NSFetchRequest<SensorDataEntity> = SensorDataEntity.fetchRequest()
request.predicate = self?.getPredicateForConditions(type: type, from: from, till: till)
do {
let recordsCount = try context.count(for: request)
completion(recordsCount, nil)
} catch {
completion(nil, error)
}
}
}
func removeSensorData(withType type: SensorDataType?, from: Date?, till: Date?, completion: @escaping (Bool) -> ()) {
container?.performBackgroundTask { [weak self ] context in
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "SensorDataEntity")
request.predicate = self?.getPredicateForConditions(type: type, from: from, till: till)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
do {
try context.execute(deleteRequest)
try context.save()
} catch {
completion(false)
}
completion(true)
}
}
// MARK: - Utilities
private func getPredicateForConditions(type: SensorDataType?, from: Date?, till: Date?) -> NSPredicate {
var predicates = [NSPredicate]()
if let type = type {
predicates.append(NSPredicate(format: "type = %@", type.rawValue))
}
if from != nil {
predicates.append(NSPredicate(format: "timestamp >= %@", from! as NSDate))
}
if till != nil {
predicates.append(NSPredicate(format: "timestamp <= %@", till! as NSDate))
}
if predicates.count == 0 {
return NSPredicate(value: true)
} else {
return NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
}
}
private func reduceSensorData(sensorData: [SensorDataEntity], datefrom: Date?, datetill: Date?, pointsMaxCount: Int) -> [SensorDataUnit] {
guard let startDate = sensorData.first?.timestamp, let endDate = datetill ?? sensorData.last?.timestamp else {
return []
}
guard let typeString = sensorData.first?.type, let sensorDataType = SensorDataType(rawValue: typeString) else {
return []
}
var result = [SensorDataUnit]()
var pointsCount = 0
var accumulator = 0.0
let dateStep = endDate.timeIntervalSince(startDate) / Double(pointsMaxCount)
var nextPeriodThreshold: Date = startDate.addingTimeInterval(dateStep)
for sensorDataEntity in sensorData {
if let time = sensorDataEntity.timestamp, time > nextPeriodThreshold {
let pointTime = nextPeriodThreshold.addingTimeInterval(-dateStep/2.0)
let value: Double = pointsCount > 0 ? accumulator / Double(pointsCount) : 0.0
result.append(SensorDataUnit(type: sensorDataType, value: value, timeStamp: pointTime))
nextPeriodThreshold = nextPeriodThreshold.addingTimeInterval(dateStep)
accumulator = 0.0
pointsCount = 0
}
accumulator += sensorDataEntity.value
pointsCount += 1
}
return result
}
}
| 40.695652 | 165 | 0.585623 |
181079ab9f7cea4774ab55490cb31a3ee7f71694 | 1,092 | //
// SplashViewController.swift
// GyverLamp
//
// Created by Максим Казачков on 08.12.2020.
// Copyright © 2020 Maksim Kazachkov. All rights reserved.
//
import UIKit
class SplashViewController: UIViewController {
@IBOutlet var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
lamps.loadData()
var i: Float = 1
_ = Timer.scheduledTimer(withTimeInterval: 0.015, repeats: true) { timer in
if i != 52 {
self.nameLabel.text = "GVR\nLamp"
self.nameLabel.font = UIFont.boldSystemFont(ofSize: CGFloat(i))
self.nameLabel.alpha = CGFloat(i / 52)
i += 1
} else {
timer.invalidate()
sleep(1)
DispatchQueue.main.async(execute: {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "mainView") as! ViewController
UIApplication.shared.keyWindow?.rootViewController = vc
})
}
}
}
}
| 28 | 118 | 0.554945 |
ef13945108a1dc7a07fafd2295c9448ae360cff2 | 75,949 | //
// NCMBUser.swift
// NCMB
//
// Translated by OOPer in cooperation with shlab.jp, on 2019/05/01
//
///*
// Copyright 2017-2020 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// */
//
//#import <Foundation/Foundation.h>
import Foundation
//
//#import "NCMBObject.h"
//
//@class NCMBAnonymousUtils;
//@class NCMBQuery;
//
///**
// NCMBUserクラスは、ニフクラ mobile backend上に保存されたユーザデータを管理するクラスです。
// ユーザの新規登録やログイン/ログアウト、会員情報の更新・取得・削除を行います。
// また、パスワードリセットやメールアドレス認証のリクエスト送信も行います。
// */
//@interface NCMBUser : NCMBObject
public class NCMBUser: NCMBObject {
//
///** @name User */
//
///// ユーザ名
//@property (nonatomic, copy) NSString *userName;
////@property (nonatomic, strong, getter = getUserName, setter=setUserName:) NSString *userName;
//
///// パスワード
//@property (nonatomic, copy) NSString *password;
private var _password: String?
////@property (nonatomic, strong, getter = getPassword, setter=setPassword:) NSString *password;
//
///// メールアドレス
//@property (nonatomic, copy) NSString *mailAddress;
////@property (nonatomic, strong, getter = getMailAddress, setter=setMailAddress:) NSString *mailAddress;
//
///// NCMBUserオブジェクトの登録の有無
//@property (readonly, assign) BOOL isNew;
private(set) public var isNew: Bool = false
//
///// セッショントークン
//@property (nonatomic, copy) NSString *sessionToken;
public var sessionToken: String?
//
///**
// NCMBUserのインスタンスを新規生成
// @return 新規生成したNCMBUserのインスタンス
// */
//+ (NCMBUser *)user;
//
//
///**
// NCMBQueryのインスタンスを新規作成する
// @return userクラスがセットされたNCMBQueryインスタンスを返却する
// */
//+ (NCMBQuery*)query;
//
///**
// 現在ログインしているユーザ情報を取得する
// もしログインしているユーザーがいない場合にはnilが返ってくる
// @return 現在ログインしているユーザオブジェクト
// */
//+ (NCMBUser *)currentUser;
//
///**
// enableAutomaticUserを設定した場合に、anonymous認証による自動会員登録を実行する。
//
// enableAutomaticUserが設定されていない場合や、すでにログイン済みの会員が存在している場合はcurrentUserと同じ処理を行う。
//
// @param block anonymous認証による会員登録がリクエストされたあとに実行されるブロック
// */
//+ (void)automaticCurrentUserWithBlock:(NCMBUserResultBlock)block;
//
///**
// enableAutomaticUserを設定した場合に、anonymous認証による自動会員登録を実行する。
//
// enableAutomaticUserが設定されていない場合や、すでにログイン済みの会員が存在している場合はcurrentUserと同じ処理を行う。
//
// @param target anonymous認証による会員登録がリクエストされたあとに実行されるセレクタのターゲット
// @param selector anonymous認証による会員登録がリクエストされたあとに実行されるセレクタ
// */
//+ (void)automaticCurrentUserWithTarget:(id)target selector:(SEL)selector;
//
///**
// ユーザが認証済みかを判定
// @return BOOL型YES=認証済、NO=未認証
// */
//- (BOOL)isAuthenticated;
//
///**
// 匿名ユーザの自動生成を有効化
// */
//+ (void)enableAutomaticUser;
//
///** @name Signup */
//
///**
// ユーザの新規登録。必要があればエラーをセットし、取得することもできる。
// @param error 処理中に起きたエラーのポインタ
// */
//- (void)signUp:(NSError **)error;
//
///**
// ユーザを非同期で新規登録。新規登録し終わったら与えられたblockを呼び出す。
// @param block 通信後実行されるblock。blockは次の引数のシグネチャを持つ必要がある(NSError *error)
// errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)signUpInBackgroundWithBlock:(NCMBErrorResultBlock)block;
//
///**
// ユーザを非同期で新規登録。新規登録し終わったら指定されたコールバックを呼び出す。
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ。次のシグネチャを持つ必要がある。 (void)callbackWithResult:(NSError **)error
// errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)signUpInBackgroundWithTarget:(id)target selector:(SEL)selector;
//
///**
// googleのauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param googleInfo google認証に必要なauthData
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithGoogleToken:(NSDictionary *)googleInfo withBlock:(NCMBErrorResultBlock)block;
//
///**
// twitterのauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param twitterInfo twitter認証に必要なauthData
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithTwitterToken:(NSDictionary *)twitterInfo withBlock:(NCMBErrorResultBlock)block;
//
///**
// facebookのauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param facebookInfo facebook認証に必要なauthData
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithFacebookToken:(NSDictionary *)facebookInfo withBlock:(NCMBErrorResultBlock)block;
//
///**
// appleのauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param appleInfo apple認証に必要なauthData
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithAppleToken:(NSDictionary *)appleInfo withBlock:(NCMBErrorResultBlock)block;
//
//MARK: requestAuthenticationMail
///** @name requestAuthenticationMail */
//
///**
// 指定したメールアドレスに対して、会員登録を行うためのメールを送信するよう要求する。必要があればエラーをセットし、取得することもできる。
// @param email 指定するメールアドレス
// @param error 処理中に起きたエラーのポインタ
// */
//+ (void)requestAuthenticationMail:(NSString *)email
// error:(NSError **)error;
//
///**
// 指定したメールアドレスに対して、会員登録を行うためのメールを送信するよう要求する。終わったら指定されたコールバックを呼び出す。
// @param email 指定するメールアドレス
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ。次のシグネチャを持つ必要がある。 (void)callbackWithResult:(NSError **)error
// errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//+ (void)requestAuthenticationMailInBackground:(NSString *)email
// target:(id)target
// selector:(SEL)selector;
//
///**
// 指定したメールアドレスに対して、会員登録を行うためのメールを送信するよう要求する。終わったら与えられたblockを呼び出す。
// @param email 指定するメールアドレス
// @param block 通信後実行されるblock。blockは次の引数のシグネチャを持つ必要がある (NSError *error)
// errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//+ (void)requestAuthenticationMailInBackground:(NSString *)email
// block:(NCMBErrorResultBlock)block;
//
//
///** @name LogIn */
//
///**
// ユーザ名とパスワードを指定してログイン。必要があればエラーをセットし、取得することもできる。
// @param username ログイン時に指定するユーザ名
// @param password ログイン時に指定するパスワード
// @param error 処理中に起きたエラーのポインタ
// @return ログインしたユーザの情報
// */
//+ (NCMBUser *)logInWithUsername:(NSString *)username
// password:(NSString *)password
// error:(NSError **)error;
//
//
///**
// ユーザ名とパスワードを指定して非同期でログイン。ログインし終わったら指定されたコールバックを呼び出す。
// @param username ログイン時に指定するユーザ名
// @param password ログイン時に指定するパスワード
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ。次のシグネチャを持つ必要がある。(void)callbackWithResult:(NCMBUser *)user error:(NSError **)error
// userにはログインしたユーザの情報が渡される。errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//+ (void)logInWithUsernameInBackground:(NSString *)username
// password:(NSString *)password
// target:(id)target
// selector:(SEL)selector;
//
///**
// ユーザ名とパスワードを指定して非同期でログイン。ログインし終わったら与えられたblockを呼び出す。
// @param username ログイン時に指定するユーザ名
// @param password ログイン時に指定するパスワード
// @param block 通信後実行されるblock。blockは次の引数のシグネチャを持つ必要がある(NCMBUser *user, NSError *error) userにはログインしたユーザの情報が渡される。errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//+ (void)logInWithUsernameInBackground:(NSString *)username
// password:(NSString *)password
// block:(NCMBUserResultBlock)block;
//
///**
// メールアドレスとパスワードを指定してログイン。必要があればエラーをセットし、取得することもできる。
// @param email ログイン時に指定するメールアドレス
// @param password ログイン時に指定するパスワード
// @param error 処理中に起きたエラーのポインタ
// @return ログインしたユーザの情報
// */
//+ (NCMBUser *)logInWithMailAddress:(NSString *)email
// password:(NSString *)password
// error:(NSError **)error;
//
///**
// メールアドレスとパスワードを指定して非同期でログイン。ログインし終わったら与えられたコールバックを呼び出す。
// @param email ログイン時に指定するメールアドレス
// @param password ログイン時に指定するパスワード
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ。次のシグネチャを持つ必要がある。(void)callbackWithResult:(NCMBUser *)user error:(NSError **)error
// userにはログインしたユーザの情報が渡される。errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//+ (void)logInWithMailAddressInBackground:(NSString *)email
// password:(NSString *)password
// target:(id)target
// selector:(SEL)selector;
//
///**
// メールアドレスとパスワードを指定して非同期でログイン。ログインし終わったら与えられたblockを呼び出す。
// @param email ログイン時に指定するメールアドレス
// @param password ログイン時に指定するパスワード
// @param block 通信後実行されるblock。blockは次の引数のシグネチャを持つ必要がある(NCMBUser *user, NSError *error) userにはログインしたユーザの情報が渡される。errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//+ (void)logInWithMailAddressInBackground:(NSString *)email
// password:(NSString *)password
// block:(NCMBUserResultBlock)block;
//
//MARK: Logout
///** @name Logout */
//
///**
// ログアウト
// */
//+ (void)logOut;
//
///**
// 非同期でログアウトを行う
// @param block ログアウトのリクエストをした後に実行されるblock
// */
//+ (void)logOutInBackgroundWithBlock:(NCMBErrorResultBlock)block;
//
///** @name requestPasswordReset */
//
///**
// 指定したメールアドレスを持つユーザのパスワードリセットを要求。ユーザが存在した場合、パスワードをリセットし、再設定のメールを送信する。必要があればエラーをセットし、取得することもできる。
// @param email 指定するメールアドレス
// @param error 処理中に起きたエラーのポインタ
// */
//+ (void)requestPasswordResetForEmail:(NSString *)email
// error:(NSError **)error;
//
///**
// 指定したメールアドレスを持つユーザのパスワードリセットを非同期で要求。ユーザが存在した場合、パスワードをリセットし、再設定のメールを送信する。リセットし終わったら指定されたコールバックを呼び出す。
// @param email 指定するメールアドレス
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ。次のシグネチャを持つ必要がある。 (void)callbackWithResult:(NSNumber *)result error:(NSError **)error
// resultにはリセットの有無をNSNumber型で渡される。errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//+ (void)requestPasswordResetForEmailInBackground:(NSString *)email
// target:(id)target
// selector:(SEL)selector;
//
///**
// 指定したメールアドレスを持つユーザのパスワードリセットを非同期で要求。ユーザが存在した場合、パスワードをリセットし、再設定のメールを送信する。リセットし終わったら与えられたblockを呼び出す。
// @param email 指定するメールアドレス
// @param block 通信後実行されるblock。blockは次の引数のシグネチャを持つ必要がある (NSError *error)errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//+ (void)requestPasswordResetForEmailInBackground:(NSString *)email
// block:(NCMBErrorResultBlock)block;
//
///**
// 匿名会員を正規会員として同期で登録する。2回のAPIリクエストが発生する。objectiId,createDate,updateDate,authdata以外の情報を引き継ぐ。必要があればエラーをセットし、取得することもできる。
// @param userName 正規会員のユーザー名
// @param password 正規会員のパスワード
// @param error 処理中に起きたエラーのポインタ
// */
//- (void)signUpFromAnonymous:(NSString *)userName password:(NSString *)password error:(NSError **)error;
//
///**
// 匿名会員を正規会員として非同期で登録する。2回のAPIリクエストが発生する。objectiId,createDate,updateDate,authdata以外の情報を引き継ぐ。必要があればエラーをセットし、取得することもできる。
// @param userName 正規会員のユーザー名
// @param password 正規会員のパスワード
// @param block 通信後実行されるblock。blockは次の引数のシグネチャを持つ必要がある(NSError *error)
// errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)signUpFromAnonymousInBackgroundWithBlock:(NSString *)userName
// password:(NSString *)password
// block:(NCMBErrorResultBlock)block;
///**
// 匿名会員を正規会員として非同期で登録する。2回のAPIリクエストが発生する。objectiId,createDate,updateDate,authdata以外の情報を引き継ぐ。必要があればエラーをセットし、取得することもできる。
// @param userName 正規会員のユーザー名
// @param password 正規会員のパスワード
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ。次のシグネチャを持つ必要がある。 (void)callbackWithResult:(NSError **)error
// errorにはエラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)signUpFromAnonymousInBackgroundWithTarget:(NSString *)userName
// password:(NSString *)password
// target:(id)target
// selector:(SEL)selector;
//
//MARK: - link
///** @name link */
//
///**
// ログイン中のユーザー情報に、googleの認証情報を紐付ける
// @param googleInfo googleの認証情報(idとaccess_token)
// @param block 既存のauthDataのgoogle情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithGoogleToken:(NSDictionary *)googleInfo
// withBlock:(NCMBErrorResultBlock)block;
//
///**
// ログイン中のユーザー情報に、twitterの認証情報を紐付ける
// @param twitterInfo twitterの認証情報
// @param block 既存のauthDataのtwitter情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithTwitterToken:(NSDictionary *)twitterInfo
// withBlock:(NCMBErrorResultBlock)block;
//
///**
// ログイン中のユーザー情報に、facebookの認証情報を紐付ける
// @param facebookInfo facebookの認証情報
// @param block 既存のauthDataのfacebook情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithFacebookToken:(NSDictionary *)facebookInfo
// withBlock:(NCMBErrorResultBlock)block;
//
///**
// ログイン中のユーザー情報に、appleの認証情報を紐付ける
// @param appleInfo appleの認証情報
// @param block 既存のauthDataのapple情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithAppleToken:(NSDictionary *)appleInfo
// withBlock:(NCMBErrorResultBlock)block;
//
///**
// 会員情報に、引数で指定したtypeの認証情報が含まれているか確認する
// @param type 認証情報のtype(googleもしくはtwitter、facebook、apple、anonymous)
// @return 引数で指定したtypeの会員情報が含まれている場合はYESを返す
// */
//- (BOOL)isLinkedWith:(NSString *)type;
//
///**
// 会員情報から、引数で指定したtypeの認証情報を削除する
// @param type 認証情報のtype(googleもしくはtwitter、facebook、apple、anonymous)
// @param block エラー情報を返却するblock エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)unlink:(NSString *)type
// withBlock:(NCMBErrorResultBlock)block;
//
//MARK: - mailAddressConfirm
///** @name mailAddressConfirm */
//
///**
// メールアドレスが確認済みのものかを把握する
// @return メールアドレスが確認済みの場合はYESを返す
// */
//- (BOOL)isMailAddressConfirm;
//
//@end
///*
// Copyright 2017-2020 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// */
//
//#import "NCMBUser.h"
//
//#import "NCMBAnonymousUtils.h"
//#import "NCMBQuery.h"
//#import "NCMBACL.h"
//
//#import "NCMBURLSession.h"
//
//#import "NCMBObject+Private.h"
//#import "NCMBObject+Subclass.h"
//#import "NCMBRelation+Private.h"
//
//@implementation NCMBUser
//#define DATA_MAIN_PATH [NSHomeDirectory() stringByAppendingPathComponent:@"Library/"]
//#define DATA_CURRENTUSER_PATH [NSString stringWithFormat:@"%@/Private Documents/NCMB/currentUser", DATA_MAIN_PATH]
private static var DATA_CURRENTUSER_PATH = "\(DATA_MAIN_PATH)/Private Documents/NCMB/currentUser"
//
//MARK: - URL
//#define URL_LOGIN @"login"
//#define URL_LOGOUT @"logout"
private static let URL_LOGOUT = "logout"
//#define URL_USERS @"users"
//#define URL_AUTHENTICATION_MAIL @"requestMailAddressUserEntry"
private static let URL_AUTHENTICATION_MAIL = "requestMailAddressUserEntry"
//#define URL_PASSWOR_RESET @"requestPasswordReset"
private static let URL_PASSWORD_RESET = "requestPasswordReset"
//
//#define AUTH_TYPE_GOOGLE @"google"
private let AUTH_TYPE_GOOGLE = "google"
//#define AUTH_TYPE_TWITTER @"twitter"
private let AUTH_TYPE_TWITTER = "twitter"
//#define AUTH_TYPE_FACEBOOK @"facebook"
private let AUTH_TYPE_FACEBOOK = "facebook"
//#define AUTH_TYPE_ANONYMOUS @"Anonymous"
private let AUTH_TYPE_ANONYMOUS = "Anonymous"
//#define AUTH_TYPE_APPLE @"apple"
private let AUTH_TYPE_APPLE = "apple"
//
//static NCMBUser *currentUser = nil;
private static var _currentUser: NCMBUser? = nil
//static BOOL isEnableAutomaticUser = NO;
private static var isEnableAutomaticUser: Bool = false
//
//MARK: - init
//
////description用のメソッド
//- (NSDictionary*)getLocalData{
override func getLocalData() -> [String : Any] {
// NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[super getLocalData]];
var dic = super.getLocalData()
// if (self.userName){
if let userName = self.userName {
// [dic setObject:self.userName forKey:@"userName"];
dic["userName"] = userName
// }
}
// if (self.mailAddress){
if let mailAddress = self.mailAddress {
// [dic setObject:self.mailAddress forKey:@"mailAddress"];
dic["mailAddress"] = mailAddress
// }
}
// if (self.sessionToken){
if let sessionToken = self.sessionToken {
// [dic setObject:self.sessionToken forKey:@"sessionToken"];
dic["sessionToken"] = sessionToken
// }
}
// return dic;
return dic
//}
}
//
////NCMBUserはクラス名を指定しての初期化は出来ない
//+ (NCMBObject*)objectWithClassName:(NSString *)className{
// [[NSException exceptionWithName:NSInternalInconsistencyException reason:@"Cannot initialize a NCMBUser with a custom class name." userInfo:nil] raise];
// return nil;
//}
//
//- (instancetype)init{
public required init() {
// self = [self initWithClassName:@"user"];
super.init(className: "user")
// return self;
//}
}
//
//NOT implemented. Use `init()` instead.
//+ (NCMBUser *)user{
// NCMBUser *user = [[NCMBUser alloc] init];
// return user;
//}
//
//+ (NCMBQuery*)query{
public override static func query() -> NCMBQuery {
// return [NCMBQuery queryWithClassName:@"user"];
return NCMBQuery(className: "user")
//}
}
//
//MARK: - get/set
//
///**
// ユーザー名の設定
// @param userName ユーザー名
// */
public var userName: String? {
//- (void)setUserName:(NSString *)userName{
set {
// [self setObject:userName forKey:@"userName"];
self.setObject(newValue, forKey: "userName")
//}
}
//
///**
// ユーザー名の取得
// @return NSString型ユーザー名
// */
//- (NSString *)userName{
get {
// return [self objectForKey:@"userName"];
return self.object(forKey: "userName") as? String
//}
}
}
//
///**
// パスワードの設定
// @param password パスワード
// */
public var password: String? {
get {
return _password
}
//- (void)setPassword:(NSString *)password{
set {
// [self setObject:password forKey:@"password"];
self.setObject(newValue, forKey: "password")
//}
}
}
//
///**
// Eメールの設定
// @param mailAddress Eメール
// */
public var mailAddress: String? {
//- (void)setMailAddress:(NSString *)mailAddress{
set {
// [self setObject:mailAddress forKey:@"mailAddress"];
self.setObject(newValue, forKey: "mailAddress")
//}
}
//
///**
// Eメールの取得
// @return NSString型メールアドレス
// */
//- (NSString *)mailAddress{
get {
// return [self objectForKey:@"mailAddress"];
return self.object(forKey: "mailAddress") as? String
}
//}
}
//
///**
// セッショントークンの設定
// @param newSessionToken ユーザーのセッショントークンを設定する
// */
//- (void)setSessionToken:(NSString *)newSessionToken{
// _sessionToken = newSessionToken;
//}
//
//
///**
// 現在ログイン中のユーザーのセッショントークンを返す
// @return NSString型セッショントークン
// */
//+ (NSString *)getCurrentSessionToken{
internal static func getCurrentSessionToken() -> String? {
// if (currentUser != nil) {
if let user = _currentUser {
// return currentUser.sessionToken;
return user.sessionToken
// }
}
// return nil;
return nil
//}
}
//
///**
// 匿名ユーザの自動生成を有効化
// */
//+ (void)enableAutomaticUser{
public static func enableAutomaticUser() {
// isEnableAutomaticUser = TRUE;
isEnableAutomaticUser = false
//}
}
/**
現在ログインしているユーザ情報を取得
@return NCMBUser型ログイン中のユーザー
*/
public static var currentUser: NCMBUser? {
if _currentUser != nil {
return _currentUser
}
_currentUser = nil
//アプリ再起動などでcurrentUserがnilになった時は端末に保存したユーザ情報を取得、設定する。
if FileManager.default.fileExists(atPath: DATA_CURRENTUSER_PATH) {
_currentUser = NCMBUser.getFromFileCurrentUser()
}
return _currentUser
}
//+ (void)automaticCurrentUserWithBlock:(NCMBUserResultBlock)block{
public static func automaticCurrentUser(block: NCMBUserResultBlock?) {
// if ([self currentUser]) {
if let user = self.currentUser {
// if(block){
// block([self currentUser], nil);
block?(.success(user))
// }
// }
// //匿名ユーザーの自動生成がYESの時は匿名ユーザーでログインする
// else if (isEnableAutomaticUser) {
} else if isEnableAutomaticUser {
// isEnableAutomaticUser = NO;
isEnableAutomaticUser = false
// [NCMBAnonymousUtils logInWithBlock:^(NCMBUser *user, NSError *error) {
NCMBAnonymousUtils.logIn {result in
switch result {
case .success(let user):
// if (!error) {
// currentUser = user;
_currentUser = user
isEnableAutomaticUser = true
block?(.success(user))
// }
// isEnableAutomaticUser = YES;
// if (block){
// block(user, error);
case .failure(let error):
isEnableAutomaticUser = true
block?(.failure(error))
// }
}
// }];
}
// }
}
//}
}
//
//+ (void)automaticCurrentUserWithTarget:(id)target selector:(SEL)selector{
public static func automaticCurrentUser(target: AnyObject, selector: Selector) {
// if (!target || !selector){
// [NSException raise:@"NCMBInvalidValueException" format:@"target and selector must not be nil."];
// }
// NSMethodSignature *signature = [target methodSignatureForSelector:selector];
// NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
// [invocation setTarget:target];
// [invocation setSelector:selector];
// [self automaticCurrentUserWithBlock:^(NCMBUser *user, NSError *error) {
self.automaticCurrentUser {result in
switch result {
case .success(let user):
_ = target.perform(selector, with: user, with: nil)
case .failure(let error):
// [invocation retainArguments];
// [invocation setArgument:&user atIndex:2];
// [invocation setArgument:&error atIndex:3];
// [invocation invoke];
_ = target.perform(selector, with: nil, with: error)
}
// }];
}
//}
}
//
///**
// 認証済みか判定
// @return BOOL型YES=認証済、NO=未認証
// */
//- (BOOL)isAuthenticated{
var isAuthenticated: Bool {
// BOOL isAuthenticateFlag = FALSE;
var isAuthenticateFlag = false
// if (self.sessionToken) {
if self.sessionToken != nil {
// isAuthenticateFlag =TRUE;
isAuthenticateFlag = true
// }
}
// return isAuthenticateFlag;
return isAuthenticateFlag
//}
}
//
//MARK: - signUp
//
///**
// ユーザの新規登録。必要があればエラーをセットし、取得することもできる。
// @param error 処理中に起きたエラーのポインタ
// */
//- (void)signUp:(NSError **)error{
public func __signUp() throws {
fatalError("\(#function): Sync methods not supported")
// [self save:error];
//}
}
//
///**
// ユーザ の新規登録(非同期)
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpInBackgroundWithBlock:(NCMBErrorResultBlock)block{
public func signUpAsync(block: @escaping NCMBErrorResultBlock) {
// [self saveInBackgroundWithBlock:block];
self.saveAsync(block: block)
//}
}
//
///**
// target用ユーザの新規登録処理
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ
// */
//- (void)signUpInBackgroundWithTarget:(id)target selector:(SEL)selector{
public func signUpAsync(target: AnyObject, selector: Selector) {
// [self saveInBackgroundWithTarget:target selector:selector];
self.saveAsync(target: target, selector: selector)
//}
}
//
///**
// typeで指定したsns情報のauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param snsInfo snsの認証に必要なauthData
// @param type 認証情報のtype
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithToken:(NSDictionary *)snsInfo withType:(NSString *)type withBlock:(NCMBErrorResultBlock)block{
public func signUp(token snsInfo: [String: Any], type: String, block: NCMBErrorResultBlock?) {
// //既存のauthDataのtype情報のみ更新する
// NSMutableDictionary *userAuthData = [NSMutableDictionary dictionary];
var userAuthData: [String: Any] = [:]
// if([[self objectForKey:@"authData"] isKindOfClass:[NSDictionary class]]){
if let authData = self.object(forKey: "authData") as? [String: Any] {
// userAuthData = [NSMutableDictionary dictionaryWithDictionary:[self objectForKey:@"authData"]];
userAuthData = authData
// }
}
// [userAuthData setObject:snsInfo forKey:type];
userAuthData[type] = snsInfo
// [self setObject:userAuthData forKey:@"authData"];
self.setObject(userAuthData, forKey: "authData")
// [self signUpInBackgroundWithBlock:^(NSError *error) {
self.signUpAsync {error in
// if (error) {
if error != nil {
// [userAuthData removeObjectForKey:type];
userAuthData.removeValue(forKey: type)
// [self setObject:userAuthData forKey:@"authData"];
self.setObject(userAuthData, forKey: "authData")
// }
}
// [self executeUserCallback:block error:error];
block?(error)
// }];
}
//}
}
//
///**
// googleのauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param googleInfo google認証に必要なauthData
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithGoogleToken:(NSDictionary *)googleInfo withBlock:(NCMBErrorResultBlock)block{
public func signUp(googleToken googleInfo: [String: Any], block: NCMBErrorResultBlock?) {
// [self signUpWithToken:googleInfo withType:AUTH_TYPE_GOOGLE withBlock:block];
self.signUp(token: googleInfo, type: AUTH_TYPE_GOOGLE, block: block)
//}
}
//
///**
// twitterのauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param twitterInfo twitter認証に必要なauthData
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithTwitterToken:(NSDictionary *)twitterInfo withBlock:(NCMBErrorResultBlock)block{
public func signUp(twitterToken twitterInfo: [String: Any], block: NCMBErrorResultBlock?) {
// [self signUpWithToken:twitterInfo withType:AUTH_TYPE_TWITTER withBlock:block];
self.signUp(token: twitterInfo, type: AUTH_TYPE_TWITTER, block: block)
//}
}
//
///**
// facebookのauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param facebookInfo facebook認証に必要なauthData
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithFacebookToken:(NSDictionary *)facebookInfo withBlock:(NCMBErrorResultBlock)block{
public func signUp(facebookToken facebookInfo: [String: Any], block: NCMBErrorResultBlock?) {
// [self signUpWithToken:facebookInfo withType:AUTH_TYPE_FACEBOOK withBlock:block];
self.signUp(token: facebookInfo, type: AUTH_TYPE_FACEBOOK, block: block)
//}
}
//
///**
// appleのauthDataをもとにニフクラ mobile backendへの会員登録(ログイン)を行う
// @param appleInfo apple認証に必要なauthData
// @param block サインアップ後に実行されるblock
// */
//- (void)signUpWithAppleToken:(NSDictionary *)appleInfo withBlock:(NCMBErrorResultBlock)block{
public func signUp(appleToken appleInfo: [String: Any], block: NCMBErrorResultBlock?) {
// NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
let bundleIdentifier = Bundle.main.bundleIdentifier ?? ""
// NSDictionary *appleInfoParam = [appleInfo mutableCopy];
var appleInfoParam = appleInfo
// [appleInfoParam setValue:bundleIdentifier forKey:@"client_id"];
appleInfoParam["client_id"] = bundleIdentifier
// [self signUpWithToken:appleInfoParam withType:AUTH_TYPE_APPLE withBlock:block];
self.signUp(token: appleInfoParam, type: AUTH_TYPE_APPLE, block: block)
//}
}
//
//MARK: - signUpAnonymous
//
//- (void)signUpFromAnonymous:(NSString *)userName password:(NSString *)password error:(NSError **)error{
public func signUpFromAnonymous(userName: String, password: String) throws {
fatalError("\(#function): Sync methods not supported")
// //匿名ユーザーか判定し、正規用ユーザー作成
// NCMBUser *signUpUser = [self checkAnonymousUser];
// //正規ユーザーにデータをセットし、削除用ユーザー作成
// NCMBUser *deleteUser = [self setTheDataForUser:signUpUser userName:userName password:password];
// //新規ユーザー登録
// NSError *errorLocal = nil;
// [signUpUser signUp:&errorLocal];
// if(errorLocal){
// if (error){
// *error = errorLocal;
// }
// } else {
// //匿名ユーザー削除
// currentUser = deleteUser;
// [deleteUser delete:&errorLocal];
// if(errorLocal){
// if (error){
// *error = errorLocal;
// }
// } else {
// currentUser = signUpUser;
// }
// }
//}
}
//
//
//- (void)signUpFromAnonymousInBackgroundWithBlock:(NSString *)userName
public func signUpFromAnonymousAsync(userName: String,
password: String,
// password:(NSString *)password
// block:(NCMBErrorResultBlock)block{
block: NCMBErrorResultBlock?) {
// dispatch_queue_t queue = dispatch_queue_create("saveInBackgroundWithBlock", NULL);
// dispatch_async(queue, ^{
// //匿名ユーザーか判定し、正規用ユーザー作成
// NCMBUser *signUpUser = [self checkAnonymousUser];
guard let signUpUser = self.checkAnonymousUser() else {
block?(NCMBError.noLoginUser)
return
}
// //正規ユーザーにデータをセットし、削除用ユーザー作成
// NCMBUser *deleteUser = [self setTheDataForUser:signUpUser userName:userName password:password];
let deleteUser = self.setTheData(for: signUpUser, userName: userName, password: password)
// //新規ユーザー登録
// [signUpUser signUpInBackgroundWithBlock:^(NSError *error) {
signUpUser.signUpAsync {error in
// if(error){
if let error = error {
// [self executeUserCallback:block error:error];
block?(error)
// }else{
} else {
// //匿名ユーザー削除
// currentUser = deleteUser;
NCMBUser._currentUser = deleteUser
// [deleteUser deleteInBackgroundWithBlock:^(NSError *error) {
deleteUser.deleteAsync {error in
// currentUser = signUpUser;
NCMBUser._currentUser = signUpUser
// [self executeUserCallback:block error:error];
block?(error)
// }];
}
// }
}
// }];
}
// });
//}
}
//
///**
// target用ユーザの新規登録処理
// @param userName ユーザーネーム
// @param password パスワード
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ
// */
//- (void)signUpFromAnonymousInBackgroundWithTarget:(NSString *)userName password:(NSString *)password target:(id)target selector:(SEL)selector{
public func signUpFromAnonymousAsync(userName: String, password: String, target: AnyObject, selector: Selector) {
// NSMethodSignature* signature = [target methodSignatureForSelector: selector ];
// NSInvocation* invocation = [ NSInvocation invocationWithMethodSignature: signature ];
// [ invocation setTarget:target];
// [ invocation setSelector: selector ];
//
// [self signUpFromAnonymousInBackgroundWithBlock:userName password:password block:^(NSError *error) {
self.signUpFromAnonymousAsync(userName: userName, password: password) {error in
// [invocation setArgument:&error atIndex: 2 ];
// [invocation invoke ];
_ = target.perform(selector, with: error)
// }];
}
//}
}
//
//- (NCMBUser *)checkAnonymousUser{
private func checkAnonymousUser() -> NCMBUser? {
// NCMBUser * anonymousUser = [NCMBUser currentUser];
let anonymousUser = NCMBUser.currentUser
// if(![NCMBAnonymousUtils isLinkedWithUser:anonymousUser]){
if let anonymousUser = anonymousUser,
!NCMBAnonymousUtils.isLinked(user: anonymousUser) {
// [[NSException exceptionWithName:NSInternalInconsistencyException reason:@"This user is not a anonymous user." userInfo:nil] raise];
fatalError("This user is not a anonymous user.")
// }
}
// return anonymousUser;
return anonymousUser
//}
}
//
//- (NCMBUser *)setTheDataForUser:(NCMBUser *)signUpUser userName:(NSString *)userName password:(NSString *)password{
private func setTheData(for signUpUser: NCMBUser, userName: String, password: String) -> NCMBUser {
// //削除用ユーザー作成
// NCMBUser *deleteUser = [NCMBUser user];
let deleteUser = NCMBUser()
// deleteUser.objectId = signUpUser.objectId;
deleteUser.objectId = signUpUser.objectId
// deleteUser.sessionToken = signUpUser.sessionToken;
deleteUser.sessionToken = signUpUser.sessionToken
//
// //saiguUp用ユーザー作成。authData以外を引き継ぐ
// [signUpUser removeObjectForKey:@"authData"];
signUpUser.removeObject(forKey: "authData")
// for(id key in [signUpUser allKeys]){
for key in signUpUser.allKeys {
// [signUpUser setObject:[self convertToJSONFromNCMBObject:[signUpUser objectForKey:key]] forKey:key];
signUpUser.setObject(self.convertToJSONFromNCMBObject(signUpUser.object(forKey: key)), forKey: key)
// }
}
// signUpUser.userName = userName;
signUpUser.userName = userName
// signUpUser.password = password;
signUpUser.password = password
// signUpUser.objectId = nil;
signUpUser.objectId = nil
//
// return deleteUser;
return deleteUser
//}
}
//
//MARK: - requestAuthenticationMail
//
///**
// 同期で会員登録メールの要求を行う
// @param email メールアドレス
// @param error エラー
// */
//+ (void)requestAuthenticationMail:(NSString *)email
public static func __requestAuthenticationMail(_ email: String) throws {
// error:(NSError **)error{
fatalError("\(#function): Sync methods not supported")
// [NCMBUser requestMailFromNCMB:URL_AUTHENTICATION_MAIL mail:email error:error];
//}
}
//
///**
// 非同期で会員登録メールの要求を行う
// @param email メールアドレス
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ
// */
//+ (void)requestAuthenticationMailInBackground:(NSString *)email
public static func requestAuthenticationMailAsync(_ email: String,
// target:(id)target
target: AnyObject,
// selector:(SEL)selector{
selector: Selector) {
// [NCMBUser requestMailFromNCMB:URL_AUTHENTICATION_MAIL mail:email target:target selector:selector];
NCMBUser.requestMailFromNCMB(URL_AUTHENTICATION_MAIL, mail: email, target: target, selector: selector)
//}
}
//
///**
// 非同期で会員登録メールの要求を行う
// @param email メールアドレス
// @param block 登録メールの要求後に実行されるblock
// */
//+ (void)requestAuthenticationMailInBackground:(NSString *)email
public static func requestAuthenticationMailAsync(_ email: String,
// block:(NCMBErrorResultBlock)block{
block: NCMBErrorResultBlock?) {
// [NCMBUser requestMailFromNCMB:URL_AUTHENTICATION_MAIL mail:email block:block];
NCMBUser.requestMailFromNCMB(URL_AUTHENTICATION_MAIL, mail: email, block: block)
//}
}
//
//
//MARK: requestMailFromNCMB
//
///**
// target用ログイン処理
// @param path パス
// @param email メールアドレス
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ
// */
//+ (void)requestMailFromNCMB:(NSString *)path
private static func requestMailFromNCMB(_ path: String,
mail email: String,
// mail:(NSString *)email
// target:(id)target
target: AnyObject,
// selector:(SEL)selector{
selector: Selector) {
// NSMethodSignature* signature = [target methodSignatureForSelector: selector ];
// NSInvocation* invocation = [ NSInvocation invocationWithMethodSignature: signature ];
// [ invocation setTarget:target];
// [ invocation setSelector: selector ];
//
// NCMBErrorResultBlock block = ^(NSError *error) {
let block: NCMBErrorResultBlock = {error in
// [ invocation setArgument:&error atIndex: 2 ];
// [ invocation invoke ];
_ = target.perform(selector, with: error)
// };
}
//
// if ([path isEqualToString:URL_PASSWOR_RESET]){
if path == URL_PASSWORD_RESET {
// [NCMBUser requestPasswordResetForEmailInBackground:email block:block];
NCMBUser.requestPasswordResetAsync(forEmail: email, block: block)
// } else if ([path isEqualToString:URL_AUTHENTICATION_MAIL]){
} else if path == URL_AUTHENTICATION_MAIL {
// [NCMBUser requestAuthenticationMailInBackground:email block:block];
NCMBUser.requestAuthenticationMailAsync(email, block: block)
// }
}
//}
}
//
///**
// 同期メアド要求処理
// @param path パス
// @param email メールアドレス
// @param error エラー
// */
//+ (BOOL)requestMailFromNCMB:(NSString *)path mail:(NSString *)email
private static func __requestMailFromNCMB(_ path: String, mail email: String) throws {
fatalError("\(#function): Sync methods not supported")
// error:(NSError **)error{
// NCMBUser *user = [NCMBUser user];
// user.mailAddress = email;
//
// dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
// NSMutableDictionary *operations = [user beforeConnection];
// NSMutableDictionary *ncmbDic = [user convertToJSONDicFromOperation:operations];
// NSMutableDictionary *jsonDic = [user convertToJSONFromNCMBObject:ncmbDic];
//
// //通信開始
// NCMBRequest *request = [[NCMBRequest alloc] initWithURLString:path
// method:@"POST"
// header:nil
// body:jsonDic];
//
// // 通信
// NSError __block *sessionError = nil;
// NCMBURLSession *session = [[NCMBURLSession alloc] initWithRequestSync:request];
// [session dataAsyncConnectionWithBlock:^(NSDictionary *responseData, NSError *requestError){
// if (requestError){
// sessionError = requestError;
// }
// dispatch_semaphore_signal(semaphore);
// }];
//
// dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//
// bool isSuccess = YES;
// if (sessionError) {
// if(error){
// *error = sessionError;
// }
// isSuccess = NO;
// } return isSuccess;
//}
}
//
///**
// 非同期メアド要求処理
// @param path パス
// @param email メールアドレス
// @param block メアド要求後に実行されるblock
// */
//+ (void)requestMailFromNCMB:(NSString *)path
private static func requestMailFromNCMB(_ path: String,
// mail:(NSString *)email
mail email: String,
// block:(NCMBErrorResultBlock)block{
block: NCMBErrorResultBlock?) {
// NCMBUser *user = [NCMBUser user];
let user = NCMBUser()
// user.mailAddress = email;
user.mailAddress = email
//
// NSMutableDictionary *operations = [user beforeConnection];
let operations = user.beforeConnection()
// NSMutableDictionary *ncmbDic = [user convertToJSONDicFromOperation:operations];
let ncmbDic = user.convertToJSONDicFromOperation(operations)
// NSMutableDictionary *jsonDic = [user convertToJSONFromNCMBObject:ncmbDic];
let jsonDic = user.convertToJSONFromNCMBObject(ncmbDic) as! [String: Any]
//
// // リクエスト作成
// NCMBRequest *request = [[NCMBRequest alloc] initWithURLString:path
let request = NCMBRequest(urlString: path,
method: "POST",
header: nil,
body: jsonDic)
// method:@"POST"
// header:nil
// body:jsonDic];
//
// // 通信
// NCMBURLSession *session = [[NCMBURLSession alloc] initWithRequestAsync:request];
let session = NCMBURLSession(requestAsync: request)
// [session dataAsyncConnectionWithBlock:^(NSDictionary *responseData, NSError *requestError){
session.dataAsyncConnection {result in
switch result {
case .success(_):
block?(nil)
// if(block){
case .failure(let requestError):
// block(requestError);
block?(requestError)
// }
}
// }];
}
//}
}
//
//MARK: - logIn
//
//
///**
// 同期でログイン(ユーザ名とパスワード)を行う
// @param username ユーザー名
// @param password パスワード
// @param error エラー
// */
//+ (NCMBUser *)logInWithUsername:(NSString *)username
public static func __logIn(username: String,
// password:(NSString *)password
password: String) throws -> NCMBUser {
// error:(NSError **)error{
fatalError("\(#function): Sync methods not supported")
// return [NCMBUser ncmbLogIn:username mailAddress:nil password:password error:error];
//}
}
//
///**
// 非同期でログイン(ユーザ名とパスワード)を行う
// @param username ユーザー名
// @param password パスワード
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ
// */
//+ (void)logInWithUsernameInBackground:(NSString *)username
public static func logInAsync(username: String,
// password:(NSString *)password
password: String,
// target:(id)target
target: AnyObject,
// selector:(SEL)selector{
selector: Selector) {
// [NCMBUser ncmbLogInInBackground:username mailAddress:nil password:password target:target selector:selector];
NCMBUser.ncmbLogInAsync(username, mailAddress: nil, password: password, target: target, selector: selector)
//}
}
/**
非同期でログイン(ユーザ名とパスワード)を行う
@param username ユーザー名
@param password パスワード
@param block ログイン後に実行されるblock
*/
public static func logInAsync(username: String,
password: String,
block: NCMBUserResultBlock?) {
NCMBUser.ncmbLogInAsync(username, mailAddress: nil, password: password, block: block)
}
//MARK: - logInWithMailAddress
///**
// 同期でログイン(メールアドレスとパスワード)を行う
// @param email メールアドレス
// @param password パスワード
// @param error エラー
// */
//+ (NCMBUser *)logInWithMailAddress:(NSString *)email
public static func __logIn(mailAddress email: String,
// password:(NSString *)password
password: String) throws -> NCMBUser {
// error:(NSError **)error{
fatalError("\(#function): Sync methods not supported")
// return [NCMBUser ncmbLogIn:nil mailAddress:email password:password error:error];
//}
}
//
///**
// 非同期でログイン(メールアドレスとパスワード)を行う
// @param email メールアドレス
// @param password パスワード
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ
// */
//+ (void)logInWithMailAddressInBackground:(NSString *)email
public static func logInAsync(mailAddress email: String,
// password:(NSString *)password
password: String,
// target:(id)target
target: AnyObject,
// selector:(SEL)selector{
selector: Selector) {
// [NCMBUser ncmbLogInInBackground:nil mailAddress:email password:password target:target selector:selector];
NCMBUser.ncmbLogInAsync(nil, mailAddress: email, password: password, target: target, selector: selector)
//}
}
//
//
///**
// 非同期でログイン(メールアドレスとパスワード)を行う
// @param email メールアドレス
// @param password パスワード
// @param block ログイン後に実行されるblock
// */
//+ (void)logInWithMailAddressInBackground:(NSString *)email
public static func logInAsync(mailAddress email: String,
// password:(NSString *)password
password: String,
// block:(NCMBUserResultBlock)block{
block: @escaping NCMBUserResultBlock) {
// [NCMBUser ncmbLogInInBackground:nil mailAddress:email password:password block:block];
NCMBUser.ncmbLogInAsync(nil, mailAddress: email, password: password, block: block)
//}
}
//
//MARK: ncmbLogIn
//
//
///**
// targetログイン処理
// @param username ユーザー名
// @param email メールアドレス
// @param password パスワード
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ
// */
//+ (void)ncmbLogInInBackground:(NSString *)username
private static func ncmbLogInAsync(_ username: String?,
// mailAddress:(NSString *)email
mailAddress email: String?,
// password:(NSString *)password
password: String,
// target:(id)target
target: AnyObject,
// selector:(SEL)selector{
selector: Selector) {
//
// NSMethodSignature* signature = [target methodSignatureForSelector: selector ];
// NSInvocation* invocation = [ NSInvocation invocationWithMethodSignature: signature ];
// [ invocation setTarget:target];
// [ invocation setSelector: selector ];
//
// [NCMBUser ncmbLogInInBackground:username mailAddress:email password:password block:^(NCMBUser *user, NSError *error) {
NCMBUser.ncmbLogInAsync(username, mailAddress: email, password: password) {
result in
// [ invocation setArgument:&user atIndex: 2 ];
// [ invocation setArgument:&error atIndex: 3 ];
// [ invocation invoke ];
switch result {
case .success(let user):
_ = target.perform(selector, with: user, with: nil)
case .failure(let error):
_ = target.perform(selector, with: nil, with: error)
}
// }];
}
//}
}
//
///**
// ログイン用のNCMBRequestを返す
// */
//+(NCMBRequest*)createConnectionForLogin:(NSString*)username
private static func createConnectionForLogin(_ username: String?,
// mailAddress:(NSString*)mailAddress
mailAddress: String?,
// password:(NSString*)password{
password: String) -> NCMBRequest {
// //ログインパラメーター文字列の作成
// NSMutableArray *queryArray = [NSMutableArray array];
var queryArray: [String] = []
// NSArray *sortedQueryArray = nil;
// if (![username isKindOfClass:[NSNull class]] &&
// ![mailAddress isKindOfClass:[NSNull class]] &&
// ![password isKindOfClass:[NSNull class]]){
//
// [queryArray addObject:[NSString stringWithFormat:@"password=%@", password]];
queryArray.append("password=\(password)") //###escaping?
// if ([username length] != 0 && [mailAddress length] == 0){
if !(username?.isEmpty ?? true) && (mailAddress?.isEmpty ?? true) {
// [queryArray addObject:[NSString stringWithFormat:@"userName=%@", username]];
queryArray.append("userName=\(username!)") //###escaping?
// } else if ([username length] == 0 && [mailAddress length] != 0){
} else if (username?.isEmpty ?? true) && !(mailAddress?.isEmpty ?? true) {
// [queryArray addObject:[NSString stringWithFormat:@"mailAddress=%@", mailAddress]];
queryArray.append("mailAddress=\(mailAddress!)")
// }
}
// sortedQueryArray = [NSArray arrayWithArray:[queryArray sortedArrayUsingSelector:@selector(compare:)]];
let sortedQueryArray = queryArray.sorted()
// }
//
// //pathの作成
// NSString *path = @"";
// for (int i = 0; i< [sortedQueryArray count]; i++){
// NSString * query = [sortedQueryArray[i] stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"#[]@!&()*+,;\"<>\\%^`{|} \b\t\n\a\r"] invertedSet]];
func escape(query: String) -> String {
query.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "#[]@!&()*+,;\"<>\\%^`{|} \u{08}\t\n\u{07}\r").inverted)!
}
// if (i == 0){
// path = [path stringByAppendingString:[NSString stringWithFormat:@"%@", query]];
// } else {
// path = [path stringByAppendingString:[NSString stringWithFormat:@"&%@", query]];
// }
// }
let path = sortedQueryArray.map(escape(query:)).joined(separator: "&")
// NSString *url = [NSString stringWithFormat:@"login?%@", path];
let url = "login?\(path)"
// NCMBRequest *request = [[NCMBRequest alloc] initWithURLStringForUser:url
let request = NCMBRequest(urlStringForUser: url,
method: "GET",
header: nil,
body: nil)
// method:@"GET"
// header:nil
// body:nil];
// return request;
return request
//}
}
//
///**
// 同期ログイン処理
// @param username ユーザー名
// @param email メールアドレス
// @param password パスワード
// @param error エラー
// */
//+ (NCMBUser *)ncmbLogIn:(NSString *)username
// mailAddress:(NSString *)email
// password:(NSString *)password
// error:(NSError **)error{
private static func __ncmbLogIn(username: String?,
mailAddress email: String?,
password: String) throws -> NCMBUser {
fatalError("\(#function): Sync methods not supported")
// dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
// //通信開始
// NCMBRequest *request = [self createConnectionForLogin:username
// mailAddress:email
// password:password];
// // 通信
// NCMBUser __block *loginUser = nil;
// NSError __block *sessionError = nil;
// NCMBURLSession *session = [[NCMBURLSession alloc] initWithRequestSync:request];
// [session dataAsyncConnectionWithBlock:^(NSDictionary *responseData, NSError *requestError){
// if (!requestError){
// loginUser = [self responseLogIn:responseData];
// [self saveToFileCurrentUser:loginUser];
// } else {
// sessionError = requestError;
// }
// dispatch_semaphore_signal(semaphore);
// }];
//
// dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//
// if(error){
// *error = sessionError;
// }
// return loginUser;
//}
}
/**
非同期ログイン処理
@param username ユーザー名
@param email メールアドレス
@param password パスワード
@param block ログイン後に実行されるblock
*/
private static func ncmbLogInAsync(_ username: String?,
mailAddress email: String?,
password: String,
block: NCMBUserResultBlock?) {
//リクエストを作成
let request = self.createConnectionForLogin(username,
mailAddress: email,
password: password)
// 通信
let session = NCMBURLSession(requestAsync: request)
session.dataAsyncConnection {result in
switch result {
case .success(let responseData):
let loginUser = self.responseLogIn(responseData)
self.saveToFileCurrentUser(loginUser)
block?(.success(loginUser))
case .failure(let requestError):
block?(.failure(requestError))
}
}
}
/**
ログイン系のレスポンス処理
@param responseData サーバーからのレスポンスデータ
@return NCMBUser型サーバーのデータを反映させたユーザー
*/
private static func responseLogIn(_ responseData: Any) -> NCMBUser {
let loginUser = NCMBUser()
guard let responseDic = responseData as? [String: Any] else {
fatalError("ResponseData is not a Dictionary")
}
loginUser.afterFetch(responseDic, isRefresh: true)
return loginUser
}
//MARK: - logout
//
///**
// 同期でログアウトを行う
// */
///Do NOT use this method.
//+ (void)logOut{
public static func __logOut() {
fatalError("\(#function): Sync methods not supported")
// dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
// NSError *sessionError = nil;
// NCMBRequest *request = [[NCMBRequest alloc] initWithURLString:URL_LOGOUT
// method:@"GET"
// header:nil
// body:nil];
//
// NCMBURLSession *session = [[NCMBURLSession alloc] initWithRequestSync:request];
// [session dataAsyncConnectionWithBlock:^(NSDictionary *responseData, NSError *requestError){
// dispatch_semaphore_signal(semaphore);
// }];
//
// dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//
// if (sessionError==nil) {
// [self logOutEvent];
// }
//}
}
/**
非同期でログアウトを行う
@param block ログアウトのリクエストをした後に実行されるblock
*/
public static func logOutAsync(block: NCMBErrorResultBlock?) {
//リクエストを作成
let request = NCMBRequest(urlString: NCMBUser.URL_LOGOUT,
method: "GET",
header: nil,
body: nil)
// 通信
let session = NCMBURLSession(requestAsync: request)
session.dataAsyncConnection {result in
switch result {
case .success(_):
self.logOutEvent()
block?(nil)
case .failure(let requestError):
block?(requestError)
}
}
}
/**
ログアウトの処理
*/
internal static func logOutEvent() {
if _currentUser != nil {
_currentUser?.sessionToken = nil
_currentUser = nil
}
if FileManager.default.fileExists(atPath: DATA_CURRENTUSER_PATH) {
_ = try? FileManager.default.removeItem(atPath: DATA_CURRENTUSER_PATH)
}
}
//MARK: requestPasswordResetForEmail
//
///**
// 同期でパスワードリセット要求を行う。
// @param error エラー
// */
//+ (void)requestPasswordResetForEmail:(NSString *)email
public static func __requestPasswordReset(forEmail email: String) throws {
fatalError("\(#function): Sync methods not supported")
// error:(NSError **)error{
// [NCMBUser requestMailFromNCMB:URL_PASSWOR_RESET mail:email error:error];
//}
}
//
///**
// 非同期でパスワードリセット要求を行う。
// @param target 呼び出すセレクタのターゲット
// @param selector 呼び出すセレクタ
// */
//+ (void)requestPasswordResetForEmailInBackground:(NSString *)email
public static func requestPasswordResetAsync(forEmail email: String,
// target:(id)target
target: AnyObject,
// selector:(SEL)selector{
selector: Selector) {
// [NCMBUser requestMailFromNCMB:URL_PASSWOR_RESET mail:email target:target selector:selector];
NCMBUser.requestMailFromNCMB(URL_PASSWORD_RESET, mail: email, target: target, selector: selector)
//}
}
//
//
///**
// 非同期でパスワードリセット要求を行う。
// @param block リセット要求後に実行されるblock
// */
//+ (void)requestPasswordResetForEmailInBackground:(NSString *)email
public static func requestPasswordResetAsync(forEmail email: String,
// block:(NCMBErrorResultBlock)block{
block: NCMBErrorResultBlock?) {
// [NCMBUser requestMailFromNCMB:URL_PASSWOR_RESET mail:email block:block];
NCMBUser.requestMailFromNCMB(URL_PASSWORD_RESET, mail: email, block: block)
//}
}
//
//MARK: - file
//
//+(NCMBUser*)getFromFileCurrentUser{
private static func getFromFileCurrentUser() -> NCMBUser? {
// NCMBUser *user = [NCMBUser user];
let user = NCMBUser()
// [user setACL:[[NCMBACL alloc]init]];
user.acl = NCMBACL()
// NSError *error = nil;
do {
// NSString *str = [[NSString alloc] initWithContentsOfFile:DATA_CURRENTUSER_PATH encoding:NSUTF8StringEncoding error:&error];
// NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
let url = URL(fileURLWithPath: DATA_CURRENTUSER_PATH)
let data = try Data(contentsOf: url)
// NSMutableDictionary *dicData = [NSMutableDictionary dictionary];
//
// if ([data isKindOfClass:[NSData class]] && [data length] != 0){
//
// dicData = [NSJSONSerialization JSONObjectWithData:data
guard let dicData = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
print("response is not a Dictionary")
return nil
}
// options:NSJSONReadingAllowFragments
// error:&error];
// if ([[dicData allKeys] containsObject:@"data"] &&
if
let userData = dicData["data"] as? [String: Any],
// [[dicData allKeys] containsObject:@"className"] &&
let _ = dicData["className"] as? String,
// [dicData count] == 2){
dicData.count == 2
{
// //v1の形式でファイルを保存していた場合
// [user afterFetch:[NSMutableDictionary dictionaryWithDictionary:dicData[@"data"]] isRefresh:YES];
user.afterFetch(userData, isRefresh: true)
// } else {
} else {
// [user afterFetch:[NSMutableDictionary dictionaryWithDictionary:dicData] isRefresh:YES];
user.afterFetch(dicData, isRefresh: true)
// }
}
// }
} catch {
print(error)
return nil
}
// return user;
return user
//}
}
//
///**
// ログインユーザーをファイルに保存する
// @param user NCMBUSer型ファイルに保存するユーザー
// */
//+ (void) saveToFileCurrentUser:(NCMBUser *)user {
internal static func saveToFileCurrentUser(_ user: NCMBUser) {
// NSError *e = nil;
do {
// NSMutableDictionary *dic = [user toJSONObjectForDataFile];
let dic = user.toJSONObjectForDataFile()
// NSData *json = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:&e];
let json = try JSONSerialization.data(withJSONObject: dic)
// NSString *strSaveData = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
// [strSaveData writeToFile:DATA_CURRENTUSER_PATH atomically:YES encoding:NSUTF8StringEncoding error:&e];
let url = URL(fileURLWithPath: DATA_CURRENTUSER_PATH)
try json.write(to: url, options: .atomic)
// currentUser = user;
_currentUser = user
} catch let e {
print(e)
}
//}
}
//
///**
// ファイルに書き込むためユーザー情報作成
// @return NSMutableDictionary型ユーザー情報
// */
//- (NSMutableDictionary *)toJSONObjectForDataFile{
private func toJSONObjectForDataFile() -> [String: Any] {
// NSMutableDictionary *dic = [NSMutableDictionary dictionary];
var dic: [String: Any] = [:]
// for (id key in [estimatedData keyEnumerator]) {
for (key, value) in estimatedData {
// [dic setObject:[self convertToJSONFromNCMBObject:[estimatedData valueForKey:key]] forKey:key];
dic[key] = self.convertToJSONFromNCMBObject(value)
// }
}
// if (self.objectId) {
if let objectId = self.objectId {
// [dic setObject:self.objectId forKey:@"objectId"];
dic["objectId"] = objectId
// }
}
// if (self.createDate){
if let createDate = self.createDate {
// NSDateFormatter *df = [self createNCMBDateFormatter];
let df = self.createNCMBDateFormatter()
// [dic setObject:[df stringFromDate:self.createDate] forKey:@"createDate"];
dic["createDate"] = df.string(from: createDate)
// }
}
// if (self.updateDate){
if let updateDate = self.updateDate {
// NSDateFormatter *df = [self createNCMBDateFormatter];
let df = self.createNCMBDateFormatter()
// [dic setObject:[df stringFromDate:self.updateDate] forKey:@"updateDate"];
dic["updateDate"] = df.string(from: updateDate)
// }
}
// if(self.sessionToken){
if let token = self.sessionToken {
// [dic setObject:self.sessionToken forKey:@"sessionToken"];
dic["sessionToken"] = token
// }
}
// if (self.ACL) {
if let acl = self.acl {
// [dic setObject:self.ACL.dicACL forKey:@"acl"];
dic["acl"] = acl.dicACL
// }
}
// return dic;
return dic
//}
}
//
//
//MARK: - override
//
///**
// ローカルオブジェクトをリセットし、ログアウトする
// */
//- (void)afterDelete{
override func afterDelete() {
// if ([NCMBUser currentUser]!= nil && [NCMBUser.currentUser.objectId isEqualToString:self.objectId]) {
if let user = NCMBUser.currentUser, user.objectId == self.objectId {
// [NCMBUser logOutEvent];
NCMBUser.logOutEvent()
// }
}
// self.userName = nil;
self.userName = nil
// self.password = nil;
self.password = nil
// self.sessionToken = nil;
self.sessionToken = nil
// self.mailAddress = nil;
self.mailAddress = nil
// [super afterDelete];
super.afterDelete()
//}
}
//
//- (void)afterFetch:(NSMutableDictionary *)response isRefresh:(BOOL)isRefresh{
public override func afterFetch(_ response: [String : Any], isRefresh: Bool) {
// if ([response objectForKey:@"userName"]){
if let userName = response["userName"] as? String {
// self.userName = [response objectForKey:@"userName"];
self.userName = userName
// }
}
// if ([response objectForKey:@"mailAddress"]){
if let mailAddress = response["mailAddress"] as? String {
// self.mailAddress = [response objectForKey:@"mailAddress"];
self.mailAddress = mailAddress
// }
}
// if ([response objectForKey:@"sessionToken"]) {
if let sessionToken = response["sessionToken"] as? String {
// self.sessionToken = [response objectForKey:@"sessionToken"];
self.sessionToken = sessionToken
// }
}
// [super afterFetch:response isRefresh:YES];
super.afterFetch(response, isRefresh: true)
//}
}
//
///**
// オブジェクト更新後に操作履歴とestimatedDataを同期する
// @param response REST APIのレスポンスデータ
// @param operations 同期する操作履歴
// */
//-(void)afterSave:(NSDictionary*)response operations:(NSMutableDictionary *)operations{
override func afterSave(_ response: [String : Any], operations: NCMBOperationSet?) {
// [super afterSave:response operations:operations];
super.afterSave(response, operations: operations)
//
// //会員新規登録の有無
// //if ([response objectForKey:@"createDate"]&&![response objectForKey:@"updateDate"]){
// if ([response objectForKey:@"createDate"] && [response objectForKey:@"updateDate"]){
if let createDate = response["createDate"] as? String,
let updateDate = response["updateDate"] as? String {
// if ([response objectForKey:@"createDate"] == [response objectForKey:@"updateDate"]){
if createDate == updateDate {
// _isNew = YES;
isNew = true
// }
}
// }else{
} else {
// _isNew = NO;
isNew = false
// }
}
//
// //SNS連携(匿名ユーザー等はリクエスト時にuserNameを設定しない)時に必要
// if ([response objectForKey:@"userName"]){
if let userName = response["userName"] as? String {
// [estimatedData setObject:[response objectForKey:@"userName"] forKey:@"userName"];
estimatedData["userName"] = userName
// }
}
// //SNS連携時に必要
// //if (![[response objectForKey:@"authData"] isKindOfClass:[NSNull class]]){
// if ([response objectForKey:@"authData"]){
if let authData = response["authData"] {
// if([[response objectForKey:@"authData"] isKindOfClass:[NSNull class]]){
// } else {
if let authDataDic = authData as? [String: Any] {
// NSDictionary *authDataDic = [response objectForKey:@"authData"];
// NSMutableDictionary *converted = [NSMutableDictionary dictionary];
var converted: [String: Any] = [:]
// for (NSString *key in [[authDataDic allKeys] objectEnumerator]){
for (key, value) in authDataDic {
// [converted setObject:[self convertToNCMBObjectFromJSON:[authDataDic objectForKey:key]
converted[key] = self.convertToNCMBObjectFromJSON(value, convertKey: key)
// convertKey:key]
// forKey:key];
// }
}
// [estimatedData setObject:converted forKey:@"authData"];
estimatedData["authData"] = converted
// }
}
// if ([response objectForKey:@"sessionToken"]){
if let token = response["sessionToken"] as? String {
// [self setSessionToken:[response objectForKey:@"sessionToken"]];
self.sessionToken = token
// }
}
//
// [NCMBUser saveToFileCurrentUser:self];
NCMBUser.saveToFileCurrentUser(self)
// }
}
//
// if ([self.objectId isEqualToString:[NCMBUser currentUser].objectId]) {
if self.objectId == NCMBUser.currentUser?.objectId {
// self.sessionToken = [NCMBUser currentUser].sessionToken;
self.sessionToken = NCMBUser.currentUser?.sessionToken
// [NCMBUser saveToFileCurrentUser:self];
NCMBUser.saveToFileCurrentUser(self)
// }
}
//}
}
//
//MARK: - link
//
///**
// ログイン中のユーザー情報に、snsの認証情報を紐付ける
// @param snsInfo snsの認証情報
// @param type 認証情報のtype
// @param block 既存のauthDataのtype情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithToken:(NSDictionary *)snsInfo withType:(NSString *)type withBlock:(NCMBErrorResultBlock)block{
private func link(token snsInfo: [String: Any], type: String, block: @escaping NCMBErrorResultBlock) {
// // ローカルデータを取得
// NSMutableDictionary *localAuthData = [NSMutableDictionary dictionary];
// localAuthData = [NSMutableDictionary dictionaryWithDictionary:[self objectForKey:@"authData"]];
// }
var localAuthData = self.object(forKey: "authData") as? [String: Any] ?? [:]
// //既存のauthDataのtype情報のみ更新する
// NSMutableDictionary *userAuthData = [NSMutableDictionary dictionary];
var userAuthData: [String: Any] = [:]
// [userAuthData setObject:snsInfo forKey:type];
userAuthData[type] = snsInfo
// [self setObject:userAuthData forKey:@"authData"];
self.setObject(userAuthData, forKey: "authData")
// [self saveInBackgroundWithBlock:^(NSError *error) {
self.saveAsync {error in
// if (!error){
if error == nil {
// // ローカルデータから既にあるauthDataを取得して認証情報をマージ
// [localAuthData setObject:snsInfo forKey:type];
localAuthData[type] = snsInfo
// }
}
// [estimatedData setObject:localAuthData forKey:@"authData"];
self.estimatedData["authData"] = localAuthData
// // ログインユーザーをファイルに保存する
// [NCMBUser saveToFileCurrentUser:self];
NCMBUser.saveToFileCurrentUser(self)
// [self executeUserCallback:block error:error];
block(error)
// }];
}
//}
}
//
///**
// ログイン中のユーザー情報に、googleの認証情報を紐付ける
// @param googleInfo googleの認証情報(idとaccess_token)
// @param block 既存のauthDataのgoogle情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithGoogleToken:(NSDictionary *)googleInfo withBlock:(NCMBErrorResultBlock)block{
public func link(googleToken googleInfo: [String: Any], block: @escaping NCMBErrorResultBlock) {
// [self linkWithToken:googleInfo withType:AUTH_TYPE_GOOGLE withBlock:block];
self.link(token: googleInfo, type: AUTH_TYPE_GOOGLE, block: block)
//}
}
//
///**
// ログイン中のユーザー情報に、twitterの認証情報を紐付ける
// @param twitterInfo twitterの認証情報
// @param block 既存のauthDataのtwitter情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithTwitterToken:(NSDictionary *)twitterInfo withBlock:(NCMBErrorResultBlock)block{
public func link(twitterToken twitterInfo: [String: Any], block: @escaping NCMBErrorResultBlock) {
// [self linkWithToken:twitterInfo withType:AUTH_TYPE_TWITTER withBlock:block];
self.link(token: twitterInfo, type: AUTH_TYPE_TWITTER, block: block)
//}
}
//
///**
// ログイン中のユーザー情報に、facebookの認証情報を紐付ける
// @param facebookInfo facebookの認証情報
// @param block 既存のauthDataのfacebook情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithFacebookToken:(NSDictionary *)facebookInfo withBlock:(NCMBErrorResultBlock)block{
public func link(facebookToken facebookInfo: [String: Any], block: @escaping NCMBErrorResultBlock) {
// [self linkWithToken:facebookInfo withType:AUTH_TYPE_FACEBOOK withBlock:block];
self.link(token: facebookInfo, type: AUTH_TYPE_FACEBOOK, block: block)
//}
}
//
///**
// ログイン中のユーザー情報に、appleの認証情報を紐付ける
// @param appleInfo appleの認証情報
// @param block 既存のauthDataのapple情報のみ更新後実行されるblock。エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)linkWithAppleToken:(NSDictionary *)appleInfo withBlock:(NCMBErrorResultBlock)block{
public func link(appleToken appleInfo: [String: Any], block: @escaping NCMBErrorResultBlock) {
// NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
let bundleIdentifier = Bundle.main.bundleIdentifier ?? ""
// NSDictionary *appleInfoParam = [appleInfo mutableCopy];
var appleInfoParam = appleInfo
// [appleInfoParam setValue:bundleIdentifier forKey:@"client_id"];
appleInfoParam["client_id"] = bundleIdentifier
// [self linkWithToken:appleInfoParam withType:AUTH_TYPE_APPLE withBlock:block];
self.link(token: appleInfo, type: AUTH_TYPE_APPLE, block: block)
//}
}
//
///**
// 会員情報に、引数で指定したtypeの認証情報が含まれているか確認する
// @param type 認証情報のtype(googleもしくはtwitter、facebook、apple、anonymous)
// @return 引数で指定したtypeの会員情報が含まれている場合はYESを返す
// */
//- (BOOL)isLinkedWith:(NSString *)type{
public func isLinkedWith(_ type: String) -> Bool {
//
// BOOL isLinkerFlag = NO;
var isLinked = false
switch type {
// if ([type isEqualToString:AUTH_TYPE_GOOGLE]
case AUTH_TYPE_GOOGLE,
AUTH_TYPE_TWITTER,
AUTH_TYPE_FACEBOOK,
AUTH_TYPE_ANONYMOUS,
AUTH_TYPE_APPLE:
// || [type isEqualToString:AUTH_TYPE_TWITTER]
// || [type isEqualToString:AUTH_TYPE_FACEBOOK]
// || [type isEqualToString:AUTH_TYPE_ANONYMOUS]
// || [type isEqualToString:AUTH_TYPE_APPLE])
// {
// if ([self objectForKey:@"authData"] && [[self objectForKey:@"authData"] isKindOfClass:[NSDictionary class]]) {
if let authData = self.object(forKey: "authData") as? [String: Any] {
// if ([[self objectForKey:@"authData"] objectForKey:type]) {
if authData[type] != nil {
// isLinkerFlag = YES;
isLinked = true
// }
}
// }
}
// }
default:
break
}
// return isLinkerFlag;
return isLinked
//}
}
//
///**
// 会員情報から、引数で指定したtypeの認証情報を削除する
// @param type 認証情報のtype(googleもしくはtwitter、facebook、apple、anonymous)
// @param block エラー情報を返却するblock エラーがあればエラーのポインタが、なければnilが渡される。
// */
//- (void)unlink:(NSString *)type withBlock:(NCMBErrorResultBlock)block{
public func unlink(_ type: String, block: NCMBErrorResultBlock?) {
//
// // Userから指定したtypeの認証情報を削除する
// if ([[self objectForKey:@"authData"] isKindOfClass:[NSDictionary class]]){
if var authData = self.object(forKey: "authData") as? [String: Any] {
// // 指定したtypeと同じ認証情報の場合は削除する
// if ([self isLinkedWith:type]) {
if self.isLinkedWith(type) {
// // ローカルデータを取得
// NSMutableDictionary *localAuthData = [NSMutableDictionary dictionary];
// if([[self objectForKey:@"authData"] isKindOfClass:[NSDictionary class]]){
// localAuthData = [NSMutableDictionary dictionaryWithDictionary:[self objectForKey:@"authData"]];
// }
var localAuthData = authData
// // 削除する認証情報を取得
// NSMutableDictionary *authData = [NSMutableDictionary dictionaryWithDictionary:[self objectForKey:@"authData"]];
// // 引数で指定した認証情報を削除
// [authData setObject:[NSNull null] forKey:type];
authData[type] = NSNull()
//
// [self setObject:authData forKey:@"authData"];
self.setObject(authData, forKey: "authData")
// [self saveInBackgroundWithBlock:^(NSError *error) {
self.saveAsync {error in
// if (!error){
if error == nil {
// // ローカルデータから既にあるauthDataを取得して引数で指定した認証情報を削除してマージ
// [localAuthData removeObjectForKey:type];
localAuthData.removeValue(forKey: type)
// }
}
// [estimatedData setObject:localAuthData forKey:@"authData"];
self.estimatedData["authData"] = localAuthData
// // ログインユーザーをファイルに保存する
// [NCMBUser saveToFileCurrentUser:self];
NCMBUser.saveToFileCurrentUser(self)
// [self executeUserCallback:block error:error];
block?(error)
// }];
}
// } else {
} else {
// // 指定したtype以外の認証情報の場合はエラーを返す
// NSError *error = [NSError errorWithDomain:ERRORDOMAIN
let error = NSError(domain: ERRORDOMAIN,
// code:404003
code: 404003,
// userInfo:@{NSLocalizedDescriptionKey:@"other token type"}];
userInfo: [NSLocalizedDescriptionKey: "other token type"])
// [self executeUserCallback:block error:error];
block?(error)
// }
}
// } else {
} else {
// // 認証情報がない場合エラーを返す
// NSError *error = [NSError errorWithDomain:ERRORDOMAIN
let error = NSError(domain: ERRORDOMAIN,
code: 404003,
userInfo: [NSLocalizedDescriptionKey: "token not found"])
// code:404003
// userInfo:@{NSLocalizedDescriptionKey:@"token not found"}];
// [self executeUserCallback:block error:error];
block?(error)
// }
}
//}
}
//
//MARK: - mailAddressConfirm
//
///**
// メールアドレスが確認済みのものかを把握する
// @return メールアドレスが確認済みの場合はYESを返す
// */
//- (BOOL)isMailAddressConfirm{
public var isMailAddressConfirmed: Bool {
//
// return [self objectForKey:@"mailAddressConfirm"]!= [NSNull null] && [[self objectForKey:@"mailAddressConfirm"]boolValue] ? YES : NO;
if let mailAddressConfirm = self.object(forKey: "mailAddressConfirm") as? Bool {
return mailAddressConfirm
} else {
return false
}
//}
}
//
//@end
}
| 36.304493 | 207 | 0.626723 |
897a1ec9054caab3bba4a045e0dc5f7ae66b2408 | 201 | //
// Kind.swift
// FBSnapshotTestCase
//
// Created by Victor C Tavernari on 21/02/20.
//
import Foundation
public enum Kind: Equatable {
case event
case screen
case custom(String)
}
| 13.4 | 46 | 0.666667 |
715add9dee87895e1069850063bc55f84fc42b34 | 4,331 | import UIKit
import Mediasoup
import AVFoundation
import WebRTC
final class ViewController: UIViewController {
@IBOutlet var label: UILabel!
private let peerConnectionFactory = RTCPeerConnectionFactory()
private var mediaStream: RTCMediaStream?
private var audioTrack: RTCAudioTrack?
private var device: Device?
private var sendTransport: SendTransport?
private var producer: Producer?
override func viewDidLoad() {
super.viewDidLoad()
guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
self.label.text = "accept all permission requests and restart the app"
AVCaptureDevice.requestAccess(for: .audio) { _ in
}
return
}
mediaStream = peerConnectionFactory.mediaStream(withStreamId: TestData.MediaStream.mediaStreamId)
let audioTrack = peerConnectionFactory.audioTrack(withTrackId: TestData.MediaStream.audioTrackId)
mediaStream?.addAudioTrack(audioTrack)
self.audioTrack = audioTrack
let device = Device()
do {
print("isLoaded: \(device.isLoaded())")
try device.load(with: TestData.Device.rtpCapabilities)
print("isLoaded: \(device.isLoaded())")
let canProduceVideo = try device.canProduce(.video)
print("can produce video: \(canProduceVideo)")
let canProduceAudio = try device.canProduce(.audio)
print("can produce audio: \(canProduceAudio)")
let sctpCapabilities = try device.sctpCapabilities()
print("SCTP capabilities: \(sctpCapabilities)")
let rtpCapabilities = try device.rtpCapabilities()
print("RTP capabilities: \(rtpCapabilities)")
let sendTransport = try device.createSendTransport(
id: TestData.SendTransport.transportId,
iceParameters: TestData.SendTransport.iceParameters,
iceCandidates: TestData.SendTransport.iceCandidates,
dtlsParameters: TestData.SendTransport.dtlsParameters,
sctpParameters: nil,
appData: nil)
sendTransport.delegate = self
self.sendTransport = sendTransport
print("transport id: \(sendTransport.id)")
print("transport is closed: \(sendTransport.closed)")
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
if let producer = try? sendTransport.createProducer(for: audioTrack, encodings: nil, codecOptions: nil, appData: nil) {
self.producer = producer
producer.delegate = self
print("producer created")
producer.resume()
}
}
// try sendTransport.updateICEServers("[]")
// print("ICE servers updated")
//
// try sendTransport.restartICE(with: "{}")
// print("ICE restarted")
DispatchQueue.main.asyncAfter(deadline: .now() + 20) {
sendTransport.close()
print("transport is closed: \(sendTransport.closed)")
}
label.text = "OK"
} catch let error as MediasoupError {
switch error {
case let .unsupported(message):
label.text = "unsupported: \(message)"
case let .invalidState(message):
label.text = "invalid state: \(message)"
case let .invalidParameters(message):
label.text = "invalid parameters: \(message)"
case let .mediasoup(underlyingError):
label.text = "mediasoup: \(underlyingError)"
case .unknown(let underlyingError):
label.text = "unknown: \(underlyingError)"
@unknown default:
label.text = "unknown"
}
} catch {
label.text = error.localizedDescription
}
self.device = device
DispatchQueue.main.asyncAfter(deadline: .now() + 25) {
print("Deallocating SendTransport...")
self.sendTransport = nil
self.device = nil
print("device deallocated")
}
}
}
extension ViewController: SendTransportDelegate {
func onProduce(transport: Transport, kind: MediaKind, rtpParameters: String, appData: String,
callback: @escaping (String?) -> Void) {
print("on produce \(kind)")
}
func onProduceData(transport: Transport, sctpParameters: String, label: String,
protocol dataProtocol: String, appData: String, callback: @escaping (String?) -> Void) {
print("on produce data \(label)")
}
func onConnect(transport: Transport, dtlsParameters: String) {
print("on connect")
}
func onConnectionStateChange(transport: Transport, connectionState: TransportConnectionState) {
print("on connection state change: \(connectionState)")
}
}
extension ViewController: ProducerDelegate {
func onTransportClose(in producer: Producer) {
print("on transport close in \(producer)")
}
}
| 29.868966 | 123 | 0.725237 |
710276a2f9ce7850bf6f0b26187ef618ba134bae | 652 | //
// TimeFormatter.swift
// Movie Demo
//
// Created by Charles Reitz on 4/1/19.
//
import Foundation
extension DateFormatter {
static func defaultFormatter(format :String) -> DateFormatter {
let formatter = DateFormatter()
let loc = Locale(identifier: "en_US_POSIX")
formatter.locale = loc
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.dateFormat = format
return formatter
}
func dateFrom(date: Date?) -> String? {
guard let date = date else {
return nil
}
return self.string(from: date)
}
}
| 20.375 | 67 | 0.579755 |
383ea7b68113ac92ea8770273055ae4f1bb12643 | 1,096 | // swiftlint:disable nesting
import Foundation
struct MAString {
struct Scenes {
struct Categories {
static let title = String.localized(by: "scenes_categories_title")
static let mealCellSubtitle = String.localized(by: "scenes_categories_cell_subtitle")
private init() {}
}
struct Filter {
static let title = String.localized(by: "scenes_filter_title")
static let byArea = String.localized(by: "scenes_filter_by_area")
static let byIngredient = String.localized(by: "scenes_filter_by_ingredient")
private init() {}
}
private init() {}
}
struct Errors {
static let generic = String.localized(by: "errors_generic")
static let noConnection = String.localized(by: "errors_no_connection")
private init() {}
}
struct General {
static let loading = String.localized(by: "general_loading")
static let tryAgain = String.localized(by: "general_try_again")
private init() {}
}
private init() {}
}
| 27.4 | 97 | 0.623175 |
d7b178c87586df3d7fce0871dec00136600c0b50 | 8,712 | // Radix2CooleyTukey benchmark
//
// Originally written by @owensd. Used with his permission.
#if os(Linux)
import Glibc
#elseif os(Windows)
import MSVCRT
#else
import Darwin
#endif
import TestsUtils
public let benchmarks = [
BenchmarkInfo(
name: "Radix2CooleyTukey",
runFunction: run_Radix2CooleyTukey,
tags: [.validation, .algorithm],
setUpFunction: setUpRadix2CooleyTukey,
tearDownFunction: tearDownRadix2CooleyTukey,
legacyFactor: 48),
BenchmarkInfo(
name: "Radix2CooleyTukeyf",
runFunction: run_Radix2CooleyTukeyf,
tags: [.validation, .algorithm],
setUpFunction: setUpRadix2CooleyTukeyf,
tearDownFunction: tearDownRadix2CooleyTukeyf,
legacyFactor: 48),
]
//===----------------------------------------------------------------------===//
// Double Benchmark
//===----------------------------------------------------------------------===//
var double_input_real: UnsafeMutablePointer<Double>?
var double_input_imag: UnsafeMutablePointer<Double>?
var double_output_real: UnsafeMutablePointer<Double>?
var double_output_imag: UnsafeMutablePointer<Double>?
var double_temp_real: UnsafeMutablePointer<Double>?
var double_temp_imag: UnsafeMutablePointer<Double>?
let doubleN = 2_048
let doubleSize = { MemoryLayout<Double>.size * doubleN }()
func setUpRadix2CooleyTukey() {
let size = doubleSize
double_input_real = UnsafeMutablePointer<Double>.allocate(capacity: size)
double_input_imag = UnsafeMutablePointer<Double>.allocate(capacity: size)
double_output_real = UnsafeMutablePointer<Double>.allocate(capacity: size)
double_output_imag = UnsafeMutablePointer<Double>.allocate(capacity: size)
double_temp_real = UnsafeMutablePointer<Double>.allocate(capacity: size)
double_temp_imag = UnsafeMutablePointer<Double>.allocate(capacity: size)
}
func tearDownRadix2CooleyTukey() {
double_input_real?.deallocate()
double_input_imag?.deallocate()
double_output_real?.deallocate()
double_output_imag?.deallocate()
double_temp_real?.deallocate()
double_temp_imag?.deallocate()
}
func radix2CooleyTukey(_ level: Int,
input_real: UnsafeMutablePointer<Double>,
input_imag: UnsafeMutablePointer<Double>,
stride: Int, output_real: UnsafeMutablePointer<Double>,
output_imag: UnsafeMutablePointer<Double>,
temp_real: UnsafeMutablePointer<Double>,
temp_imag: UnsafeMutablePointer<Double>) {
if level == 0 {
output_real[0] = input_real[0];
output_imag[0] = input_imag[0];
return
}
let length = 1 << level
let half = length >> 1
radix2CooleyTukey(level - 1,
input_real: input_real,
input_imag: input_imag,
stride: stride << 1,
output_real: temp_real,
output_imag: temp_imag,
temp_real: output_real,
temp_imag: output_imag)
radix2CooleyTukey(level - 1,
input_real: input_real + stride,
input_imag: input_imag + stride,
stride: stride << 1,
output_real: temp_real + half,
output_imag: temp_imag + half,
temp_real: output_real + half,
temp_imag: output_imag + half)
for idx in 0..<half {
let angle = -Double.pi * Double(idx) / Double(half)
let _cos = cos(angle)
let _sin = sin(angle)
output_real[idx] = temp_real[idx] + _cos *
temp_real[idx + half] - _sin * temp_imag[idx + half]
output_imag[idx] = temp_imag[idx] + _cos *
temp_imag[idx + half] + _sin *
temp_real[idx + half]
output_real[idx + half] = temp_real[idx] - _cos *
temp_real[idx + half] + _sin *
temp_imag[idx + half]
output_imag[idx + half] = temp_imag[idx] - _cos *
temp_imag[idx + half] - _sin *
temp_real[idx + half]
}
}
func testDouble(iter: Int) {
let stride = 1
let size = doubleSize
let level = Int(log2(Double(doubleN)))
let input_real = double_input_real.unsafelyUnwrapped
let input_imag = double_input_imag.unsafelyUnwrapped
let output_real = double_output_real.unsafelyUnwrapped
let output_imag = double_output_imag.unsafelyUnwrapped
let temp_real = double_temp_real.unsafelyUnwrapped
let temp_imag = double_temp_imag.unsafelyUnwrapped
for _ in 0..<iter {
memset(UnsafeMutableRawPointer(input_real), 0, size)
memset(UnsafeMutableRawPointer(input_imag), 0, size)
memset(UnsafeMutableRawPointer(output_real), 0, size)
memset(UnsafeMutableRawPointer(output_imag), 0, size)
memset(UnsafeMutableRawPointer(temp_real), 0, size)
memset(UnsafeMutableRawPointer(temp_imag), 0, size)
radix2CooleyTukey(level,
input_real: input_real,
input_imag: input_imag,
stride: stride,
output_real: output_real,
output_imag: output_imag,
temp_real: temp_real,
temp_imag: temp_imag)
}
}
@inline(never)
public func run_Radix2CooleyTukey(_ n: Int) {
testDouble(iter: n)
}
//===----------------------------------------------------------------------===//
// Float Benchmark
//===----------------------------------------------------------------------===//
let floatN = 2_048
let floatSize = { MemoryLayout<Float>.size * floatN }()
var float_input_real: UnsafeMutablePointer<Float>?
var float_input_imag: UnsafeMutablePointer<Float>?
var float_output_real: UnsafeMutablePointer<Float>?
var float_output_imag: UnsafeMutablePointer<Float>?
var float_temp_real: UnsafeMutablePointer<Float>?
var float_temp_imag: UnsafeMutablePointer<Float>?
func setUpRadix2CooleyTukeyf() {
let size = floatSize
float_input_real = UnsafeMutablePointer<Float>.allocate(capacity: size)
float_input_imag = UnsafeMutablePointer<Float>.allocate(capacity: size)
float_output_real = UnsafeMutablePointer<Float>.allocate(capacity: size)
float_output_imag = UnsafeMutablePointer<Float>.allocate(capacity: size)
float_temp_real = UnsafeMutablePointer<Float>.allocate(capacity: size)
float_temp_imag = UnsafeMutablePointer<Float>.allocate(capacity: size)
}
func tearDownRadix2CooleyTukeyf() {
float_input_real?.deallocate()
float_input_imag?.deallocate()
float_output_real?.deallocate()
float_output_imag?.deallocate()
float_temp_real?.deallocate()
float_temp_imag?.deallocate()
}
func radix2CooleyTukeyf(_ level: Int,
input_real: UnsafeMutablePointer<Float>,
input_imag: UnsafeMutablePointer<Float>,
stride: Int, output_real: UnsafeMutablePointer<Float>,
output_imag: UnsafeMutablePointer<Float>,
temp_real: UnsafeMutablePointer<Float>,
temp_imag: UnsafeMutablePointer<Float>) {
if level == 0 {
output_real[0] = input_real[0];
output_imag[0] = input_imag[0];
return
}
let length = 1 << level
let half = length >> 1
radix2CooleyTukeyf(level - 1,
input_real: input_real,
input_imag: input_imag,
stride: stride << 1,
output_real: temp_real,
output_imag: temp_imag,
temp_real: output_real,
temp_imag: output_imag)
radix2CooleyTukeyf(level - 1,
input_real: input_real + stride,
input_imag: input_imag + stride,
stride: stride << 1,
output_real: temp_real + half,
output_imag: temp_imag + half,
temp_real: output_real + half,
temp_imag: output_imag + half)
for idx in 0..<half {
let angle = -Float.pi * Float(idx) / Float(half)
let _cos = cosf(angle)
let _sin = sinf(angle)
output_real[idx] = temp_real[idx] + _cos *
temp_real[idx + half] - _sin * temp_imag[idx + half]
output_imag[idx] = temp_imag[idx] + _cos *
temp_imag[idx + half] + _sin * temp_real[idx + half]
output_real[idx + half] = temp_real[idx] - _cos *
temp_real[idx + half] + _sin *
temp_imag[idx + half]
output_imag[idx + half] = temp_imag[idx] - _cos *
temp_imag[idx + half] - _sin *
temp_real[idx + half]
}
}
func testFloat(iter: Int) {
let stride = 1
let n = floatN
let size = floatSize
let input_real = float_input_real.unsafelyUnwrapped
let input_imag = float_input_imag.unsafelyUnwrapped
let output_real = float_output_real.unsafelyUnwrapped
let output_imag = float_output_imag.unsafelyUnwrapped
let temp_real = float_temp_real.unsafelyUnwrapped
let temp_imag = float_temp_imag.unsafelyUnwrapped
let level = Int(log2(Float(n)))
for _ in 0..<iter {
memset(UnsafeMutableRawPointer(input_real), 0, size)
memset(UnsafeMutableRawPointer(input_imag), 0, size)
memset(UnsafeMutableRawPointer(output_real), 0, size)
memset(UnsafeMutableRawPointer(output_imag), 0, size)
memset(UnsafeMutableRawPointer(temp_real), 0, size)
memset(UnsafeMutableRawPointer(temp_imag), 0, size)
radix2CooleyTukeyf(level,
input_real: input_real,
input_imag: input_imag,
stride: stride,
output_real: output_real,
output_imag: output_imag,
temp_real: temp_real,
temp_imag: temp_imag)
}
}
@inline(never)
public func run_Radix2CooleyTukeyf(_ n: Int) {
testFloat(iter: n)
}
| 32.629213 | 80 | 0.709481 |
0e96253d09d25c7f9bf01e8f39d012ac28fa01e2 | 5,612 | /*
MIT License
Copyright (c) 2017-2018 MessageKit
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
/// A protocol used by the `MessagesCollectionViewFlowLayout` object to determine
/// the size and layout of a `MessageCollectionViewCell` and its contents.
public protocol MessagesLayoutDelegate: AnyObject {
/// Specifies the size to use for a header view.
///
/// - Parameters:
/// - section: The section number of the header.
/// - messagesCollectionView: The `MessagesCollectionView` in which this header will be displayed.
///
/// - Note:
/// The default value returned by this method is a size of `GGSize.zero`.
func headerViewSize(for section: Int, in messagesCollectionView: MessagesCollectionView) -> CGSize
/// Specifies the size to use for a footer view.
///
/// - Parameters:
/// - section: The section number of the footer.
/// - messagesCollectionView: The `MessagesCollectionView` in which this footer will be displayed.
///
/// - Note:
/// The default value returned by this method is a size of `GGSize.zero`.
func footerViewSize(for section: Int, in messagesCollectionView: MessagesCollectionView) -> CGSize
/// Specifies the height for the `MessageContentCell`'s top label.
///
/// - Parameters:
/// - message: The `MessageType` that will be displayed for this cell.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// The default value returned by this method is zero.
func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat
/// Specifies the height for the message bubble's top label.
///
/// - Parameters:
/// - message: The `MessageType` that will be displayed for this cell.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// The default value returned by this method is zero.
func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat
/// Specifies the height for the `MessageContentCell`'s bottom label.
///
/// - Parameters:
/// - message: The `MessageType` that will be displayed for this cell.
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// The default value returned by this method is zero.
func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat
/// Custom cell size calculator for messages with MessageType.custom.
///
/// - Parameters:
/// - message: The custom message
/// - indexPath: The `IndexPath` of the cell.
/// - messagesCollectionView: The `MessagesCollectionView` in which this cell will be displayed.
///
/// - Note:
/// The default implementation will throw fatalError(). You must override this method if you are using messages with MessageType.custom.
func customCellSizeCalculator(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CellSizeCalculator
}
public extension MessagesLayoutDelegate {
func headerViewSize(for section: Int, in messagesCollectionView: MessagesCollectionView) -> CGSize {
return .zero
}
func footerViewSize(for section: Int, in messagesCollectionView: MessagesCollectionView) -> CGSize {
return .zero
}
func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 0
}
func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 0
}
func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
return 0
}
func customCellSizeCalculator(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CellSizeCalculator {
fatalError("Must return a CellSizeCalculator for MessageKind.custom(Any?)")
}
}
| 46 | 159 | 0.718817 |
f8db120e7748dba6856af253936a9a5fef545cbc | 3,985 | //
// Node+Transform.swift
//
// Created by Andrey Volodin on 23.07.16.
// Copyright © 2016. All rights reserved.
//
import Foundation
import SwiftMath
public extension Node {
@inline(__always)
internal func calculateTransformIfNeeded() {
guard isTransformDirty else {
return
}
// Get content size
// Convert position to points
var positionInPoints: p2d
if positionType.isBasicPoints {
// Optimization for basic points (most common case)
positionInPoints = position
} else {
positionInPoints = self.positionInPoints
}
// Get x and y
var x = Float(positionInPoints.x)
var y = Float(positionInPoints.y)
// Rotation values
// Change rotation code to handle X and Y
// If we skew with the exact same value for both x and y then we're simply just rotating
var cx: Float = 1
var sx: Float = 0
var cy: Float = 1
var sy: Float = 0
if rotationalSkewX != 0° || rotationalSkewY != 0° {
let radiansX = -rotationalSkewX.radians
let radiansY = -rotationalSkewY.radians
cx = cosf(radiansX)
sx = sinf(radiansX)
cy = cosf(radiansY)
sy = sinf(radiansY)
}
let needsSkewMatrix = skewX != 0° || skewY != 0°
var scaleFactor: Float = 1
if scaleType == .scaled {
scaleFactor = Setup.shared.UIScale
}
// optimization:
// inline anchor point calculation if skew is not needed
// Adjusted transform calculation for rotational skew
if !needsSkewMatrix && !anchorPointInPoints.isZero {
x += cy * -anchorPointInPoints.x * scaleX * scaleFactor + -sx * -anchorPointInPoints.y * scaleY
y += sy * -anchorPointInPoints.x * scaleX * scaleFactor + cx * -anchorPointInPoints.y * scaleY
}
// Build Transform Matrix
// Adjusted transfor m calculation for rotational skew
self.transform = Matrix4x4f(vec4(cy * scaleX * scaleFactor, sy * scaleX * scaleFactor, 0.0, 0.0),
vec4(-sx * scaleY * scaleFactor, cx * scaleY * scaleFactor, 0.0, 0.0),
vec4(0, 0, 1, 0),
vec4(x, y, vertexZ, 1))
// XXX: Try to inline skew
// If skew is needed, apply skew and then anchor point
if needsSkewMatrix {
let skewMatrix = Matrix4x4f(vec4(1.0, tanf(skewY.radians), 0.0, 0.0),
vec4(tanf(skewX.radians), 1.0, 0.0, 0.0),
vec4(0.0, 0.0, 1.0, 0.0),
vec4(0.0, 0.0, 0.0, 1.0))
self.transform = transform * skewMatrix
// adjust anchor point
if !anchorPointInPoints.isZero {
self.transform = transform.translated(by: vec3(-anchorPointInPoints))
}
}
isTransformDirty = false
}
/** Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates. The matrix is in points.
@see nodeToParentMatrix
*/
public var parentToNodeMatrix: Matrix4x4f {
return nodeToParentMatrix.inversed
}
/** Returns the world transform matrix. The matrix is in points.
@see nodeToParentMatrix
@see worldToNodeMatrix
*/
public var nodeToWorldMatrix: Matrix4x4f {
var t = self.nodeToParentMatrix
var p = parent
while p != nil {
t = p!.nodeToParentMatrix * t
p = p!.parent
}
return t
}
/** Returns the inverse world transform matrix. The matrix is in points.
@see nodeToWorldTransform
*/
public var worldToNodeMatrix: Matrix4x4f {
return nodeToWorldMatrix.inversed
}
}
| 36.227273 | 134 | 0.558344 |
e6508a73ef8c36cb6a3349a2062366496541e4f9 | 1,462 | //
// SettingsViewController.swift
// tipCalculator
//
// Created by Sofiya Taskova on 9/22/16.
// Copyright © 2016 Sofiya Taskova. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var defaultTipControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let defaults = UserDefaults.standard
let intValue = defaults.integer(forKey: "default_tip")
defaultTipControl.selectedSegmentIndex = intValue
}
@IBAction func updateDefaultTipAmount(_ sender: AnyObject) {
let defaults = UserDefaults.standard
defaults.set(defaultTipControl.selectedSegmentIndex, forKey: "default_tip")
defaults.synchronize()
}
/*
// 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.
}
*/
}
| 28.666667 | 106 | 0.681943 |
72eda23087e40137ad7caffa6f36267b950aa029 | 959 | //
// DouYuTests.swift
// DouYuTests
//
// Created by Beeda on 2017/8/5.
// Copyright © 2017年 com.xiao.douyu. All rights reserved.
//
import XCTest
@testable import DouYu
class DouYuTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.918919 | 111 | 0.627737 |
e8f0f702cfd8a20e4196be1df427402de579de94 | 508 | //
// ViewController.swift
// NNLogger
//
// Created by Nang Nguyen on 03/31/2019.
// Copyright (c) 2019 Nang Nguyen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.32 | 80 | 0.669291 |
e8a634a30d7a9cd88e9f6522009eaef75052c03a | 117 | public struct Message {
public var value: String
public init(value: String = "") {
self.value = value
}
}
| 14.625 | 35 | 0.632479 |
0a6780f00693af3d02685e41766dd43962ed7fda | 389 | //
// String+CapitalizeFirst.swift
// slate
//
// Created by Kyle Lee on 11/18/19.
// Copyright © 2019 Jason Fieldman. All rights reserved.
//
import Foundation
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).capitalized + dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
| 19.45 | 57 | 0.66581 |
030269d6a2f4a975798623ad65a6b3e628d37324 | 1,580 | //
// RadarChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class RadarChartDataSet: LineRadarChartDataSet, IRadarChartDataSet
{
private func initialize()
{
self.valueFont = NSUIFont.systemFont(ofSize: 13.0)
}
public required init()
{
super.init()
initialize()
}
public required override init(entries: [ChartDataEntry]?, label: String?)
{
super.init(entries: entries, label: label)
initialize()
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// flag indicating whether highlight circle should be drawn or not
/// **default**: false
open var drawHighlightCircleEnabled: Bool = false
/// `true` if highlight circle should be drawn, `false` ifnot
open var isDrawHighlightCircleEnabled: Bool { return drawHighlightCircleEnabled }
open var highlightCircleFillColor: NSUIColor? = NSUIColor.white
/// The stroke color for highlight circle.
/// If `nil`, the color of the dataset is taken.
open var highlightCircleStrokeColor: NSUIColor?
open var highlightCircleStrokeAlpha: CGFloat = 0.3
open var highlightCircleInnerRadius: CGFloat = 3.0
open var highlightCircleOuterRadius: CGFloat = 4.0
open var highlightCircleStrokeWidth: CGFloat = 2.0
}
| 26.333333 | 85 | 0.674684 |
bb8c19ce027ea167b892edb7257dc2d2d7198a2c | 2,354 | //
// AddAssignmentsViewController.swift
// M2M
//
// Created by Victor Zhong on 4/17/18.
// Copyright © 2018 Tran Sam. All rights reserved.
//
import UIKit
class AddAssignmentViewController: UIViewController {
// MARK: - Properties and Outlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var doneButton: UIButton!
var cellID = "exerciseCell"
var exercises = [ExerciseData]()
var selectedExercise: ExerciseData?
override func viewDidLoad() {
super.viewDidLoad()
doneButton.isEnabled = false
tableView.delegate = self
tableView.dataSource = self
tableView.allowsSelection = true
DispatchQueue.main.async {
self.exercises = SelectedExercise.manager.retrieveExerciseList()
self.tableView.reloadData()
}
}
@IBAction func backButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func doneButtonTapped(_ sender: UIButton) {
// TODO: Create assignment and send to user
guard let exerciseToPost = selectedExercise else { return }
AssignmentAPIHelper.manager.createAssignment(exerciseToPost, patientID: "ebb1f78c-704d-40c5-a1bc-8b024e3956bc", creatorID: "d19c786f-633a-44ba-98ab-0d207592c4cc", completionHandler: { _ in
self.dismiss(animated: true, completion: nil)
}, errorHandler: { print($0) })
}
}
extension AddAssignmentViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return exercises.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
let exerciseAtRow = exercises[indexPath.row]
cell.textLabel?.text = exerciseAtRow.exerciseName
cell.detailTextLabel?.text = exerciseAtRow.description
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedExercise = exercises[indexPath.row]
print("Selected Exercise: \(exercises[indexPath.row].exerciseName), chosen: \(selectedExercise!.exerciseName)")
doneButton.isEnabled = true
}
}
| 32.246575 | 196 | 0.695837 |
79cb6ff8dc4cd98b50015d2c660f566e68094179 | 899 | //
// NYCWifiTests.swift
// NYCWifiTests
//
// Created by Pritesh Nadiadhara on 2/23/21.
//
import XCTest
@testable import NYCWifi
class NYCWifiTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.441176 | 111 | 0.664071 |
2611b40c1de27c441c7ec1b5b87ae554d82a9b6d | 2,354 | //
// SceneDelegate.swift
// WWKS_Part1
//
// Created by Stephanie Chiu on 1/3/2021.
// Copyright © 2021 Stephanie Chiu. All rights reserved.
//
import UIKit
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).
guard let _ = (scene as? UIWindowScene) else { return }
}
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 necessarily 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.
}
}
| 43.592593 | 147 | 0.713679 |
50438ee3f44215dc33c0afd49c23463b5ba42bac | 2,906 | //
// OWindow.swift
// Outlander
//
// Created by Joe McBride on 12/5/21.
// Copyright © 2021 Joe McBride. All rights reserved.
//
import Cocoa
import Foundation
class OWindow: NSWindow {
@IBInspectable
public var titleColor = NSColor(hex: "#f5f5f5")! {
didSet {
updateTitle()
}
}
@IBInspectable
public var titleBackgroundColor: NSColor? {
didSet {
updateTitle()
}
}
@IBInspectable
public var titleFont = NSFont(name: "Helvetica", size: 14)! {
didSet {
updateTitle()
}
}
var gameContext: GameContext?
var lastKeyWasMacro = false
func registerKeyHandlers(_ gameContext: GameContext) {
self.gameContext = gameContext
NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
if self.macroKeyDown(with: $0) {
self.lastKeyWasMacro = true
return nil
}
self.lastKeyWasMacro = false
return $0
}
NSEvent.addLocalMonitorForEvents(matching: .keyUp) {
if self.lastKeyWasMacro {
self.lastKeyWasMacro = false
return nil
}
return $0
}
}
func macroKeyDown(with event: NSEvent) -> Bool {
// handle keyDown only if current window has focus, i.e. is keyWindow
guard NSApplication.shared.keyWindow === self else { return false }
guard let found = gameContext?.findMacro(description: event.macro) else {
return false
}
gameContext?.events2.sendCommand(Command2(command: found.action))
return true
}
func updateTitle() {
guard let windowContentView = contentView else {
return
}
guard let contentSuperView = windowContentView.superview else {
return
}
let titleView = findViewInSubview(contentSuperView.subviews, ignoreView: windowContentView, test: { view in
view is NSTextField
})
guard let titleText = titleView as? NSTextField else {
return
}
var attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: titleColor,
]
if let bg = titleBackgroundColor {
attributes[.backgroundColor] = bg
}
titleText.attributedStringValue = NSAttributedString(string: title, attributes: attributes)
}
func findViewInSubview(_ subviews: [NSView], ignoreView: NSView, test: (NSView) -> Bool) -> NSView? {
for v in subviews {
if test(v) {
return v
} else if v != ignoreView {
if let found = findViewInSubview(v.subviews as [NSView], ignoreView: ignoreView, test: test) {
return found
}
}
}
return nil
}
}
| 26.18018 | 115 | 0.568135 |
61e74869224323aa0998314431e9df0c1d74241e | 862 | //
// ThemeButton.swift
// iOS Example
//
// Copyright © 2018 Coinbase All rights reserved.
//
import UIKit
class ThemeButton: UIButton {
@IBInspectable var color: UIColor = Colors.green
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
initialSetup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
initialSetup()
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = color
}
// MARK: - Private Methods
private func initialSetup() {
backgroundColor = color
layer.cornerRadius = 4
titleLabel?.font = UIFont(name: Fonts.medium, size: 15)
setTitleColor(UIColor.white, for: .normal)
}
}
| 18.73913 | 63 | 0.554524 |
7636f09604743d17de97e3cda38cbd26fa0e1c10 | 796 | //
// SelectPhotoCell.swift
// InstagramClone
//
// Created by David on 2020/8/8.
// Copyright © 2020 David. All rights reserved.
//
import UIKit
class SelectPhotoCell: UICollectionViewCell {
let photoImageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
iv.backgroundColor = .lightGray
return iv
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(photoImageView)
photoImageView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 24.121212 | 188 | 0.688442 |
b9b540fd489027b560ef60f11a831e7b85b26984 | 1,219 | @testable import novawallet
import RobinHood
final class ExtrinsicOperationFactoryStub: ExtrinsicOperationFactoryProtocol {
func submitAndWatch(_ closure: @escaping ExtrinsicBuilderClosure, signer: SigningWrapperProtocol) -> CompoundOperationWrapper<String> {
let txHash = Data(repeating: 7, count: 32).toHex(includePrefix: true)
return CompoundOperationWrapper.createWithResult(txHash)
}
func submit(_ closure: @escaping ExtrinsicBuilderIndexedClosure, signer: SigningWrapperProtocol, numberOfExtrinsics: Int) -> CompoundOperationWrapper<[SubmitExtrinsicResult]> {
let txHash = Data(repeating: 7, count: 32).toHex(includePrefix: true)
return CompoundOperationWrapper.createWithResult([.success(txHash)])
}
func estimateFeeOperation(_ closure: @escaping ExtrinsicBuilderIndexedClosure, numberOfExtrinsics: Int) -> CompoundOperationWrapper<[FeeExtrinsicResult]> {
let dispatchInfo = RuntimeDispatchInfo(dispatchClass: "Extrinsic",
fee: "10000000000",
weight: 10005000)
return CompoundOperationWrapper.createWithResult([.success(dispatchInfo)])
}
}
| 48.76 | 180 | 0.716161 |
08e7c5483517cba8ed50e86bf4f80db51fc29e83 | 5,750 | //
// CornerPointView.swift
// ImageCropper
//
// Created by Abdul Rehman on 1/19/21.
//
import UIKit
class CornerpointView: UIView {
// MARK: - PROPERTIES
var delegate: CornerpointProtocol?
private var dragger: UIPanGestureRecognizer!
private var dragStart: CGPoint!
var centerPoint: CGPoint? {
didSet(oldPoint) {
if let newCenter = centerPoint {
isHidden = false
center = newCenter
} else {
isHidden = true
}
}
}
// MARK: - METHODS
init(color: CGColor, cornersSize: CGSize) {
super.init(frame:CGRect.zero)
setupViews(color: color, cornersSize: cornersSize)
}
init(color: CGColor, cornersSize: CGSize, cornersLineWidth: CGFloat, cornerPosition: CornerPosition) {
super.init(frame:CGRect.zero)
setupViews(color: color, cornersSize: cornersSize, cornersLineWidth: cornersLineWidth, cornerPosition: cornerPosition)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setupViews(color: CGColor, cornersSize: CGSize) {
dragger = UIPanGestureRecognizer(target: self as AnyObject,
action: #selector(handleCornerDrag(_:)))
addGestureRecognizer(dragger)
//Make the corner point view big enough to drag with a finger.
bounds.size = CGSize(width: 30, height: 30)
//Add a layer to the view to draw an outline for this corner point.
let newLayer = CALayer()
newLayer.position = CGPoint(x: layer.bounds.midX, y: layer.bounds.midY)
newLayer.bounds.size = cornersSize
newLayer.borderWidth = 1.0
newLayer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor
newLayer.backgroundColor = color
layer.addSublayer(newLayer)
}
private func setupViews(color: CGColor, cornersSize: CGSize, cornersLineWidth: CGFloat, cornerPosition: CornerPosition) {
dragger = UIPanGestureRecognizer(target: self as AnyObject,
action: #selector(handleCornerDrag(_:)))
addGestureRecognizer(dragger)
//Make the corner point view big enough to drag with a finger.
bounds.size = CGSize(width: 30, height: 30)
//Add a layer to the view to draw an outline for this corner point.
let newLayer = CAShapeLayer()
let linePath = UIBezierPath()
switch cornerPosition {
case .topLeft:
linePath.move(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY))
linePath.addLine(to: CGPoint(x: layer.bounds.midX + cornersSize.width, y: layer.bounds.midY))
linePath.move(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY))
linePath.addLine(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY + cornersSize.height))
case .topRight:
linePath.move(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY))
linePath.addLine(to: CGPoint(x: layer.bounds.midX - cornersSize.width, y: layer.bounds.midY))
linePath.move(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY))
linePath.addLine(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY + cornersSize.height))
case .bottomLeft:
linePath.move(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY))
linePath.addLine(to: CGPoint(x: layer.bounds.midX + cornersSize.width, y: layer.bounds.midY))
linePath.move(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY))
linePath.addLine(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY - cornersSize.height))
case .bottomRight:
linePath.move(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY))
linePath.addLine(to: CGPoint(x: layer.bounds.midX - cornersSize.width, y: layer.bounds.midY))
linePath.move(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY))
linePath.addLine(to: CGPoint(x: layer.bounds.midX, y: layer.bounds.midY - cornersSize.height))
}
newLayer.lineWidth = cornersLineWidth
newLayer.strokeColor = color
newLayer.path = linePath.cgPath
layer.addSublayer(newLayer)
}
//-------------------------------------------------------------------------------------------------------
@objc func handleCornerDrag(_ thePanner: UIPanGestureRecognizer) {
switch thePanner.state {
case .began:
dragStart = centerPoint
thePanner.setTranslation(CGPoint.zero,
in: self)
case .changed:
//println("In view dragger changed at \(newPoint)")
centerPoint = CGPoint(x: dragStart.x + thePanner.translation(in: self).x,
y: dragStart.y + thePanner.translation(in: self).y)
//If we have a delegate, notify it that this corner has moved.
//This code uses "optional binding" to convert the optional "cornerpointDelegate" to a required
//variable "theDelegate". If cornerpointDelegate == nil, the code that follows is skipped.
if let theDelegate = delegate {
theDelegate.cornerHasChanged(self)
}
default:
break;
}
}
}
protocol CornerpointProtocol {
func cornerHasChanged(_: CornerpointView)
}
enum CornerPosition: Int {
case topLeft = 0, topRight, bottomRight, bottomLeft
}
public enum CornerShape {
case square, line
}
| 40.492958 | 126 | 0.604696 |
9ce63352ff66f578c09a890ac2b53e6ccfa59e27 | 2,172 | //
// AppDelegate.swift
// Sample
//
// Created by Omar Hassan on 11/20/19.
// Copyright © 2019 Omar Hassan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.212766 | 285 | 0.754144 |
c1a3b15b5c56e9902d9b32d3cff202b8e2aab0db | 3,549 | import UIKit
public protocol Drawing: Touching {
var canvas: DrawableView? { get set }
var path: UIBezierPath { get }
}
extension Drawing {
public var view: UIView? {
return canvas?.view
}
}
public protocol Viewable {
var view: UIView { get }
}
extension UIView: Viewable {
public var view: UIView {
return self
}
}
public protocol Drawable {
var drawingLayer: CAShapeLayer { get }
var drawing: Drawing? { get set }
func update(path: UIBezierPath?)
}
extension Drawable {
public func update(path: UIBezierPath?) {
guard let path = path else {
drawingLayer.path = nil
return
}
let newPath = path.copy() as! UIBezierPath
drawingLayer.path = newPath.CGPath
}
}
public typealias DrawableView = protocol<Drawable, Viewable>
public class DrawingView: UIView, Drawable {
public var drawing: Drawing? = nil {
willSet {
if newValue == nil {
drawing?.canvas = nil
}
}
didSet {
//to avoid retain cycle between drawing and the view
weak var weakSelf = self
drawing?.canvas = weakSelf
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.addSublayer(backgroundLayer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy public var drawingLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.strokeColor = UIColor.blackColor().CGColor
layer.fillColor = UIColor.clearColor().CGColor
layer.backgroundColor = nil
layer.lineWidth = 2
self.layer.addSublayer(layer)
return layer
}()
lazy public var backgroundLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.strokeColor = UIColor.blackColor().CGColor
layer.fillColor = UIColor.clearColor().CGColor
layer.backgroundColor = nil
layer.lineWidth = 2
return layer
}()
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
drawing?.touchesBegan(touches, withEvent: event)
update(drawing?.path)
}
override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
drawing?.touchesMoved(touches, withEvent: event)
update(drawing?.path)
}
override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
drawing?.touchesEnded(touches, withEvent: event)
update(drawing?.path)
completePath(drawing?.path)
}
override public func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
drawing?.touchesCancelled(touches, withEvent: event)
update(nil)
}
func completePath(path: UIBezierPath?) {
guard let path = path?.copy() as? UIBezierPath else { return }
if let backgroundPath = backgroundLayer.path {
path.appendPath(UIBezierPath(CGPath: backgroundPath))
}
backgroundLayer.path = path.CGPath
}
}
public class DrawingViewController: UIViewController {
override public func viewDidLoad() {
view.backgroundColor = UIColor.whiteColor()
}
public var drawingView: DrawingView {
return view as! DrawingView
}
override public func loadView() {
view = DrawingView()
}
}
| 26.288889 | 94 | 0.618202 |
69282d2d7fdcfd4095aa7b4040c9afa15fb2cd4d | 986 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS REGENERATED BY EASY BINDINGS, ONLY MODIFY IT WITHIN USER ZONES
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//--- START OF USER ZONE 1
//--- END OF USER ZONE 1
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
func transient_AutoLayoutProjectDocument_unplacedPackagesCountString (
_ self_unplacedPackageCount : Int
) -> String {
//--- START OF USER ZONE 2
return "+ \(self_unplacedPackageCount)"
//--- END OF USER ZONE 2
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 39.44 | 120 | 0.269777 |
ffe80d7881f681f32e1c6f74aa3259339d9f4637 | 5,410 | import Dispatch
import Nimble
import Quick
@testable import ReactiveSwift
private class Object {
var value: Int = 0
}
class UnidirectionalBindingSpec: QuickSpec {
override func spec() {
describe("BindingTarget") {
var token: Lifetime.Token!
var lifetime: Lifetime!
beforeEach {
token = Lifetime.Token()
lifetime = Lifetime(token)
}
describe("closure binding target") {
var target: BindingTarget<Int>?
var optionalTarget: BindingTarget<Int?>?
var value: Int?
beforeEach {
target = BindingTarget(lifetime: lifetime, action: { value = $0 })
optionalTarget = BindingTarget(lifetime: lifetime, action: { value = $0 })
value = nil
}
describe("non-optional target") {
it("should pass through the lifetime") {
expect(target!.lifetime).to(beIdenticalTo(lifetime))
}
it("should trigger the supplied setter") {
expect(value).to(beNil())
target!.action(1)
expect(value) == 1
}
it("should accept bindings from properties") {
expect(value).to(beNil())
let property = MutableProperty(1)
target! <~ property
expect(value) == 1
property.value = 2
expect(value) == 2
}
}
describe("target of optional value") {
it("should pass through the lifetime") {
expect(optionalTarget!.lifetime).to(beIdenticalTo(lifetime))
}
it("should trigger the supplied setter") {
expect(value).to(beNil())
optionalTarget!.action(1)
expect(value) == 1
}
it("should accept bindings from properties") {
expect(value).to(beNil())
let property = MutableProperty(1)
optionalTarget! <~ property
expect(value) == 1
property.value = 2
expect(value) == 2
}
}
describe("optional LHS binding with non-nil LHS at runtime") {
it("should pass through the lifetime") {
expect(target.bindingTarget.lifetime).to(beIdenticalTo(lifetime))
}
it("should accept bindings from properties") {
expect(value).to(beNil())
let property = MutableProperty(1)
optionalTarget <~ property
expect(value) == 1
property.value = 2
expect(value) == 2
}
}
describe("optional LHS binding with nil LHS at runtime") {
it("should pass through the empty lifetime") {
let nilTarget: BindingTarget<Int>? = nil
expect(nilTarget.bindingTarget.lifetime).to(beIdenticalTo(Lifetime.empty))
}
}
}
describe("key path binding target") {
var target: BindingTarget<Int>!
var object: Object!
beforeEach {
object = Object()
target = BindingTarget(lifetime: lifetime, object: object, keyPath: \.value)
}
it("should pass through the lifetime") {
expect(target.lifetime).to(beIdenticalTo(lifetime))
}
it("should trigger the supplied setter") {
expect(object.value) == 0
target.action(1)
expect(object.value) == 1
}
it("should accept bindings from properties") {
expect(object.value) == 0
let property = MutableProperty(1)
target <~ property
expect(object.value) == 1
property.value = 2
expect(object.value) == 2
}
}
it("should not deadlock on the same queue") {
var value: Int?
let target = BindingTarget(on: UIScheduler(),
lifetime: lifetime,
action: { value = $0 })
let property = MutableProperty(1)
target <~ property
expect(value) == 1
}
it("should not deadlock on the main thread even if the context was switched to a different queue") {
var value: Int?
let queue = DispatchQueue(label: #file)
let target = BindingTarget(on: UIScheduler(),
lifetime: lifetime,
action: { value = $0 })
let property = MutableProperty(1)
queue.sync {
_ = target <~ property
}
expect(value).toEventually(equal(1))
}
it("should not deadlock even if the value is originated from the same queue indirectly") {
var value: Int?
let key = DispatchSpecificKey<Void>()
DispatchQueue.main.setSpecific(key: key, value: ())
let mainQueueCounter = Atomic(0)
let setter: (Int) -> Void = {
value = $0
mainQueueCounter.modify { $0 += DispatchQueue.getSpecific(key: key) != nil ? 1 : 0 }
}
let target = BindingTarget(on: UIScheduler(),
lifetime: lifetime,
action: setter)
let scheduler = QueueScheduler.makeForTesting()
let property = MutableProperty(1)
target <~ property.producer
.start(on: scheduler)
.observe(on: scheduler)
expect(value).toEventually(equal(1))
expect(mainQueueCounter.value).toEventually(equal(1))
property.value = 2
expect(value).toEventually(equal(2))
expect(mainQueueCounter.value).toEventually(equal(2))
}
describe("observer binding operator") {
it("should forward values to observer") {
let targetPipe = Signal<Int?, Never>.pipe()
let sourcePipe = Signal<Int?, Never>.pipe()
let targetProperty = Property<Int?>(initial: nil, then: targetPipe.output)
targetPipe.input <~ sourcePipe.output
expect(targetProperty.value).to(beNil())
sourcePipe.input.send(value: 1)
expect(targetProperty.value).to(equal(1))
}
}
}
}
}
| 25.280374 | 103 | 0.61793 |
238640a5b03f77514821222c8fd8cb804d206926 | 1,795 | //
// ValueImportProcessorDashboardWhiteList.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class ValueImportProcessorDashboardWhiteList: ValueImportProcessor {
init() {
super.init(identifier: "com.apple.dashboard.whiteList")
}
override func addValue(toCurrentValue: [Any]?, cellView: PayloadCellView, completionHandler: @escaping (_ value: Any?) -> Void) throws {
// Verify it's a dashboard widget
guard
self.fileUTI == UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, "wdgt" as CFString, nil)?.takeUnretainedValue() as String?,
let fileURL = self.fileURL,
let applicationBundle = Bundle(url: fileURL) else {
completionHandler(nil)
return
}
guard let bundleIdentifier = applicationBundle.bundleIdentifier else {
throw ValueImportError("The file: \"\(self.fileURL?.lastPathComponent ?? "Unknown File")\" does not seem to be a valid application bundle.")
}
// Check if this bundle identifier is already added
if let currentValue = toCurrentValue as? [[String: Any]], currentValue.contains(where: { $0["ID"] as? String == bundleIdentifier }) {
completionHandler(nil)
return
}
var value = [String: Any]()
// whiteList.whiteListItem.Type
value["Type"] = "bundleID"
// whiteList.whiteListItem.bundleID
value["ID"] = bundleIdentifier
if var currentValue = toCurrentValue as? [[String: Any]] {
currentValue.append(value)
completionHandler(currentValue)
} else {
completionHandler([value])
}
}
}
| 33.240741 | 155 | 0.637326 |
644642b880ef6aae068e39a12151ca2d327e812a | 4,588 | /* The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
contributed by Ian Partridge
converted to Swift 3 by Sergo Beruashvili
Swift port of Java #3 implementation
*/
let LINE_LENGTH = 60
let OUT_BUFFER_SIZE = 256*1024
let LOOKUP_SIZE = 4*1024
let LOOKUP_SCALE = Double(LOOKUP_SIZE - 1)
struct Freq {
var c: Character
var p: Double
init(_ c: Character, _ p: Double) {
self.c = c
self.p = p
}
}
let ALU =
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTG" +
"GGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGA" +
"GACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAA" +
"AATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT" +
"CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAAC" +
"CCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTG" +
"CACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"
var IUB =
[Freq("a", 0.27),
Freq("c", 0.12),
Freq("g", 0.12),
Freq("t", 0.27),
Freq("B", 0.02),
Freq("D", 0.02),
Freq("H", 0.02),
Freq("K", 0.02),
Freq("M", 0.02),
Freq("N", 0.02),
Freq("R", 0.02),
Freq("S", 0.02),
Freq("V", 0.02),
Freq("W", 0.02),
Freq("Y", 0.02)]
var HomoSapiens =
[Freq("a", 0.3029549426680),
Freq("c", 0.1979883004921),
Freq("g", 0.1975473066391),
Freq("t", 0.3015094502008)]
func sumAndScale( a: inout [Freq]) {
var p = 0.0
for i in 0..<a.count {
p += a[i].p
a[i].p = p * LOOKUP_SCALE
}
a[a.count - 1].p = LOOKUP_SCALE
}
class Random {
static let IM = 139968
static let IA = 3877
static let IC = 29573
static var SCALE: Double { get { return LOOKUP_SCALE / Double(IM)}}
static var last = 42
class func next() -> Double {
last = (last * IA + IC) % IM
return SCALE * Double(last)
}
}
class Out {
static var buf = String()
static let lim = OUT_BUFFER_SIZE - (2 * LINE_LENGTH) - 1
static var ct = 0
class func checkFlush() -> Bool {
if(ct >= lim) {
print(buf, terminator: "")
ct = 0
buf = ""
return true
}
return false
}
class func close() {
print(buf, terminator: "")
ct = 0
buf = ""
}
}
struct RandomFasta {
var lookup = [Freq]()
mutating func makeLookup( a: inout [Freq]) {
lookup = []
var j = 0
for i in 0..<LOOKUP_SIZE {
while (a[j].p < Double(i)) {
j += 1
}
lookup.append(a[j])
}
}
func addLine(bytes: Int) {
Out.checkFlush()
var lct = Out.ct
while (lct < Out.ct + bytes) {
let r = Random.next()
var ai = Int(r)
while (lookup[ai].p < r) {
ai += 1
}
Out.buf.append(lookup[ai].c)
lct += 1
}
Out.buf.append(Character("\n"))
lct += 1
Out.ct = lct
}
mutating func make (desc: String, a: [Freq], n: Int) {
var a = a
var n = n
makeLookup(a: &a)
Out.buf.append(desc)
Out.ct += desc.characters.count
while (n > 0) {
let bytes = min(LINE_LENGTH, n)
addLine(bytes: bytes)
n -= bytes
}
}
}
struct RepeatFasta {
static func make(desc: String, alu: String, n: Int) {
var n = n
Out.buf.append(desc)
Out.ct += desc.characters.count
let len = alu.characters.count
var buf = alu
buf.append(alu[alu.startIndex..<alu.index(alu.startIndex, offsetBy: LINE_LENGTH)])
var pos = 0
while (n > 0) {
let bytes = min(LINE_LENGTH, n)
Out.checkFlush()
let startIndex = buf.index(buf.startIndex, offsetBy: pos)
let endIndex = buf.index(startIndex, offsetBy: bytes)
let towrite = buf[startIndex..<endIndex]
Out.buf.append(towrite)
Out.buf.append(Character("\n"))
Out.ct += bytes + 1
pos = (pos + bytes) % len
n -= bytes
}
}
}
var n = 25000000
if CommandLine.argc > 1 {
n = Int(CommandLine.arguments[1])!
}
sumAndScale(a: &IUB)
sumAndScale(a: &HomoSapiens)
RepeatFasta.make(desc: ">ONE Homo sapiens alu\n", alu: ALU, n: n * 2)
var randomFasta = RandomFasta()
randomFasta.make(desc: ">TWO IUB ambiguity codes\n", a: IUB, n: n * 3)
randomFasta.make(desc: ">THREE Homo sapiens frequency\n", a: HomoSapiens, n: n * 5)
Out.close()
| 24.666667 | 90 | 0.529207 |
4b35f3fc47bfe651c6ab5c63ad52725b7302803b | 213 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a(Any) {
[k<D> Void>()
{
class
case c,
| 21.3 | 87 | 0.7277 |
e66a0351e79769f48553e4db3c71c98c6cc59172 | 12,621 | //
// SubredditFilteringViewController.swift
// Beam
//
// Created by Rens Verhoeven on 30-08-16.
// Copyright © 2016 Awkward. All rights reserved.
//
import UIKit
import Snoo
import CoreData
private enum SubredditFilteringType {
case keywords
case subreddits
}
class SubredditFilteringViewController: BeamViewController {
var subreddit: Subreddit!
@IBOutlet fileprivate var tableView: UITableView!
@IBOutlet fileprivate var toolbar: UIToolbar!
@IBOutlet fileprivate var buttonBarItem: UIBarButtonItem!
@IBOutlet fileprivate var buttonBar: ButtonBar!
fileprivate var keywordsChanged: Bool = false
fileprivate var canFilterSubreddits: Bool {
return self.subreddit.identifier == Subreddit.allIdentifier || self.subreddit.identifier == Subreddit.frontpageIdentifier
}
fileprivate var filteringType: SubredditFilteringType = SubredditFilteringType.keywords {
didSet {
self.tableView.reloadData()
}
}
fileprivate var filterKeywords: [String] {
get {
if let filterKeywords: [String] = self.subreddit?.filterKeywords, self.filteringType == SubredditFilteringType.keywords {
return filterKeywords
} else if let filterSubreddits: [String] = self.subreddit?.filterSubreddits, self.filteringType == SubredditFilteringType.subreddits {
return filterSubreddits
} else {
return [String]()
}
}
set {
self.keywordsChanged = true
if self.filteringType == SubredditFilteringType.keywords {
self.subreddit.filterKeywords = newValue
} else if self.filteringType == SubredditFilteringType.subreddits {
self.subreddit.filterSubreddits = newValue
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("content-filtering-view-title", comment: "The title of the content filtering subreddit setting view")
if self.canFilterSubreddits {
self.buttonBar.items = [ButtonBarButton(title: NSLocalizedString("keywords-filtering-type", comment: "The button in the top bar of the subreddit filtering screen"), showsBadge: false),
ButtonBarButton(title: NSLocalizedString("subreddits-filtering-type", comment: "The button in the top bar of the subreddit filtering screen"), showsBadge: false)]
self.toolbar.isHidden = false
self.tableView.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0)
} else {
self.toolbar.isHidden = true
self.buttonBar.items = [ButtonBarButton(title: NSLocalizedString("keywords-filtering-type", comment: "The button in the top bar of the subreddit filtering screen"), showsBadge: false)]
}
self.buttonBar.addTarget(self, action: #selector(SubredditFilteringViewController.buttonBarChanged(_:)), for: UIControlEvents.valueChanged)
NotificationCenter.default.addObserver(self, selector: #selector(SubredditFilteringViewController.keyboardWillChangeFrame(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.keywordsChanged == true {
self.keywordsChanged = false
let dataController: DataController = DataController.shared
let operations: [Operation] = dataController.persistentSaveOperations(AppDelegate.shared.managedObjectContext)
dataController.executeOperations(operations) { (error: Error?) in
if let error = error {
print("Error saving filters \(error)")
}
}
}
}
@objc fileprivate func buttonBarChanged(_ sender: ButtonBar) {
if sender.selectedItemIndex == 1 && self.canFilterSubreddits {
self.filteringType = SubredditFilteringType.subreddits
} else {
self.filteringType = SubredditFilteringType.keywords
}
}
override func displayModeDidChange() {
super.displayModeDidChange()
switch self.displayMode {
case .default:
self.view.backgroundColor = UIColor.groupTableViewBackground
self.tableView.backgroundColor = UIColor.groupTableViewBackground
self.tableView.separatorColor = UIColor.beamTableViewSeperatorColor()
self.tableView.sectionIndexBackgroundColor = UIColor.beamBarColor()
self.tableView.sectionIndexColor = UIColor.beamColor()
case .dark:
self.view.backgroundColor = UIColor.beamDarkBackgroundColor()
self.tableView.backgroundColor = UIColor.beamDarkBackgroundColor()
self.tableView.separatorColor = UIColor.beamDarkTableViewSeperatorColor()
self.tableView.sectionIndexBackgroundColor = UIColor.beamDarkContentBackgroundColor()
self.tableView.sectionIndexColor = UIColor.beamPurpleLight()
}
self.setNeedsStatusBarAppearanceUpdate()
}
@objc fileprivate func keyboardWillChangeFrame(_ notification: Notification) {
//We can only change the frame if we own the keyboard and the user info is available
guard let userInfo = (notification as NSNotification).userInfo, let isLocalKeyboard = userInfo[UIKeyboardIsLocalUserInfoKey] as? NSNumber, isLocalKeyboard == true else {
return
}
//We can only animate if the frame value is available
guard let keyboardFrameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
//Cet the CGRect of the keyboard frame NSValue
let keyboardFrame = keyboardFrameValue.cgRectValue
//Get the keyboard animation duration
let keyboardAnimationDuration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval) ?? 0
//Get the keyboard animation curve
var keyboardAnimationOptions: UIViewAnimationOptions = UIViewAnimationOptions()
if userInfo[UIKeyboardAnimationCurveUserInfoKey] != nil {
(userInfo[UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).getValue(&keyboardAnimationOptions)
}
//Calculate the height the keyboard is covering
let keyboardHeight = self.view.bounds.maxY - keyboardFrame.minY
var insets: UIEdgeInsets = self.tableView.contentInset
insets.bottom = keyboardHeight
var scrollBarInsets: UIEdgeInsets = self.tableView.scrollIndicatorInsets
scrollBarInsets.bottom = keyboardHeight
//Animate the doing the frame calculation of the view
UIView.animate(withDuration: keyboardAnimationDuration, delay: 0, options: keyboardAnimationOptions, animations: {
self.tableView.contentInset = insets
self.tableView.scrollIndicatorInsets = scrollBarInsets
self.view.layoutIfNeeded()
}, completion: nil)
}
}
extension SubredditFilteringViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filterKeywords.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath as IndexPath).row < self.filterKeywords.count {
let cell = tableView.dequeueReusableCell(withIdentifier: "keyword", for: indexPath)
let keyword: String = self.filterKeywords[(indexPath as IndexPath).row]
cell.textLabel!.text = keyword
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
} else {
let cell: SubredditFilteringTextFieldTableViewCell = tableView.dequeueReusableCell(withIdentifier: "textfield", for: indexPath) as! SubredditFilteringTextFieldTableViewCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
if self.filteringType == SubredditFilteringType.subreddits {
cell.placeholder = NSLocalizedString("add-subreddit-placeholder", comment: "The placeholder in the textfield for content filtering")
} else {
cell.placeholder = NSLocalizedString("add-keyword-placeholder", comment: "The placeholder in the textfield for content filtering")
}
return cell
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == UITableViewCellEditingStyle.delete && (indexPath as IndexPath).row < self.filterKeywords.count else {
return
}
let keyword: String = self.filterKeywords[(indexPath as IndexPath).row]
var keywords: [String] = self.filterKeywords
if let index: Int = keywords.index(of: keyword) {
keywords.remove(at: index)
self.filterKeywords = keywords
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.automatic)
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
guard (indexPath as IndexPath).row < self.filterKeywords.count else {
return false
}
return true
}
}
extension SubredditFilteringViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let keyword: String = textField.text?.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).lowercased() {
var keywords = self.filterKeywords
if keyword.count < 2 {
if self.filteringType == SubredditFilteringType.subreddits {
let alertController: UIAlertController = UIAlertController(alertWithCloseButtonAndTitle: NSLocalizedString("filter-subreddit-too-short-alert-title", comment: "The title of the alert when the filter subreddit is too short"), message: NSLocalizedString("filter-subreddit-too-short-alert-message", comment: "The message of the alert when the filter subreddit is too short"))
self.present(alertController, animated: true, completion: nil)
} else {
let alertController: UIAlertController = UIAlertController(alertWithCloseButtonAndTitle: NSLocalizedString("filter-keyword-too-short-alert-title", comment: "The title of the alert when the filter keyword is too short"), message: NSLocalizedString("filter-keyword-too-short-alert-message", comment: "The message of the alert when the filter keyword is too short"))
self.present(alertController, animated: true, completion: nil)
}
} else if keywords.contains(keyword) {
if self.filteringType == SubredditFilteringType.subreddits {
let alertController: UIAlertController = UIAlertController(alertWithCloseButtonAndTitle: NSLocalizedString("filter-subreddit-already-exists-alert-title", comment: "The title of the alert when the filter subreddit already exists"), message: NSLocalizedString("filter-subreddit-already-exists-alert-message", comment: "The message of the alert when the filter subreddit already exists"))
self.present(alertController, animated: true, completion: nil)
} else {
let alertController: UIAlertController = UIAlertController(alertWithCloseButtonAndTitle: NSLocalizedString("filter-keyword-already-exists-alert-title", comment: "The title of the alert when the filter keyword already exists"), message: NSLocalizedString("filter-keyword-already-exists-alert-message", comment: "The message of the alert when the filter keyword already exists"))
self.present(alertController, animated: true, completion: nil)
}
} else {
textField.text = ""
keywords.append(keyword)
self.filterKeywords = keywords
self.tableView.insertRows(at: [IndexPath(row: self.filterKeywords.count - 1, section: 0)], with: UITableViewRowAnimation.automatic)
}
}
return false
}
}
| 51.097166 | 405 | 0.676571 |
9cab856fdb354d719b295fa62de568a03e23dd63 | 3,329 | //
// V2User.swift
// V2ex-Swift
//
// Created by skyline on 16/3/28.
// Copyright © 2016年 Fin. All rights reserved.
//
import UIKit
import Alamofire
let kUserName = "me.fin.username"
let kUserToken = "me.fin.token"
let kUserTicket = "me.fin.ticket"
class V2User: NSObject {
static let sharedInstance = V2User()
/// 用户信息
fileprivate var _user:UserModel?
var user:UserModel? {
get {
return self._user
}
set {
//保证给user赋值是在主线程进行的
//原因是 有很多UI可能会监听这个属性,这个属性发生更改时,那些UI也会相应的修改自己,所以要在主线程操作
dispatch_sync_safely_main_queue {
self._user = newValue
self.username = newValue?.username
}
}
}
@objc dynamic var username:String?
fileprivate var _once:String?
//全局once字符串,用于用户各种操作,例如回帖 登录 。这些操作都需要用的once ,而且这个once是全局统一的
var once:String? {
get {
//取了之后就删掉,
//因为once 只能使用一次,之后就不可再用了,
let onceStr = _once
_once = nil
return onceStr;
}
set{
_once = newValue
}
}
/// 返回 客户端显示是否有可用的once
var hasOnce:Bool {
get {
return _once != nil && _once!.Lenght > 0
}
}
/// 通知数量
@objc dynamic var notificationCount:Int = 0
fileprivate override init() {
super.init()
dispatch_sync_safely_main_queue {
self.setup()
//如果客户端是登录状态,则去验证一下登录有没有过期
if self.isLogin {
self.verifyLoginStatus()
}
}
}
func setup(){
self.username = V2EXSettings.sharedInstance[kUserName]
}
/// 是否登录
var isLogin:Bool {
get {
if let len = self.username?.Lenght , len > 0 {
return true
}
else {
return false
}
}
}
func ensureLoginWithHandler(_ handler:()->()) {
guard isLogin else {
V2Inform("请先登录")
return;
}
handler()
}
/**
退出登录
*/
func loginOut() {
removeAllCookies()
self.user = nil
self.username = nil
self.once = nil
self.notificationCount = 0
//清空settings中的username
V2EXSettings.sharedInstance[kUserName] = nil
}
/**
删除客户端所有cookies
*/
func removeAllCookies() {
let storage = HTTPCookieStorage.shared
if let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
}
/**
打印客户端cookies
*/
func printAllCookies(){
let storage = HTTPCookieStorage.shared
if let cookies = storage.cookies {
for cookie in cookies {
NSLog("name:%@ , value:%@ \n", cookie.name,cookie.value)
}
}
}
/**
验证客户端登录状态
*/
func verifyLoginStatus() {
Alamofire.request(V2EXURL + "new", headers: MOBILE_CLIENT_HEADERS).responseString(encoding: nil) { (response) -> Void in
if response.response?.url?.path == "/signin"{
//没有登录 ,注销客户端
dispatch_sync_safely_main_queue({ () -> () in
self.loginOut()
})
}
}
}
}
| 22.80137 | 129 | 0.511865 |
ef97126b1a54cb0c2c607e22ac24097d48ea0bc8 | 727 | //
// CodableBundleExtention.swift
// Africa
//
// Created by Alexander Rojas Benavides on 9/10/21.
//
import Foundation
extension Bundle {
func decode<T: Codable>(_ file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to locate \(file) in bundle")
}
let decoder = JSONDecoder()
guard let loaded = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to locate \(file) in bundle")
}
return loaded
}
}
| 25.068966 | 78 | 0.563961 |
21bec6a7c9ab260628321ef6d894d504b1a81d9a | 1,689 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
struct PEGParticipant: Participant {
static var name: String { "PEG" }
}
import Prototypes
private func graphemeBreakPropertyData(forLine line: String) -> GraphemeBreakEntry? {
typealias Pattern = PEG<Character>.Pattern
/*
# This is a comment
0600..0605 ; Prepend # Cf [6] ARABIC NUMBER SIGN..ARABIC NUMBER MARK ABOVE
06DD ; Prepend # Cf ARABIC END OF AYAH
Decl -> Scalar (".." Scalar)? Space+ ";" Space Property Space "#" .* success
Scalar -> \h{4, 6}
Space -> \s
Property -> \w+
*/
let scalar = Pattern.repeatRange(.charactetSet(\.isHexDigit), atLeast: 4, atMost: 6)
let space = Pattern.charactetSet(\.isWhitespace)
let property = Pattern.oneOrMore(.charactetSet(\.isLetter))
let entry = Pattern(
scalar, .zeroOrOne(Pattern("..", scalar)), .repeat(space, atLeast: 1),
";", space, property, space, "#", .many(.any), .success)
let program = PEG.Program(start: "Entry", environment: ["Entry": entry])
let vm = program.compile(for: String.self)
let engine = try! program.transpile()
_ = (vm, engine)
fatalError("Unsupported")
// let resultVM = vm.consume(line)
// let resultTrans = engine.consume(line)
//
// precondition(resultVM == resultTrans)
}
| 31.277778 | 86 | 0.602131 |
ac114dee3d29f4cc5ca92b777e9b32ebb9b8d7d3 | 1,359 | // ----------------------------------------------------------------------------
//
// Check.NotValid.swift
//
// @author Alexander Bragin <[email protected]>
// @copyright Copyright (c) 2017, Roxie Mobile Ltd. All rights reserved.
// @link http://www.roxiemobile.com/
//
// ----------------------------------------------------------------------------
import SwiftCommons
// ----------------------------------------------------------------------------
extension Check
{
// MARK: - Methods
/// Checks that an object is not `nil` and not valid.
///
/// - Parameters:
/// - object: Object to check or `nil`.
/// - message: The identifying message for the `CheckError` (`nil` okay). The default is an empty string.
/// - file: The file name. The default is the file where function is called.
/// - line: The line number. The default is the line number where function is called.
///
/// - Throws:
/// CheckError
///
public static func notValid(_ object: Validatable?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) throws {
guard let object = object, object.isNotValid else {
throw newCheckError(message, file, line)
}
}
}
// ----------------------------------------------------------------------------
| 35.763158 | 155 | 0.472406 |
9039f1025d00d20b976e596d5ec51485f6be8960 | 4,083 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
import SceneKit
@available(iOS 14.0, *)
struct OnboardingCelebrationScreen: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
private var horizontalPadding: CGFloat {
horizontalSizeClass == .regular ? 50 : 16
}
// MARK: Public
@ObservedObject var viewModel: OnboardingCelebrationViewModel.Context
// MARK: Views
var body: some View {
GeometryReader { geometry in
VStack {
ScrollView(showsIndicators: false) {
Spacer()
.frame(height: OnboardingMetrics.spacerHeight(in: geometry))
mainContent
.padding(.top, 106)
.padding(.horizontal, horizontalPadding)
.frame(maxWidth: OnboardingMetrics.maxContentWidth)
}
.frame(maxWidth: .infinity)
buttons
.frame(maxWidth: OnboardingMetrics.maxContentWidth)
.padding(.horizontal, horizontalPadding)
.padding(.bottom, 24)
.padding(.bottom, geometry.safeAreaInsets.bottom > 0 ? 0 : 16)
Spacer()
.frame(height: OnboardingMetrics.spacerHeight(in: geometry))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.overlay(effects.ignoresSafeArea())
.background(theme.colors.background.ignoresSafeArea())
.accentColor(theme.colors.accent)
.navigationBarHidden(true)
}
/// The main content of the view to be shown in a scroll view.
var mainContent: some View {
VStack(spacing: 8) {
Image(Asset.Images.onboardingCelebrationIcon.name)
.resizable()
.scaledToFit()
.frame(width: 90)
.foregroundColor(theme.colors.accent)
.background(Circle().foregroundColor(.white).padding(2))
.padding(.bottom, 42)
.accessibilityHidden(true)
Text(VectorL10n.onboardingCelebrationTitle)
.font(theme.fonts.title2B)
.multilineTextAlignment(.center)
.foregroundColor(theme.colors.primaryContent)
Text(VectorL10n.onboardingCelebrationMessage)
.font(theme.fonts.subheadline)
.multilineTextAlignment(.center)
.foregroundColor(theme.colors.secondaryContent)
}
}
/// The action buttons shown at the bottom of the view.
var buttons: some View {
VStack {
Button { viewModel.send(viewAction: .complete) } label: {
Text(VectorL10n.onboardingCelebrationButton)
.font(theme.fonts.body)
}
.buttonStyle(PrimaryActionButtonStyle())
}
}
var effects: some View {
EffectsView(effectsType: .confetti)
.allowsHitTesting(false)
}
}
// MARK: - Previews
@available(iOS 15.0, *)
struct OnboardingCelebration_Previews: PreviewProvider {
static let stateRenderer = MockOnboardingCelebrationScreenState.stateRenderer
static var previews: some View {
stateRenderer.screenGroup()
}
}
| 33.743802 | 84 | 0.589762 |
bfacc52e5ed59b9db35eb1784ce54973c96edb75 | 523 | //
// ConfigWindowController.swift
// Surf
//
// Created by networkextension on 21/11/2016.
// Copyright © 2016 yarshure. All rights reserved.
//
import Cocoa
class ConfigWindowController: NSWindowController,NSTableViewDelegate,NSTableViewDataSource {
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
deinit {
print("window deinit")
}
}
| 23.772727 | 134 | 0.705545 |
8f5e8d8180404d3ab462a7269c1d1bda9cddad74 | 930 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
public class ResourceLinks: APIModel {
public var _self: String
public init(_self: String) {
self._self = _self
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
_self = try container.decode("self")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(_self, forKey: "self")
}
public func isEqual(to object: Any?) -> Bool {
guard let object = object as? ResourceLinks else { return false }
guard self._self == object._self else { return false }
return true
}
public static func == (lhs: ResourceLinks, rhs: ResourceLinks) -> Bool {
return lhs.isEqual(to: rhs)
}
}
| 24.473684 | 76 | 0.652688 |
87aef9697d024a1f0d929791968bc38858e4d59d | 1,093 | //
// AppDelegate.swift
// MovieBrowser
//
// Created by Mac-6 on 14/07/21.
//
import UIKit
class HTTPRequestCallResult: NSObject {
var result : Any
var resultDict : [String : Any]
var errorCode : Int = 0
var errorMessage : String = ""
var RequestStartTime : Date
var ResponseFinishTime : Date
override init(){
self.result = String("Default Result") as Any
self.resultDict = [:]
//self.errorCode = 0
self.errorMessage = String("Undefined Error")
self.RequestStartTime = Date.init()
self.ResponseFinishTime = Date.init()
}
init(result: AnyObject, resultDict: [String:Any], errorCode: Int, errorMessage: String, RequestStartTime: Date, ResponseFinishTime: Date) {
self.result = result
self.resultDict = resultDict
self.errorCode = errorCode
self.errorMessage = errorMessage
self.RequestStartTime = RequestStartTime
self.ResponseFinishTime = ResponseFinishTime
}
}
| 27.325 | 143 | 0.601098 |
2f2f2811136de35c615f576e52bc1edbbcb63c37 | 1,650 | //
// BasicOperation.swift
// FileableTests
//
// Created by Shota Shimazu on 2018/08/27.
// Copyright © 2018 Shota Shimazu. All rights reserved.
//
import XCTest
@testable import Fileable
class BasicOperation: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testCd() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let current: String = Path.pwd
try? Path.cd(Path.pwd)
let moved: String = Path.pwd
XCTAssertEqual(current, moved)
}
func testPwdMoveDir() {
let current: String = Path.pwd
Path.pwd = Path.pwd
let moved: String = Path.pwd
XCTAssertEqual(current, moved)
}
func testPwd() {
let current: String = Path.pwd
Path.pwd = Path.current
let moved: String = Path.pwd
XCTAssertEqual(current, moved)
}
func testMkdir() {
try? Path.mkdir("TEST_DIR")
XCTAssertTrue(Path(Path.pwd + "/TEST_DIR").isDir)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 22.916667 | 111 | 0.577576 |
fcc95a95e5ea2522ee44c45ad8db38078a4d0f75 | 449 | // 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
var b{class B<A{class a{class B:a{protocol A{func<
| 44.9 | 79 | 0.752784 |
fb52eba9391383826c13f1137e36a8fd0e343b88 | 4,909 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
// This file was auto-autogenerated by scripts and templates at http://github.com/AudioKit/AudioKitDevTools/
//changes needed so it compiles
import AVFoundation
/// AudioKit version of Apple's Compressor Audio Unit
///
public class Compressor: Node {
fileprivate let effectAU = AVAudioUnitEffect(appleEffect: kAudioUnitSubType_DynamicsProcessor)
let input: Node
/// Connected nodes
public var connections: [Node] { [input] }
/// Underlying AVAudioNode
public var avAudioNode: AVAudioNode { effectAU }
/// Specification details for threshold
public static let thresholdDef = NodeParameterDef(
identifier: "threshold",
name: "Threshold",
address: AUParameterAddress(kDynamicsProcessorParam_Threshold),
defaultValue: -20,
range: -40 ... 20,
unit: .decibels)
/// Threshold (decibels) ranges from -40 to 20 (Default: -20)
@Parameter(thresholdDef) public var threshold: AUValue
/// Specification details for headRoom
public static let headRoomDef = NodeParameterDef(
identifier: "headRoom",
name: "Head Room",
address: AUParameterAddress(kDynamicsProcessorParam_HeadRoom),
defaultValue: 5,
range: 0.1 ... 40.0,
unit: .decibels)
/// Head Room (decibels) ranges from 0.1 to 40.0 (Default: 5)
@Parameter(headRoomDef) public var headRoom: AUValue
/// Specification details for attackTime
public static let attackTimeDef = NodeParameterDef(
identifier: "attackTime",
name: "Attack Time",
address: AUParameterAddress(kDynamicsProcessorParam_AttackTime),
defaultValue: 0.001,
range: 0.0001 ... 0.2,
unit: .seconds)
/// Attack Time (seconds) ranges from 0.0001 to 0.2 (Default: 0.001)
@Parameter(attackTimeDef) public var attackTime: AUValue
/// Specification details for releaseTime
public static let releaseTimeDef = NodeParameterDef(
identifier: "releaseTime",
name: "Release Time",
address: AUParameterAddress(kDynamicsProcessorParam_ReleaseTime),
defaultValue: 0.05,
range: 0.01 ... 3,
unit: .seconds)
/// Release Time (seconds) ranges from 0.01 to 3 (Default: 0.05)
@Parameter(releaseTimeDef) public var releaseTime: AUValue
/// Specification details for masterGain
public static let masterGainDef = NodeParameterDef(
identifier: "masterGain",
name: "Master Gain",
address: AUParameterAddress(6),
defaultValue: 0,
range: -40 ... 40,
unit: .decibels)
/// Master Gain (decibels) ranges from -40 to 40 (Default: 0)
@Parameter(masterGainDef) public var masterGain: AUValue
/// Compression Amount (dB) read only
public var compressionAmount: AUValue {
return effectAU.auAudioUnit.parameterTree?.allParameters[7].value ?? 0
}
/// Input Amplitude (dB) read only
public var inputAmplitude: AUValue {
return effectAU.auAudioUnit.parameterTree?.allParameters[8].value ?? 0
}
/// Output Amplitude (dB) read only
public var outputAmplitude: AUValue {
return effectAU.auAudioUnit.parameterTree?.allParameters[9].value ?? 0
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted = true
/// Initialize the compressor node
///
/// - parameter input: Input node to process
/// - parameter threshold: Threshold (decibels) ranges from -40 to 20 (Default: -20)
/// - parameter headRoom: Head Room (decibels) ranges from 0.1 to 40.0 (Default: 5)
/// - parameter attackTime: Attack Time (seconds) ranges from 0.0001 to 0.2 (Default: 0.001)
/// - parameter releaseTime: Release Time (seconds) ranges from 0.01 to 3 (Default: 0.05)
/// - parameter masterGain: Master Gain (decibels) ranges from -40 to 40 (Default: 0)
///
public init(
_ input: Node,
threshold: AUValue = thresholdDef.defaultValue,
headRoom: AUValue = headRoomDef.defaultValue,
attackTime: AUValue = attackTimeDef.defaultValue,
releaseTime: AUValue = releaseTimeDef.defaultValue,
masterGain: AUValue = masterGainDef.defaultValue) {
self.input = input
associateParams(with: effectAU)
self.threshold = threshold
self.headRoom = headRoom
self.attackTime = attackTime
self.releaseTime = releaseTime
self.masterGain = masterGain
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
effectAU.bypass = false
isStarted = true
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
effectAU.bypass = true
isStarted = false
}
}
| 35.832117 | 108 | 0.667957 |
1a09037f3134528ab6a3911c1443d4660545759b | 1,501 | //
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import biometric_storage
import bitsdojo_window_macos
import file_selector_macos
import flutter_local_notifications
import package_info_plus_macos
import path_provider_macos
import share_plus_macos
import shared_preferences_macos
import sqflite
import sqlcipher_flutter_libs
import url_launcher_macos
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
BiometricStorageMacOSPlugin.register(with: registry.registrar(forPlugin: "BiometricStorageMacOSPlugin"))
BitsdojoWindowPlugin.register(with: registry.registrar(forPlugin: "BitsdojoWindowPlugin"))
FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
FLTPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FLTPackageInfoPlusPlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin"))
Sqlite3FlutterLibsPlugin.register(with: registry.registrar(forPlugin: "Sqlite3FlutterLibsPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
}
| 45.484848 | 114 | 0.852765 |
d96dc18c6c47b4a6d2c750c8c982c1e55d3571c3 | 1,517 | import Foundation
#if canImport(UIKit)
import UIKit
#endif
public class VZNetwork {}
public extension URLSession {
func dataTask(with request: VZNetwork.Request) -> URLSessionDataTask {
return self.dataTask(with: request.request, completionHandler: { (data, response, error) in
DispatchQueue.main.async {
request._end?()
#if canImport(UIKit)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
#endif
}
if let error = error {
DispatchQueue.main.async {
request._result?(.fail(error.localizedDescription))
}
return
}
let httpResponse = response as? HTTPURLResponse
if let response = VZNetwork.Response(response: httpResponse, data: data) {
DispatchQueue.main.async {
request._result?(.success(response))
}
} else {
DispatchQueue.main.async {
request._result?(.fail(""))
}
}
})
}
func perform(with request: VZNetwork.Request) {
self.dataTask(with: request).resume()
DispatchQueue.main.async {
request._start?()
#if canImport(UIKit)
UIApplication.shared.isNetworkActivityIndicatorVisible = true
#endif
}
}
}
| 31.604167 | 99 | 0.521424 |
23d8c688d088f9425ef48859b55fc1feb15d7183 | 7,172 | //
// HeatmapSerieSpec.swift
// SwiftyEcharts
//
// Created by Pluto Y on 16/07/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import Quick
import Nimble
@testable import SwiftyEcharts
class HeatmapSerieSpec: QuickSpec {
override func spec() {
let nameDataValue = "dataNameValue"
let valueDataValue: [Jsonable] = ["周一", "周二", "周三"]
let labelDataValue = EmphasisLabel(
.normal(LabelStyle(
.align(Align.auto),
.verticalAlign(VerticalAlign.top),
.show(true),
.position(.top)
))
)
let itemStyleDataValue = ItemStyle(
.normal(CommonItemStyleContent(
.opacity(0.7),
.color(.hexColor("#332342")),
.borderWidth(3),
.borderColor(.hexColor("#235894"))
))
)
let data = HeatmapSerie.Data()
data.name = nameDataValue
data.value = valueDataValue
data.label = labelDataValue
data.itemStyle = itemStyleDataValue
describe("For HeatmapSerie.Data") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"name": nameDataValue,
"value": valueDataValue,
"label": labelDataValue,
"itemStyle": itemStyleDataValue
]
expect(data.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let dataByEnums = HeatmapSerie.Data(
.name(nameDataValue),
.value(valueDataValue),
.label(labelDataValue),
.itemStyle(itemStyleDataValue)
)
expect(dataByEnums.jsonString).to(equal(data.jsonString))
}
}
describe("For HeatmapSerie") {
let nameValue = "heatmapSerieNameValue"
let coordinateSystemValue = CoordinateSystem.polar
let xAxisIndexValue: UInt8 = 28
let yAxisIndexValue: UInt8 = 255
let geoIndexValue: UInt8 = 0
let calendarIndexValue: UInt8 = 84
let blurSizeValue: Float = 2.423
let minOpacityValue: Float = 0.99
let maxOpacityValue: Float = 0.01
let dataValue: [Jsonable] = [
data,
12, 34, ["value": 56]
]
let markPointValue = MarkPoint(
.silent(true),
.animation(false),
.animationDuration(Time.number(2.835))
)
let markLineValue = MarkLine(
.data([["name": "两个坐标之间的标线", "coord": [10, 20]], ["coord": [20, 30]]])
)
let markAreaValue = MarkArea(
.label(EmphasisLabel(
.normal(LabelStyle(
.position(.right)
))
))
)
let zlevelValue: Float = 28.423
let zValue: Float = 8.2323
let silentValue = true
let labelValue = EmphasisLabel(
.emphasis(LabelStyle(
.show(false),
.padding(5),
.height(20%),
.rich([:]),
.borderColor(rgba(200, 1, 200, 0.5555))
))
)
let itemStyleValue = ItemStyle(
.normal(CommonItemStyleContent(
.opacity(0.294),
.borderType(LineType.dashed)
))
)
let heatmapSerie = HeatmapSerie()
heatmapSerie.name = nameValue
heatmapSerie.coordinateSystem = coordinateSystemValue
heatmapSerie.xAxisIndex = xAxisIndexValue
heatmapSerie.yAxisIndex = yAxisIndexValue
heatmapSerie.geoIndex = geoIndexValue
heatmapSerie.calendarIndex = calendarIndexValue
heatmapSerie.blurSize = blurSizeValue
heatmapSerie.minOpacity = minOpacityValue
heatmapSerie.maxOpacity = maxOpacityValue
heatmapSerie.data = dataValue
heatmapSerie.markPoint = markPointValue
heatmapSerie.markLine = markLineValue
heatmapSerie.markArea = markAreaValue
heatmapSerie.zlevel = zlevelValue
heatmapSerie.z = zValue
heatmapSerie.silent = silentValue
heatmapSerie.label = labelValue
heatmapSerie.itemStyle = itemStyleValue
it("needs to check the type value") {
expect(heatmapSerie.type.jsonString).to(equal(SerieType.heatmap.jsonString))
}
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"type": SerieType.heatmap,
"name": nameValue,
"coordinateSystem": coordinateSystemValue,
"xAxisIndex": xAxisIndexValue,
"yAxisIndex": yAxisIndexValue,
"geoIndex": geoIndexValue,
"calendarIndex": calendarIndexValue,
"blurSize": blurSizeValue,
"minOpacity": minOpacityValue,
"maxOpacity": maxOpacityValue,
"data": dataValue,
"markPoint": markPointValue,
"markLine": markLineValue,
"markArea": markAreaValue,
"zlevel": zlevelValue,
"z": zValue,
"silent": silentValue,
"label": labelValue,
"itemStyle": itemStyleValue
]
expect(heatmapSerie.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let heatmapSerieByEnums = HeatmapSerie(
.name(nameValue),
.coordinateSystem(coordinateSystemValue),
.xAxisIndex(xAxisIndexValue),
.yAxisIndex(yAxisIndexValue),
.geoIndex(geoIndexValue),
.calendarIndex(calendarIndexValue),
.blurSize(blurSizeValue),
.minOpacity(minOpacityValue),
.maxOpacity(maxOpacityValue),
.data(dataValue),
.markPoint(markPointValue),
.markLine(markLineValue),
.markArea(markAreaValue),
.zlevel(zlevelValue),
.z(zValue),
.silent(silentValue),
.label(labelValue),
.itemStyle(itemStyleValue)
)
expect(heatmapSerieByEnums.jsonString).to(equal(heatmapSerie.jsonString))
}
}
}
}
| 37.549738 | 92 | 0.48773 |
6af4cdda9e41b92e4c06a26bac0fa9e58b93616b | 2,021 | import Foundation
import MixboxFoundation
public final class DebugEnvironmentProvider: EnvironmentProvider {
private let originalEnvironmentProvider: EnvironmentProvider
public init(originalEnvironmentProvider: EnvironmentProvider) {
self.originalEnvironmentProvider = originalEnvironmentProvider
}
public lazy var environment: [String: String] = {
let environment = originalEnvironmentProvider.environment
do {
return environment.merging(
try patch(),
uniquingKeysWith: { _, patched in patched }
)
} catch {
print("Skipping patching environment due to error: \(error)")
}
return environment
}()
private func patch() throws -> [String: String] {
let home = try originalEnvironmentProvider.environment["SIMULATOR_HOST_HOME"].unwrapOrThrow()
let path = "\(home)/.mixbox_ci_debug_environment"
let whitespaceSeparatedEnvironment = try String(
contentsOfFile: (path as NSString).expandingTildeInPath
)
var environmentAsDictionary = [String: String]()
let equalsSignSeparatedKeyValues = whitespaceSeparatedEnvironment.split { character in
character == " " || character == "\n"
}
for equalsSignSeparatedKeyValue in equalsSignSeparatedKeyValues {
let keyValueAsArray = equalsSignSeparatedKeyValue.split(separator: "=", omittingEmptySubsequences: true)
if keyValueAsArray.count == 2 {
let key = String(keyValueAsArray[0])
let value = String(keyValueAsArray[1])
environmentAsDictionary[key] = value
} else {
print("\(path) should contain pairs of key value: \"A=B C=D E=F\", got this pair: \(equalsSignSeparatedKeyValue)")
}
}
return environmentAsDictionary
}
}
| 36.089286 | 130 | 0.614052 |
8f55599b810cc5f2465378b398f59fe495890016 | 14,730 | // Corona-Warn-App
//
// SAP SE and all other contributors
// copyright owners license this file to you under the Apache
// License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
import UIKit
class ExposureSubmissionTestResultViewController: DynamicTableViewController, ENANavigationControllerWithFooterChild {
// MARK: - Attributes.
var testResult: TestResult?
var timeStamp: Int64?
private(set) weak var coordinator: ExposureSubmissionCoordinating?
private(set) weak var exposureSubmissionService: ExposureSubmissionService?
// MARK: - Initializers.
init?(coder: NSCoder, coordinator: ExposureSubmissionCoordinating, exposureSubmissionService: ExposureSubmissionService, testResult: TestResult?) {
self.coordinator = coordinator
self.exposureSubmissionService = exposureSubmissionService
self.testResult = testResult
super.init(coder: coder)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle methods.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupButtons()
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
// MARK: - View Setup Helper methods.
private func setupView() {
setupDynamicTableView()
setupNavigationBar()
timeStamp = exposureSubmissionService?.devicePairingSuccessfulTimestamp
}
private func setupButtons() {
guard let result = testResult else { return }
// Make sure to reset all button loading states.
self.navigationFooterItem?.isPrimaryButtonLoading = false
self.navigationFooterItem?.isSecondaryButtonLoading = false
// Make sure to reset buttons to default state.
self.navigationFooterItem?.isPrimaryButtonEnabled = true
self.navigationFooterItem?.isPrimaryButtonHidden = false
self.navigationFooterItem?.isSecondaryButtonEnabled = false
self.navigationFooterItem?.isSecondaryButtonHidden = true
switch result {
case .positive:
navigationFooterItem?.primaryButtonTitle = AppStrings.ExposureSubmissionResult.continueButton
navigationFooterItem?.isSecondaryButtonHidden = true
case .negative, .invalid, .redeemed:
navigationFooterItem?.primaryButtonTitle = AppStrings.ExposureSubmissionResult.deleteButton
navigationFooterItem?.isSecondaryButtonHidden = true
case .pending:
navigationFooterItem?.primaryButtonTitle = AppStrings.ExposureSubmissionResult.refreshButton
navigationFooterItem?.secondaryButtonTitle = AppStrings.ExposureSubmissionResult.deleteButton
navigationFooterItem?.isSecondaryButtonEnabled = true
navigationFooterItem?.isSecondaryButtonHidden = false
}
}
private func setupNavigationBar() {
navigationItem.hidesBackButton = true
navigationController?.navigationItem.largeTitleDisplayMode = .always
navigationItem.title = AppStrings.ExposureSubmissionResult.title
}
private func setupDynamicTableView() {
guard let result = testResult else {
logError(message: "No test result.", level: .error)
return
}
tableView.register(
UINib(nibName: String(describing: ExposureSubmissionTestResultHeaderView.self), bundle: nil),
forHeaderFooterViewReuseIdentifier: HeaderReuseIdentifier.testResult.rawValue
)
tableView.register(
UINib(nibName: String(describing: ExposureSubmissionStepCell.self), bundle: nil),
forCellReuseIdentifier: CustomCellReuseIdentifiers.stepCell.rawValue
)
dynamicTableViewModel = dynamicTableViewModel(for: result)
}
// MARK: - Convenience methods for buttons.
private func deleteTest() {
let alert = UIAlertController(
title: AppStrings.ExposureSubmissionResult.removeAlert_Title,
message: AppStrings.ExposureSubmissionResult.removeAlert_Text,
preferredStyle: .alert
)
let cancel = UIAlertAction(
title: AppStrings.Common.alertActionCancel,
style: .cancel,
handler: { _ in alert.dismiss(animated: true, completion: nil) }
)
let delete = UIAlertAction(
title: AppStrings.Common.alertActionRemove,
style: .destructive,
handler: { _ in
self.exposureSubmissionService?.deleteTest()
self.navigationController?.dismiss(animated: true, completion: nil)
}
)
alert.addAction(delete)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
private func refreshTest() {
navigationFooterItem?.isPrimaryButtonEnabled = false
navigationFooterItem?.isPrimaryButtonLoading = true
exposureSubmissionService?
.getTestResult { result in
switch result {
case let .failure(error):
let alert = self.setupErrorAlert(message: error.localizedDescription)
self.present(alert, animated: true, completion: {
self.navigationFooterItem?.isPrimaryButtonEnabled = true
self.navigationFooterItem?.isPrimaryButtonLoading = false
})
case let .success(testResult):
self.refreshView(for: testResult)
}
}
}
private func refreshView(for result: TestResult) {
self.testResult = result
self.dynamicTableViewModel = self.dynamicTableViewModel(for: result)
self.tableView.reloadData()
self.setupButtons()
}
/// Only show the "warn others" screen if the ENManager is enabled correctly,
/// otherwise, show an alert.
private func showWarnOthers() {
if let state = exposureSubmissionService?.preconditions() {
if !state.isGood {
let alert = self.setupErrorAlert(
message: ExposureSubmissionError.enNotEnabled.localizedDescription
)
self.present(alert, animated: true, completion: nil)
return
}
self.coordinator?.showSymptomsScreen()
}
}
}
// MARK: - Custom HeaderReuseIdentifiers.
extension ExposureSubmissionTestResultViewController {
enum HeaderReuseIdentifier: String, TableViewHeaderFooterReuseIdentifiers {
case testResult = "testResultCell"
}
}
// MARK: - Cell reuse identifiers.
extension ExposureSubmissionTestResultViewController {
enum CustomCellReuseIdentifiers: String, TableViewCellReuseIdentifiers {
case stepCell
}
}
// MARK: ENANavigationControllerWithFooterChild methods.
extension ExposureSubmissionTestResultViewController {
func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapPrimaryButton button: UIButton) {
guard let result = testResult else { return }
switch result {
case .positive:
showWarnOthers()
case .negative, .invalid, .redeemed:
deleteTest()
case .pending:
refreshTest()
}
}
func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapSecondaryButton button: UIButton) {
guard let result = testResult else { return }
switch result {
case .pending:
deleteTest()
default:
// Secondary button is only active for pending result state.
break
}
}
}
// MARK: - DynamicTableViewModel convenience setup methods.
private extension ExposureSubmissionTestResultViewController {
private func dynamicTableViewModel(for result: TestResult) -> DynamicTableViewModel {
DynamicTableViewModel.with {
$0.add(
testResultSection(for: result)
)
}
}
private func testResultSection(for result: TestResult) -> DynamicSection {
switch result {
case .positive:
return positiveTestResultSection()
case .negative:
return negativeTestResultSection()
case .invalid:
return invalidTestResultSection()
case .pending:
return pendingTestResultSection()
case .redeemed:
return redeemedTestResultSection()
}
}
private func positiveTestResultSection() -> DynamicSection {
.section(
header: .identifier(
ExposureSubmissionTestResultViewController.HeaderReuseIdentifier.testResult,
configure: { view, _ in
(view as? ExposureSubmissionTestResultHeaderView)?.configure(testResult: .positive, timeStamp: self.timeStamp)
}
),
separators: .none,
cells: [
.title2(text: AppStrings.ExposureSubmissionResult.procedure,
accessibilityIdentifier: AccessibilityIdentifiers.ExposureSubmissionResult.procedure),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testAdded,
description: AppStrings.ExposureSubmissionResult.testAddedDesc,
icon: UIImage(named: "Icons_Grey_Check"),
hairline: .iconAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testPositive,
description: AppStrings.ExposureSubmissionResult.testPositiveDesc,
icon: UIImage(named: "Icons_Grey_Error"),
hairline: .topAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.warnOthers,
description: AppStrings.ExposureSubmissionResult.warnOthersDesc,
icon: UIImage(named: "Icons_Grey_Warnen"),
hairline: .none
)
]
)
}
private func negativeTestResultSection() -> DynamicSection {
.section(
header: .identifier(
ExposureSubmissionTestResultViewController.HeaderReuseIdentifier.testResult,
configure: { view, _ in
(view as? ExposureSubmissionTestResultHeaderView)?.configure(testResult: .negative, timeStamp: self.timeStamp)
}
),
separators: .none,
cells: [
.title2(text: AppStrings.ExposureSubmissionResult.procedure,
accessibilityIdentifier: AccessibilityIdentifiers.ExposureSubmissionResult.procedure),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testAdded,
description: AppStrings.ExposureSubmissionResult.testAddedDesc,
icon: UIImage(named: "Icons_Grey_Check"),
hairline: .iconAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testNegative,
description: AppStrings.ExposureSubmissionResult.testNegativeDesc,
icon: UIImage(named: "Icons_Grey_Error"),
hairline: .topAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testRemove,
description: AppStrings.ExposureSubmissionResult.testRemoveDesc,
icon: UIImage(named: "Icons_Grey_Entfernen"),
hairline: .none
),
.title2(text: AppStrings.ExposureSubmissionResult.furtherInfos_Title,
accessibilityIdentifier: AccessibilityIdentifiers.ExposureSubmissionResult.furtherInfos_Title),
.bulletPoint(text: AppStrings.ExposureSubmissionResult.furtherInfos_ListItem1, spacing: .large),
.bulletPoint(text: AppStrings.ExposureSubmissionResult.furtherInfos_ListItem2, spacing: .large),
.bulletPoint(text: AppStrings.ExposureSubmissionResult.furtherInfos_ListItem3, spacing: .large),
.bulletPoint(text: AppStrings.ExposureSubmissionResult.furtherInfos_TestAgain, spacing: .large)
]
)
}
private func invalidTestResultSection() -> DynamicSection {
.section(
header: .identifier(
ExposureSubmissionTestResultViewController.HeaderReuseIdentifier.testResult,
configure: { view, _ in
(view as? ExposureSubmissionTestResultHeaderView)?.configure(testResult: .invalid, timeStamp: self.timeStamp)
}
),
separators: .none,
cells: [
.title2(text: AppStrings.ExposureSubmissionResult.procedure,
accessibilityIdentifier: AccessibilityIdentifiers.ExposureSubmissionResult.procedure),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testAdded,
description: AppStrings.ExposureSubmissionResult.testAddedDesc,
icon: UIImage(named: "Icons_Grey_Check"),
hairline: .iconAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testInvalid,
description: AppStrings.ExposureSubmissionResult.testInvalidDesc,
icon: UIImage(named: "Icons_Grey_Error"),
hairline: .topAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testRemove,
description: AppStrings.ExposureSubmissionResult.testRemoveDesc,
icon: UIImage(named: "Icons_Grey_Entfernen"),
hairline: .none
)
]
)
}
private func redeemedTestResultSection() -> DynamicSection {
.section(
header: .identifier(
ExposureSubmissionTestResultViewController.HeaderReuseIdentifier.testResult,
configure: { view, _ in
(view as? ExposureSubmissionTestResultHeaderView)?.configure(testResult: .invalid, timeStamp: self.timeStamp)
}
),
separators: .none,
cells: [
.title2(text: AppStrings.ExposureSubmissionResult.procedure,
accessibilityIdentifier: AccessibilityIdentifiers.ExposureSubmissionResult.procedure),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testAdded,
description: AppStrings.ExposureSubmissionResult.testAddedDesc,
icon: UIImage(named: "Icons_Grey_Check"),
hairline: .iconAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testRedeemed,
description: AppStrings.ExposureSubmissionResult.testRedeemedDesc,
icon: UIImage(named: "Icons_Grey_Error"),
hairline: .topAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testRemove,
description: AppStrings.ExposureSubmissionResult.testRemoveDesc,
icon: UIImage(named: "Icons_Grey_Entfernen"),
hairline: .none
)
]
)
}
private func pendingTestResultSection() -> DynamicSection {
.section(
header: .identifier(
ExposureSubmissionTestResultViewController.HeaderReuseIdentifier.testResult,
configure: { view, _ in
(view as? ExposureSubmissionTestResultHeaderView)?.configure(testResult: .pending, timeStamp: self.timeStamp)
}
),
cells: [
.title2(text: AppStrings.ExposureSubmissionResult.procedure,
accessibilityIdentifier: AccessibilityIdentifiers.ExposureSubmissionResult.procedure),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testAdded,
description: AppStrings.ExposureSubmissionResult.testAddedDesc,
icon: UIImage(named: "Icons_Grey_Check"),
hairline: .iconAttached
),
ExposureSubmissionDynamicCell.stepCell(
title: AppStrings.ExposureSubmissionResult.testPending,
description: AppStrings.ExposureSubmissionResult.testPendingDesc,
icon: UIImage(named: "Icons_Grey_Wait"),
hairline: .none
)
]
)
}
}
| 32.879464 | 148 | 0.768296 |
f8c582ba8d66bc8ab70232245afd75b7c54799ba | 342 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func < {
{
}
class k { { }
{
{
}
}
class a<f : b, l {
}
protocol b {
typealias k
}
struct j<n > : b {
typealias l = n
typealias k = a<j<n> , l>
func e {
class m {
{
}
}
m {
| 12.666667 | 87 | 0.628655 |
dd7743832ca8b02ca81e426a9b7c2007cc5ebf72 | 2,480 | //
// Copyright © 2021 Stream.io Inc. All rights reserved.
//
import Foundation
/// Read-only collection that applies transformation to element on first access.
///
/// Compared to `LazyMapCollection` does not evaluate the whole collection on `count` call.
public struct LazyCachedMapCollection<Element>: RandomAccessCollection {
public typealias Index = Int
public func index(before i: Index) -> Index {
cache.values.index(before: i)
}
public func index(after i: Index) -> Index {
cache.values.index(after: i)
}
public var startIndex: Index { cache.values.startIndex }
public var endIndex: Index { cache.values.endIndex }
public var count: Index { cache.values.count }
public init<Collection: RandomAccessCollection, SourceElement>(
source: Collection,
map: @escaping (SourceElement) -> Element
) where Collection.Element == SourceElement, Collection.Index == Index {
generator = { map(source[$0]) }
cache = .init(capacity: source.count)
}
private var generator: (Index) -> Element
private var cache: Cache<Element>
public subscript(position: Index) -> Element {
if let cached = cache.values[position] {
return cached
} else {
let value = generator(position)
defer { cache.values[position] = value }
return value
}
}
}
extension LazyCachedMapCollection: ExpressibleByArrayLiteral {
public typealias ArrayLiteralElement = Element
public init(arrayLiteral elements: Element...) {
generator = { elements[$0] }
cache = .init(capacity: elements.count)
}
}
extension LazyCachedMapCollection: Equatable where Element: Equatable {
public static func == (lhs: LazyCachedMapCollection<Element>, rhs: LazyCachedMapCollection<Element>) -> Bool {
guard lhs.count == rhs.count else { return false }
return zip(lhs, rhs).allSatisfy(==)
}
}
extension RandomAccessCollection where Index == Int {
/// Lazily apply transformation to sequence
public func lazyCachedMap<T>(_ transformation: @escaping (Element) -> T) -> LazyCachedMapCollection<T> {
.init(source: self, map: transformation)
}
}
// Must be class so it can be mutable while the collection isn't
private class Cache<Element> {
init(capacity: Int) {
values = ContiguousArray(repeating: nil, count: capacity)
}
var values: ContiguousArray<Element?>
}
| 31 | 114 | 0.670565 |
e8034bc6ecf8a4f3813f8cf71dbd97c983c85008 | 616 | //
// FastAdapterCollectionView.swift
// FastAdapter
//
// Created by Fabian Terhorst on 24.07.18.
// Copyright © 2018 everHome. All rights reserved.
//
import UIKit
import Foundation
open class FastAdapterCollectionView<Itm: Item>: UICollectionView {
public weak var fastAdapter: FastAdapter<Itm>?
public override init(frame: CGRect, collectionViewLayout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: collectionViewLayout)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 25.666667 | 87 | 0.714286 |
145e184418b5d083750ee5f5a20c7c78a0175b69 | 1,426 | //
// AppDelegate.swift
// sample-app
//
// Created by Alexey Alter Pesotskiy on 20/06/2020.
// Copyright © 2020 alteral. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.526316 | 179 | 0.748247 |
2942d290ba80401f21018d8a348d7007d4797a36 | 9,464 | /*
* file MachineFilteredLocalisationVision.swift
*
* This file was generated by classgenerator from machine_filtered_localisation_vision.gen.
* DO NOT CHANGE MANUALLY!
*
* Copyright © 2020 Callum McColl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgement:
*
* This product includes software developed by Callum McColl.
*
* 4. Neither the name of the author nor the names of contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* -----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or
* modify it under the above terms or under the terms of the GNU
* General Public License as published by the Free Software Foundation;
* either version 2 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/
* or write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
//swiftlint:disable superfluous_disable_command
//swiftlint:disable type_body_length
//swiftlint:disable function_body_length
//swiftlint:disable file_length
//swiftlint:disable line_length
//swiftlint:disable identifier_name
#if canImport(swiftfsm)
import swiftfsm
#endif
/**
* Results of the FSM (and sub machines) "SMFilterVision".
* This machine applies some basic filtering to vision output messages.
* It also handles the coord conversion and kinematics for distance and bearing calculations on the Nao robot.
*/
public struct MachineFilteredLocalisationVision {
public var _raw: wb_machine_filtered_localisation_vision
public var numberOfSightings: UInt8 {
get {
return self._raw.numberOfSightings
} set {
self._raw.numberOfSightings = newValue
}
}
public var sightings: [LandmarkSighting] {
get {
var sightings = self._raw.sightings
return withUnsafePointer(to: &sightings.0) { sightings_p in
var sightings: [LandmarkSighting] = []
sightings.reserveCapacity(12)
for sightings_index in 0..<12 {
sightings.append(LandmarkSighting(sightings_p[sightings_index]))
}
return sightings
}
} set {
_ = withUnsafeMutablePointer(to: &self._raw.sightings.0) { sightings_p in
for sightings_index in 0..<min(12, newValue.count) {
sightings_p[sightings_index] = newValue[sightings_index]._raw
}
}
}
}
public var computedVars: [String: Any] {
return [
"numberOfSightings": self._raw.numberOfSightings,
"sightings": self._raw.sightings
]
}
public var manipulators: [String: (Any) -> Any] {
return [:]
}
public var validVars: [String: [Any]] {
return ["_raw": []]
}
/**
* Create a new `wb_machine_filtered_localisation_vision`.
*/
public init(numberOfSightings: UInt8 = 0, sightings: [LandmarkSighting] = [LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting()), LandmarkSighting(wb_landmark_sighting())]) {
self._raw = wb_machine_filtered_localisation_vision()
self.numberOfSightings = numberOfSightings
self.sightings = sightings
}
/**
* Create a new `wb_machine_filtered_localisation_vision`.
*/
public init(_ rawValue: wb_machine_filtered_localisation_vision) {
self._raw = rawValue
}
/**
* Create a `wb_machine_filtered_localisation_vision` from a dictionary.
*/
public init(fromDictionary dictionary: [String: Any?]) {
self.init()
guard
let numberOfSightings = dictionary["numberOfSightings"] as? UInt8,
let sightings = dictionary["sightings"] as? [LandmarkSighting]
else {
fatalError("Unable to convert \(dictionary) to wb_machine_filtered_localisation_vision.")
}
self.numberOfSightings = numberOfSightings
self.sightings = sightings
}
private func firstSighting(sightingType: LandmarkSightingType) -> LandmarkSighting? {
for sighting in sightings {
if sighting.sightingType == sightingType {
return sighting
}
}
return nil
}
public var ball: LandmarkSighting? {
return firstSighting(sightingType: BallSightingType)
}
public var firstGenericGoalPost: LandmarkSighting? {
return firstSighting(sightingType: GenericGoalPostSightingType)
}
public var leftGoalPost: LandmarkSighting? {
return firstSighting(sightingType: LeftGoalPostSightingType)
}
public var rightGoalPost: LandmarkSighting? {
return firstSighting(sightingType: RightGoalPostSightingType)
}
public var goal: LandmarkSighting? {
return firstSighting(sightingType: GoalLandmarkSightingType)
}
public var lineHorizon: LandmarkSighting? {
return firstSighting(sightingType: LineHorizonSightingType)
}
public var cornerHorizon: LandmarkSighting? {
return firstSighting(sightingType: CornerHorizonSightingType)
}
public var horizon: LandmarkSighting? {
guard let lineSighting = lineHorizon else {
return cornerHorizon
}
return lineSighting
}
public var line: LandmarkSighting? {
return firstSighting(sightingType: StraightLineSightingType)
}
public var cornerLine: LandmarkSighting? {
return firstSighting(sightingType: CornerLineSightingType)
}
public var tLine: LandmarkSighting? {
return firstSighting(sightingType: TIntersectionLineSightingType)
}
public var crossLine: LandmarkSighting? {
return firstSighting(sightingType: CrossLineSightingType)
}
}
extension MachineFilteredLocalisationVision: CustomStringConvertible {
/**
* Convert to a description String.
*/
public var description: String {
var descString = ""
descString += "numberOfSightings=\(self.numberOfSightings)"
descString += ", "
if self.sightings.isEmpty {
descString += "sightings={}"
} else {
let first = "{" + self.sightings[0].description + "}"
descString += "sightings={"
descString += self.sightings.dropFirst().reduce("\(first)") { $0 + ", " + "{" + $1.description + "}" }
descString += "}"
}
return descString
}
}
extension MachineFilteredLocalisationVision: Equatable {}
public func == (lhs: MachineFilteredLocalisationVision, rhs: MachineFilteredLocalisationVision) -> Bool {
return lhs.numberOfSightings == rhs.numberOfSightings
&& lhs.sightings == rhs.sightings
}
extension wb_machine_filtered_localisation_vision: Equatable {}
public func == (lhs: wb_machine_filtered_localisation_vision, rhs: wb_machine_filtered_localisation_vision) -> Bool {
return MachineFilteredLocalisationVision(lhs) == MachineFilteredLocalisationVision(rhs)
}
#if canImport(swiftfsm)
extension MachineFilteredLocalisationVision: ExternalVariables, KripkeVariablesModifier {}
#endif
| 37.259843 | 585 | 0.694738 |
d932a352e882c4ce697ffb9a9fc23ee9d0f0ead4 | 2,685 | /**
* (C) Copyright IBM Corp. 2020.
*
* 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
/**
Response payload for languages.
*/
public struct Language: Codable, Equatable {
/**
The language code for the language (for example, `af`).
*/
public var language: String?
/**
The name of the language in English (for example, `Afrikaans`).
*/
public var languageName: String?
/**
The native name of the language (for example, `Afrikaans`).
*/
public var nativeLanguageName: String?
/**
The country code for the language (for example, `ZA` for South Africa).
*/
public var countryCode: String?
/**
Indicates whether words of the language are separated by whitespace: `true` if the words are separated; `false`
otherwise.
*/
public var wordsSeparated: Bool?
/**
Indicates the direction of the language: `right_to_left` or `left_to_right`.
*/
public var direction: String?
/**
Indicates whether the language can be used as the source for translation: `true` if the language can be used as the
source; `false` otherwise.
*/
public var supportedAsSource: Bool?
/**
Indicates whether the language can be used as the target for translation: `true` if the language can be used as the
target; `false` otherwise.
*/
public var supportedAsTarget: Bool?
/**
Indicates whether the language supports automatic detection: `true` if the language can be detected automatically;
`false` otherwise.
*/
public var identifiable: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case language = "language"
case languageName = "language_name"
case nativeLanguageName = "native_language_name"
case countryCode = "country_code"
case wordsSeparated = "words_separated"
case direction = "direction"
case supportedAsSource = "supported_as_source"
case supportedAsTarget = "supported_as_target"
case identifiable = "identifiable"
}
}
| 30.862069 | 120 | 0.678212 |
6afbfa1930db0a93295d401dac748e8e3eb74d2d | 15,723 | //
// ProfileViewController.swift
// swaap
//
// Created by Marlon Raskin on 11/22/19.
// Copyright © 2019 swaap. All rights reserved.
//
import UIKit
import NetworkHandler
/// This was originally designed with only displaying the current user in mind. Functionality to display the current
/// user's contacts was somewhat grafted on, not always elegantly. It could probably use a little refactoring to make
/// it a bit smoother. (But it works, so don't fret too much)
class ProfileViewController: UIViewController, Storyboarded, ProfileAccessor, ContactsAccessor {
@IBOutlet private weak var noInfoDescLabel: UILabel!
@IBOutlet private weak var profileCardView: ProfileCardView!
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet private weak var backButtonVisualFXContainerView: UIVisualEffectView!
@IBOutlet private weak var editProfileButtonVisualFXContainerView: UIVisualEffectView!
@IBOutlet private weak var backButton: UIButton!
@IBOutlet private weak var socialButtonsStackView: UIStackView!
@IBOutlet private weak var birthdayHeaderContainer: UIView!
@IBOutlet private weak var birthdayLabelContainer: UIView!
@IBOutlet private weak var birthdayLabel: UILabel!
@IBOutlet private weak var bioHeaderContainer: UIView!
@IBOutlet private weak var bioLabelContainer: UIView!
@IBOutlet private weak var bioLabel: UILabel!
@IBOutlet private weak var notesHeaderContainer: UIView!
@IBOutlet private weak var notesLabelContainer: UIView!
@IBOutlet private weak var notesLabel: UILabel!
@IBOutlet private weak var notesField: BasicInfoView!
@IBOutlet private weak var eventsHeaderContainer: UIView!
@IBOutlet private weak var eventsLabelContainer: UIView!
@IBOutlet private weak var eventsLabel: UILabel!
@IBOutlet private weak var eventsField: BasicInfoView!
@IBOutlet private weak var locationViewContainer: UIView!
@IBOutlet private weak var locationView: BasicInfoView!
@IBOutlet private weak var birthdayImageContainerView: UIView!
@IBOutlet private weak var bioImageViewContainer: UIView!
@IBOutlet private weak var modesOfContactHeaderContainer: UIView!
@IBOutlet private weak var modesOfContactPreviewStackView: UIStackView!
@IBOutlet private weak var modesOfContactImageViewContainer: UIView!
@IBOutlet private weak var locationMapViewContainer: UIView!
@IBOutlet private weak var locationmapView: MeetingLocationView!
@IBOutlet private weak var bottomFadeView: UIView!
@IBOutlet private weak var bottomFadeviewBottomConstraint: NSLayoutConstraint!
var profileController: ProfileController?
var profileChangedObserver: NSObjectProtocol?
var contactsController: ContactsController?
var floatingTextField: FloatingTextFieldView?
override var prefersStatusBarHidden: Bool {
profileCardView?.isAtTop ?? false
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
.slide
}
var contact: ConnectionContact?
var aContact: Contact?
var userProfile: UserProfile? {
didSet { updateViews() }
}
var meetingCoordinate: MeetingCoordinate? {
didSet {
updateViews()
}
}
var isCurrentUser = false
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
configureProfileCard()
setupCardShadow()
setupFXView()
updateViews()
setupNotifications()
locationViewContainer.isVisible = UIScreen.main.bounds.height <= 667
if let appearance = tabBarController?.tabBar.standardAppearance.copy() {
appearance.backgroundImage = UIImage()
appearance.shadowImage = UIImage()
appearance.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.5)
appearance.shadowColor = .clear
tabBarItem.standardAppearance = appearance
}
updateFadeViewPosition()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setupCardShadow()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
profileCardView.setupImageView()
updateViews()
tabBarController?.delegate = self
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
tabBarController?.delegate = nil
}
private func configureProfileCard() {
profileCardView.layer.cornerRadius = 20
profileCardView.layer.cornerCurve = .continuous
profileCardView.isSmallProfileCard = false
profileCardView.delegate = self
}
private func updateViews() {
guard isViewLoaded else { return }
profileCardView.userProfile = userProfile
birthdayLabel.text = userProfile?.birthdate
bioLabel.text = userProfile?.bio ?? "No bio"
notesLabel.text = userProfile?.notes
eventsLabel.text = userProfile?.events
locationView.valueText = userProfile?.location
locationView.customSubview = nil
editProfileButtonVisualFXContainerView.isVisible = isCurrentUser
populateSocialButtons()
if let count = navigationController?.viewControllers.count, count > 1 {
backButtonVisualFXContainerView.isHidden = false
} else {
backButtonVisualFXContainerView.isHidden = true
}
birthdayImageContainerView.isVisible = shouldShowIllustration(infoValueType: .string(birthdayLabel?.text))
[birthdayHeaderContainer, birthdayLabelContainer].forEach {
$0?.isVisible = shouldShowLabelInfo(infoValueType: .string(birthdayLabel?.text))
}
bioImageViewContainer.isVisible = shouldShowIllustration(infoValueType: .string(bioLabel?.text))
[bioHeaderContainer, bioLabelContainer].forEach {
$0?.isVisible = shouldShowLabelInfo(infoValueType: .string(bioLabel?.text))
}
let hasSocialButtons = !socialButtonsStackView.arrangedSubviews.isEmpty
socialButtonsStackView.isVisible = hasSocialButtons
modesOfContactPreviewStackView.isVisible = shouldShowIllustration(infoValueType: .hasContents(hasSocialButtons))
modesOfContactHeaderContainer.isVisible = shouldShowIllustration(infoValueType: .hasContents(hasSocialButtons))
locationMapViewContainer.isHidden = meetingCoordinate == nil
locationmapView.location = meetingCoordinate
shouldShowNoInfoLabel()
// the current user image is loaded through the profile controller and shown when populated after a notification comes through, but
// that doesn't happen for a user's contacts, so this is set to run when showing a connection's profile
if !isCurrentUser, userProfile?.photoData == nil, let imageURL = userProfile?.pictureURL {
profileController?.fetchImage(url: imageURL, completion: { [weak self] result in
do {
let imageData = try result.get()
DispatchQueue.main.async {
self?.userProfile?.photoData = imageData
}
} catch {
NSLog("Error updating contact image: \(error)")
}
})
}
if isCurrentUser {
notesHeaderContainer.isHidden = true
notesField.isHidden = true
eventsHeaderContainer.isHidden = true
eventsField.isHidden = true
}
}
func updateNotes() {
guard let userProfile = userProfile,
let contact = contact,
let connectionID = contact.connectionID,
let notes = notesLabel.text else { return }
if userProfile.id == contact.id {
contactsController?.updateSenderNotes(toConnectionID: connectionID, senderNote: notes, completion: completionBlock())
} else {
contactsController?.updateSenderNotes(toConnectionID: connectionID, receiverNote: notes, completion: completionBlock())
}
}
func updateEvents() {
guard let userProfile = userProfile,
let contact = contact,
let connectionID = contact.connectionID,
let events = eventsLabel.text else { return }
if userProfile.id == contact.id {
contactsController?.updateSenderEvents(toConnectionID: connectionID, senderEvent: events, completion: completionBlock())
} else {
contactsController?.updateSenderEvents(toConnectionID: connectionID, receiverEvent: events, completion: completionBlock())
}
}
func completionBlock() -> (Result<GQLMutationResponse, NetworkError>) -> Void {
let closure = { (result: Result<GQLMutationResponse, NetworkError>) -> Void in
switch result {
case .success:
break
case .failure(let error):
NSLog("Error: \(error)")
}
}
return closure
}
enum InfoValueType {
case string(String?)
case hasContents(Bool)
}
private func shouldShowIllustration(infoValueType: InfoValueType) -> Bool {
guard isCurrentUser else { return false }
switch infoValueType {
case .string(let labelText):
return labelText?.isEmpty ?? true
case .hasContents(let hasContents):
return !hasContents
}
}
private func shouldShowLabelInfo(infoValueType: InfoValueType) -> Bool {
guard !isCurrentUser else { return true }
switch infoValueType {
case .string(let labelText):
return labelText?.isNotEmpty ?? false
case .hasContents(let hasContents):
return hasContents
}
}
private func shouldShowNoInfoLabel() {
guard !isCurrentUser else { return }
let name = userProfile?.name ?? "This user"
noInfoDescLabel.text = "\(name) hasn't added any info yet."
let contentsAreEmpty = [birthdayLabelContainer, bioLabelContainer, modesOfContactHeaderContainer].allSatisfy({ $0?.isVisible == false })
noInfoDescLabel.isVisible = contentsAreEmpty
}
private func shouldShowNotesAndEvents() {
guard !isCurrentUser else { return }
}
private func populateSocialButtons() {
guard let profileContactMethods = userProfile?.profileContactMethods else { return }
socialButtonsStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
profileContactMethods.forEach {
guard !$0.preferredContact else { return }
let contactMethodCell = ContactMethodCellView(contactMethod: $0, mode: .display)
contactMethodCell.contactMethod = $0
socialButtonsStackView.addArrangedSubview(contactMethodCell)
}
}
private func setupNotifications() {
guard isCurrentUser else { return }
let updateClosure = { [weak self] (_: Notification) in
DispatchQueue.main.async {
guard self?.isCurrentUser == true else { return }
self?.userProfile = self?.profileController?.userProfile
}
}
profileChangedObserver = NotificationCenter.default.addObserver(forName: .userProfileChanged, object: nil, queue: nil, using: updateClosure)
}
private func setupCardShadow() {
profileCardView.layer.shadowPath = UIBezierPath(rect: profileCardView.bounds).cgPath
profileCardView.layer.shadowRadius = 14
profileCardView.layer.shadowOffset = .zero
profileCardView.layer.shadowOpacity = 0.3
}
private func setupFXView() {
backButtonVisualFXContainerView.layer.cornerRadius = backButtonVisualFXContainerView.frame.height / 2
backButtonVisualFXContainerView.clipsToBounds = true
editProfileButtonVisualFXContainerView.layer.cornerRadius = editProfileButtonVisualFXContainerView.frame.height / 2
editProfileButtonVisualFXContainerView.clipsToBounds = true
}
// MARK: - Actions
@IBAction func backbuttonTapped(_ sender: UIButton) {
navigationController?.popViewController(animated: true)
try? CoreDataStack.shared.save(context: CoreDataStack.shared.mainContext)
}
@IBSegueAction func editButtonTappedSegue(_ coder: NSCoder) -> UINavigationController? {
SwipeBackNavigationController(coder: coder, profileController: profileController)
}
@IBAction func updateNoteButton(_ sender: Any) {
let alertController = UIAlertController(title: "Create a note", message: "", preferredStyle: .alert)
alertController.addTextField { (textField: UITextField!) -> Void in
textField.placeholder = "Add note"
}
let saveAction = UIAlertAction(title: "Save", style: .default, handler: { _ -> Void in
if let noteTextField = alertController.textFields {
let textFields = noteTextField as [UITextField]
let enteredText = textFields[0].text
self.notesLabel.text = enteredText
self.updateNotes()
if let notes = self.notesLabel.text {
if let contact = self.contact {
self.contactsController?.updateNote(note: contact, with: notes, context: CoreDataStack.shared.mainContext)
self.userProfile?.notes = notes
} else {
self.contactsController?.createNote(with: notes, context: CoreDataStack.shared.mainContext)
self.userProfile?.notes = notes
}
}
}
})
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil )
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
@IBAction func updateEventButton(_ sender: Any) {
let alertController = UIAlertController(title: "Create an event", message: "", preferredStyle: .alert)
alertController.addTextField { (textField: UITextField!) -> Void in
textField.placeholder = "Add event"
}
let saveAction = UIAlertAction(title: "Save", style: .default, handler: { _ -> Void in
if let eventTextField = alertController.textFields {
let textFields = eventTextField as [UITextField]
let enteredText = textFields[0].text
self.eventsLabel.text = enteredText
if let events = self.eventsLabel.text {
if let contact = self.contact {
self.contactsController?.updateEvent(event: contact, with: events, context: CoreDataStack.shared.mainContext)
} else {
self.contactsController?.createEvent(with: events, context: CoreDataStack.shared.mainContext)
}
}
}
})
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil )
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
extension ProfileViewController: ProfileCardViewDelegate {
func updateFadeViewPosition() {
let currentProgress = max(profileCardView.currentSlidingProgress, 0)
bottomFadeviewBottomConstraint.constant = CGFloat(currentProgress * -120)
}
func profileCardDidFinishAnimation(_ card: ProfileCardView) {
UIView.animate(withDuration: 0.3) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
func positionDidChange(on view: ProfileCardView) {
updateFadeViewPosition()
}
}
extension ProfileViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y <= -120 {
scrollView.isScrollEnabled = false
HapticFeedback.produceRigidFeedback()
profileCardView.animateToPrimaryPosition()
scrollView.isScrollEnabled = true
}
}
}
extension ProfileViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
guard viewController == self.navigationController else { return }
profileController?.fetchProfileFromServer(completion: { _ in })
}
}
| 38.442543 | 142 | 0.721046 |
e98e4f1f6943cf04356ecee9af5ed3ecd498e7c7 | 4,831 | //
// VGSAPIClientSatelliteTests.swift
// VGSCheckoutSDKTests
import Foundation
import XCTest
@testable import VGSCheckoutSDK
/// Tests for API cleint and satellite configuration: verify API URL policy setup.
class VGSAPIClientSatelliteTests: VGSCheckoutBaseTestCase {
/// Valid tenant ID.
let tenantID: String = "testID"
/// Holds satellite test data.
struct APISatelliteTestData {
let environment: String
let hostname: String?
let port: Int?
let url: URL
}
/// Set up satellite tests.
override class func setUp() {
super.setUp()
// Disable satellite assetions for unit tests.
VGSCollectSatelliteUtils.isAssertionsEnabled = false
}
/// Tear down flow.
override class func tearDown() {
super.tearDown()
// Enable satellite assertions.
VGSCollectSatelliteUtils.isAssertionsEnabled = true
}
/// Test `API` valid satellite configurations to be resolved to `.satelliteURL` policy.
func testAPIURLPolicyValidSatellite() {
let testData = [
APISatelliteTestData(environment: "sandbox", hostname: "localhost", port: 9908, url: URL(string: "http://localhost:9908")!),
APISatelliteTestData(environment: "sandbox", hostname: "192.168.0", port: 9908, url: URL(string: "http://192.168.0:9908")!),
APISatelliteTestData(environment: "sandbox", hostname: "192.168.1.5", port: 9908, url: URL(string: "http://192.168.1.5:9908")!),
APISatelliteTestData(environment: "sandbox", hostname: "http://192.168.1.5", port: 9908, url: URL(string: "http://192.168.1.5:9908")!)
]
for index in 0..<testData.count {
let config = testData[index]
let mockedFormData = VGSCheckoutFormAnanlyticsDetails(formId: "123", tenantId: tenantID, environment: config.environment)
let outputText = "index: \(index) satellite configuration with environment: \(config.environment) hostname: \(config.hostname ?? "*nil*") port: \(config.port!) should produce: \(config.url)"
let client = APIClient(tenantId: tenantID, regionalEnvironment: config.environment, hostname: config.hostname, formAnalyticsDetails: mockedFormData, satellitePort: config.port)
XCTAssertTrue(client.formAnalyticDetails.isSatelliteMode == true, "\(outputText) should produce *satellite* mode in analytics")
switch client.hostURLPolicy {
case .satelliteURL(let url):
XCTAssertTrue(url == config.url, outputText)
case .invalidVaultURL:
XCTFail("\(outputText). API policy is *invalidURL*. Should be *satelliteURL* policy!!!")
case .customHostURL:
XCTFail("\(outputText). API policy is *customHostURL*. Should be *satelliteURL* policy URL mode!!!")
case .vaultURL:
XCTFail("\(outputText). API policy is *vaultURL*. Should be *satelliteURL* policy URL mode!!!")
}
}
}
/// Test `API` invalid satellite configurations to be resolved to `.vaultURL` policy.
func testAPIURLPolicyInValidSatellite() {
let testData = [
APISatelliteTestData(environment: "live", hostname: "localhost", port: 9908, url: URL(string: "https://testID.live.verygoodproxy.com")!),
APISatelliteTestData(environment: "live-eu", hostname: "192.168.0", port: 9908, url: URL(string: "https://testID.live-eu.verygoodproxy.com")!),
APISatelliteTestData(environment: "sandbox", hostname: nil, port: 9908, url: URL(string: "https://testID.sandbox.verygoodproxy.com")!),
APISatelliteTestData(environment: "sandbox", hostname: nil, port: nil, url: URL(string: "https://testID.sandbox.verygoodproxy.com")!),
APISatelliteTestData(environment: "live", hostname: "http://192.168.1.5", port: 9908, url: URL(string: "https://testID.live.verygoodproxy.com")!)
]
for index in 0..<testData.count {
let config = testData[index]
var portText = "nil"
if let port = config.port {
portText = "\(port)"
}
let mockedFormData = VGSCheckoutFormAnanlyticsDetails(formId: "123", tenantId: tenantID, environment: config.environment)
let outputText = "index: \(index) satellite configuration with environment: \(config.environment) hostname: \(config.hostname ?? "*nil*") port: \(portText) should produce *nil*"
let client = APIClient(tenantId: tenantID, regionalEnvironment: config.environment, hostname: config.hostname, formAnalyticsDetails: mockedFormData, satellitePort: config.port)
XCTAssertTrue(client.formAnalyticDetails.isSatelliteMode == false, "\(outputText) should NOT produce satellite mode in analytics")
switch client.hostURLPolicy {
case .vaultURL(let url):
XCTAssertTrue(url == config.url, outputText)
case .satelliteURL:
XCTFail("\(outputText). API policy is *satellite*. Should be *vaultURL* policy!!!")
case .invalidVaultURL:
XCTFail("\(outputText). API policy is *invalidURL*. Should be *vaultURL* policy!!!")
case .customHostURL:
XCTFail("\(outputText). API policy is *customHostURL*. Should be *vaultURL* policy URL mode!!!")
}
}
}
}
| 43.133929 | 193 | 0.725523 |
7604b7f0b68ebe84b6b78e788dc377a8c899c165 | 6,612 | //
// HashtagsVC.swift
// Instagram
//
// Created by 刘铭 on 16/8/10.
// Copyright © 2016年 刘铭. All rights reserved.
//
import UIKit
import AVOSCloud
var hashtag = [String]()
class HashtagsVC: UICollectionViewController,UICollectionViewDelegateFlowLayout {
// UI objects
var refresher: UIRefreshControl!
var page: Int = 24
// 从云端获取记录后,存储数据的数组
var picArray = [AVFile]()
var uuidArray = [String]()
var filterArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.alwaysBounceVertical = true
self.navigationItem.title = "#" + "\(hashtag.last!.uppercased())"
// 定义导航栏中新的返回按钮
self.navigationItem.hidesBackButton = true
//let backBtn = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(back(_:)))
let backBtn = UIBarButtonItem(image: UIImage(named: "back.png"), style: .plain, target: self, action: #selector(back(_:)))
self.navigationItem.leftBarButtonItem = backBtn
// 实现向右划动返回
let backSwipe = UISwipeGestureRecognizer(target: self, action: #selector(back(_:)))
backSwipe.direction = .right
self.view.addGestureRecognizer(backSwipe)
// 安装refresh控件
refresher = UIRefreshControl()
refresher.addTarget(self, action: #selector(refresh), for: .valueChanged)
self.collectionView?.addSubview(refresher)
loadHashtags()
}
func back(_: UIBarButtonItem) {
// 退回到之前的控制器
_ = self.navigationController?.popViewController(animated: true)
// 从hashtag数组中移除最后一个主题标签
if !hashtag.isEmpty {
hashtag.removeLast()
}
}
// 刷新方法
func refresh() {
loadHashtags()
}
// 载入hashtag
func loadHashtags() {
// STEP 1. 获取与Hashtag相关的帖子
let hashtagQuery = AVQuery(className: "Hashtags")
hashtagQuery?.whereKey("hashtag", equalTo: hashtag.last!)
hashtagQuery?.findObjectsInBackground({ (objects:[AnyObject]?, error:Error?) in
if error == nil {
// 清空 filterArray 数组
self.filterArray.removeAll(keepingCapacity: false)
// 存储相关的帖子到filterArray数组
for object in objects! {
self.filterArray.append(object.value(forKey: "to") as! String)
}
// STEP 2. 通过filterArray的uuid,找出相关的帖子
let query = AVQuery(className: "Posts")
query?.whereKey("puuid", containedIn: self.filterArray)
query?.limit = self.page
query?.addDescendingOrder("createdAt")
query?.findObjectsInBackground({ (objects:[AnyObject]?, error:Error?) in
if error == nil {
// 清空数组
self.picArray.removeAll(keepingCapacity: false)
self.uuidArray.removeAll(keepingCapacity: false)
for object in objects! {
self.picArray.append(object.value(forKey: "pic") as! AVFile)
self.uuidArray.append(object.value(forKey: "puuid") as! String)
}
// reload
self.collectionView?.reloadData()
self.refresher.endRefreshing()
}else {
print(error?.localizedDescription)
}
})
}else {
print(error?.localizedDescription)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
// 设置单元格大小
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = CGSize(width: self.view.frame.width / 3, height: self.view.frame.width / 3)
return size
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 从集合视图的可复用队列中获取单元格对象
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PictureCell
// 从picArray数组中获取图片
picArray[indexPath.row].getDataInBackground { (data:Data?, error:Error?) in
if error == nil {
cell.picImg.image = UIImage(data: data!)
}else{
print(error?.localizedDescription)
}
}
return cell
}
// go post
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 发送post uuid 到 postuuid数组中
postuuid.append(uuidArray[indexPath.row])
// 导航到postVC控制器
let postVC = self.storyboard?.instantiateViewController(withIdentifier: "PostVC") as! PostVC
self.navigationController?.pushViewController(postVC, animated: true)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y >= scrollView.contentSize.height / 3 {
loadMore()
}
}
// 用于分页
func loadMore() {
// 如果服务器端的帖子大于默认显示数量
if page <= uuidArray.count {
page = page + 15
// STEP 1. 获取与Hashtag相关的帖子
let hashtagQuery = AVQuery(className: "Hashtags")
hashtagQuery?.whereKey("hashtag", equalTo: hashtag.last!)
hashtagQuery?.findObjectsInBackground({ (objects:[AnyObject]?, error:Error?) in
if error == nil {
// 清空 filterArray 数组
self.filterArray.removeAll(keepingCapacity: false)
// 存储相关的帖子到filterArray数组
for object in objects! {
self.filterArray.append(object.value(forKey: "to") as! String)
}
// STEP 2. 通过filterArray的uuid,找出相关的帖子
let query = AVQuery(className: "Posts")
query?.whereKey("puuid", containedIn: self.filterArray)
query?.limit = self.page
query?.addDescendingOrder("createdAt")
query?.findObjectsInBackground({ (objects:[AnyObject]?, error:Error?) in
if error == nil {
// 清空数组
self.picArray.removeAll(keepingCapacity: false)
self.uuidArray.removeAll(keepingCapacity: false)
for object in objects! {
self.picArray.append(object.value(forKey: "pic") as! AVFile)
self.uuidArray.append(object.value(forKey: "puuid") as! String)
}
// reload
self.collectionView?.reloadData()
}else {
print(error?.localizedDescription)
}
})
}else {
print(error?.localizedDescription)
}
})
}
}
}
| 31.788462 | 158 | 0.632033 |
01e40cc333e7a3db4795e5a9c7ea40500eb71a3b | 503 | //
// DaraPersistenceManager.swift
// WeatherApp
//
// Created by Genesis Mosquera on 1/21/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import Foundation
final class DataPersistenceManager {
static func documentsDirectory() -> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
}
static func filepathToDocumentsDirectory(filename: String) -> URL {
return documentsDirectory().appendingPathComponent(filename)
}
}
| 26.473684 | 88 | 0.71173 |
fe15fff253bc046f85ce656d0fdd097437c3b526 | 6,033 | //===--- LazyCollection.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection on which normally-eager operations such as `map` and
/// `filter` are implemented lazily.
///
/// Please see `LazySequenceProtocol` for background; `LazyCollectionProtocol`
/// is an analogous component, but for collections.
///
/// To add new lazy collection operations, extend this protocol with
/// methods that return lazy wrappers that are themselves
/// `LazyCollectionProtocol`s.
///
/// - See Also: `LazySequenceProtocol`, `LazyCollection`
public protocol LazyCollectionProtocol
: Collection, LazySequenceProtocol {
/// A `Collection` that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// - See also: `elements`
associatedtype Elements : Collection = Self
}
/// When there's no special associated `Elements` type, the `elements`
/// property is provided.
extension LazyCollectionProtocol where Elements == Self {
/// Identical to `self`.
public var elements: Self { return self }
}
/// A collection containing the same elements as a `Base` collection,
/// but on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceProtocol`, `LazyCollection`
public struct LazyCollection<Base : Collection>
: LazyCollectionProtocol {
/// The type of the underlying collection
public typealias Elements = Base
/// The underlying collection
public var elements: Elements { return _base }
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Base.Index
/// Construct an instance with `base` as its underlying Collection
/// instance.
internal init(_base: Base) {
self._base = _base
}
internal var _base: Base
}
/// Forward implementations to the base collection, to pick up any
/// optimizations it might implement.
extension LazyCollection : Sequence {
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
public func makeIterator() -> Base.Iterator {
return _base.makeIterator()
}
/// Returns a value less than or equal to the number of elements in
/// `self`, **nondestructively**.
///
/// - Complexity: O(N).
public var underestimatedCount: Int { return _base.underestimatedCount }
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Iterator.Element> {
return _base._copyToNativeArrayBuffer()
}
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Base.Iterator.Element>
) -> UnsafeMutablePointer<Base.Iterator.Element> {
return _base._copyContents(initializing: ptr)
}
public func _customContainsEquatableElement(
_ element: Base.Iterator.Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
}
extension LazyCollection : Collection {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Base.Index {
return _base.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Base.Index {
return _base.endIndex
}
/// Access the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Base.Iterator.Element {
return _base[position]
}
/// Returns a collection representing a contiguous sub-range of
/// `self`'s elements.
///
/// - Complexity: O(1)
public subscript(bounds: Range<Index>) -> LazyCollection<Slice<Base>> {
return Slice(_base: _base, bounds: bounds).lazy
}
/// Returns `true` iff `self` is empty.
public var isEmpty: Bool {
return _base.isEmpty
}
/// Returns the number of elements.
///
/// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`;
/// O(N) otherwise.
public var count: Index.Distance {
return _base.count
}
// The following requirement enables dispatching for index(of:) when
// the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found;
/// `nil` otherwise.
///
/// - Complexity: O(N).
public func _customIndexOfEquatableElement(
_ element: Base.Iterator.Element
) -> Index?? {
return _base._customIndexOfEquatableElement(element)
}
/// Returns the first element of `self`, or `nil` if `self` is empty.
public var first: Base.Iterator.Element? {
return _base.first
}
}
/// Augment `self` with lazy methods such as `map`, `filter`, etc.
extension Collection {
/// A collection with contents identical to `self`, but on which
/// normally-eager operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See Also: `LazySequenceProtocol`, `LazyCollectionProtocol`.
public var lazy: LazyCollection<Self> {
return LazyCollection(_base: self)
}
}
extension LazyCollectionProtocol {
/// Identical to `self`.
public var lazy: Self { // Don't re-wrap already-lazy collections
return self
}
}
@available(*, unavailable, renamed: "LazyCollectionProtocol")
public typealias LazyCollectionType = LazyCollectionProtocol
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
| 31.097938 | 80 | 0.683242 |
1447dda0ae1ff229457e552d079a8705c28b6790 | 839 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import UIKit
import FeedFeature
final class FeedViewAdapter: FeedView {
private weak var controller: FeedViewController?
private let imageLoader: FeedImageDataLoader
init(controller: FeedViewController, imageLoader: FeedImageDataLoader) {
self.controller = controller
self.imageLoader = imageLoader
}
func display(_ viewModel: FeedViewModel) {
controller?.display(viewModel.feed.map { model in
let adapter = FeedImageDataLoaderPresentationAdapter<WeakRefVirtualProxy<FeedImageCellController>, UIImage>(model: model, imageLoader: imageLoader)
let view = FeedImageCellController(delegate: adapter)
adapter.presenter = FeedImagePresenter(
view: WeakRefVirtualProxy(view),
imageTransformer: UIImage.init)
return view
})
}
}
| 27.064516 | 150 | 0.77354 |
d5a1305832aab7752c287b2dbb1c87016c658ed1 | 457 | //
// MainModule.swift
// IgniteExample
//
// Created by Grzegorz Sagadyn on 22/09/2020.
// Copyright © 2020 IgniteExample. All rights reserved.
//
import Foundation
import Singularity
internal class MainModule: ModuleType {
internal func load(to resolver: ResolverType) {
resolver.register(type: MultiplyServiceType.self) { MultiplyService() }
resolver.register(type: CalculatorAssemblyType.self) { CalculatorAssembly() }
}
}
| 25.388889 | 85 | 0.724289 |
f4dc1053bdc61100f54079b103d7b29e7fc1cb8d | 6,444 | //
// IWStatusFrame.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/15.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
//定义 cell里字控件的间距
private let CELL_CHILD_VIEW_MARGIN :CGFloat = 10
//定义名字字体的大小
let CELL_STATUS_NAME_FONT: CGFloat = 14
//定义创建时间的字体大小
let CELL_STATUS_CREATE_AT_FONT: CGFloat = 10
//微博内容字体的大小
let CELL_STATUS_TEXT_FONT: CGFloat = 15
class IWStatusFrame: NSObject {
var status: IWStatus? {
didSet{
setStatus()
}
}
//整体 原创 view 的 frame
var originalViewF:CGRect?
//头像
var headImageViewF:CGRect?
//姓名
var nameLableF: CGRect?
//vip
var vipImageViewF: CGRect?
//创建时间
var created_atF: CGRect?
//来源
var sourceF: CGRect?
//原创微博内容
var textF: CGRect?
//原创微博的图片
var originalPhotosF: CGRect?
//转发微博的整体 view
var retweetViewF:CGRect?
//转发微博 内容
var retweetTextLabelF: CGRect?
//转发微博的图片
var retweetPhotosF: CGRect?
//计算底部 toolBar的frame
var statusToolBarF:CGRect?
//cell的高度
var cellHeight: CGFloat?
//计算 frame
private func setStatus(){
let status = self.status!
//----------------------------------------计算原创微博的frame-----------------------------------------------------//
//原创整体 view 的 frame
let originalViewX :CGFloat = 0
let originalViewY = CELL_CHILD_VIEW_MARGIN
let originalViewW = SCREEN_W
var originalViewH :CGFloat = 0
//头像
let headImageViewX = CELL_CHILD_VIEW_MARGIN
let headImageViewY = CELL_CHILD_VIEW_MARGIN
let headImageSize = CGSizeMake(35, 35)
headImageViewF = CGRect(origin: CGPointMake(headImageViewX, headImageViewY), size: headImageSize)
//姓名
let nameLabelX = CGRectGetMaxX(headImageViewF!) + CELL_CHILD_VIEW_MARGIN
let nameLabelY = CELL_CHILD_VIEW_MARGIN
let nameLabelSize = status.user!.name!.size(UIFont.systemFontOfSize(CELL_STATUS_NAME_FONT))
nameLableF = CGRect(origin: CGPointMake(nameLabelX, nameLabelY), size: nameLabelSize)
//会员
//frame
let vipImageViewX = CGRectGetMaxX(nameLableF!) + CELL_CHILD_VIEW_MARGIN
let vipImageViewY = headImageViewY
let vipImageVeiwSize = CGSizeMake(nameLabelSize.height, nameLabelSize.height)
vipImageViewF = CGRect(origin: CGPointMake(vipImageViewX, vipImageViewY), size: vipImageVeiwSize)
//创建时间
let created_atX = nameLabelX
let created_atSize = status.created_at!.size(UIFont.systemFontOfSize(CELL_STATUS_CREATE_AT_FONT))
let created_atY = CGRectGetMaxY(headImageViewF!) - created_atSize.height
created_atF = CGRect(origin: CGPointMake(created_atX, created_atY), size: created_atSize)
//微博来源
let sourceX = CGRectGetMaxX(created_atF!) + CELL_CHILD_VIEW_MARGIN
let sourceY = created_atY
let sourceSize = status.source?.size(UIFont.systemFontOfSize(CELL_STATUS_CREATE_AT_FONT))
sourceF = CGRect(origin: CGPointMake(sourceX, sourceY), size: sourceSize!)
//原创微博内容
let textX = CELL_CHILD_VIEW_MARGIN
let textY = CGRectGetMaxY(headImageViewF!) + CELL_CHILD_VIEW_MARGIN
let textSize = status.text?.size(UIFont.systemFontOfSize(CELL_STATUS_TEXT_FONT), constrainedToSize: CGSizeMake(SCREEN_W - 2 * CELL_CHILD_VIEW_MARGIN, CGFloat(MAXFLOAT)))
textF = CGRect(origin: CGPointMake(textX, textY), size: textSize!)
//原创微博整体 view 的 H
originalViewH = CGRectGetMaxY(textF!)
//原创微博的图片
if let originalPhotosUrls = status.pic_urls where status.pic_urls?.count > 0{
let originalPhotosX = CELL_CHILD_VIEW_MARGIN
let originalPhotosY = CGRectGetMaxY(textF!) + CELL_CHILD_VIEW_MARGIN
let originalPhotosSize = IWStatusPhotos.size(originalPhotosUrls.count)
originalPhotosF = CGRect(origin: CGPointMake(originalPhotosX, originalPhotosY), size: originalPhotosSize)
//整体 view 的 y
originalViewH = CGRectGetMaxY(originalPhotosF!)
}
//整体的 view.frame
originalViewF = CGRectMake(originalViewX, originalViewY, originalViewW, originalViewH)
//底部toolBar 的Y
var statusToolBarY = CGRectGetMaxY(originalViewF!)
//----------------------------------------计算转发微博的frame-----------------------------------------------------//
//转发微博的 frame
if let retStatus = status.retweeted_status {
//转发微博的内容frame
let retweetTextLabelX = CELL_CHILD_VIEW_MARGIN
let retweetTextLabelY = CELL_CHILD_VIEW_MARGIN
let retweetTextLabelSize = retStatus.text?.size(UIFont.systemFontOfSize(CELL_STATUS_TEXT_FONT), constrainedToSize: CGSizeMake(SCREEN_W - 2 * CELL_CHILD_VIEW_MARGIN, CGFloat(MAXFLOAT)))
retweetTextLabelF = CGRect(origin: CGPointMake(retweetTextLabelX, retweetTextLabelY), size: retweetTextLabelSize!)
var retweetViewH = CGRectGetMaxY(retweetTextLabelF!)
//转发微博的图片 frame
if let retweetPhotosUrls = retStatus.pic_urls where retStatus.pic_urls?.count>0 {
let retweetPhotosX = CELL_CHILD_VIEW_MARGIN
let retweetPhotosY = CGRectGetMaxY(retweetTextLabelF!) + CELL_CHILD_VIEW_MARGIN
let retweetPhotosSize = IWStatusPhotos.size(retweetPhotosUrls.count)
retweetPhotosF = CGRect(origin: CGPointMake(retweetPhotosX, retweetPhotosY), size: retweetPhotosSize)
retweetViewH = CGRectGetMaxY(retweetPhotosF!)
}
//转发整体 view的 frame
let retweetViewX = CGFloat(0)
let retweetViewY = CGRectGetMaxY(textF!) + CELL_CHILD_VIEW_MARGIN
let retweetViewW = SCREEN_W
retweetViewF = CGRectMake(retweetViewX, retweetViewY, retweetViewW, retweetViewH)
//重新计算底部 toolBar的y
statusToolBarY = CGRectGetMaxY(retweetViewF!)
}
//----------------------------------------计算底部toolBar微博的frame-----------------------------------------------------//
//底部 toolBar 的大小
let statusToolBarX :CGFloat = 0
let statusToolBarSize = CGSizeMake(SCREEN_W, 35)
statusToolBarF = CGRect(origin: CGPointMake(statusToolBarX, statusToolBarY), size: statusToolBarSize)
//cell的高度
cellHeight = CGRectGetMaxY(statusToolBarF!)
}
}
| 42.394737 | 196 | 0.648045 |
8758a4d274ac6304a7d409d879ca454de90288f7 | 8,830 | //
// AppDelegate.swift
// bluefruitconnect
//
// Created by Antonio García on 22/09/15.
// Copyright © 2015 Adafruit. All rights reserved.
//
import Cocoa
@available(OSX 10.13, *)
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
// UI
@IBOutlet weak var peripheralsMenu: NSMenu!
@IBOutlet weak var startScanningMenuItem: NSMenuItem!
@IBOutlet weak var stopScanningMenuItem: NSMenuItem!
// Status Menu
let statusMenu = NSMenu()
var isMenuOpen = false
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Init
peripheralsMenu.delegate = self
peripheralsMenu.autoenablesItems = false
// Check if there is any update to the fimware database
FirmwareUpdater.refreshSoftwareUpdatesDatabase(url: Preferences.updateServerUrl, completion: nil)
// Add system status button
setupStatusButton()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
releaseStatusButton()
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
/*
let appInSystemStatusBar = Preferences.appInSystemStatusBar
return appInSystemStatusBar ? false : true
*/
return true
}
// MARK: System status button
func setupStatusButton() {
statusItem.image = NSImage(named: "sytemstatusicon")
statusItem.alternateImage = NSImage(named: "sytemstatusicon_selected")
statusItem.highlightMode = true
updateStatusTitle()
statusMenu.delegate = self
// Setup contents
statusItem.menu = statusMenu
updateStatusContent(nil)
/* TODO: restore
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(updateStatus(_:)), name: UartDataManager.UartNotifications.DidReceiveData.rawValue, object: nil)
notificationCenter.addObserver(self, selector: #selector(updateStatus(_:)), name: UartDataManager.UartNotifications.DidSendData.rawValue, object: nil)
notificationCenter.addObserver(self, selector: #selector(updateStatus(_:)), name: StatusManager.StatusNotifications.DidUpdateStatus.rawValue, object: nil)
*/
}
func releaseStatusButton() {
/* TODO: restore
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: UartDataManager.UartNotifications.DidReceiveData.rawValue, object: nil)
notificationCenter.removeObserver(self, name: UartDataManager.UartNotifications.DidSendData.rawValue, object: nil)
notificationCenter.removeObserver(self, name: StatusManager.StatusNotifications.DidUpdateStatus.rawValue, object: nil)
*/
}
func statusGeneralAction(_ sender: AnyObject?) {
}
func updateStatus(_ nofitication: Notification?) {
updateStatusTitle()
if isMenuOpen {
updateStatusContent(nil)
}
}
func updateStatusTitle() {
/*TODO: restore
var title: String?
let bleManager = BleManager.sharedInstance
if let featuredPeripheral = bleManager.connectedPeripherals().first {
if featuredPeripheral.isUartAdvertised() {
let receivedBytes = featuredPeripheral.uartData.receivedBytes
let sentBytes = featuredPeripheral.uartData.sentBytes
title = "\(sentBytes)/\(receivedBytes)"
}
}
statusItem.title = title
*/
}
func updateStatusContent(_ notification: Notification?) {
let bleManager = BleManager.sharedInstance
let statusText = StatusManager.sharedInstance.statusDescription()
DispatchQueue.main.async(execute: { [unowned self] in // Execute on main thrad to avoid flickering on macOS Sierra
self.statusMenu.removeAllItems()
// Main Area
let descriptionItem = NSMenuItem(title: statusText, action: nil, keyEquivalent: "")
descriptionItem.isEnabled = false
self.statusMenu.addItem(descriptionItem)
self.statusMenu.addItem(NSMenuItem.separator())
// Connecting/Connected Peripheral
var featuredPeripheralIds = [UUID]()
for connectedPeripheral in bleManager.connectedPeripherals() {
let menuItem = self.addPeripheralToSystemMenu(connectedPeripheral)
menuItem.offStateImage = NSImage(named: "NSMenuOnStateTemplate")
featuredPeripheralIds.append(connectedPeripheral.identifier)
}
for connectingPeripheral in bleManager.connectingPeripherals() {
if !featuredPeripheralIds.contains(connectingPeripheral.identifier) {
let menuItem = self.addPeripheralToSystemMenu(connectingPeripheral)
menuItem.offStateImage = NSImage(named: "NSMenuOnStateTemplate")
featuredPeripheralIds.append(connectingPeripheral.identifier)
}
}
// Discovered Peripherals
let blePeripheralsFound = bleManager.peripherals().sorted(by: {$0.name ?? "" <= $1.name ?? ""}) // Alphabetical order
for blePeripheral in blePeripheralsFound {
if !featuredPeripheralIds.contains(blePeripheral.identifier) {
self.addPeripheralToSystemMenu(blePeripheral)
}
}
/*TODO: restore
// Uart data
if let featuredPeripheral = featuredPeripheral {
// Separator
self.statusMenu.addItem(NSMenuItem.separator())
// Uart title
let title = featuredPeripheral.name != nil ? "\(featuredPeripheral.name!) Stats:" : "Stats:"
let uartTitleMenuItem = NSMenuItem(title: title, action: nil, keyEquivalent: "")
uartTitleMenuItem.enabled = false
self.statusMenu.addItem(uartTitleMenuItem)
// Stats
let receivedBytes = featuredPeripheral.uartData.receivedBytes
let sentBytes = featuredPeripheral.uartData.sentBytes
let uartSentMenuItem = NSMenuItem(title: "Uart Sent: \(sentBytes) bytes", action: nil, keyEquivalent: "")
let uartReceivedMenuItem = NSMenuItem(title: "Uart Received: \(receivedBytes) bytes", action: nil, keyEquivalent: "")
uartSentMenuItem.indentationLevel = 1
uartReceivedMenuItem.indentationLevel = 1
uartSentMenuItem.enabled = false
uartReceivedMenuItem.enabled = false
self.statusMenu.addItem(uartSentMenuItem)
self.statusMenu.addItem(uartReceivedMenuItem)
}
*/
})
}
@discardableResult
func addPeripheralToSystemMenu(_ blePeripheral: BlePeripheral) -> NSMenuItem {
let name = blePeripheral.name != nil ? blePeripheral.name! : LocalizationManager.sharedInstance.localizedString("peripherallist_unnamed")
let menuItem = NSMenuItem(title: name, action: #selector(onClickPeripheralMenuItem(_:)), keyEquivalent: "")
let identifier = blePeripheral.peripheral.identifier
menuItem.representedObject = identifier
statusMenu.addItem(menuItem)
return menuItem
}
func onClickPeripheralMenuItem(_ sender: NSMenuItem) {
let identifier = sender.representedObject as! UUID
StatusManager.sharedInstance.startConnectionToPeripheral(identifier)
}
// MARK: - NSMenuDelegate
func menuWillOpen(_ menu: NSMenu) {
if menu == statusMenu {
isMenuOpen = true
updateStatusContent(nil)
} else if menu == peripheralsMenu {
let isScanning = BleManager.sharedInstance.isScanning
startScanningMenuItem.isEnabled = !isScanning
stopScanningMenuItem.isEnabled = isScanning
}
}
func menuDidClose(_ menu: NSMenu) {
if menu == statusMenu {
isMenuOpen = false
}
}
// MARK: - Main Menu
@IBAction func onStartScanning(_ sender: AnyObject) {
BleManager.sharedInstance.startScan()
}
@IBAction func onStopScanning(_ sender: AnyObject) {
BleManager.sharedInstance.stopScan()
}
@IBAction func onRefreshPeripherals(_ sender: AnyObject) {
BleManager.sharedInstance.refreshPeripherals()
}
/* launch app from menuitem
[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
[_window makeKeyAndOrderFront:self];
*/
}
| 37.735043 | 162 | 0.661835 |
f90ec9e6f88804ea35da81fc46f4c41777f082af | 1,485 | var randomNumbers = [42, 12, 88, 62, 63, 56, 1, 77, 88, 97, 97, 20, 45, 91, 62, 2, 15, 31, 59, 5]
var list = [5, 2, 1, 3, 4]
//var k = 2
//println(randomNumbers[0...k-1])
//println(7/2)
//把一个无序的数组排成有序
func mergeSort (input : Array<Int>) -> Array<Int>
{
if input.count < 2 {
return input
}
let mid = input.count/2
var x = 0
var left: [Int] = []
var right: [Int] = []
for x = 0; x < mid; x++ {
left.append(input[x])
}
for x = mid; x < input.count; x++ {
right.append(input[x])
}
//let left = Array(input[0...mid-1])
//let right = Array(input[mid...input.count-1])
println(left)
var leftSorted = mergeSort(left)
var rightSorted = mergeSort(right)
return mergeTwoArray(leftSorted, rightSorted)
}
//将两个有序的数组合并成一个有序的数组
func mergeTwoArray(left: Array<Int>, right: Array<Int>) -> Array<Int>{
var temp: [Int] = []
var tleft = left
var tright = right
while (tleft.count + tright.count) != 0 {
if tleft.count == 0{
temp += tright
break
}else if tright.count == 0{
temp += tleft
break
}else{
if tleft[0] < tright[0]{
temp.append(tleft[0])
tleft.removeAtIndex(0)
}else{
temp.append(tright[0])
tright.removeAtIndex(0)
}
}
}
println(temp)
return temp
}
println(mergeSort(randomNumbers)) | 24.75 | 97 | 0.519865 |
1ead96799a95b23a7645f3e3ac2549ce1590ae6f | 31,251 | import Photos
import Foundation
import AssetsLibrary // TODO: needed for deprecated functionality
import MobileCoreServices
extension PHAsset {
// Returns original file name, useful for photos synced with iTunes
var originalFileName: String? {
var result: String?
// This technique is slow
if #available(iOS 9.0, *) {
let resources = PHAssetResource.assetResources(for: self)
if let resource = resources.first {
result = resource.originalFilename
}
}
return result
}
var fileName: String? {
return self.value(forKey: "filename") as? String
}
}
final class PhotoLibraryService {
let fetchOptions: PHFetchOptions!
let thumbnailRequestOptions: PHImageRequestOptions!
let imageRequestOptions: PHImageRequestOptions!
let dateFormatter: DateFormatter!
let cachingImageManager: PHCachingImageManager!
let contentMode = PHImageContentMode.aspectFill // AspectFit: can be smaller, AspectFill - can be larger. TODO: resize to exact size
var cacheActive = false
let mimeTypes = [
"flv": "video/x-flv",
"mp4": "video/mp4",
"m3u8": "application/x-mpegURL",
"ts": "video/MP2T",
"3gp": "video/3gpp",
"mov": "video/quicktime",
"avi": "video/x-msvideo",
"wmv": "video/x-ms-wmv",
"gif": "image/gif",
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"tiff": "image/tiff",
"tif": "image/tiff"
]
static let PERMISSION_ERROR = "Permission Denial: This application is not allowed to access Photo data."
let dataURLPattern = try! NSRegularExpression(pattern: "^data:.+?;base64,", options: NSRegularExpression.Options(rawValue: 0))
let assetCollectionTypes = [PHAssetCollectionType.album, PHAssetCollectionType.smartAlbum/*, PHAssetCollectionType.moment*/]
fileprivate init() {
fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
//fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
if #available(iOS 9.0, *) {
fetchOptions.includeAssetSourceTypes = [.typeUserLibrary, .typeiTunesSynced, .typeCloudShared]
}
thumbnailRequestOptions = PHImageRequestOptions()
thumbnailRequestOptions.isSynchronous = false
thumbnailRequestOptions.resizeMode = .exact
thumbnailRequestOptions.deliveryMode = .highQualityFormat
thumbnailRequestOptions.version = .current
thumbnailRequestOptions.isNetworkAccessAllowed = false
imageRequestOptions = PHImageRequestOptions()
imageRequestOptions.isSynchronous = false
imageRequestOptions.resizeMode = .exact
imageRequestOptions.deliveryMode = .highQualityFormat
imageRequestOptions.version = .current
imageRequestOptions.isNetworkAccessAllowed = false
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
cachingImageManager = PHCachingImageManager()
}
class var instance: PhotoLibraryService {
struct SingletonWrapper {
static let singleton = PhotoLibraryService()
}
return SingletonWrapper.singleton
}
static func hasPermission() -> Bool {
return PHPhotoLibrary.authorizationStatus() == .authorized
}
func getLibrary(_ options: PhotoLibraryGetLibraryOptions, completion: @escaping (_ result: [NSDictionary], _ chunkNum: Int, _ isLastChunk: Bool) -> Void) {
if(options.includeCloudData == false) {
if #available(iOS 9.0, *) {
// remove iCloud source type
fetchOptions.includeAssetSourceTypes = [.typeUserLibrary, .typeiTunesSynced]
}
}
// let fetchResult = PHAsset.fetchAssets(with: .image, options: self.fetchOptions)
if(options.includeImages == true && options.includeVideos == true) {
fetchOptions.predicate = NSPredicate(format: "mediaType == %d || mediaType == %d",
PHAssetMediaType.image.rawValue,
PHAssetMediaType.video.rawValue)
}
else {
if(options.includeImages == true) {
fetchOptions.predicate = NSPredicate(format: "mediaType == %d",
PHAssetMediaType.image.rawValue)
}
else if(options.includeVideos == true) {
fetchOptions.predicate = NSPredicate(format: "mediaType == %d",
PHAssetMediaType.video.rawValue)
}
}
let fetchResult = PHAsset.fetchAssets(with: fetchOptions)
// TODO: do not restart caching on multiple calls
// if fetchResult.count > 0 {
//
// var assets = [PHAsset]()
// fetchResult.enumerateObjects({(asset, index, stop) in
// assets.append(asset)
// })
//
// self.stopCaching()
// self.cachingImageManager.startCachingImages(for: assets, targetSize: CGSize(width: options.thumbnailWidth, height: options.thumbnailHeight), contentMode: self.contentMode, options: self.imageRequestOptions)
// self.cacheActive = true
// }
var chunk = [NSDictionary]()
var chunkStartTime = NSDate()
var chunkNum = 0
fetchResult.enumerateObjects({ (asset: PHAsset, index, stop) in
if (options.maxItems > 0 && index + 1 > options.maxItems) {
completion(chunk, chunkNum, true)
return
}
let libraryItem = self.assetToLibraryItem(asset: asset, useOriginalFileNames: options.useOriginalFileNames, includeAlbumData: options.includeAlbumData)
chunk.append(libraryItem)
self.getCompleteInfo(libraryItem, completion: { (fullPath) in
libraryItem["filePath"] = fullPath
if index == fetchResult.count - 1 { // Last item
completion(chunk, chunkNum, true)
} else if (options.itemsInChunk > 0 && chunk.count == options.itemsInChunk) ||
(options.chunkTimeSec > 0 && abs(chunkStartTime.timeIntervalSinceNow) >= options.chunkTimeSec) {
completion(chunk, chunkNum, false)
chunkNum += 1
chunk = [NSDictionary]()
chunkStartTime = NSDate()
}
})
})
}
func mimeTypeForPath(path: String) -> String {
let url = NSURL(fileURLWithPath: path)
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
func getCompleteInfo(_ libraryItem: NSDictionary, completion: @escaping (_ fullPath: String?) -> Void) {
let ident = libraryItem.object(forKey: "id") as! String
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [ident], options: self.fetchOptions)
if fetchResult.count == 0 {
completion(nil)
return
}
let mime_type = libraryItem.object(forKey: "mimeType") as! String
let mediaType = mime_type.components(separatedBy: "/").first
fetchResult.enumerateObjects({
(obj: AnyObject, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
let asset = obj as! PHAsset
if(mediaType == "image") {
PHImageManager.default().requestImageData(for: asset, options: self.imageRequestOptions) {
(imageData: Data?, dataUTI: String?, orientation: UIImage.Orientation, info: [AnyHashable: Any]?) in
if(imageData == nil) {
completion(nil)
}
else {
let file_url:URL = info!["PHImageFileURLKey"] as! URL
// let mime_type = self.mimeTypes[file_url.pathExtension.lowercased()]!
completion(file_url.relativePath)
}
}
}
else if(mediaType == "video") {
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (avAsset: AVAsset?, avAudioMix: AVAudioMix?, info: [AnyHashable : Any]?) in
if( avAsset is AVURLAsset ) {
let video_asset = avAsset as! AVURLAsset
let url = URL(fileURLWithPath: video_asset.url.relativePath)
completion(url.relativePath)
}
else if(avAsset is AVComposition) {
let token = info?["PHImageFileSandboxExtensionTokenKey"] as! String
let path = token.components(separatedBy: ";").last
completion(path)
}
})
}
else if(mediaType == "audio") {
// TODO:
completion(nil)
}
else {
completion(nil) // unknown
}
})
}
private func assetToLibraryItem(asset: PHAsset, useOriginalFileNames: Bool, includeAlbumData: Bool) -> NSMutableDictionary {
let libraryItem = NSMutableDictionary()
libraryItem["id"] = asset.localIdentifier
libraryItem["fileName"] = useOriginalFileNames ? asset.originalFileName : asset.fileName // originalFilename is much slower
libraryItem["width"] = asset.pixelWidth
libraryItem["height"] = asset.pixelHeight
let fname = libraryItem["fileName"] as! String
libraryItem["mimeType"] = self.mimeTypeForPath(path: fname)
libraryItem["creationDate"] = self.dateFormatter.string(from: asset.creationDate!)
if let location = asset.location {
libraryItem["latitude"] = location.coordinate.latitude
libraryItem["longitude"] = location.coordinate.longitude
}
if includeAlbumData {
// This is pretty slow, use only when needed
var assetCollectionIds = [String]()
for assetCollectionType in self.assetCollectionTypes {
let albumsOfAsset = PHAssetCollection.fetchAssetCollectionsContaining(asset, with: assetCollectionType, options: nil)
albumsOfAsset.enumerateObjects({ (assetCollection: PHAssetCollection, index, stop) in
assetCollectionIds.append(assetCollection.localIdentifier)
})
}
libraryItem["albumIds"] = assetCollectionIds
}
return libraryItem
}
func getAlbums() -> [NSDictionary] {
var result = [NSDictionary]()
for assetCollectionType in assetCollectionTypes {
let fetchResult = PHAssetCollection.fetchAssetCollections(with: assetCollectionType, subtype: .any, options: nil)
fetchResult.enumerateObjects({ (assetCollection: PHAssetCollection, index, stop) in
let albumItem = NSMutableDictionary()
albumItem["id"] = assetCollection.localIdentifier
albumItem["title"] = assetCollection.localizedTitle
result.append(albumItem)
});
}
return result;
}
func getThumbnail(_ photoId: String, thumbnailWidth: Int, thumbnailHeight: Int, quality: Float, completion: @escaping (_ result: PictureData?) -> Void) {
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [photoId], options: self.fetchOptions)
if fetchResult.count == 0 {
completion(nil)
return
}
fetchResult.enumerateObjects({
(obj: AnyObject, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
let asset = obj as! PHAsset
self.cachingImageManager.requestImage(for: asset, targetSize: CGSize(width: thumbnailWidth, height: thumbnailHeight), contentMode: self.contentMode, options: self.thumbnailRequestOptions) {
(image: UIImage?, imageInfo: [AnyHashable: Any]?) in
guard let image = image else {
completion(nil)
return
}
let imageData = PhotoLibraryService.image2PictureData(image, quality: quality)
completion(imageData)
}
})
}
func getPhoto(_ photoId: String, completion: @escaping (_ result: PictureData?) -> Void) {
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [photoId], options: self.fetchOptions)
if fetchResult.count == 0 {
completion(nil)
return
}
fetchResult.enumerateObjects({
(obj: AnyObject, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
let asset = obj as! PHAsset
PHImageManager.default().requestImageData(for: asset, options: self.imageRequestOptions) {
(imageData: Data?, dataUTI: String?, orientation: UIImage.Orientation, info: [AnyHashable: Any]?) in
guard let image = imageData != nil ? UIImage(data: imageData!) : nil else {
completion(nil)
return
}
let imageData = PhotoLibraryService.image2PictureData(image, quality: 1.0)
completion(imageData)
}
})
}
func getLibraryItem(_ itemId: String, mimeType: String, completion: @escaping (_ base64: String?) -> Void) {
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [itemId], options: self.fetchOptions)
if fetchResult.count == 0 {
completion(nil)
return
}
// TODO: data should be returned as chunks, even for pics.
// a massive data object might increase RAM usage too much, and iOS will then kill the app.
fetchResult.enumerateObjects({
(obj: AnyObject, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
let asset = obj as! PHAsset
let mediaType = mimeType.components(separatedBy: "/")[0]
if(mediaType == "image") {
PHImageManager.default().requestImageData(for: asset, options: self.imageRequestOptions) {
(imageData: Data?, dataUTI: String?, orientation: UIImage.Orientation, info: [AnyHashable: Any]?) in
if(imageData == nil) {
completion(nil)
}
else {
// let file_url:URL = info!["PHImageFileURLKey"] as! URL
// let mime_type = self.mimeTypes[file_url.pathExtension.lowercased()]
completion(imageData!.base64EncodedString())
}
}
}
else if(mediaType == "video") {
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (avAsset: AVAsset?, avAudioMix: AVAudioMix?, info: [AnyHashable : Any]?) in
let video_asset = avAsset as! AVURLAsset
let url = URL(fileURLWithPath: video_asset.url.relativePath)
do {
let video_data = try Data(contentsOf: url)
let video_base64 = video_data.base64EncodedString()
// let mime_type = self.mimeTypes[url.pathExtension.lowercased()]
completion(video_base64)
}
catch _ {
completion(nil)
}
})
}
else if(mediaType == "audio") {
// TODO:
completion(nil)
}
else {
completion(nil) // unknown
}
})
}
func getVideo(_ videoId: String, completion: @escaping (_ result: PictureData?) -> Void) {
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [videoId], options: self.fetchOptions)
if fetchResult.count == 0 {
completion(nil)
return
}
fetchResult.enumerateObjects({
(obj: AnyObject, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
let asset = obj as! PHAsset
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (avAsset: AVAsset?, avAudioMix: AVAudioMix?, info: [AnyHashable : Any]?) in
let video_asset = avAsset as! AVURLAsset
let url = URL(fileURLWithPath: video_asset.url.relativePath)
do {
let video_data = try Data(contentsOf: url)
let pic_data = PictureData(data: video_data, mimeType: "video/quicktime") // TODO: get mime from info dic ?
completion(pic_data)
}
catch _ {
completion(nil)
}
})
})
}
func stopCaching() {
if self.cacheActive {
self.cachingImageManager.stopCachingImagesForAllAssets()
self.cacheActive = false
}
}
func requestAuthorization(_ success: @escaping () -> Void, failure: @escaping (_ err: String) -> Void ) {
let status = PHPhotoLibrary.authorizationStatus()
if status == .authorized {
success()
return
}
if status == .notDetermined {
// Ask for permission
PHPhotoLibrary.requestAuthorization() { (status) -> Void in
switch status {
case .authorized:
success()
default:
failure("requestAuthorization denied by user")
}
}
return
}
// Permission was manually denied by user, open settings screen
let settingsUrl = URL(string: UIApplication.openSettingsURLString)
if let url = settingsUrl {
UIApplication.shared.openURL(url)
// TODO: run callback only when return ?
// Do not call success, as the app will be restarted when user changes permission
} else {
failure("could not open settings url")
}
}
// TODO: implement with PHPhotoLibrary (UIImageWriteToSavedPhotosAlbum) instead of deprecated ALAssetsLibrary,
// as described here: http://stackoverflow.com/questions/11972185/ios-save-photo-in-an-app-specific-album
// but first find a way to save animated gif with it.
// TODO: should return library item
func saveImage(_ url: String, album: String, completion: @escaping (_ libraryItem: NSDictionary?, _ error: String?)->Void) {
let sourceData: Data
do {
sourceData = try getDataFromURL(url)
} catch {
completion(nil, "\(error)")
return
}
let assetsLibrary = ALAssetsLibrary()
func saveImage(_ photoAlbum: PHAssetCollection) {
assetsLibrary.writeImageData(toSavedPhotosAlbum: sourceData, metadata: nil) { (assetUrl: URL?, error: Error?) in
if error != nil {
completion(nil, "Could not write image to album: \(error)")
return
}
guard let assetUrl = assetUrl else {
completion(nil, "Writing image to album resulted empty asset")
return
}
self.putMediaToAlbum(assetsLibrary, url: assetUrl, album: album, completion: { (error) in
if error != nil {
completion(nil, error)
} else {
let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [assetUrl], options: nil)
var libraryItem: NSDictionary? = nil
if fetchResult.count == 1 {
let asset = fetchResult.firstObject
if let asset = asset {
libraryItem = self.assetToLibraryItem(asset: asset, useOriginalFileNames: false, includeAlbumData: true)
}
}
completion(libraryItem, nil)
}
})
}
}
if let photoAlbum = PhotoLibraryService.getPhotoAlbum(album) {
saveImage(photoAlbum)
return
}
PhotoLibraryService.createPhotoAlbum(album) { (photoAlbum: PHAssetCollection?, error: String?) in
guard let photoAlbum = photoAlbum else {
completion(nil, error)
return
}
saveImage(photoAlbum)
}
}
func saveVideo(_ url: String, album: String, completion: @escaping (_ libraryItem: NSDictionary?, _ error: String?)->Void) {
guard let videoURL = URL(string: url) else {
completion(nil, "Could not parse DataURL")
return
}
let assetsLibrary = ALAssetsLibrary()
func saveVideo(_ photoAlbum: PHAssetCollection) {
// TODO: new way, seems not supports dataURL
// if !UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoURL.relativePath!) {
// completion(url: nil, error: "Provided video is not compatible with Saved Photo album")
// return
// }
// UISaveVideoAtPathToSavedPhotosAlbum(videoURL.relativePath!, nil, nil, nil)
if !assetsLibrary.videoAtPathIs(compatibleWithSavedPhotosAlbum: videoURL) {
// TODO: try to convert to MP4 as described here?: http://stackoverflow.com/a/39329155/1691132
completion(nil, "Provided video is not compatible with Saved Photo album")
return
}
assetsLibrary.writeVideoAtPath(toSavedPhotosAlbum: videoURL) { (assetUrl: URL?, error: Error?) in
if error != nil {
completion(nil, "Could not write video to album: \(error)")
return
}
guard let assetUrl = assetUrl else {
completion(nil, "Writing video to album resulted empty asset")
return
}
self.putMediaToAlbum(assetsLibrary, url: assetUrl, album: album, completion: { (error) in
if error != nil {
completion(nil, error)
} else {
let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [assetUrl], options: nil)
var libraryItem: NSDictionary? = nil
if fetchResult.count == 1 {
let asset = fetchResult.firstObject
if let asset = asset {
libraryItem = self.assetToLibraryItem(asset: asset, useOriginalFileNames: false, includeAlbumData: true)
}
}
completion(libraryItem, nil)
}
})
}
}
if let photoAlbum = PhotoLibraryService.getPhotoAlbum(album) {
saveVideo(photoAlbum)
return
}
PhotoLibraryService.createPhotoAlbum(album) { (photoAlbum: PHAssetCollection?, error: String?) in
guard let photoAlbum = photoAlbum else {
completion(nil, error)
return
}
saveVideo(photoAlbum)
}
}
struct PictureData {
var data: Data
var mimeType: String
}
// TODO: currently seems useless
enum PhotoLibraryError: Error, CustomStringConvertible {
case error(description: String)
var description: String {
switch self {
case .error(let description): return description
}
}
}
fileprivate func getDataFromURL(_ url: String) throws -> Data {
if url.hasPrefix("data:") {
guard let match = self.dataURLPattern.firstMatch(in: url, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, url.count)) else { // TODO: firstMatchInString seems to be slow for unknown reason
throw PhotoLibraryError.error(description: "The dataURL could not be parsed")
}
let dataPos = match.range(at: 0).length
let base64 = (url as NSString).substring(from: dataPos)
guard let decoded = Data(base64Encoded: base64, options: NSData.Base64DecodingOptions(rawValue: 0)) else {
throw PhotoLibraryError.error(description: "The dataURL could not be decoded")
}
return decoded
} else {
guard let nsURL = URL(string: url) else {
throw PhotoLibraryError.error(description: "The url could not be decoded: \(url)")
}
guard let fileContent = try? Data(contentsOf: nsURL) else {
throw PhotoLibraryError.error(description: "The url could not be read: \(url)")
}
return fileContent
}
}
fileprivate func putMediaToAlbum(_ assetsLibrary: ALAssetsLibrary, url: URL, album: String, completion: @escaping (_ error: String?)->Void) {
assetsLibrary.asset(for: url, resultBlock: { (asset: ALAsset?) in
guard let asset = asset else {
completion("Retrieved asset is nil")
return
}
PhotoLibraryService.getAlPhotoAlbum(assetsLibrary, album: album, completion: { (alPhotoAlbum: ALAssetsGroup?, error: String?) in
if error != nil {
completion("getting photo album caused error: \(error)")
return
}
alPhotoAlbum!.add(asset)
completion(nil)
})
}, failureBlock: { (error: Error?) in
completion("Could not retrieve saved asset: \(error)")
})
}
fileprivate static func image2PictureData(_ image: UIImage, quality: Float) -> PictureData? {
// This returns raw data, but mime type is unknown. Anyway, crodova performs base64 for messageAsArrayBuffer, so there's no performance gain visible
// let provider: CGDataProvider = CGImageGetDataProvider(image.CGImage)!
// let data = CGDataProviderCopyData(provider)
// return data;
var data: Data?
var mimeType: String?
if (imageHasAlpha(image)){
data = image.pngData()
mimeType = data != nil ? "image/png" : nil
} else {
data = image.jpegData(compressionQuality: CGFloat(quality))
mimeType = data != nil ? "image/jpeg" : nil
}
if data != nil && mimeType != nil {
return PictureData(data: data!, mimeType: mimeType!)
}
return nil
}
fileprivate static func imageHasAlpha(_ image: UIImage) -> Bool {
let alphaInfo = (image.cgImage)?.alphaInfo
return alphaInfo == .first || alphaInfo == .last || alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast
}
fileprivate static func getPhotoAlbum(_ album: String) -> PHAssetCollection? {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", album)
let fetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: fetchOptions)
guard let photoAlbum = fetchResult.firstObject else {
return nil
}
return photoAlbum
}
fileprivate static func createPhotoAlbum(_ album: String, completion: @escaping (_ photoAlbum: PHAssetCollection?, _ error: String?)->()) {
var albumPlaceholder: PHObjectPlaceholder?
PHPhotoLibrary.shared().performChanges({
let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: album)
albumPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}) { success, error in
guard let placeholder = albumPlaceholder else {
completion(nil, "Album placeholder is nil")
return
}
let fetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [placeholder.localIdentifier], options: nil)
guard let photoAlbum = fetchResult.firstObject else {
completion(nil, "FetchResult has no PHAssetCollection")
return
}
if success {
completion(photoAlbum, nil)
}
else {
completion(nil, "\(error)")
}
}
}
fileprivate static func getAlPhotoAlbum(_ assetsLibrary: ALAssetsLibrary, album: String, completion: @escaping (_ alPhotoAlbum: ALAssetsGroup?, _ error: String?)->Void) {
var groupPlaceHolder: ALAssetsGroup?
assetsLibrary.enumerateGroupsWithTypes(ALAssetsGroupAlbum, usingBlock: { (group: ALAssetsGroup?, _ ) in
guard let group = group else { // done enumerating
guard let groupPlaceHolder = groupPlaceHolder else {
completion(nil, "Could not find album")
return
}
completion(groupPlaceHolder, nil)
return
}
if group.value(forProperty: ALAssetsGroupPropertyName) as? String == album {
groupPlaceHolder = group
}
}, failureBlock: { (error: Error?) in
completion(nil, "Could not enumerate assets library")
})
}
}
| 38.110976 | 234 | 0.560334 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.