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
|
---|---|---|---|---|---|
fca5851fc17e8356f7d251e4aa3679ed49990674 | 237 | //
// main.swift
// TestSwift
//
// Created by 岳琛 on 2018/10/12.
// Copyright © 2018 KMF-Engineering. All rights reserved.
//
import Foundation
func sayHelloWorld() -> String {
return "Hello, World!"
}
print(sayHelloWorld())
| 13.941176 | 58 | 0.658228 |
7689cd21b6931a55b9c3bf7464a20e5d69496cf9 | 365 | //
// YMCalendarLayoutDataSource.swift
// YMCalendar
//
// Created by Yuma Matsune on 2017/02/21.
// Copyright © 2017年 Yuma Matsune. All rights reserved.
//
import Foundation
import UIKit
protocol YMCalendarLayoutDataSource: class {
func collectionView(_ collectionView: UICollectionView, layout: YMCalendarLayout, columnAt indexPath: IndexPath) -> Int
}
| 24.333333 | 123 | 0.764384 |
cc2bb1993c17731c3b85d60e926caa326500485f | 1,158 | /*
* Copyright 2016, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Cocoa
import SwiftGRPC
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_: Notification) {
gRPC.initialize()
print("GRPC version", gRPC.version)
}
func applicationWillTerminate(_: Notification) {
// We don't call shutdown() here because we can't be sure that
// any running server queues will have stopped by the time this is
// called. If one is still running after we call shutdown(), the
// program will crash.
// gRPC.shutdown()
}
}
| 34.058824 | 75 | 0.729706 |
fe4d4bc79c825ca202a2e882ffab66b2d88b2246 | 5,575 | // Copyright (c) 2016, Nate Stedman <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
@testable import PrettyOkayKit
import XCTest
final class ProductTests: XCTestCase
{
private func encoded(links links: [String:AnyObject]) -> [String:AnyObject]
{
return [
"_links": links,
"categories": [
[
"id": 1,
"name": "Apparel",
"slug": "apparel"
]
],
"created_at": [
"_date": "2016-11-28T18:51:52.300163+00:00"
],
"currency": NSNull(),
"domain_for_display": "test.com",
"formatted_price": "$25-$50",
"gender": "male",
"id": 1,
"image_bucket": NSNull(),
"image_key": "1234",
"image_url": "https://test.com/image",
"in_your_goods": false,
"medium_image_url": "https://test.com/image_medium",
"orig_image_url": "https://test.com/image_orig",
"price_category": [
"id": 2,
"range_max": 50,
"range_min": 25
],
"price_category_id": 2,
"slug": "test",
"source_domain": "https://test.com",
"source_url": "https://test.com/product",
"title": "Test",
"updated_at": [
"_date": "2016-11-28T18:51:59.371457+00:00"
]
]
}
private let linksNoDelete: [String:AnyObject] = [
"good:add": [
"href": "/users/test/goods"
],
"self": [
"href": "/products/1"
]
]
private let linksWithDelete: [String:AnyObject] = [
"good:delete": [
"href": "/test/path"
],
"self": [
"href": "/products/1"
]
]
func testDecodeNoDeleteNoCustomLinks()
{
let encoded = self.encoded(links: linksNoDelete)
XCTAssertEqual(try? Product(encoded: encoded), Product(
identifier: 1,
title: "Test",
formattedPrice: "$25-$50",
gender: .Male,
imageURL: NSURL(string: "https://test.com/image"),
mediumImageURL: NSURL(string: "https://test.com/image_medium"),
originalImageURL: NSURL(string: "https://test.com/image_orig"),
displayDomain: "test.com",
sourceDomain: NSURL(string: "https://test.com"),
sourceURL: NSURL(string: "https://test.com/product"),
goodDeletePath: nil
))
}
func testDecodeWithDeleteNoCustomLinks()
{
let encoded = self.encoded(links: linksWithDelete)
XCTAssertEqual(try? Product(encoded: encoded), Product(
identifier: 1,
title: "Test",
formattedPrice: "$25-$50",
gender: .Male,
imageURL: NSURL(string: "https://test.com/image"),
mediumImageURL: NSURL(string: "https://test.com/image_medium"),
originalImageURL: NSURL(string: "https://test.com/image_orig"),
displayDomain: "test.com",
sourceDomain: NSURL(string: "https://test.com"),
sourceURL: NSURL(string: "https://test.com/product"),
goodDeletePath: "test/path"
))
}
func testDecodeNoDeleteWithCustomLinksNoDelete()
{
let encoded = self.encoded(links: linksNoDelete)
XCTAssertEqual(try? Product(encoded: encoded, links: linksNoDelete), Product(
identifier: 1,
title: "Test",
formattedPrice: "$25-$50",
gender: .Male,
imageURL: NSURL(string: "https://test.com/image"),
mediumImageURL: NSURL(string: "https://test.com/image_medium"),
originalImageURL: NSURL(string: "https://test.com/image_orig"),
displayDomain: "test.com",
sourceDomain: NSURL(string: "https://test.com"),
sourceURL: NSURL(string: "https://test.com/product"),
goodDeletePath: nil
))
}
func testDecodeNoDeleteWithCustomLinksWithDelete()
{
let encoded = self.encoded(links: linksNoDelete)
XCTAssertEqual(try? Product(encoded: encoded, links: linksWithDelete), Product(
identifier: 1,
title: "Test",
formattedPrice: "$25-$50",
gender: .Male,
imageURL: NSURL(string: "https://test.com/image"),
mediumImageURL: NSURL(string: "https://test.com/image_medium"),
originalImageURL: NSURL(string: "https://test.com/image_orig"),
displayDomain: "test.com",
sourceDomain: NSURL(string: "https://test.com"),
sourceURL: NSURL(string: "https://test.com/product"),
goodDeletePath: "test/path"
))
}
}
| 35.967742 | 87 | 0.556592 |
03defc658ce7d427589235890cbb73887d8b390f | 1,850 | //
// Scope.swift
// evecodegen
//
// Created by Artem Shimanski on 29.04.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
class Global: Namespace {
override init() {
super.init()
self.name = "EVE"
}
}
let global = Global()
class Scope: Namespace {
var operations: [Operation] = []
init(_ dictionary: Any, name: String) throws {
super.init()
guard let dic = dictionary as? [String: Any] else {throw ParserError.format(Swift.type(of: self).self, dictionary)}
self.name = name.camelCaps
var operations = [Operation]()
for (key, value) in dic {
operations.append(try Operation(value, name: key, scope: self))
}
parent = global
self.operations = operations
children = operations.map {$0.result}
global.children.append(self)
}
func typeDefinitions() throws -> String {
var definitions = [String]()
for child in children.sorted(by: {$0.name < $1.name}) {
if let item = child as? Class {
let s = item.typeDefinition
definitions.append(s)
}
else if let item = child as? Enum {
let s = item.enumDefinition
definitions.append(s)
}
}
return definitions.joined(separator: "\n\n")
}
func scopeDefinition() throws -> String {
var template = try! String(contentsOf: scopeURL)
let variable = name.camelBack
var operations = [String]()
for operation in self.operations.sorted(by: {$0.name < $1.name}) {
operations.append(operation.definition)
}
template = template.replacingOccurrences(of: "{classes}", with: try typeDefinitions())
template = template.replacingOccurrences(of: "{variable}", with: variable)
template = template.replacingOccurrences(of: "{scope}", with: name)
template = template.replacingOccurrences(of: "{operations}", with: operations.joined(separator: "\n"))
return template
}
}
| 24.666667 | 117 | 0.676757 |
e93c5e94535edb23595d52dbabfa321a9caee7b3 | 2,714 | //
// AppDelegate.swift
// WorkingManagement
//
// Created by Tetsu on 2016/10/18.
// Copyright © 2016年 Pond_T. All rights reserved.
//
import UIKit
import FoldingTabBar
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var calendarNavigation: UINavigationController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// ===============================================================================
// MARK: - NavigationController Congigure
let calendarView: CalendarView = CalendarView()
calendarNavigation = UINavigationController(rootViewController: calendarView)
self.window?.rootViewController = calendarNavigation
self.window?.backgroundColor = UIColor.white
self.window?.makeKeyAndVisible()
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.793103 | 285 | 0.721076 |
187089a5938d6a44aeabef78a9399d6113c0793c | 893 | import Quick
import Nimble
import ReactiveSwift
import ReactiveCocoa
import Result
class UIActivityIndicatorSpec: QuickSpec {
override func spec() {
var activityIndicatorView: UIActivityIndicatorView!
weak var _activityIndicatorView: UIActivityIndicatorView?
beforeEach {
activityIndicatorView = UIActivityIndicatorView(frame: .zero)
_activityIndicatorView = activityIndicatorView
}
afterEach {
activityIndicatorView = nil
expect(_activityIndicatorView).to(beNil())
}
it("should accept changes from bindings to its animating state") {
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
activityIndicatorView.reactive.isAnimating <~ SignalProducer(signal: pipeSignal)
observer.send(value: true)
expect(activityIndicatorView.isAnimating) == true
observer.send(value: false)
expect(activityIndicatorView.isAnimating) == false
}
}
}
| 26.264706 | 83 | 0.773796 |
89bdd811b85a045513d28e13eb9d59763814f338 | 4,511 | // Copyright 2018-2021 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// StandardEncodingOptions.swift
// ShapeCoding
//
import Foundation
/// The strategy to use for encoding shape keys.
public enum ShapeKeyEncodingStrategy {
/// The encoder will concatinate attribute keys specified character to indicate a
/// nested structure that could include nested types, dictionaries and arrays. This is the default.
///
/// Array entries are indicated by a 1-based index
/// ie. ShapeOutput(theArray: ["Value1", "Value2"]) --> ["theArray.1": "Value1", "theArray.2": "Value2]
/// Nested type attributes are indicated by the attribute keys
/// ie. ShapeOutput(theType: TheType(foo: "Value1", bar: "Value2")) ?theType.foo=Value1&theType.bar=Value2
/// Dictionary entries are indicated based on the provided `ShapeMapEncodingStrategy`
/// Matches the decoding strategy `ShapeKeyDecodingStrategy.useAsShapeSeparator`.
case useAsShapeSeparator(Character)
/// The encoder will concatinate attribute keys with no separator.
/// Matches the decoding strategy `ShapeKeyDecodingStrategy.useShapePrefix`.
case noSeparator
/// Get the separator string to use for this strategy
var separatorString: String {
switch self {
case .useAsShapeSeparator(let character):
return "\(character)"
case .noSeparator:
return ""
}
}
}
/// The strategy to use for encoding maps.
public enum ShapeMapEncodingStrategy {
/// The output will contain a single shape entry for
/// each entry of the map. This is the default.
/// ie. ShapeOutput(theMap: ["Key": "Value"]) --> ["theMap.Key": "Value"]
case singleShapeEntry
/// The output will contain separate entries for the key and value
/// of each entry of the map, specified as a list.
/// ie. ShapeOutput(theMap: ["Key": "Value"]) --> ["theMap.1.KeyTag": "Key", "theMap.1.ValueTag": "Value"]
case separateShapeEntriesWith(keyTag: String, valueTag: String)
}
/// The strategy to use when encoding lists.
public enum ShapeListEncodingStrategy {
/// The index of the item in the list will be used as
/// the tag for each individual item. This is the default strategy.
/// ie. ShapeOutput(theList: ["Value"]) --> ["theList.1": "Value"]
case expandListWithIndex
/// The item tag will used as as the tag in addition to the index of the item in the list.
/// ie. ShapeOutput(theList: ["Value"]) --> ["theList.ItemTag.1": "Value"]
case expandListWithIndexAndItemTag(itemTag: String)
}
/// The strategy to use for transforming shape keys.
public enum ShapeKeyEncodeTransformStrategy {
/// The shape keys will not be transformed.
case none
/// The first character of shape keys will be capitialized.
case capitalizeFirstCharacter
/// The shape key will be transformed using the provided function.
case custom((String) -> String)
}
/// The standard encoding options to use in conjunction with
/// StandardShapeSingleValueEncodingContainerDelegate.
public struct StandardEncodingOptions {
public let shapeKeyEncodingStrategy: ShapeKeyEncodingStrategy
public let shapeMapEncodingStrategy: ShapeMapEncodingStrategy
public let shapeListEncodingStrategy: ShapeListEncodingStrategy
public let shapeKeyEncodeTransformStrategy: ShapeKeyEncodeTransformStrategy
public init(shapeKeyEncodingStrategy: ShapeKeyEncodingStrategy,
shapeMapEncodingStrategy: ShapeMapEncodingStrategy,
shapeListEncodingStrategy: ShapeListEncodingStrategy,
shapeKeyEncodeTransformStrategy: ShapeKeyEncodeTransformStrategy) {
self.shapeKeyEncodingStrategy = shapeKeyEncodingStrategy
self.shapeMapEncodingStrategy = shapeMapEncodingStrategy
self.shapeListEncodingStrategy = shapeListEncodingStrategy
self.shapeKeyEncodeTransformStrategy = shapeKeyEncodeTransformStrategy
}
}
| 43.796117 | 110 | 0.720904 |
6a547441d85e4434f401abe0cac9de1fb36627dc | 8,436 | //
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
public typealias View = UIView
#else
import AppKit
public typealias View = NSView
#endif
/**
Used to expose public API on views
*/
public extension View {
/// left edge
public var snp_left: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Left) }
/// top edge
public var snp_top: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Top) }
/// right edge
public var snp_right: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Right) }
/// bottom edge
public var snp_bottom: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Bottom) }
/// leading edge
public var snp_leading: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Leading) }
/// trailing edge
public var snp_trailing: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Trailing) }
/// width dimension
public var snp_width: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Width) }
/// height dimension
public var snp_height: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Height) }
/// centerX position
public var snp_centerX: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterX) }
/// centerY position
public var snp_centerY: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterY) }
/// baseline position
public var snp_baseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Baseline) }
/// first baseline position
@available(iOS 8.0, *)
public var snp_firstBaseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.FirstBaseline) }
/// left margin
@available(iOS 8.0, *)
public var snp_leftMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeftMargin) }
/// right margin
@available(iOS 8.0, *)
public var snp_rightMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.RightMargin) }
/// top margin
@available(iOS 8.0, *)
public var snp_topMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TopMargin) }
/// bottom margin
@available(iOS 8.0, *)
public var snp_bottomMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.BottomMargin) }
/// leading margin
@available(iOS 8.0, *)
public var snp_leadingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeadingMargin) }
/// trailing margin
@available(iOS 8.0, *)
public var snp_trailingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TrailingMargin) }
/// centerX within margins
@available(iOS 8.0, *)
public var snp_centerXWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterXWithinMargins) }
/// centerY within margins
@available(iOS 8.0, *)
public var snp_centerYWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterYWithinMargins) }
// top + left + bottom + right edges
public var snp_edges: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Edges) }
// width + height dimensions
public var snp_size: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Size) }
// centerX + centerY positions
public var snp_center: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Center) }
// top + left + bottom + right margins
@available(iOS 8.0, *)
public var snp_margins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Margins) }
// centerX + centerY within margins
@available(iOS 8.0, *)
public var snp_centerWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterWithinMargins) }
/**
Prepares constraints with a `ConstraintMaker` and returns the made constraints but does not install them.
- parameter closure that will be passed the `ConstraintMaker` to make the constraints with
- returns: the constraints made
*/
public func snp_prepareConstraints(_ file: String = #file, line: UInt = #line, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] {
return ConstraintMaker.prepareConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Makes constraints with a `ConstraintMaker` and installs them along side any previous made constraints.
- parameter closure that will be passed the `ConstraintMaker` to make the constraints with
*/
public func snp_makeConstraints(_ file: String = #file, line: UInt = #line, closure: (_ make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.makeConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Updates constraints with a `ConstraintMaker` that will replace existing constraints that match and install new ones.
For constraints to match only the constant can be updated.
- parameter closure that will be passed the `ConstraintMaker` to update the constraints with
*/
public func snp_updateConstraints(_ file: String = #file, line: UInt = #line, closure: (_ make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.updateConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Remakes constraints with a `ConstraintMaker` that will first remove all previously made constraints and make and install new ones.
- parameter closure that will be passed the `ConstraintMaker` to remake the constraints with
*/
public func snp_remakeConstraints(_ file: String = #file, line: UInt = #line, closure: (_ make: ConstraintMaker) -> Void) -> Void {
ConstraintMaker.remakeConstraints(view: self, file: file, line: line, closure: closure)
}
/**
Removes all previously made constraints.
*/
public func snp_removeConstraints() {
ConstraintMaker.removeConstraints(view: self)
}
internal var snp_installedLayoutConstraints: [LayoutConstraint] {
get {
if let constraints = objc_getAssociatedObject(self, &installedLayoutConstraintsKey) as? [LayoutConstraint] {
return constraints
}
return []
}
set {
objc_setAssociatedObject(self, &installedLayoutConstraintsKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
private var installedLayoutConstraintsKey = ""
| 45.847826 | 150 | 0.717283 |
f566e357eb41eceba3068c579b9f0f8a95a3f7fe | 3,902 | //
// CanvasViewController+TransitionActions.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 16/02/2017.
// Copyright © 2017 Felipe Espinoza Dev. All rights reserved.
//
import Foundation
import LinkedIdeas_Shared
// MARK: - CanvasViewController+TransitionActions
extension CanvasViewController {
func select(elements: [Element]) {
for var element in elements { element.isSelected = true }
}
func unselect(elements: [Element]) {
for var element in elements { element.isSelected = false }
}
func delete(element: Element) {
switch element {
case let link as Link:
document.remove(link: link)
case let concept as Concept:
delete(concept: concept)
default:
break
}
}
func delete(elements: [Element]) {
for element in elements {
guard let concept = element as? Concept else {
continue
}
delete(concept: concept)
}
}
func delete(concept: Concept) {
let linksToRemove = document.links.filter { $0.doesBelongTo(concept: concept) }
for link in linksToRemove {
document.remove(link: link)
}
document.remove(concept: concept)
}
func saveConcept(text: NSAttributedString, atPoint point: CGPoint) -> Concept? {
guard text.string != "" else {
return nil
}
let newConcept = Concept(attributedStringValue: text, centerPoint: point)
document.save(concept: newConcept)
return newConcept
}
func saveLink(fromConcept: Concept, toConcept: Concept, text: NSAttributedString? = nil) -> Link {
var linkText = NSAttributedString(string: "")
if let text = text {
linkText = text
}
let newLink = Link(origin: fromConcept, target: toConcept, attributedStringValue: linkText)
document.save(link: newLink)
return newLink
}
func showTextView(inRect rect: CGRect, text: NSAttributedString? = nil, constrainedSize: CGSize? = nil) {
textStorage.setAttributedString(text ?? NSAttributedString(string: ""))
if text == nil {
textView.typingAttributes = self.defaultTextAttributes
}
let textViewFrame = rect
func calculateMaxSize(forCenterPoint centerPoint: CGPoint) -> CGSize {
let centerPointInScrollView = scrollView.convert(centerPoint, from: canvasView)
let deltaX1 = centerPointInScrollView.x
let deltaX2 = scrollView.visibleRect.width - centerPointInScrollView.x
return CGSize(
width: min(deltaX1, deltaX2) * 2,
height: scrollView.visibleRect.height
)
}
// the maxSize for the textView should be the max size allowed given
// the centerPoint where the text view will be displayed and the visible
// rect that is shown by the NSScrollView
let maxSize = constrainedSize ?? calculateMaxSize(forCenterPoint: rect.center)
print(maxSize.debugDescription)
textContainer.size = maxSize
textView.maxSize = maxSize
textView.frame = textViewFrame
textView.sizeToFit()
reCenterTextView(atPoint: rect.center)
textView.isHidden = false
textView.isEditable = true
canvasView.window?.makeFirstResponder(textView)
}
func showTextView(atPoint point: CGPoint, text: NSAttributedString? = nil, constrainedSize: CGSize? = nil) {
let textViewFrame = CGRect(center: point, size: CGSize(width: 60, height: 25))
showTextView(inRect: textViewFrame, text: text, constrainedSize: constrainedSize)
}
func dismissTextView() {
textStorage.setAttributedString(NSAttributedString(string: ""))
textView.setFrameOrigin(CGPoint.zero)
textView.isEditable = false
textView.isHidden = true
canvasView.window?.makeFirstResponder(canvasView)
}
func reCenterTextView(atPoint centerPoint: CGPoint) {
textView.setFrameOrigin(
CGPoint(
x: centerPoint.x - textView.frame.width / 2,
y: centerPoint.y - textView.frame.height / 2
)
)
}
}
| 28.481752 | 110 | 0.698104 |
0a341de114f8383c7a375498f8e173ec6ae79819 | 2,440 | //
// ViewController.swift
// CurrencyExchange
//
// Created by KEEN on 2021/10/13.
//
import UIKit
class ViewController: UIViewController {
// MARK: Properties
var exchangeRate = ExchangeRate(currencyRate: 1100, USD: 1)
// MARK: UI
@IBOutlet weak var wonTextField: UITextField!
@IBOutlet weak var dollarTextField: UITextField!
@IBOutlet weak var currencyRateTextField: UITextField!
@IBOutlet weak var cardView: UIView!
// MARK: View Life-Cycle
override func viewDidLoad() {
super.viewDidLoad()
cardView.layer.cornerRadius = CGFloat(8)
currencyRateTextField.text = "\(exchangeRate.currencyRate)"
dollarTextField.text = "\(exchangeRate.USD)"
}
// MARK: Alert
func showAlert(_ message: String) {
let alert = UIAlertController(title: "⚠️ 환산 불가 ⚠️", message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "확인", style: .default)
alert.addAction(ok)
present(alert, animated: true, completion: nil)
}
func isDouble(_ str: String) -> Bool {
return Double(str) == nil ? false : true
}
// MARK: Actions
@IBAction func toDollar(_ sender: UIButton) {
guard let wonText = wonTextField.text else {
showAlert("환율과 KRW를 모두 채웠는지\n다시 확인해주세요.")
return
}
guard let currencyText = currencyRateTextField.text else {
showAlert("환율과 KRW를 모두 채웠는지\n다시 확인해주세요.")
return
}
// TODO: if let으로 리팩토링
if let currency = Double(currencyText), let won = Double(wonText) {
exchangeRate.currencyRate = currency
exchangeRate.KRW = won
} else {
showAlert("숫자만 적어주세요!")
}
// dollarTextField.text = "\(exchangeRate.USD * 100)" // 전체 출력
dollarTextField.text = "\(round(exchangeRate.USD * 100) / 100)" // 소수점 2자리까지만
}
@IBAction func toWon(_ sender: UIButton) {
guard let dollarText = dollarTextField.text else {
showAlert("환율과 KRW를 모두 채웠는지\n다시 확인해주세요.")
return
}
guard let currencyText = currencyRateTextField.text else {
showAlert("환율과 KRW를 모두 채웠는지\n다시 확인해주세요.")
return
}
if let currency = Double(currencyText), let dollar = Double(dollarText) {
exchangeRate.currencyRate = currency
exchangeRate.USD = dollar
} else {
showAlert("숫자만 적어주세요.")
}
// wonTextField.text = "\(exchangeRate.KRW)" // 전체 출력
wonTextField.text = "\(round(exchangeRate.KRW * 100) / 100)" // 소수점 2자리까지 출력
}
}
| 27.727273 | 97 | 0.652459 |
e8cdccd193af7dcceb66f3c2053f2c71a0ab6efd | 8,050 | //
// SpecialistChatView.swift
// YourHealth
//
// Created by pannullocarlo on 16/01/2021.
//
import SwiftUI
struct SpecialistChatView : View {
@State var navColor: Color = Color.init(red: 255/255, green: 240/255, blue: 240/255)
var body: some View {
ZStack{
navColor.edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
ScrollView {
VStack {
HStack(spacing : -10){
Image("logo")
.resizable()
.frame(width: 50, height: 50)
ChatBubble(direction: .left) {
Text("Hi")
.padding(.all, 20)
.foregroundColor(Color.black)
.background(LinearGradient(gradient: Gradient(colors: [Color("Darkpink"), Color("Lightpink")]), startPoint: .leading, endPoint: .trailing))
}
}
.frame(maxWidth: 400, maxHeight: .infinity, alignment: .leading)
HStack(spacing : -10){
Image("logo")
.resizable()
.frame(width: 50, height: 50)
NavigationLink(destination: SpecialistRequestView()){
ChatBubble(direction: .left) {
Text("You have a new request from Sara, tap for see")
.padding(.all, 20)
.foregroundColor(Color.black)
.background(LinearGradient(gradient: Gradient(colors: [Color("Darkpink"), Color("Lightpink")]), startPoint: .leading, endPoint: .trailing))
}
}
}.frame(maxWidth: 400, maxHeight: .infinity, alignment: .leading)
}
}
}
.navigationTitle("")
.navigationBarTitleDisplayMode(.inline)
.toolbar(content: {
ToolbarItem(placement: .principal) {
HStack {
Image("logo")
.resizable()
.scaledToFill()
.frame(width: 20, height: 20)
Text("YourHealth")
.fontWeight(.semibold)
}
}
})
}
}
struct ChatBubble<Content>: View where Content: View {
let direction: ChatBubbleShape.Direction
let content: () -> Content
init(direction: ChatBubbleShape.Direction, @ViewBuilder content: @escaping () -> Content) {
self.content = content
self.direction = direction
}
var body: some View {
HStack {
if direction == .right {
Spacer()
}
content().clipShape(ChatBubbleShape(direction: direction))
if direction == .left {
Spacer()
}
}.padding([(direction == .left) ? .leading : .trailing, .top, .bottom], 20)
.padding((direction == .right) ? .leading : .trailing, 50)
}
}
struct ChatBubbleShape: Shape {
enum Direction {
case left
case right
}
let direction: Direction
func path(in rect: CGRect) -> Path {
return (direction == .left) ? getLeftBubblePath(in: rect) : getRightBubblePath(in: rect)
}
private func getLeftBubblePath(in rect: CGRect) -> Path {
let width = rect.width
let height = rect.height
let path = Path { p in
p.move(to: CGPoint(x: 25, y: height))
p.addLine(to: CGPoint(x: width - 20, y: height))
p.addCurve(to: CGPoint(x: width, y: height - 20),
control1: CGPoint(x: width - 8, y: height),
control2: CGPoint(x: width, y: height - 8))
p.addLine(to: CGPoint(x: width, y: 20))
p.addCurve(to: CGPoint(x: width - 20, y: 0),
control1: CGPoint(x: width, y: 8),
control2: CGPoint(x: width - 8, y: 0))
p.addLine(to: CGPoint(x: 21, y: 0))
p.addCurve(to: CGPoint(x: 4, y: 20),
control1: CGPoint(x: 12, y: 0),
control2: CGPoint(x: 4, y: 8))
p.addLine(to: CGPoint(x: 4, y: height - 11))
p.addCurve(to: CGPoint(x: 0, y: height),
control1: CGPoint(x: 4, y: height - 1),
control2: CGPoint(x: 0, y: height))
p.addLine(to: CGPoint(x: -0.05, y: height - 0.01))
p.addCurve(to: CGPoint(x: 11.0, y: height - 4.0),
control1: CGPoint(x: 4.0, y: height + 0.5),
control2: CGPoint(x: 8, y: height - 1))
p.addCurve(to: CGPoint(x: 25, y: height),
control1: CGPoint(x: 16, y: height),
control2: CGPoint(x: 20, y: height))
}
return path
}
private func getRightBubblePath(in rect: CGRect) -> Path {
let width = rect.width
let height = rect.height
let path = Path { p in
p.move(to: CGPoint(x: 25, y: height))
p.addLine(to: CGPoint(x: 20, y: height))
p.addCurve(to: CGPoint(x: 0, y: height - 20),
control1: CGPoint(x: 8, y: height),
control2: CGPoint(x: 0, y: height - 8))
p.addLine(to: CGPoint(x: 0, y: 20))
p.addCurve(to: CGPoint(x: 20, y: 0),
control1: CGPoint(x: 0, y: 8),
control2: CGPoint(x: 8, y: 0))
p.addLine(to: CGPoint(x: width - 21, y: 0))
p.addCurve(to: CGPoint(x: width - 4, y: 20),
control1: CGPoint(x: width - 12, y: 0),
control2: CGPoint(x: width - 4, y: 8))
p.addLine(to: CGPoint(x: width - 4, y: height - 11))
p.addCurve(to: CGPoint(x: width, y: height),
control1: CGPoint(x: width - 4, y: height - 1),
control2: CGPoint(x: width, y: height))
p.addLine(to: CGPoint(x: width + 0.05, y: height - 0.01))
p.addCurve(to: CGPoint(x: width - 11, y: height - 4),
control1: CGPoint(x: width - 4, y: height + 0.5),
control2: CGPoint(x: width - 8, y: height - 1))
p.addCurve(to: CGPoint(x: width - 25, y: height),
control1: CGPoint(x: width - 16, y: height),
control2: CGPoint(x: width - 20, y: height))
}
return path
}
}
struct Demo: View {
var body: some View {
ScrollView {
VStack {
HStack(spacing : -10){
Image(systemName: "person.circle.fill")
.resizable()
.frame(width: 50, height: 50)
ChatBubble(direction: .left) {
Text("I'm your specialist")
.padding(.all, 20)
.foregroundColor(Color.white)
.background(Color("Color"))
}
}
HStack(spacing : -10){
Image(systemName: "person.circle.fill")
.resizable()
.frame(width: 50, height: 50)
ChatBubble(direction: .left) {
Text("Call me to book an appointment")
.padding(.all, 20)
.foregroundColor(Color.white)
.background(Color("Color"))
}
}
}
}
}
}
struct ChatBubble_Previews: PreviewProvider {
@State var username: String = ""
static var previews: some View {
SpecialistChatView()
}
}
| 39.268293 | 175 | 0.45354 |
8f06ea1f1fafb5f8d09e2ebb4a12608d34835bc3 | 2,168 | //
// AppDelegate.swift
// Done
//
// Created by Alex on 11.10.17.
// Copyright © 2017 Alexander Dobrynin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: 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.12766 | 285 | 0.755074 |
dd5d44fb18feb786dae2863291f111544c5a828d | 467 | //
// UIButton+Rx.swift
// SHWMark
//
// Created by yehot on 2017/12/27.
// Copyright © 2017年 Xin Hua Zhi Yun. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
extension Reactive where Base: UIButton {
var tapEnabled: Binder<Bool> {
return Binder(self.base, binding: { (button, canTap) in
button.isEnabled = canTap
// TODO: alpha 的变化,这种写法不通用
button.alpha = canTap ? 1.0 : 0.5
})
}
}
| 21.227273 | 63 | 0.610278 |
ef7e998845c0c8cb3f7a932e4224a901a6919f9e | 999 | //
// main.swift
// Add Two Numbers
//
// Created by xuezhaofeng on 2017/8/2.
// Copyright © 2017年 paladinfeng. All rights reserved.
//
import Foundation
class ListNode {
var val: Int
var next: ListNode?
init(_ val: Int) {
self.val = val
// self.next = nil
}
// var description: String {
//
// }
}
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
return nil
}
}
func creatList(_ list: String) -> ListNode? {
// _ = list.map {
// }
let nodeArray = Array(list.characters.flatMap{ Int(String($0)) }.reversed())
// let node: ListNode = ListNode(array[2])
// node.next = ListNode(array[1])
// node.next?.next = ListNode(array[0])
let node = ListNode(nodeArray.last!)
// print(array)
return nil
}
let l1 = creatList("342")
let l2 = creatList("465")
let result = Solution().addTwoNumbers(l1, l2);
print(result)
| 16.65 | 80 | 0.565566 |
9b353ff874e4272891c24d22dccfb81864748a41 | 41,417 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 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
//
//===----------------------------------------------------------------------===//
import XCTest
@_spi(Testing) import OrderedCollections
import CollectionsTestSupport
class OrderedDictionaryTests: CollectionTestCase {
func test_empty() {
let d = OrderedDictionary<String, Int>()
expectEqualElements(d, [])
expectEqual(d.count, 0)
}
func test_init_minimumCapacity() {
let d = OrderedDictionary<String, Int>(minimumCapacity: 1000)
expectGreaterThanOrEqual(d.keys.__unstable.capacity, 1000)
expectGreaterThanOrEqual(d.values.elements.capacity, 1000)
expectEqual(d.keys.__unstable.reservedScale, 0)
}
func test_init_minimumCapacity_persistent() {
let d = OrderedDictionary<String, Int>(minimumCapacity: 1000, persistent: true)
expectGreaterThanOrEqual(d.keys.__unstable.capacity, 1000)
expectGreaterThanOrEqual(d.values.elements.capacity, 1000)
expectNotEqual(d.keys.__unstable.reservedScale, 0)
}
func test_uniqueKeysWithValues_Dictionary() {
let items: Dictionary<String, Int> = [
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
]
let d = OrderedDictionary(uncheckedUniqueKeysWithValues: items)
expectEqualElements(d, items)
}
func test_uniqueKeysWithValues_labeled_tuples() {
let items: KeyValuePairs<String, Int> = [
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
]
let d = OrderedDictionary(uncheckedUniqueKeysWithValues: items)
expectEqualElements(d, items)
}
func test_uniqueKeysWithValues_unlabeled_tuples() {
let items: [(String, Int)] = [
("zero", 0),
("one", 1),
("two", 2),
("three", 3),
]
let d = OrderedDictionary(uncheckedUniqueKeysWithValues: items)
expectEqualElements(d, items)
}
func test_uniqueKeys_values() {
let d = OrderedDictionary(
uncheckedUniqueKeys: ["zero", "one", "two", "three"],
values: [0, 1, 2, 3])
expectEqualElements(d, [
(key: "zero", value: 0),
(key: "one", value: 1),
(key: "two", value: 2),
(key: "three", value: 3),
])
}
func test_uniquing_initializer_labeled_tuples() {
let items: KeyValuePairs<String, Int> = [
"a": 1,
"b": 1,
"c": 1,
"a": 2,
"a": 2,
"b": 1,
"d": 3,
]
let d = OrderedDictionary(items, uniquingKeysWith: +)
expectEqualElements(d, [
(key: "a", value: 5),
(key: "b", value: 2),
(key: "c", value: 1),
(key: "d", value: 3)
])
}
func test_uniquing_initializer_unlabeled_tuples() {
let items: [(String, Int)] = [
("a", 1),
("b", 1),
("c", 1),
("a", 2),
("a", 2),
("b", 1),
("d", 3),
]
let d = OrderedDictionary(items, uniquingKeysWith: +)
expectEqualElements(d, [
(key: "a", value: 5),
(key: "b", value: 2),
(key: "c", value: 1),
(key: "d", value: 3)
])
}
func test_grouping_initializer() {
let items: [String] = [
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"
]
let d = OrderedDictionary<Int, [String]>(grouping: items, by: { $0.count })
expectEqualElements(d, [
(key: 3, value: ["one", "two", "six", "ten"]),
(key: 5, value: ["three", "seven", "eight"]),
(key: 4, value: ["four", "five", "nine"]),
])
}
func test_uncheckedUniqueKeysWithValues_labeled_tuples() {
let items: KeyValuePairs<String, Int> = [
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
]
let d = OrderedDictionary(uncheckedUniqueKeysWithValues: items)
expectEqualElements(d, items)
}
func test_uncheckedUniqueKeysWithValues_unlabeled_tuples() {
let items: [(String, Int)] = [
("zero", 0),
("one", 1),
("two", 2),
("three", 3),
]
let d = OrderedDictionary(uncheckedUniqueKeysWithValues: items)
expectEqualElements(d, items)
}
func test_uncheckedUniqueKeys_values() {
let d = OrderedDictionary(
uncheckedUniqueKeys: ["zero", "one", "two", "three"],
values: [0, 1, 2, 3])
expectEqualElements(d, [
(key: "zero", value: 0),
(key: "one", value: 1),
(key: "two", value: 2),
(key: "three", value: 3),
])
}
func test_ExpressibleByDictionaryLiteral() {
let d0: OrderedDictionary<String, Int> = [:]
expectTrue(d0.isEmpty)
let d1: OrderedDictionary<String, Int> = [
"one": 1,
"two": 2,
"three": 3,
"four": 4,
]
expectEqualElements(d1.map { $0.key }, ["one", "two", "three", "four"])
expectEqualElements(d1.map { $0.value }, [1, 2, 3, 4])
}
func test_keys() {
let d: OrderedDictionary = [
"one": 1,
"two": 2,
"three": 3,
"four": 4,
]
expectEqual(d.keys, ["one", "two", "three", "four"] as OrderedSet)
}
func test_counts() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
let (d, _) = tracker.orderedDictionary(keys: 0 ..< count)
expectEqual(d.isEmpty, count == 0)
expectEqual(d.count, count)
expectEqual(d.underestimatedCount, count)
}
}
}
func test_index_forKey() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEvery("offset", in: 0 ..< count) { offset in
expectEqual(d.index(forKey: reference[offset].key), offset)
}
expectNil(d.index(forKey: tracker.instance(for: -1)))
expectNil(d.index(forKey: tracker.instance(for: count)))
}
}
}
@available(*, deprecated)
func test_subscript_offset() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEvery("offset", in: 0 ..< count) { offset in
let item = d[offset: offset]
expectEqual(item, reference[offset])
}
}
}
}
func test_subscript_getter() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withEvery("offset", in: 0 ..< count) { offset in
expectEqual(d[reference[offset].key], reference[offset].value)
}
expectNil(d[tracker.instance(for: -1)])
expectNil(d[tracker.instance(for: count)])
}
}
}
func test_subscript_setter_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
withHiddenCopies(if: isShared, of: &d) { d in
d[reference[offset].key] = replacement
reference[offset].value = replacement
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_subscript_setter_remove() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
d[reference[offset].key] = nil
reference.remove(at: offset)
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_subscript_setter_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary<LifetimeTracked<Int>, LifetimeTracked<Int>> = [:]
withEvery("offset", in: 0 ..< count) { offset in
withHiddenCopies(if: isShared, of: &d) { d in
d[keys[offset]] = values[offset]
expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
}
}
}
func test_subscript_setter_noop() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let key = tracker.instance(for: -1)
withHiddenCopies(if: isShared, of: &d) { d in
d[key] = nil
}
expectEqualElements(d, reference)
}
}
}
}
func mutate<T, R>(
_ value: inout T,
_ body: (inout T) throws -> R
) rethrows -> R {
try body(&value)
}
func test_subscript_modify_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
withHiddenCopies(if: isShared, of: &d) { d in
mutate(&d[reference[offset].key]) { $0 = replacement }
reference[offset].value = replacement
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_subscript_modify_remove() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
let key = reference[offset].key
mutate(&d[key]) { v in
expectEqual(v, reference[offset].value)
v = nil
}
reference.remove(at: offset)
}
}
}
}
}
}
func test_subscript_modify_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary<LifetimeTracked<Int>, LifetimeTracked<Int>> = [:]
withEvery("offset", in: 0 ..< count) { offset in
withHiddenCopies(if: isShared, of: &d) { d in
mutate(&d[keys[offset]]) { v in
expectNil(v)
v = values[offset]
}
expectEqual(d.count, offset + 1)
expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
}
}
}
func test_subscript_modify_noop() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let key = tracker.instance(for: -1)
withHiddenCopies(if: isShared, of: &d) { d in
mutate(&d[key]) { v in
expectNil(v)
v = nil
}
}
expectEqualElements(d, reference)
}
}
}
}
func test_defaulted_subscript_getter() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let fallback = tracker.instance(for: -1)
withEvery("offset", in: 0 ..< count) { offset in
let key = reference[offset].key
expectEqual(d[key, default: fallback], reference[offset].value)
}
expectEqual(
d[tracker.instance(for: -1), default: fallback],
fallback)
expectEqual(
d[tracker.instance(for: count), default: fallback],
fallback)
}
}
}
}
func test_defaulted_subscript_modify_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
let fallback = tracker.instance(for: -1)
withHiddenCopies(if: isShared, of: &d) { d in
let key = reference[offset].key
mutate(&d[key, default: fallback]) { v in
expectEqual(v, reference[offset].value)
v = replacement
}
reference[offset].value = replacement
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_defaulted_subscript_modify_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary<LifetimeTracked<Int>, LifetimeTracked<Int>> = [:]
let fallback = tracker.instance(for: -1)
withEvery("offset", in: 0 ..< count) { offset in
withHiddenCopies(if: isShared, of: &d) { d in
let key = keys[offset]
mutate(&d[key, default: fallback]) { v in
expectEqual(v, fallback)
v = values[offset]
}
expectEqual(d.count, offset + 1)
expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
}
}
}
func test_updateValue_forKey_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
withHiddenCopies(if: isShared, of: &d) { d in
let key = reference[offset].key
let old = d.updateValue(replacement, forKey: key)
expectEqual(old, reference[offset].value)
reference[offset].value = replacement
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_updateValue_forKey_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary<LifetimeTracked<Int>, LifetimeTracked<Int>> = [:]
withEvery("offset", in: 0 ..< count) { offset in
withHiddenCopies(if: isShared, of: &d) { d in
let key = keys[offset]
let old = d.updateValue(values[offset], forKey: key)
expectNil(old)
expectEqual(d.count, offset + 1)
expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
}
}
}
func test_updateValue_forKey_insertingAt_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
withHiddenCopies(if: isShared, of: &d) { d in
let key = reference[offset].key
let (old, index) =
d.updateValue(replacement, forKey: key, insertingAt: 0)
expectEqual(old, reference[offset].value)
expectEqual(index, offset)
reference[offset].value = replacement
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_updateValue_forKey_insertingAt_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary<LifetimeTracked<Int>, LifetimeTracked<Int>> = [:]
withEvery("offset", in: 0 ..< count) { offset in
withHiddenCopies(if: isShared, of: &d) { d in
let key = keys[count - 1 - offset]
let value = values[count - 1 - offset]
let (old, index) =
d.updateValue(value, forKey: key, insertingAt: 0)
expectNil(old)
expectEqual(index, 0)
expectEqual(d.count, offset + 1)
expectEqualElements(d, reference.suffix(offset + 1))
}
}
}
}
}
}
func test_updateValue_forKey_default_closure_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
let fallback = tracker.instance(for: -2)
withHiddenCopies(if: isShared, of: &d) { d in
let key = reference[offset].key
d.updateValue(forKey: key, default: fallback) { value in
expectEqual(value, reference[offset].value)
value = replacement
}
reference[offset].value = replacement
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_updateValue_forKey_default_closure_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary<LifetimeTracked<Int>, LifetimeTracked<Int>> = [:]
let fallback = tracker.instance(for: -2)
withEvery("offset", in: 0 ..< count) { offset in
withHiddenCopies(if: isShared, of: &d) { d in
let key = keys[offset]
d.updateValue(forKey: key, default: fallback) { value in
expectEqual(value, fallback)
value = values[offset]
}
expectEqual(d.count, offset + 1)
expectEqualElements(d, reference.prefix(offset + 1))
}
}
}
}
}
}
func test_updateValue_forKey_insertingDefault_at_closure_update() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
let replacement = tracker.instance(for: -1)
let fallback = tracker.instance(for: -2)
withHiddenCopies(if: isShared, of: &d) { d in
let (key, value) = reference[offset]
d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in
expectEqual(v, value)
v = replacement
}
reference[offset].value = replacement
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_updateValue_forKey_insertingDefault_at_closure_insert() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
let keys = tracker.instances(for: 0 ..< count)
let values = tracker.instances(for: (0 ..< count).map { 100 + $0 })
let reference = zip(keys, values).map { (key: $0.0, value: $0.1) }
var d: OrderedDictionary<LifetimeTracked<Int>, LifetimeTracked<Int>> = [:]
let fallback = tracker.instance(for: -2)
withEvery("offset", in: 0 ..< count) { offset in
withHiddenCopies(if: isShared, of: &d) { d in
let (key, value) = reference[count - 1 - offset]
d.updateValue(forKey: key, insertingDefault: fallback, at: 0) { v in
expectEqual(v, fallback)
v = value
}
expectEqual(d.count, offset + 1)
expectEqualElements(d, reference.suffix(offset + 1))
}
}
}
}
}
}
func test_removeValue_forKey() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
let (key, value) = reference.remove(at: offset)
let actual = d.removeValue(forKey: key)
expectEqual(actual, value)
expectEqualElements(d, reference)
expectNil(d.removeValue(forKey: key))
}
}
}
}
}
}
func test_merge_labeled_tuple() {
var d: OrderedDictionary = [
"one": 1,
"two": 1,
"three": 1,
]
let items: KeyValuePairs = [
"one": 1,
"one": 1,
"three": 1,
"four": 1,
"one": 1,
]
d.merge(items, uniquingKeysWith: +)
expectEqualElements(d, [
"one": 4,
"two": 1,
"three": 2,
"four": 1,
] as KeyValuePairs)
}
func test_merge_unlabeled_tuple() {
var d: OrderedDictionary = [
"one": 1,
"two": 1,
"three": 1,
]
let items: [(String, Int)] = [
("one", 1),
("one", 1),
("three", 1),
("four", 1),
("one", 1),
]
d.merge(items, uniquingKeysWith: +)
expectEqualElements(d, [
"one": 4,
"two": 1,
"three": 2,
"four": 1,
] as KeyValuePairs)
}
func test_merging_labeled_tuple() {
let d: OrderedDictionary = [
"one": 1,
"two": 1,
"three": 1,
]
let items: KeyValuePairs = [
"one": 1,
"one": 1,
"three": 1,
"four": 1,
"one": 1,
]
let d2 = d.merging(items, uniquingKeysWith: +)
expectEqualElements(d, [
"one": 1,
"two": 1,
"three": 1,
] as KeyValuePairs)
expectEqualElements(d2, [
"one": 4,
"two": 1,
"three": 2,
"four": 1,
] as KeyValuePairs)
}
func test_merging_unlabeled_tuple() {
let d: OrderedDictionary = [
"one": 1,
"two": 1,
"three": 1,
]
let items: [(String, Int)] = [
("one", 1),
("one", 1),
("three", 1),
("four", 1),
("one", 1),
]
let d2 = d.merging(items, uniquingKeysWith: +)
expectEqualElements(d, [
"one": 1,
"two": 1,
"three": 1,
] as KeyValuePairs)
expectEqualElements(d2, [
"one": 4,
"two": 1,
"three": 2,
"four": 1,
] as KeyValuePairs)
}
func test_filter() {
let items = (0 ..< 100).map { ($0, 100 * $0) }
let d = OrderedDictionary(uniqueKeysWithValues: items)
var c = 0
let d2 = d.filter { item in
c += 1
expectEqual(item.value, 100 * item.key)
return item.key.isMultiple(of: 2)
}
expectEqual(c, 100)
expectEqualElements(d, items)
expectEqualElements(d2, (0 ..< 50).compactMap { key in
return (key: 2 * key, value: 200 * key)
})
}
func test_mapValues() {
let items = (0 ..< 100).map { ($0, 100 * $0) }
let d = OrderedDictionary(uniqueKeysWithValues: items)
var c = 0
let d2 = d.mapValues { value -> String in
c += 1
expectTrue(value.isMultiple(of: 100))
return "\(value)"
}
expectEqual(c, 100)
expectEqualElements(d, items)
expectEqualElements(d2, (0 ..< 100).compactMap { key in
(key: key, value: "\(100 * key)")
})
}
func test_compactMapValue() {
let items = (0 ..< 100).map { ($0, 100 * $0) }
let d = OrderedDictionary(uniqueKeysWithValues: items)
var c = 0
let d2 = d.compactMapValues { value -> String? in
c += 1
guard value.isMultiple(of: 200) else { return nil }
expectTrue(value.isMultiple(of: 100))
return "\(value)"
}
expectEqual(c, 100)
expectEqualElements(d, items)
expectEqualElements(d2, (0 ..< 50).map { key in
(key: 2 * key, value: "\(200 * key)")
})
}
func test_CustomStringConvertible() {
let a: OrderedDictionary<Int, Int> = [:]
expectEqual(a.description, "[:]")
let b: OrderedDictionary<Int, Int> = [0: 1]
expectEqual(b.description, "[0: 1]")
let c: OrderedDictionary<Int, Int> = [0: 1, 2: 3, 4: 5]
expectEqual(c.description, "[0: 1, 2: 3, 4: 5]")
}
func test_CustomDebugStringConvertible() {
let a: OrderedDictionary<Int, Int> = [:]
expectEqual(a.debugDescription,
"OrderedDictionary<Int, Int>([:])")
let b: OrderedDictionary<Int, Int> = [0: 1]
expectEqual(b.debugDescription,
"OrderedDictionary<Int, Int>([0: 1])")
let c: OrderedDictionary<Int, Int> = [0: 1, 2: 3, 4: 5]
expectEqual(c.debugDescription,
"OrderedDictionary<Int, Int>([0: 1, 2: 3, 4: 5])")
}
func test_customReflectable() {
do {
let d: OrderedDictionary<Int, Int> = [1: 2, 3: 4, 5: 6]
let mirror = Mirror(reflecting: d)
expectEqual(mirror.displayStyle, .dictionary)
expectNil(mirror.superclassMirror)
expectTrue(mirror.children.compactMap { $0.label }.isEmpty) // No label
expectEqualElements(
mirror.children.compactMap { $0.value as? (key: Int, value: Int) },
d.map { $0 })
}
}
func test_Equatable_Hashable() {
let samples: [[OrderedDictionary<Int, Int>]] = [
[[:], [:]],
[[1: 100], [1: 100]],
[[2: 200], [2: 200]],
[[3: 300], [3: 300]],
[[100: 1], [100: 1]],
[[1: 1], [1: 1]],
[[100: 100], [100: 100]],
[[1: 100, 2: 200], [1: 100, 2: 200]],
[[2: 200, 1: 100], [2: 200, 1: 100]],
[[1: 100, 2: 200, 3: 300], [1: 100, 2: 200, 3: 300]],
[[2: 200, 1: 100, 3: 300], [2: 200, 1: 100, 3: 300]],
[[3: 300, 2: 200, 1: 100], [3: 300, 2: 200, 1: 100]],
[[3: 300, 1: 100, 2: 200], [3: 300, 1: 100, 2: 200]]
]
checkHashable(equivalenceClasses: samples)
}
func test_Encodable() throws {
let d1: OrderedDictionary<Int, Int> = [:]
let v1: MinimalEncoder.Value = .array([])
expectEqual(try MinimalEncoder.encode(d1), v1)
let d2: OrderedDictionary<Int, Int> = [0: 1]
let v2: MinimalEncoder.Value = .array([.int(0), .int(1)])
expectEqual(try MinimalEncoder.encode(d2), v2)
let d3: OrderedDictionary<Int, Int> = [0: 1, 2: 3]
let v3: MinimalEncoder.Value =
.array([.int(0), .int(1), .int(2), .int(3)])
expectEqual(try MinimalEncoder.encode(d3), v3)
let d4 = OrderedDictionary(
uniqueKeys: 0 ..< 100,
values: (0 ..< 100).map { 100 * $0 })
let v4: MinimalEncoder.Value =
.array((0 ..< 100).flatMap { [.int($0), .int(100 * $0)] })
expectEqual(try MinimalEncoder.encode(d4), v4)
}
func test_Decodable() throws {
typealias OD = OrderedDictionary<Int, Int>
let d1: OD = [:]
let v1: MinimalEncoder.Value = .array([])
expectEqual(try MinimalDecoder.decode(v1, as: OD.self), d1)
let d2: OD = [0: 1]
let v2: MinimalEncoder.Value = .array([.int(0), .int(1)])
expectEqual(try MinimalDecoder.decode(v2, as: OD.self), d2)
let d3: OD = [0: 1, 2: 3]
let v3: MinimalEncoder.Value =
.array([.int(0), .int(1), .int(2), .int(3)])
expectEqual(try MinimalDecoder.decode(v3, as: OD.self), d3)
let d4 = OrderedDictionary(
uniqueKeys: 0 ..< 100,
values: (0 ..< 100).map { 100 * $0 })
let v4: MinimalEncoder.Value =
.array((0 ..< 100).flatMap { [.int($0), .int(100 * $0)] })
expectEqual(try MinimalDecoder.decode(v4, as: OD.self), d4)
let v5: MinimalEncoder.Value = .array([.int(0), .int(1), .int(2)])
expectThrows(try MinimalDecoder.decode(v5, as: OD.self)) { error in
guard case DecodingError.dataCorrupted(let context) = error else {
expectFailure("Unexpected error \(error)")
return
}
expectEqual(context.debugDescription,
"Unkeyed container reached end before value in key-value pair")
}
let v6: MinimalEncoder.Value = .array([.int(0), .int(1), .int(0), .int(2)])
expectThrows(try MinimalDecoder.decode(v6, as: OD.self)) { error in
guard case DecodingError.dataCorrupted(let context) = error else {
expectFailure("Unexpected error \(error)")
return
}
expectEqual(context.debugDescription, "Duplicate key at offset 2")
}
}
func test_swapAt() {
withEvery("count", in: 0 ..< 20) { count in
withEvery("i", in: 0 ..< count) { i in
withEvery("j", in: 0 ..< count) { j in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
reference.swapAt(i, j)
withHiddenCopies(if: isShared, of: &d) { d in
d.swapAt(i, j)
expectEqualElements(d, reference)
expectEqual(d[reference[i].key], reference[i].value)
expectEqual(d[reference[j].key], reference[j].value)
}
}
}
}
}
}
}
func test_partition() {
withEvery("seed", in: 0 ..< 10) { seed in
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
let expectedPivot = reference.partition { $0.key.payload < count / 2 }
withHiddenCopies(if: isShared, of: &d) { d in
let actualPivot = d.partition { $0.key.payload < count / 2 }
expectEqual(actualPivot, expectedPivot)
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_sort() {
withEvery("seed", in: 0 ..< 10) { seed in
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
reference.sort(by: { $0.key < $1.key })
withHiddenCopies(if: isShared, of: &d) { d in
d.sort()
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_sort_by() {
withEvery("seed", in: 0 ..< 10) { seed in
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var rng = RepeatableRandomNumberGenerator(seed: seed)
var (d, reference) = tracker.orderedDictionary(
keys: (0 ..< count).shuffled(using: &rng))
reference.sort(by: { $0.key > $1.key })
withHiddenCopies(if: isShared, of: &d) { d in
d.sort(by: { $0.key > $1.key })
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_shuffle() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withEvery("seed", in: 0 ..< 10) { seed in
var d = OrderedDictionary(
uniqueKeys: 0 ..< count,
values: 100 ..< 100 + count)
var items = (0 ..< count).map { (key: $0, value: 100 + $0) }
withHiddenCopies(if: isShared, of: &d) { d in
expectEqualElements(d, items)
var rng1 = RepeatableRandomNumberGenerator(seed: seed)
items.shuffle(using: &rng1)
var rng2 = RepeatableRandomNumberGenerator(seed: seed)
d.shuffle(using: &rng2)
items.sort(by: { $0.key < $1.key })
d.sort()
expectEqualElements(d, items)
}
}
}
if count >= 2 {
// Check that shuffling with the system RNG does permute the elements.
var d = OrderedDictionary(
uniqueKeys: 0 ..< count,
values: 100 ..< 100 + count)
let original = d
var success = false
for _ in 0 ..< 1000 {
d.shuffle()
if !d.elementsEqual(
original,
by: { $0.key == $1.key && $0.value == $1.value}
) {
success = true
break
}
}
expectTrue(success)
}
}
}
func test_reverse() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
reference.reverse()
d.reverse()
expectEqualElements(d, reference)
}
}
}
}
}
func test_removeAll() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, _) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
d.removeAll()
expectEqual(d.keys.__unstable.scale, 0)
expectEqualElements(d, [])
}
}
}
}
}
func test_removeAll_keepCapacity() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, _) = tracker.orderedDictionary(keys: 0 ..< count)
let origScale = d.keys.__unstable.scale
withHiddenCopies(if: isShared, of: &d) { d in
d.removeAll(keepingCapacity: true)
expectEqual(d.keys.__unstable.scale, origScale)
expectEqualElements(d, [])
}
}
}
}
}
func test_remove_at() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("offset", in: 0 ..< count) { offset in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
let actual = d.remove(at: offset)
let expectedItem = reference.remove(at: offset)
expectEqual(actual.key, expectedItem.key)
expectEqual(actual.value, expectedItem.value)
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_removeSubrange() {
withEvery("count", in: 0 ..< 30) { count in
withEveryRange("range", in: 0 ..< count) { range in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
d.removeSubrange(range)
reference.removeSubrange(range)
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_removeSubrange_rangeExpression() {
let d = OrderedDictionary(uniqueKeys: 0 ..< 30, values: 100 ..< 130)
let item = (0 ..< 30).map { (key: $0, value: 100 + $0) }
var d1 = d
d1.removeSubrange(...10)
expectEqualElements(d1, item[11...])
var d2 = d
d2.removeSubrange(..<10)
expectEqualElements(d2, item[10...])
var d3 = d
d3.removeSubrange(10...)
expectEqualElements(d3, item[0 ..< 10])
}
func test_removeLast() {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 30)
withEvery("i", in: 0 ..< d.count) { i in
withHiddenCopies(if: isShared, of: &d) { d in
let actual = d.removeLast()
let ref = reference.removeLast()
expectEqual(actual.key, ref.key)
expectEqual(actual.value, ref.value)
expectEqualElements(d, reference)
}
}
}
}
}
func test_removeFirst() {
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 30)
withEvery("i", in: 0 ..< d.count) { i in
withHiddenCopies(if: isShared, of: &d) { d in
let actual = d.removeFirst()
let expected = reference.removeFirst()
expectEqual(actual.key, expected.key)
expectEqual(actual.value, expected.value)
expectEqualElements(d, reference)
}
}
}
}
}
func test_removeLast_n() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("suffix", in: 0 ..< count) { suffix in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
d.removeLast(suffix)
reference.removeLast(suffix)
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_removeFirst_n() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("prefix", in: 0 ..< count) { prefix in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
d.removeFirst(prefix)
reference.removeFirst(prefix)
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_removeAll_where() {
withEvery("count", in: 0 ..< 30) { count in
withEvery("n", in: [2, 3, 4]) { n in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
withHiddenCopies(if: isShared, of: &d) { d in
d.removeAll(where: { !$0.key.payload.isMultiple(of: n) })
reference.removeAll(where: { !$0.key.payload.isMultiple(of: n) })
expectEqualElements(d, reference)
}
}
}
}
}
}
func test_Sequence() {
withEvery("count", in: 0 ..< 30) { count in
withLifetimeTracking { tracker in
let (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
checkSequence(
{ d },
expectedContents: reference,
by: { $0.key == $1.0 && $0.value == $1.1 })
}
}
}
}
| 32.306552 | 84 | 0.544607 |
fb4937adafd63134ab5946b67bbe3086d263287d | 514 | //
// String+Version.swift
// MsrSwifty
//
// Created by monsoir on 4/4/20.
//
import Foundation
public extension CompatibleValue {
var asVersion: Wrapper<Self> {
return Wrapper(self)
}
}
public extension Wrapper where Base == String {
/// 是否新版本
func isNewerThan(_ compareVersion: String) -> Bool {
if base.compare(compareVersion, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedDescending {
return true
}
return false
}
}
| 20.56 | 121 | 0.649805 |
14647d6fa6a47596cbdb656b751842161314a07d | 6,593 | /*
* --------------------------------------------------------------------------------
* <copyright company="Aspose" file="DeleteCommentsRequest.swift">
* Copyright (c) 2021 Aspose.Words for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------
*/
import Foundation
// Request model for deleteComments operation.
@available(macOS 10.12, iOS 10.3, watchOS 3.3, tvOS 12.0, *)
public class DeleteCommentsRequest : WordsApiRequest {
private let name : String;
private let folder : String?;
private let storage : String?;
private let loadEncoding : String?;
private let password : String?;
private let destFileName : String?;
private let revisionAuthor : String?;
private let revisionDateTime : String?;
private enum CodingKeys: String, CodingKey {
case name;
case folder;
case storage;
case loadEncoding;
case password;
case destFileName;
case revisionAuthor;
case revisionDateTime;
case invalidCodingKey;
}
// Initializes a new instance of the DeleteCommentsRequest class.
public init(name : String, folder : String? = nil, storage : String? = nil, loadEncoding : String? = nil, password : String? = nil, destFileName : String? = nil, revisionAuthor : String? = nil, revisionDateTime : String? = nil) {
self.name = name;
self.folder = folder;
self.storage = storage;
self.loadEncoding = loadEncoding;
self.password = password;
self.destFileName = destFileName;
self.revisionAuthor = revisionAuthor;
self.revisionDateTime = revisionDateTime;
}
// The filename of the input document.
public func getName() -> String {
return self.name;
}
// Original document folder.
public func getFolder() -> String? {
return self.folder;
}
// Original document storage.
public func getStorage() -> String? {
return self.storage;
}
// Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML.
public func getLoadEncoding() -> String? {
return self.loadEncoding;
}
// Password for opening an encrypted document.
public func getPassword() -> String? {
return self.password;
}
// Result path of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document.
public func getDestFileName() -> String? {
return self.destFileName;
}
// Initials of the author to use for revisions.If you set this parameter and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.
public func getRevisionAuthor() -> String? {
return self.revisionAuthor;
}
// The date and time to use for revisions.
public func getRevisionDateTime() -> String? {
return self.revisionDateTime;
}
// Creates the api request data
public func createApiRequestData(apiInvoker : ApiInvoker, configuration : Configuration) throws -> WordsApiRequestData {
var rawPath = "/words/{name}/comments";
rawPath = rawPath.replacingOccurrences(of: "{name}", with: try ObjectSerializer.serializeToString(value: self.getName()));
rawPath = rawPath.replacingOccurrences(of: "//", with: "/");
let urlPath = (try configuration.getApiRootUrl()).appendingPathComponent(rawPath);
var urlBuilder = URLComponents(url: urlPath, resolvingAgainstBaseURL: false)!;
var queryItems : [URLQueryItem] = [];
if (self.getFolder() != nil) {
queryItems.append(URLQueryItem(name: "folder", value: try ObjectSerializer.serializeToString(value: self.getFolder()!)));
}
if (self.getStorage() != nil) {
queryItems.append(URLQueryItem(name: "storage", value: try ObjectSerializer.serializeToString(value: self.getStorage()!)));
}
if (self.getLoadEncoding() != nil) {
queryItems.append(URLQueryItem(name: "loadEncoding", value: try ObjectSerializer.serializeToString(value: self.getLoadEncoding()!)));
}
if (self.getPassword() != nil) {
queryItems.append(URLQueryItem(name: apiInvoker.isEncryptionAllowed() ? "encryptedPassword" : "password", value: try apiInvoker.encryptString(value: self.getPassword()!)));
}
if (self.getDestFileName() != nil) {
queryItems.append(URLQueryItem(name: "destFileName", value: try ObjectSerializer.serializeToString(value: self.getDestFileName()!)));
}
if (self.getRevisionAuthor() != nil) {
queryItems.append(URLQueryItem(name: "revisionAuthor", value: try ObjectSerializer.serializeToString(value: self.getRevisionAuthor()!)));
}
if (self.getRevisionDateTime() != nil) {
queryItems.append(URLQueryItem(name: "revisionDateTime", value: try ObjectSerializer.serializeToString(value: self.getRevisionDateTime()!)));
}
if (queryItems.count > 0) {
urlBuilder.queryItems = queryItems;
}
let result = WordsApiRequestData(url: urlBuilder.url!, method: "DELETE");
return result;
}
// Deserialize response of this request
public func deserializeResponse(data : Data) throws -> Any? {
return nil;
}
}
| 43.953333 | 235 | 0.660701 |
5d47cb09d2502fdb174f0fdaab671aaf6a2238bf | 1,208 | //
// AppTaskHandler.swift
// PGAppTask_Example
//
// Created by ipagong.dev on 2021/04/26.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import UIKit
import PGAppTask
enum AppTaskType : Int, AppTaskComparable {
case vendorSetup
case doSomthing
case scheme
var taskType: AppBaseTask.Type {
switch self {
case .vendorSetup: return VendorSetupTask.self
case .doSomthing: return DoSomethingTask.self
case .scheme: return SchemeTask.self
}
}
}
struct AppTaskHandler {
static func didFinishLaunchingWithOptions(_ options: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AppTaskQueue.shared.push(.vendorSetup, options: options)
return true
}
static func initialize(_ options: [UIApplication.LaunchOptionsKey: Any]? = nil) {
AppTaskQueue.shared.push(.doSomthing, options: options)
AppTaskQueue.shared.start()
}
static func destroy() {
AppTaskQueue.shared.clear()
}
}
extension AppTaskQueue {
func push(_ type: AppTaskType, options: [AnyHashable: Any]? = nil, object: Any? = nil) {
self.push(with: type, options: options, object: object)
}
}
| 25.702128 | 106 | 0.665563 |
8a4c95a17574a492c9e4d632f5d735332d866246 | 1,382 | //
// main.swift
// BirthdayCalculator - Finding days left (on average) on Earth
// Motivational tool to focus on what matters.
//
// Created by Benjamin Dirgo on 5/25/20.
// Copyright © 2020 Benjamin Dirgo. All rights reserved.
//
import Foundation
// Totally copied from SO: https://stackoverflow.com/questions/50950092/calculating-the-difference-between-two-dates-in-swift
// Probably don't need this, and only needed to type cast to a double
extension Date {
static func - (lhs: Date, rhs: Date) -> TimeInterval {
return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate
}
}
// TODO: Ask for birthday?
var components = DateComponents()
let birthYear = 1990
components.year = birthYear
let date = Calendar.current.date(from: components) ?? Date()
// Calculate date from then
// https://media.nmfn.com/tnetwork/lifespan
let actualYears = 87 // A new highscore!
var actualComponent = DateComponents()
actualComponent.year = birthYear + actualYears
let lastDate = Calendar.current.date(from: actualComponent) ?? Date()
// Output the days left
let today = Date()
// TODO: terrible names, and this function is probably not necessary
func secondsToDays(_ time: TimeInterval) -> String {
let secondsPerDay = 60 * 60 * 24
let days = Double(time) / Double(secondsPerDay)
return "\(days)"
}
print(secondsToDays(lastDate - today))
| 33.707317 | 125 | 0.734443 |
5646dc0719d379924b8eb3fb843dc4a241771038 | 5,445 | //
// UIDebugClassCollectionViewController.swift
// OpenLink
//
// Created by Vince Davis on 4/5/19.
// Copyright © 2019 Milwaukee Tool. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class UIDebugClassCollectionViewController: UIViewController {
var debugItem: UIDebuggable!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .lightGray
self.title = String(describing: debugItem.classType)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
layout.itemSize = CGSize(width: self.view.frame.size.width - 30, height: 400)
let collectionView: UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.backgroundColor = .lightGray
self.view.addSubview(collectionView)
}
convenience init(with item: UIDebuggable) {
self.init()
self.debugItem = item
}
}
// MARK: - UICollectionViewDataSource & UICollectionViewDelegate
extension UIDebugClassCollectionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return debugItem.list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.contentView.backgroundColor = .white
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let item = debugItem.list[indexPath.row]
let split = item.components(separatedBy: ".")
let className = split.count > 1 ? split[1] : split[0]
let classLabel = UILabel()
classLabel.font = .boldSystemFont(ofSize: 18)
let stackView = UIStackView()
cell.contentView.addSubview(stackView)
stackView.alignment = .center
stackView.distribution = .fill
stackView.axis = .vertical
stackView.spacing = 4.0
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 5).isActive = true
stackView.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -5).isActive = true
stackView.leftAnchor.constraint(equalTo: cell.contentView.leftAnchor, constant: 5).isActive = true
stackView.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: -5).isActive = true
stackView.addArrangedSubview(classLabel)
classLabel.text = className
classLabel.textColor = self.navigationController?.navigationBar.tintColor
if let view = UIDebug.instantiateView(named: item) {
view.heightAnchor.constraint(equalToConstant: view.frame.size.height).isActive = true
view.widthAnchor.constraint(equalToConstant: view.frame.size.width).isActive = true
stackView.addArrangedSubview(view)
return cell
}
if let button = UIDebug.instantiateButton(named: item) {
button.heightAnchor.constraint(equalToConstant: button.frame.size.height).isActive = true
button.widthAnchor.constraint(equalToConstant: button.frame.size.width).isActive = true
stackView.addArrangedSubview(button)
return cell
}
let notSetupLabel = UILabel()
notSetupLabel.text = "Not Setup"
notSetupLabel.textColor = self.navigationController?.navigationBar.tintColor
notSetupLabel.font = .boldSystemFont(ofSize: 14)
stackView.addArrangedSubview(notSetupLabel)
return cell
}
}
extension UIDebugClassCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let className = debugItem.list[indexPath.row]
if let view = UIDebug.instantiateView(named: className) {
let size = CGSize(width: self.view.frame.size.width - 30, height: view.frame.size.height + 30)
return size
}
if let button = UIDebug.instantiateButton(named: className) {
let size = CGSize(width: self.view.frame.size.width - 30, height: button.frame.size.height + 30)
return size
}
let size = CGSize(width: self.view.frame.size.width - 30, height: 60)
return size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}
}
| 40.634328 | 162 | 0.679522 |
0e376222106f7fdad0ac52970481bc4ec11f86a2 | 5,197 | //
// Application.swift
// UniversalBrainController
//
// Created by Kumar Muthaiah on 28/10/18.
//
//Copyright 2020 Kumar Muthaiah
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UDocsUtility
import UDocsDatabaseModel
import UDocsDatabaseUtility
import UDocsNeuronModel
import UDocsNeuronUtility
public class BrainControllerApplication : Neuron {
static var dendriteMap: [String : Neuron] = [String : Neuron]()
private var responseMap: [String : NeuronRequest] = [String : NeuronRequest]()
static var rootResponseMap: [String : NeuronRequest] = [String : NeuronRequest]()
static let serialQueue = DispatchQueue(label: "SerialQueue")
static let serialQueue1 = DispatchQueue(label: "SerialQueue1")
static public func getDescription() -> String {
return "Brain Controller Application"
}
static public func getDendrite(sourceId: String) -> (Neuron) {
var neuron: Neuron?
serialQueue.sync {
print("Before: \(dendriteMap.debugDescription)")
neuron = dendriteMap[sourceId]
if neuron == nil {
print("\(getName()): Created: \(sourceId)")
dendriteMap[sourceId] = BrainControllerApplication()
neuron = dendriteMap[sourceId]
}
print("After creation: \(dendriteMap.debugDescription)")
}
return neuron!;
}
private func setChildResponse(sourceId: String, neuronRequest: NeuronRequest) {
responseMap[sourceId] = neuronRequest
}
private func getChildResponse(sourceId: String) -> NeuronRequest {
var neuronResponse: NeuronRequest?
print(responseMap)
if let _ = responseMap[sourceId] {
neuronResponse = responseMap[sourceId]
responseMap.removeValue(forKey: sourceId)
}
if neuronResponse == nil {
neuronResponse = NeuronRequest()
}
return neuronResponse!
}
public static func getDendriteSize() -> (Int) {
return dendriteMap.count
}
private static func removeDendrite(sourceId: String) {
serialQueue.sync {
print("neuronUtility: removed neuron: "+sourceId)
dendriteMap.removeValue(forKey: sourceId)
print("After removal \(getName()): \(dendriteMap.debugDescription)")
}
}
public func setDendrite(neuronRequest: NeuronRequest, udbcDatabaseOrm: UDBCDatabaseOrm, neuronUtility: NeuronUtility) {
if neuronRequest.neuronOperation.acknowledgement == true {
print("\(BrainControllerApplication.getName()): Got Acknowledgement")
return
}
if neuronRequest.neuronOperation.response == true {
print("\(BrainControllerApplication.getName()): Got Response")
BrainControllerApplication.setRootResponse(neuronSourceId: neuronRequest.neuronSource._id, request: neuronRequest)
BrainControllerApplication.removeDendrite(sourceId: neuronRequest.neuronSource._id)
print("Brain controller application Neuron Dendrite MAP: \(BrainControllerApplication.dendriteMap)")
}
}
static public func getName() -> String {
return "BrainControllerApplication"
}
public static func getRootResponse(neuronSourceId: String) -> NeuronRequest {
var neuronResponse: NeuronRequest?
// serialQueue1.sync {
if let _ = rootResponseMap[neuronSourceId] {
neuronResponse = rootResponseMap[neuronSourceId]
rootResponseMap.removeValue(forKey: neuronSourceId)
print("Root response map: \(rootResponseMap)")
}
// }
if neuronResponse == nil {
neuronResponse = NeuronRequest()
}
return neuronResponse!
}
private static func setRootResponse(neuronSourceId: String, request: NeuronRequest) {
// serialQueue1.sync {
print("\(BrainControllerNeuron.getName()) setting child response")
rootResponseMap[neuronSourceId] = request
// }
}
}
| 41.576 | 462 | 0.668847 |
1ea26ea87bebec5a88e64d53b595125f372ddccc | 1,302 | //
// SQLType.swift
// Sqlable
//
// Created by Elias Abel on 27/07/2016.
// Copyright © 2016 Meniny Lab. All rights reserved.
//
/// A SQL type
public enum SQLType: Equatable {
/// An integer
case integer
/// A double
case real
/// A string
case text
/// A date
case date
/// A boolean
case boolean
/// A nullable SQL type
indirect case nullable(SQLType)
}
public func ==(lhs: SQLType, rhs: SQLType) -> Bool {
switch (lhs, rhs) {
case (.integer, .integer): fallthrough
case (.real, .real): fallthrough
case (.text, .text): fallthrough
case (.date, .date): fallthrough
case (.boolean, .boolean): return true
case (.nullable(let t1), .nullable(let t2)) where t1 == t2: return true
case _: return false
}
}
extension SQLType: SQLPrintable {
public var sqlDescription: String {
switch self {
case .integer: return "integer not null"
case .real: return "double not null"
case .text: return "text not null"
case .date: return "timestamp not null"
case .boolean: return "integer not null"
case .nullable(.integer): return "integer"
case .nullable(.real): return "double"
case .nullable(.text): return "text"
case .nullable(.date): return "timestamp"
case .nullable(.boolean): return "integer"
case .nullable(.nullable(_)): fatalError("Nice try")
}
}
}
| 24.111111 | 72 | 0.675883 |
8970e229033545c0ce60dc67daa08d9571f68ba6 | 4,159 | //
// FloatExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/8/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Properties
public extension Float {
/// SwifterSwift: Absolute of float value.
public var abs: Float {
return Swift.abs(self)
}
/// SwifterSwift: String with number and current locale currency.
public var asLocaleCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current
return formatter.string(from: self as NSNumber)!
}
/// SwifterSwift: Ceil of float value.
public var ceil: Float {
return Foundation.ceil(self)
}
/// SwifterSwift: Radian value of degree input.
public var degreesToRadians: Float {
return Float.pi * self / 180.0
}
/// SwifterSwift: Floor of float value.
public var floor: Float {
return Foundation.floor(self)
}
/// SwifterSwift: Check if float is positive.
public var isPositive: Bool {
return self > 0
}
/// SwifterSwift: Check if float is negative.
public var isNegative: Bool {
return self < 0
}
/// SwifterSwift: Int.
public var int: Int {
return Int(self)
}
/// SwifterSwift: Double.
public var double: Double {
return Double(self)
}
/// SwifterSwift: CGFloat.
public var cgFloat: CGFloat {
return CGFloat(self)
}
/// SwifterSwift: String.
public var string: String {
return String(self)
}
/// SwifterSwift: Degree value of radian input.
public var radiansToDegrees: Float {
return self * 180 / Float.pi
}
}
// MARK: - Methods
extension Float {
/// SwifterSwift: Random float between two float values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
/// - Returns: random double between two double values.
public static func random(between min: Float, max: Float) -> Float {
return random(inRange: min...max)
}
/// SwifterSwift: Random float in a closed interval range.
///
/// - Parameter range: closed interval range.
public static func random(inRange range: ClosedRange<Float>) -> Float {
let delta = range.upperBound - range.lowerBound
return Float(arc4random()) / Float(UInt64(UINT32_MAX)) * delta + range.lowerBound
}
}
// MARK: - Initializers
public extension Float {
/// SwifterSwift: Created a random float between two float values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
public init(randomBetween min: Float, max: Float) {
self = Float.random(between: min, max: max)
}
/// SwifterSwift: Create a random float in a closed interval range.
///
/// - Parameter range: closed interval range.
public init(randomInRange range: ClosedRange<Float>) {
self = Float.random(inRange: range)
}
}
// MARK: - Operators
infix operator **
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
/// - lhs: base float.
/// - rhs: exponent float.
/// - Returns: exponentiation result (4.4 ** 0.5 = 2.0976176963).
public func ** (lhs: Float, rhs: Float) -> Float {
// http://nshipster.com/swift-operators/
return pow(lhs, rhs)
}
prefix operator √
/// SwifterSwift: Square root of float.
///
/// - Parameter int: float value to find square root for
/// - Returns: square root of given float.
public prefix func √ (Float: Float) -> Float {
// http://nshipster.com/swift-operators/
return sqrt(Float)
}
infix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameters:
/// - lhs: float number
/// - rhs: float number
/// - Returns: tuple of plus-minus operation ( 2.5 ± 1.5 -> (4, 1)).
public func ± (lhs: Float, rhs: Float) -> (Float, Float) {
// http://nshipster.com/swift-operators/
return (lhs + rhs, lhs - rhs)
}
prefix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameter int: float number
/// - Returns: tuple of plus-minus operation (± 2.5 -> (2.5, -2.5)).
public prefix func ± (Float: Float) -> (Float, Float) {
// http://nshipster.com/swift-operators/
return 0 ± Float
}
| 23.630682 | 83 | 0.67396 |
3a0a65374af963568a8586666c7e6180243994e9 | 1,543 | //
// ApplicationCoordinator.swift
// TestLocation
//
// Created by Socratis Michaelides on 07/11/2018.
// Copyright © 2018 Socratis Michaelides. All rights reserved.
//
import Core
fileprivate var onboardingWasShown = false // Always display onboarding for now
fileprivate enum LaunchInstructor {
case main, onboarding
static func configure(
tutorialWasShown: Bool = onboardingWasShown) -> LaunchInstructor {
switch (tutorialWasShown) {
case false: return .onboarding
case true: return .main
}
}
}
final class ApplicationCoordinator: BaseCoordinator {
private let coordinatorFactory: CoordinatorFactory
private let router: Router
private var instructor: LaunchInstructor {
return LaunchInstructor.configure()
}
init(router: Router, coordinatorFactory: CoordinatorFactory) {
self.router = router
self.coordinatorFactory = coordinatorFactory
}
override func start() {
switch instructor {
case .onboarding: runOnboardingFlow()
case .main: runMainFlow()
}
}
private func runOnboardingFlow() {
let coordinator = coordinatorFactory.makeOnboardingCoordinator(router: router)
coordinator.finishFlow = { [weak self, weak coordinator] in
onboardingWasShown = true
self?.start()
self?.removeDependency(coordinator)
}
addDependency(coordinator)
coordinator.start()
}
private func runMainFlow() {
let (coordinator, module) = coordinatorFactory.makeTabbarCoordinator()
addDependency(coordinator)
router.setRootModule(module, hideBar: true)
coordinator.start()
}
}
| 23.378788 | 80 | 0.754375 |
0377b9b24c10bd4a631fd58f0a0ab48124593fc1 | 2,651 | //
// ContentView.swift
// Emoji Tac Toe Swift UI
//
// Created by John Pavley on 10/7/19.
// Copyright © 2019 John Pavley. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var cellMap: [CellMarker] = [.e,.e,.e,
.e,.e,.e,
.e,.e,.e]
@State var currentTurn: CellMarker = .o
@State var score = Score(xWins: 0, oWins: 0, ties: 0)
@State var playWithAI: Bool = false {
didSet {
// TODO: Why is this not called when set?
restartGame()
}
}
@State var difficulty: Double = 0.5
var body: some View {
VStack {
// header
Text("⭕️ vs. ❌").font(.largeTitle)
Text("Score: \(score.oWins):\(score.xWins):\(score.ties)").font(.headline).padding()
// row 0
HStack {
makeCellView(index: 0)
makeCellView(index: 1)
makeCellView(index: 2)
}
// row 1
HStack {
makeCellView(index: 3)
makeCellView(index: 4)
makeCellView(index: 5)
}
// row 2
HStack {
makeCellView(index: 6)
makeCellView(index: 7)
makeCellView(index: 8)
}
// footer
Text("\(currentTurn.rawValue)'s Turn").font(.headline).padding()
HStack {
Toggle(isOn: $playWithAI) {
Text("")
}.labelsHidden()
Text("Play with AI")
}
HStack {
Text("Easy").foregroundColor(labelColor)
Slider(value: $difficulty).disabled(!playWithAI)
Text("Hard").foregroundColor(labelColor)
}.padding()
Button(action: {
self.restartGame()
}) {
Text("New Game")
}.padding()
}.padding()
}
var labelColor: Color {
if playWithAI {
return .primary
} else {
return .secondary
}
}
func restartGame() {
currentTurn = .o
cellMap = [.e,.e,.e,.e,.e,.e,.e,.e,.e]
}
func makeCellView(index: Int) -> CellView {
return CellView(index: index, currentTurn: $currentTurn, cellMap: $cellMap, score: $score, playWithAI: $playWithAI, difficulty: $difficulty)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 27.329897 | 148 | 0.464353 |
3364d27670021f928d85e5fbdd6d2c69a4f354d3 | 19,117 | //
// NSObject+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
import Foundation
import RxSwift
#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux)
import RxCocoaRuntime
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
private var deallocatingSubjectTriggerContext: UInt8 = 0
private var deallocatingSubjectContext: UInt8 = 0
#endif
private var deallocatedSubjectTriggerContext: UInt8 = 0
private var deallocatedSubjectContext: UInt8 = 0
#if !os(Linux)
/**
KVO is a tricky mechanism.
When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior.
When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior.
KVO with weak references is especially tricky. For it to work, some kind of swizzling is required.
That can be done by
* replacing object class dynamically (like KVO does)
* by swizzling `dealloc` method on all instances for a class.
* some third method ...
Both approaches can fail in certain scenarios:
* problems arise when swizzlers return original object class (like KVO does when nobody is observing)
* Problems can arise because replacing dealloc method isn't atomic operation (get implementation,
set implementation).
Second approach is chosen. It can fail in case there are multiple libraries dynamically trying
to replace dealloc method. In case that isn't the case, it should be ok.
*/
extension Reactive where Base: NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set.
`observe` is just a simple and performant wrapper around KVO mechanism.
* it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`)
* it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`)
* the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc.
If support for weak properties is needed or observing arbitrary or unknown relationships in the
ownership tree, `observeWeakly` is the preferred option.
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- parameter retainSelf: Retains self during observation if set `true`.
- returns: Observable sequence of objects on `keyPath`.
*/
public func observe<Element>(_ type: Element.Type,
_ keyPath: String,
options: KeyValueObservingOptions = [.new, .initial],
retainSelf: Bool = true) -> Observable<Element?> {
KVOObservable(object: self.base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable()
}
/**
Observes values at the provided key path using the provided options.
- parameter keyPath: A key path between the object and one of its properties.
- parameter options: Key-value observation options, defaults to `.new` and `.initial`.
- note: When the object is deallocated, a completion event is emitted.
- returns: An observable emitting value changes at the provided key path.
*/
public func observe<Element>(_ keyPath: KeyPath<Base, Element>,
options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable<Element> {
Observable<Element>.create { [weak base] observer in
let observation = base?.observe(keyPath, options: options) { obj, _ in
observer.on(.next(obj[keyPath: keyPath]))
}
return Disposables.create { observation?.invalidate() }
}
.take(until: base.rx.deallocated)
}
}
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
// KVO
extension Reactive where Base: NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`.
It can be used in all cases where `observe` can be used and additionally
* because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown
* it can be used to observe `weak` properties
**Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.**
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- returns: Observable sequence of objects on `keyPath`.
*/
public func observeWeakly<Element>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable<Element?> {
return observeWeaklyKeyPathFor(self.base, keyPath: keyPath, options: options)
.map { n in
return n as? Element
}
}
}
#endif
// Dealloc
extension Reactive where Base: AnyObject {
/**
Observable sequence of object deallocated events.
After object is deallocated one `()` element will be produced and sequence will immediately complete.
- returns: Observable sequence of object deallocated events.
*/
public var deallocated: Observable<Void> {
return self.synchronized {
if let deallocObservable = objc_getAssociatedObject(self.base, &deallocatedSubjectContext) as? DeallocObservable {
return deallocObservable.subject
}
let deallocObservable = DeallocObservable()
objc_setAssociatedObject(self.base, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return deallocObservable.subject
}
}
#if !DISABLE_SWIZZLING && !os(Linux)
/**
Observable sequence of message arguments that completes when object is deallocated.
Each element is produced before message is invoked on target object. `methodInvoked`
exists in case observing of invoked messages is needed.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of arguments passed to `selector` method.
*/
public func sentMessage(_ selector: Selector) -> Observable<[Any]> {
return self.synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return self.deallocating.map { _ in [] }
}
do {
let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector)
return proxy.messageSent.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
/**
Observable sequence of message arguments that completes when object is deallocated.
Each element is produced after message is invoked on target object. `sentMessage`
exists in case interception of sent messages before they were invoked is needed.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of arguments passed to `selector` method.
*/
public func methodInvoked(_ selector: Selector) -> Observable<[Any]> {
return self.synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return self.deallocated.map { _ in [] }
}
do {
let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector)
return proxy.methodInvoked.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
/**
Observable sequence of object deallocating events.
When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence
will immediately complete.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
- returns: Observable sequence of object deallocating events.
*/
public var deallocating: Observable<()> {
return self.synchronized {
do {
let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector)
return proxy.messageSent.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
private func registerMessageInterceptor<T: MessageInterceptorSubject>(_ selector: Selector) throws -> T {
let rxSelector = RX_selector(selector)
let selectorReference = RX_reference_from_selector(rxSelector)
let subject: T
if let existingSubject = objc_getAssociatedObject(self.base, selectorReference) as? T {
subject = existingSubject
}
else {
subject = T()
objc_setAssociatedObject(
self.base,
selectorReference,
subject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
if subject.isActive {
return subject
}
var error: NSError?
let targetImplementation = RX_ensure_observing(self.base, selector, &error)
if targetImplementation == nil {
throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown
}
subject.targetImplementation = targetImplementation!
return subject
}
#endif
}
// MARK: Message interceptors
#if !DISABLE_SWIZZLING && !os(Linux)
private protocol MessageInterceptorSubject: class {
init()
var isActive: Bool {
get
}
var targetImplementation: IMP { get set }
}
private final class DeallocatingProxy
: MessageInterceptorSubject
, RXDeallocatingObserver {
typealias Element = ()
let messageSent = ReplaySubject<()>.create(bufferSize: 1)
@objc var targetImplementation: IMP = RX_default_target_implementation()
var isActive: Bool {
return self.targetImplementation != RX_default_target_implementation()
}
init() {
}
@objc func deallocating() {
self.messageSent.on(.next(()))
}
deinit {
self.messageSent.on(.completed)
}
}
private final class MessageSentProxy
: MessageInterceptorSubject
, RXMessageSentObserver {
typealias Element = [AnyObject]
let messageSent = PublishSubject<[Any]>()
let methodInvoked = PublishSubject<[Any]>()
@objc var targetImplementation: IMP = RX_default_target_implementation()
var isActive: Bool {
return self.targetImplementation != RX_default_target_implementation()
}
init() {
}
@objc func messageSent(withArguments arguments: [Any]) {
self.messageSent.on(.next(arguments))
}
@objc func methodInvoked(withArguments arguments: [Any]) {
self.methodInvoked.on(.next(arguments))
}
deinit {
self.messageSent.on(.completed)
self.methodInvoked.on(.completed)
}
}
#endif
private final class DeallocObservable {
let subject = ReplaySubject<Void>.create(bufferSize:1)
init() {
}
deinit {
self.subject.on(.next(()))
self.subject.on(.completed)
}
}
// MARK: KVO
#if !os(Linux)
private protocol KVOObservableProtocol {
var target: AnyObject { get }
var keyPath: String { get }
var retainTarget: Bool { get }
var options: KeyValueObservingOptions { get }
}
private final class KVOObserver
: _RXKVOObserver
, Disposable {
typealias Callback = (Any?) -> Void
var retainSelf: KVOObserver?
init(parent: KVOObservableProtocol, callback: @escaping Callback) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
super.init(target: parent.target, retainTarget: parent.retainTarget, keyPath: parent.keyPath, options: parent.options.nsOptions, callback: callback)
self.retainSelf = self
}
override func dispose() {
super.dispose()
self.retainSelf = nil
}
deinit {
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
private final class KVOObservable<Element>
: ObservableType
, KVOObservableProtocol {
typealias Element = Element?
unowned var target: AnyObject
var strongTarget: AnyObject?
var keyPath: String
var options: KeyValueObservingOptions
var retainTarget: Bool
init(object: AnyObject, keyPath: String, options: KeyValueObservingOptions, retainTarget: Bool) {
self.target = object
self.keyPath = keyPath
self.options = options
self.retainTarget = retainTarget
if retainTarget {
self.strongTarget = object
}
}
func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element? {
let observer = KVOObserver(parent: self) { value in
if value as? NSNull != nil {
observer.on(.next(nil))
return
}
observer.on(.next(value as? Element))
}
return Disposables.create(with: observer.dispose)
}
}
private extension KeyValueObservingOptions {
var nsOptions: NSKeyValueObservingOptions {
var result: UInt = 0
if self.contains(.new) {
result |= NSKeyValueObservingOptions.new.rawValue
}
if self.contains(.initial) {
result |= NSKeyValueObservingOptions.initial.rawValue
}
return NSKeyValueObservingOptions(rawValue: result)
}
}
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
private func observeWeaklyKeyPathFor(_ target: NSObject, keyPath: String, options: KeyValueObservingOptions) -> Observable<AnyObject?> {
let components = keyPath.components(separatedBy: ".").filter { $0 != "self" }
let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options)
.finishWithNilWhenDealloc(target)
if !options.isDisjoint(with: .initial) {
return observable
}
else {
return observable
.skip(1)
}
}
// This should work correctly
// Identifiers can't contain `,`, so the only place where `,` can appear
// is as a delimiter.
// This means there is `W` as element in an array of property attributes.
private func isWeakProperty(_ properyRuntimeInfo: String) -> Bool {
properyRuntimeInfo.range(of: ",W,") != nil
}
private extension ObservableType where Element == AnyObject? {
func finishWithNilWhenDealloc(_ target: NSObject)
-> Observable<AnyObject?> {
let deallocating = target.rx.deallocating
return deallocating
.map { _ in
return Observable.just(nil)
}
.startWith(self.asObservable())
.switchLatest()
}
}
private func observeWeaklyKeyPathFor(
_ target: NSObject,
keyPathSections: [String],
options: KeyValueObservingOptions
) -> Observable<AnyObject?> {
weak var weakTarget: AnyObject? = target
let propertyName = keyPathSections[0]
let remainingPaths = Array(keyPathSections[1..<keyPathSections.count])
let property = class_getProperty(object_getClass(target), propertyName)
if property == nil {
return Observable.error(RxCocoaError.invalidPropertyName(object: target, propertyName: propertyName))
}
let propertyAttributes = property_getAttributes(property!)
// should dealloc hook be in place if week property, or just create strong reference because it doesn't matter
let isWeak = isWeakProperty(propertyAttributes.map(String.init) ?? "")
let propertyObservable = KVOObservable(object: target, keyPath: propertyName, options: options.union(.initial), retainTarget: false) as KVOObservable<AnyObject>
// KVO recursion for value changes
return propertyObservable
.flatMapLatest { (nextTarget: AnyObject?) -> Observable<AnyObject?> in
if nextTarget == nil {
return Observable.just(nil)
}
let nextObject = nextTarget! as? NSObject
let strongTarget: AnyObject? = weakTarget
if nextObject == nil {
return Observable.error(RxCocoaError.invalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName))
}
// if target is alive, then send change
// if it's deallocated, don't send anything
if strongTarget == nil {
return Observable.empty()
}
let nextElementsObservable = keyPathSections.count == 1
? Observable.just(nextTarget)
: observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options)
if isWeak {
return nextElementsObservable
.finishWithNilWhenDealloc(nextObject!)
}
else {
return nextElementsObservable
}
}
}
#endif
// MARK: Constants
private let deallocSelector = NSSelectorFromString("dealloc")
// MARK: AnyObject + Reactive
extension Reactive where Base: AnyObject {
func synchronized<T>( _ action: () -> T) -> T {
objc_sync_enter(self.base)
let result = action()
objc_sync_exit(self.base)
return result
}
}
extension Reactive where Base: AnyObject {
/**
Helper to make sure that `Observable` returned from `createCachedObservable` is only created once.
This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`.
*/
func lazyInstanceObservable<T: AnyObject>(_ key: UnsafeRawPointer, createCachedObservable: () -> T) -> T {
if let value = objc_getAssociatedObject(self.base, key) {
return value as! T
}
let observable = createCachedObservable()
objc_setAssociatedObject(self.base, key, observable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return observable
}
}
#endif
| 33.538596 | 169 | 0.639745 |
e5698d59dfd08249a76795c10fb169f1abd20254 | 529 | //
// Copyright © 2020 An Tran. All rights reserved.
//
import Foundation
@testable import IndieApps
class MockConfiguration: ConfigurationProtocol {
var archiveURL: URL? = Bundle(for: MockConfiguration.self).url(forResource: "ArchiveTest", withExtension: ".zip")!
var contentLocation = ContentLocation(
localURL: Configuration.Default.rootFolderURL
.appendingPathComponent("test"),
remoteURL: Configuration.Default.remoteRepositoryURL,
branch: Configuration.Default.branch
)
}
| 31.117647 | 118 | 0.727788 |
293d75fa0d37c6274d182e0dcba3100eac3ebd19 | 1,274 | //
// HideRowSeparatorModifier.swift
// Rando
//
// Created by Mathieu Vandeginste on 26/02/2021.
// Copyright © 2021 Mathieu Vandeginste. All rights reserved.
//
import SwiftUI
struct HideRowSeparatorModifier: ViewModifier {
static let defaultListRowHeight: CGFloat = 44
var insets: EdgeInsets
var background: Color
init(insets: EdgeInsets, background: Color) {
self.insets = insets
var alpha: CGFloat = 0
UIColor(background).getWhite(nil, alpha: &alpha)
assert(alpha == 1, "Setting background to a non-opaque color will result in separators remaining visible.")
self.background = background
}
func body(content: Content) -> some View {
content
.padding(insets)
.frame(
minWidth: 0, maxWidth: .infinity,
minHeight: Self.defaultListRowHeight,
alignment: .leading
)
.listRowInsets(EdgeInsets())
.background(background)
}
}
extension EdgeInsets {
static let defaultListRowInsets = Self(top: 0, leading: 16, bottom: 0, trailing: 16)
}
extension View {
func hideRowSeparator(
insets: EdgeInsets = .defaultListRowInsets,
background: Color = .white
) -> some View {
modifier(HideRowSeparatorModifier(
insets: insets,
background: background
))
}
}
| 27.106383 | 111 | 0.688383 |
5b3124afe36f6ceca03a2ca8e6738fff8a0e37ec | 840 | //
// JIRAOptionCell.swift
// JIRAMobileKit
//
// Created by Will Powell on 11/10/2017.
//
import Foundation
class JIRAOptionCell:JIRACell{
override func setup(){
self.accessoryType = .disclosureIndicator
self.detailTextLabel?.textColor = JIRA.MainColor
}
override func applyData(data:[String:Any]){
if let field = field, let identifier = field.identifier {
if let element = data[identifier] as? DisplayClass {
self.detailTextLabel?.text = element.label
}else if let elements = data[identifier] as? [DisplayClass] {
let strs = elements.compactMap({ (element) -> String? in
return element.label
})
self.detailTextLabel?.text = strs.joined(separator: ", ")
}
}
}
}
| 30 | 73 | 0.589286 |
d6d54c263f427c8c251ceef7663323968d4be9dc | 2,553 | //
// BarcodeDetectionViewController.swift
// VerIDIDCapture
//
// Created by Jakub Dolejs on 02/01/2018.
// Copyright © 2018 Applied Recognition, Inc. All rights reserved.
//
import UIKit
import AVFoundation
import Vision
/// Barcode detection view controller
/// - Since: 1.4.0
public class BarcodeDetectionViewController: ObjectDetectionViewController {
/// Barcode detection view controller delegate
/// - Since: 1.4.0
@objc public weak var delegate: BarcodeDetectionViewControllerDelegate?
/// Barcode detection settings
/// - Since: 1.4.0
@objc public let settings: BarcodeDetectionSettings
/// Initializer
/// - Parameter settings: Barcode detection settings
/// - Since: 1.4.0
@objc public init(settings: BarcodeDetectionSettings) {
self.settings = settings
let bundle = Bundle(for: type(of: self))
if let cameraBundleURL = bundle.url(forResource: "IDCardCamera", withExtension: "bundle"), let cameraBundle = Bundle(url: cameraBundleURL) {
super.init(nibName: "BarcodeDetectionViewController", bundle: cameraBundle)
} else {
super.init(nibName: "BarcodeDetectionViewController", bundle: bundle)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
self.sessionHandler.torchSettings = self.settings
self.sessionHandler.barcodeDetectionSettings = self.settings
}
override func sessionHandler(_ handler: ObjectDetectionSessionHandler, didDetectBarcodes barcodes: [VNBarcodeObservation]) {
self.sessionHandler.delegate = nil
DispatchQueue.main.async {
guard self.isViewLoaded else {
return
}
self.dismiss()
self.delegate?.barcodeDetectionViewController(self, didDetectBarcodes: barcodes)
self.delegate = nil
}
}
override func shouldDetectBarcodeWithSessionHandler(_ handler: ObjectDetectionSessionHandler) -> Bool {
return true
}
@IBAction override func cancel() {
super.cancel()
self.delegateCancel()
}
public override func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
self.delegateCancel()
}
private func delegateCancel() {
self.delegate?.barcodeDetectionViewControllerDidCancel?(self)
self.delegate = nil
}
}
| 32.730769 | 148 | 0.670975 |
3a345c86055ec82de157c7e4dec507815ca891ed | 977 | //
// Project1Tests.swift
// Project1Tests
//
// Created by Keri Clowes on 3/18/16.
// Copyright © 2016 Keri Clowes. All rights reserved.
//
import XCTest
@testable import Project1
class Project1Tests: 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.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.405405 | 111 | 0.634596 |
21b4c9f913f7c94e130cf7f3bc2bc2618e5d2f1d | 379 | //
// String+Path.swift
// Filtr
//
// Created by Daniel Lozano on 6/21/16.
// Copyright © 2016 danielozano. All rights reserved.
//
import Foundation
public extension String {
public func stringByAppendingPathComponent(_ path: String) -> String {
let nsString = self as NSString
return nsString.appendingPathComponent(path) as String
}
}
| 19.947368 | 74 | 0.675462 |
ede5cff556f5f54247924eee818cef5c2605d518 | 1,017 | //
// Race+CoreDataProperties.swift
// STracker
//
// Created by Isaac Allport on 01/10/2021.
//
//
import Foundation
import CoreData
extension Race {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Race> {
return NSFetchRequest<Race>(entityName: "Race")
}
@NSManaged public var gender: Bool
@NSManaged public var relay: String?
@NSManaged public var title: String?
@NSManaged public var trackOrField: String?
@NSManaged public var participants: NSSet?
}
// MARK: Generated accessors for participants
extension Race {
@objc(addParticipantsObject:)
@NSManaged public func addToParticipants(_ value: Participant)
@objc(removeParticipantsObject:)
@NSManaged public func removeFromParticipants(_ value: Participant)
@objc(addParticipants:)
@NSManaged public func addToParticipants(_ values: NSSet)
@objc(removeParticipants:)
@NSManaged public func removeFromParticipants(_ values: NSSet)
}
extension Race : Identifiable {
}
| 21.638298 | 71 | 0.72468 |
0a6fc2976ee488e3bb4ccd6419074eb3f1d692b7 | 1,056 | //
// StringBooleanMap.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct StringBooleanMap: Codable, Hashable {
public private(set) var additionalProperties: [String: Bool] = [:]
public subscript(key: String) -> Bool? {
get {
if let value = additionalProperties[key] {
return value
}
return nil
}
set {
additionalProperties[key] = newValue
}
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: String.self)
try container.encodeMap(additionalProperties)
}
// Decodable protocol methods
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: String.self)
var nonAdditionalPropertyKeys = Set<String>()
additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys)
}
}
| 22.956522 | 106 | 0.640152 |
16d52a0ca19ab783280f3f05c6b44b58a123cf28 | 2,997 | //
// SubscriptionStore.swift
// AlpsSDK
//
// Created by Maciej Burda on 27/10/2017.
// Copyright © 2018 Matchmore SA. All rights reserved.
//
import Foundation
final public class SubscriptionStore: CRD {
var kSubscriptionFile: String {
return "kSubscriptionFile.Alps_" + id
}
typealias DataType = Subscription
internal private(set) var items: [Subscription] {
get {
return _items.withoutExpired
}
set {
_items = newValue
}
}
private var _items = [Subscription]() {
didSet {
_ = PersistenceManager.save(object: self._items.withoutExpired.map { $0.encodableSubscription }, to: kSubscriptionFile)
}
}
let id: String
internal init(id: String) {
self.id = id
self.items = PersistenceManager.read(type: [EncodableSubscription].self, from: kSubscriptionFile)?.map { $0.object }.withoutExpired ?? []
}
public func create(item: Subscription, completion: @escaping (Result<Subscription>) -> Void) {
guard let deviceId = item.deviceId else { return }
SubscriptionAPI.createSubscription(deviceId: deviceId, subscription: item) { (subscription, error) in
if let subscription = subscription, error == nil {
self.items.append(subscription)
completion(.success(subscription))
} else {
completion(.failure(error as? ErrorResponse))
}
}
}
public func find(byId: String, completion: @escaping (Subscription?) -> Void) {
completion(items.filter { $0.id ?? "" == byId }.first)
}
public func findAll(completion: @escaping ([Subscription]) -> Void) {
completion(items)
}
public func delete(item: Subscription, completion: @escaping (ErrorResponse?) -> Void) {
guard let id = item.id else { completion(ErrorResponse.missingId); return }
guard let deviceId = item.deviceId else { completion(ErrorResponse.missingId); return }
SubscriptionAPI.deleteSubscription(deviceId: deviceId, subscriptionId: id, completion: { (error) in
if error == nil {
self.items = self.items.filter { $0.id != id }
}
completion(error as? ErrorResponse)
})
}
public func deleteAll(completion: @escaping (ErrorResponse?) -> Void) {
var lastError: ErrorResponse?
let dispatchGroup = DispatchGroup()
items.forEach {
dispatchGroup.enter()
self.delete(item: $0, completion: { error in
if error != nil { lastError = error }
dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: .main) {
completion(lastError)
}
}
}
extension SubscriptionStore: DeviceDeleteDelegate {
func didDeleteDeviceWith(id: String) {
self.items = self.items.filter { $0.deviceId != id }
}
}
| 33.3 | 145 | 0.599933 |
4aba2104f2bfd81f6f361708b1cc18e2b916e551 | 24,279 | //
// StravaStyleKit.swift
// Strava
//
// Created by Brennan Stehling on 11/23/16.
// Copyright © 2016 BikeALot LLC. All rights reserved.
//
// Generated by PaintCode
// http://www.paintcodeapp.com
//
import UIKit
open class StravaStyleKit : NSObject {
//// Cache
fileprivate struct Cache {
static let logoColor: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000)
static let backgroundColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)
static let shadeColor: UIColor = UIColor(red: 0.922, green: 0.922, blue: 0.922, alpha: 1.000)
}
//// Colors
open dynamic class var logoColor: UIColor { return Cache.logoColor }
open dynamic class var backgroundColor: UIColor { return Cache.backgroundColor }
open dynamic class var shadeColor: UIColor { return Cache.shadeColor }
//// Drawing Methods
open dynamic class func drawStrava(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 460, height: 95), resizing: ResizingBehavior = .aspectFit, color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 460, height: 95), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 460, y: resizedFrame.height / 95)
//// Letters Drawing
let lettersPath = UIBezierPath()
lettersPath.move(to: CGPoint(x: 266.34, y: 41.07))
lettersPath.addCurve(to: CGPoint(x: 245.25, y: 82.68), controlPoint1: CGPoint(x: 254.92, y: 63.76), controlPoint2: CGPoint(x: 245.44, y: 82.48))
lettersPath.addCurve(to: CGPoint(x: 230.59, y: 61.66), controlPoint1: CGPoint(x: 244.91, y: 83.07), controlPoint2: CGPoint(x: 230.93, y: 62.98))
lettersPath.addCurve(to: CGPoint(x: 232.38, y: 60.04), controlPoint1: CGPoint(x: 230.49, y: 61.31), controlPoint2: CGPoint(x: 231.32, y: 60.58))
lettersPath.addCurve(to: CGPoint(x: 236.73, y: 56.96), controlPoint1: CGPoint(x: 233.44, y: 59.46), controlPoint2: CGPoint(x: 235.38, y: 58.09))
lettersPath.addCurve(to: CGPoint(x: 246.65, y: 33.3), controlPoint1: CGPoint(x: 244.04, y: 50.75), controlPoint2: CGPoint(x: 247.04, y: 43.62))
lettersPath.addCurve(to: CGPoint(x: 242.39, y: 19.03), controlPoint1: CGPoint(x: 246.41, y: 27.09), controlPoint2: CGPoint(x: 245.3, y: 23.43))
lettersPath.addCurve(to: CGPoint(x: 225.12, y: 6.75), controlPoint1: CGPoint(x: 238.38, y: 12.91), controlPoint2: CGPoint(x: 233.35, y: 9.35))
lettersPath.addLine(to: CGPoint(x: 220.58, y: 5.34))
lettersPath.addLine(to: CGPoint(x: 193.77, y: 5.14))
lettersPath.addLine(to: CGPoint(x: 167.02, y: 4.99))
lettersPath.addLine(to: CGPoint(x: 167.02, y: 47.87))
lettersPath.addLine(to: CGPoint(x: 167.02, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 180.95, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 194.93, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 194.93, y: 78.43))
lettersPath.addLine(to: CGPoint(x: 194.93, y: 66.11))
lettersPath.addLine(to: CGPoint(x: 198.27, y: 66.11))
lettersPath.addLine(to: CGPoint(x: 201.61, y: 66.11))
lettersPath.addLine(to: CGPoint(x: 209.55, y: 78.43))
lettersPath.addLine(to: CGPoint(x: 217.53, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 242.68, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 267.84, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 277.42, y: 72.27))
lettersPath.addCurve(to: CGPoint(x: 287.34, y: 54.08), controlPoint1: CGPoint(x: 282.69, y: 62.1), controlPoint2: CGPoint(x: 287.14, y: 53.93))
lettersPath.addCurve(to: CGPoint(x: 296.87, y: 72.46), controlPoint1: CGPoint(x: 287.48, y: 54.27), controlPoint2: CGPoint(x: 291.79, y: 62.54))
lettersPath.addLine(to: CGPoint(x: 306.06, y: 90.5))
lettersPath.addLine(to: CGPoint(x: 319.36, y: 90.65))
lettersPath.addLine(to: CGPoint(x: 332.67, y: 90.79))
lettersPath.addLine(to: CGPoint(x: 310.22, y: 45.72))
lettersPath.addCurve(to: CGPoint(x: 287.43, y: 0.3), controlPoint1: CGPoint(x: 297.88, y: 20.93), controlPoint2: CGPoint(x: 287.63, y: 0.5))
lettersPath.addCurve(to: CGPoint(x: 266.34, y: 41.07), controlPoint1: CGPoint(x: 287.24, y: 0.06), controlPoint2: CGPoint(x: 277.71, y: 18.44))
lettersPath.close()
lettersPath.move(to: CGPoint(x: 214.62, y: 30.07))
lettersPath.addCurve(to: CGPoint(x: 218.3, y: 36.87), controlPoint1: CGPoint(x: 217.24, y: 31.49), controlPoint2: CGPoint(x: 218.3, y: 33.45))
lettersPath.addCurve(to: CGPoint(x: 212.79, y: 45.03), controlPoint1: CGPoint(x: 218.3, y: 40.93), controlPoint2: CGPoint(x: 216.37, y: 43.81))
lettersPath.addCurve(to: CGPoint(x: 202.97, y: 45.57), controlPoint1: CGPoint(x: 211.77, y: 45.33), controlPoint2: CGPoint(x: 207.66, y: 45.57))
lettersPath.addLine(to: CGPoint(x: 194.93, y: 45.57))
lettersPath.addLine(to: CGPoint(x: 194.93, y: 37.07))
lettersPath.addLine(to: CGPoint(x: 194.93, y: 28.56))
lettersPath.addLine(to: CGPoint(x: 203.69, y: 28.75))
lettersPath.addCurve(to: CGPoint(x: 214.62, y: 30.07), controlPoint1: CGPoint(x: 211.63, y: 28.9), controlPoint2: CGPoint(x: 212.64, y: 29.05))
lettersPath.close()
lettersPath.move(to: CGPoint(x: 413.46, y: 1.77))
lettersPath.addCurve(to: CGPoint(x: 390.82, y: 46.99), controlPoint1: CGPoint(x: 412.93, y: 2.89), controlPoint2: CGPoint(x: 402.72, y: 23.23))
lettersPath.addCurve(to: CGPoint(x: 369.19, y: 90.5), controlPoint1: CGPoint(x: 378.92, y: 70.75), controlPoint2: CGPoint(x: 369.19, y: 90.31))
lettersPath.addCurve(to: CGPoint(x: 382.59, y: 90.79), controlPoint1: CGPoint(x: 369.19, y: 90.65), controlPoint2: CGPoint(x: 375.19, y: 90.79))
lettersPath.addLine(to: CGPoint(x: 395.99, y: 90.79))
lettersPath.addLine(to: CGPoint(x: 402.62, y: 77.55))
lettersPath.addCurve(to: CGPoint(x: 412.01, y: 58.97), controlPoint1: CGPoint(x: 406.25, y: 70.26), controlPoint2: CGPoint(x: 410.51, y: 61.95))
lettersPath.addLine(to: CGPoint(x: 414.81, y: 53.64))
lettersPath.addLine(to: CGPoint(x: 424.01, y: 72.22))
lettersPath.addLine(to: CGPoint(x: 433.2, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 446.69, y: 90.75))
lettersPath.addCurve(to: CGPoint(x: 460, y: 90.35), controlPoint1: CGPoint(x: 454.1, y: 90.75), controlPoint2: CGPoint(x: 460.1, y: 90.6))
lettersPath.addCurve(to: CGPoint(x: 414.57, y: 0.01), controlPoint1: CGPoint(x: 459.71, y: 89.72), controlPoint2: CGPoint(x: 414.77, y: 0.2))
lettersPath.addCurve(to: CGPoint(x: 413.46, y: 1.77), controlPoint1: CGPoint(x: 414.52, y: -0.09), controlPoint2: CGPoint(x: 413.99, y: 0.69))
lettersPath.close()
lettersPath.move(to: CGPoint(x: 38.96, y: 3.53))
lettersPath.addCurve(to: CGPoint(x: 9.6, y: 33.55), controlPoint1: CGPoint(x: 19.61, y: 5.83), controlPoint2: CGPoint(x: 8.97, y: 16.63))
lettersPath.addCurve(to: CGPoint(x: 11.44, y: 42.15), controlPoint1: CGPoint(x: 9.79, y: 38.14), controlPoint2: CGPoint(x: 9.99, y: 39.12))
lettersPath.addCurve(to: CGPoint(x: 30.35, y: 56.13), controlPoint1: CGPoint(x: 14.39, y: 48.16), controlPoint2: CGPoint(x: 20.68, y: 52.81))
lettersPath.addCurve(to: CGPoint(x: 42.25, y: 59.21), controlPoint1: CGPoint(x: 32.38, y: 56.82), controlPoint2: CGPoint(x: 37.75, y: 58.23))
lettersPath.addCurve(to: CGPoint(x: 55.36, y: 63.17), controlPoint1: CGPoint(x: 51.93, y: 61.36), controlPoint2: CGPoint(x: 53.53, y: 61.85))
lettersPath.addCurve(to: CGPoint(x: 55.65, y: 68.16), controlPoint1: CGPoint(x: 57.11, y: 64.39), controlPoint2: CGPoint(x: 57.25, y: 66.64))
lettersPath.addCurve(to: CGPoint(x: 22.03, y: 61.41), controlPoint1: CGPoint(x: 51.49, y: 72.12), controlPoint2: CGPoint(x: 32.82, y: 68.35))
lettersPath.addCurve(to: CGPoint(x: 19.27, y: 60.29), controlPoint1: CGPoint(x: 20.63, y: 60.43), controlPoint2: CGPoint(x: 19.47, y: 59.99))
lettersPath.addCurve(to: CGPoint(x: 11.87, y: 69.38), controlPoint1: CGPoint(x: 19.08, y: 60.58), controlPoint2: CGPoint(x: 15.74, y: 64.69))
lettersPath.addCurve(to: CGPoint(x: 5, y: 78.18), controlPoint1: CGPoint(x: 8, y: 74.12), controlPoint2: CGPoint(x: 4.91, y: 78.08))
lettersPath.addCurve(to: CGPoint(x: 17.53, y: 85.56), controlPoint1: CGPoint(x: 5.78, y: 78.91), controlPoint2: CGPoint(x: 14.15, y: 83.85))
lettersPath.addCurve(to: CGPoint(x: 49.03, y: 91.67), controlPoint1: CGPoint(x: 27.26, y: 90.5), controlPoint2: CGPoint(x: 35.05, y: 92.02))
lettersPath.addCurve(to: CGPoint(x: 62.86, y: 90.31), controlPoint1: CGPoint(x: 56.52, y: 91.48), controlPoint2: CGPoint(x: 59.48, y: 91.19))
lettersPath.addCurve(to: CGPoint(x: 85.26, y: 67.77), controlPoint1: CGPoint(x: 75.92, y: 86.93), controlPoint2: CGPoint(x: 83.81, y: 79.01))
lettersPath.addCurve(to: CGPoint(x: 83.42, y: 52.91), controlPoint1: CGPoint(x: 85.94, y: 62.54), controlPoint2: CGPoint(x: 85.26, y: 56.91))
lettersPath.addCurve(to: CGPoint(x: 54.73, y: 36.63), controlPoint1: CGPoint(x: 79.65, y: 44.55), controlPoint2: CGPoint(x: 73.46, y: 41.03))
lettersPath.addCurve(to: CGPoint(x: 38.82, y: 31.1), controlPoint1: CGPoint(x: 42.64, y: 33.74), controlPoint2: CGPoint(x: 40.08, y: 32.86))
lettersPath.addCurve(to: CGPoint(x: 38.29, y: 28.27), controlPoint1: CGPoint(x: 38, y: 29.98), controlPoint2: CGPoint(x: 37.85, y: 29.39))
lettersPath.addCurve(to: CGPoint(x: 64.51, y: 30.91), controlPoint1: CGPoint(x: 39.83, y: 23.82), controlPoint2: CGPoint(x: 53.09, y: 25.19))
lettersPath.addLine(to: CGPoint(x: 69.93, y: 33.64))
lettersPath.addLine(to: CGPoint(x: 76.65, y: 24.4))
lettersPath.addLine(to: CGPoint(x: 83.37, y: 15.16))
lettersPath.addLine(to: CGPoint(x: 82.17, y: 14.19))
lettersPath.addCurve(to: CGPoint(x: 70.31, y: 7.54), controlPoint1: CGPoint(x: 80.04, y: 12.47), controlPoint2: CGPoint(x: 74.09, y: 9.1))
lettersPath.addCurve(to: CGPoint(x: 38.96, y: 3.53), controlPoint1: CGPoint(x: 61.17, y: 3.72), controlPoint2: CGPoint(x: 49.66, y: 2.26))
lettersPath.close()
lettersPath.move(to: CGPoint(x: 84.2, y: 16.83))
lettersPath.addLine(to: CGPoint(x: 84.2, y: 28.66))
lettersPath.addLine(to: CGPoint(x: 96.78, y: 28.75))
lettersPath.addLine(to: CGPoint(x: 109.35, y: 28.9))
lettersPath.addLine(to: CGPoint(x: 109.45, y: 59.85))
lettersPath.addLine(to: CGPoint(x: 109.6, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 123.58, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 137.56, y: 90.75))
lettersPath.addLine(to: CGPoint(x: 137.56, y: 59.7))
lettersPath.addLine(to: CGPoint(x: 137.56, y: 28.66))
lettersPath.addLine(to: CGPoint(x: 150.23, y: 28.66))
lettersPath.addLine(to: CGPoint(x: 162.96, y: 28.66))
lettersPath.addLine(to: CGPoint(x: 162.96, y: 16.83))
lettersPath.addLine(to: CGPoint(x: 162.96, y: 5.04))
lettersPath.addLine(to: CGPoint(x: 123.58, y: 5.04))
lettersPath.addLine(to: CGPoint(x: 84.2, y: 5.04))
lettersPath.addLine(to: CGPoint(x: 84.2, y: 16.83))
lettersPath.close()
lettersPath.move(to: CGPoint(x: 305.67, y: 5.34))
lettersPath.addCurve(to: CGPoint(x: 350.95, y: 95), controlPoint1: CGPoint(x: 305.67, y: 6.22), controlPoint2: CGPoint(x: 350.66, y: 95.29))
lettersPath.addCurve(to: CGPoint(x: 395.99, y: 5.43), controlPoint1: CGPoint(x: 351.2, y: 94.66), controlPoint2: CGPoint(x: 395.51, y: 6.66))
lettersPath.addCurve(to: CGPoint(x: 382.69, y: 5.04), controlPoint1: CGPoint(x: 396.09, y: 5.24), controlPoint2: CGPoint(x: 390.09, y: 5.04))
lettersPath.addLine(to: CGPoint(x: 369.19, y: 5.04))
lettersPath.addLine(to: CGPoint(x: 360.1, y: 23.33))
lettersPath.addLine(to: CGPoint(x: 351.05, y: 41.66))
lettersPath.addLine(to: CGPoint(x: 348, y: 35.79))
lettersPath.addCurve(to: CGPoint(x: 338.67, y: 17.51), controlPoint1: CGPoint(x: 346.31, y: 32.57), controlPoint2: CGPoint(x: 342.1, y: 24.35))
lettersPath.addLine(to: CGPoint(x: 332.43, y: 5.04))
lettersPath.addLine(to: CGPoint(x: 319.07, y: 5.04))
lettersPath.addCurve(to: CGPoint(x: 305.67, y: 5.34), controlPoint1: CGPoint(x: 311.72, y: 5.04), controlPoint2: CGPoint(x: 305.67, y: 5.19))
lettersPath.close()
color1.setFill()
lettersPath.fill()
context.restoreGState()
}
open dynamic class func drawTitleLogo(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Symbol Drawing
let symbolRect = CGRect(x: 0, y: 0, width: 150, height: 30)
context.saveGState()
context.clip(to: symbolRect)
context.translateBy(x: symbolRect.minX, y: symbolRect.minY)
StravaStyleKit.drawStrava(frame: CGRect(origin: .zero, size: symbolRect.size), resizing: .stretch, color1: color1)
context.restoreGState()
}
open dynamic class func drawConnectButton(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000), color2: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Background Drawing
let backgroundPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 190, height: 30), cornerRadius: 7)
color1.setFill()
backgroundPath.fill()
//// Logo Drawing
let logoRect = CGRect(x: 99, y: 6, width: 84, height: 17)
context.saveGState()
context.clip(to: logoRect)
context.translateBy(x: logoRect.minX, y: logoRect.minY)
StravaStyleKit.drawStrava(frame: CGRect(origin: .zero, size: logoRect.size), resizing: .stretch, color1: color2)
context.restoreGState()
//// Connect Text Drawing
let connectTextRect = CGRect(x: 6, y: 6, width: 90, height: 21)
let connectTextStyle = NSMutableParagraphStyle()
connectTextStyle.alignment = .right
let connectTextFontAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: UIFont.systemFontSize)!, NSForegroundColorAttributeName: color2, NSParagraphStyleAttributeName: connectTextStyle]
"Connect with ".draw(in: connectTextRect, withAttributes: connectTextFontAttributes)
}
open dynamic class func drawLogInButton(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000), color2: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Background Drawing
let backgroundPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 174, height: 30), cornerRadius: 7)
color1.setFill()
backgroundPath.fill()
//// Logo Drawing
let logoRect = CGRect(x: 86, y: 6, width: 84, height: 17)
context.saveGState()
context.clip(to: logoRect)
context.translateBy(x: logoRect.minX, y: logoRect.minY)
StravaStyleKit.drawStrava(frame: CGRect(origin: .zero, size: logoRect.size), resizing: .stretch, color1: color2)
context.restoreGState()
//// Log In Text Drawing
let logInTextRect = CGRect(x: 7, y: 6, width: 76, height: 21)
let logInTextStyle = NSMutableParagraphStyle()
logInTextStyle.alignment = .right
let logInTextFontAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: UIFont.systemFontSize)!, NSForegroundColorAttributeName: color2, NSParagraphStyleAttributeName: logInTextStyle]
"Log in with ".draw(in: logInTextRect, withAttributes: logInTextFontAttributes)
}
open dynamic class func drawDisconnectButton(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000), color2: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Background Drawing
let backgroundPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 212, height: 30), cornerRadius: 7)
color1.setFill()
backgroundPath.fill()
//// Logo Drawing
let logoRect = CGRect(x: 121, y: 6, width: 84, height: 17)
context.saveGState()
context.clip(to: logoRect)
context.translateBy(x: logoRect.minX, y: logoRect.minY)
StravaStyleKit.drawStrava(frame: CGRect(origin: .zero, size: logoRect.size), resizing: .stretch, color1: color2)
context.restoreGState()
//// Disconnect Text Drawing
let disconnectTextRect = CGRect(x: 4, y: 5, width: 114, height: 21)
let disconnectTextStyle = NSMutableParagraphStyle()
disconnectTextStyle.alignment = .right
let disconnectTextFontAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: UIFont.systemFontSize)!, NSForegroundColorAttributeName: color2, NSParagraphStyleAttributeName: disconnectTextStyle]
"Disconnect from ".draw(in: disconnectTextRect, withAttributes: disconnectTextFontAttributes)
}
open dynamic class func drawLogOutButton(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000), color2: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Background Drawing
let backgroundPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 189, height: 30), cornerRadius: 7)
color1.setFill()
backgroundPath.fill()
//// Logo Drawing
let logoRect = CGRect(x: 99, y: 6, width: 84, height: 17)
context.saveGState()
context.clip(to: logoRect)
context.translateBy(x: logoRect.minX, y: logoRect.minY)
StravaStyleKit.drawStrava(frame: CGRect(origin: .zero, size: logoRect.size), resizing: .stretch, color1: color2)
context.restoreGState()
//// Log In Text Drawing
let logInTextRect = CGRect(x: 7, y: 6, width: 88, height: 21)
let logInTextStyle = NSMutableParagraphStyle()
logInTextStyle.alignment = .right
let logInTextFontAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: UIFont.systemFontSize)!, NSForegroundColorAttributeName: color2, NSParagraphStyleAttributeName: logInTextStyle]
"Log out from ".draw(in: logInTextRect, withAttributes: logInTextFontAttributes)
}
//// Generated Images
open dynamic class func imageOfStrava(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000)) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 460, height: 95), false, 0)
StravaStyleKit.drawStrava(color1: color1)
let imageOfStrava = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile).withRenderingMode(.alwaysTemplate)
UIGraphicsEndImageContext()
return imageOfStrava
}
open dynamic class func imageOfTitleLogo(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000)) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 150, height: 30), false, 0)
StravaStyleKit.drawTitleLogo(color1: color1)
let imageOfTitleLogo = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return imageOfTitleLogo
}
open dynamic class func imageOfConnectButton(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000), color2: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 190, height: 30), false, 0)
StravaStyleKit.drawConnectButton(color1: color1, color2: color2)
let imageOfConnectButton = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return imageOfConnectButton
}
open dynamic class func imageOfLogInButton(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000), color2: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 174, height: 30), false, 0)
StravaStyleKit.drawLogInButton(color1: color1, color2: color2)
let imageOfLogInButton = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return imageOfLogInButton
}
open dynamic class func imageOfDisconnectButton(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000), color2: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 212, height: 30), false, 0)
StravaStyleKit.drawDisconnectButton(color1: color1, color2: color2)
let imageOfDisconnectButton = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return imageOfDisconnectButton
}
open dynamic class func imageOfLogOutButton(color1: UIColor = UIColor(red: 0.969, green: 0.439, blue: 0.255, alpha: 1.000), color2: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 189, height: 30), false, 0)
StravaStyleKit.drawLogOutButton(color1: color1, color2: color2)
let imageOfLogOutButton = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return imageOfLogOutButton
}
@objc public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: CGRect, target: CGRect) -> CGRect {
if rect == target || target == CGRect.zero {
return rect
}
var scales = CGSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
| 60.245658 | 233 | 0.653981 |
292501196e0cde3e5e1e4afa88aa0b0c3babc115 | 1,794 | //
// RecommendGameView.swift
// DYZB
//
// Created by 刘金萌 on 2019/7/25.
// Copyright © 2019 刘金萌. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetMargin:CGFloat = 10
class RecommendGameView: UIView {
// MARK:- 定义数据属性
var groups:[BaseGameModel]?{
didSet{
// 3.刷新表格
collectionView.reloadData()
}
}
// MARK:- 控件属性
@IBOutlet weak var collectionView: UICollectionView!
// MARK:- 系统回调
override func awakeFromNib() {
super.awakeFromNib()
// 设置该控件不随着父控件的拉伸而拉伸
autoresizingMask = UIView.AutoresizingMask()
// 注册cell
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
// 给collectionView添加内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin)
}
}
// MARK:- 提供快速创建的类方法
extension RecommendGameView{
class func recommendGameView()->RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView
}
}
// MARK:- 遵守UIcollectionView的数据源协议
extension RecommendGameView:UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = groups![indexPath.item]
return cell
}
}
| 28.935484 | 126 | 0.679487 |
20bc172785c7b71b5f046b6c7f66e8c5e0544362 | 664 | //
// TeacherCell.swift
// MyApp
//
// Created by Van Le H. on 11/27/18.
// Copyright © 2018 Asian Tech Co., Ltd. All rights reserved.
//
import UIKit
final class TeacherCell: UITableViewCell {
// MARK: - Outlets
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
var viewModel: TeacherCellViewModel? {
didSet {
updateUI()
}
}
override func layoutSubviews() {
super.layoutSubviews()
avatarImageView.circle()
}
func updateUI() {
guard let viewModel = viewModel else { return }
avatarImageView.setImage(path: viewModel.avatarUrl)
nameLabel.text = viewModel.name
}
}
| 19.529412 | 63 | 0.676205 |
624ae41d0fafe792907d979ae4dfd90f8ccc17dc | 4,378 | //
// BreakfastVC.swift
// DemoVision
//
// Created by Tam Nguyen M. on 12/20/18.
// Copyright © 2018 Tam Nguyen M. All rights reserved.
//
import UIKit
import Vision
import AVFoundation
final class BreakfastDetectVC: VisionBaseVC {
// MARK: - Properties
private let label = UILabel()
private var requests = [VNRequest]()
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
guard #available(iOS 12.0, *) else {
backToPreviousScreen()
return
}
configLabel()
configImagesRequest()
startCaptureSession()
}
// MARK: - Config request handler
override func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
let requestHandler = VNSequenceRequestHandler()
do {
try requestHandler.perform(requests,
on: pixelBuffer,
orientation: exifOrientation)
} catch {
print(error)
}
}
}
private extension BreakfastDetectVC {
/// Config label
private func configLabel() {
label.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.7)
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
label.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
label.layoutIfNeeded()
}
/// Config text rectangles request
@available(iOS 12.0, *)
func configImagesRequest() {
guard let model = try? VNCoreMLModel(for: ObjectDetector().model) else { return }
let request = VNCoreMLRequest(model: model) { [weak self] (request, error) in
guard let this = self else { return }
DispatchQueue.main.async {
if let results = request.results {
this.drawDectectResults(results)
}
}
}
self.requests = [request]
}
}
// MARK: - Handle draw rectangles
private extension BreakfastDetectVC {
@available(iOS 12.0, *)
func drawDectectResults(_ results: [Any]) {
let observations = results.map({ $0 as? VNRecognizedObjectObservation }).compactMap({ $0 })
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
detectionLayer.sublayers = nil
var detectedObjects = ""
for observation in observations {
if let topLabel = observation.labels.first {
highlightBox(observation.boundingBox)
detectedObjects += "\(topLabel.identifier), \(topLabel.confidence)\n"
print("\(topLabel.identifier)\(topLabel.confidence)")
}
}
label.text = detectedObjects
updateLayerGeometry()
CATransaction.commit()
}
func highlightBox(_ rect: CGRect) {
let objectBound: CGRect
if exifOrientation == .up {
objectBound = VNImageRectForNormalizedRect(rect,
Int(bufferSize.width),
Int(bufferSize.height))
} else {
objectBound = VNImageRectForNormalizedRect(rect,
Int(bufferSize.height),
Int(bufferSize.width))
}
let outline = createRoundedRectLayer(objectBound)
detectionLayer.addSublayer(outline)
}
func createRoundedRectLayer(_ bounds: CGRect) -> CALayer {
let layer = CALayer()
layer.bounds = bounds
layer.position = CGPoint(x: bounds.midX,
y: bounds.midY)
layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(),
components: [1.0, 1.0, 0.2, 0.4])
layer.cornerRadius = 5
return layer
}
}
| 33.937984 | 138 | 0.582686 |
d9de26000b1b1c57645cf8a1067b5d9dad72dbf9 | 268 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func e<T {
{
}
enum e {
func a
func a<T where f = compose
{
{
}
{
}
}
protocol a
var f = a
class a
| 13.4 | 87 | 0.69403 |
093421eca7e7560b9f44be44c718ed19eca44a7d | 10,047 | //
// ViewController.swift
// Slide Cards
//
// Created by Gokul Nair on 20/06/20.
// Copyright © 2020 Gokul Nair. All rights reserved.
//
import UIKit
import CardSlider
struct Item: CardSliderItem {
var image: UIImage
var rating: Int?
var title: String
var subtitle: String?
var description: String?
}
class slideCards: UIViewController , CardSliderDataSource{
@IBOutlet var presentButoon: UIButton!
var data = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
presentButoon.setTitleColor(#colorLiteral(red: 0.01680417731, green: 0.1983509958, blue: 1, alpha: 1), for: .normal)
data.append(Item(image: UIImage(imageLiteralResourceName: "logo"),
rating: nil,
title: "Avengers",
subtitle: "The Team Of Superheros",
description: "The Avengers began as a group of extraordinary individuals who were assembled to defeat Loki and his Chitauri army in New York City. Since then, the team has expanded its roster and faced a host of new threats, while dealing with their own turmoil."))
data.append(Item(image: UIImage(imageLiteralResourceName: "im"),
rating: 5,
title: "IRON MAN",
subtitle: "Love You 3000",
description: "Inventor Tony Stark applies his genius for high-tech solutions to problems as Iron Man, the armored Avenger"))
data.append(Item(image: UIImage(imageLiteralResourceName: "ca"),
rating: 5,
title: "CAPTAIN AMERICA",
subtitle: "The Army Man",
description: "America’s World War II Super-Soldier continues his fight in the present as an Avenger and untiring sentinel of liberty."))
data.append(Item(image: UIImage(imageLiteralResourceName: "ds"),
rating: 4,
title: "DOCTOR STRANGE",
subtitle: "Time Stone",
description: "In an accident, Stephen Strange, a famous neurosurgeon, loses the ability to use his hands. He goes to visit the mysterious Ancient One to heal himself and becomes a great sorcerer under her tutelage."))
data.append(Item(image: UIImage(imageLiteralResourceName: "hulk"),
rating: 4,
title: "HULK",
subtitle: "The Gamma Man",
description: "Exposed to heavy doses of gamma radiation, scientist Bruce Banner transforms into the mean, green rage machine called the Hulk."))
data.append(Item(image: UIImage(imageLiteralResourceName: "bw"),
rating: 4,
title: "BLACK WIDOW",
subtitle: "Natasha",
description: "Trusted by some and feared by most, the Black Widow strives to make up for the bad she had done in the past by helping the world, even if that means getting her hands dirty in the process."))
data.append(Item(image: UIImage(imageLiteralResourceName: "thor"),
rating: 4,
title: "Thor",
subtitle: "King Of Asgard",
description: "Thor Odinson wields the power of the ancient Asgardians to fight evil throughout the Nine Realms and beyond."))
data.append(Item(image: UIImage(imageLiteralResourceName: "vision"),
rating: 4,
title: "VISION",
subtitle: "Mind Stone",
description: "A fully unique being, Vision came about thanks to a combination of Wakandan Vibranium, Asgardian lightning, an Infinity Stone, and more."))
data.append(Item(image: UIImage(imageLiteralResourceName: "he"),
rating: 4,
title: "HAWKEYE",
subtitle: "The Family Man ",
description: "An expert marksman and fighter, Clint Barton puts his talents to good use by working for S.H.I.E.L.D. as a special agent. The archer known as Hawkeye also boasts a strong moral compass that at times leads him astray from his direct orders."))
data.append(Item(image: UIImage(imageLiteralResourceName: "f"),
rating: 4,
title: "FALCON",
subtitle: nil,
description: "When Captain America asked Air Force Veteran Sam Wilson for help, Wilson immediately agreed. He donned the flight suit he’d used in combat to become the Falcon, setting him on a path towards becoming an Avenger."))
data.append(Item(image: UIImage(imageLiteralResourceName: "wm"),
rating: 4,
title: "SCARLET WITCH",
subtitle: "Manipulator",
description: "Notably powerful, Wanda Maximoff has fought both against and with the Avengers, attempting to hone her abilities and do what she believes is right to help the world."))
data.append(Item(image: UIImage(imageLiteralResourceName: "am"),
rating: 4,
title: "ANT MAN",
subtitle: "Ant King",
description: "Ex-con Scott Lang uses high-tech equipment to shrink down to insect-size and fight injustice as Ant-Man."))
data.append(Item(image: UIImage(imageLiteralResourceName: "w"),
rating: 3,
title: "WASP",
subtitle: nil,
description: "Wasp is a fictional superhero appearing in American comic books published by Marvel Comics. Created by Stan Lee, Ernie Hart, and Jack Kirby, the character first appeared in Tales to Astonish "))
data.append(Item(image: UIImage(imageLiteralResourceName: "bp"),
rating: 4,
title: "BLACK PANTHER",
subtitle: "King Of Wakanda",
description: "As the king of the African nation of Wakanda, T’Challa protects his people as the latest in a legacy line of Black Panther warriors."))
data.append(Item(image: UIImage(imageLiteralResourceName: "s"),
rating: 4,
title: "SPIDERMAN",
subtitle: "Spidey",
description: "With amazing spider-like abilities, teenage science whiz Peter Parker fights crime and dreams of becoming an Avenger as Spider-Man."))
data.append(Item(image: UIImage(imageLiteralResourceName: "wm"),
rating: 3,
title: "WAR MACHINE",
subtitle: nil,
description: "Air Force Lieutenant Colonel James “Rhodey” Rhodes exudes loyalty and courage, whether flying a plane or piloting the War Machine armor."))
data.append(Item(image: UIImage(imageLiteralResourceName: "cm"),
rating: 3,
title: "CAPTAIN MARVEL",
subtitle: "Marvel Of Galexy",
description: "Amidst a mission, Vers, a Kree warrior, gets separated from her team and is stranded on Earth. However, her life takes an unusual turn after she teams up with Fury, a S.H.I.E.L.D. agent."))
data.append(Item(image: UIImage(imageLiteralResourceName: "thanos"),
rating: 5,
title: "Most powerful eternal of Titan",
subtitle: "The Team Of Superheros",
description: "Thanos is a fictional supervillain appearing in American comic books published by Marvel Comics. The character was created by writer-artist Jim Starlin, and made his first appearance in The Invincible Iron Man "))
data.append(Item(image: UIImage(imageLiteralResourceName: "l"),
rating: 4,
title: "LOKI",
subtitle: "Son of King Odin",
description: "Loki is a fictional character appearing in American comic books published by Marvel Comics. Created by writer Stan Lee, scripter Larry Lieber and penciller Jack Kirby, a version of the character first appeared in Venus. The modern-day incarnation of Loki first appeared in Journey into Mystery."))
}
@IBAction func presentSlider(){
let vc = CardSliderViewController.with(dataSource: self)//Here view controller is the one which we got from pod file , dont get confused between the controller on which you are working and this one(cardSliderViewController)
vc.title = "Avengers"
vc.modalPresentationStyle = .fullScreen
present(vc,animated: true)
}
func item(for index: Int) -> CardSliderItem {
return data[index]
}
func numberOfItems() -> Int {
return data.count
}
}
| 60.161677 | 343 | 0.53618 |
20abc319347a171ba17e778dbc6ce05ec60e32d8 | 3,637 | import Foundation
@testable import KsApi
@testable import Library
import Prelude
import ReactiveExtensions_TestHelpers
import ReactiveSwift
import XCTest
final class ManagePledgeSummaryViewModelTests: TestCase {
private let vm = ManagePledgeSummaryViewModel()
private let backerImagePlaceholderImageName = TestObserver<String, Never>()
private let backerImageURL = TestObserver<URL, Never>()
private let backerNameLabelHidden = TestObserver<Bool, Never>()
private let backerNameText = TestObserver<String, Never>()
private let backerNumberText = TestObserver<String, Never>()
private let backingDateText = TestObserver<String, Never>()
private let circleAvatarViewHidden = TestObserver<Bool, Never>()
private let totalAmountText = TestObserver<String, Never>()
override func setUp() {
super.setUp()
self.vm.outputs.backerImageURLAndPlaceholderImageName.map(second)
.observe(self.backerImagePlaceholderImageName.observer)
self.vm.outputs.backerImageURLAndPlaceholderImageName.map(first).observe(self.backerImageURL.observer)
self.vm.outputs.backerNameLabelHidden.observe(self.backerNameLabelHidden.observer)
self.vm.outputs.backerNameText.observe(self.backerNameText.observer)
self.vm.outputs.backerNumberText.observe(self.backerNumberText.observer)
self.vm.outputs.backingDateText.observe(self.backingDateText.observer)
self.vm.outputs.circleAvatarViewHidden.observe(self.circleAvatarViewHidden.observer)
self.vm.outputs.totalAmountText.map { $0.string }
.observe(self.totalAmountText.observer)
}
func testTextOutputsEmitTheCorrectValue() {
let backing = .template
|> Backing.lens.sequence .~ 999
|> Backing.lens.pledgedAt .~ 1_568_666_243.0
|> Backing.lens.amount .~ 30.0
|> Backing.lens.shippingAmount .~ 7
let project = Project.template
|> \.personalization.isBacking .~ true
|> \.personalization.backing .~ backing
self.vm.inputs.configureWith(project)
self.vm.inputs.viewDidLoad()
self.backerNumberText.assertValue("Backer #999")
self.backingDateText.assertValue("As of September 16, 2019")
self.totalAmountText.assertValue("$30.00")
}
func testBackerUserInfo_UserIsBacker() {
let backing = Backing.template
|> Backing.lens.backerId .~ 123
let user = User.template
|> User.lens.id .~ 123
|> User.lens.name .~ "Blob"
let project = Project.template
|> Project.lens.personalization.backing .~ backing
withEnvironment(currentUser: user) {
self.vm.inputs.configureWith(project)
self.vm.inputs.viewDidLoad()
self.backerNameText.assertValues(["Blob"])
self.backerNameLabelHidden.assertValues([false])
self.backerImageURL.assertValues([URL(string: "http://www.kickstarter.com/small.jpg")!])
self.backerImagePlaceholderImageName.assertValues(["avatar--placeholder"])
self.circleAvatarViewHidden.assertValues([false])
}
}
func testBackerUserInfo_UserIsNotBacker() {
let backing = Backing.template
|> Backing.lens.backerId .~ 321
let user = User.template
|> User.lens.id .~ 123
let project = Project.template
|> Project.lens.personalization.backing .~ backing
withEnvironment(currentUser: user) {
self.vm.inputs.configureWith(project)
self.vm.inputs.viewDidLoad()
self.backerNameText.assertDidNotEmitValue()
self.backerNameLabelHidden.assertValues([true])
self.backerImageURL.assertDidNotEmitValue()
self.backerImagePlaceholderImageName.assertDidNotEmitValue()
self.circleAvatarViewHidden.assertValues([true])
}
}
}
| 37.494845 | 106 | 0.74237 |
39edb50130e741d5173e353e407eaf454b577186 | 485 | import SourceryRuntime
import Foundation
struct InjectAnnotation {
let scope: String?
let name: String?
let type: String?
init(scope: String?, name: String?, type: String?) {
self.scope = scope
self.name = name
self.type = type
}
init(attributes: [String: Any]) {
self.init(scope: attributes["scope"] as? String,
name: attributes["name"] as? String,
type: attributes["type"] as? String)
}
} | 24.25 | 56 | 0.583505 |
e6cc62d2c6ada39a4c0dd7a984860436310b76a5 | 3,403 | //
// RepositoryListActionCreator.swift
// SwiftUI-Flux
//
// Created by David S on 6/15/19.
// Copyright © 2019 David S. All rights reserved.
//
import Foundation
import Combine
final class RepositoryListActionCreator {
private let dispatcher: RepositoryListDispatcher
private let apiService: APIServiceType
private let trackerService: TrackerType
private let experimentService: ExperimentServiceType
private let onAppearSubject = PassthroughSubject<Void, Never>()
private let responseSubject = PassthroughSubject<SearchRepositoryResponse, Never>()
private let errorSubject = PassthroughSubject<APIServiceError, Never>()
private let trackingSubject = PassthroughSubject<TrackEventType, Never>()
private var cancellables: [AnyCancellable] = []
init(dispatcher: RepositoryListDispatcher = .shared,
apiService: APIServiceType = APIService(),
trackerService: TrackerType = TrackerService(),
experimentService: ExperimentServiceType = ExperimentService()) {
self.dispatcher = dispatcher
self.apiService = apiService
self.trackerService = trackerService
self.experimentService = experimentService
bindData()
bindActions()
}
func bindData() {
let request = SearchRepositoryRequest()
let responsePublisher = onAppearSubject
.flatMap { [apiService] _ in
apiService.response(from: request)
.catch { [weak self] error -> Empty<SearchRepositoryResponse, Never> in
self?.errorSubject.send(error)
return .init()
}
}
let responseStream = responsePublisher
.share()
.subscribe(responseSubject)
let trackingDataStream = trackingSubject
.sink(receiveValue: trackerService.log)
let trackingStream = onAppearSubject
.map { .listView }
.subscribe(trackingSubject)
cancellables += [
responseStream,
trackingDataStream,
trackingStream,
]
}
func bindActions() {
let responseDataStream = responseSubject
.map { $0.items }
.sink(receiveValue: { [dispatcher] in dispatcher.dispatch(.updateRepositories($0)) })
let errorDataStream = errorSubject
.map { error -> String in
switch error {
case .responseError: return "network error"
case .parseError: return "parse error"
}
}
.sink(receiveValue: { [dispatcher] in dispatcher.dispatch(.updateErrorMessage($0)) })
let errorStream = errorSubject
.map { _ in }
.sink(receiveValue: { [dispatcher] in dispatcher.dispatch(.showError) })
let experimentStream = onAppearSubject
.filter { [experimentService] _ in
experimentService.experiment(for: .showIcon)
}
.sink(receiveValue: { [dispatcher] in dispatcher.dispatch(.showIcon) })
cancellables += [
responseDataStream,
errorDataStream,
errorStream,
experimentStream,
]
}
func onAppear() {
onAppearSubject.send(())
}
}
| 33.693069 | 97 | 0.601822 |
795c063056068e50a228926767736d50d608c883 | 13,017 | //
// MainPhoneViewController.swift
// Sunlit
//
// Created by Jonathan Hays on 6/20/20.
// Copyright © 2020 Micro.blog, LLC. All rights reserved.
//
import UIKit
import Snippets
class MainPhoneViewController: UIViewController {
static var needsMentionsSwitch = false
@IBOutlet var contentView : UIView!
@IBOutlet var scrollView : UIScrollView!
@IBOutlet var tabBar : UIView!
@IBOutlet var timelineButton : TabButton!
@IBOutlet var discoverButton : TabButton!
@IBOutlet var mentionsButton : TabButton!
@IBOutlet var profileButton : TabButton!
var discoverViewController : DiscoverViewController!
var timelineViewController : TimelineViewController!
var profileViewController : MyProfileViewController!
var mentionsViewController : MentionsViewController!
var currentViewController : ContentViewController? = nil
/* ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MARK: -
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */
override func viewDidLoad() {
super.viewDidLoad()
self.setupProfileButton()
self.loadContentViews()
self.updateInterfaceForLogin()
NotificationCenter.default.addObserver(self, selector: #selector(handleCurrentUserUpdatedNotification), name: .currentUserUpdatedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleUserMentionsUpdated), name: .mentionsUpdatedNotification, object: nil)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var frame = self.scrollView.frame
frame.size.width = self.view.frame.size.width
self.scrollView.frame = frame
self.timelineViewController.view.frame = frame
frame.origin.x += frame.size.width
self.mentionsViewController.view.frame = frame
frame.origin.x += frame.size.width
self.discoverViewController.view.frame = frame
frame.origin.x += frame.size.width
self.profileViewController.view.frame = frame
let contentSize = CGSize(width: frame.size.width * 4.0, height: 0.0)
self.scrollView.contentSize = contentSize
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.reloadTabs()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if MainPhoneViewController.needsMentionsSwitch {
MainPhoneViewController.needsMentionsSwitch = false
self.onShowMentions()
}
}
func loadContentViews() {
self.addChild(self.timelineViewController)
self.addChild(self.mentionsViewController)
self.addChild(self.discoverViewController)
self.addChild(self.profileViewController)
var frame = self.scrollView.bounds
self.scrollView.addSubview(self.timelineViewController.view)
self.timelineViewController.view.frame = frame
frame.origin.x += frame.size.width
self.scrollView.addSubview(self.mentionsViewController.view)
self.mentionsViewController.view.frame = frame
frame.origin.x += frame.size.width
self.scrollView.addSubview(self.discoverViewController.view)
self.discoverViewController.view.frame = frame
frame.origin.x += frame.size.width
self.scrollView.addSubview(self.profileViewController.view)
self.profileViewController.view.frame = frame
frame.origin.x += frame.size.width
self.scrollView.isUserInteractionEnabled = true
self.scrollView.contentSize = CGSize(width: frame.origin.x, height: 0)
self.timelineButton.isSelected = true
//self.timelineButton.isEnabled = false
self.currentViewController = self.timelineViewController
self.timelineViewController.prepareToDisplay()
}
func reloadTabs() {
self.timelineViewController.tableView.reloadData()
self.discoverViewController.tableView.reloadData()
self.discoverViewController.collectionView.reloadData()
self.profileViewController.collectionView.reloadData()
self.mentionsViewController.tableView.reloadData()
}
func setupProfileButton() {
var profileImage : UIImage? = UIImage(systemName: "person.crop.circle")
var profileUsername = "Profile"
if let current = SnippetsUser.current() {
if current.userName.count < 10 {
profileUsername = "@" + current.userName
}
if let image = ImageCache.prefetch(current.avatarURL) {
profileImage = image
}
}
if let image = profileImage {
profileImage = image.uuScaleAndCropToSize(targetSize: CGSize(width: 26, height: 26)).withRenderingMode(.alwaysOriginal)
}
self.profileButton.setTitle(profileUsername, for: .normal)
self.profileButton.setImage(profileImage, for: .normal)
self.profileButton.setImage(profileImage, for: .selected)
self.profileButton.setCornerRadius(13)
let longpressGesture = UILongPressGestureRecognizer(target: self, action: #selector(onSelectBlogConfiguration))
self.profileButton.addGestureRecognizer(longpressGesture)
}
func updateInterfaceForLogin() {
if let user = SnippetsUser.current() {
// Update the user name...
DispatchQueue.main.async {
self.scrollView.isScrollEnabled = true
if user.userName.count < 10 {
self.profileButton.setTitle("@" + user.userName, for: .normal)
}
else {
self.profileButton.setTitle("Profile", for: .normal)
}
}
// Go ahead and go get the avatar for the logged in user
ImageCache.fetch(self, user.avatarURL) { (image) in
if let image = image {
let profileImage = image.uuScaleAndCropToSize(targetSize: CGSize(width: 26, height: 26)).withRenderingMode(.alwaysOriginal)
DispatchQueue.main.async {
self.profileButton.setImage(profileImage, for: .normal)
self.profileButton.setImage(profileImage, for: .selected)
self.profileButton.setCornerRadius(13)
self.view.layoutIfNeeded()
}
}
}
}
else {
self.profileButton.setImage(UIImage(systemName: "person.crop.circle"), for: .normal)
self.profileButton.setTitle("Profile", for: .normal)
self.onTabBarButtonPressed(self.timelineButton)
self.scrollView.isScrollEnabled = false
}
}
@objc func handleCurrentUserUpdatedNotification() {
self.updateInterfaceForLogin()
}
@objc func handleUserMentionsUpdated() {
let mentionCount = SunlitMentions.shared.newMentionCount()
self.mentionsButton.shouldDisplayNotificationDot = mentionCount > 0
}
@IBAction func onTabBarButtonPressed(_ button : UIButton) {
// If not logged in, show the login screen...
if button != self.discoverButton {
if SnippetsUser.current() == nil {
NotificationCenter.default.post(name: .showLoginNotification, object: nil)
self.onShowTimeline()
return
}
}
if button == self.profileButton {
self.onShowProfile()
}
if button == self.timelineButton {
self.onShowTimeline()
}
if button == self.discoverButton {
self.onShowDiscover()
}
if button == self.mentionsButton {
self.onShowMentions()
}
}
@objc func onSelectBlogConfiguration() {
Dialog(self).selectBlog()
}
func onShowTimeline() {
if self.currentViewController == self.timelineViewController {
self.timelineViewController.handleScrollToTopGesture()
return
}
var animate = false
if self.currentViewController == self.mentionsViewController {
animate = true
}
var offset = self.scrollView.contentOffset
offset.x = 0.0
self.scrollView.setContentOffset(offset, animated: animate)
self.timelineViewController.loadTimeline()
self.updateTabBar(self.scrollView)
self.updateCurrentViewController(self.scrollView)
}
func onShowMentions() {
if self.currentViewController == self.mentionsViewController {
self.mentionsViewController.handleScrollToTopGesture()
return
}
var animate = false
if self.currentViewController == self.timelineViewController ||
self.currentViewController == self.discoverViewController {
animate = true
}
var offset = self.scrollView.contentOffset
offset.x = self.scrollView.bounds.size.width * 1.0
self.scrollView.setContentOffset(offset, animated: animate)
if !animate {
self.updateTabBar(self.scrollView)
self.updateCurrentViewController(self.scrollView)
}
}
func onShowDiscover() {
if self.currentViewController == self.discoverViewController {
self.discoverViewController.handleScrollToTopGesture()
return
}
var animate = false
if self.currentViewController == self.mentionsViewController ||
self.currentViewController == self.profileViewController{
animate = true
}
var offset = self.scrollView.contentOffset
offset.x = self.scrollView.bounds.size.width * 2.0
self.scrollView.setContentOffset(offset, animated: animate)
self.updateTabBar(self.scrollView)
self.updateCurrentViewController(self.scrollView)
}
func onShowProfile() {
if self.currentViewController == self.profileViewController {
self.profileViewController.handleScrollToTopGesture()
return
}
var animate = false
if self.currentViewController == self.discoverViewController {
animate = true
}
var offset = self.scrollView.contentOffset
offset.x = self.scrollView.bounds.size.width * 3.0
self.scrollView.setContentOffset(offset, animated: animate)
self.updateTabBar(self.scrollView)
self.updateCurrentViewController(self.scrollView)
}
}
/* ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MARK: -
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */
extension MainPhoneViewController : UIScrollViewDelegate {
func updateTabBar(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x
let frameSize = scrollView.bounds.size.width
//self.timelineButton.isEnabled = true
//self.profileButton.isEnabled = true
//self.discoverButton.isEnabled = true
//self.mentionsButton.isEnabled = true
self.timelineButton.isSelected = false
self.profileButton.isSelected = false
self.discoverButton.isSelected = false
self.mentionsButton.isSelected = false
if offset < (frameSize / 2.0) {
self.timelineButton.isSelected = true
//self.timelineButton.isEnabled = false
}
else if offset < (frameSize + (frameSize / 2.0)) {
self.mentionsButton.isSelected = true
//self.mentionsButton.isEnabled = false
}
else if offset < (frameSize * 2.0 + (frameSize / 2.0)) {
self.discoverButton.isSelected = true
//self.discoverButton.isEnabled = false
}
else {
self.profileButton.isSelected = true
//self.profileButton.isEnabled = false
}
}
func updateCurrentViewController(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x
let frameSize = scrollView.bounds.size.width
let previousViewController = self.currentViewController
if offset < (frameSize / 2.0) {
self.currentViewController = self.timelineViewController
}
else if offset < (frameSize + (frameSize / 2.0)) {
self.currentViewController = self.mentionsViewController
}
else if offset < (frameSize * 2.0 + (frameSize / 2.0)) {
self.currentViewController = self.discoverViewController
}
else {
self.currentViewController = self.profileViewController
}
if !(previousViewController === self.currentViewController) {
previousViewController?.prepareToHide()
self.currentViewController?.prepareToDisplay()
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
self.updateCurrentViewController(scrollView)
self.updateCurrentViewController(self.scrollView)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.updateCurrentViewController(scrollView)
self.updateCurrentViewController(self.scrollView)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.updateTabBar(scrollView)
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
self.updateTabBar(scrollView)
self.updateCurrentViewController(self.scrollView)
}
}
| 32.95443 | 157 | 0.672659 |
1ac56604f566c83101f8205e4c4bd65bce3998e6 | 1,027 | extension OrderedMap {
@available(*, deprecated, message: "Please use init(values:uniquelyKeyedBy:).", renamed: "init(values:uniquelyKeyedBy:)")
public init<S: Sequence>(
values: S,
keyedBy extractKey: (Value) -> Key
) where S.Element == Value {
#if swift(>=4.1.3)
self.init(values: values, uniquelyKeyedBy: extractKey)
#else
try! self.init(values: values, uniquelyKeyedBy: extractKey)
#endif
}
@available(*, deprecated, message: "Please use init(values:uniquelyKeyedBy:).", renamed: "init(values:uniquelyKeyedBy:)")
public init(
values: [Value],
keyedBy keyPath: KeyPath<Value, Key>
) {
self.init(values: values, uniquelyKeyedBy: keyPath)
}
@available(*, deprecated, message: "Please use init(uniqueKeysWithValues:).", renamed: "init(uniqueKeysWithValues:)")
public init<S: Sequence>(_ elements: S) where S.Element == Element {
self.init(uniqueKeysWithValues: elements)
}
}
| 35.413793 | 125 | 0.633885 |
f95d886f02cefbedd62cd3e0c47fe3ae3c63dc71 | 4,295 | //
// ProjectsFeaturedViewController.swift
// Wclient
//
// Created by Aaron Lee on 2017/11/05.
// Copyright © 2017 Aaron Lee. All rights reserved.
//
import UIKit
final class ProjectsFeaturedViewController: UICollectionViewController {
var configurator = ProjectsFeaturedConfiguratorImplementation()
var presenter: ProjectsFeaturedPresenter!
var notificationFeedbackGenerator: UINotificationFeedbackGenerator?
override func viewDidLoad() {
super.viewDidLoad()
configurator.configure(projectsFeaturedViewController: self)
presenter.viewDidLoad()
notificationFeedbackGenerator = UINotificationFeedbackGenerator()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
presenter.router.prepare(for: segue, sender: sender)
}
// MARK: - IBAction
@IBAction func orderButtonPressed(_ sender: Any) {
}
// MARK: - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return presenter.numberOfProjects
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(for: indexPath) as ProjectCollectionViewCell
presenter.configure(cell: cell, forRow: indexPath.row)
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
presenter.didSelect(row: indexPath.row)
}
// MARK: - UIScrollViewDelegate
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollToNearestVisibleCollectionViewCell()
}
// if at end
let offsetX = scrollView.contentOffset.x
let contentWidth = scrollView.contentSize.width
if offsetX > contentWidth - scrollView.frame.size.width {
notificationFeedbackGenerator?.prepare()
presenter.didScrollViewToEnd()
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollToNearestVisibleCollectionViewCell()
}
// MARK: private
private func scrollToNearestVisibleCollectionViewCell() {
guard let collectionView = collectionView else {
return
}
let visibleCenterPositionOfScrollView = Float(collectionView.contentOffset.x + (collectionView.bounds.size.width / 2))
var closestCellIndex = -1
var closestDistance: Float = .greatestFiniteMagnitude
for i in 0..<collectionView.visibleCells.count {
let cell = collectionView.visibleCells[i]
let cellWidth = cell.bounds.size.width
let cellCenter = Float(cell.frame.origin.x + cellWidth / 2)
// Now calculate closest cell
let distance: Float = fabsf(visibleCenterPositionOfScrollView - cellCenter)
if distance < closestDistance {
closestDistance = distance
closestCellIndex = collectionView.indexPath(for: cell)!.row
presenter.didSnap(to: closestCellIndex)
}
}
if closestCellIndex != -1 {
self.collectionView!.scrollToItem(at: IndexPath(row: closestCellIndex, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
// MARK: - ProjectsFeaturedView
extension ProjectsFeaturedViewController: ProjectsFeaturedView {
func refreshProjectsView() {
presenter.didSnap(to: 0)
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
func displayProjectsRetrievalError(title: String, message: String) {
presentAlert(withTitle: title, message: message)
notificationFeedbackGenerator?.notificationOccurred(.error)
}
func updateBackground(hexColour: String) {
UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseInOut], animations: {
self.collectionView?.backgroundColor = UIColor(hex: hexColour)
})
}
}
| 34.918699 | 138 | 0.668219 |
222b9743765b09ac0c4400785f9406cc9165b865 | 8,665 | /*
Copyright (c) 2016 Matthijs Hollemans and contributors
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.
*/
internal struct Heap<T> {
/** The array that stores the heap's nodes. */
var nodes = [T]()
/**
* Determines how to compare two nodes in the heap.
* Use '>' for a max-heap or '<' for a min-heap,
* or provide a comparing method if the heap is made
* of custom elements, for example tuples.
*/
private var orderCriteria: (T, T) -> Bool
/**
* Creates an empty heap.
* The sort function determines whether this is a min-heap or max-heap.
* For comparable data types, > makes a max-heap, < makes a min-heap.
*/
init(sort: @escaping (T, T) -> Bool) {
self.orderCriteria = sort
}
/**
* Creates a heap from an array. The order of the array does not matter;
* the elements are inserted into the heap in the order determined by the
* sort function. For comparable data types, '>' makes a max-heap,
* '<' makes a min-heap.
*/
init(array: [T], sort: @escaping (T, T) -> Bool) {
self.orderCriteria = sort
configureHeap(from: array)
}
/**
* Configures the max-heap or min-heap from an array, in a bottom-up manner.
* Performance: This runs pretty much in O(n).
*/
private mutating func configureHeap(from array: [T]) {
nodes = array
for i in stride(from: (nodes.count/2-1), through: 0, by: -1) {
shiftDown(i)
}
}
var isEmpty: Bool {
return nodes.isEmpty
}
var count: Int {
return nodes.count
}
/**
* Returns the index of the parent of the element at index i.
* The element at index 0 is the root of the tree and has no parent.
*/
@inline(__always) internal func parentIndex(ofIndex i: Int) -> Int {
return (i - 1) / 2
}
/**
* Returns the index of the left child of the element at index i.
* Note that this index can be greater than the heap size, in which case
* there is no left child.
*/
@inline(__always) internal func leftChildIndex(ofIndex i: Int) -> Int {
return 2*i + 1
}
/**
* Returns the index of the right child of the element at index i.
* Note that this index can be greater than the heap size, in which case
* there is no right child.
*/
@inline(__always) internal func rightChildIndex(ofIndex i: Int) -> Int {
return 2*i + 2
}
/**
* Returns the maximum value in the heap (for a max-heap) or the minimum
* value (for a min-heap).
*/
func peek() -> T? {
return nodes.first
}
/**
* Adds a new value to the heap. This reorders the heap so that the max-heap
* or min-heap property still holds. Performance: O(log n).
*/
mutating func insert(_ value: T) {
nodes.append(value)
shiftUp(nodes.count - 1)
}
/**
* Adds a sequence of values to the heap. This reorders the heap so that
* the max-heap or min-heap property still holds. Performance: O(log n).
*/
mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T {
for value in sequence {
insert(value)
}
}
/**
* Allows you to change an element. This reorders the heap so that
* the max-heap or min-heap property still holds.
*/
mutating func replace(index i: Int, value: T) {
guard i < nodes.count else { return }
remove(at: i)
insert(value)
}
/**
* Removes the root node from the heap. For a max-heap, this is the maximum
* value; for a min-heap it is the minimum value. Performance: O(log n).
*/
@discardableResult mutating func remove() -> T? {
guard !nodes.isEmpty else { return nil }
if nodes.count == 1 {
return nodes.removeLast()
}
// Use the last node to replace the first one, then fix the heap by
// shifting this new first node into its proper position.
let value = nodes[0]
nodes[0] = nodes.removeLast()
shiftDown(0)
return value
}
/**
* Removes an arbitrary node from the heap. Performance: O(log n).
* Note that you need to know the node's index.
*/
@discardableResult mutating func remove(at index: Int) -> T? {
guard index < nodes.count else { return nil }
let size = nodes.count - 1
if index != size {
nodes.swapAt(index, size)
shiftDown(from: index, until: size)
shiftUp(index)
}
return nodes.removeLast()
}
/**
* Takes a child node and looks at its parents; if a parent is not larger
* (max-heap) or not smaller (min-heap) than the child, we exchange them.
*/
internal mutating func shiftUp(_ index: Int) {
var childIndex = index
let child = nodes[childIndex]
var parentIndex = self.parentIndex(ofIndex: childIndex)
while childIndex > 0 && orderCriteria(child, nodes[parentIndex]) {
nodes[childIndex] = nodes[parentIndex]
childIndex = parentIndex
parentIndex = self.parentIndex(ofIndex: childIndex)
}
nodes[childIndex] = child
}
/**
* Looks at a parent node and makes sure it is still larger (max-heap) or
* smaller (min-heap) than its children.
*/
internal mutating func shiftDown(from index: Int, until endIndex: Int) {
let leftChildIndex = self.leftChildIndex(ofIndex: index)
let rightChildIndex = leftChildIndex + 1
// Figure out which comes first if we order them by the sort function:
// the parent, the left child, or the right child. If the parent comes
// first, we're done. If not, that element is out-of-place and we make
// it "float down" the tree until the heap property is restored.
var first = index
if leftChildIndex < endIndex && orderCriteria(nodes[leftChildIndex], nodes[first]) {
first = leftChildIndex
}
if rightChildIndex < endIndex && orderCriteria(nodes[rightChildIndex], nodes[first]) {
first = rightChildIndex
}
if first == index { return }
nodes.swapAt(index, first)
shiftDown(from: first, until: endIndex)
}
internal mutating func shiftDown(_ index: Int) {
shiftDown(from: index, until: nodes.count)
}
}
// MARK: - Searching
extension Heap where T: Equatable {
/** Get the index of a node in the heap. Performance: O(n). */
func index(of node: T) -> Int? {
return nodes.firstIndex(where: { $0 == node })
}
/** Removes the first occurrence of a node from the heap. Performance: O(n log n). */
@discardableResult mutating func remove(node: T) -> T? {
if let index = index(of: node) {
return remove(at: index)
}
return nil
}
}
// MARK: - Sorting
extension Heap {
mutating func sort() -> [T] {
for i in stride(from: (nodes.count - 1), through: 1, by: -1) {
nodes.swapAt(0, i)
shiftDown(from: 0, until: i)
}
return nodes
}
}
/*
Sorts an array using heap.
Heapsort can be performed in-place, but it is not a stable sort.
*/
func heapsort<T>(_ a: [T], _ sort: @escaping (T, T) -> Bool) -> [T] {
let reverseOrder = { i1, i2 in sort(i2, i1) }
var h = Heap(array: a, sort: reverseOrder)
return h.sort()
}
| 33.326923 | 94 | 0.606809 |
67e83d5b5d3b172a66294134e03868d48611031f | 554 | //
// HelpSlide.swift
// Konnex
//
// Created by Sean Simmons on 2021-08-26.
// Copyright © 2021 Unit Circle Inc. All rights reserved.
//
import UIKit
class HelpSlide: UIView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelDescription: UILabel!
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 22.16 | 78 | 0.669675 |
50b60273450090d64554b536a29cad0f86adc40f | 200 | //
// APIError.swift
// OpenWeather
//
// Created by mani on 2021-06-13.
//
import Foundation
enum APIError: Error {
case parsing(description: String)
case network(description: String)
}
| 14.285714 | 37 | 0.68 |
29e235da9e267b0959c3b105e9566c1640c2d52f | 11,822 | //
// GroupProfileController.swift
// InstagramClone
//
// Created by Andrei Homentcovschi on 1/17/20.
// Copyright © 2020 Andrei Homentcovschi. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
// This will be the basis of group profile controller
class FollowPageController: UICollectionViewController, loadMoreFollowersCellDelegate, UserFollowCellDelegate {
var user: User? {
didSet {
configureFollowing()
}
}
var following = [User]()
var followers = [User]()
var oldestRetrievedDate = 10000000000000.0
private var header: FollowPageHeader?
private let alertController: UIAlertController = {
let ac = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
return ac
}()
// private var isFinishedPaging = false
// private var pagingCount: Int = 4
//MARK: First follow popup
private let firstFollowLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.black
label.layer.zPosition = 4
label.numberOfLines = 0
label.isHidden = true
label.textAlignment = .center
let attributedText = NSMutableAttributedString(string: "Auto Group Follow", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)])
attributedText.append(NSMutableAttributedString(string: "\n\nWhen you follow someone\nposts from their public groups\nwill appear in the following feed.", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]))
label.attributedText = attributedText
return label
}()
private lazy var firstFollowButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(closeFirstFollowPopup), for: .touchUpInside)
button.layer.zPosition = 4;
button.isHidden = true
button.backgroundColor = UIColor(white: 0.9, alpha: 1)
button.setTitleColor(.black, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.setTitle("Got it", for: .normal)
return button
}()
private let firstFollowBackground: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 1, alpha: 1)
// view.layer.borderWidth = 1
// view.layer.borderColor = UIColor.darkGray.cgColor
view.layer.zPosition = 3
view.isUserInteractionEnabled = false
view.layer.cornerRadius = 10
view.isHidden = true
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = 1
view.layer.shadowOffset = .zero
view.layer.shadowRadius = 150
return view
}()
var isFollowerView: Bool? {
didSet {
configureHeader()
}
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .light
}
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem?.tintColor = .black
navigationItem.title = "Users"
self.navigationController?.navigationBar.shadowImage = UIColor.white.as1ptImage()
collectionView?.backgroundColor = .white
collectionView?.alwaysBounceVertical = true
collectionView?.keyboardDismissMode = .onDrag
collectionView?.register(FollowPageCell.self, forCellWithReuseIdentifier: FollowPageCell.cellId)
collectionView?.register(LoadMoreFollowersCell.self, forCellWithReuseIdentifier: LoadMoreFollowersCell.cellId)
collectionView?.register(FollowPageHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FollowPageHeader.headerId)
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
collectionView?.refreshControl = refreshControl
firstFollowLabel.frame = CGRect(x: 0, y: UIScreen.main.bounds.height/3-80, width: UIScreen.main.bounds.width, height: 120)
self.view.insertSubview(firstFollowLabel, at: 4)
firstFollowBackground.frame = CGRect(x: UIScreen.main.bounds.width/2-140, y: UIScreen.main.bounds.height/3-120, width: 280, height: 270)
self.view.insertSubview(firstFollowBackground, at: 3)
firstFollowButton.frame = CGRect(x: UIScreen.main.bounds.width/2-50, y: UIScreen.main.bounds.height/3+60, width: 100, height: 50)
firstFollowButton.layer.cornerRadius = 18
self.view.insertSubview(firstFollowButton, at: 4)
}
private func configureFollowing() {
guard let user = user else { return }
self.navigationItem.title = user.username
handleRefresh()
}
private func configureHeader() {
header?.isFollowerView = isFollowerView!
}
@objc private func handleRefresh() {
guard let user_id = user?.uid else { return }
followers.removeAll()
following.removeAll()
oldestRetrievedDate = 10000000000000.0
self.collectionView?.refreshControl?.beginRefreshing()
Database.database().fetchUserFollowing(withUID: user_id, completion: { (following_users) in
self.following = following_users
self.collectionView?.reloadData()
self.collectionView?.refreshControl?.endRefreshing()
}) { (err) in
self.collectionView?.refreshControl?.endRefreshing()
}
fetchMoreFollowers()
}
func handleLoadMoreFollowers() {
fetchMoreFollowers()
}
private func fetchMoreFollowers() {
guard let user_id = user?.uid else { return }
collectionView?.refreshControl?.beginRefreshing()
Database.database().fetchMoreFollowers(withUID: user_id, endAt: oldestRetrievedDate, completion: { (follower_users, lastFollow) in
self.followers += follower_users
if follower_users.last == nil {
self.collectionView?.refreshControl?.endRefreshing()
return
}
self.oldestRetrievedDate = lastFollow
print("setting oldest date as: ", self.oldestRetrievedDate)
self.collectionView?.reloadData()
self.collectionView?.refreshControl?.endRefreshing()
}) { (_) in
self.collectionView?.refreshControl?.endRefreshing()
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let userProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout())
if isFollowerView! {
if indexPath.item < followers.count {
userProfileController.user = followers[indexPath.item]
navigationController?.pushViewController(userProfileController, animated: true)
}
}
else{
userProfileController.user = following[indexPath.item]
navigationController?.pushViewController(userProfileController, animated: true)
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if isFollowerView! {
if followers.count > 0 {
return followers.count + 1
}
return 0
}
return following.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if isFollowerView! {
if indexPath.row < followers.count {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FollowPageCell.cellId, for: indexPath) as! FollowPageCell
cell.user = followers[indexPath.item]
cell.delegate = self
return cell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LoadMoreFollowersCell.cellId, for: indexPath) as! LoadMoreFollowersCell
cell.delegate = self
cell.index = indexPath.row // set tag as the row to decide whether or not the load more label is visible
cell.user = user
return cell
}
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FollowPageCell.cellId, for: indexPath) as! FollowPageCell
cell.delegate = self
if indexPath.item < following.count {
cell.user = following[indexPath.item]
}
return cell
}
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if header == nil {
header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FollowPageHeader.headerId, for: indexPath) as? FollowPageHeader
header?.delegate = self
header?.isFollowerView = isFollowerView!
}
return header!
}
func didFollowFirstUser() {
self.showFirstFollowPopup()
}
@objc func showFirstFollowPopup() {
self.firstFollowLabel.isHidden = false
self.firstFollowBackground.isHidden = false
self.firstFollowButton.isHidden = false
self.firstFollowLabel.alpha = 0
self.firstFollowBackground.alpha = 0
self.firstFollowButton.alpha = 0
UIView.animate(withDuration: 0.5) {
self.collectionView.alpha = 0
self.firstFollowLabel.alpha = 1
self.firstFollowBackground.alpha = 1
self.firstFollowButton.alpha = 1
}
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { timer in
self.collectionView.isHidden = true
}
}
@objc func closeFirstFollowPopup() {
self.firstFollowLabel.alpha = 1
self.firstFollowBackground.alpha = 1
self.firstFollowButton.alpha = 1
self.collectionView.isHidden = false
self.collectionView.alpha = 0
UIView.animate(withDuration: 0.5) {
self.collectionView.alpha = 1
self.firstFollowLabel.alpha = 0
self.firstFollowBackground.alpha = 0
self.firstFollowButton.alpha = 0
}
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { timer in
self.firstFollowLabel.isHidden = true
self.firstFollowBackground.isHidden = true
self.firstFollowButton.isHidden = true
}
}
}
extension FollowPageController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 66)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: view.frame.width, height: 44)
}
}
//MARK: - FollowPageHeaderDelegate
extension FollowPageController: FollowPageHeaderDelegate {
func didChangeToFollowersView() {
isFollowerView = true
collectionView?.reloadData()
}
func didChangeToFollowingView() {
isFollowerView = false
collectionView?.reloadData()
}
}
| 38.760656 | 238 | 0.657672 |
bf7bae93c9eab2e1885a9be878c45037bf4098d4 | 1,936 | import UIKit
extension UIColor {
convenience init(r:UInt32 ,g:UInt32 , b:UInt32 , a:CGFloat = 1.0) {
self.init(red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: a)
}
class var random: UIColor {
return UIColor(r: arc4random_uniform(256),
g: arc4random_uniform(256),
b: arc4random_uniform(256))
}
func image() -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(self.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
class func hex(hexString: String) -> UIColor {
var cString: String = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
if cString.count < 6 { return UIColor.black }
let index = cString.index(cString.endIndex, offsetBy: -6)
let subString = cString[index...]
if cString.hasPrefix("0X") { cString = String(subString) }
if cString.hasPrefix("#") { cString = String(subString) }
if cString.count != 6 { return UIColor.black }
var range: NSRange = NSMakeRange(0, 2)
let rString = (cString as NSString).substring(with: range)
range.location = 2
let gString = (cString as NSString).substring(with: range)
range.location = 4
let bString = (cString as NSString).substring(with: range)
var r: UInt32 = 0x0
var g: UInt32 = 0x0
var b: UInt32 = 0x0
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(r: r, g: g, b: b)
}
}
| 32.813559 | 87 | 0.592975 |
1cd5eba65671064079d4cb94f14316415818435a | 1,305 | //
// JsonConvert.swift
// learning_swift
//
// Created by lxh on 2021/9/29.
//
import Foundation
protocol Jsonable: Codable {
/// 从数据中转换成 struct
static func json(_ data: Data?) -> Self?
static func json(_ str: String?) -> Self?
/// struct 转换为 字典
var dict:[String: Any] { get }
}
extension Jsonable {
static func json(_ data: Data?) -> Self? {
guard let data = data else {
print("json error: data == nil")
return nil
}
do {
let obj = try JSONDecoder().decode(Self.self, from: data)
return obj
} catch {
print("json error:", error)
return nil
}
}
static func json(_ str: String?) -> Self? {
guard let str = str else {
print("json error: str == nil")
return nil
}
let data = str.data(using: .utf8)
guard let data = data else {
print("json error: data == nil")
return nil
}
do {
let obj = try JSONDecoder().decode(Self.self, from: data)
return obj
} catch {
print("json error:", error)
return nil
}
}
var dict:[String: Any] {
get {
let data = try? JSONEncoder().encode(self)
if data == nil {
return Dictionary()
}
let dict = try? JSONSerialization.jsonObject(with: data!, options: .fragmentsAllowed)
if dict == nil {
return Dictionary()
}
return dict as! [String: Any]
}
}
}
| 17.876712 | 88 | 0.60613 |
bf774b061acb2519c76e3c8cf60cd9f395783706 | 267 | //
// MyTapGuesture.swift
// MINTEL_LiveChat
//
// Created by Autthapon Sukjaroen on 13/8/2563 BE.
//
import Foundation
class MyTapGuesture : UITapGestureRecognizer {
var message: MyMessage?
var cell : UITableViewCell?
var menu: [String:Any] = [:]
}
| 17.8 | 51 | 0.689139 |
f8a23bff3818561cf31e39f0b133c4998d71740c | 1,741 | @testable import IBLinterKit
import XCTest
class ConfigLintablePathsTests: XCTestCase {
let fixture = Fixture()
func testIncluded() {
let config = Config(
disabledRules: [], enabledRules: [],
excluded: ["Level1_1"], included: [],
customModuleRule: [], baseClassRule: [], reporter: ""
)
let projectPath = fixture.path("Resources/Utils/Glob/ProjectMock")
let lintablePaths = config.lintablePaths(workDirectory: projectPath, fileExtension: "xib")
XCTAssertEqual(
lintablePaths.map { $0.path },
[projectPath.appendingPathComponent("Level1_2/Level1_2.xib").path]
)
}
func testExcluded() {
let config = Config(
disabledRules: [], enabledRules: [],
excluded: [], included: ["Level1_2"],
customModuleRule: [], baseClassRule: [], reporter: ""
)
let projectPath = fixture.path("Resources/Utils/Glob/ProjectMock")
let lintablePaths = config.lintablePaths(workDirectory: projectPath, fileExtension: "xib")
XCTAssertEqual(
lintablePaths.map { $0.path },
[projectPath.appendingPathComponent("Level1_2/Level1_2.xib").path]
)
}
func testIncludedAndExcluded() {
let config = Config(
disabledRules: [], enabledRules: [],
excluded: ["Level1_1"], included: ["Level1_1/Level2_1"],
customModuleRule: [], baseClassRule: [], reporter: ""
)
let projectPath = fixture.path("Resources/Utils/Glob/ProjectMock")
let lintablePaths = config.lintablePaths(workDirectory: projectPath, fileExtension: "xib")
XCTAssertEqual(lintablePaths, [])
}
}
| 34.137255 | 98 | 0.612866 |
b995735492abd1e1f0b9cd6c6e35a7a44a44c269 | 2,776 | //
// SceneDelegate.swift
// SplashCardTest
//
// Created by Jean-Marc Boullianne on 4/24/20.
// Copyright © 2020 TrailingClosure. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.707692 | 147 | 0.707493 |
1888076e794024182b0672b152263dae9a93dd2a | 6,826 | //
// ChooseImageViewController.swift
// imageMultiSelect
//
// Created by Amir Shayegh on 2017-12-12.
// Copyright © 2017 Amir Shayegh. All rights reserved.
//
import UIKit
import Photos
extension Notification.Name {
static let selectedImages = Notification.Name("selectedImages")
}
class ChooseImageViewController: UIViewController {
@IBOutlet weak var navBar: UIView!
@IBOutlet weak var container: UIView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var loading: UIActivityIndicatorView!
@IBOutlet weak var loadingContainer: UIView!
var images = [PHAsset]()
var selectedIndexs = [Int]()
var callBack: ((_ close: Bool) -> Void )?
let cellReuseIdentifier = "GalleryImageCell"
let cellXibName = "GalleryImageCollectionViewCell"
var mode: GalleryMode = GalleryMode.Image
// colors:
var bg: UIColor = UIColor(hex: "1598a7")
var utilBarBG: UIColor = UIColor(hex: "0a3e44")
var buttonText: UIColor = UIColor(hex: "d7eef1")
var loadingBG: UIColor = UIColor(hex: "1598a7")
var loadingIndicator: UIColor = UIColor(hex: "d7eef1")
override func viewDidLoad() {
super.viewDidLoad()
lockdown()
style()
loadData()
setUpCollectionView()
NotificationCenter.default.addObserver(self, selector: #selector(sent), name: .selectedImages, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
styleContainer(view: navBar.layer)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
unlock()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.selectedIndexs.removeAll()
}
func sendBackImages(images: [PHAsset]) {
NotificationCenter.default.post(name: .selectedImages, object: self, userInfo: ["name":images])
unlock()
closeVC()
}
@objc func sent() {}
@objc func appWillEnterForeground() {
if self.images.count != AssetManager.sharedInstance.getPHAssetImages().count {
reloadData()
}
}
@IBAction func addImages(_ sender: Any) {
if selectedIndexs.count == 0 {
closeVC()
}
lockdown()
var selectedImages = [PHAsset]()
for index in selectedIndexs {
selectedImages.append(images[index])
}
sendBackImages(images: selectedImages)
}
@IBAction func cancel(_ sender: Any) {
closeVC()
}
func closeVC() {
self.selectedIndexs.removeAll()
self.collectionView.reloadData()
self.dismiss(animated: true, completion: {
if self.callBack != nil {
return self.callBack!(true)
}
})
}
func lockdown() {
self.loading.startAnimating()
self.view.isUserInteractionEnabled = false
self.loading.isHidden = false
self.loadingContainer.isHidden = false
}
func unlock() {
self.loading.stopAnimating()
self.loading.isHidden = true
self.loadingContainer.isHidden = true
self.view.isUserInteractionEnabled = true
}
func reloadCellsOfInterest(indexPath: IndexPath) {
let indexes = self.selectedIndexs.map { (value) -> IndexPath in
return IndexPath(row: value, section: 0)
}
if indexes.contains(indexPath) {
self.collectionView.reloadItems(at: indexes)
} else {
self.collectionView.reloadItems(at: indexes)
self.collectionView.reloadItems(at: [indexPath])
}
}
func style() {
loadingContainer.layer.cornerRadius = loadingContainer.frame.height / 2
self.container.backgroundColor = bg
self.collectionView.backgroundColor = bg
self.loadingContainer.backgroundColor = loadingBG
self.loading.color = loadingIndicator
}
func setColors(bg: UIColor, utilBarBG: UIColor, buttonText: UIColor, loadingBG: UIColor, loadingIndicator: UIColor) {
self.bg = bg
self.utilBarBG = utilBarBG
self.buttonText = buttonText
self.loadingBG = loadingBG
self.loadingIndicator = loadingIndicator
}
func styleContainer(view: CALayer) {
view.borderColor = UIColor(red:0, green:0, blue:0, alpha:0.5).cgColor
view.shadowOffset = CGSize(width: 0, height: 2)
view.shadowColor = UIColor(red:0, green:0, blue:0, alpha:0.5).cgColor
view.shadowOpacity = 1
view.shadowRadius = 3
}
}
extension ChooseImageViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func reloadData() {
self.selectedIndexs.removeAll()
loadData()
}
func loadData() {
if self.mode == .Image {
self.images = AssetManager.sharedInstance.getPHAssetImages()
self.collectionView.reloadData()
} else {
self.images = AssetManager.sharedInstance.getPHAssetVideos()
self.collectionView.reloadData()
}
}
func setUpCollectionView() {
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.register(UINib(nibName: cellXibName, bundle: nil), forCellWithReuseIdentifier: cellReuseIdentifier)
// set size of cells
guard let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
layout.itemSize = getCellSize()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : GalleryImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as! GalleryImageCollectionViewCell
cell.setUp(selectedIndexes: selectedIndexs, indexPath: indexPath, phAsset: images[indexPath.row], primaryColor:UIColor(hex: "4667a2"), textColor: UIColor.white)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if selectedIndexs.contains(indexPath.row) {
selectedIndexs.remove(at: selectedIndexs.index(of: indexPath.row)!)
} else {
selectedIndexs.append(indexPath.row)
}
reloadCellsOfInterest(indexPath: indexPath)
}
func getCellSize() -> CGSize {
return CGSize(width: self.view.frame.size.width/3 - 10, height: self.view.frame.size.width/3 - 15)
}
}
| 32.350711 | 179 | 0.661295 |
504faae9ebb7dd748504cd45bf50fdd7f881eb94 | 199 | //
// Device.swift
// PlaneTalk
//
// Created by Annino De Petra on 14/03/2020.
// Copyright © 2020 Annino De Petra. All rights reserved.
//
import Foundation
struct Device {
var ip: String
}
| 14.214286 | 58 | 0.673367 |
0ec19c168566a9fd319c3b4fcfebe745bd694536 | 1,188 | //
// MetalGettingStartedUITests.swift
// MetalGettingStartedUITests
//
// Created by Frad Lee on 7/31/19.
// Copyright © 2019 Frad Lee. All rights reserved.
//
import XCTest
class MetalGettingStartedUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.942857 | 182 | 0.69697 |
752b76b46a13164312af07adb907ef89cb794c6b | 856 | //
// RxSwift+EventProtocol.swift
// MERLin
//
// Created by Giuseppe Lanza on 29/08/18.
// Copyright © 2018 Giuseppe Lanza. All rights reserved.
//
import RxSwift
public extension ObservableType where Element: EventProtocol {
func toEventProtocol() -> Observable<EventProtocol> {
return map { $0 as EventProtocol }
}
func toAnyEvent() -> Observable<AnyEvent> {
return map(AnyEvent.init)
}
}
public extension ObservableType where Element == AnyEvent {
func capture<T: EventProtocol>(case target: T) -> Observable<T> {
return filter { $0.matches(event: target) }
.compactMap { $0.base as? T }
}
func capture<T: EventProtocol, Payload>(case pattern: @escaping (Payload) -> T) -> Observable<Payload> {
return compactMap { $0.extractPayload(ifMatches: pattern) }
}
}
| 27.612903 | 108 | 0.653037 |
ac6df1dd8e43b748f5508dd0b5ba9cb9b572552a | 23,176 | import Apollo
import Foundation
import PerimeterX
import Prelude
import ReactiveExtensions
import ReactiveSwift
public extension Bundle {
var _buildVersion: String {
return (self.infoDictionary?["CFBundleVersion"] as? String) ?? "1"
}
}
/**
A `ServerType` that requests data from an API webservice.
*/
public struct Service: ServiceType {
public let appId: String
public let serverConfig: ServerConfigType
public let oauthToken: OauthTokenAuthType?
public let language: String
public let currency: String
public let buildVersion: String
public let deviceIdentifier: String
public let perimeterXClient: PerimeterXClientType
public let apolloClient: ApolloClientType?
public init(
appId: String = Bundle.main.bundleIdentifier ?? "com.kickstarter.kickstarter",
serverConfig: ServerConfigType = ServerConfig.production,
oauthToken: OauthTokenAuthType? = nil,
language: String = "en",
currency: String = "USD",
buildVersion: String = Bundle.main._buildVersion,
deviceIdentifier: String = UIDevice.current.identifierForVendor.coalesceWith(UUID()).uuidString,
apolloClient: ApolloClientType? = nil,
perimeterXClient: PerimeterXClientType = PerimeterXClient()
) {
self.appId = appId
self.serverConfig = serverConfig
self.oauthToken = oauthToken
self.language = language
self.currency = currency
self.buildVersion = buildVersion
self.deviceIdentifier = deviceIdentifier
self.perimeterXClient = perimeterXClient
/// Dummy client, only required to satisfy `ApolloClientType` protocol, not used.
self.apolloClient = apolloClient
// Global override required for injecting custom User-Agent header in ajax requests
UserDefaults.standard.register(defaults: ["UserAgent": Service.userAgent])
// Initialize PerimeterX
PXManager.sharedInstance().start(with: Secrets.PerimeterX.appId)
// Configure GraphQL Client
GraphQL.shared.configure(
with: serverConfig.graphQLEndpointUrl,
headers: self.defaultHeaders,
additionalHeaders: { perimeterXClient.headers() }
)
}
public func login(_ oauthToken: OauthTokenAuthType) -> Service {
return Service(
appId: self.appId,
serverConfig: self.serverConfig,
oauthToken: oauthToken,
language: self.language,
buildVersion: self.buildVersion
)
}
public func logout() -> Service {
return Service(
appId: self.appId,
serverConfig: self.serverConfig,
oauthToken: nil,
language: self.language,
buildVersion: self.buildVersion
)
}
public func facebookConnect(facebookAccessToken token: String) -> SignalProducer<User, ErrorEnvelope> {
return request(.facebookConnect(facebookAccessToken: token))
}
public func addImage(file fileURL: URL, toDraft draft: UpdateDraft)
-> SignalProducer<UpdateDraft.Image, ErrorEnvelope> {
return request(Route.addImage(fileUrl: fileURL, toDraft: draft))
}
public func addNewCreditCard(input: CreatePaymentSourceInput)
-> SignalProducer<CreatePaymentSourceEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.CreatePaymentSourceMutation(input: GraphAPI.CreatePaymentSourceInput.from(input)))
.flatMap(CreatePaymentSourceEnvelope.producer(from:))
}
public func cancelBacking(input: CancelBackingInput)
-> SignalProducer<EmptyResponseEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.CancelBackingMutation(input: GraphAPI.CancelBackingInput(id: input.backingId)))
.flatMap { _ in
SignalProducer(value: EmptyResponseEnvelope())
}
}
public func changeEmail(input: ChangeEmailInput) ->
SignalProducer<EmptyResponseEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.UpdateUserAccountMutation(input: GraphAPI.UpdateUserAccountInput.from(input)))
.flatMap { _ in
SignalProducer(value: EmptyResponseEnvelope())
}
}
public func changePassword(input: ChangePasswordInput) ->
SignalProducer<EmptyResponseEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.UpdateUserAccountMutation(input: GraphAPI.UpdateUserAccountInput.from(input)))
.flatMap { _ in
SignalProducer(value: EmptyResponseEnvelope())
}
}
public func createBacking(input: CreateBackingInput) ->
SignalProducer<CreateBackingEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI.CreateBackingMutation(input: GraphAPI.CreateBackingInput.from(input)))
.flatMap(CreateBackingEnvelope.producer(from:))
}
public func createPassword(input: CreatePasswordInput)
-> SignalProducer<EmptyResponseEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.UpdateUserAccountMutation(input: GraphAPI.UpdateUserAccountInput.from(input)))
.flatMap { _ in
SignalProducer(value: EmptyResponseEnvelope())
}
}
public func clearUserUnseenActivity(input _: EmptyInput)
-> SignalProducer<ClearUserUnseenActivityEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.ClearUserUnseenActivityMutation(input: GraphAPI.ClearUserUnseenActivityInput()))
.flatMap(ClearUserUnseenActivityEnvelope.producer(from:))
}
public func deletePaymentMethod(input: PaymentSourceDeleteInput)
-> SignalProducer<DeletePaymentMethodEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.DeletePaymentSourceMutation(input: GraphAPI.PaymentSourceDeleteInput.from(input)))
.flatMap(DeletePaymentMethodEnvelope.producer(from:))
}
public func changeCurrency(input: ChangeCurrencyInput) ->
SignalProducer<EmptyResponseEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.UpdateUserProfileMutation(input: GraphAPI.UpdateUserProfileInput.from(input)))
.flatMap { _ in
SignalProducer(value: EmptyResponseEnvelope())
}
}
public func delete(image: UpdateDraft.Image, fromDraft draft: UpdateDraft)
-> SignalProducer<UpdateDraft.Image, ErrorEnvelope> {
return request(.deleteImage(image, fromDraft: draft))
}
public func exportData() -> SignalProducer<VoidEnvelope, ErrorEnvelope> {
return request(.exportData)
}
public func exportDataState()
-> SignalProducer<ExportDataEnvelope, ErrorEnvelope> {
return request(.exportDataState)
}
public func previewUrl(forDraft draft: UpdateDraft) -> URL? {
return self.serverConfig.apiBaseUrl
.appendingPathComponent("/v1/projects/\(draft.update.projectId)/updates/draft/preview")
}
public func fetchActivities(count: Int?) -> SignalProducer<ActivityEnvelope, ErrorEnvelope> {
let categories: [Activity.Category] = [
.backing,
.cancellation,
.failure,
.follow,
.launch,
.success,
.update
]
return request(.activities(categories: categories, count: count))
}
public func fetchActivities(paginationUrl: String)
-> SignalProducer<ActivityEnvelope, ErrorEnvelope> {
return requestPaginationDecodable(paginationUrl)
}
// FIXME: Should be able to convert this to Apollo.
public func fetchBacking(forProject project: Project, forUser user: User)
-> SignalProducer<Backing, ErrorEnvelope> {
return request(.backing(projectId: project.id, backerId: user.id))
}
public func fetchProjectComments(
slug: String,
cursor: String?,
limit: Int?,
withStoredCards: Bool
) -> SignalProducer<CommentsEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.fetch(query: GraphAPI.FetchProjectCommentsQuery(
slug: slug,
cursor: cursor,
limit: limit,
withStoredCards: withStoredCards
))
.flatMap(CommentsEnvelope.envelopeProducer(from:))
}
public func fetchUpdateComments(
id: String,
cursor: String?,
limit: Int?,
withStoredCards: Bool
) -> SignalProducer<CommentsEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.fetch(query: GraphAPI.FetchUpdateCommentsQuery(
postId: id,
cursor: cursor,
limit: limit,
withStoredCards: withStoredCards
))
.flatMap(CommentsEnvelope.envelopeProducer(from:))
}
// FIXME: Should be able to convert this to Apollo.
public func fetchCommentReplies(query: NonEmptySet<Query>)
-> SignalProducer<CommentRepliesEnvelope, ErrorEnvelope> {
return fetch(query: query)
.mapError(ErrorEnvelope.envelope(from:))
.flatMap(CommentRepliesEnvelope.envelopeProducer(from:))
}
public func fetchConfig() -> SignalProducer<Config, ErrorEnvelope> {
return request(.config)
}
public func fetchDiscovery(paginationUrl: String)
-> SignalProducer<DiscoveryEnvelope, ErrorEnvelope> {
return requestPaginationDecodable(paginationUrl)
}
public func fetchDiscovery(params: DiscoveryParams)
-> SignalProducer<DiscoveryEnvelope, ErrorEnvelope> {
return request(.discover(params))
}
public func fetchFriends() -> SignalProducer<FindFriendsEnvelope, ErrorEnvelope> {
return request(.friends)
}
public func fetchFriends(paginationUrl: String)
-> SignalProducer<FindFriendsEnvelope, ErrorEnvelope> {
return requestPaginationDecodable(paginationUrl)
}
public func fetchFriendStats() -> SignalProducer<FriendStatsEnvelope, ErrorEnvelope> {
return request(.friendStats)
}
public func fetchGraphCategories(query: NonEmptySet<Query>)
-> SignalProducer<RootCategoriesEnvelope, GraphError> {
return fetch(query: query)
}
public func fetchGraphCategory(query: NonEmptySet<Query>)
-> SignalProducer<CategoryEnvelope, GraphError> {
return fetch(query: query)
}
public func fetchGraphUser(withStoredCards: Bool)
-> SignalProducer<UserEnvelope<GraphUser>, ErrorEnvelope> {
return GraphQL.shared.client
.fetch(query: GraphAPI.FetchUserQuery(withStoredCards: withStoredCards))
.flatMap(UserEnvelope<GraphUser>.envelopeProducer(from:))
}
public func fetchErroredUserBackings(status: BackingState)
-> SignalProducer<ErroredBackingsEnvelope, ErrorEnvelope> {
guard let status = GraphAPI.BackingState.from(status) else
{ return SignalProducer(error: .couldNotParseJSON) }
return GraphQL.shared.client
.fetch(query: GraphAPI.FetchUserBackingsQuery(status: status, withStoredCards: false))
.flatMap(ErroredBackingsEnvelope.producer(from:))
}
public func fetchBacking(id: Int, withStoredCards: Bool)
-> SignalProducer<ProjectAndBackingEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.fetch(query: GraphAPI.FetchBackingQuery(id: "\(id)", withStoredCards: withStoredCards))
.flatMap(ProjectAndBackingEnvelope.envelopeProducer(from:))
}
public func fetchMessageThread(messageThreadId: Int)
-> SignalProducer<MessageThreadEnvelope, ErrorEnvelope> {
return request(.messagesForThread(messageThreadId: messageThreadId))
}
public func fetchMessageThread(backing: Backing)
-> SignalProducer<MessageThreadEnvelope?, ErrorEnvelope> {
return request(.messagesForBacking(backing))
}
public func fetchMessageThreads(mailbox: Mailbox, project: Project?)
-> SignalProducer<MessageThreadsEnvelope, ErrorEnvelope> {
return request(.messageThreads(mailbox: mailbox, project: project))
}
public func fetchMessageThreads(paginationUrl: String)
-> SignalProducer<MessageThreadsEnvelope, ErrorEnvelope> {
return requestPaginationDecodable(paginationUrl)
}
/**
Use case:
- `ProjectPamphletViewModel`
This is the only use case at the moment as it effects the `ProjectPamphletViewController` directly.
*/
public func fetchProject(projectParam: Param)
-> SignalProducer<Project.ProjectPamphletData, ErrorEnvelope> {
switch (projectParam.id, projectParam.slug) {
case let (.some(projectId), _):
let query = GraphAPI.FetchProjectByIdQuery(projectId: projectId, withStoredCards: false)
return GraphQL.shared.client
.fetch(query: query)
.flatMap(Project.projectProducer(from:))
case let (_, .some(projectSlug)):
let query = GraphAPI.FetchProjectBySlugQuery(slug: projectSlug, withStoredCards: false)
return GraphQL.shared.client
.fetch(query: query)
.flatMap(Project.projectProducer(from:))
default:
return .empty
}
}
/**
Use cases:
- `ManagePledgeViewModel`
- `CommentsViewModel`
- `UpdateViewModel`
- `UpdatePreviewViewModel`
- `AppDelegateViewModel`
Eventually this v1 network request can be replaced with `fetchProject(projectParam:)` if we refactor the use cases above in the future.
*/
public func fetchProject(param: Param) -> SignalProducer<Project, ErrorEnvelope> {
return request(.project(param))
}
public func fetchProjectFriends(param: Param) -> SignalProducer<[User], ErrorEnvelope> {
switch (param.id, param.slug) {
case let (.some(projectId), _):
let query = GraphAPI.FetchProjectFriendsByIdQuery(projectId: projectId, withStoredCards: false)
return GraphQL.shared.client
.fetch(query: query)
.flatMap(Project.projectFriendsProducer(from:))
case let (_, .some(projectSlug)):
let query = GraphAPI.FetchProjectFriendsBySlugQuery(slug: projectSlug, withStoredCards: false)
return GraphQL.shared.client
.fetch(query: query)
.flatMap(Project.projectFriendsProducer(from:))
default:
return .empty
}
}
public func fetchProject(_ params: DiscoveryParams) -> SignalProducer<DiscoveryEnvelope, ErrorEnvelope> {
return request(.discover(params |> DiscoveryParams.lens.perPage .~ 1))
}
public func fetchProject(project: Project) -> SignalProducer<Project, ErrorEnvelope> {
return request(.project(.id(project.id)))
}
public func fetchProjectActivities(forProject project: Project) ->
SignalProducer<ProjectActivityEnvelope, ErrorEnvelope> {
return request(.projectActivities(project))
}
public func fetchProjectActivities(paginationUrl: String)
-> SignalProducer<ProjectActivityEnvelope, ErrorEnvelope> {
return requestPaginationDecodable(paginationUrl)
}
public func fetchProjectNotifications() -> SignalProducer<[ProjectNotification], ErrorEnvelope> {
return request(.projectNotifications)
}
public func fetchProjects(member: Bool) -> SignalProducer<ProjectsEnvelope, ErrorEnvelope> {
return request(.projects(member: member))
}
public func fetchProjects(paginationUrl url: String) -> SignalProducer<ProjectsEnvelope, ErrorEnvelope> {
return requestPaginationDecodable(url)
}
public func fetchProjectStats(projectId: Int) ->
SignalProducer<ProjectStatsEnvelope, ErrorEnvelope> {
return request(.projectStats(projectId: projectId))
}
public func fetchRewardAddOnsSelectionViewRewards(
slug: String,
shippingEnabled: Bool,
locationId: String?
) -> SignalProducer<Project, ErrorEnvelope> {
let query = GraphAPI.FetchAddOnsQuery(
projectSlug: slug,
shippingEnabled: shippingEnabled,
locationId: locationId,
withStoredCards: false
)
return GraphQL.shared.client
.fetch(query: query)
.flatMap(Project.projectProducer(from:))
}
public func fetchRewardShippingRules(projectId: Int, rewardId: Int)
-> SignalProducer<ShippingRulesEnvelope, ErrorEnvelope> {
return request(.shippingRules(projectId: projectId, rewardId: rewardId))
}
public func fetchSurveyResponse(surveyResponseId id: Int) -> SignalProducer<SurveyResponse, ErrorEnvelope> {
return request(.surveyResponse(surveyResponseId: id))
}
public func fetchUserSelf() -> SignalProducer<User, ErrorEnvelope> {
return request(.userSelf)
}
public func fetchUser(userId: Int) -> SignalProducer<User, ErrorEnvelope> {
return request(.user(userId: userId))
}
public func fetchUser(_ user: User) -> SignalProducer<User, ErrorEnvelope> {
return self.fetchUser(userId: user.id)
}
public func fetchUpdate(updateId: Int, projectParam: Param)
-> SignalProducer<Update, ErrorEnvelope> {
return request(.update(updateId: updateId, projectParam: projectParam))
}
public func fetchUpdateDraft(forProject project: Project) -> SignalProducer<UpdateDraft, ErrorEnvelope> {
return request(.fetchUpdateDraft(forProject: project))
}
public func fetchUnansweredSurveyResponses() -> SignalProducer<[SurveyResponse], ErrorEnvelope> {
return request(.unansweredSurveyResponses)
}
public func backingUpdate(forProject project: Project, forUser user: User, received: Bool) ->
SignalProducer<Backing, ErrorEnvelope> {
return request(.backingUpdate(projectId: project.id, backerId: user.id, received: received))
}
public func followAllFriends() -> SignalProducer<VoidEnvelope, ErrorEnvelope> {
return request(.followAllFriends)
}
public func followFriend(userId id: Int) -> SignalProducer<User, ErrorEnvelope> {
return request(.followFriend(userId: id))
}
public func incrementVideoCompletion(forProject project: Project) ->
SignalProducer<VoidEnvelope, ErrorEnvelope> {
let producer = request(.incrementVideoCompletion(project: project))
as SignalProducer<VoidEnvelope, ErrorEnvelope>
return producer
.flatMapError { env -> SignalProducer<VoidEnvelope, ErrorEnvelope> in
if env.ksrCode == .ErrorEnvelopeJSONParsingFailed {
return .init(value: VoidEnvelope())
}
return .init(error: env)
}
}
public func incrementVideoStart(forProject project: Project) ->
SignalProducer<VoidEnvelope, ErrorEnvelope> {
let producer = request(.incrementVideoStart(project: project))
as SignalProducer<VoidEnvelope, ErrorEnvelope>
return producer
.flatMapError { env -> SignalProducer<VoidEnvelope, ErrorEnvelope> in
if env.ksrCode == .ErrorEnvelopeJSONParsingFailed {
return .init(value: VoidEnvelope())
}
return .init(error: env)
}
}
public func login(email: String, password: String, code: String?) ->
SignalProducer<AccessTokenEnvelope, ErrorEnvelope> {
return request(.login(email: email, password: password, code: code))
}
public func login(facebookAccessToken: String, code: String?) ->
SignalProducer<AccessTokenEnvelope, ErrorEnvelope> {
return request(.facebookLogin(facebookAccessToken: facebookAccessToken, code: code))
}
public func markAsRead(messageThread: MessageThread) -> SignalProducer<MessageThread, ErrorEnvelope> {
return request(.markAsRead(messageThread))
}
// FIXME: Convert to using Apollo instead of DSL
public func postComment(input: PostCommentInput)
-> SignalProducer<Comment, ErrorEnvelope> {
return applyMutation(mutation: PostCommentMutation(input: input))
.mapError(ErrorEnvelope.envelope(from:))
.flatMap(PostCommentEnvelope.modelProducer(from:))
}
public func publish(draft: UpdateDraft) -> SignalProducer<Update, ErrorEnvelope> {
return request(.publishUpdateDraft(draft))
}
public func register(pushToken: String) -> SignalProducer<VoidEnvelope, ErrorEnvelope> {
return request(.registerPushToken(pushToken))
}
public func resetPassword(email: String) -> SignalProducer<User, ErrorEnvelope> {
return request(.resetPassword(email: email))
}
public func searchMessages(query: String, project: Project?)
-> SignalProducer<MessageThreadsEnvelope, ErrorEnvelope> {
return request(.searchMessages(query: query, project: project))
}
public func sendMessage(body: String, toSubject subject: MessageSubject)
-> SignalProducer<Message, ErrorEnvelope> {
return request(.sendMessage(body: body, messageSubject: subject))
}
public func sendVerificationEmail(input _: EmptyInput) ->
SignalProducer<EmptyResponseEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI
.UserSendEmailVerificationMutation(input: GraphAPI.UserSendEmailVerificationInput()))
.flatMap { _ in
SignalProducer(value: EmptyResponseEnvelope())
}
}
public func signInWithApple(input: SignInWithAppleInput)
-> SignalProducer<SignInWithAppleEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI.SignInWithAppleMutation(input: GraphAPI.SignInWithAppleInput.from(input)))
.flatMap(SignInWithAppleEnvelope.producer(from:))
}
public func signup(
name: String,
email: String,
password: String,
passwordConfirmation: String,
sendNewsletters: Bool
) -> SignalProducer<AccessTokenEnvelope, ErrorEnvelope> {
return request(.signup(
name: name,
email: email,
password: password,
passwordConfirmation: passwordConfirmation,
sendNewsletters: sendNewsletters
))
}
public func signup(facebookAccessToken token: String, sendNewsletters: Bool) ->
SignalProducer<AccessTokenEnvelope, ErrorEnvelope> {
return request(.facebookSignup(facebookAccessToken: token, sendNewsletters: sendNewsletters))
}
public func unfollowFriend(userId id: Int) -> SignalProducer<VoidEnvelope, ErrorEnvelope> {
return request(.unfollowFriend(userId: id))
}
public func updateBacking(input: UpdateBackingInput)
-> SignalProducer<UpdateBackingEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI.UpdateBackingMutation(input: GraphAPI.UpdateBackingInput.from(input)))
.flatMap(UpdateBackingEnvelope.producer(from:))
}
public func update(draft: UpdateDraft, title: String, body: String, isPublic: Bool)
-> SignalProducer<UpdateDraft, ErrorEnvelope> {
return request(.updateUpdateDraft(draft, title: title, body: body, isPublic: isPublic))
}
public func updateProjectNotification(_ notification: ProjectNotification)
-> SignalProducer<ProjectNotification, ErrorEnvelope> {
return request(.updateProjectNotification(notification: notification))
}
public func updateUserSelf(_ user: User) -> SignalProducer<User, ErrorEnvelope> {
return request(.updateUserSelf(user))
}
public func unwatchProject(input: WatchProjectInput) ->
SignalProducer<WatchProjectResponseEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI.UnwatchProjectMutation(input: GraphAPI.UnwatchProjectInput.from(input)))
.flatMap(WatchProjectResponseEnvelope.producer(from:))
}
public func verifyEmail(withToken token: String)
-> SignalProducer<EmailVerificationResponseEnvelope, ErrorEnvelope> {
request(.verifyEmail(accessToken: token))
}
public func watchProject(input: WatchProjectInput) ->
SignalProducer<WatchProjectResponseEnvelope, ErrorEnvelope> {
return GraphQL.shared.client
.perform(mutation: GraphAPI.WatchProjectMutation(input: GraphAPI.WatchProjectInput.from(input)))
.flatMap(WatchProjectResponseEnvelope.producer(from:))
}
}
| 35.655385 | 138 | 0.736667 |
e554f0d02d9fdd7d0bbfb319b50563d43628d613 | 961 | //
// swiftui_simple_tutorialTests.swift
// swiftui-simple-tutorialTests
//
// Created by Atsuki Kakehi on 2021/11/16.
//
import XCTest
@testable import swiftui_simple_tutorial
class swiftui_simple_tutorialTests: 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.
}
}
}
| 28.264706 | 111 | 0.683663 |
f5bce613c56d90a8d55beab51ae9f3d18ae820f2 | 544 | //
// Icon+Extension..swift
// MaterialDesignSymbol
//
// Created by tichise on 2020年8月10日 20/08/10.
//
import SwiftUI
@available(iOS 14.0, watchOS 7.0, *)
extension Image {
public init(materialDesignIcon: MaterialDesignIconEnum, size: CGFloat, color: Color) {
let symbol = MaterialDesignSymbol(icon: materialDesignIcon, size: size)
symbol.addAttribute(foregroundColor: UIColor(color))
let iconImage = symbol.image(size: CGSize(width: size, height: size))
self.init(uiImage: iconImage)
}
}
| 27.2 | 90 | 0.6875 |
03ec703f24d8654ea5ae378cfb33349d7b13fa6f | 2,212 | //
// GroupAdminControlsTableViewCell.swift
// uChat-project
//
// Created by Luccas Beck on 3/22/19.
// Copyright © 2019 Luccas Beck. All rights reserved.
//
import UIKit
class GroupAdminControlsTableViewCell: UITableViewCell {
var title: UILabel = {
var title = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
title.font = UIFont.systemFont(ofSize: 18)
title.textColor = FalconPalette.defaultBlue
title.text = "Title here"
title.textAlignment = .center
return title
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
selectionColor = ThemeManager.currentTheme().cellSelectionColor
contentView.layer.cornerRadius = 25
contentView.backgroundColor = ThemeManager.currentTheme().controlButtonsColor
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
contentView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5).isActive = true
if #available(iOS 11.0, *) {
contentView.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true
contentView.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -10).isActive = true
} else {
contentView.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
contentView.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
}
contentView.addSubview(title)
title.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
title.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
title.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
title.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
| 37.491525 | 113 | 0.750452 |
cc3a1964fa7552f2039e2ebb5e007f82f2c9cec4 | 3,333 | //
// AppDelegate.swift
// threeDTouch
//
// Created by singerDream on 2018/7/12.
// Copyright © 2018 cz. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
shortCut.append("didFinishLaunching")
if #available(iOS 9.1, *) {
let item1 = UIApplicationShortcutItem(type: "human.name", localizedTitle: "dynamic1", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .favorite), userInfo: nil)
let item2 = UIApplicationShortcutItem(type: "human.name", localizedTitle: "dynamic2", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .favorite), userInfo: nil)
let item3 = UIApplicationShortcutItem(type: "human.name", localizedTitle: "dynamic3", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .favorite), userInfo: nil)
UIApplication.shared.shortcutItems = [item1,item2,item3]
}
//if allow system to hander launchOptions, return true, or false
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:.
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
shortCut.append(shortcutItem.localizedTitle)
completionHandler(false)
}
}
| 52.904762 | 285 | 0.735674 |
08866bf9302a64b514cb8897afabf32d041b5eaa | 4,293 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
import UIKit
extension UIViewController {
/**
A convenience property that provides access to the StatusBarController.
This is the recommended method of accessing the StatusBarController
through child UIViewControllers.
*/
public var statusBarController: StatusBarController? {
return traverseViewControllerHierarchyForClassType()
}
}
open class StatusBarController: TransitionController {
/**
A Display value to indicate whether or not to
display the rootViewController to the full view
bounds, or up to the toolbar height.
*/
open var displayStyle = DisplayStyle.full {
didSet {
layoutSubviews()
}
}
/// Device status bar style.
open var statusBarStyle: UIStatusBarStyle {
get {
return Application.statusBarStyle
}
set(value) {
Application.statusBarStyle = value
}
}
/// Device visibility state.
open var isStatusBarHidden: Bool {
get {
return Application.isStatusBarHidden
}
set(value) {
Application.isStatusBarHidden = value
statusBar.isHidden = isStatusBarHidden
}
}
/// An adjustment based on the rules for displaying the statusBar.
open var statusBarOffsetAdjustment: CGFloat {
return Application.shouldStatusBarBeHidden || statusBar.isHidden ? 0 : statusBar.bounds.height
}
/// A boolean that indicates to hide the statusBar on rotation.
open var shouldHideStatusBarOnRotation = false
/// A reference to the statusBar.
public let statusBar = UIView()
open override func layoutSubviews() {
super.layoutSubviews()
if shouldHideStatusBarOnRotation {
statusBar.isHidden = Application.shouldStatusBarBeHidden
}
statusBar.frame.size.width = view.bounds.width
if #available(iOS 11, *) {
let v = topLayoutGuide.length
statusBar.frame.size.height = 0 < v ? v : 20
} else {
statusBar.frame.size.height = 20
}
switch displayStyle {
case .partial:
let h = statusBar.bounds.height
container.frame.origin.y = h
container.frame.size.height = view.bounds.height - h
case .full:
container.frame = view.bounds
}
rootViewController.view.frame = container.bounds
container.layer.zPosition = statusBar.layer.zPosition + (Application.shouldStatusBarBeHidden ? 1 : -1)
}
open override func prepare() {
super.prepare()
prepareStatusBar()
}
}
fileprivate extension StatusBarController {
/// Prepares the statusBar.
func prepareStatusBar() {
if nil == statusBar.backgroundColor {
statusBar.backgroundColor = .white
}
view.addSubview(statusBar)
}
}
| 31.8 | 106 | 0.717214 |
ef8a17ce76eb76b0d06e28aabd23c7ed3555880d | 13,392 | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import Photos
protocol PhotoLibraryDataSourceDelegate: class {
/// Informs the delegate the photo library contents changed.
func photoLibraryDataSourceLibraryDidChange(changes: PHFetchResultChangeDetails<PHAsset>?)
/// Informs the delegate the photo library permissions changed.
func photoLibraryDataSourcePermissionsDidChange(accessGranted: Bool)
}
// TODO: Support albums. http://b/64225998
class PhotoLibraryDataSource: NSObject, PHPhotoLibraryChangeObserver {
// MARK: - Nested class
/// Stores progress data for photo downloads.
private class DownloadProgressHandler {
// MARK: - Properties
// Photo download progress, keyed by photo asset ID.
private var downloadProgress = [String : Double]()
// Photo download progress blocks, keyed by photo asset ID, called with progress, error and
// whether or not the download is complete.
private var progressBlocks =
[String : (progress: Double, error: Error?, complete: Bool) -> ()]()
// MARK: - Public
/// Sets the download progress for a photo asset.
func setDownloadProgress(_ progress: Double, for photoAsset: PHAsset) {
downloadProgress[photoAsset.localIdentifier] = (0.0...1.0).clamp(progress)
}
/// Gets the download progress for a photo asset.
func downloadProgress(for photoAsset: PHAsset) -> Double? {
return downloadProgress[photoAsset.localIdentifier]
}
/// Removes the download progress for a photo asset.
func removeDownloadProgress(for photoAsset: PHAsset) {
downloadProgress[photoAsset.localIdentifier] = nil
}
/// Sets a progress block for a photo asset.
func setProgressBlock(_ progressBlock: ((Double, Error?, Bool) -> ())?,
for photoAsset: PHAsset) {
progressBlocks[photoAsset.localIdentifier] = progressBlock
}
/// Gets a progress block for a photo asset.
func progressBlock(for photoAsset: PHAsset) -> ((Double, Error?, Bool) -> ())? {
return progressBlocks[photoAsset.localIdentifier]
}
/// Removes a progress block for a photo asset.
func removeProgressBlock(for photoAsset: PHAsset) {
progressBlocks[photoAsset.localIdentifier] = nil
}
}
// MARK: - PhotoLibraryDataSource
// MARK: - Properties
/// Photo library data source delegate.
weak var delegate: PhotoLibraryDataSourceDelegate?
/// The permissions state of the capturer.
var isPhotoLibraryPermissionGranted: Bool {
let authStatus = PHPhotoLibrary.authorizationStatus()
switch authStatus {
case .denied, .restricted: return false
case .authorized: return true
case .notDetermined:
// Prompt user for the permission to use the camera.
PHPhotoLibrary.requestAuthorization({ (status) in
DispatchQueue.main.sync {
let granted = status == .authorized
self.delegate?.photoLibraryDataSourcePermissionsDidChange(accessGranted: granted)
}
})
return false
}
}
private let downloadProgressHandler = DownloadProgressHandler()
private var photoAssetFetchResult: PHFetchResult<PHAsset>?
// Request options configured for image data.
private var requestOptions: PHImageRequestOptions {
let requestOptions = PHImageRequestOptions()
requestOptions.version = .current
requestOptions.deliveryMode = .fastFormat
requestOptions.resizeMode = .fast
requestOptions.isSynchronous = true
requestOptions.isNetworkAccessAllowed = true
return requestOptions
}
// MARK: - Public
/// Performs a photo asset fetch.
func fetch() {
let fetchOptions = PHFetchOptions()
fetchOptions.fetchLimit = 250
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
photoAssetFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
}
/// The number of photo assets.
var numberOfPhotoAssets: Int {
guard let photoAssetFetchResult = photoAssetFetchResult else { return 0 }
return photoAssetFetchResult.count
}
/// Returns the index path of a photo asset.
///
/// - Parameter photoAsset: The photo asset.
/// - Returns: The index path.
func indexPathOfPhotoAsset(_ photoAsset: PHAsset) -> IndexPath? {
guard let index = photoAssetFetchResult?.index(of: photoAsset) else { return nil }
return indexPath(for: index)
}
/// Returns the photo asset for an index path.
///
/// - Parameter indexPath: The index path.
/// - Returns: The photo asset.
func photoAsset(for indexPath: IndexPath) -> PHAsset? {
guard let index = photoAssetIndex(for: indexPath) else { return nil }
return photoAssetFetchResult?.object(at: index)
}
/// Starts the photo library observer. If the caller should reload after, true is returned.
///
/// - Returns: Should the caller refresh collection data?
func startObserving() -> Bool {
PHPhotoLibrary.shared().register(self)
if photoAssetFetchResult == nil {
fetch()
return true
}
return false
}
/// Stops the photo library observer.
func stopObserving() {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
/// Returns the thumbnail for a photo asset at an index path.
///
/// - Parameters:
/// - indexPath: The index path.
/// - size: The target size for the thumbnail.
/// - contentMode: The content mode for the thumbnail.
/// - completion: Called with the thumbnail image.
func thumbnailImageForPhotoAsset(at indexPath: IndexPath,
withSize size: CGSize,
contentMode: PHImageContentMode,
completion: @escaping (UIImage?) -> ()) {
guard let photoAssetFetchResult = photoAssetFetchResult,
let index = photoAssetIndex(for: indexPath) else {
completion(nil)
return
}
let photoAsset = photoAssetFetchResult.object(at: index)
PHImageManager.default().requestImage(for: photoAsset,
targetSize: size,
contentMode: contentMode,
options: requestOptions) { (image, info) in
if let error = info?[PHImageErrorKey] as? Error {
print(error)
return
}
if let isDegradedNumber = info?[PHImageResultIsDegradedKey] as? NSNumber {
// Ignore low-res thumbnails.
guard !isDegradedNumber.boolValue else { return }
}
completion(image)
}
}
/// Returns the data for an image at an index path, including available metadata.
///
/// - Parameters:
/// - indexPath: The index path.
/// - downloadDidBegin: Called when a photo asset image download begins.
/// - completion: Called with the image, available metadata and photo asset the fetch was
/// performed for.
/// - Returns: The photo asset.
func imageForPhotoAsset(
at indexPath: IndexPath,
downloadDidBegin: @escaping () -> (),
completion: @escaping (UIImage?, NSDictionary?, PHAsset?) -> ()) -> PHAsset? {
guard let photoAssetFetchResult = photoAssetFetchResult,
let index = photoAssetIndex(for: indexPath) else {
completion(nil, nil, nil)
return nil
}
let photoAsset = photoAssetFetchResult.object(at: index)
// If the photo asset has a download in progress, return the photo asset so its cell can be
// shown as selected when the download does complete.
guard !isDownloadInProgress(for: indexPath).hasDownload else {
completion(nil, nil, nil)
return photoAsset
}
DispatchQueue.global().async {
let targetSize = CGSize(width: 1000, height: 1000).applying(scale: UIScreen.main.scale)
let options = self.requestOptions
var isDownloading = false
options.progressHandler = { (downloadProgress, error, _, _) in
DispatchQueue.main.async {
if !isDownloading {
downloadDidBegin()
isDownloading = true
}
self.downloadProgressHandler.setDownloadProgress(downloadProgress, for: photoAsset)
if let progressBlock = self.downloadProgressHandler.progressBlock(for: photoAsset) {
progressBlock((0.0...1.0).clamp(downloadProgress), error, false)
}
if error != nil {
self.downloadProgressHandler.removeDownloadProgress(for: photoAsset)
}
}
}
PHImageManager.default().requestImage(for: photoAsset,
targetSize: targetSize,
contentMode: .aspectFit,
options: options) { (image, imageInfo) in
if let error = imageInfo?[PHImageErrorKey] as? Error {
print(error)
return
}
if let isDegradedNumber = imageInfo?[PHImageResultIsDegradedKey] as? NSNumber {
// Ignore low-res thumbnails.
guard !isDegradedNumber.boolValue else { return }
}
DispatchQueue.main.async {
if let progressBlock = self.downloadProgressHandler.progressBlock(for: photoAsset) {
progressBlock(1, nil, true)
}
self.downloadProgressHandler.removeDownloadProgress(for: photoAsset)
// Return the image. We cannot capture metadata using requestImage, so we return nil. This
// means any photo asset chosen for the picker will not bring across its metadata.
completion(image, nil, photoAsset)
}
}
}
return photoAsset
}
/// Sets the progress block of download progress for an index path.
///
/// - Parameters:
/// - indexPath: The index path.
/// - progressBlock: The progress block.
func setDownloadProgressListener(for indexPath: IndexPath,
progressBlock: ((Double, Error?, Bool) -> ())?) {
guard let index = photoAssetIndex(for: indexPath),
let photoAsset = photoAssetFetchResult?.object(at: index) else { return }
downloadProgressHandler.setProgressBlock(progressBlock, for: photoAsset)
}
/// Removes the download progress block for an index path.
///
/// - Parameter indexPath: The index path.
func removeDownloadProgressListener(for indexPath: IndexPath) {
// This can be called for removed index paths, so we have to protect against a bad index.
guard let index = photoAssetIndex(for: indexPath),
let photoAssetFetchResult = photoAssetFetchResult,
index < photoAssetFetchResult.count else { return }
let photoAsset = photoAssetFetchResult.object(at: index)
downloadProgressHandler.removeDownloadProgress(for: photoAsset)
}
/// Whether or not there is a download in progress for an index path.
///
/// - Parameter indexPath: The index path.
/// - Returns: Whether or not there is a download, and its progress.
func isDownloadInProgress(for indexPath: IndexPath) -> (hasDownload: Bool, progress: Double) {
guard let index = photoAssetIndex(for: indexPath),
let photoAsset = photoAssetFetchResult?.object(at: index) else { return (false, 0) }
if let progress = downloadProgressHandler.downloadProgress(for: photoAsset) {
return (true, progress)
} else {
return (false, 0)
}
}
// MARK: - Private
private func indexPath(for photoAssetIndex: Int) -> IndexPath {
// Only section 0 contains photo assets.
return IndexPath(item: photoAssetIndex, section: 0)
}
private func photoAssetIndex(for indexPath: IndexPath) -> Int? {
// Only section 0 contains photo assets .
guard indexPath.section == 0 else { return nil }
return indexPath.item
}
// MARK: - PHPhotoLibraryChangeObserver
func photoLibraryDidChange(_ changeInstance: PHChange) {
DispatchQueue.main.sync {
if let previousFetchResult = photoAssetFetchResult,
let changes = changeInstance.changeDetails(for: previousFetchResult) {
// Remove any listeners for index paths that were removed.
if let removedIndexes = changes.removedIndexes {
for removedIndex in 0..<removedIndexes.count {
let indexPath = IndexPath(item: removedIndex, section: 0)
removeDownloadProgressListener(for: indexPath)
}
}
// Keep the new fetch result for future use.
photoAssetFetchResult = changes.fetchResultAfterChanges
if changes.hasIncrementalChanges {
delegate?.photoLibraryDataSourceLibraryDidChange(changes: changes)
} else {
// Reload the collection view if incremental diffs are not available.
delegate?.photoLibraryDataSourceLibraryDidChange(changes: nil)
}
}
}
}
}
| 36.690411 | 100 | 0.668459 |
5d41307e4f1f54681ea2ddaf0dcde1094f1ebaec | 1,130 | //
// Fetcher.swift
// Haneke
//
// Created by Hermes Pique on 9/9/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
// See: http://stackoverflow.com/questions/25915306/generic-closure-in-protocol
open class Fetcher<T : DataConvertible> {
public let key: String
public init(key: String) {
self.key = key
}
open func fetch(failure fail: @escaping ((Error?) -> ()), success succeed: @escaping (T.Result, @escaping () -> Data) -> ()) {}
open func cancelFetch() {}
}
class SimpleFetcher<T : DataConvertible&DataRepresentable> : Fetcher<T> where T.Result == T {
let getValue : () -> T
init(key: String, value getValue : @autoclosure @escaping () -> T) {
self.getValue = getValue
super.init(key: key)
}
override func fetch(failure fail: @escaping ((Error?) -> ()), success succeed: @escaping (T.Result, @escaping () -> Data) -> ()) {
let value = getValue()
let dataGenerator = { () -> Data in value.asData() }
succeed(value, dataGenerator)
}
override func cancelFetch() {}
}
| 26.27907 | 134 | 0.59823 |
761566fd92f3e85f202c40198b9fe1ce30f21c64 | 7,274 | //
// PulsingAnimationCall.swift
// CircularLoaderLBTA
//
// Created by manh.le on 5/8/19.
// Copyright © 2019 Lets Build That App. All rights reserved.
//
import UIKit
@objcMembers
public class PulsingAnimationCall: CAReplicatorLayer, CAAnimationDelegate
{
// var pulsatingLayer: CAShapeLayer!
var affect:CALayer!
var prevSuperlayer:CALayer!
var prevLayerIndex: UInt32 = 0
var prevAnimation: CAAnimation!
var shouldResume: Bool = false
var animationGroup: CAAnimationGroup!
var _animationDuration: CFTimeInterval!
var animationDuration: CFTimeInterval!
{
get {
return _animationDuration
}
set
{
_animationDuration = newValue
self.instanceDelay = (_animationDuration + _pulseInterval)/Double(_layerNumber)
}
}
var keyTimeForHalfOpacity: CFTimeInterval!
var fromValueForRadius: CGFloat!
var _layerNumber: NSInteger! = 0
var layerNumber: NSInteger
{
get{
return _layerNumber
}
set{
_layerNumber = newValue
self.instanceCount = _layerNumber
self.instanceDelay = (animationDuration + pulseInterval)/Double(_layerNumber)
}
}
var _radius: CGFloat!
var radius: CGFloat
{
get{
return _radius
}
set
{
_radius = newValue
let diameter = _radius*2
self.affect.bounds = CGRect(x: 0, y: 0, width: diameter, height: diameter)
self.affect.cornerRadius = _radius
}
}
var _pulseInterval: CFTimeInterval! = 0.0
var pulseInterval: CFTimeInterval!
{
get
{
return _pulseInterval
}
set
{
_pulseInterval = newValue
affect.removeAnimation(forKey: "pulse")
}
}
var _startInterval: TimeInterval!
var startInterval: TimeInterval!
{
get {
return _startInterval
}
set{
_startInterval = newValue
self.instanceDelay = _startInterval
}
}
override public var backgroundColor: CGColor?
{
get{
return super.backgroundColor
}
set{
super.backgroundColor = newValue
affect.backgroundColor = newValue
}
}
override public var repeatCount: Float
{
get
{
return super.repeatCount
}
set{
super.repeatCount = newValue
if animationGroup != nil {
animationGroup.repeatCount = newValue
}
}
}
override init() {
super.init()
affect = CALayer()
affect.contentsScale = UIScreen.main.scale
affect.opacity = 0
addSublayer(affect)
setupDefault()
// NotificationCenter.default.addObserver(self,
// selector: #selector(onDidEnterBackground),
// name: Notification.Name.UIApplicationDidEnterBackground,
// object: nil)
//
// NotificationCenter.default.addObserver(self,
// selector: #selector(onWillEnterForeground),
// name: NSNotification.Name.UIApplicationWillEnterForeground,
// object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupDefault()
{
shouldResume = true
animationDuration = 3
keyTimeForHalfOpacity = 0.2
_pulseInterval = 0
fromValueForRadius = 0.1
radius = UIScreen.main.bounds.size.width
startInterval = 1
layerNumber = 5
self.repeatCount = Float.infinity
self.backgroundColor = UIColor.white.cgColor//UIColor(displayP3Red: 0.000, green: 0.455, blue: 0.756, alpha: 0.45).cgColor
// affect.backgroundColor = self.backgroundColor
}
@objc public func start()
{
animatePulsatingLayer()
affect.add(animationGroup, forKey: "pulse")
}
private func createCircleShapeLayer(strokeColor: UIColor, fillColor: UIColor, radius: CGFloat) -> CAShapeLayer {
let layer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
layer.path = circularPath.cgPath
layer.strokeColor = strokeColor.cgColor
layer.lineWidth = 20
layer.fillColor = fillColor.cgColor
// layer.lineCap = kCALineCapRound
// layer.position = self.center
return layer
}
public func animatePulsatingLayer() {
let aGroup = CAAnimationGroup()
aGroup.duration = animationDuration + pulseInterval
aGroup.repeatCount = self.repeatCount
// aGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) //CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)
let animation = CABasicAnimation(keyPath: "transform.scale.xy")
animation.fromValue = fromValueForRadius
animation.toValue = 1
animation.duration = animationDuration
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.duration = animationDuration
// let fromValueForAlpha = 1//self.backgroundColor?.alpha
opacityAnimation.values = [0, 0.3, 0]
opacityAnimation.keyTimes = ([0, keyTimeForHalfOpacity, 1] as! [NSNumber])
aGroup.animations = [animation,opacityAnimation]
animationGroup = aGroup
animationGroup.delegate = self
}
@objc func onDidEnterBackground()
{
if self.superlayer != nil {
self.prevSuperlayer = self.superlayer;
if (self.prevSuperlayer != nil) {
var layerIndex: UInt32 = 0
for aSublayer in self.superlayer!.sublayers!
{
if aSublayer == self
{
self.prevLayerIndex = layerIndex
break
}
layerIndex = layerIndex + 1
}
}
self.prevAnimation = affect.animation(forKey: "pulse")
}
}
@objc func onWillEnterForeground()
{
if (shouldResume)
{
resume()
}
}
func resume() {
self.addSublayer(affect)
if(prevSuperlayer != nil)
{
prevSuperlayer.insertSublayer(self, at: prevLayerIndex)
}
if (prevAnimation != nil) {
affect.add(prevAnimation, forKey: "pulse")
}
}
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
// if let arrKey = affect.animationKeys(), arrKey.count > 0
// {
// affect.removeAllAnimations()
// }
// affect.removeFromSuperlayer()
// self.removeFromSuperlayer()
}
}
| 31.626087 | 157 | 0.574374 |
feda7adde4a8ced215389801073ac88b71c13d0c | 368 | //
// PlayerView.swift
// Ahobsu
//
// Created by 김선재 on 20/02/2020.
// Copyright © 2020 ahobsu. All rights reserved.
//
import SwiftUI
struct PlayerView: UIViewRepresentable {
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PlayerView>) {
}
func makeUIView(context: Context) -> UIView {
return PlayerUIView(frame: .zero)
}
}
| 20.444444 | 88 | 0.706522 |
1a73c22eb0027a9b17452c9f269b7d4a832cd2bf | 734 | //
// Weak.swift
// ASToolkit
//
// Created by andrzej semeniuk on 9/7/17.
// Copyright © 2017 Andrzej Semeniuk. All rights reserved.
//
import Foundation
open class Weak<T: AnyObject> {
public weak var value : T?
public init (_ value: T) {
self.value = value
}
}
open class WeakHashable<T: Hashable & AnyObject> : Hashable, Equatable {
public weak var value : T?
public init (_ value: T) {
self.value = value
}
public var hashValue : Int {
return value?.hashValue ?? 0
}
public static func ==(lhs: WeakHashable<T>, rhs: WeakHashable<T>) -> Bool {
return lhs.value != nil && rhs.value != nil && lhs.value! == rhs.value!
}
}
| 19.837838 | 79 | 0.580381 |
5b06f3414a1a5672a579bb8adca42e16f6bd86b9 | 893 | //
// RedditListingServiceManager.swift
// RedditReader
//
// Created by Alfonso Mestre on 29/5/21.
//
import Foundation
final class RedditListingServiceManager {
private var serviceProvider: RedditListingServiceProtocol
init(serviceProvider: RedditListingServiceProtocol = RedditListingService(NetworkingURLSession())) {
self.serviceProvider = serviceProvider
}
func getReddits(topic: Topic, after: String?, count: Int, completion: @escaping(Result<Listing, NetworkingError>) -> Void) {
self.serviceProvider.getReddits(topic: topic, after: after, count: count) { (result) in
completion(result)
}
}
func getImage(imageUrl: String, completion: @escaping(Result<Data, NetworkingError>) -> Void) {
self.serviceProvider.getImage(imageUrl: imageUrl) { (result) in
completion(result)
}
}
}
| 29.766667 | 128 | 0.68981 |
14ac3a387dc6af834b246e1516b98587c4453809 | 475 | //
// SYImageListCollectionViewCell.swift
// SYBasicTools
//
// Created by Yunis on 2022/5/30.
//
import UIKit
class SYImageListCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var rightConstraint: NSLayoutConstraint!
@IBOutlet weak var baseView: UIView!
@IBOutlet weak var imageVIew: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 20.652174 | 59 | 0.738947 |
1c58f3225c25bad354501d5e4fc3790f2c8dca72 | 242 | // 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 end = [ {
return ( ) { func a {
struct S {
protocol P {
class
case ,
| 22 | 87 | 0.714876 |
91f64a14444fbb8ee99daf8264c051f39640c921 | 1,266 | //
// SDThemPopViewDemoUITests.swift
// SDThemPopViewDemoUITests
//
// Created by pangxiang on 5/8/18.
// Copyright © 2018 pangxiang. All rights reserved.
//
import XCTest
class SDThemPopViewDemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.216216 | 182 | 0.669826 |
71eb1630d9f1c824f74f9ca44fd65f72899d50d8 | 2,137 | //
// AppDelegate.swift
// ios-metal
//
// Created by Emiliano on 4/25/16.
// Copyright © 2016 Emiliano. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.468085 | 285 | 0.753393 |
3a4c37fd578081adbf1d11c9ff4bd891af5ecd0e | 1,419 | // Test that when:
//
// 1. Using -incremental -v -driver-show-incremental, and...
// 2. ...the arguments passed to the Swift compiler version differ from the ones
// used in the original compilation...
//
// ...then the driver prints a message indicating that incremental compilation
// is disabled.
// RUN: rm -rf %t && cp -r %S/Inputs/one-way/ %t
// RUN: %S/Inputs/touch.py 443865900 %t/*
// RUN: echo '{version: "'$(%swiftc_driver_plain -version | head -n1)'", inputs: {"./main.swift": [443865900, 0], "./other.swift": [443865900, 0]}}' > %t/main~buildrecord.swiftdeps
// RUN: cd %t && %swiftc_driver -driver-use-frontend-path %S/Inputs/update-dependencies.py -c ./main.swift ./other.swift -module-name main -incremental -v -driver-show-incremental -output-file-map %t/output.json | %FileCheck --check-prefix CHECK-INCREMENTAL %s
// CHECK-INCREMENTAL-NOT: Incremental compilation has been disabled
// CHECK-INCREMENTAL: Queuing (initial): {compile: main.o <= main.swift}
// RUN: cd %t && %swiftc_driver -driver-use-frontend-path %S/Inputs/update-dependencies.py -g -c ./main.swift ./other.swift -module-name main -incremental -v -driver-show-incremental -output-file-map %t/output.json | %FileCheck --check-prefix CHECK-ARGS-MISMATCH %s
// CHECK-ARGS-MISMATCH: Incremental compilation has been disabled{{.*}}different arguments
// CHECK-ARGS-MISMATCH-NOT: Queuing (initial): {compile: main.o <= main.swift}
| 61.695652 | 265 | 0.711769 |
767756e6c8bac032d4d1ecf77cc26dd0fb32b978 | 650 | //
// PrivateKeyWIF.swift
// EllipticCurveKit
//
// Created by Alexander Cyon on 2018-07-09.
// Copyright © 2018 Alexander Cyon. All rights reserved.
//
import Foundation
/// WIF == Wallet Import Format
public struct PrivateKeyWIF<System: DistributedSystem> {
let compressed: Base58String
let uncompressed: Base58String
public init(privateKey: PrivateKeyType, system: System) {
uncompressed = system.wifUncompressed(from: privateKey)
compressed = system.wifCompressed(from: privateKey)
}
}
public extension PrivateKeyWIF {
typealias Curve = System.Curve
typealias PrivateKeyType = PrivateKey<Curve>
}
| 24.074074 | 63 | 0.727692 |
754ed28745c553aff69230bd4ad36b53051dc652 | 3,668 | import Foundation
import XCTest
@testable import NIO
@testable import Metrics
@testable import SwiftBoxMetricsStatsD
class StatsDHandlerTests: XCTestCase {
class FakeStatsDClient: StatsDClientProtocol {
public var gatheredMetrics: Array<String> = []
func pushMetric(metricLine: String) {
self.gatheredMetrics.append(metricLine)
}
}
func testHandlerShouldGatherTimerMetrics() throws {
let client = FakeStatsDClient()
let handler = try StatsDMetricsFactory(
baseMetricPath: "com.allegro"
) { path in
StatsDMetricsHandler(path: path, client: client)
}
let timer = handler.makeTimer(label: "stats.timer", dimensions: [])
timer.recordNanoseconds(1_010_000)
let metric = client.gatheredMetrics[0]
XCTAssertEqual(metric, "com.allegro.stats.timer:1.01|ms")
}
func testHandlerShouldGatherRecorderMetrics() throws {
let client = FakeStatsDClient()
let handler = try StatsDMetricsFactory(
baseMetricPath: "com.allegro"
) { path in
StatsDMetricsHandler(path: path, client: client)
}
let recorder = handler.makeRecorder(label: "stats.recorder", dimensions: [], aggregate: false)
recorder.record(Int64(11))
let metric = client.gatheredMetrics[0]
XCTAssertEqual(metric, "com.allegro.stats.recorder:11.0|g")
}
func testHandlerShouldGatherCounterMetrics() throws {
let client = FakeStatsDClient()
let handler = try StatsDMetricsFactory(
baseMetricPath: "com.allegro"
) { path in
StatsDMetricsHandler(path: path, client: client)
}
let counter = handler.makeCounter(label: "stats.counter", dimensions: [])
counter.increment(by: 11)
let metric = client.gatheredMetrics[0]
XCTAssertEqual(metric, "com.allegro.stats.counter:11|c")
}
func testHandlerShouldValidateBasePath() throws {
XCTAssertTrue(StatsDMetricsFactory.validateBasePath("example"))
XCTAssertTrue(StatsDMetricsFactory.validateBasePath("example.com"))
XCTAssertTrue(StatsDMetricsFactory.validateBasePath("example.com.test"))
XCTAssertTrue(StatsDMetricsFactory.validateBasePath("example.com.test"))
XCTAssertFalse(StatsDMetricsFactory.validateBasePath("example..com"))
XCTAssertFalse(StatsDMetricsFactory.validateBasePath("example.com."))
XCTAssertFalse(StatsDMetricsFactory.validateBasePath("example com test"))
}
func testHandlerShouldThrowWhenBasePathIsWrong() throws {
let client = FakeStatsDClient()
XCTAssertThrowsError(
try StatsDMetricsFactory(
baseMetricPath: "com."
) { path in
StatsDMetricsHandler(path: path, client: client)
}
) { error in
XCTAssertTrue(error is InvalidConfigurationError)
XCTAssertTrue((error as! InvalidConfigurationError).message.contains("Invalid base path"))
}
}
static var allTests: [(String, (StatsDHandlerTests) -> () throws -> Void)] {
return [
("testHandlerShouldGatherTimerMetrics", testHandlerShouldGatherTimerMetrics),
("testHandlerShouldGatherRecorderMetrics", testHandlerShouldGatherRecorderMetrics),
("testHandlerShouldGatherCounterMetrics", testHandlerShouldGatherCounterMetrics),
("testHandlerShouldValidateBasePath", testHandlerShouldValidateBasePath),
("testHandlerShouldThrowWhenBasePathIsWrong", testHandlerShouldThrowWhenBasePathIsWrong),
]
}
}
| 38.208333 | 102 | 0.675845 |
f544034d30a23a81cf5415c8cd4e7f2562ba5aa6 | 12,210 | protocol BMCView: AnyObject {
func update(sections: [BMCSection])
func delete(at indexPaths: [IndexPath])
func insert(at indexPaths: [IndexPath])
func conversionFinished(success: Bool)
}
enum BMCShareCategoryStatus {
case success(URL)
case error(title: String, text: String)
}
final class BMCDefaultViewModel: NSObject {
private let manager = BookmarksManager.shared()
weak var view: BMCView?
private var sections: [BMCSection] = []
private var permissions: [BMCPermission] = []
private var categories: [BookmarkGroup] = []
private var actions: [BMCAction] = []
private var notifications: [BMCNotification] = []
private(set) var isPendingPermission = false
private var isAuthenticated = false
private var filesPrepared = false
typealias OnPreparedToShareHandler = (BMCShareCategoryStatus) -> Void
private var onPreparedToShareCategory: OnPreparedToShareHandler?
let minCategoryNameLength: UInt = 0
let maxCategoryNameLength: UInt = 60
override init() {
super.init()
reloadData()
}
private func setPermissions() {
isAuthenticated = User.isAuthenticated()
if !isAuthenticated {
Statistics.logEvent(kStatBookmarksSyncProposalShown, withParameters: [kStatHasAuthorization: 0])
permissions = [.signup]
} else if !manager.isCloudEnabled() {
Statistics.logEvent(kStatBookmarksSyncProposalShown, withParameters: [kStatHasAuthorization: 1])
isPendingPermission = false
permissions = [.backup]
} else {
isPendingPermission = false
permissions = [.restore(manager.lastSynchronizationDate())]
}
}
private func setCategories() {
categories = manager.userCategories()
}
private func setActions() {
actions = [.create]
}
private func setNotifications() {
notifications = [.load]
}
func reloadData() {
sections = []
// sections.append(.permissions)
// setPermissions()
if manager.areBookmarksLoaded() {
sections.append(.categories)
setCategories()
sections.append(.actions)
setActions()
} else {
sections.append(.notifications)
setNotifications()
}
view?.update(sections: [])
}
}
extension BMCDefaultViewModel {
func numberOfSections() -> Int {
return sections.count
}
func sectionType(section: Int) -> BMCSection {
return sections[section]
}
func sectionIndex(section: BMCSection) -> Int {
return sections.firstIndex(of: section)!
}
func numberOfRows(section: Int) -> Int {
return numberOfRows(section: sectionType(section: section))
}
func numberOfRows(section: BMCSection) -> Int {
switch section {
case .permissions: return permissions.count
case .categories: return categories.count
case .actions: return actions.count
case .notifications: return notifications.count
}
}
func permission(at index: Int) -> BMCPermission {
return permissions[index]
}
func category(at index: Int) -> BookmarkGroup {
return categories[index]
}
func action(at index: Int) -> BMCAction {
return actions[index]
}
func notification(at index: Int) -> BMCNotification {
return notifications[index]
}
func areAllCategoriesHidden() -> Bool {
var result = true
categories.forEach { if $0.isVisible { result = false } }
return result
}
func updateAllCategoriesVisibility(isShowAll: Bool) {
manager.setUserCategoriesVisible(isShowAll)
}
func addCategory(name: String) {
guard let section = sections.firstIndex(of: .categories) else {
assertionFailure()
return
}
categories.append(manager.category(withId: manager.createCategory(withName: name)))
view?.insert(at: [IndexPath(row: categories.count - 1, section: section)])
}
func deleteCategory(at index: Int) {
guard let section = sections.firstIndex(of: .categories) else {
assertionFailure()
return
}
let category = categories[index]
categories.remove(at: index)
manager.deleteCategory(category.categoryId)
view?.delete(at: [IndexPath(row: index, section: section)])
}
func checkCategory(name: String) -> Bool {
return manager.checkCategoryName(name)
}
func shareCategoryFile(at index: Int, handler: @escaping OnPreparedToShareHandler) {
let category = categories[index]
onPreparedToShareCategory = handler
manager.shareCategory(category.categoryId)
}
func finishShareCategory() {
manager.finishShareCategory()
onPreparedToShareCategory = nil
}
func pendingPermission(isPending: Bool) {
isPendingPermission = isPending
setPermissions()
view?.update(sections: [.permissions])
}
func grant(permission: BMCPermission?) {
if let permission = permission {
switch permission {
case .signup:
assertionFailure()
case .backup:
Statistics.logEvent(kStatBookmarksSyncProposalApproved,
withParameters: [
kStatNetwork: Statistics.connectionTypeString(),
kStatHasAuthorization: isAuthenticated ? 1 : 0
])
manager.setCloudEnabled(true)
case .restore:
assertionFailure("Not implemented")
}
}
pendingPermission(isPending: false)
}
func convertAllKMLIfNeeded() {
let count = manager.filesCountForConversion()
if count > 0 {
MWMAlertViewController.activeAlert().presentConvertBookmarksAlert(withCount: count) { [weak self] in
MWMAlertViewController.activeAlert().presentSpinnerAlert(withTitle: L("converting"),
cancel: nil)
self?.manager.convertAll()
}
}
}
func addToObserverList() {
manager.add(self)
}
func removeFromObserverList() {
manager.remove(self)
}
func setNotificationsEnabled(_ enabled: Bool) {
manager.setNotificationsEnabled(enabled)
}
func areNotificationsEnabled() -> Bool {
return manager.areNotificationsEnabled()
}
func requestRestoring() {
let statusStr: String
switch NetworkPolicy.shared().connectionType {
case .none:
statusStr = kStatOffline
case .wifi:
statusStr = kStatWifi
case .cellular:
statusStr = kStatMobile
}
Statistics.logEvent(kStatBookmarksRestoreProposalClick, withParameters: [kStatNetwork: statusStr])
manager.requestRestoring()
}
func applyRestoring() {
manager.applyRestoring()
Statistics.logEvent(kStatBookmarksRestoreProposalSuccess)
}
func cancelRestoring() {
if filesPrepared {
return
}
manager.cancelRestoring()
Statistics.logEvent(kStatBookmarksRestoreProposalCancel)
}
func showSyncErrorMessage() {
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("error_server_title"),
message: L("error_server_message"),
rightButtonTitle: L("try_again"),
leftButtonTitle: L("cancel")) {
[weak self] in
self?.requestRestoring()
}
}
}
extension BMCDefaultViewModel: BookmarksObserver {
func onBackupStarted() {
Statistics.logEvent(kStatBookmarksSyncStarted)
}
func onRestoringStarted() {
filesPrepared = false
MWMAlertViewController.activeAlert().presentSpinnerAlert(withTitle: L("bookmarks_restore_process")) { [weak self] in self?.cancelRestoring() }
}
func onRestoringFilesPrepared() {
filesPrepared = true
}
func onSynchronizationFinished(_ result: MWMSynchronizationResult) {
MWMAlertViewController.activeAlert().closeAlert { [weak self] in
guard let s = self else { return }
switch result {
case .invalidCall:
s.showSyncErrorMessage()
Statistics.logEvent(kStatBookmarksSyncError, withParameters: [kStatType: kStatInvalidCall])
case .networkError:
s.showSyncErrorMessage()
Statistics.logEvent(kStatBookmarksSyncError, withParameters: [kStatType: kStatNetwork])
case .authError:
s.showSyncErrorMessage()
Statistics.logEvent(kStatBookmarksSyncError, withParameters: [kStatType: kStatAuth])
case .diskError:
MWMAlertViewController.activeAlert().presentInternalErrorAlert()
Statistics.logEvent(kStatBookmarksSyncError, withParameters: [kStatType: kStatDisk])
case .userInterrupted:
Statistics.logEvent(kStatBookmarksSyncError, withParameters: [kStatType: kStatUserInterrupted])
case .success:
s.reloadData()
Statistics.logEvent(kStatBookmarksSyncSuccess)
@unknown default:
fatalError()
}
}
}
func onRestoringRequest(_ result: MWMRestoringRequestResult, deviceName name: String?, backupDate date: Date?) {
MWMAlertViewController.activeAlert().closeAlert {
switch result {
case .noInternet: MWMAlertViewController.activeAlert().presentNoConnectionAlert()
case .backupExists:
guard let date = date else {
assertionFailure()
return
}
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .none
let deviceName = name ?? ""
let message = String(coreFormat: L("bookmarks_restore_message"),
arguments: [formatter.string(from: date), deviceName])
let cancelAction = { [weak self] in self?.cancelRestoring() } as MWMVoidBlock
MWMAlertViewController.activeAlert().presentRestoreBookmarkAlert(withMessage: message,
rightButtonAction: { [weak self] in
MWMAlertViewController.activeAlert().presentSpinnerAlert(withTitle: L("bookmarks_restore_process"),
cancel: cancelAction)
self?.applyRestoring()
}, leftButtonAction: cancelAction)
case .noBackup:
Statistics.logEvent(kStatBookmarksRestoreProposalError,
withParameters: [kStatType: kStatNoBackup, kStatError: ""])
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("bookmarks_restore_empty_title"),
message: L("bookmarks_restore_empty_message"),
rightButtonTitle: L("ok"),
leftButtonTitle: nil,
rightButtonAction: nil)
case .notEnoughDiskSpace:
Statistics.logEvent(kStatBookmarksRestoreProposalError,
withParameters: [kStatType: kStatDisk, kStatError: "Not enough disk space"])
MWMAlertViewController.activeAlert().presentNotEnoughSpaceAlert()
case .requestError:
assertionFailure()
}
}
}
func onBookmarksLoadFinished() {
reloadData()
convertAllKMLIfNeeded()
}
func onBookmarkDeleted(_: MWMMarkID) {
reloadData()
}
func onBookmarksCategoryFilePrepared(_ status: BookmarksShareStatus) {
switch status {
case .success:
onPreparedToShareCategory?(.success(manager.shareCategoryURL()))
case .emptyCategory:
onPreparedToShareCategory?(.error(title: L("bookmarks_error_title_share_empty"), text: L("bookmarks_error_message_share_empty")))
case .archiveError: fallthrough
case .fileError:
onPreparedToShareCategory?(.error(title: L("dialog_routing_system_error"), text: L("bookmarks_error_message_share_general")))
}
}
func onConversionFinish(_ success: Bool) {
setCategories()
view?.update(sections: [.categories])
view?.conversionFinished(success: success)
}
}
| 32.216359 | 173 | 0.641769 |
f82edee10654096814af4985786e0a91d62170cf | 1,526 | //
// Extensions.swift
// EthereumAddress
//
// Created by Alex Vlasov on 25/10/2018.
// Copyright © 2018 Alex Vlasov. All rights reserved.
//
import Foundation
extension Array where Element == UInt8 {
init(hex: String) {
self.init()
self.reserveCapacity(hex.unicodeScalars.lazy.underestimatedCount)
var buffer: UInt8?
var skip = hex.hasPrefix("0x") ? 2 : 0
for char in hex.unicodeScalars.lazy {
guard skip == 0 else {
skip -= 1
continue
}
guard char.value >= 48 && char.value <= 102 else {
removeAll()
return
}
let v: UInt8
let c: UInt8 = UInt8(char.value)
switch c {
case let c where c <= 57:
v = c - 48
case let c where c >= 65 && c <= 70:
v = c - 55
case let c where c >= 97:
v = c - 87
default:
removeAll()
return
}
if let b = buffer {
append(b << 4 | v)
buffer = nil
} else {
buffer = v
}
}
if let b = buffer {
append(b)
}
}
func toHexString() -> String {
return `lazy`.reduce("") {
var s = String($1, radix: 16)
if s.count == 1 {
s = "0" + s
}
return $0 + s
}
}
}
| 25.016393 | 73 | 0.410223 |
23860b62733d3f43b7e6975d1e4886a4694758aa | 1,347 | //
// AppDelegate.swift
// Prework
//
// Created by Mimi Ogunyemi on 1/24/22.
//
import UIKit
@main
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.
}
}
| 36.405405 | 179 | 0.74536 |
d5315ab8c811d75f5919618e37f4bdca1a80ec58 | 2,567 | //
// User.swift
// Twitter Client
//
// Created by Sean McRoskey on 4/14/17.
// Copyright © 2017 codepath. All rights reserved.
//
import Foundation
class User: NSObject{
private static let currentUserKey = "k_currentUser"
var profileImageUrl: URL!
var name: String!
var handle: String!
var jsonDictionary: NSDictionary!
static var _current: User?
class var current: User? {
get {
if (_current == nil){
if let currentUserData = UserDefaults.standard.data(forKey: currentUserKey){
let currentUserDictionary = try! JSONSerialization.jsonObject(with: currentUserData, options: []) as! NSDictionary
_current = User(dictionary: currentUserDictionary)
}
}
return _current
}
set(newUser){
_current = newUser
if let currentUser = _current {
let currentUserData = try! JSONSerialization.data(withJSONObject: currentUser.jsonDictionary, options: [])
UserDefaults.standard.set(currentUserData, forKey: currentUserKey)
UserDefaults.standard.synchronize()
} else {
UserDefaults.standard.removeObject(forKey: currentUserKey)
}
}
}
init(dictionary: NSDictionary!){
profileImageUrl = URL(string: dictionary["profile_image_url_https"] as! String)
name = dictionary["name"] as? String
handle = "@\((dictionary["screen_name"] as! String))"
jsonDictionary = dictionary
}
func retweet(_ tweet:Tweet, completion: @escaping (Tweet) -> Void, failure: @escaping (Error) -> Void){
TwitterClient.sharedInstance.retweet(tweet, completion: completion, failure: failure)
}
func logout(){
TwitterClient.sharedInstance.logout()
}
func tweet(_ text:String, completion: @escaping (Tweet) -> Void, failure: @escaping (Error) -> Void){
TwitterClient.sharedInstance.tweet(text, completion: completion, failure: failure)
}
func replyTo(_ tweet:Tweet, text: String, completion: @escaping (Tweet) -> Void, failure: @escaping (Error) -> Void){
TwitterClient.sharedInstance.replyTo(tweet, text: text, completion: completion, failure: failure)
}
func favorite(_ tweet:Tweet, completion: @escaping (Tweet) -> Void, failure: @escaping (Error) -> Void){
TwitterClient.sharedInstance.favorite(tweet, completion: completion, failure: failure)
}
}
| 34.689189 | 134 | 0.62836 |
61f8dda3645f82045807f4056a92df7da5cd5353 | 521 | // 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{{let:A
let h{
func a{b{
var:{{
}
{
g a{
var b{{{
class B{let:{{class B{
class a{
let c{
var b{{
func a{
func a{
h=
{
| 20.84 | 79 | 0.706334 |
388d61faf8ec9f4c30fa9e5bf38ad7f4db751f25 | 5,568 | //
// ViewController.swift
// Aula12_02
//
// Created by SP11793 on 22/03/22.
//
import UIKit
class ViewController: UIViewController {
private enum Defaults {
static let textInfo = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
static let textButton = "Call View"
static let textLabel = "Label centralizada"
}
var safeArea: UILayoutGuide!
lazy var iconImageView: UIImageView = {
let icon = UIImageView()
icon.image = UIImage(systemName: "gamecontroller")
icon.translatesAutoresizingMaskIntoConstraints = false
return icon
}()
lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 13)
label.text = Defaults.textInfo
label.textAlignment = .left
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var callButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitle(Defaults.textButton, for: .normal)
button.backgroundColor = .systemBlue
button.setTitleColor(UIColor.white, for: .normal)
button.addTarget(self, action: #selector(getView), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
lazy var content: UIView = {
let view = UIView()
view.backgroundColor = .systemIndigo
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var descriptionLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = .white
label.text = Defaults.textLabel
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
@objc func getView() {
print("Botão clicado")
}
// MARK: - Private Methods
private func addSubViews() {
view.addSubview(iconImageView)
view.addSubview(titleLabel)
view.addSubview(callButton)
view.addSubview(content)
content.addSubview(descriptionLabel)
}
private func configureIconImageView() {
NSLayoutConstraint.activate([
iconImageView.topAnchor.constraint(equalTo: safeArea.topAnchor, constant: 10),
iconImageView.heightAnchor.constraint(equalToConstant: 70),
iconImageView.widthAnchor.constraint(equalToConstant: 100),
iconImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
private func configureTitleLabel() {
titleLabel.topAnchor.constraint(equalTo: iconImageView.bottomAnchor, constant: Metrics.Margin.default).isActive = true
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Metrics.Margin.default).isActive = true
titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.Margin.default).isActive = true
}
private func configureCallButton() {
NSLayoutConstraint.activate([
callButton.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: Metrics.Margin.default),
callButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Metrics.Margin.default),
callButton.heightAnchor.constraint(equalToConstant: Metrics.Margin.input),
callButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.Margin.default)
])
}
private func configureContentView() {
NSLayoutConstraint.activate([
content.topAnchor.constraint(equalTo: callButton.bottomAnchor, constant: Metrics.Margin.default),
content.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Metrics.Margin.default),
content.heightAnchor.constraint(equalToConstant: 200),
content.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.Margin.default)
])
}
private func configureDescriptionLabel() {
NSLayoutConstraint.activate([
descriptionLabel.centerXAnchor.constraint(equalTo: content.centerXAnchor),
descriptionLabel.centerYAnchor.constraint(equalTo: content.centerYAnchor)
])
}
override func viewDidLoad() {
super.viewDidLoad()
safeArea = view.layoutMarginsGuide
// button.setTitle("Button view", for: .normal)
// button.frame = CGRect(x: 16, y: 100, width: 130, height: 45)
// button.backgroundColor = .darkGray
//
// view.addSubview(button)
addSubViews()
configureIconImageView()
configureTitleLabel()
configureCallButton()
configureContentView()
configureDescriptionLabel()
title = "Using View Code"
view.backgroundColor = .white
}
}
| 37.621622 | 606 | 0.673132 |
9005f58e9fd0f4c09504e5934b98e1726a436064 | 731 | /* Шахматная доска (Легкий уровень)
1. Создайте тип шахматная доска.
2. Добавьте сабскрипт, который выдает цвет клетки по координате клетки (буква и цифра).
3. Если юзер ошибся координатами - выдавайте нил */
struct ChessBoard {
subscript(row: Int, column: String) -> String? {
let error = "Incorrect enter data"
if row <= 0 || row > 8 { return error }
let columns = ["a", "b", "c", "d", "e", "f", "g", "h"]
let column = columns.indexOf(column)
if let column = column {
return row % 2 == column % 2 ? "White" : "Black"
} else {
return error
}
}
}
let chessBoard = ChessBoard()
chessBoard[1, "e"]
chessBoard[8, "e"]
chessBoard[0, "e"]
chessBoard[15, "e"]
chessBoard[5, "j"]
| 24.366667 | 87 | 0.612859 |
16f88046a67aae0acea640a5411ccf05bddc2e4e | 5,537 | //
// Copyright © 2020 Optimize Fitness Inc.
// Licensed under the MIT license
// https://github.com/OptimizeFitness/Minerva/blob/master/LICENSE
//
import Foundation
import Minerva
import RxRelay
import RxSwift
import UIKit
public final class CreateUserPresenter: ListPresenter {
public enum Action {
case create(email: String, password: String, dailyCalories: Int32, role: UserRole)
}
private static let emailCellModelIdentifier = "emailCellModelIdentifier"
private static let passwordCellModelIdentifier = "passwordCellModelIdentifier"
private static let caloriesCellModelIdentifier = "caloriesCellModelIdentifier"
private let actionsRelay = PublishRelay<Action>()
public var actions: Observable<Action> { actionsRelay.asObservable() }
public var sections = BehaviorRelay<[ListSection]>(value: [])
private let disposeBag = DisposeBag()
private var email: String = ""
private var password: String = ""
private var dailyCalories: Int32 = 2_000
private var role: UserRole = .user
public init() {
sections.accept([createSection()])
}
// MARK: - Private
private func createSection() -> ListSection {
let cellModels = loadCellModels()
let section = ListSection(cellModels: cellModels, identifier: "SECTION")
return section
}
private func loadCellModels() -> [ListCellModel] {
let doneModel = SelectableLabelCellModel(identifier: "doneModel", text: "Save", font: .title1)
doneModel.directionalLayoutMargins.leading = 0
doneModel.directionalLayoutMargins.trailing = 0
doneModel.textAlignment = .center
doneModel.textColor = .selectable
doneModel.selectionAction = { [weak self] _, _ -> Void in
guard let strongSelf = self else { return }
let action = Action.create(
email: strongSelf.email,
password: strongSelf.password,
dailyCalories: strongSelf.dailyCalories,
role: strongSelf.role
)
strongSelf.actionsRelay.accept(action)
}
return [
MarginCellModel(identifier: "headerMarginModel"),
createEmailCellModel(),
MarginCellModel(identifier: "emailMarginModel", height: 12),
createCaloriesCellModel(),
MarginCellModel(identifier: "passwordMarginModel", height: 12),
createPasswordCellModel(),
MarginCellModel(identifier: "caloriesMarginModel", height: 12),
createRoleCellModel(),
MarginCellModel(identifier: "roleMarginModel", height: 12),
doneModel,
MarginCellModel(identifier: "doneMarginModel")
]
}
private func createEmailCellModel() -> ListCellModel {
let cellModel = TextInputCellModel(
identifier: CreateUserPresenter.emailCellModelIdentifier,
placeholder: "Email",
font: .subheadline
)
cellModel.text = email
cellModel.keyboardType = .emailAddress
cellModel.textContentType = .emailAddress
cellModel.cursorColor = .selectable
cellModel.textColor = .black
cellModel.inputTextColor = .black
cellModel.placeholderTextColor = .gray
cellModel.bottomBorderColor.onNext(.black)
cellModel.textInputAction = { [weak self] _, text in
guard let text = text else { return }
self?.email = text
}
return cellModel
}
private func createCaloriesCellModel() -> ListCellModel {
let cellModel = TextInputCellModel(
identifier: CreateUserPresenter.caloriesCellModelIdentifier,
placeholder: "Daily Calories",
font: .subheadline
)
cellModel.text = dailyCalories > 0 ? String(dailyCalories) : nil
cellModel.keyboardType = .numberPad
cellModel.cursorColor = .selectable
cellModel.textColor = .black
cellModel.inputTextColor = .black
cellModel.placeholderTextColor = .gray
cellModel.bottomBorderColor.onNext(.black)
cellModel.textInputAction = { [weak self] _, text in
guard let text = text, let calories = Int32(text) else { return }
self?.dailyCalories = calories
}
return cellModel
}
private func createPasswordCellModel() -> ListCellModel {
let inputFont = UIFont.headline
let cellModel = TextInputCellModel(
identifier: CreateUserPresenter.passwordCellModelIdentifier,
placeholder: "Password",
font: inputFont
)
cellModel.keyboardType = .asciiCapable
cellModel.isSecureTextEntry = true
cellModel.textContentType = .password
cellModel.autocorrectionType = .no
cellModel.cursorColor = .selectable
cellModel.inputTextColor = .black
cellModel.placeholderTextColor = .darkGray
cellModel.bottomBorderColor.onNext(.black)
cellModel.textInputAction = { [weak self] _, text in
guard let text = text else { return }
self?.password = text
}
return cellModel
}
private func createRoleCellModel() -> ListCellModel {
let roleData = UserRole.allCases.map { role -> PickerDataRow in
let text = NSAttributedString(string: role.description)
return PickerDataRow(text: text, imageData: nil)
}
let startingRow = role.rawValue - 1
let componentData = PickerDataComponent(
data: roleData,
textAlignment: .center,
verticalMargin: 8,
startingRow: startingRow
)
let pickerModel = PickerCellModel(
identifier: "rolePickerCellModel",
pickerDataComponents: [componentData]
) { [weak self] _, _, row, _ -> Void in
guard let role = UserRole(rawValue: row + 1) else {
assertionFailure("Role should exist at row \(row)")
return
}
self?.role = role
}
return pickerModel
}
}
| 32.763314 | 98 | 0.7067 |
50c7e80862d10fbf2a54b2a8703fc43748614c95 | 1,244 | import SwiftUI
extension View {
public func eraseToAnyView() -> some View {
AnyView(self)
}
}
extension View {
@ViewBuilder
public func embeddedInScrollView(when condition: Bool) -> some View {
if condition {
ScrollView {
self
}
} else {
self
}
}
@ViewBuilder
public func overlayIf<Overlay: View>(_ condition: Bool, content: @escaping () -> Overlay) -> some View {
ZStack {
self
if condition {
content()
}
}
}
}
extension View {
public func fillParentWidth(alignment: Alignment = .center) -> some View {
return GeometryReader { geometry in
self.frame(width: geometry.size.width, height: nil, alignment: alignment)
}
}
}
#if canImport(UIKit)
@available(iOSApplicationExtension, unavailable)
extension View {
public func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
public func endEditing(_ force: Bool) {
UIApplication.shared.windows.forEach {
$0.endEditing(force)
}
}
}
#endif
| 23.037037 | 114 | 0.575563 |
015eec015a5697661399f6b69db0e4dd1739599c | 3,590 | //
// MKAuthcodeView.swift
// MKSwiftRes
//
// Created by miaokii on 2021/1/28.
//
import UIKit
fileprivate class CodeField: UITextField {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
/// 验证码视图
public class MKAuthcodeView: MKView {
/// 验证码位数
public var codeDigit: Int = 4
/// 验证码之间间距
public var codeSpace: CGFloat = 10
/// 号码背景颜色
public var codeNumBgColor: UIColor = .table_bg
/// 号码颜色
public var codeNumColor = UIColor.text_l1
/// 字体
public var codeFont = UIFont.boldSystemFont(ofSize: 20)
/// 圆角
public var cradius: CGFloat = 3
/// 输入结束回调
public var codeClosure: ((String)->Void)?
public var code: String {
return codeField.text ?? ""
}
private var inited = false
private var codeField: CodeField!
public override func setup() {
codeField = CodeField.init(super: self,
textColor: .clear,
tintColor: .clear,
backgroundColor: .clear,
keyboardType: .numberPad)
codeField.snp.makeConstraints({ $0.edges.equalTo(0) })
codeField.addTarget(self, action: #selector(codeFieldTextChanged), for: .editingChanged)
codeField.addTarget(self, action: #selector(codeFieldEditBegin), for: .editingDidBegin)
clipsToBounds = true
}
@discardableResult public override func becomeFirstResponder() -> Bool {
codeField.becomeFirstResponder()
}
@objc private func codeFieldTextChanged() {
var codeString = codeField.text ?? ""
/// 给每一个label设置值
for i in 0..<codeDigit {
let codeLabel = codeField.viewWithTag(i+1) as! UILabel
if i < codeString.count {
codeLabel.text = String.init(codeString[i])
} else {
codeLabel.text = ""
}
}
/// 如果输入框超出了最大长度,就截取
if codeString.count >= codeDigit {
codeField.resignFirstResponder()
codeString = codeString[0..<codeDigit]
codeField.text = codeString
codeClosure?(codeString)
}
}
@objc private func codeFieldEditBegin() {
codeField.text = ""
guard inited else {
return
}
/// 给每一个label设置值
for i in 0..<codeDigit {
let codeLabel = codeField.viewWithTag(i+1) as! UILabel
codeLabel.text = ""
}
}
public override func layoutSubviews() {
super.layoutSubviews()
for i in 0..<codeDigit {
let codeLabel = UILabel.init(super: codeField,
textColor: codeNumColor,
font: codeFont,
aligment: .center)
codeLabel.backgroundColor = codeNumBgColor
codeLabel.tag = i+1
if cradius > 0 {
codeLabel.layer.cornerRadius = cradius
codeLabel.clipsToBounds = true
}
codeLabel.snp.makeConstraints { (make) in
make.centerY.centerY.equalToSuperview()
make.centerX.equalToSuperview().multipliedBy((CGFloat(i)*2+1)/CGFloat(codeDigit))
make.top.equalTo(5)
make.width.equalToSuperview().dividedBy(codeDigit).offset(-codeSpace)
}
}
inited = true
}
}
| 30.948276 | 97 | 0.543454 |
87f366f2abafd7a706cdcc5ed3a127fee89d57a8 | 1,430 | //
// Bookworm10UITests.swift
// Bookworm10UITests
//
// Created by Viettasc on 2/1/20.
// Copyright © 2020 Viettasc. All rights reserved.
//
import XCTest
class Bookworm10UITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 32.5 | 182 | 0.653846 |
9bf7203b16cac6e75caf7e48e2c6836a606c983b | 1,053 | //: ## Vector Arithmetic
//: This example shows how to perform basic vector operations on arrays
import Upsurge
//: Regular Swift arrays can be used to perform some arithmetic operations. Let's add all the elements in an array.
let array = [1.0, 2.0, 3.0, 4.0, 5.0]
let arraySum = sum(array)
//: Upsurge's `ValueArray`s are more powerful than regular Swift arrays for doing math. For instance, `ValueArray` overloads `+` and `+=` to mean addition, whereas for Swift arrays they mean concatenation. Let's define two `ValueArray`s and add them together.
let a: ValueArray<Double> = [1.0, 3.0, 5.0, 7.0]
let b: ValueArray<Double> = [2.0, 4.0, 6.0, 8.0]
let c = a + b
//: You can also perform operations that are unique to `ValueArray`. This is how you would compute the dot product between two arrays
let product = a • b
//: You can also perform operations on parts of an array using the usual slice syntax
let d = a[0..<2] + b[2..<4]
//: And you can of course mix operations into more elaborate expressions
let result = sqrt(a[0..<2] * 2 + a[2..<4] / 2)
| 61.941176 | 259 | 0.709402 |
e407e736e8ed2e6c58f360e527af4ca3c5e455d6 | 12,047 | //
// ViewController.swift
// CVReusable
//
// Created by caven on 2018/9/29.
// Copyright © 2018年 com.caven. All rights reserved.
//
import UIKit
enum HomeType {
case hot
case new
}
let space_line: CGFloat = 1
class ViewController: UIViewController {
var categary: CVReusableView!
var themeView: CVReusableView!
var left: UIButton!
var right: UIButton!
var type: HomeType = .hot
var hot_cate = ["你好\n中国", "上海\nShanghai", "河北\nHeBei", "广东\nGuangdong", "桂林\nGuiLin", "邢台\nXingtai", "北京\nBaeijing", "山西\nShanXI", "新疆\nXinJiang"]
var new_cate = [["用户分享", "新门户", "揍你", "亲子活动"], ["用户分享", "新门户", "揍你", "亲子活动"], ["用户分享", "新门户", "揍你", "亲子活动"]]
var new_cate_image = [["1", "2", "3", "4"], ["5", "6", "7", "8"], ["1", "2", "3", "4"]]
var hot_theme = [[["pic":"1", "title":"五一活动"], ["pic":"2", "title":"亲自活动"]], [["pic":"3", "title":"港澳行"]]]
var new_theme = [[["pic":"4", "title":"港澳行"], ["pic":"5", "title":"广场活动"]],
[["pic":"6", "title":"爱琴海旅行"]],
[["pic":"7", "title":"长城游"], ["pic":"8", "title":"古北水镇"]]]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(hue: 0xF2F2F2, saturation: 0.5, brightness: 0.5, alpha: 1)
left = UIButton(type: .custom)
left.setTitle("hot", for: .normal)
left.setTitleColor(UIColor.white, for: UIControl.State.normal)
left.backgroundColor = UIColor.red
left.tag = 100
left.addTarget(self, action: #selector(onClickChangeType(_:)), for: .touchUpInside)
self.view.addSubview(left)
right = UIButton(type: .custom)
right.setTitle("new", for: .normal)
right.setTitleColor(UIColor.white, for: UIControl.State.normal)
right.backgroundColor = UIColor.red
right.tag = 101
right.addTarget(self, action: #selector(onClickChangeType(_:)), for: .touchUpInside)
self.view.addSubview(right)
left.frame = CGRect(x: 0, y: 80, width: self.view.frame.width / 2, height: 40)
right.frame = CGRect(x: left.frame.maxX, y: 80, width: self.view.frame.width / 2, height: 40)
// 分类
self.categary = CVReusableView(frame: CGRect(x: 0, y: left.frame.maxY, width: self.view.frame.width, height: 200))
self.categary.backgroundColor = UIColor.white
self.categary.register(TestView.self, forItemReuseIdentifier: "TestView")
self.categary.register(CategaryView.self, forItemReuseIdentifier: "CategaryView")
self.categary.minimumLineSpacing = 1
self.categary.delegate = self
self.categary.dataSource = self
self.view.addSubview(self.categary)
// 主题
self.themeView = CVReusableView(frame: CGRect(x: 0, y: self.categary.frame.maxY + 10, width: self.view.frame.width, height: 200))
self.themeView.backgroundColor = UIColor.white
self.themeView.register(TestView.self, forItemReuseIdentifier: "TestView")
self.themeView.register(CategaryView.self, forItemReuseIdentifier: "CategaryView")
self.themeView.delegate = self
self.themeView.dataSource = self
self.themeView.minimumLineSpacing = 1
self.themeView.minimumInteritemSpacing = 1
self.view.addSubview(self.themeView)
self.onClickChangeType(left)
}
@objc func onClickChangeType(_ sender: UIButton) {
for i in 100..<102 {
let btn = self.view.viewWithTag(i) as! UIButton
btn.backgroundColor = UIColor.lightGray
}
sender.backgroundColor = UIColor.red
if sender.tag == 100 {
self.type = .hot
} else if sender.tag == 101 {
self.type = .new
}
if self.type == .hot {
self.categary.frame = CGRect(x: 0, y: left.frame.maxY + 10, width: self.view.frame.width, height: 60)
self.themeView.frame = CGRect(x: 0, y: self.categary.frame.maxY + 10, width: self.view.frame.width, height: 150)
} else if self.type == .new {
self.categary.frame = CGRect(x: 0, y: left.frame.maxY + 10, width: self.view.frame.width, height: 120)
self.themeView.frame = CGRect(x: 0, y: self.categary.frame.maxY + 10, width: self.view.frame.width, height: 225)
}
self.categary.reloadData()
self.themeView.reloadData()
}
}
extension ViewController : CVReusableViewDelegate, CVReusableViewDataSource {
func numberOfSection(in reusableView: CVReusableView) -> Int {
if self.type == .hot {
if self.categary == reusableView {
return 1
} else if self.themeView == reusableView {
return self.hot_theme.count
}
} else if self.type == .new {
if self.categary == reusableView {
return 2
} else if self.themeView == reusableView {
return self.new_theme.count
}
}
return 0
}
func reusableView(_ reusableView: CVReusableView, numberOfRowsInColumn column: Int) -> Int {
if self.type == .hot {
if self.categary == reusableView {
return self.hot_cate.count
} else if self.themeView == reusableView {
return self.hot_theme[column].count
}
} else if self.type == .new {
if self.categary == reusableView {
return self.new_cate[column].count
} else if self.themeView == reusableView {
return self.new_theme[column].count
}
}
return 0
}
func reusableView(_ reusableView: CVReusableView, sizeForRowAt indexPath: IndexPath) -> CGSize {
if self.type == .hot {
if self.categary == reusableView {
return CGSize(width: 60, height: 60)
} else if self.themeView == reusableView {
// 这里的theme有三个
if indexPath.section == 0 {
if indexPath.row == 0 { return CGSize(width: 150, height: 75) }
if indexPath.row == 1 { return CGSize(width: reusableView.frame.width - 150 - space_line, height: 150)}
} else if indexPath.section == 1 {
if indexPath.row == 0 { return CGSize(width: 150, height: 75 - space_line) }
}
return CGSize.zero
}
} else if self.type == .new {
if self.categary == reusableView {
let width = reusableView.frame.width / CGFloat(self.new_cate[indexPath.section].count)
return CGSize(width: width, height: reusableView.frame.height / 2)
} else if self.themeView == reusableView {
// 这里的theme有三个
if indexPath.section == 0 {
if indexPath.row == 0 { return CGSize(width: 150, height: 75) }
if indexPath.row == 1 { return CGSize(width: reusableView.frame.width - 150 - space_line, height: 150)}
} else if indexPath.section == 1 {
if indexPath.row == 0 { return CGSize(width: 150, height: 75 - space_line) }
} else if indexPath.section == 2 {
if indexPath.row == 0 { return CGSize(width: 150, height: 75 - space_line) }
if indexPath.row == 1 { return CGSize(width: reusableView.frame.width - 150 - space_line, height: 75 - space_line)}
}
}
}
return CGSize.zero
}
func reusableView(_ reusableView: CVReusableView, itemForRowAt indexPath: IndexPath) -> CVReusableViewItem {
if self.type == .hot {
if self.categary == reusableView {
let item = reusableView.dequeueReusableItem(withIdentifier: "TestView") as! TestView
item.titleLabel.text = self.hot_cate[indexPath.row]
return item
} else {
let ontTheme = self.hot_theme[indexPath.section][indexPath.row]
let item = reusableView.dequeueReusableItem(withIdentifier: "CategaryView") as! CategaryView
item.titleLabel.text = ontTheme["title"]
item.imageView.image = UIImage(named: ontTheme["pic"]!)
return item
}
} else if self.type == .new {
if self.categary == reusableView {
let oneCate = self.new_cate[indexPath.section][indexPath.row]
let oneCateImage = self.new_cate_image[indexPath.section][indexPath.row]
let item = reusableView.dequeueReusableItem(withIdentifier: "CategaryView") as! CategaryView
item.selectedStyle = .blue
item.titleLabel.text = oneCate
item.imageView.image = UIImage(named: oneCateImage)
return item
} else {
let ontTheme = self.new_theme[indexPath.section][indexPath.row]
let item = reusableView.dequeueReusableItem(withIdentifier: "CategaryView") as! CategaryView
item.titleLabel.text = ontTheme["title"]
item.imageView.image = UIImage(named: ontTheme["pic"]!)
return item
}
}
return CVReusableViewItem.init(frame: CGRect.zero)
}
func reusableView(_ reusableView: CVReusableView, didSelectRowAt indexPath: IndexPath) {
reusableView.deselectedItem(at: indexPath)
if self.type == .hot {
print(self.hot_cate[indexPath.row])
} else if self.type == .new {
print(self.new_cate[indexPath.section][indexPath.row])
}
}
}
class TestView: CVReusableViewItem {
var titleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(reuseIdentifier: String) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.orange
self.titleLabel = UILabel(frame: CGRect.zero)
self.titleLabel.textColor = UIColor.white
self.titleLabel.font = UIFont.systemFont(ofSize: 12)
self.titleLabel.textAlignment = .center
self.titleLabel.numberOfLines = 0
self.addSubview(self.titleLabel)
}
override func layoutSubviews() {
self.titleLabel.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
}
}
class CategaryView: CVReusableViewItem {
var imageView: UIImageView!
var titleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(reuseIdentifier: String) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.orange
self.titleLabel = UILabel(frame: CGRect.zero)
self.titleLabel.textColor = UIColor.white
self.titleLabel.font = UIFont.systemFont(ofSize: 14)
self.titleLabel.textAlignment = .center
self.titleLabel.numberOfLines = 0
self.addSubview(self.titleLabel)
self.imageView = UIImageView(frame: CGRect.zero)
self.imageView.contentMode = .scaleAspectFill
self.addSubview(self.imageView)
}
override func layoutSubviews() {
self.imageView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
self.imageView.center = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 - 10)
self.titleLabel.frame = CGRect(x: 0, y: self.imageView.frame.maxY + 5, width: self.frame.width, height: 15)
}
}
| 38.612179 | 150 | 0.582386 |
0937d588bbe269628c8d921eb7850010dc02a1f1 | 558 | // Plugins.swift
// Copyright (c) 2020 FastlaneTools
// This autogenerated file will be overwritten or replaced when installing/updating plugins or running "fastlane generate_swift"
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Foundation
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.56]
| 32.823529 | 128 | 0.750896 |
89de4d4d155b556d296606bf1aec1f2145a5acfb | 2,901 | //
// ColorizerTextFieldDelegate.swift
// ClickCounter
//
// Created by juan ocampo on 4/10/20.
// Copyright © 2020 juan ocampo. All rights reserved.
//
import Foundation
import UIKit
class ColorizerTextFieldDelegate: NSObject, UITextFieldDelegate {
// MARK: Properties
let colors: [String:UIColor] = [
"red": UIColor.red,
"orange": UIColor.orange,
"yellow": UIColor.yellow,
"green": UIColor.green,
"blue": UIColor.blue,
"brown": UIColor.brown,
"black": UIColor.black,
"purple": UIColor.purple,
"cyan" : UIColor.cyan,
"magenta" : UIColor.magenta,
"white" : UIColor.white
]
/**
* Examines the new string whenever the text changes. Finds color-words, blends them, and set the text color
*/
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var colorsInTheText = [UIColor]()
// Construct the text that will be in the field if this change is accepted
var newText = textField.text! as NSString
newText = newText.replacingCharacters(in: range, with: string) as NSString
// For each dictionary entry in translations, pull out a string to search for
for (key, color) in self.colors {
if newText.range(of: key, options: .caseInsensitive).location != NSNotFound {
colorsInTheText.append(color)
}
}
// If we found any colors then blend them and set the text color
if colorsInTheText.count > 0 {
textField.textColor = self.blendColorArray(colorsInTheText)
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
/**
* accepts an array of colors, and return a blend of all the elements
*/
func blendColorArray(_ colors: [UIColor]) -> UIColor {
var colorComponents: [CGFloat] = [CGFloat](repeating: 0.0, count: 4)
for color in colors {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
colorComponents[0] += red
colorComponents[1] += green
colorComponents[2] += blue
colorComponents[3] += alpha
}
for i in 0...colorComponents.count - 1 {
colorComponents[i] /= CGFloat(colors.count)
}
return UIColor(red: colorComponents[0], green: colorComponents[1], blue: colorComponents[2], alpha: colorComponents[3])
}
}
| 30.21875 | 129 | 0.576698 |
d68a788b124062aa5876d2a3481b4d82e81a8a27 | 320 | import EventKit
import Foundation
import PromiseKit
import XCTest
class Test_EventKit_Swift: XCTestCase {
func test() {
let ex = expectationWithDescription("")
EKEventStoreRequestAccess().then { _ in
ex.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
}
| 21.333333 | 55 | 0.665625 |
26a88d4c2c0a88d816a5adac71fb79e8194cc825 | 2,492 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "XercesSwift",
products: [
.library(
name: "XercesSwift",
targets: ["ObjCXercesSwift", "XercesSwift"]
)
],
dependencies: [],
targets: [
.systemLibrary(
name: "libxerces",
pkgConfig: "libxerces"
),
.target(
name: "ObjCXercesSwift",
path: "Sources/ObjC",
cxxSettings: [
.headerSearchPath("../XercesHeaders/src"),
.headerSearchPath("../XercesHeaders/src/xercesc/dom"),
.headerSearchPath("../XercesHeaders/src/xercesc/dom/impl"),
.headerSearchPath("../XercesHeaders/src/xercesc/framework"),
.headerSearchPath("../XercesHeaders/src/xercesc/framework/psvi"),
.headerSearchPath("../XercesHeaders/src/xercesc/internal"),
.headerSearchPath("../XercesHeaders/src/xercesc/parsers"),
.headerSearchPath("../XercesHeaders/src/xercesc/sax"),
.headerSearchPath("../XercesHeaders/src/xercesc/sax2"),
.headerSearchPath("../XercesHeaders/src/xercesc/util"),
.headerSearchPath("../XercesHeaders/src/xercesc/util/FileManagers"),
.headerSearchPath("../XercesHeaders/src/xercesc/util/MsgLoaders"),
.headerSearchPath("../XercesHeaders/src/xercesc/util/MutexManagers"),
.headerSearchPath("../XercesHeaders/src/xercesc/util/NetAccessors"),
.headerSearchPath("../XercesHeaders/src/xercesc/util/regx"),
.headerSearchPath("../XercesHeaders/src/xercesc/util/Transcoders"),
.headerSearchPath("../XercesHeaders/src/xercesc/validators"),
.headerSearchPath("../XercesHeaders/src/xercesc/validators/common"),
.headerSearchPath("../XercesHeaders/src/xercesc/validators/datatype"),
.headerSearchPath("../XercesHeaders/src/xercesc/validators/DTD"),
.headerSearchPath("../XercesHeaders/src/xercesc/validators/schema"),
.headerSearchPath("../XercesHeaders/src/xercesc/validators/schema/identity"),
.headerSearchPath("../XercesHeaders/src/xercesc/xinclude"),
]
),
.target(
name: "XercesSwift",
dependencies: ["ObjCXercesSwift"],
path: "Sources/Swift"
)
]
)
| 45.309091 | 93 | 0.583868 |
2934698ced1fe5e7e3e2b16918139037837ccd07 | 1,510 | import Vapor
import Fluent
import Foundation
final class Player: Model {
static let tableName = "players"
var id: Node?
var team_id: Node?
var firstname: String
var lastname: String
var number: Int
var position: String
init(node: Node, in context: Context) throws {
id = try node.extract("id")
team_id = try node.extract("team_id")
firstname = try node.extract("firstname")
lastname = try node.extract("lastname")
number = try node.extract("number")
position = try node.extract("position")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"team_id": team_id,
"firstname": firstname,
"lastname": lastname,
"number": number,
"position": position,
])
}
}
extension Player: Preparation {
static func prepare(_ database: Database) throws {
try database.create(Player.tableName) { player in
player.id()
player.parent(Team.self, optional: false, unique: false, default: nil)
player.string("firstName")
player.string("lastname")
player.int("number")
player.string("position")
}
}
static func revert(_ database: Database) throws {
try database.delete(Player.tableName)
}
}
extension Player {
func team() throws -> Parent<Team> {
return try parent(team_id)
}
}
| 26.034483 | 82 | 0.582119 |
f9b1cb3149a16a5a7335376c2708afd466658f11 | 243 | // RUN: %target-typecheck-verify-swift
// NOTE: DO NOT add a newline at EOF.
// expected-error@+2 {{unterminated string literal}}
// expected-error@+3 {{cannot find ')' to match opening '(' in string interpolation}}
_ = """
foo
\("bar | 30.375 | 85 | 0.654321 |
5d9f438c47614baef08728bdcb133cabe11661c3 | 5,459 | //
// CoreDataSandboxedPersonCRUDTests.swift
// From SimpleCoreDataManagerDemo
//
// Created by Emily Ivie on 2/19/17.
// Copyright © 2017 urdnot. All rights reserved.
//
import XCTest
@testable import SerializableDataDemo
class CoreDataSandboxedPersonCRUDTests: XCTestCase {
// You can run performance tests on these, because they don't use static SimpleCoreDataManager.current.
// It's just more annoying, because you have to pass the manager all around.
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
private func getSandboxedManager() -> SimpleCoreDataManager {
return SimpleCoreDataManager(storeName: SimpleCoreDataManager.defaultStoreName, isConfineToMemoryStore: true)
}
func testCreateRead() {
testCreateRead(with: getSandboxedManager())
}
func testCreateRead(with manager: SimpleSerializedCoreDataManageable) {
let newPerson = createPhil(with: manager)
let newPersonId = newPerson?.id
// reload to make sure the value was created
let phil = CoreDataPerson.get(name: "Phil Myman", with: manager)
XCTAssert(phil != nil, "Person was not created")
XCTAssert(phil?.id == newPersonId, "Created Person id not saved correctly")
}
func testReadAll() {
testReadAll(with: getSandboxedManager())
}
func testReadAll(with manager: SimpleSerializedCoreDataManageable) {
_ = createPhil(with: manager)
_ = createLem(with: manager)
_ = createVeronica(with: manager)
let persons = CoreDataPerson.getAll(with: manager).sorted(by: CoreDataPerson.sort)
XCTAssert(persons.count == 3, "All Persons were not created")
XCTAssert(persons.first?.name == "Lem Hewitt", "Persons sorted incorrectly")
}
func testReadAllPerformance() {
measure {
self.testReadAll(with: self.getSandboxedManager())
}
}
func testUpdate() {
testUpdate(with: getSandboxedManager())
}
func testUpdate(with manager: SimpleSerializedCoreDataManageable) {
_ = createPhil(with: manager)
// reload to make sure the value was created
var phil = CoreDataPerson.get(name: "Phil Myman", with: manager)
XCTAssert(phil != nil, "Person was not created")
phil?.name = "Byron McNertny"
phil?.profession = "Cowboy"
phil?.organization = "Some Ranch"
_ = phil?.save(with: manager)
let byron = CoreDataPerson.get(name: "Byron McNertny", with: manager)
XCTAssert(byron != nil, "Updated Person not found in the store")
XCTAssert(byron?.name == "Byron McNertny", "Updated Person has incorrect values")
let missingPhil = CoreDataPerson.get(name: "Phil Myman", with: manager)
XCTAssert(CoreDataPerson.getCount(with: manager) == 1, "Saved multiple copies of same person")
XCTAssert(missingPhil == nil, "Updated Person has older values in the store")
}
func testDelete() {
testDelete(with: getSandboxedManager())
}
func testDelete(with manager: SimpleSerializedCoreDataManageable) {
_ = createPhil(with: manager)
// reload to make sure the value was created
var phil = CoreDataPerson.get(name: "Phil Myman", with: manager)
XCTAssert(phil != nil, "Person was not created")
_ = phil?.delete(with: manager)
let missingPhil = CoreDataPerson.get(name: "Phil Myman", with: manager)
XCTAssert(missingPhil == nil, "Deleted Person still found in store")
}
func testDeleteAll() {
testDeleteAll(with: getSandboxedManager())
}
func testDeleteAll(with manager: SimpleSerializedCoreDataManageable) {
testReadAll(with: manager)
_ = CoreDataPerson.deleteAll(with: manager)
XCTAssert(CoreDataPerson.getCount(with: manager) == 0, "Person deleteAll failed")
}
private func createPhil(with manager: SimpleSerializedCoreDataManageable? = nil) -> CoreDataPerson? {
var phil = CoreDataPerson(serializedString: "{\"id\": \"\(UUID())\", \"name\": \"Phil Myman\", \"profession\": \"R&D Lab Scientist\", \"organization\": \"Veridian Dynamics\", \"notes\": \"You know what you did.\", \"createdDate\": \"2010-03-18 19:05:15\", \"modifiedDate\": \"2010-01-26 20:00:09\"}")
_ = phil?.save(with: manager)
return phil
}
private func createLem(with manager: SimpleSerializedCoreDataManageable? = nil) -> CoreDataPerson? {
var lem = CoreDataPerson(serializedString: "{\"id\": \"\(UUID())\", \"name\": \"Lem Hewitt\", \"profession\": \"R&D Lab Scientist\", \"organization\": \"Veridian Dynamics\", \"notes\": \"You heard the statistically average lady.\", \"createdDate\": \"2017-02-20 13:14:00\", \"modifiedDate\": \"2017-02-20 13:14:00\"}")
_ = lem?.save(with: manager)
return lem
}
private func createVeronica(with manager: SimpleSerializedCoreDataManageable? = nil) -> CoreDataPerson? {
var veronica = CoreDataPerson(serializedString: "{\"id\": \"\(UUID())\", \"name\": \"Veronica Palmer\", \"profession\": \"Executive\", \"organization\": \"Veridian Dynamics\", \"notes\": \"Friendship. It's the same as stealing.\", \"createdDate\": \"2010-03-18 19:00:07\", \"modifiedDate\": \"2010-01-26 23:17:20\"}")
_ = veronica?.save(with: manager)
return veronica
}
}
| 46.262712 | 326 | 0.653233 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.