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
|
---|---|---|---|---|---|
46ccc2bf52b468b9a89231cc65b256cbc041a2e6 | 189 | //
// PhotoBrowerUtil.swift
// PhotoBrower
//
// Created by kingcong on 2019/1/29.
// Copyright © 2019 ustc. All rights reserved.
//
import UIKit
class PhotoBrowerUtil: NSObject {
}
| 13.5 | 47 | 0.687831 |
e21bfe3647e891843a09a6369f43d35659f772d2 | 438 | //
// ConsentError.swift
// DigiMeSDK
//
// Created on 11/06/2021.
// Copyright © 2021 digi.me Limited. All rights reserved.
//
import Foundation
enum ConsentError: String, Error {
case initializeCheckFailed = "INITIALIZE_CHECK_FAIL"
case userCancelled = "USER_CANCEL"
case serviceOnboardError = "ONBOARD_ERROR"
case invalidCode = "INVALID_CODE"
case serverError = "SERVER_ERROR"
case unexpectedError
}
| 21.9 | 58 | 0.712329 |
5baa74b573e8271db8fba97b777e3b8100fba841 | 1,307 | //
// Project8_Swipe_To_Dismiss_KeyboardUITests.swift
// Project8-Swipe To Dismiss KeyboardUITests
//
// Created by 朱立焜 on 16/4/13.
// Copyright © 2016年 朱立焜. All rights reserved.
//
import XCTest
class Project8_Swipe_To_Dismiss_KeyboardUITests: 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.
}
}
| 35.324324 | 182 | 0.677123 |
fcd3dc383b527c16e383687a97191b1cba041a0c | 8,582 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SPLarkSettingsCloseButton: UIButton {
private let iconView = SPLarkSettingsCloseIconButton()
override public var isHighlighted: Bool {
didSet {
if isHighlighted {
self.iconView.color = self.color.withAlphaComponent(0.7)
} else {
self.iconView.color = self.color.withAlphaComponent(1)
}
}
}
var color = UIColor.lightGray {
didSet {
self.iconView.color = self.color
}
}
init() {
super.init(frame: .zero)
self.iconView.isUserInteractionEnabled = false
self.backgroundColor = UIColor.white.withAlphaComponent(0.15)
self.color = UIColor.lightGray
self.addSubview(self.iconView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func layout(bottomX: CGFloat, y: CGFloat) {
self.sizeToFit()
self.frame.origin.x = bottomX - self.frame.width
self.frame.origin.y = y
self.layoutSubviews()
}
override public func sizeToFit() {
super.sizeToFit()
self.frame = CGRect.init(x: self.frame.origin.x, y: self.frame.origin.y, width: 30, height: 30)
}
public override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.frame.width / 2
self.iconView.frame = CGRect.init(x: 0, y: 0, width: self.frame.width * 0.36, height: self.frame.height * 0.36)
self.iconView.center = CGPoint.init(x: self.frame.width / 2, y: self.frame.height / 2)
}
}
class SPLarkSettingsCloseIconButton: UIView {
var color = UIColor.lightGray {
didSet {
self.setNeedsDisplay()
}
}
init() {
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
SPLarkSettingsCodeDraw.SystemIconPack.drawClose(frame: rect, resizing: .aspectFit, color: self.color)
}
}
struct SPLarkSettingsCodeDraw {
public class SystemIconPack : NSObject {
private struct Cache {
static let gradient: CGGradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.red.cgColor] as CFArray, locations: [0, 1])!
}
@objc dynamic public class var gradient: CGGradient { return Cache.gradient }
@objc dynamic public class func drawClose(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100), resizing: ResizingBehavior = .aspectFit, color: UIColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)) {
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 100, height: 100), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 100, y: resizedFrame.height / 100)
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 92.02, y: 22.92))
bezierPath.addLine(to: CGPoint(x: 64.42, y: 50.52))
bezierPath.addLine(to: CGPoint(x: 92.02, y: 78.13))
bezierPath.addCurve(to: CGPoint(x: 92.02, y: 92.99), controlPoint1: CGPoint(x: 96.13, y: 82.23), controlPoint2: CGPoint(x: 96.13, y: 88.89))
bezierPath.addCurve(to: CGPoint(x: 84.59, y: 96.07), controlPoint1: CGPoint(x: 89.97, y: 95.05), controlPoint2: CGPoint(x: 87.28, y: 96.07))
bezierPath.addCurve(to: CGPoint(x: 77.16, y: 92.99), controlPoint1: CGPoint(x: 81.9, y: 96.07), controlPoint2: CGPoint(x: 79.22, y: 95.05))
bezierPath.addLine(to: CGPoint(x: 49.55, y: 65.38))
bezierPath.addLine(to: CGPoint(x: 21.95, y: 92.99))
bezierPath.addCurve(to: CGPoint(x: 14.51, y: 96.07), controlPoint1: CGPoint(x: 19.89, y: 95.05), controlPoint2: CGPoint(x: 17.2, y: 96.07))
bezierPath.addCurve(to: CGPoint(x: 7.08, y: 92.99), controlPoint1: CGPoint(x: 11.82, y: 96.07), controlPoint2: CGPoint(x: 9.13, y: 95.05))
bezierPath.addCurve(to: CGPoint(x: 7.08, y: 78.13), controlPoint1: CGPoint(x: 2.97, y: 88.89), controlPoint2: CGPoint(x: 2.97, y: 82.23))
bezierPath.addLine(to: CGPoint(x: 34.69, y: 50.52))
bezierPath.addLine(to: CGPoint(x: 7.08, y: 22.92))
bezierPath.addCurve(to: CGPoint(x: 7.08, y: 8.04), controlPoint1: CGPoint(x: 2.97, y: 18.8), controlPoint2: CGPoint(x: 2.97, y: 12.15))
bezierPath.addCurve(to: CGPoint(x: 21.94, y: 8.04), controlPoint1: CGPoint(x: 11.18, y: 3.94), controlPoint2: CGPoint(x: 17.84, y: 3.94))
bezierPath.addLine(to: CGPoint(x: 49.55, y: 35.65))
bezierPath.addLine(to: CGPoint(x: 77.16, y: 8.04))
bezierPath.addCurve(to: CGPoint(x: 92.02, y: 8.04), controlPoint1: CGPoint(x: 81.26, y: 3.94), controlPoint2: CGPoint(x: 87.92, y: 3.94))
bezierPath.addCurve(to: CGPoint(x: 92.02, y: 22.92), controlPoint1: CGPoint(x: 96.13, y: 12.15), controlPoint2: CGPoint(x: 96.13, y: 18.8))
bezierPath.close()
color.setFill()
bezierPath.fill()
context.restoreGState()
}
@objc(StyleKitNameResizingBehavior)
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
}
}
private override init() {}
}
}
| 45.648936 | 244 | 0.603239 |
1a5020b0a36d8dacc108e50ffbdc6973067a37a1 | 2,533 | //
// TextPreferences.swift
// VSpinGame
//
// Created by MacV on 07/01/21.
//
import Foundation
import UIKit
public struct TextPreferences {
public var font: UIFont
public var textColorType: VConfiguration.ColorType
public var horizontalOffset: CGFloat = 0
public var verticalOffset: CGFloat
public var flipUpsideDown: Bool = true
public var isCurved: Bool = true
public var orientation: Orientation = .horizontal
public var lineBreakMode: LineBreakMode = .clip
public var numberOfLines: Int = 1
public var spacing: CGFloat = 3
public var alignment: NSTextAlignment = .center
public var maxWidth: CGFloat = .greatestFiniteMagnitude
public init(textColorType: VConfiguration.ColorType,font: UIFont,verticalOffset: CGFloat = 0) {
self.textColorType = textColorType
self.font = font
self.verticalOffset = verticalOffset
}
}
public extension TextPreferences {
enum Orientation {
case horizontal
case vertical
}
}
public extension TextPreferences {
enum LineBreakMode {
case clip
case truncateTail
case wordWrap
case characterWrap
var systemLineBreakMode: NSLineBreakMode {
switch self {
case .clip:
return .byClipping
case .truncateTail:
return .byTruncatingTail
case .wordWrap:
return .byWordWrapping
case .characterWrap:
return .byCharWrapping
}
}
}
}
extension TextPreferences {
func color(for index: Int) -> UIColor {
var color: UIColor = .clear
switch self.textColorType {
case .evenOddColors(let evenColor, let oddColor):
color = index % 2 == 0 ? evenColor : oddColor
case .customPatternColors(let colors, let defaultColor):
color = colors?[index, default: defaultColor] ?? defaultColor
}
return color
}
func textAttributes(for index: Int) -> [NSAttributedString.Key:Any] {
let textColor = self.color(for: index)
let textStyle = NSMutableParagraphStyle()
textStyle.alignment = alignment
textStyle.lineBreakMode = lineBreakMode.systemLineBreakMode
textStyle.lineSpacing = spacing
let deafultAttributes:[NSAttributedString.Key: Any] =
[.font: self.font,
.foregroundColor: textColor,
.paragraphStyle: textStyle ]
return deafultAttributes
}
}
| 30.518072 | 99 | 0.640742 |
e8a753af983bb2d29ea2b11d88c13a9d6707fd71 | 150 | // RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
{class T{protocol b{#^A^#associatedtype b:B<T>struct B<b
| 50 | 92 | 0.74 |
f9493eaf9bcf54624976a0c1bed940d87739caf1 | 87 | public struct AttachmentIdentifier: TestRailModel {
public var attachmentId: Int
}
| 21.75 | 51 | 0.793103 |
ab541ed0e74dce586849281966ce26ecf8256322 | 1,006 | //
// HawkCI
// BitriseAPIClien
// 2019
//
import Foundation
public struct AppWebhookUpdateParams: APIModel {
public var events: String?
public var headers: String?
public var url: String?
public init(events: String? = nil, headers: String? = nil, url: String? = nil) {
self.events = events
self.headers = headers
self.url = url
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
events = try container.decodeIfPresent("events")
headers = try container.decodeIfPresent("headers")
url = try container.decodeIfPresent("url")
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encodeIfPresent(events, forKey: "events")
try container.encodeIfPresent(headers, forKey: "headers")
try container.encodeIfPresent(url, forKey: "url")
}
}
| 25.15 | 84 | 0.664016 |
290606f5da1024e82e636cb0d085a0f3a7a33bb8 | 2,376 | //
// EditBookmarkAlert.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. 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 UIKit
import Core
class EditBookmarkAlert {
typealias SaveCompletion = (Link) -> Swift.Void
typealias CancelCompletion = () -> Swift.Void
static func buildAlert(title: String,
bookmark: Link,
saveCompletion: @escaping SaveCompletion,
cancelCompletion: @escaping CancelCompletion) -> UIAlertController {
let editBox = UIAlertController(title: title, message: "", preferredStyle: .alert)
editBox.addTextField { (textField) in textField.text = bookmark.title }
editBox.addTextField { (textField) in textField.text = bookmark.url.absoluteString }
editBox.addAction(saveAction(editBox: editBox, originalBookmark: bookmark, completion: saveCompletion))
editBox.addAction(cancelAction(completion: cancelCompletion))
return editBox
}
private static func saveAction(editBox: UIAlertController, originalBookmark bookmark: Link, completion: @escaping SaveCompletion) -> UIAlertAction {
return UIAlertAction(title: UserText.actionSave, style: .default) { (action) in
if let title = editBox.textFields?[0].text,
let urlString = editBox.textFields?[1].text,
let url = URL(string: urlString) {
let newBookmark = Link(title: title, url: url, favicon: bookmark.favicon)
completion(newBookmark)
}
}
}
private static func cancelAction(completion: @escaping CancelCompletion) -> UIAlertAction {
return UIAlertAction(title: UserText.actionCancel, style: .cancel) { (action) in
completion()
}
}
}
| 40.271186 | 152 | 0.665404 |
7a7f1dc80263a44630394c300b96c32bf14f64ce | 6,531 | /*
* --------------------------------------------------------------------------------
* <copyright company="Aspose" file="DeleteFieldsOnlineRequest.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 deleteFieldsOnline operation.
@available(macOS 10.12, iOS 10.3, watchOS 3.3, tvOS 12.0, *)
public class DeleteFieldsOnlineRequest : WordsApiRequest {
private let document : InputStream;
private let nodePath : 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 document;
case nodePath;
case loadEncoding;
case password;
case destFileName;
case revisionAuthor;
case revisionDateTime;
case invalidCodingKey;
}
// Initializes a new instance of the DeleteFieldsOnlineRequest class.
public init(document : InputStream, nodePath : String? = nil, loadEncoding : String? = nil, password : String? = nil, destFileName : String? = nil, revisionAuthor : String? = nil, revisionDateTime : String? = nil) {
self.document = document;
self.nodePath = nodePath;
self.loadEncoding = loadEncoding;
self.password = password;
self.destFileName = destFileName;
self.revisionAuthor = revisionAuthor;
self.revisionDateTime = revisionDateTime;
}
// The document.
public func getDocument() -> InputStream {
return self.document;
}
// The path to the node in the document tree.
public func getNodePath() -> String? {
return self.nodePath;
}
// 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/online/delete/{nodePath}/fields";
if (self.getNodePath() != nil) {
rawPath = rawPath.replacingOccurrences(of: "{nodePath}", with: try ObjectSerializer.serializeToString(value: self.getNodePath()!));
}
else {
rawPath = rawPath.replacingOccurrences(of: "{nodePath}", with: "");
}
rawPath = rawPath.replacingOccurrences(of: "//", with: "/");
let urlPath = (try configuration.getApiRootUrl()).appendingPathComponent(rawPath);
var urlBuilder = URLComponents(url: urlPath, resolvingAgainstBaseURL: false)!;
var queryItems : [URLQueryItem] = [];
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;
}
var formParams : [RequestFormParam] = [];
formParams.append(RequestFormParam(name: "document", body: try ObjectSerializer.serializeFile(value: self.getDocument()), contentType: "application/octet-stream"));
var result = WordsApiRequestData(url: urlBuilder.url!, method: "PUT");
result.setBody(formParams: formParams);
return result;
}
// Deserialize response of this request
public func deserializeResponse(data : Data) throws -> Any? {
return data;
}
}
| 45.041379 | 235 | 0.664829 |
900e3af3587776f3a3804c0775528b22c0d5ab18 | 225 | public struct IDLConstant: IDLNode, IDLNamed {
public static let type = "const"
public let name: String
public let idlType: IDLType
public let value: IDLValue
public let extAttrs: [IDLExtendedAttribute]
}
| 28.125 | 47 | 0.724444 |
8f09d511a4a8bf1d2ca8e6c78fd2c5be488579f5 | 3,725 | //
// Activities.swift
// SBSwiftComponents
//
// Created by nanhu on 2018/9/12.
// Copyright © 2018年 nanhu. All rights reserved.
//
import UIKit
public class SBActivity: UIActivity {
var URLToOpen: URL?
var schemePrefix: String?
override public var activityType : UIActivity.ActivityType? {
let typeArray = "\(type(of: self))".components(separatedBy: ".")
let _type: String = typeArray[typeArray.count-1]
return UIActivity.ActivityType(rawValue: _type)
}
override public var activityImage : UIImage {
if let type = activityType?.rawValue {
return WebBrowser.bundledImage(named: "\(type)")!
} else {
assert(false, "Unknow type")
return UIImage()
}
}
override public func prepare(withActivityItems activityItems: [Any]) {
for activityItem in activityItems {
if activityItem is URL {
URLToOpen = activityItem as? URL
}
}
}
}
public class SBActivitySafari: SBActivity {
override public var activityTitle : String {
return NSLocalizedString("Open in Safari", tableName: "SBWebBrowser", comment: "")
}
override public func canPerform(withActivityItems activityItems: [Any]) -> Bool {
for activityItem in activityItems {
if let activityItem = activityItem as? URL, UIApplication.shared.canOpenURL(activityItem) {
return true
}
}
return false
}
override public func perform() {
//let completed: Bool = UIApplication.shared.openURL(URLToOpen! as URL)
//activityDidFinish(completed)
if #available(iOS 10.0.0, *) {
UIApplication.shared.open(URLToOpen!, options: [:]) { [weak self](finished) in
self?.activityDidFinish(finished)
}
} else {
UIApplication.shared.openURL(URLToOpen!)
}
}
}
public class SBActivityChrome: SBActivity {
override public var activityTitle : String {
return NSLocalizedString("Open in Chrome", tableName: "SBWebBrowser", comment: "")
}
override public func canPerform(withActivityItems activityItems: [Any]) -> Bool {
for activityItem in activityItems {
if activityItem is URL, UIApplication.shared.canOpenURL(URL(string: "googlechrome://")!) {
return true;
}
}
return false;
}
override public func perform() {
let inputURL: URL! = URLToOpen as URL?
let scheme: String! = inputURL.scheme
// Replace the URL Scheme with the Chrome equivalent.
var chromeScheme: String? = nil;
if scheme == "http" {
chromeScheme = "googlechrome"
} else if scheme == "https" {
chromeScheme = "googlechromes"
}
// Proceed only if a valid Google Chrome URI Scheme is available.
if chromeScheme != nil {
let absoluteString: NSString! = inputURL!.absoluteString as NSString?
let rangeForScheme: NSRange! = absoluteString.range(of: ":")
let urlNoScheme: String! = absoluteString.substring(from: rangeForScheme.location)
let chromeURLString: String! = chromeScheme!+urlNoScheme
let chromeURL: URL! = URL(string: chromeURLString)
// Open the URL with Chrome.
//UIApplication.shared.openURL(chromeURL)
if #available(iOS 10.0.0, *) {
UIApplication.shared.open(chromeURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URLToOpen!)
}
}
}
}
| 34.174312 | 103 | 0.600268 |
ccb9aab34aa00829751cf771dad7eebc4b7754e6 | 510 | //
// Comment.swift
// bloggingapp
//
// Created by Aduh Perfect on 19/07/2021.
//
import Foundation
// MARK: - Comment
struct Comment: Codable {
let id: Int
let postId: Int
let name: String
let email: String
let body: String
init(
id: Int,
postId: Int,
name: String,
email: String,
body: String
) {
self.id = id
self.postId = postId
self.name = name
self.email = email
self.body = body
}
}
| 15.454545 | 42 | 0.531373 |
283727d062ae5f67676f2be7a5deab0cc1ec542a | 277 | //
// AuthObject.swift
// SchoolChatIOS
//
// Created by Константин Леонов on 07.02.2022.
//
import Foundation
class AuthObj: ObservableObject {
@Published var Auth: Bool = false
@Published var NoUser: Bool = false
@Published var WrongPassword: Bool = false
}
| 18.466667 | 47 | 0.696751 |
11548a86c31bc3f63a39d3e3fc960186c8137a95 | 385 | import Foundation
/// Represents the error occured in MapGL.
public class MapGLError : Error, LocalizedError {
/// Description of the error.
private let text: String
/// Creates the new instance of the error object.
///
/// - Parameter text: Description of the error
init(text: String) {
self.text = text
}
public var errorDescription: String? {
return self.text
}
}
| 18.333333 | 50 | 0.703896 |
4bdce4c1115d402ec208497e54651afc8b55e81b | 720 | //
// AnzeeConstants.swift
// Anzee
//
// Created by Shawn Veader on 4/23/19.
// Copyright 2019 The Rocket Science Group LLC
//
// Licensed under the Mailchimp Mobile SDK License Agreement (the "License");
// you may not use this file except in compliance with the License. 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 or express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
struct AnzeeConstants {
static let APIHost = "api.mailchimp.com"
}
| 31.304348 | 80 | 0.723611 |
169eb09e63a12298dc437ea2cd7bab8f5dc46037 | 3,554 | //
// Auth.swift
// app-ios
//
// Created by Sinan Ulkuatam on 5/11/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import Crashlytics
class Auth {
let username: String
let email: String
let password: String
required init(username: String, email: String, password: String) {
self.username = username
self.email = email
self.password = password
}
class func login(email: String, username: String, password: String, completionHandler: (String, Bool, String, NSError) -> ()) {
// check for empty fields
if(email.isEmpty) {
// display alert message
return;
} else if(password.isEmpty) {
return;
}
Alamofire.request(.POST, API_URL + "/login", parameters: [
"username": username,
"email":email,
"password":password
],
encoding:.JSON)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
// print(totalBytesWritten)
// print(totalBytesExpectedToWrite)
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
// print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.responseJSON { response in
// go to main view
if(response.response?.statusCode == 200) {
NSUserDefaults.standardUserDefaults().setBool(true,forKey:"userLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
} else {
// display error
}
switch response.result {
case .Success:
if let value = response.result.value {
let data = JSON(value)
// completion handler here for apple watch
let token = data["token"].stringValue
if response.result.error != nil {
completionHandler(token, false, username, response.result.error!)
} else {
completionHandler(token, true, username, NSError(domain: "nil", code: 000, userInfo: [:]))
}
NSUserDefaults.standardUserDefaults().setValue(token, forKey: "userAccessToken")
NSUserDefaults.standardUserDefaults().synchronize()
Answers.logLoginWithMethod("Access",
success: true,
customAttributes: nil)
// go to main view from completion handler
// self.performSegueWithIdentifier("homeView", sender: self);
}
case .Failure(let error):
print(error)
Answers.logLoginWithMethod("Access",
success: false,
customAttributes: nil)
// display error
}
}
}
} | 36.639175 | 131 | 0.482555 |
d9effa36250f5c1b5f7b679de54c56bc9531665b | 607 | //
// ProductViewModel.swift
// CleanArchitecture
//
// Created by Tuan Truong on 9/6/18.
// Copyright © 2018 Sun Asterisk. All rights reserved.
//
struct ProductViewModel {
let product: ProductModel
var name: String {
return product.product.name
}
var price: String {
return product.product.price.currency
}
var icon: UIImage? {
return product.edited ? #imageLiteral(resourceName: "edited") : nil
}
var backgroundColor: UIColor {
return product.edited ? UIColor.yellow.withAlphaComponent(0.5) : UIColor.white
}
}
| 21.678571 | 86 | 0.637562 |
e811463638b2a15a31f670d46e973ac5b35e4802 | 980 | import Substate
import SubstateMiddleware
import Foundation
@MainActor let appTriggers = ActionTriggers {
soundTriggers
notificationTriggers
saveTriggers
// Titlebar
ModelSaver.LoadDidComplete
.replace(with: \Tasks.all.count)
.trigger { Titlebar.UpdateCount(count: $0) }
Tasks.Changed
.replace(with: \Tasks.all.count)
.trigger { Titlebar.UpdateCount(count: $0) }
// Toolbar
Toolbar.SaveButtonWasPressed
.trigger(Toolbar.Reset())
Toolbar.SaveButtonWasPressed
.replace(with: \Toolbar.newTaskBody)
.trigger { Tasks.Create.init(body: $0) }
Tasks.Toggle
.map(\.id)
.combine(with: \Tasks.all)
.trigger { id, tasks -> Notifications.Show? in
if let index = tasks.firstIndex(where: { $0.id == id }) {
return Notifications.Show(for: tasks[index], at: index)
} else {
return nil
}
}
}
| 23.333333 | 71 | 0.6 |
18313c197705860e51dcb4100066ca04fcb7e06d | 2,821 | // Created by Keith Harrison https://useyourloaf.com
// Copyright © 2020 Keith Harrison. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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
final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
private var listController: ListController?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let navController = window?.rootViewController as? UINavigationController {
listController = navController.topViewController as? ListController
loadData()
}
}
private func loadData() {
guard let url = Bundle.main.url(forResource: "countryInfo", withExtension: "json") else {
return
}
DispatchQueue.global(qos: .userInteractive).async {
do {
let data = try Data(contentsOf: url)
let countryInfo = try JSONDecoder().decode(CountryInfo.self, from: data)
let countries = countryInfo.geonames.sorted(by: { $0.name < $1.name })
DispatchQueue.main.async {
self.listController?.countries = countries
}
} catch {
print("Unable to load data: \(error)")
}
}
}
}
| 45.5 | 127 | 0.698688 |
bfd5d95325679d070e4a553e7212227f5d98fc0a | 3,104 | //
// SelectTestViewController.swift
// NiconLensWear
//
// Created by 森邦彦 on 2017/11/13.
// Copyright © 2017年 Nicon-Essilor. All rights reserved.
//
import UIKit
class SelectTestViewController: UIViewController {
@IBOutlet weak var normalGlassButton_: UIButton!
@IBOutlet weak var trialGlassButton_: UIButton!
@IBAction func tappedMyopeButton(_ sender: Any) {
let dataServer = DataServer.shared
dataServer.setEyeStatus(EyeStatus.Myope)
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "Description")
nextVC?.modalTransitionStyle = .crossDissolve
present(nextVC!, animated: true, completion: nil)
}
@IBAction func tappedHyperopeButton(_ sender: Any) {
let dataServer = DataServer.shared
dataServer.setEyeStatus(EyeStatus.Hyperope)
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "Description")
nextVC?.modalTransitionStyle = .crossDissolve
present(nextVC!, animated: true, completion: nil)
}
@IBAction func gotoStartUp(_ sender: Any) {
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "SelectTest")
nextVC?.modalTransitionStyle = .crossDissolve
present(nextVC!, animated: true, completion: nil)
}
@IBAction func tappedNormalGlassButton(_ sender: Any) {
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "StartUp")
nextVC?.modalTransitionStyle = .crossDissolve
present(nextVC!, animated: true, completion: nil)
}
@IBAction func tappedGlassButton(_ sender: Any) {
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "StartUp")
nextVC?.modalTransitionStyle = .crossDissolve
present(nextVC!, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// let dataServer = DataServer.shared
// let glassType = dataServer.getGlassType()
/*
if (glassType == GlassType.TrialSet) {
trialGlassButton_.isHidden = true
normalGlassButton_.isHidden = true
} else {
trialGlassButton_.isHidden = true
normalGlassButton_.isHidden = true
}
*/
self.setNeedsStatusBarAppearanceUpdate()
}
override var prefersStatusBarHidden: Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 31.673469 | 106 | 0.658505 |
110a03236a3a4fe6510b8cae5a1e608af2392693 | 4,888 | //
// ViewController.swift
// SDAnimationChain
//
// Created by sauvikdolui on 11/01/2020.
// Copyright (c) 2020 sauvikdolui. All rights reserved.
//
import UIKit
import SDAnimationChain
class ViewController: UIViewController {
@IBOutlet weak var container: UIView!
@IBOutlet weak var innerBox: UIView!
@IBOutlet weak var containerHeight: NSLayoutConstraint!
@IBOutlet weak var containerWidth: NSLayoutConstraint!
@IBOutlet weak var innerBoxCentreX: NSLayoutConstraint!
@IBOutlet weak var innerBoxWidth: NSLayoutConstraint!
@IBOutlet weak var labelstackView: UIStackView!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
@IBOutlet weak var label4: UILabel!
@IBOutlet weak var label1Width: NSLayoutConstraint!
@IBOutlet weak var label2Width: NSLayoutConstraint!
@IBOutlet weak var label3Width: NSLayoutConstraint!
@IBOutlet weak var label4Width: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//container.layer.borderColor = UIColor.black.cgColor
//container.layer.borderWidth = 1.0
container.layer.cornerRadius = 10.0
container.layer.shadowColor = UIColor.black.withAlphaComponent(0.1).cgColor
container.layer.shadowOffset = CGSize(width: 0, height: 0)
container.layer.shadowRadius = 10.0
container.layer.shadowOpacity = 1.0
containerHeight.constant = 20.0
containerWidth.constant = 20.0
innerBox.layer.cornerRadius = 5.0
innerBox.backgroundColor = label1.backgroundColor
innerBox.isHidden = true
labelstackView.isHidden = true
self.label1Width.constant = 0.0
self.label2Width.constant = 0.0
self.label3Width.constant = 0.0
self.label4Width.constant = 0.0
for view in labelstackView.subviews {
view.layer.cornerRadius = 5.0
view.layer.masksToBounds = true
}
}
@IBAction func resetButtonTapped(_ sender: UIButton) {
containerHeight.constant = 20.0
containerWidth.constant = 20.0
innerBox.isHidden = true
innerBox.layer.cornerRadius = 5.0
innerBoxWidth.constant = 10.0
innerBoxCentreX.constant = 0.0
labelstackView.isHidden = true
label1Width.constant = 0.0
label2Width.constant = 0.0
label3Width.constant = 0.0
label4Width.constant = 0.0
}
@IBAction func animateButtonTapped(_ sender: UIButton) {
view.layoutIfNeeded()
UIView.Animator().springAnimate(duration: 0.5, dampingRatio: 0.7, initialVelocity: 1.0, animations: { [weak self] in
self?.containerWidth.constant = 240.0
self?.view.layoutIfNeeded()
}).thenSpringAnimate(duration: 0.5, dampingRatio: 0.7, initialVelocity: 1.0, animations: { [weak self] in
self?.containerHeight.constant = 128.0
self?.view.layoutIfNeeded()
}, completion: { finished in
// completion
}).thenTransitionWith(view: container, duration: 0.5, options: [.transitionFlipFromTop], animations: {
// Empty completion block
}).thenSpringAnimate(duration: 1.0, delay: 0.5, dampingRatio: 0.7, initialVelocity: 1.0, animations: { [weak self] in
self?.innerBox.isHidden = false
self?.innerBoxWidth.constant = 60.0
self?.innerBoxCentreX.constant = -80.0
self?.innerBox.layer.cornerRadius = 10.0
self?.view.layoutIfNeeded()
}, completion: {[weak self] _ in
self?.labelstackView.isHidden = false
}).thenAnimate(duration: 0.5, animations: { [weak self] in
guard let welf = self else { return }
welf.label1Width.constant = welf.containerWidth.constant - welf.innerBoxWidth.constant - 36.0
welf.view.layoutIfNeeded()
}).thenAnimate(duration: 0.5, animations: { [weak self] in
guard let welf = self else { return }
welf.label2Width.constant = welf.containerWidth.constant - welf.innerBoxWidth.constant - 36.0
welf.view.layoutIfNeeded()
}).thenAnimate(duration: 0.5, animations: { [weak self] in
guard let welf = self else { return }
welf.label3Width.constant = welf.containerWidth.constant - welf.innerBoxWidth.constant - 36.0
welf.view.layoutIfNeeded()
}).thenAnimate(duration: 0.7, animations: { [weak self] in
guard let welf = self else { return }
welf.label4Width.constant = welf.containerWidth.constant - welf.innerBoxWidth.constant - 100.0
welf.view.layoutIfNeeded()
}).start()
}
}
| 41.07563 | 125 | 0.645049 |
64e188142bcca7f9e65492a6f3f2372cb5a08153 | 3,201 | //
// OceanScene.swift
// Intent
//
// Created by student on 11/12/19.
// Copyright © 2019 Paulina Asturias. All rights reserved.
import SpriteKit
import GameplayKit
class OceanScene: GameScene {
var seacurrent = SKSpriteNode()
var lastcurrentchange = 0
var lastshark = -10
override func initScene() {
super.initScene()
addCurrent()
level = 2
}
func removeCurrent() {
for node in self.children {
if let fish = node as? FishNode {
updateFishSpeedOutOfCurrent(fish: fish)
}
}
seacurrent.removeFromParent()
}
func addCurrent() {
seacurrent = CurrentNode(scene: self)
seacurrent.position = CGPoint(x: 0, y: CGFloat.random(in: -size.height/2 ... size.height/2))
self.addChild(seacurrent)
lastcurrentchange = 0
}
func summonShark() -> Shark {
let shark = Shark()
makeFish(fish: shark)
lastshark = 0
return shark
}
override func decrementCounter() {
super.decrementCounter()
if !isPaused {
if lastcurrentchange > Int.random(in: 0...20) {
removeCurrent()
addCurrent()
}
else {
lastcurrentchange += 1
}
if lastshark > Int.random(in: 10...30) {
summonShark()
}
else {
lastshark += 1
}
}
}
func updateFishSpeedOutOfCurrent(fish: FishNode) {
if let current = seacurrent as? CurrentNode {
if (fish.orientation == current.orientation && fish.currenteffect) {
fish.speed = fish.speed / 2
}
else if (fish.currenteffect) {
fish.speed = fish.speed * 2
}
fish.currenteffect = false
}
}
func updateFishSpeedInCurrent(fish: FishNode) {
if let current = seacurrent as? CurrentNode {
if (fish.orientation == current.orientation && !fish.currenteffect) {
fish.speed = fish.speed * 2
}
else if (!fish.currenteffect) {
fish.speed = fish.speed / 2
}
fish.currenteffect = true
}
}
override func update(_ currentTime: TimeInterval) {
super.update(currentTime)
for node in self.children {
if let victim = node as? FishNode {
if victim.intersects(seacurrent) && seacurrent.parent != nil {
updateFishSpeedInCurrent(fish: victim)
}
else {
updateFishSpeedOutOfCurrent(fish: victim)
}
for node2 in self.children {
if let shark = node2 as? Shark {
if victim.intersects(shark) && victim.name != "shark" {
shark.eat(fish: victim)
}
}
}
}
}
}
}
| 28.078947 | 100 | 0.481412 |
331382977d10dfaa75de2e92c4802a5f205a4172 | 1,194 | import GRPC
import NIO
import HederaProtoServices
let connection = ClientConnection(configuration: ClientConnection.Configuration.default(
// https://docs.hedera.com/guides/testnet/testnet-nodes#testnet-nodes
target: .hostAndPort("0.testnet.hedera.com", 50211),
eventLoopGroup: MultiThreadedEventLoopGroup(numberOfThreads: 1)
))
let cryptoClient = Proto_CryptoServiceClient(channel: connection)
// https://github.com/hashgraph/hedera-protobufs/blob/main/services/CryptoGetAccountBalance.proto#L35
var targetAccountId = Proto_AccountID()
targetAccountId.accountNum = 1001
var accountBalanceQuery = Proto_CryptoGetAccountBalanceQuery()
accountBalanceQuery.balanceSource = .accountID(targetAccountId)
var query = Proto_Query()
query.query = .cryptogetAccountBalance(accountBalanceQuery)
// https://github.com/hashgraph/hedera-protobufs/blob/main/services/CryptoService.proto#L52
let response: Proto_Response = try! cryptoClient.cryptoGetBalance(query).response.wait()
guard case let .cryptogetAccountBalance(accountBalanceResponse) = response.response else {
fatalError("unexpected response from cryptoGetBalance")
}
print("balance = \(accountBalanceResponse.balance) tℏ")
| 38.516129 | 101 | 0.81742 |
1caba1362ed7e3e6b66aae9aa27d7132b1060b20 | 2,301 | //
// ExponeaSharedExports.swift
// ExponeaSDK
//
// Created by Panaxeo on 12/01/2021.
// Copyright © 2021 Exponea. All rights reserved.
//
/**
When using Cocoapods, we'll just include all files from ExponeaSDKShared.
When using Carthage/SPM, we'll depend on module/framework ExponeaSDKShared.
*/
#if !COCOAPODS
import ExponeaSDKShared
/**
We need to re-export some types from ExponeaSDKShared to general public when using SPM/Carthage
*/
public typealias Exponea = ExponeaSDKShared.Exponea
public typealias Constants = ExponeaSDKShared.Constants
public typealias Configuration = ExponeaSDKShared.Configuration
public typealias Logger = ExponeaSDKShared.Logger
public typealias LogLevel = ExponeaSDKShared.LogLevel
public typealias JSONValue = ExponeaSDKShared.JSONValue
public typealias JSONConvertible = ExponeaSDKShared.JSONConvertible
public typealias Authorization = ExponeaSDKShared.Authorization
public typealias ExponeaNotificationAction = ExponeaSDKShared.ExponeaNotificationAction
public typealias ExponeaNotificationActionType = ExponeaSDKShared.ExponeaNotificationActionType
public typealias Result = ExponeaSDKShared.Result
public typealias ExponeaProject = ExponeaSDKShared.ExponeaProject
public typealias ExponeaError = ExponeaSDKShared.ExponeaError
public typealias EventType = ExponeaSDKShared.EventType
public typealias TokenTrackFrequency = ExponeaSDKShared.TokenTrackFrequency
public typealias NotificationData = ExponeaSDKShared.NotificationData
/*
Instead of including ExponeaSDKShared in every file and conditionally
turning it of when using cocoapods, we'll do it here
*/
typealias DataType = ExponeaSDKShared.DataType
typealias TrackingRepository = ExponeaSDKShared.TrackingRepository
typealias EmptyResult = ExponeaSDKShared.EmptyResult
typealias TrackingObject = ExponeaSDKShared.TrackingObject
typealias CampaignData = ExponeaSDKShared.CampaignData
typealias RepositoryError = ExponeaSDKShared.RepositoryError
typealias ServerRepository = ExponeaSDKShared.ServerRepository
typealias EventTrackingObject = ExponeaSDKShared.EventTrackingObject
typealias CustomerTrackingObject = ExponeaSDKShared.CustomerTrackingObject
typealias RequestFactory = ExponeaSDKShared.RequestFactory
typealias RequestParametersType = ExponeaSDKShared.RequestParametersType
#endif
| 42.611111 | 96 | 0.857453 |
09680ed6fb54b99a386127b4d048dc14df49c356 | 1,668 | //
// SwiftyLabel.swift
// WHCWSIFT
//
// Created by Haochen Wang on 9/26/17.
// Copyright © 2017 Haochen Wang. All rights reserved.
//
import UIKit
public class SwiftyLabel: UIView, TextEditable
{
public init(_ text: String? = nil, _ textColor: UIColor? = nil, _ backgroundColor: UIColor? = nil)
{
super.init(frame: .zero)
loadText()
usesIntrinsicContentSize = true
textAlignment = .center
font = .systemFont(ofSize: UIFont.systemFontSize)
paragraphStyle = .default
numberOfLines = 0
padding = 0
lineBreakMode = .byTruncatingTail
isHidden = false
alpha = 1.0
contentMode = .redraw
isUserInteractionEnabled = false
self.text = text
self.textColor = textColor
self.backgroundColor = backgroundColor
}
public required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
// public final class func load(_ text: String? = nil, _ textColor: UIColor? = nil, _ backgroundColor: UIColor? = nil) -> SwiftyLabel
// {
// return SwiftyLabel(text, textColor, backgroundColor)
// }
}
extension SwiftyLabel
{
open override var intrinsicContentSize: CGSize
{
return overrideIntrinsicContentSize()
}
open override func draw(_ rect: CGRect)
{
overrideDraw(rect)
}
open override func sizeThatFits(_ size: CGSize) -> CGSize
{
return overrideSizeThatFits(size)
}
open override func sizeToFit()
{
super.sizeToFit()
overrideSizeToFit()
}
}
| 23.492958 | 136 | 0.613309 |
bf05eec05a57d19f4d9d2d752a651dbe7554885a | 298 | //
// HotCornerable.swift
// EyeSpeak
//
// Created by Kyle Ohanian on 4/23/19.
// Copyright © 2019 WillowTree. All rights reserved.
//
import Foundation
protocol HotCornerTrackable {
var component: HotCornerGazeableComponent? { get set }
var trackingEngine: TrackingEngine { get }
}
| 19.866667 | 58 | 0.714765 |
cc392e9be05e12a68add8a0d7f89b30563c99250 | 1,080 | //
// CGPoint+Extensions.swift
// FoundationExtensions
//
// Created by Luis Reisewitz on 14.01.20.
// Copyright © 2020 Lautsprecher Teufel GmbH. All rights reserved.
//
import CoreGraphics
// MARK: - AdditiveArithmetic Conformance
extension CGPoint: AdditiveArithmetic {
public static func -= (lhs: inout CGPoint, rhs: CGPoint) {
lhs.x -= rhs.x
lhs.y -= rhs.y
}
public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
public static func += (lhs: inout CGPoint, rhs: CGPoint) {
lhs.x += rhs.x
lhs.y += rhs.y
}
public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
}
// MARK: - Helper for constraining values
extension CGPoint {
public var noX: CGPoint {
CGPoint(x: 0, y: y)
}
public var onlyPositive: CGPoint {
CGPoint(x: x.clamped(to: 0...CGFloat.greatestFiniteMagnitude),
y: y.clamped(to: 0...CGFloat.greatestFiniteMagnitude))
}
}
| 25.116279 | 70 | 0.606481 |
90d93e77fb38444ae0bdcf0845d933fb1f32a261 | 2,897 | //
// FoundBookCell.swift
// Readyt
//
// Created by Raul Martinez Padilla on 08/09/2018.
// Copyright © 2018 Raul Martinez Padilla. All rights reserved.
//
import UIKit
import Kingfisher
class FoundBookCell: BaseCustomCell {
var book: JSONDomain.Book? {
didSet {
if let url = book?.volumeInfo.imageLinks?.thumbnail {
let placeholderImage = UIImage(named: "icons8-book_filled")
let httpsURL = URL(string: url.replacingOccurrences(of: "http", with: "https"))
let processor = ResizingImageProcessor(referenceSize: CGSize(width: 70, height: 70))
coverImage.kf.setImage(with: httpsURL,
placeholder: placeholderImage,
options: [.transition(.fade(0.2)),
.processor(processor)])
coverImage.contentMode = .scaleAspectFit
coverImage.layer.borderColor = UIColor.lightGray.cgColor
coverImage.layer.borderWidth = 1
}
if let title = book?.volumeInfo.title {
titleLabel.text = title
}
if let author = book?.volumeInfo.authors?.first {
authorLabel.text = author
}
}
}
static let width: CGFloat = UIScreen.mainWidth - 20
static let height: CGFloat = 100
let cellSize = CGSize(width: FoundBookCell.width,
height: FoundBookCell.height)
var coverImage: UIImageView = {
let cImage = UIImageView(frame: .zero)
return cImage
}()
var titleLabel: UILabel = {
let tLabel = UILabel(frame: .zero)
tLabel.numberOfLines = 2
tLabel.lineBreakMode = .byWordWrapping
tLabel.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.black)
return tLabel
}()
var authorLabel: UILabel = {
let aLabel = UILabel(frame: .zero)
aLabel.numberOfLines = 2
aLabel.lineBreakMode = .byWordWrapping
aLabel.font = UIFont.systemFont(ofSize: 14, weight: .light)
return aLabel
}()
override func setupViews() {
[coverImage, titleLabel, authorLabel].forEach { addSubview($0) }
coverImage.anchor(top: topAnchor,
leading: leadingAnchor,
bottom: nil,
trailing: nil,
padding: .init(top: 10, left: 10, bottom: 0, right: 0),
size: CGSize(width: 70, height: 70))
titleLabel.anchor(top: topAnchor,
leading: coverImage.trailingAnchor,
bottom: nil,
trailing: trailingAnchor,
padding: .init(top: 10, left: 10, bottom: 0, right: 0) )
authorLabel.anchor(top: titleLabel.bottomAnchor,
leading: coverImage.trailingAnchor,
bottom: nil,
trailing: trailingAnchor,
padding: .init(top: 10, left: 10, bottom: 0, right: 0) )
}
}
| 31.150538 | 92 | 0.590266 |
1eb9fb950255ca33019cfb5bbe0ad71ed066687b | 10,291 | import Combine
import XCTest
@testable import Thrimer
class ThrimerTests: XCTestCase {
var cancellables = Set<AnyCancellable>()
override func tearDown() {
cancellables.forEach { $0.cancel() }
}
/// Verify that timer has correct values while running
func testStartTimer() {
let thrimer = Thrimer(interval: 5.0, repeats: false)
thrimer.start()
let expect = expectation(description: "test")
let startTime = Date()
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
XCTAssertTrue(thrimer.isRunning)
XCTAssertNotNil(thrimer.timeRemaining)
XCTAssertEqual(Date().timeIntervalSince(startTime),
thrimer.timeRemaining!,
accuracy: 0.1)
expect.fulfill()
}
waitForExpectations(timeout: 2.0, handler: nil)
}
/// Validate the lifecycle of timer actions
func testTimerActionsCycle() {
let timerInterval = 3.0
let thrimer = Thrimer(interval: timerInterval)
// Setup expectations
let expectStart = expectation(description: "start")
let expectComplete = expectation(description: "complete")
let expectIdle = expectation(description: "idle")
let expectations = [expectStart, expectComplete, expectIdle]
let startTime = Date()
thrimer.$thrimerAction
.removeDuplicates()
.sink { action in
switch action {
case .idle:
expectIdle.fulfill()
case .start:
expectStart.fulfill()
case .completed:
XCTAssertEqual(Date().timeIntervalSince(startTime),
timerInterval,
accuracy: 0.1)
expectComplete.fulfill()
default:
XCTFail("Unexpected action")
}
}
.store(in: &cancellables)
wait(for: expectations,
timeout: timerInterval + 1.0,
enforceOrder: true)
}
/// Verify that the timer properly repeats in the expected sequence
/// and interval
func testStartTimerRepeats() {
let timerInterval = 0.5
let thrimer = Thrimer(interval: timerInterval,
repeats: true)
// Setup expectations
let expectFirst = expectation(description: "first")
let expectSecond = expectation(description: "second")
let expectThird = expectation(description: "third")
let expectations = [expectFirst, expectSecond, expectThird]
var usedExpectations = expectations
var startTime = Date()
thrimer.$thrimerAction
.sink { action in
switch action {
case .start:
startTime = Date()
case .completed:
XCTAssertEqual(Date().timeIntervalSince(startTime),
timerInterval,
accuracy: 0.1)
XCTAssertFalse(usedExpectations.isEmpty)
let expect = usedExpectations.removeFirst()
expect.fulfill()
default:
break
}
}
.store(in: &cancellables)
wait(for: expectations,
timeout: 1.75,
enforceOrder: true)
}
/// Verify that setting the timer object to nil is properly handled
func testSetTimerNil() {
var thrimer: Thrimer? = Thrimer(interval: 5.0, repeats: false)
thrimer?.start()
let expectIsRunning = expectation(description: "testIsRunning")
let expectIsNil = expectation(description: "testIsNil")
let expectations = [expectIsRunning, expectIsNil]
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
XCTAssert(thrimer?.isRunning == true)
thrimer = nil
expectIsRunning.fulfill()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
XCTAssertNil(thrimer)
expectIsNil.fulfill()
}
wait(for: expectations, timeout: 4.0, enforceOrder: true)
}
/// Verify that the correct actions and values are presented when
/// pausing and then resuming the timer.
func testPauseAndResume() {
let thrimer = Thrimer(interval: 5.0, repeats: false)
let expectStart = expectation(description: "start")
let expectPause = expectation(description: "pause")
let expectResume = expectation(description: "resume")
let expectCompleted = expectation(description: "completed")
let expectIdle = expectation(description: "idle")
let expectations = [expectStart, expectPause, expectResume, expectCompleted, expectIdle]
var usedExpectations = expectations
thrimer.$thrimerAction
.sink { action in
switch action {
case .completed:
XCTAssertFalse(usedExpectations.isEmpty)
let expect = usedExpectations.removeFirst()
expect.fulfill()
case .idle:
XCTAssertFalse(usedExpectations.isEmpty)
let expect = usedExpectations.removeFirst()
expect.fulfill()
case let .pause(interval):
XCTAssertEqual(interval,
1.0,
accuracy: 0.1)
XCTAssertFalse(usedExpectations.isEmpty)
let expect = usedExpectations.removeFirst()
expect.fulfill()
case .start:
XCTAssertFalse(usedExpectations.isEmpty)
let expect = usedExpectations.removeFirst()
expect.fulfill()
case .stop:
XCTFail("Should not occur")
}
}
.store(in: &cancellables)
XCTAssertTrue(thrimer.isRunning)
sleep(1)
thrimer.pause()
XCTAssertTrue(thrimer.isPaused)
sleep(1)
XCTAssertNil(thrimer.timeRemaining)
thrimer.resume()
XCTAssertNotNil(thrimer.timeRemaining)
XCTAssertTrue(thrimer.isRunning)
wait(for: expectations, timeout: 4.0, enforceOrder: true)
}
/// Verify that the timer has the correct properties and completes
/// in the expected order.
func testCompletion() {
let expectStart = expectation(description: "expectStart")
let expectCompleted = expectation(description: "expectCompleted")
let expectIdle = expectation(description: "expectIdle")
let expectations = [expectStart, expectCompleted, expectIdle]
let thrimer = Thrimer(interval: 2.0,
autostart: true)
XCTAssertTrue(thrimer.isRunning)
XCTAssertNotNil(thrimer.timeRemaining)
thrimer.$thrimerAction
.sink { action in
switch action {
case .start:
expectStart.fulfill()
case .completed:
XCTAssertFalse(thrimer.isRunning)
XCTAssertNil(thrimer.timeRemaining)
expectCompleted.fulfill()
case .idle:
expectIdle.fulfill()
default:
XCTFail("Unexpected action")
}
}
.store(in: &cancellables)
wait(for: expectations,
timeout: 3.0,
enforceOrder: true)
}
// Verify that restarting an active timer produces the correct sequence
// of actions and properties
func testTimerRestart() {
let thrimer = Thrimer(interval: 2.0)
let expectStart = expectation(description: "expectStart")
let expectRestart = expectation(description: "expectRestart")
let expectCompleted = expectation(description: "expectCompleted")
let expectIdle = expectation(description: "expectIdle")
let expectations = [expectStart, expectRestart, expectCompleted, expectIdle]
var startActions = [expectStart, expectRestart]
let startTime = Date()
thrimer.$thrimerAction
.sink { action in
switch action {
case .start:
XCTAssertFalse(startActions.isEmpty)
let expect = startActions.removeFirst()
expect.fulfill()
case .completed:
let timeElapsed = Date().timeIntervalSince(startTime)
XCTAssertGreaterThan(timeElapsed, 3.0)
expectCompleted.fulfill()
case .idle:
expectIdle.fulfill()
default:
XCTFail("Unexpected action")
}
}
.store(in: &cancellables)
sleep(1)
thrimer.start()
wait(for: expectations,
timeout: 4.0,
enforceOrder: true)
}
func testTimerStop() {
let thrimer = Thrimer(interval: 2.0)
let expectStart = expectation(description: "expectStart")
let expectStop = expectation(description: "expectStop")
let expectations = [expectStart, expectStop]
let startTime = Date()
thrimer.$thrimerAction
.sink { action in
switch action {
case .start:
expectStart.fulfill()
case .stop:
let timeElapsed = Date().timeIntervalSince(startTime)
XCTAssertGreaterThan(timeElapsed, 1.0)
XCTAssertFalse(thrimer.isRunning)
XCTAssertNil(thrimer.timeRemaining)
expectStop.fulfill()
default:
XCTFail("Unexpected action")
}
}
.store(in: &cancellables)
sleep(1)
thrimer.stop()
wait(for: expectations,
timeout: 3.0,
enforceOrder: true)
}
}
| 34.533557 | 96 | 0.54708 |
d9eb1d7800f49548fb46e6033c458c44e43667a6 | 287 | import XCTest
extension TemplateGeneratorTests {
static let allTests = [
("testGenerateJson", testGenerateJson),
]
}
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testcase(TemplateGeneratorTests.allTests),
]
}
#endif
| 17.9375 | 50 | 0.679443 |
d98bcedacb9db44f1fae5454cc3ce89ff6a85802 | 300 | class Solution {
func repeatedNTimes(_ A: [Int]) -> Int {
for value in 1...4 {
for element in 0..<(A.count - value) {
if A[element] == A[value + element] {
return A[element]
}
}
}
return 0
}
} | 25 | 53 | 0.396667 |
464eb425961f5d6ddc16bee773be715d5ca1bc6e | 329 | //
// SpriteKitLook.swift
// Look
//
// Created by wookyoung on 12/12/15.
// Copyright © 2015 factorcat. All rights reserved.
//
import SpriteKit
extension Look {
public convenience init(SKSpriteNode sprite: SKSpriteNode) {
self.init()
self.object = sprite
self.preview = .Sprite(sprite)
}
} | 19.352941 | 64 | 0.647416 |
76c3c6737c1c31dc7cbae70a08bab6654be12d6a | 28 | public struct Attributes {
} | 14 | 26 | 0.785714 |
e6eec9e87caeaa51ee442439e47cd4dba6762182 | 2,510 | //----------------------------------------------------------------------------------------------------------------------
//
// Copyright ©2022 Peter Baumgartner. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//----------------------------------------------------------------------------------------------------------------------
import SwiftUI
//----------------------------------------------------------------------------------------------------------------------
/// This is the root view for a BXMediaBrowser.Library
public struct LibraryView : View
{
// Model
@ObservedObject var library:Library
// Environment
@Environment(\.viewFactory) private var viewFactory
// Init
public init(with library:Library)
{
self.library = library
}
// View
public var body: some View
{
EfficientVStack(alignment:.leading, spacing:4)
{
ForEach(library.sections)
{
if SectionView.shouldDisplay($0)
{
viewFactory.sectionView(for:$0)
}
}
}
// Pass Library reference down the view hierarchy. This is needed for setting the selected Container.
.environmentObject(library)
// When important properties of the library have changed, then save the current state
// .onReceive(library.$selectedContainer)
// {
// _ in library.saveState()
// }
}
}
//----------------------------------------------------------------------------------------------------------------------
| 30.240964 | 120 | 0.581673 |
90c4b88cee3a1c4605d463e9748576ef0ad60236 | 3,189 | //
// Display.swift
// Thingy
//
// Created by Bojan Dimovski on 7/18/17.
// Copyright © 2017 Bojan Dimovski. All rights reserved.
//
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyright (C) 2004 Sam Hocevar <[email protected]>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is changed.
//
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
// 0. You just DO WHAT THE FUCK YOU WANT TO.
//
//
import Foundation
/// A struct that provides an extended info on the display.
public struct Display: Equatable {
/// An enum that describes the display size.
public enum Size: Float {
/// - screen38mm: 38mm Apple Watch screen.
case screen38mm = 38
/// - screen42mm: 42mm Apple Watch screen.
case screen42mm = 42
/// - screen40mm: 40mm Apple Watch screen.
case screen40mm = 40
/// - screen44mm: 44mm Apple Watch screen.
case screen44mm = 44
/// - screen3_5Inch: 3.5in iPhone screen.
case screen3_5Inch = 3.5
/// - screen4Inch: 4in iPhone/iPod touch screen.
case screen4Inch = 4
/// - screen4_7Inch: 4.7in iPhone screen.
case screen4_7Inch = 4.7
/// - screen5_5Inch: 5.5in iPhone screen.
case screen5_5Inch = 5.5
/// - screen5_8Inch: 5.8in iPhone screen.
case screen5_8Inch = 5.8
/// - screen6_1Inch: 6.1in iPhone screen.
case screen6_1Inch = 6.1
/// - screen6_5Inch: 6.5in iPhone screen.
case screen6_5Inch = 6.5
/// - screen7_9Inch: 7.9in iPad screen.
case screen7_9Inch = 7.9
/// - screen9_7Inch: 9.7in iPad screen.
case screen9_7Inch = 9.7
/// - screen10_5Inch: 10.2in iPad screen.
case screen10_2Inch = 10.2
/// - screen10_5Inch: 10.5in iPad screen.
case screen10_5Inch = 10.5
/// - screen10_5Inch: 10.5in iPad screen.
case screen11Inch = 11
/// - screen12_9Inch: 12.9in iPad screen.
case screen12_9Inch = 12.9
/// - notApplicable: Not applicable, in case of the Apple TV.
case notApplicable = -1
}
/// An enum that describes all color spaces.
public enum ColorSpace {
/// - Wide color display (P3)
case p3
/// - Full sRGB standard
case sRGB
}
/// Screen size in inches.
public var size: Size
/// Resolution of the device.
public var resolution: CGSize
/// Full physical resolution of the device, without any down-/up-sampling.
public var physicalResolution: CGSize
/// Rendered resolution of the device, with down-/up-sampling.
public var renderedResolution: CGSize
/// Screen scale, 1.0 for non-Retina devices.
public var scale: Float
/// Density of the display in PPI (pixels-per-inch).
public var density: Int
/// True Tone display.
public var hasTrueTone: Bool
/// Color space.
public var colorSpace: ColorSpace
}
// MARK: - Screen size comparison
extension Display.Size: Comparable {
public static func <(lhs: Display.Size, rhs: Display.Size) -> Bool {
lhs.rawValue < rhs.rawValue
}
public static func ==(lhs: Display.Size, rhs: Display.Size) -> Bool {
lhs.rawValue == rhs.rawValue
}
}
| 23.977444 | 75 | 0.682659 |
d938327876e6f9b605e166f0ae9785c97f328eb2 | 1,436 | //
// AppDelegate.swift
// MailViewExample
//
// Created by Mohammad Rahchamani on 4/5/1399 AP.
// Copyright © 1399 AP BetterSleep. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.789474 | 179 | 0.75 |
e8261bbc7001f3f0eec7531b7a2e10a9dc394ed3 | 1,692 | import CGtk
/// Describes whether a `GtkFileChooser` is being used to open existing files or to save to a possibly new file.
///
/// [Gtk docs](https://docs.gtk.org/gtk3/enum.FileChooserAction.html)
public enum FileChooserAction {
/// Indicates open mode. The file chooser will only let the user pick an existing file.
case `open`
/// Indicates save mode. The file chooser will let the user pick an existing file, or type in a new filename.
case save
/// Indicates an Open mode for selecting folders. The file chooser will let the user pick an existing folder.
case selectFolder
/// Indicates a mode for creating a new folder. The file chooser will let the user name an existing or new folder.
case createFolder
func toGtkFileChooserAction() -> GtkFileChooserAction {
switch self {
case .open:
return GTK_FILE_CHOOSER_ACTION_OPEN
case .save:
return GTK_FILE_CHOOSER_ACTION_SAVE
case .selectFolder:
return GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER
case .createFolder:
return GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER
}
}
}
extension GtkFileChooserAction {
func toFileChooserAction() -> FileChooserAction {
switch self {
case GTK_FILE_CHOOSER_ACTION_OPEN:
return .open
case GTK_FILE_CHOOSER_ACTION_SAVE:
return .save
case GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER:
return .selectFolder
case GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER:
return .createFolder
default:
fatalError("Unsupported GtkFileChooserAction enum value: \(self.rawValue)")
}
}
}
| 36.782609 | 118 | 0.682624 |
1dccbc175c27463d028a1c34c584deaca773bf54 | 989 | //
// PodCreationTests.swift
// PodCreationTests
//
// Created by dinesh sharma on 22/08/17.
// Copyright © 2017 dinesh sharma. All rights reserved.
//
import XCTest
@testable import PodCreation
class PodCreationTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.72973 | 111 | 0.639029 |
75bdcfce300cd6dda81d876dd4949f460af27278 | 1,164 | //
// TippyfyUITests.swift
// TippyfyUITests
//
// Created by Andres Contreras on 8/21/19.
// Copyright © 2019 530 Software. All rights reserved.
//
import XCTest
class TippyfyUITests: 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.257143 | 182 | 0.690722 |
750fe3bfcb0c5b0fb10b072daf0a8b27ea958ca2 | 390 | //
// SceneDelegate.swift
// iOS (App)
//
// Created by Julius Tarng on 11/24/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
}
}
| 20.526316 | 127 | 0.7 |
0e8184de9447cd5b0c1ee357e83e4c42f7f54f21 | 902 | //
// SwippyTests.swift
// SwippyTests
//
// Created by Sudipta Sahoo on 03/01/20.
// Copyright © 2020 Sudipta Sahoo. All rights reserved.
//
import XCTest
@testable import Swippy
class SwippyTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.771429 | 111 | 0.652993 |
e6e34e8cd82e809f2cac1f7de064a7f69063d3eb | 2,966 | // MIT License
//
// Copyright (c) 2022 Iosif
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
public struct DeckApi {
public init() {}
public func perform<Model: Codable>(_ route: Route,
output: Model.Type,
completion: @escaping (_ result: Result<Model, Error>) -> Void) {
guard let url = URL(string: route.path, relativeTo: Route.host) else {
fatalError("Failed to create url for route: \(route)")
}
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
let httpResponse = response as? HTTPURLResponse
guard error == nil, httpResponse?.statusCode == 200, let data = data else {
let genericError = NSError(domain: "api.error.unknown", code: -324)
completion(.failure(error ?? genericError))
return
}
parseResponse(data: data, completion: completion)
}
}.resume()
}
public func getImage(from url: URL, completion: @escaping (_ image: UIImage?) -> Void) {
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
let httpResponse = response as? HTTPURLResponse
guard httpResponse?.statusCode == 200, error == nil, let imageData = data else {
completion(nil)
return
}
completion(UIImage(data: imageData))
}
}.resume()
}
// MARK: - Helpers Methods
private func parseResponse<Model: Codable>(data: Data,
completion: @escaping (_ result: Result<Model, Error>) -> Void) {
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let model = try decoder.decode(Model.self, from: data)
completion(.success(model))
} catch {
completion(.failure(error))
}
}
}
| 40.081081 | 110 | 0.660486 |
dbe9f3cba79b4b08e83732a4b43e06fed94a8ddd | 12,790 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A wrapper around _RawSetStorage that provides most of the
/// implementation of Set.
@usableFromInline
@_fixed_layout
internal struct _NativeSet<Element: Hashable> {
/// See the comments on _RawSetStorage and its subclasses to understand why we
/// store an untyped storage here.
@usableFromInline
internal var _storage: _RawSetStorage
/// Constructs an instance from the empty singleton.
@inlinable
@inline(__always)
internal init() {
self._storage = _RawSetStorage.empty
}
/// Constructs a native set adopting the given storage.
@inlinable
@inline(__always)
internal init(_ storage: __owned _RawSetStorage) {
self._storage = storage
}
@inlinable
internal init(capacity: Int) {
self._storage = _SetStorage<Element>.allocate(capacity: capacity)
}
#if _runtime(_ObjC)
@inlinable
internal init(_ cocoa: __owned _CocoaSet) {
self.init(cocoa, capacity: cocoa.count)
}
@inlinable
internal init(_ cocoa: __owned _CocoaSet, capacity: Int) {
_sanityCheck(cocoa.count <= capacity)
self.init(capacity: capacity)
for element in cocoa {
let nativeElement = _forceBridgeFromObjectiveC(element, Element.self)
insertNew(nativeElement, isUnique: true)
}
}
#endif
}
extension _NativeSet { // Primitive fields
@usableFromInline
internal typealias Bucket = _HashTable.Bucket
@inlinable
internal var capacity: Int {
@inline(__always)
get {
return _assumeNonNegative(_storage._capacity)
}
}
@inlinable
internal var hashTable: _HashTable {
@inline(__always) get {
return _storage._hashTable
}
}
// This API is unsafe and needs a `_fixLifetime` in the caller.
@inlinable
internal var _elements: UnsafeMutablePointer<Element> {
return _storage._rawElements.assumingMemoryBound(to: Element.self)
}
}
extension _NativeSet { // Low-level unchecked operations
@inlinable
@inline(__always)
internal func uncheckedElement(at bucket: Bucket) -> Element {
defer { _fixLifetime(self) }
_sanityCheck(hashTable.isOccupied(bucket))
return _elements[bucket.offset]
}
@inlinable
@inline(__always)
internal func uncheckedInitialize(
at bucket: Bucket,
to element: __owned Element) {
_sanityCheck(hashTable.isValid(bucket))
(_elements + bucket.offset).initialize(to: element)
}
}
extension _NativeSet { // Low-level lookup operations
@inlinable
@inline(__always)
internal func hashValue(for element: Element) -> Int {
return element._rawHashValue(seed: _storage._seed)
}
@inlinable
@inline(__always)
internal func find(_ element: Element) -> (bucket: Bucket, found: Bool) {
return find(element, hashValue: self.hashValue(for: element))
}
/// Search for a given element, assuming it has the specified hash value.
///
/// If the element is not present in this set, return the position where it
/// could be inserted.
@inlinable
@inline(__always)
internal func find(
_ element: Element,
hashValue: Int
) -> (bucket: Bucket, found: Bool) {
let hashTable = self.hashTable
var bucket = hashTable.idealBucket(forHashValue: hashValue)
while hashTable._isOccupied(bucket) {
if uncheckedElement(at: bucket) == element {
return (bucket, true)
}
bucket = hashTable.bucket(wrappedAfter: bucket)
}
return (bucket, false)
}
}
extension _NativeSet { // ensureUnique
@inlinable
internal mutating func resize(capacity: Int) {
let capacity = Swift.max(capacity, self.capacity)
let result = _NativeSet(_SetStorage<Element>.allocate(capacity: capacity))
if count > 0 {
for bucket in hashTable {
let element = (self._elements + bucket.offset).move()
result._unsafeInsertNew(element)
}
// Clear out old storage, ensuring that its deinit won't overrelease the
// elements we've just moved out.
_storage._hashTable.clear()
_storage._count = 0
}
_storage = result._storage
}
@inlinable
internal mutating func copy(capacity: Int) -> Bool {
let capacity = Swift.max(capacity, self.capacity)
let (newStorage, rehash) = _SetStorage<Element>.reallocate(
original: _storage,
capacity: capacity)
let result = _NativeSet(newStorage)
if count > 0 {
if rehash {
for bucket in hashTable {
result._unsafeInsertNew(self.uncheckedElement(at: bucket))
}
} else {
result.hashTable.copyContents(of: hashTable)
result._storage._count = self.count
for bucket in hashTable {
let element = uncheckedElement(at: bucket)
result.uncheckedInitialize(at: bucket, to: element)
}
}
}
_storage = result._storage
return rehash
}
/// Ensure storage of self is uniquely held and can hold at least `capacity`
/// elements. Returns true iff contents were rehashed.
@inlinable
@inline(__always)
internal mutating func ensureUnique(isUnique: Bool, capacity: Int) -> Bool {
if _fastPath(capacity <= self.capacity && isUnique) {
return false
}
guard isUnique else {
return copy(capacity: capacity)
}
resize(capacity: capacity)
return true
}
@inlinable
internal mutating func reserveCapacity(_ capacity: Int, isUnique: Bool) {
_ = ensureUnique(isUnique: isUnique, capacity: capacity)
}
}
extension _NativeSet: _SetBuffer {
@usableFromInline
internal typealias Index = Bucket
@inlinable
internal var startIndex: Index {
return hashTable.startBucket
}
@inlinable
internal var endIndex: Index {
return hashTable.endBucket
}
@inlinable
internal func index(after index: Index) -> Index {
return hashTable.occupiedBucket(after: index)
}
@inlinable
@inline(__always)
internal func index(for element: Element) -> Index? {
if count == 0 {
// Fast path that avoids computing the hash of the key.
return nil
}
let (bucket, found) = find(element)
guard found else { return nil }
return bucket
}
@inlinable
internal var count: Int {
@inline(__always) get {
return _assumeNonNegative(_storage._count)
}
}
@inlinable
@inline(__always)
internal func contains(_ member: Element) -> Bool {
// Fast path: Don't calculate the hash if the set has no elements.
if count == 0 { return false }
return find(member).found
}
@inlinable
@inline(__always)
internal func element(at index: Index) -> Element {
hashTable.checkOccupied(index)
return _elements[index.offset]
}
}
// This function has a highly visible name to make it stand out in stack traces.
@usableFromInline
@inline(never)
internal func ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(
_ elementType: Any.Type
) -> Never {
_assertionFailure(
"Fatal error",
"""
Duplicate elements of type '\(elementType)' were found in a Set.
This usually means either that the type violates Hashable's requirements, or
that members of such a set were mutated after insertion.
""",
flags: _fatalErrorFlags())
}
extension _NativeSet { // Insertions
/// Insert a new element into uniquely held storage.
/// Storage must be uniquely referenced with adequate capacity.
/// The `element` must not be already present in the Set.
@inlinable
internal func _unsafeInsertNew(_ element: __owned Element) {
_sanityCheck(count + 1 <= capacity)
let hashValue = self.hashValue(for: element)
if _isDebugAssertConfiguration() {
// In debug builds, perform a full lookup and trap if we detect duplicate
// elements -- these imply that the Element type violates Hashable
// requirements. This is generally more costly than a direct insertion,
// because we'll need to compare elements in case of hash collisions.
let (bucket, found) = find(element, hashValue: hashValue)
guard !found else {
ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)
}
hashTable.insert(bucket)
uncheckedInitialize(at: bucket, to: element)
} else {
let bucket = hashTable.insertNew(hashValue: hashValue)
uncheckedInitialize(at: bucket, to: element)
}
_storage._count += 1
}
/// Insert a new element into uniquely held storage.
/// Storage must be uniquely referenced.
/// The `element` must not be already present in the Set.
@inlinable
internal mutating func insertNew(_ element: __owned Element, isUnique: Bool) {
_ = ensureUnique(isUnique: isUnique, capacity: count + 1)
_unsafeInsertNew(element)
}
@inlinable
internal func _unsafeInsertNew(_ element: __owned Element, at bucket: Bucket) {
hashTable.insert(bucket)
uncheckedInitialize(at: bucket, to: element)
_storage._count += 1
}
@inlinable
internal mutating func insertNew(
_ element: __owned Element,
at bucket: Bucket,
isUnique: Bool
) {
_sanityCheck(!hashTable.isOccupied(bucket))
var bucket = bucket
let rehashed = ensureUnique(isUnique: isUnique, capacity: count + 1)
if rehashed {
let (b, f) = find(element)
if f {
ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)
}
bucket = b
}
_unsafeInsertNew(element, at: bucket)
}
@inlinable
internal mutating func update(
with element: __owned Element,
isUnique: Bool
) -> Element? {
var (bucket, found) = find(element)
let rehashed = ensureUnique(
isUnique: isUnique,
capacity: count + (found ? 0 : 1))
if rehashed {
let (b, f) = find(element)
if f != found {
ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)
}
bucket = b
}
if found {
let old = (_elements + bucket.offset).move()
uncheckedInitialize(at: bucket, to: element)
return old
}
_unsafeInsertNew(element, at: bucket)
return nil
}
}
extension _NativeSet: _HashTableDelegate {
@inlinable
@inline(__always)
internal func hashValue(at bucket: Bucket) -> Int {
return hashValue(for: uncheckedElement(at: bucket))
}
@inlinable
@inline(__always)
internal func moveEntry(from source: Bucket, to target: Bucket) {
(_elements + target.offset)
.moveInitialize(from: _elements + source.offset, count: 1)
}
}
extension _NativeSet { // Deletion
@inlinable
internal mutating func _delete(at bucket: Bucket) {
hashTable.delete(at: bucket, with: self)
_storage._count -= 1
}
@inlinable
@inline(__always)
internal mutating func uncheckedRemove(
at bucket: Bucket,
isUnique: Bool) -> Element {
_sanityCheck(hashTable.isOccupied(bucket))
let rehashed = ensureUnique(isUnique: isUnique, capacity: capacity)
_sanityCheck(!rehashed)
let old = (_elements + bucket.offset).move()
_delete(at: bucket)
return old
}
@inlinable
@inline(__always)
internal mutating func remove(at index: Index, isUnique: Bool) -> Element {
_precondition(hashTable.isOccupied(index), "Invalid index")
return uncheckedRemove(at: index, isUnique: isUnique)
}
@usableFromInline
internal mutating func removeAll(isUnique: Bool) {
guard isUnique else {
let scale = self._storage._scale
_storage = _SetStorage<Element>.allocate(scale: scale)
return
}
for bucket in hashTable {
(_elements + bucket.offset).deinitialize(count: 1)
}
hashTable.clear()
_storage._count = 0
}
}
extension _NativeSet: Sequence {
@usableFromInline
@_fixed_layout
internal struct Iterator {
// The iterator is iterating over a frozen view of the collection state, so
// it keeps its own reference to the set.
@usableFromInline
internal let base: _NativeSet
@usableFromInline
internal var iterator: _HashTable.Iterator
@inlinable
init(_ base: __owned _NativeSet) {
self.base = base
self.iterator = base.hashTable.makeIterator()
}
}
@inlinable
internal __consuming func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension _NativeSet.Iterator: IteratorProtocol {
@inlinable
internal mutating func next() -> Element? {
guard let index = iterator.next() else { return nil }
return base.uncheckedElement(at: index)
}
}
| 28.485523 | 81 | 0.680844 |
acae90f753e320124bfe493ed198b391e9ff5964 | 1,019 | //
// PassInformationTests.swift
// PassInformationTests
//
// Created by Carlos Santiago Cruz on 30/08/18.
// Copyright © 2018 Carlos Santiago Cruz. All rights reserved.
//
import XCTest
@testable import PassInformation
class PassInformationTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.540541 | 111 | 0.647694 |
4aacec63d13f17ade43f2b0b94be69be7def308c | 4,857 | //===--------------- VirtualPath.swift - Swift Virtual Paths --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
/// A virtual path.
public enum VirtualPath: Hashable {
/// A relative path that has not been resolved based on the current working
/// directory.
case relative(RelativePath)
/// An absolute path in the file system.
case absolute(AbsolutePath)
/// Standard input
case standardInput
/// Standard output
case standardOutput
/// A temporary file with the given name.
case temporary(RelativePath)
/// Form a virtual path which may be either absolute or relative.
public init(path: String) throws {
if let absolute = try? AbsolutePath(validating: path) {
self = .absolute(absolute)
} else {
let relative = try RelativePath(validating: path)
self = .relative(relative)
}
}
/// The name of the path for presentation purposes.
///
/// FIXME: Maybe this should be debugDescription or description
public var name: String {
switch self {
case .relative(let path):
return path.pathString
case .absolute(let path):
return path.pathString
case .standardInput, .standardOutput:
return "-"
case .temporary(let path):
return path.pathString
}
}
/// The extension of this path, for relative or absolute paths.
public var `extension`: String? {
switch self {
case .relative(let path), .temporary(let path):
return path.extension
case .absolute(let path):
return path.extension
case .standardInput, .standardOutput:
return nil
}
}
/// Whether this virtual path is to a temporary.
public var isTemporary: Bool {
switch self {
case .relative(_):
return false
case .absolute(_):
return false
case .standardInput, .standardOutput:
return false
case .temporary(_):
return true
}
}
public var absolutePath: AbsolutePath? {
switch self {
case let .absolute(absolutePath): return absolutePath
default: return nil
}
}
}
extension VirtualPath: Codable {
private enum CodingKeys: String, CodingKey {
case relative, absolute, standardInput, standardOutput, temporary
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .relative(let a1):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .relative)
try unkeyedContainer.encode(a1)
case .absolute(let a1):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .absolute)
try unkeyedContainer.encode(a1)
case .standardInput:
_ = container.nestedUnkeyedContainer(forKey: .standardInput)
case .standardOutput:
_ = container.nestedUnkeyedContainer(forKey: .standardOutput)
case .temporary(let a1):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .temporary)
try unkeyedContainer.encode(a1)
}
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
guard let key = values.allKeys.first(where: values.contains) else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key"))
}
switch key {
case .relative:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode(RelativePath.self)
self = .relative(a1)
case .absolute:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode(AbsolutePath.self)
self = .absolute(a1)
case .standardInput:
self = .standardInput
case .standardOutput:
self = .standardOutput
case .temporary:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode(RelativePath.self)
self = .temporary(a1)
}
}
}
extension VirtualPath {
/// Replace the extension of the given path with a new one based on the
/// specified file type.
public func replacingExtension(with fileType: FileType) throws -> VirtualPath {
let pathString: String
if let ext = self.extension {
pathString = String(name.dropLast(ext.count + 1))
} else {
pathString = name
}
return try VirtualPath(path: pathString.appendingFileTypeExtension(fileType))
}
}
| 29.615854 | 127 | 0.676138 |
1c52fe2855485c22db1519965e6317084dba9a5e | 820 | import UIKit
public final class WrapperView: UIView {
// MARK: - Life Cycle
public init(wrappedView: UIView, outset: CGFloat = 20) {
self.wrappedView = wrappedView
super.init(
frame: .init(
x: 0,
y: 0,
width: wrappedView.bounds.width + 2 * outset,
height: wrappedView.bounds.height + 2 * outset
)
)
addSubview(wrappedView)
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Properties
private let wrappedView: UIView
// MARK: - UIView
public override func layoutSubviews() {
wrappedView.center = .init(x: bounds.midX, y: bounds.midY)
}
}
| 21.578947 | 66 | 0.562195 |
5624abd06b4df1eaffdadaade604592a03ffc0d7 | 494 | //
// VNTrackRectangleRequest+Rx.swift
// RxVision
//
// Created by Maxim Volgin on 04/02/2019.
// Copyright (c) RxSwiftCommunity. All rights reserved.
//
import Vision
import RxSwift
@available(iOS 11.0, *)
extension Reactive where Base: VNTrackRectangleRequest {
public static func request<T>(rectangleObservation observation: VNRectangleObservation) -> RxVNTrackRectangleRequest<T> {
return RxVNTrackRectangleRequest<T>(rectangleObservation: observation)
}
}
| 24.7 | 125 | 0.740891 |
3972689f513c822055fd51a2fed5b29cf1684ca7 | 340 | //
// ViewController.swift
// CuckooExample
//
// Created by Nicholas Babo on 05/03/20.
// Copyright © 2020 Nicholas Babo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 16.190476 | 58 | 0.667647 |
4aaf28a0fbf37095d887e05427eb1da7c7d32308 | 1,743 | //
// Error.swift
// GLib
//
// Created by Rene Hexel on 27/04/2017.
// Copyright © 2017, 2019, 2020 Rene Hexel. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import CGLib
/// Alias for a reference wrapping a `GError` pointer
public typealias GLibErrorRef = ErrorRef
/// Alias for a reference wrapping a `GError` pointer
public typealias GLibErrorProtocol = ErrorProtocol
/// CustomStringConvertible extension for GError GLibError
public extension GLibErrorProtocol {
/// The error message associated with the receiver.
@inlinable var description: String {
return String(cString: error_ptr.pointee.message)
}
/// The error domain, code, and message associated with the receiver.
@inlinable var debugDescription: String {
return String("\(quarkToString(quark: error_ptr.pointee.domain) ?? "-") error \(error_ptr.pointee.code): \(String(cString: error_ptr.pointee.message) )")
}
}
public extension GLibError {
/// Initialise from a raw Integer value
/// - Parameter rawValue: value to initalise from
@inlinable convenience init(rawValue: Int32) {
let quark = g_quark_from_string("Error \(rawValue)")
let error: UnsafeMutablePointer<GError> = g_error_new_literal(quark, rawValue, g_quark_to_string(quark))
self.init(cPointer: error)
}
/// Raw error code
@inlinable var rawValue: Int32 {
get { Int32(error_ptr.pointee.code) }
set { error_ptr.pointee.code = gint(newValue) }
}
}
extension GLibError: CustomStringConvertible {}
extension GLibError: CustomDebugStringConvertible {}
extension GLibErrorRef: CustomStringConvertible {}
extension GLibErrorRef: CustomDebugStringConvertible {}
| 31.690909 | 161 | 0.717728 |
79bb51b56d0d79a84086380a038f198d2fbee593 | 1,350 | //
// TextFieldCellModel.swift
// MTZTableManager
//
// Copyright (c) 2017 Mauricio Tremea Zaquia (@mtzaquia)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import MTZTableViewManager
class TextFieldCellModel: NSObject, MTZModel {
var placeholderText: String?
var keyboardType: UIKeyboardType?
}
| 40.909091 | 80 | 0.765926 |
39f280b2beb921f2828ed36c76c20a06fb5515e3 | 796 | //
// TipCalcUITestsLaunchTests.swift
// TipCalcUITests
//
// Created by Devin Padron on 1/12/22.
//
import XCTest
class TipCalcUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}
| 24.121212 | 88 | 0.672111 |
db3654412e652b78f7e6a815d281dd977ebe9818 | 238 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a {
var d = [ {
case
( {
let a {
{
}
class a {
class
case ,
| 15.866667 | 87 | 0.701681 |
169048e941d0c4d0d849125908ea6c03d93d97ec | 3,192 | //
// CoreData.swift
// simpledata
//
// Created by user on 9/20/20.
//
import CoreData
public class PersistentCloudKitContainer {
// MARK: - Define Constants / Variables
public static var context: NSManagedObjectContext {
return persistentContainer.viewContext
}
// MARK: - Initializer
private init() {}
// MARK: - Core Data stack
public static var persistentContainer: NSPersistentContainer = {
// using "New File..." from the Project Navigator, must have created a CoreData -- "Data Model" of same name e.g. simpledata.xcdatamodeld
let container = NSPersistentContainer(name: "simpledata")
// Set location, via NSPersistentStoreDescription, for CoreData storage in local filesystem
// THIS SECTION CAN BE COMMENTED OUT BUT BE AWARE, YOU MUST USE THE URL OPTION IF YOU INTEND TO USE THIS FEATURE
// Failing to set the url for the description causes it to point to /dev/null which is bad.
let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
let url = storeDirectory.appendingPathComponent("simpledata.sqlite")
let description = NSPersistentStoreDescription(url: url)
description.shouldMigrateStoreAutomatically = true
description.shouldInferMappingModelAutomatically = true
description.shouldAddStoreAsynchronously = false
container.persistentStoreDescriptions = [description]
// END Set Location of CoreData storage
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
// This if statement can also be commented out
// It is used to help locate the coredata storage file in the local filesystem
// really only useful for debugging
if let storeDescription = storeDescription as NSPersistentStoreDescription? {
print("CoreData Store fileType: \(storeDescription.type)")
print("CoreData Store url: \(storeDescription.url!)")
print("Add Store Async? \(storeDescription.shouldAddStoreAsynchronously)")
print("Migrate Store Auto? \(storeDescription.shouldMigrateStoreAutomatically)")
print("Infer Mapping Model Auto? \(storeDescription.shouldInferMappingModelAutomatically)")
print("--------- Datastore Config Review Complete ------------")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return container
}()
// MARK: - Core Data Saving support
public static func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 44.957746 | 145 | 0.658835 |
fb04700e7f7abe26e2f36d4e064cc1c941026c9c | 1,643 | import XCTest
@testable import Git
class TestUser: XCTestCase {
override func setUp() {
Hub.session = Session()
Hub.factory.rest = MockRest()
}
func testNonEmpty() {
update("", email: "")
update("", email: "[email protected]")
update("test", email: "")
}
func testCommitCharacters() {
update("hello", email: "test<@mail.com")
update("hello", email: "test>@mail.com")
update("h<ello", email: "[email protected]")
update("h>ello", email: "[email protected]")
update("hello", email: "[email protected]\n")
update("hello\n", email: "[email protected]")
update("hello", email: "[email protected]\t")
update("hello\t", email: "[email protected]")
}
func testAt() {
update("test", email: "testmail.com")
update("test", email: "test@@mail.com")
update("test", email: "@mail.com")
}
func testDot() {
update("test", email: "test@mailcom")
update("test", email: "test@mailcom.")
update("test", email: "[email protected]")
}
func testWeird() {
update("test", email: "test@ mail.com")
update("test", email: "test @mail.com")
update("test", email: "te [email protected]")
update("test", email: " [email protected]")
update("test", email: "[email protected] ")
}
private func update(_ user: String, email: String) {
let expect = expectation(description: "")
Hub.session.update(user, email: email, error: { _ in
expect.fulfill()
}) { XCTFail() }
waitForExpectations(timeout: 1)
}
}
| 29.872727 | 60 | 0.539866 |
edf0f35bb4e0522b9990f9155b73dabd8965a92e | 259 | //
// MediaList.swift
// SimRadio
//
// Created by Alexey Vorobyov on 08.03.2022.
//
import UIKit
struct MediaList: Identifiable {
let id: UUID
let title: String
let description: String
let coverArt: UIImage
var list: [MediaSource]
}
| 15.235294 | 45 | 0.664093 |
ffe7acf16f8a0ef65dfebe1c1464ff37e12942a1 | 17,141 | //
// FuguAppFlow.swift
// Fugu
//
// Created by clickpass on 7/11/17.
//
import UIKit
class FuguFlowManager: NSObject {
public static var shared = FuguFlowManager()
class var bundle: Bundle? {
let podBundle = Bundle(for: AllConversationsViewController.self)
guard let bundleURL = podBundle.url(forResource: "Hippo", withExtension: "bundle"), let fetchBundle = Bundle(url: bundleURL) else {
// guard let bundleURL = podBundle.url(forResource: "HippoChat", withExtension: "bundle"), let fetchBundle = Bundle(url: bundleURL) else {
return podBundle
}
return fetchBundle
}
fileprivate let storyboard = UIStoryboard(name: "FuguUnique", bundle: bundle)
//MARK: AgentNavigation methods
func pushAgentConversationViewController(channelId: Int, channelName: String, channelType : channelType? = .DEFAULT) {
let conVC = AgentConversationViewController.getWith(channelID: channelId, channelName: channelName)
let navVc = UINavigationController(rootViewController: conVC)
navVc.setTheme()
navVc.modalPresentationStyle = .fullScreen
getLastVisibleController()?.present(navVc, animated: true, completion: nil)
}
func pushAgentConversationViewController(chatAttributes: AgentDirectChatAttributes) {
let conVC = AgentConversationViewController.getWith(chatAttributes: chatAttributes)
let navVc = UINavigationController(rootViewController: conVC)
navVc.setTheme()
navVc.modalPresentationStyle = .fullScreen
getLastVisibleController()?.present(navVc, animated: true, completion: nil)
}
// MARK: - Navigation Methods
func presentCustomerConversations(animation: Bool = true) {
guard let navigationController = storyboard.instantiateViewController(withIdentifier: "FuguCustomerNavigationController") as? UINavigationController else {
return
}
let visibleController = getLastVisibleController()
navigationController.modalPresentationStyle = .fullScreen
visibleController?.present(navigationController, animated: animation, completion: nil)
}
func presentCustomerConversations(on viewController: UIViewController, animation: Bool = true) {
guard let navigationController = storyboard.instantiateViewController(withIdentifier: "FuguCustomerNavigationController") as? UINavigationController, let topVC = navigationController.topViewController else {
return
}
// let visibleController = getLastVisibleController()
viewController.navigationController?.pushViewController(topVC, animated: animation)
// visibleController?.present(navigationController, animated: animation, completion: nil)
}
func presentPromotionalpushController(animation: Bool = true) {
guard let navigationController = storyboard.instantiateViewController(withIdentifier: "FuguPromotionalNavigationController") as? UINavigationController else {
return
}
let visibleController = getLastVisibleController()
guard ((visibleController as? PromotionsViewController) == nil) else {
return
}
navigationController.modalPresentationStyle = .fullScreen
visibleController?.present(navigationController, animated: animation, completion: nil)
}
func presentNLevelViewController(animation: Bool = true) {
self.openFAQScreen(animation: animation)
}
func openFAQScreen(animation: Bool) {
guard let vc = NLevelViewController.get(with: [HippoSupportList](), title: HippoSupportList.FAQName) else {
return
}
let visibleController = getLastVisibleController()
let navVC = UINavigationController(rootViewController: vc)
navVC.setTheme()
vc.isFirstLevel = true
navVC.modalPresentationStyle = .fullScreen
visibleController?.present(navVC, animated: animation, completion: nil)
}
func presentBroadcastController(animation: Bool = true) {
let visibleController = getLastVisibleController()
guard let navVC = BroadCastViewController.getNavigation() else {
return
}
navVC.modalPresentationStyle = .fullScreen
visibleController?.present(navVC, animated: animation, completion: nil)
}
func openDirectConversationHome() {
guard HippoConfig.shared.appUserType == .agent else {
return
}
guard let nav = AgentDirectViewController.get() else {
return
}
let visibleController = getLastVisibleController()
nav.modalPresentationStyle = .fullScreen
visibleController?.present(nav, animated: true, completion: nil)
}
func openDirectAgentConversation(channelTitle: String?) {
guard HippoConfig.shared.appUserType == .agent else {
return
}
guard !AgentConversationManager.searchUserUniqueKeys.isEmpty, let transactionId = AgentConversationManager.transactionID else {
return
}
let attributes = AgentDirectChatAttributes(otherUserUniqueKey: AgentConversationManager.searchUserUniqueKeys[0], channelName: channelTitle, transactionID: transactionId.trimWhiteSpacesAndNewLine())
let vc = AgentConversationViewController.getWith(chatAttributes: attributes)
vc.isSingleChat = true
let naVC = UINavigationController(rootViewController: vc)
let visibleController = getLastVisibleController()
naVC.modalPresentationStyle = .fullScreen
visibleController?.present(naVC, animated: true, completion: nil)
}
func openChatViewController(labelId: Int) {
let conversationViewController = ConversationsViewController.getWith(labelId: labelId.description)
let visibleController = getLastVisibleController()
//TODO: - Try to hit getByLabelId hit before presenting controller
let navVC = UINavigationController(rootViewController: conversationViewController)
navVC.setNavigationBarHidden(true, animated: false)
navVC.modalPresentationStyle = .fullScreen
conversationViewController.createConversationOnStart = true
visibleController?.present(navVC, animated: false, completion: nil)
}
func openChatViewControllerTempFunc(labelId: Int) {
let conversationViewController = ConversationsViewController.getWith(labelId: labelId.description)
let visibleController = getLastVisibleController()
//TODO: - Try to hit getByLabelId hit before presenting controller
let navVC = UINavigationController(rootViewController: conversationViewController)
navVC.setNavigationBarHidden(true, animated: false)
conversationViewController.createConversationOnStart = true
navVC.modalPresentationStyle = .fullScreen
visibleController?.present(navVC, animated: true, completion: nil)
}
func openChatViewController(on viewController: UIViewController, labelId: Int, hideBackButton: Bool, animation: Bool) {
let conversationViewController = ConversationsViewController.getWith(labelId: labelId.description)
// let visibleController = getLastVisibleController()
//TODO: - Try to hit getByLabelId hit before presenting controller
// let navVC = UINavigationController(rootViewController: conversationViewController)
// navVC.setNavigationBarHidden(true, animated: false)
conversationViewController.createConversationOnStart = false
conversationViewController.hideBackButton = hideBackButton
viewController.navigationController?.pushViewController(conversationViewController, animated: animation)
// visibleController?.present(navVC, animated: false, completion: nil)
}
func showFuguChat(_ chat: FuguNewChatAttributes, createConversationOnStart: Bool = false) {
let visibleViewController = getLastVisibleController()
let convVC = ConversationsViewController.getWith(chatAttributes: chat)
let navVC = UINavigationController(rootViewController: convVC)
navVC.setNavigationBarHidden(true, animated: false)
convVC.createConversationOnStart = createConversationOnStart
navVC.modalPresentationStyle = .fullScreen
visibleViewController?.present(navVC, animated: false, completion: nil)
}
func showFuguChat(on viewController: UIViewController, chat: FuguNewChatAttributes, createConversationOnStart: Bool = false) {
// let visibleViewController = getLastVisibleController()
let convVC = ConversationsViewController.getWith(chatAttributes: chat)
// let navVC = UINavigationController(rootViewController: convVC)
// navVC.setNavigationBarHidden(true, animated: false)
convVC.createConversationOnStart = createConversationOnStart
// visibleViewController?.present(navVC, animated: false, completion: nil)
viewController.navigationController?.pushViewController(convVC, animated: true)
}
func consultNowButtonClicked(consultNowInfoDict: [String: Any]){
// var fuguNewChatAttributes = FuguNewChatAttributes(transactionId: "", userUniqueKey: HippoConfig.shared.userDetail?.userUniqueKey, otherUniqueKey: nil, tags: HippoProperty.current.newConversationButtonTags, channelName: nil, preMessage: "", groupingTag: nil)
var transactionId = ""
if let id = consultNowInfoDict["transactionId"] as? Int {
transactionId = "\(id)"
}else if let id = consultNowInfoDict["transactionId"] as? String{
transactionId = id
}
var fuguNewChatAttributes = FuguNewChatAttributes(transactionId: transactionId, userUniqueKey: HippoConfig.shared.userDetail?.userUniqueKey, otherUniqueKey: nil, tags: HippoProperty.current.newConversationButtonTags, channelName: nil, preMessage: "", groupingTag: nil)
print("bodID******* \(HippoProperty.current.newconversationBotGroupId ?? "")")
print("bodID*******FuguAppFlow")
// fuguNewChatAttributes.botGroupId = HippoProperty.current.newconversationBotGroupId//"72"//
if let botID = HippoProperty.current.newconversationBotGroupId, botID != ""{
fuguNewChatAttributes.botGroupId = botID
}
let visibleViewController = getLastVisibleController()
let convVC = ConversationsViewController.getWith(chatAttributes: fuguNewChatAttributes)
let navVC = UINavigationController(rootViewController: convVC)
navVC.setNavigationBarHidden(true, animated: false)
convVC.createConversationOnStart = true
convVC.consultNowInfoDict = consultNowInfoDict
convVC.isComingFromConsultNowButton = true
navVC.modalPresentationStyle = .fullScreen
visibleViewController?.present(navVC, animated: false, completion: nil)
}
// func presentPromotionalpushController(animation: Bool = true) {
//
// guard let navigationController = storyboard.instantiateViewController(withIdentifier: "FuguPromotionalNavigationController") as? UINavigationController else {
// return
// }
// let visibleController = getLastVisibleController()
// navigationController.modalPresentationStyle = .fullScreen
// visibleController?.present(navigationController, animated: animation, completion: nil)
//
// }
func presentAgentConversations() {
guard HippoConfig.shared.appUserType == .agent else {
return
}
guard let nav = AgentHomeViewController.get() else {
return
}
let visibleController = getLastVisibleController()
nav.modalPresentationStyle = .fullScreen
visibleController?.present(nav, animated: true, completion: nil)
}
func presentPrePaymentController(_ url : String, _ channelId : Int){
guard let urlString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }
guard let config = WebViewConfig(url: urlString, title: HippoStrings.payment) else { return }
let vc = PrePaymentViewController.getNewInstance(config: config)
vc.isComingForPayment = true
let navVC = UINavigationController(rootViewController: vc)
navVC.setNavigationBarHidden(true, animated: false)
let visibleController = getLastVisibleController()
navVC.modalPresentationStyle = .fullScreen
vc.isPrePayment = true
vc.channelId = channelId
vc.isPaymentCancelled = {(sucess) in
HippoConfig.shared.HippoPrePaymentCancelled?()
}
vc.isPaymentSuccess = {(status) in
HippoConfig.shared.HippoPrePaymentSuccessful?(status)
}
visibleController?.present(navVC, animated: true, completion: nil)
}
func toShowInAppNotification(userInfo: [String: Any]) -> Bool {
if validateFuguCredential() == false {
return false
}
if let muid = userInfo["muid"] as? String {
if HippoConfig.shared.muidList.contains(muid) {
return false
}
HippoConfig.shared.muidList.append(muid)
}
if getLastVisibleController() is PromotionsViewController{
return false
}
updatePushCount(pushInfo: userInfo)
if let keys = userInfo["user_unique_key"] as? [String] {
UnreadCount.increaseUnreadCounts(for: keys)
}
pushTotalUnreadCount()
switch HippoConfig.shared.appUserType {
case .agent:
return showNotificationForAgent(with: userInfo)
case .customer:
break
}
let visibleController: UIViewController? = getLastVisibleController()
if let lastVisibleCtrl = visibleController as? AllConversationsViewController {
lastVisibleCtrl.updateChannelsWithrespectToPush(pushInfo: userInfo)
if UIApplication.shared.applicationState == .inactive {
// HippoConfig.shared.handleRemoteNotification(userInfo: userInfo)
return false
}
return true
}
return updateConversationVcForPush(userInfo: userInfo)
}
func presentFormCollector(forms: [FormData], animated: Bool = true) {
let vc = HippoDataCollectorController.get(forms: forms)
let visibleController = getLastVisibleController()
let navVC = UINavigationController(rootViewController: vc)
navVC.setTheme()
navVC.modalPresentationStyle = .fullScreen
visibleController?.present(navVC, animated: animated, completion: nil)
}
private func showNotificationForAgent(with userInfo: [String: Any]) -> Bool {
let currentChannelId = currentAgentChannelID()
let recievedId = userInfo["channel_id"] as? Int ?? userInfo["label_id"] as? Int ?? -1
guard currentChannelId != -1, recievedId > 0 else {
return true
}
if UIApplication.shared.applicationState == .inactive {
// HippoConfig.shared.handleRemoteNotification(userInfo: userInfo)
return false
}
if currentChannelId != recievedId {
return true
}
return false
}
private func currentAgentChannelID() -> Int {
let visibleController: UIViewController? = getLastVisibleController()
guard let vc = visibleController as? AgentConversationViewController, vc.channel != nil else {
return -1
}
return vc.channel.id
}
private func updateConversationVcForPush(userInfo: [String: Any]) -> Bool {
let visibleController = getLastVisibleController()
if let conversationVC = visibleController as? ConversationsViewController {
let recievedId = userInfo["channel_id"] as? Int ?? -1
let recievedLabelId = userInfo["label_id"] as? Int ?? -1
var isPresent = false
if let id = conversationVC.channel?.id, id > 0 {
isPresent = conversationVC.channel?.id != recievedId
} else {
isPresent = conversationVC.labelId != recievedLabelId
}
updatePushCount(pushInfo: userInfo)
if let navVC = conversationVC.navigationController, isPresent {
let existingViewControllers = navVC.viewControllers
for existingController in existingViewControllers {
if let lastVisibleCtrl = existingController as? AllConversationsViewController {
lastVisibleCtrl.updateChannelsWithrespectToPush(pushInfo: userInfo)
break
}
}
}
if UIApplication.shared.applicationState == .inactive {
return false
}
return isPresent
}
return true
}
}
| 45.107895 | 276 | 0.686541 |
d6c4f468d32c8411bc74e692ff23912860ad312d | 1,736 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS GENERATED BY EASY BINDINGS, DO NOT MODIFY IT
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
extension EBGraphicView {
//····················································································································
final func setIssue (_ inBezierPathes : [EBBezierPath], _ issueKind : CanariIssueKind) {
if self.mIssueBezierPathes != inBezierPathes {
if !self.issueBoundingBox.isEmpty {
self.setNeedsDisplay (self.issueBoundingBox.insetBy (dx: -1.0, dy: -1.0))
}
self.mIssueBezierPathes = inBezierPathes
self.mIssueKind = issueKind
self.setNeedsDisplayAndUpdateViewBounds ()
if !self.issueBoundingBox.isEmpty {
self.scrollToVisible (self.issueBoundingBox)
// self.setNeedsDisplay (self.issueBoundingBox.insetBy (dx: -1.0, dy: -1.0))
}
}
}
//····················································································································
final internal var issueBoundingBox : NSRect {
var box = NSRect.null
for bp in self.mIssueBezierPathes {
box = box.union (bp.bounds)
}
return box
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 39.454545 | 120 | 0.345046 |
1dfef9c6aa030c5f2aa5ba268acb50ec71698580 | 210 | //
// Bearer.swift
// Water My Plants
//
// Created by Dahna on 5/27/20.
// Copyright © 2020 Casanova Studios. All rights reserved.
//
import Foundation
struct Bearer: Codable {
let token: String
}
| 13.125 | 59 | 0.661905 |
91e4077d8692b636bb06c1b5eae7b61297c5bdc4 | 2,131 | //
// AppDelegate.swift
// day17
//
// Created by YOUNG on 2016/10/11.
// Copyright © 2016年 Young. 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.340426 | 285 | 0.753168 |
1a9b9b965d9dabf5054f57b171c832962545fab7 | 503 | import SwiftyGPIO
import DS1307
import Foundation
let i2cs = SwiftyGPIO.hardwareI2Cs(for:.RaspberryPi2)!
let i2c = i2cs[1]
let ds = DS1307(i2c)
ds.setTime(hours: 16, minutes: 25, seconds: 00, date: 10, month: 5, year: 17)
ds.start()
var (hours, minutes, seconds, date, month, year) = ds.getTime()
print("\(year)/\(month)/\(date) \(hours):\(minutes):\(seconds)")
sleep(10)
(hours, minutes, seconds, date, month, year) = ds.getTime()
print("\(year)/\(month)/\(date) \(hours):\(minutes):\(seconds)")
| 25.15 | 77 | 0.671968 |
87e4dc6ea0a38f0334b58e6ede791b18b7d34c99 | 321 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Regex",
products: [
.library(name: "Regex", targets: ["Regex"]),
],
targets: [
.target(name: "Regex"),
.testTarget(name: "RegexTests", dependencies: ["Regex"]),
],
swiftLanguageVersions: [.v4_2, .version("5")]
)
| 20.0625 | 61 | 0.626168 |
c13391514fd0fcc86df2e22759430be1f685121a | 2,564 | //
// DNSPageViewManager.swift
// DNSPageView
//
// Created by Daniels on 2018/2/24.
// Copyright © 2018 Daniels. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/*
通过这个类创建的pageView,titleView和contentView的frame是不确定的,适合于titleView和contentView分开布局的情况
需要给titleView和contentView布局,可以用frame或者Autolayout布局
*/
open class DNSPageViewManager: NSObject {
private (set) public var style: DNSPageStyle
private (set) public var titles: [String]
private (set) public var childViewControllers: [UIViewController]
private (set) public var startIndex: Int
private (set) public lazy var titleView = DNSPageTitleView(frame: .zero, style: style, titles: titles, currentIndex: startIndex)
private (set) public lazy var contentView = DNSPageContentView(frame: .zero, style: style, childViewControllers: childViewControllers, currentIndex: startIndex)
public init(style: DNSPageStyle, titles: [String], childViewControllers: [UIViewController], startIndex: Int = 0) {
self.style = style
self.titles = titles
self.childViewControllers = childViewControllers
self.startIndex = startIndex
super.init()
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DNSPageViewManager {
private func setupUI() {
titleView.delegate = contentView
contentView.delegate = titleView
}
}
| 38.848485 | 164 | 0.727379 |
e6f7a1b45077af0d9202464e001dce955453e861 | 2,412 | //
// UserSearchTableViewController.swift
// DotaMate
//
// Created by Philip DesJean on 9/5/16.
// Copyright © 2016 Yerbol Kopzhassar. All rights reserved.
//
import UIKit
class UserSearchTableViewController: UITableViewController {
var users = [ApiUser]()
var matchToShow = Int()
override func viewDidLoad() {
super.viewDidLoad()
getUsers()
}
func getUsers() {
users.removeAll()
AppService.sharedInstance.getSearchResults("Graphs", success: { (result) in
self.users = result!
self.tableView.reloadData()
}) { (result) in
print("shit")
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userSearchCell", for: indexPath) as! UserSearchTableViewCell
let user = users[(indexPath as NSIndexPath).row]
cell.displayNameLabel.text = user.displayName!
AppService.sharedInstance.getImage(user.avatar!, imageView: cell.avatarImageView)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let user = users[(indexPath as NSIndexPath).row]
AppService.sharedInstance.getRecentMatches(user.accountId!, success: { (result) in
self.matchToShow = result!.first!.matchId!
self.performSegue(withIdentifier: "matchSegue", sender: nil)
}) { (result) in
print("shit")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "matchSegue" {
let vc = segue.destination as! MatchDetailsViewController
vc.matchId = matchToShow
}
}
}
| 25.659574 | 126 | 0.5767 |
111011e25edb9bc3ec0100f9f5e3ae4233c3b1a9 | 3,629 | //
// PPArrayDemo.swift
// AlgorithmWithMac
//
// Created by panwei on 2019/11/1.
// Copyright © 2019 WeirdPan. All rights reserved.
//
import Foundation
///数组相关的题目
class PPArrayDemo: NSObject {
//MARK:反转字符串
//👉swift👈
//t👉wif👈s
//tf👉i👈ws
//tf👈i👉ws start < end(👉<👈),结束循环
fileprivate func reverse<T>(_ chars: inout [T], _ start: Int, _ end: Int) {
var start = start, end = end
while start < end {
swap(&chars, start, end)
start += 1
end -= 1
}
}
//交换 p 和 q 位置的字符,chars交换后会改变
fileprivate func swap<T>(_ chars: inout [T], _ p: Int, _ q: Int) {
(chars[p], chars[q]) = (chars[q], chars[p])
}
//MARK: PPLeetCode151 翻转英文句子(以单词为单位翻转)
//https://leetcode-cn.com/problems/reverse-words-in-a-string/
//首先翻转所有字母,然后以空格字符为判断依据,来翻转当前index到这一轮的起始index
func pp_reverseWords(_ s: String) -> String {
var chars = Array(s), start = 0
reverse(&chars, 0, chars.count - 1)//整个字符串翻转,"the sky is blue" -> "eulb si yks eht"
while chars.first == " " {
chars.removeFirst()
}
while chars.last == " " {
chars.removeLast()
}
for i in 0 ..< chars.count {
if i == chars.count - 1 || chars[i + 1] == " " {
reverse(&chars, start, i)//"👉eulb👈 si yks eht" -> "👉blue👈 si yks eht"
start = i + 2//"blue 👉si yks eht"
}
}
var newChars = [Character]()
for i in 0 ..< chars.count {
if i > 0 && chars[i-1] == " " && chars[i] == " "{
continue
}
newChars.append(chars[i])
}
return String(newChars)
}
//测试用例
func testReverseWords() {
//let str = " hello world! "
let str = "a good example"
let newStr = PPArrayDemo().pp_reverseWords(str)
debugPrint(newStr)
}
//PPLeetCode344. 反转字符串
//使用两个指针,-个左指针left ,右指针right
//开始工作时left指向首元素,right指向尾元素。
//交换两个指针指向的元素,并向中间移动,直到两个指针相遇。
func reverseString(_ s: inout [Character]) {
var start = 0, end = s.count-1
while start < end {
s.swapAt(start, end)
//或者(s[start], s[end]) = (s[start], s[end])
start += 1
end -= 1
}
}
//测试用例:
//var chars = Array("hello")
//PPArrayDemo().reverseString(&chars)
//感谢 https://leetcode-cn.com/problems/first-missing-positive/solution/tong-pai-xu-python-dai-ma-by-liweiwei1419/
//假设确实的数字大于len + 1,那么就算数组里len个数字只有一种可能:数字1到len且不重样,所以可得:缺失的第一个整数是 [1, len + 1] 之间,所以这是循环的区间
//遍历数组,将 1 就填充到 nums[0] 的位置, 2 填充到 nums[1] 的位置...
//填充完成后再遍历一次数组,如果对应的 nums[i] != i + 1,即第1个遇到的它的值不等于下标的那个数,那么这个 i + 1 就是缺失的第一个正数
//测试用例:let res = PPArrayDemo().firstMissingPositive([-1,0,1,2,-1,-4])
//[3,4,-1,1] (原始数组)
//[-1,4,3,1] (第一次for循环后)
//
//[-1,1,3,4] (第二次for循环第1次while后)
//[1,-1,3,4] (第二次for循环第2次while后)
//MARK: PPLeetCode41. 缺失的第一个正数
func firstMissingPositive(_ nums: [Int]) -> Int {
var numbers = nums
let length = numbers.count
//使用 while 是因为交换后,原本 i 位置的 nums[i] 已经交换到了别的地方,交换后到这里的新值不一定是适合这个位置的,因此需要重新进行判断交换
//如果使用 if,那么进行一次交换后,i 就会 +1 进入下一个循环,那么交换过来的新值就没有去找到它该有的位置
for i in 0..<length {
while numbers[i]>0 && numbers[i]<=length && numbers[numbers[i] - 1] != numbers[i] {
numbers.swapAt(i, numbers[i] - 1)
}
}
for i in 0..<length {
if numbers[i] != i+1 {
return i+1
}
}
return length + 1
}
}
| 31.556522 | 116 | 0.532929 |
e5941c83ae3c88eef99e5b87bcb43c8aaf7a3605 | 2,999 | //
// QuestionBank.swift
// Quizzler
//
// Created by Philip Yu on 6/29/19.
// Copyright © 2019 London App Brewery. All rights reserved.
//
import Foundation
struct QuestionBank {
// MARK: - Properties
var questionBank = [
Question(text: "A slug's blood is green.", correctAnswer: true),
Question(text: "Approximately one quarter of human bones are in the feet.", correctAnswer: true),
Question(text: "The total surface area of two human lungs is approximately 70 square metres.", correctAnswer: true),
Question(text: "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.", correctAnswer: true),
Question(text: "In London, UK, if you happen to die in the House of Parliament, you are technically entitled to a state funeral, because the building is considered too sacred a place.", correctAnswer: false),
Question(text: "It is illegal to pee in the Ocean in Portugal.", correctAnswer: true),
Question(text: "You can lead a cow down stairs but not up stairs.", correctAnswer: false),
Question(text: "Google was originally called 'Backrub'.", correctAnswer: true),
Question(text: "Buzz Aldrin's mother's maiden name was 'Moon'.", correctAnswer: true),
Question(text: "The loudest sound produced by any animal is 188 decibels. That animal is the African Elephant.", correctAnswer: false),
Question(text: "No piece of square dry paper can be folded in half more than 7 times.", correctAnswer: false),
Question(text: "Chocolate affects a dog's heart and nervous system; a few ounces are enough to kill a small dog.", correctAnswer: true)
]
var questionNumber: Int = 0
var score: Int = 0
mutating func checkAnswer(_ userSelection: Int) -> Bool {
let correctAnswer = questionBank[questionNumber].answer
let userAnswer = questionBank[userSelection].answer
if correctAnswer == userAnswer {
// User got the answer right
score += 1
return true
} else {
// User got the answer wrong
return false
}
}
func getQuestionText() -> String {
var questionText: String = ""
if questionNumber < questionBank.count {
questionText = questionBank[questionNumber].questionText
}
return questionText
}
func getProgress() -> Float {
let progress = Float(questionNumber) / Float(questionBank.count)
return progress
}
mutating func nextQuestion() {
if questionNumber < questionBank.count {
questionNumber += 1
}
}
mutating func startOver () {
questionNumber = 0
score = 0
}
func getScore() -> Int {
return score
}
}
| 34.079545 | 216 | 0.614205 |
f4f793537cfda8ddc9ca7c990b428ac93a25f019 | 2,453 | //
// UIButtonCell.swift
// Bank-Investment
//
// Created by Jonathan Martins on 07/01/19.
// Copyright © 2019 Surrey. All rights reserved.
//
import UIKit
class UIButtonCell: BaseCell {
/// The Button
let button: UIButton = {
let button = UIButton()
button.setTitleColor(.white, for: .normal)
button.cornerRadius = 15
button.backgroundColor = .red
button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
/// Adds the constraints to the views in this cell
private func setupConstraints(){
self.contentView.addSubview(button)
topSpacing = button.topAnchor.constraint(equalTo: self.contentView.topAnchor)
NSLayoutConstraint.activate([
button.heightAnchor .constraint(equalToConstant: 35),
button.bottomAnchor .constraint(equalTo: self.contentView.bottomAnchor, constant: -30),
button.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor),
button.widthAnchor .constraint(equalTo: self.contentView.widthAnchor, multiplier: 1/1.3),
topSpacing!
])
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Sets up the cell information
func setupCell(_ item:FormItem, callback:(()->Void)? = nil){
setupTopSpace(item)
self.item = item
self.callback = callback
button.setTitle("Enviar", for: .normal)
button.addTarget(self, action: #selector(buttonClicked), for: UIControl.Event.touchUpInside)
}
/// Sets the callback to notify the controller
func setCallback(_ callback:@escaping (()->Void)){
self.callback = callback
topSpacing?.constant = 20
button.setTitle("Investir", for: .normal)
button.addTarget(self, action: #selector(buttonClicked), for: UIControl.Event.touchUpInside)
}
/// Callback to notify the Controller when the button is clicked
private var callback:(()->Void)?
@objc private func buttonClicked(myButton: UIButton) {
callback?()
}
}
| 34.069444 | 102 | 0.648594 |
1e75ebd5e74b3434a81dc8f53f391a1ac8455313 | 6,177 | //
// FullScreenCover.swift
// ViewInspector
//
// Created by Richard Gist on 9/2/21.
//
import SwiftUI
// MARK: - FullScreenCover
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct FullScreenCover: KnownViewType {
public static var typePrefix: String = "ViewType.FullScreenCover.Container"
public static var namespacedPrefixes: [String] {
return ["ViewInspector." + typePrefix]
}
public static func inspectionCall(typeName: String) -> String {
return "fullScreenCover(\(ViewType.indexPlaceholder))"
}
}
}
// MARK: - Content Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.FullScreenCover: SingleViewContent {
public static func child(_ content: Content) throws -> Content {
let view = try Inspector.attribute(label: "view", value: content.view)
let medium = content.medium.resettingViewModifiers()
return try Inspector.unwrap(view: view, medium: medium)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.FullScreenCover: MultipleViewContent {
public static func children(_ content: Content) throws -> LazyGroup<Content> {
let view = try Inspector.attribute(label: "view", value: content.view)
let medium = content.medium.resettingViewModifiers()
return try Inspector.viewsInContainer(view: view, medium: medium)
}
}
// MARK: - Extraction
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public extension InspectableView {
func fullScreenCover(_ index: Int? = nil) throws -> InspectableView<ViewType.FullScreenCover> {
return try contentForModifierLookup.fullScreenCover(parent: self, index: index)
}
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
internal extension Content {
func fullScreenCover(parent: UnwrappedView, index: Int?) throws -> InspectableView<ViewType.FullScreenCover> {
guard let fullScreenCoverBuilder = try? self.modifierAttribute(
modifierLookup: { isFullScreenCoverBuilder(modifier: $0) }, path: "modifier",
type: FullScreenCoverBuilder.self, call: "", index: index ?? 0)
else {
_ = try self.modifier({
$0.modifierType == "IdentifiedPreferenceTransformModifier<Key>"
|| $0.modifierType.contains("SheetPresentationModifier")
}, call: "fullScreenCover")
throw InspectionError.notSupported(
"""
Please refer to the Guide for inspecting the FullScreenCover: \
https://github.com/nalexn/ViewInspector/blob/master/guide.md#alert-sheet-actionsheet-and-fullscreencover
""")
}
let view = try fullScreenCoverBuilder.buildFullScreenCover()
let container = ViewType.FullScreenCover.Container(view: view, builder: fullScreenCoverBuilder)
let medium = self.medium.resettingViewModifiers()
let content = Content(container, medium: medium)
let call = ViewType.inspectionCall(
base: ViewType.FullScreenCover.inspectionCall(typeName: ""), index: index)
return try .init(content, parent: parent, call: call, index: index)
}
func fullScreenCoversForSearch() -> [ViewSearch.ModifierIdentity] {
let count = medium.viewModifiers
.compactMap { isFullScreenCoverBuilder(modifier: $0) }
.count
return Array(0..<count).map { _ in
.init(name: "", builder: { parent, index in
try parent.content.fullScreenCover(parent: parent, index: index)
})
}
}
private func isFullScreenCoverBuilder(modifier: Any) -> Bool {
return (try? Inspector.attribute(
label: "modifier", value: modifier, type: FullScreenCoverBuilder.self)) != nil
}
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
internal extension ViewType.FullScreenCover {
struct Container: CustomViewIdentityMapping {
let view: Any
let builder: FullScreenCoverBuilder
var viewTypeForSearch: KnownViewType.Type { ViewType.FullScreenCover.self }
}
}
// MARK: - Custom Attributes
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public extension InspectableView where View == ViewType.FullScreenCover {
func callOnDismiss() throws {
let fullScreenCover = try Inspector.cast(value: content.view, type: ViewType.FullScreenCover.Container.self)
fullScreenCover.builder.dismissPopup()
}
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public protocol FullScreenCoverBuilder: SystemPopupPresenter {
var onDismiss: (() -> Void)? { get }
func buildFullScreenCover() throws -> Any
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public protocol FullScreenCoverProvider: FullScreenCoverBuilder {
var isPresented: Binding<Bool> { get }
var fullScreenCoverBuilder: () -> Any { get }
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public protocol FullScreenCoverItemProvider: FullScreenCoverBuilder {
associatedtype Item: Identifiable
var item: Binding<Item?> { get }
var fullScreenCoverBuilder: (Item) -> Any { get }
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public extension FullScreenCoverProvider {
func buildFullScreenCover() throws -> Any {
guard isPresented.wrappedValue else {
throw InspectionError.viewNotFound(parent: "FullScreenCover")
}
return fullScreenCoverBuilder()
}
func dismissPopup() {
isPresented.wrappedValue = false
onDismiss?()
}
}
@available(iOS 13.0, tvOS 13.0, *)
@available(macOS, unavailable)
public extension FullScreenCoverItemProvider {
func buildFullScreenCover() throws -> Any {
guard let value = item.wrappedValue else {
throw InspectionError.viewNotFound(parent: "FullScreenCover")
}
return fullScreenCoverBuilder(value)
}
func dismissPopup() {
item.wrappedValue = nil
onDismiss?()
}
}
| 33.93956 | 120 | 0.674761 |
1ce9c1cd77728562364cd4e8801184112b5df78c | 205 | //
// AppDrawerTheme.swift
// PACECloudSDK
//
// Created by PACE Telematics GmbH.
//
import Foundation
public extension AppKit {
enum AppDrawerTheme {
case light
case dark
}
}
| 12.8125 | 36 | 0.634146 |
c181aa9df5a2e3eb5885c6fc1bbdee1108470216 | 1,639 | //
// MockContactDetailsViewModel.swift
// GJContactsDemoTests
//
// Created by pvharsha on 11/11/19.
// Copyright © 2019 SPH. All rights reserved.
//
import UIKit
@testable import GJContactsDemo
class MockContactDetailsViewModel: ContactDetailViewModel {
var mockDataSource:Contact?
var isContractObserverInvoked = false
var isInvokeEditViewInvoked = false
var isTextMessage_invoked = false
var ismakePhoneCall_invoked = false
var isInvokeEmail_invoked = false
var isMarkFavourite_invoked = false
var isDelete_invoked = false
var isDismissDetailView_invoked = false
override func fetch() {
self.dataSource = mockDataSource
detailProtocol?.loadUI(dataSource)
}
override func contactObserver(_ contact: Contact?, _ error: NSError?, _ serviceEvent: ContactServiceEvent) {
isContractObserverInvoked = true
}
override func invokeEditView() {
isInvokeEditViewInvoked = true
}
// MARK:- viewcontroller handler functions
override func textMessage() {
isTextMessage_invoked = true
}
override func makePhoneCall() {
ismakePhoneCall_invoked = true
}
override func invokeEmail() {
isInvokeEmail_invoked = true
}
override func markFavourite(_ isFavourite:Bool) {
isMarkFavourite_invoked = true
}
override func delete() {
isDelete_invoked = true
}
override func dismissDetailView() {
isDismissDetailView_invoked = true
}
}
| 23.084507 | 112 | 0.647346 |
acbc48dedad2a2e63e7a04d7e1dadd9e85f6f3a0 | 8,565 | //
// Copyright (c) Vatsal Manot
//
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
import Swift
import SwiftUI
import UIKit
protocol _opaque_UIHostingPageViewController: NSObject {
var _pageUpdateDriver: _PageUpdateDriver { get }
var internalPaginationState: PaginationState { get }
}
class _PageUpdateDriver: ObservableObject {
}
class UIHostingPageViewController<Page: View>: UIPageViewController, _opaque_UIHostingPageViewController, UIScrollViewDelegate {
var _pageUpdateDriver = _PageUpdateDriver()
var internalScrollView: UIScrollView?
var cachedChildren: [Int: PageContentController] = [:]
var _isSwiftUIRuntimeUpdateActive: Bool = false
var _isAnimated: Bool = true
var cyclesPages: Bool = false
var internalPaginationState = PaginationState() {
didSet {
paginationState?.wrappedValue = internalPaginationState
}
}
var paginationState: Binding<PaginationState>?
var content: AnyForEach<Page>? {
didSet {
if let content = content {
preheatViewControllersCache()
if let oldValue = oldValue, oldValue.count != content.count {
cachedChildren = [:]
if let firstViewController = viewController(for: content.data.startIndex) {
setViewControllers(
[firstViewController],
direction: .forward,
animated: false
)
}
} else {
if let viewControllers = viewControllers?.compactMap({ $0 as? PageContentController }), let firstViewController = viewControllers.first, !viewControllers.isEmpty {
for viewController in viewControllers {
_withoutAnimation_AppKitOrUIKit(!(viewController === firstViewController)) {
viewController.mainView.page = content.content(content.data[viewController.mainView.index])
}
}
}
}
}
}
}
var currentPageIndex: AnyIndex? {
get {
guard let currentViewController = viewControllers?.first as? PageContentController else {
return nil
}
return currentViewController.mainView.index
} set {
guard let newValue = newValue else {
return setViewControllers([], direction: .forward, animated: _isAnimated, completion: nil)
}
guard let currentPageIndex = currentPageIndex else {
return
}
guard newValue != currentPageIndex else {
return
}
var direction: UIPageViewController.NavigationDirection
if newValue < currentPageIndex {
direction = .reverse
} else {
direction = .forward
}
if internalPaginationState.activePageTransitionProgress == 0.0 {
if let viewController = viewController(for: newValue) {
setViewControllers(
[viewController],
direction: direction,
animated: _isAnimated
)
}
}
}
}
var currentPageIndexOffset: Int? {
guard let content = content else {
return nil
}
guard let currentPageIndex = currentPageIndex else {
return nil
}
return content.data.distance(from: content.data.startIndex, to: currentPageIndex)
}
var previousPageIndex: AnyIndex? {
guard let currentPageIndex = currentPageIndex else {
return nil
}
return content?.data.index(before: currentPageIndex)
}
var nextPageIndex: AnyIndex? {
guard let currentPageIndex = currentPageIndex else {
return nil
}
return content?.data.index(after: currentPageIndex)
}
private func preheatViewControllersCache() {
guard let content = content else {
return
}
if content.data.count <= 4 {
for index in content.data.indices {
_ = viewController(for: index)
}
}
}
public override func viewDidLoad() {
super.viewDidLoad()
for subview in view.subviews {
if let scrollView = subview as? UIScrollView {
internalScrollView = scrollView
scrollView.delegate = self
}
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard !_isSwiftUIRuntimeUpdateActive else {
return
}
let activePageTransitionProgress = (scrollView.contentOffset.x - view.frame.size.width) / view.frame.size.width
if paginationState != nil {
_pageUpdateDriver.objectWillChange.send()
}
if activePageTransitionProgress == 0 {
internalPaginationState.activePageTransitionDirection = nil
} else {
internalPaginationState.activePageTransitionDirection = activePageTransitionProgress < 0 ? .backward : .forward
}
internalPaginationState.activePageTransitionProgress = abs(Double(activePageTransitionProgress))
}
}
extension UIHostingPageViewController {
func viewController(for index: AnyIndex) -> UIViewController? {
guard let content = content else {
return nil
}
guard index < content.data.endIndex else {
return nil
}
let indexOffset = content.data.distance(from: content.data.startIndex, to: index)
if let cachedResult = cachedChildren[indexOffset] {
return cachedResult
}
let result = PageContentController(
mainView: PageContainer(
index: index,
page: content.content(content.data[index]),
_updateDriver: _pageUpdateDriver
)
)
cachedChildren[indexOffset] = result
return result
}
func viewController(before viewController: UIViewController) -> UIViewController? {
guard let content = content else {
return nil
}
guard let viewController = viewController as? PageContentController else {
assertionFailure()
return nil
}
let index = viewController.mainView.index == content.data.startIndex
? (cyclesPages ? content.data.indices.last : nil)
: content.data.index(before: viewController.mainView.index)
return index.flatMap { index in
self.viewController(for: index)
}
}
func viewController(after viewController: UIViewController) -> UIViewController? {
guard let content = content else {
return nil
}
guard let viewController = viewController as? PageContentController else {
assertionFailure()
return nil
}
let index = content.data.index(after: viewController.mainView.index) == content.data.endIndex
? (cyclesPages ? content.data.startIndex : nil)
: content.data.index(after: viewController.mainView.index)
return index.flatMap { index in
self.viewController(for: index)
}
}
}
extension UIHostingPageViewController {
struct PageContainer: View {
let index: AnyIndex
var page: Page
@ObservedObject var _updateDriver: _PageUpdateDriver
var body: some View {
page
}
}
class PageContentController: CocoaHostingController<PageContainer> {
init(mainView: PageContainer) {
super.init(mainView: mainView)
_fixSafeAreaInsetsIfNecessary()
view.backgroundColor = .clear
}
@objc required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
#endif
| 31.373626 | 183 | 0.561821 |
3826f61eb2b5d7fbf71fe27a717e0c50e466f263 | 1,061 | // import Flow
// @testable import FlowSwift
// import XCTest
//
// final class FlowClientTests: XCTestCase {
// let client = FlowClient()
//
// func testFlowClientConnection() {
// let expectation = XCTestExpectation(description: "test Flow Client connection.")
//
// client.ping { response in
// XCTAssertNil(response.error, "Client connection error: \(String(describing: response.error?.localizedDescription)).")
// expectation.fulfill()
// }
//
// wait(for: [expectation], timeout: 5)
// }
//
// func testRetrieveCollectionById() {
// let expectation = XCTestExpectation(description: "retrieve the latest block")
//
// client.getLatestBlock(isSealed: true) { latestBlockResponse in
// XCTAssertNil(latestBlockResponse.error, "getLatestBlock error: \(String(describing: latestBlockResponse.error?.localizedDescription)).")
// // let latestBlock = latestBlockResponse.result as! FlowBlock
// }
// wait(for: [expectation], timeout: 5)
// }
// }
| 36.586207 | 150 | 0.65033 |
fef7d1a8f73361574463c30e84e05105235044d7 | 2,368 | //
// AttributedStringComponent+Components.swift
// AttributedStringBuilder
//
// Copyright (c) 2020 Rocket Insights, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import UIKit
extension AttributedStringComponent {
public var bold: AttributedStringComponent {
return adding(traits: .traitBold)
}
public var italic: AttributedStringComponent {
return adding(traits: .traitItalic)
}
public var underline: AttributedStringComponent {
return adding(attribute: .underlineStyle, withValue: NSUnderlineStyle.single.rawValue)
}
public func foregroundColor(_ color: UIColor) -> AttributedStringComponent {
return adding(attribute: .foregroundColor, withValue: color)
}
public func backgroundColor(_ color: UIColor) -> AttributedStringComponent {
return adding(attribute: .backgroundColor, withValue: color)
}
}
public let Space = " "
public func Space(count: Int = 1) -> AttributedStringComponent {
return String(repeating: " ", count: count)
}
public let Tab = "\t"
public func Tab(count: Int = 1) -> AttributedStringComponent {
return String(repeating: "\t", count: count)
}
public let Newline = "\n"
public func Newline(count: Int = 1) -> AttributedStringComponent {
return String(repeating: "\n", count: count)
}
| 34.823529 | 94 | 0.72973 |
de0cb0c544f2f3def13f388ccabd41764b5125a2 | 482 | // 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
class A{a{}
func a{nc b
H : ){ }
func f:A.b:
typealias e=B{}class B{
}
"
enum B<:A{
| 28.352941 | 79 | 0.719917 |
fbcac9428c854cf79dcb3ad0338a8942392214fd | 6,961 | import Foundation
import ArgumentParser
import Shared
struct ScanCommand: FrontendCommand {
static let configuration = CommandConfiguration(
commandName: "scan",
abstract: "Scan for unused code"
)
private static let defaultConfig = Configuration.make()
@Argument(help: "Arguments following '--' will be passed to the underlying build tool, which is either 'swift build' or 'xcodebuild' depending on your project")
var buildArguments: [String] = defaultConfig.buildArguments
@Flag(help: "Enable guided setup")
var setup: Bool = defaultConfig.guidedSetup
@Option(help: "Path to configuration file. By default Periphery will look for .periphery.yml in the current directory")
var config: String?
@Option(help: "Path to your project's .xcworkspace. Xcode projects only")
var workspace: String?
@Option(help: "Path to your project's .xcodeproj - supply this option if your project doesn't have an .xcworkspace. Xcode projects only")
var project: String?
@Option(help: "Comma-separated list of schemes that must be built in order to produce the targets passed to the --targets option. Xcode projects only", transform: split(by: ","))
var schemes: [String] = defaultConfig.schemes
@Option(help: "Comma-separated list of target names to scan. Requied for Xcode projects. Optional for Swift Package Manager projects, default behavior is to scan all targets defined in Package.swift", transform: split(by: ","))
var targets: [String] = defaultConfig.targets
@Option(help: "Output format (allowed: \(OutputFormat.allValueStrings.joined(separator: ", ")))")
var format: OutputFormat = defaultConfig.outputFormat
@Option(help: "Path glob of source files which should be excluded from indexing. Declarations and references within these files will not be considered during analysis. Multiple globs may be delimited by a pipe", transform: split(by: "|"))
var indexExclude: [String] = defaultConfig.indexExclude
@Option(help: "Path glob of source files which should be excluded from the results. Note that this option is purely cosmetic, these files will still be indexed. Multiple globs may be delimited by a pipe", transform: split(by: "|"))
var reportExclude: [String] = defaultConfig.reportExclude
@Option(help: "Path to index store to use. Implies '--skip-build'")
var indexStorePath: String?
@Flag(help: "Retain all public declarations - you'll likely want to enable this if you're scanning a framework/library project")
var retainPublic: Bool = defaultConfig.retainPublic
@Flag(help: "Disable identification of redundant public accessibility")
var disableRedundantPublicAnalysis: Bool = defaultConfig.disableRedundantPublicAnalysis
@Flag(help: "Retain properties that are assigned, but never used")
var retainAssignOnlyProperties: Bool = defaultConfig.retainAssignOnlyProperties
@Option(help: "Comma-separated list of property types to retain if the property is assigned, but never read", transform: split(by: ","))
var retainAssignOnlyPropertyTypes: [String] = defaultConfig.retainAssignOnlyPropertyTypes
@Flag(help: "Retain objects inherit Encodable")
var retainEncodable: Bool = defaultConfig.retainEncodable
@Option(help: "Comma-separated list of external protocols that inherit Encodable. Properties of types conforming to these protocols will be retained", transform: split(by: ","))
var externalEncodableProtocols: [String] = defaultConfig.externalEncodableProtocols
@Option(help: "Comma-separated list of retainable classes and structs", transform: split(by: ","))
var retainObjects: [String] = defaultConfig.retainObjects
@Flag(help: "Retain declarations that are exposed to Objective-C implicitly by inheriting NSObject classes, or explicitly with the @objc and @objcMembers attributes")
var retainObjcAccessible: Bool = defaultConfig.retainObjcAccessible
@Flag(help: "Retain unused protocol function parameters, even if the parameter is unused in all conforming functions")
var retainUnusedProtocolFuncParams: Bool = defaultConfig.retainUnusedProtocolFuncParams
@Flag(help: "Clean existing build artifacts before building")
var cleanBuild: Bool = defaultConfig.cleanBuild
@Flag(help: "Skip the project build step")
var skipBuild: Bool = defaultConfig.skipBuild
@Flag(help: "Exit with non-zero status if any unused code is found")
var strict: Bool = defaultConfig.strict
@Flag(help: "Disable checking for updates")
var disableUpdateCheck: Bool = defaultConfig.disableUpdateCheck
@Flag(help: "Enable verbose logging")
var verbose: Bool = defaultConfig.verbose
@Flag(help: "Only output results")
var quiet: Bool = defaultConfig.quiet
func run() throws {
let scanBehavior = ScanBehavior.make()
if !setup {
try scanBehavior.setup(config).get()
}
let configuration = inject(Configuration.self)
configuration.guidedSetup = setup
configuration.apply(\.$workspace, workspace)
configuration.apply(\.$project, project)
configuration.apply(\.$schemes, schemes)
configuration.apply(\.$targets, targets)
configuration.apply(\.$indexExclude, indexExclude)
configuration.apply(\.$reportExclude, reportExclude)
configuration.apply(\.$outputFormat, format)
configuration.apply(\.$retainPublic, retainPublic)
configuration.apply(\.$retainAssignOnlyProperties, retainAssignOnlyProperties)
configuration.apply(\.$retainAssignOnlyPropertyTypes, retainAssignOnlyPropertyTypes)
configuration.apply(\.$retainObjcAccessible, retainObjcAccessible)
configuration.apply(\.$retainUnusedProtocolFuncParams, retainUnusedProtocolFuncParams)
configuration.apply(\.$disableRedundantPublicAnalysis, disableRedundantPublicAnalysis)
configuration.apply(\.$externalEncodableProtocols, externalEncodableProtocols)
configuration.apply(\.$verbose, verbose)
configuration.apply(\.$quiet, quiet)
configuration.apply(\.$disableUpdateCheck, disableUpdateCheck)
configuration.apply(\.$strict, strict)
configuration.apply(\.$indexStorePath, indexStorePath)
configuration.apply(\.$skipBuild, skipBuild)
configuration.apply(\.$cleanBuild, cleanBuild)
configuration.apply(\.$buildArguments, buildArguments)
configuration.apply(\.$retainObjects, retainObjects)
configuration.apply(\.$retainEncodable, retainEncodable)
try scanBehavior.main { project in
try Scan.make().perform(project: project)
}.get()
}
// MARK: - Private
private static func split(by delimiter: Character) -> (String?) -> [String] {
return { options in options?.split(separator: delimiter).map(String.init) ?? [] }
}
}
extension OutputFormat: ExpressibleByArgument {}
| 50.442029 | 242 | 0.734665 |
7a8ffc44686fc6d7ce7f29c80a200f44bf37aea9 | 11,576 | //
// ViewControllertabSchedule.swift
// RsyncOSXver30
//
// Created by Thomas Evensen on 19/08/2016.
// Copyright © 2016 Thomas Evensen. All rights reserved.
//
// swiftlint:disable line_length cyclomatic_complexity
import Foundation
import Cocoa
// Protocol for restarting timer
protocol StartTimer: class {
func startTimerNextJob()
}
protocol SetProfileinfo: class {
func setprofile(profile: String, color: NSColor)
}
class ViewControllertabSchedule: NSViewController, SetConfigurations, SetSchedules, Coloractivetask, OperationChanged, VcSchedule, Delay, GetIndex {
private var index: Int?
private var hiddenID: Int?
private var schedulessorted: ScheduleSortedAndExpand?
var tools: Tools?
var schedule: Scheduletype?
private var preselectrow: Bool = false
// Main tableview
@IBOutlet weak var mainTableView: NSTableView!
@IBOutlet weak var profilInfo: NSTextField!
@IBOutlet weak var operation: NSTextField!
@IBOutlet weak var weeklybutton: NSButton!
@IBOutlet weak var dailybutton: NSButton!
@IBOutlet weak var oncebutton: NSButton!
@IBOutlet weak var info: NSTextField!
@IBOutlet weak var rsyncosxschedbutton: NSButton!
@IBAction func rsyncosxsched(_ sender: NSButton) {
let pathtorsyncosxschedapp: String = ViewControllerReference.shared.pathrsyncosxsched! + ViewControllerReference.shared.namersyncosssched
NSWorkspace.shared.open(URL(fileURLWithPath: pathtorsyncosxschedapp))
self.rsyncosxschedbutton.isEnabled = false
NSApp.terminate(self)
}
private func info (num: Int) {
switch num {
case 1:
self.info.stringValue = "Select a task..."
case 2:
self.info.stringValue = "Scheduled tasks in menu app..."
case 3:
self.info.stringValue = "Preselected row from main view..."
default:
self.info.stringValue = ""
}
}
@IBAction func once(_ sender: NSButton) {
self.schedule = .once
self.addschedule()
}
@IBAction func daily(_ sender: NSButton) {
self.schedule = .daily
self.addschedule()
}
@IBAction func weekly(_ sender: NSButton) {
self.schedule = .weekly
self.addschedule()
}
@IBAction func selectdate(_ sender: NSDatePicker) {
self.schedulebuttonsonoff()
}
@IBAction func selecttime(_ sender: NSDatePicker) {
self.schedulebuttonsonoff()
}
private func addschedule() {
let answer = Alerts.dialogOKCancel("Add Schedule?", text: "Cancel or OK")
if answer {
if ViewControllerReference.shared.executescheduledtasksmenuapp == true {
self.info(num: 2)
}
let seconds: TimeInterval = self.starttime.dateValue.timeIntervalSinceNow
let startdate: Date = self.startdate.dateValue.addingTimeInterval(seconds)
if self.index != nil {
self.schedules!.addschedule(self.hiddenID!, schedule: self.schedule ?? .once, start: startdate)
}
}
}
private func schedulebuttonsonoff() {
let seconds: TimeInterval = self.starttime.dateValue.timeIntervalSinceNow
// Date and time for stop
let startime: Date = self.startdate.dateValue.addingTimeInterval(seconds)
let secondstostart = startime.timeIntervalSinceNow
if secondstostart < 60 {
self.weeklybutton.isEnabled = false
self.dailybutton.isEnabled = false
self.oncebutton.isEnabled = false
}
if secondstostart > 60 {
self.weeklybutton.isEnabled = true
self.dailybutton.isEnabled = true
self.oncebutton.isEnabled = true
}
}
// Selecting profiles
@IBAction func profiles(_ sender: NSButton) {
globalMainQueue.async(execute: { () -> Void in
self.presentViewControllerAsSheet(self.viewControllerProfile!)
})
}
// Userconfiguration button
@IBAction func userconfiguration(_ sender: NSButton) {
globalMainQueue.async(execute: { () -> Void in
self.presentViewControllerAsSheet(self.viewControllerUserconfiguration!)
})
}
// Logg records
@IBAction func loggrecords(_ sender: NSButton) {
globalMainQueue.async(execute: { () -> Void in
self.presentViewControllerAsSheet(self.viewControllerScheduleDetails!)
})
}
@IBOutlet weak var startdate: NSDatePicker!
@IBOutlet weak var starttime: NSDatePicker!
// Initial functions viewDidLoad and viewDidAppear
override func viewDidLoad() {
super.viewDidLoad()
self.mainTableView.delegate = self
self.mainTableView.dataSource = self
self.mainTableView.doubleAction = #selector(ViewControllertabMain.tableViewDoubleClick(sender:))
ViewControllerReference.shared.setvcref(viewcontroller: .vctabschedule, nsviewcontroller: self)
self.tools = Tools()
}
override func viewDidAppear() {
super.viewDidAppear()
self.index = self.index(viewcontroller: .vctabmain)
if self.index != nil {
self.hiddenID = self.configurations!.gethiddenID(index: self.index!)
self.info(num: 3)
self.preselectrow = true
} else {
self.preselectrow = false
self.info(num: 0)
}
self.weeklybutton.isEnabled = false
self.dailybutton.isEnabled = false
self.oncebutton.isEnabled = false
self.startdate.dateValue = Date()
self.starttime.dateValue = Date()
if self.schedulessorted == nil {
self.schedulessorted = ScheduleSortedAndExpand()
}
globalMainQueue.async(execute: { () -> Void in
self.mainTableView.reloadData()
})
self.operationsmethod()
self.delayWithSeconds(0.5) {
self.enablemenuappbutton()
}
}
internal func operationsmethod() {
switch ViewControllerReference.shared.operation {
case .dispatch:
self.operation.stringValue = "Operation method: dispatch"
case .timer:
self.operation.stringValue = "Operation method: timer"
}
}
// setting which table row is selected
func tableViewSelectionDidChange(_ notification: Notification) {
self.info(num: 0)
self.preselectrow = false
let myTableViewFromNotification = (notification.object as? NSTableView)!
let indexes = myTableViewFromNotification.selectedRowIndexes
if let index = indexes.first {
// Set index
self.index = index
let dict = self.configurations!.getConfigurationsDataSourcecountBackup()![index]
self.hiddenID = dict.value(forKey: "hiddenID") as? Int
} else {
self.index = nil
self.hiddenID = nil
}
}
// Execute tasks by double click in table
@objc(tableViewDoubleClick:) func tableViewDoubleClick(sender: AnyObject) {
self.preselectrow = false
globalMainQueue.async(execute: { () -> Void in
self.presentViewControllerAsSheet(self.viewControllerScheduleDetails!)
})
}
private func enablemenuappbutton() {
globalMainQueue.async(execute: { () -> Void in
guard Running().enablemenuappbutton() == true else {
self.rsyncosxschedbutton.isEnabled = false
self.info(num: 5)
return
}
self.rsyncosxschedbutton.isEnabled = true
})
}
}
extension ViewControllertabSchedule: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return self.configurations?.getConfigurationsDataSourcecountBackup()?.count ?? 0
}
}
extension ViewControllertabSchedule: NSTableViewDelegate, Attributedestring {
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
guard row < self.configurations!.getConfigurationsDataSourcecountBackup()!.count else { return nil }
let object: NSDictionary = self.configurations!.getConfigurationsDataSourcecountBackup()![row]
let hiddenID: Int = object.value(forKey: "hiddenID") as? Int ?? -1
switch tableColumn!.identifier.rawValue {
case "scheduleID" :
if self.schedulessorted != nil {
let schedule: String? = self.schedulessorted!.sortandcountscheduledonetask(hiddenID, number: false)
return schedule ?? ""
}
case "offsiteServerCellID":
if (object[tableColumn!.identifier] as? String)!.isEmpty {
if self.preselectrow == true && hiddenID == self.hiddenID ?? -1 {
return self.attributedstring(str: "localhost", color: NSColor.red, align: .left)
} else {
return "localhost"
}
} else {
if self.preselectrow == true && hiddenID == self.hiddenID ?? -1 {
let text = object[tableColumn!.identifier] as? String
return self.attributedstring(str: text!, color: NSColor.red, align: .left)
} else {
return object[tableColumn!.identifier] as? String
}
}
case "inCellID":
if self.schedulessorted != nil {
let taskintime: String? = self.schedulessorted!.sortandcountscheduledonetask(hiddenID, number: true)
return taskintime ?? ""
}
default:
if self.preselectrow == true && hiddenID == self.hiddenID ?? -1 {
let text = object[tableColumn!.identifier] as? String
return self.attributedstring(str: text!, color: NSColor.red, align: .left)
} else {
return object[tableColumn!.identifier] as? String
}
}
return nil
}
}
extension ViewControllertabSchedule: GetHiddenID {
func gethiddenID() -> Int? {
return self.hiddenID
}
}
extension ViewControllertabSchedule: DismissViewController {
func dismiss_view(viewcontroller: NSViewController) {
self.dismissViewController(viewcontroller)
globalMainQueue.async(execute: { () -> Void in
self.mainTableView.reloadData()
})
self.operationsmethod()
}
}
extension ViewControllertabSchedule: Reloadandrefresh {
func reloadtabledata() {
// Create a New schedules object
self.schedulessorted = ScheduleSortedAndExpand()
globalMainQueue.async(execute: { () -> Void in
self.mainTableView.reloadData()
})
}
}
extension ViewControllertabSchedule: StartTimer {
// Called from Process
func startTimerNextJob() {
self.schedulessorted = ScheduleSortedAndExpand()
globalMainQueue.async(execute: { () -> Void in
self.mainTableView.reloadData()
})
}
}
// Deselect a row
extension ViewControllertabSchedule: DeselectRowTable {
// deselect a row after row is deleted
func deselect() {
guard self.index != nil else { return }
self.mainTableView.deselectRow(self.index!)
}
}
extension ViewControllertabSchedule: SetProfileinfo {
func setprofile(profile: String, color: NSColor) {
globalMainQueue.async(execute: { () -> Void in
self.profilInfo.stringValue = profile
self.profilInfo.textColor = color
})
}
}
| 34.86747 | 148 | 0.635194 |
87f3d99853153a28f72f51f4c3fd8d756b5b6094 | 3,813 | //
// ResetPasswordController.swift
// CardPang
//
// Created by 윤병일 on 2020/08/10.
// Copyright © 2020 Byoungil Youn. All rights reserved.
//
import UIKit
protocol ResetPasswordControllerDelegate : class {
func didSendResetPasswordLink()
}
class ResetPasswordController : UIViewController {
//MARK: - Properties
private let iconImage = UIImageView(image: #imageLiteral(resourceName: "Main Icon"))
private let emailTextField = CustomTextField(placeholder: "이메일")
private let resetPasswordButton : AuthButton = {
let button = AuthButton(type: .system)
button.title = "비밀번호 초기화 링크 보내기"
button.addTarget(self, action: #selector(handleResetPassword), for: .touchUpInside)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
return button
}()
private let backButton : UIButton = {
let button = UIButton(type: .system)
button.tintColor = .white
button.addTarget(self, action: #selector(handleGoBack), for: .touchUpInside)
button.setImage(UIImage(systemName: "chevron.left"), for: .normal)
return button
}()
private var viewModel = ResetPasswordViewModel()
var email : String?
weak var delegate : ResetPasswordControllerDelegate?
//MARK: - viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
configureGradientBackground()
setUI()
setConstraints()
configureNotificationObservers()
loadEmail()
}
//MARK: - setUI()
private func setUI() {
view.addSubview(iconImage)
view.addSubview(backButton)
emailTextField.delegate = self
let stackView = UIStackView(arrangedSubviews: [emailTextField, resetPasswordButton])
stackView.axis = .vertical
stackView.spacing = 20
view.addSubview(stackView)
stackView.anchor(top: iconImage.bottomAnchor, left: view.leftAnchor, right: view.rightAnchor, paddingTop: 50 , paddingLeft: 30, paddingRight: 30)
}
//MARK: - setConstraints()
private func setConstraints() {
iconImage.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.width.height.equalTo(100)
$0.top.equalTo(50)
}
backButton.snp.makeConstraints {
$0.top.left.equalTo(view.safeAreaLayoutGuide).offset(20)
}
}
//MARK: - configureNotificationObservers()
private func configureNotificationObservers() {
emailTextField.addTarget(self, action: #selector(textDidChange(_:)), for: .editingChanged)
}
//MARK: - loadEmail()
private func loadEmail() {
guard let email = email else {return}
viewModel.email = email
emailTextField.text = email
updateForm()
}
//MARK: - @objc func
@objc func handleResetPassword() {
guard let email = viewModel.email else {return}
showLoader(true)
Service.resetPassword(forEmail: email) { error in
self.showLoader(false)
if error != nil {
self.showMessage(withTitle: "", message: MSG_NOT_RIGHT_EMAIL)
return
}
self.delegate?.didSendResetPasswordLink()
}
}
@objc func handleGoBack() {
navigationController?.popViewController(animated: true)
}
@objc func textDidChange(_ sender : UITextField) {
if sender == emailTextField {
viewModel.email = sender.text
}
updateForm()
}
}
//MARK: - FormViewModel
extension ResetPasswordController : FormViewModel {
func updateForm() {
resetPasswordButton.isEnabled = viewModel.shouldEnableButton
resetPasswordButton.backgroundColor = viewModel.buttonBackgroundColor
resetPasswordButton.setTitleColor(viewModel.buttonTitleColor, for: .normal)
}
}
//MARK: - UITextFieldDelegate
extension ResetPasswordController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
emailTextField.endEditing(true)
return true
}
}
| 27.832117 | 149 | 0.699712 |
f5dac1a4619b3f032033d2b6e4a68f58446a289c | 13,969 | //
// Shapes.swift
// TastyImitationKeyboard
//
// Created by Alexei Baboulevitch on 10/5/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
// TODO: these shapes were traced and as such are erratic and inaccurate; should redo as SVG or PDF
///////////////////
// SHAPE OBJECTS //
///////////////////
class BackspaceShape: Shape {
override func drawCall(color: UIColor) {
drawBackspace(self.bounds, color)
}
}
class ShiftShape: Shape {
var withLock: Bool = false {
didSet {
self.overflowCanvas.setNeedsDisplay()
}
}
override func drawCall(color: UIColor) {
drawShift(self.bounds, color, self.withLock)
}
}
class GlobeShape: Shape {
override func drawCall(color: UIColor) {
drawGlobe(self.bounds, color)
}
}
class Shape: UIView {
var color: UIColor? {
didSet {
if let color = self.color {
self.overflowCanvas.setNeedsDisplay()
}
}
}
// in case shapes draw out of bounds, we still want them to show
var overflowCanvas: OverflowCanvas!
convenience init() {
self.init(frame: CGRectZero)
}
override required init(frame: CGRect) {
super.init(frame: frame)
self.opaque = false
self.clipsToBounds = false
self.overflowCanvas = OverflowCanvas(shape: self)
self.addSubview(self.overflowCanvas)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var oldBounds: CGRect?
override func layoutSubviews() {
if self.bounds.width == 0 || self.bounds.height == 0 {
return
}
if oldBounds != nil && CGRectEqualToRect(self.bounds, oldBounds!) {
return
}
oldBounds = self.bounds
super.layoutSubviews()
let overflowCanvasSizeRatio = CGFloat(1.25)
let overflowCanvasSize = CGSizeMake(self.bounds.width * overflowCanvasSizeRatio, self.bounds.height * overflowCanvasSizeRatio)
self.overflowCanvas.frame = CGRectMake(
CGFloat((self.bounds.width - overflowCanvasSize.width) / 2.0),
CGFloat((self.bounds.height - overflowCanvasSize.height) / 2.0),
overflowCanvasSize.width,
overflowCanvasSize.height)
self.overflowCanvas.setNeedsDisplay()
}
func drawCall(color: UIColor) { /* override me! */ }
class OverflowCanvas: UIView {
unowned var shape: Shape
init(shape: Shape) {
self.shape = shape
super.init(frame: CGRectZero)
self.opaque = false
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
let csp = CGColorSpaceCreateDeviceRGB()
CGContextSaveGState(ctx)
let xOffset = (self.bounds.width - self.shape.bounds.width) / CGFloat(2)
let yOffset = (self.bounds.height - self.shape.bounds.height) / CGFloat(2)
CGContextTranslateCTM(ctx, xOffset, yOffset)
self.shape.drawCall(shape.color != nil ? shape.color! : UIColor.redColor())
CGContextRestoreGState(ctx)
}
}
}
/////////////////////
// SHAPE FUNCTIONS //
/////////////////////
func getFactors(fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, yScalingFactor: CGFloat, lineWidthScalingFactor: CGFloat, fillIsHorizontal: Bool, offset: CGFloat) {
var xSize = { () -> CGFloat in
let scaledSize = (fromSize.width / CGFloat(2))
if scaledSize > toRect.width {
return (toRect.width / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
var ySize = { () -> CGFloat in
let scaledSize = (fromSize.height / CGFloat(2))
if scaledSize > toRect.height {
return (toRect.height / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let actualSize = min(xSize, ySize)
return (actualSize, actualSize, actualSize, false, 0)
}
func centerShape(fromSize: CGSize, toRect: CGRect) {
let xOffset = (toRect.width - fromSize.width) / CGFloat(2)
let yOffset = (toRect.height - fromSize.height) / CGFloat(2)
let ctx = UIGraphicsGetCurrentContext()
CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, xOffset, yOffset)
}
func endCenter() {
let ctx = UIGraphicsGetCurrentContext()
CGContextRestoreGState(ctx)
}
func drawBackspace(bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSizeMake(44, 32), bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSizeMake(44 * xScalingFactor, 32 * yScalingFactor), bounds)
//// Color Declarations
let color = color
let color2 = UIColor.redColor() // TODO:
//// Bezier Drawing
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(16 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(44 * xScalingFactor, 26 * yScalingFactor), controlPoint1: CGPointMake(38 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(44 * xScalingFactor, 6 * yScalingFactor), controlPoint1: CGPointMake(44 * xScalingFactor, 22 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 6 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(36 * xScalingFactor, 0 * yScalingFactor), controlPoint1: CGPointMake(44 * xScalingFactor, 6 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 0 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(16 * xScalingFactor, 0 * yScalingFactor), controlPoint1: CGPointMake(32 * xScalingFactor, 0 * yScalingFactor), controlPoint2: CGPointMake(16 * xScalingFactor, 0 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(16 * xScalingFactor, 32 * yScalingFactor))
bezierPath.closePath()
color.setFill()
bezierPath.fill()
//// Bezier 2 Drawing
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(20 * xScalingFactor, 10 * yScalingFactor))
bezier2Path.addLineToPoint(CGPointMake(34 * xScalingFactor, 22 * yScalingFactor))
bezier2Path.addLineToPoint(CGPointMake(20 * xScalingFactor, 10 * yScalingFactor))
bezier2Path.closePath()
UIColor.grayColor().setFill()
bezier2Path.fill()
color2.setStroke()
bezier2Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
var bezier3Path = UIBezierPath()
bezier3Path.moveToPoint(CGPointMake(20 * xScalingFactor, 22 * yScalingFactor))
bezier3Path.addLineToPoint(CGPointMake(34 * xScalingFactor, 10 * yScalingFactor))
bezier3Path.addLineToPoint(CGPointMake(20 * xScalingFactor, 22 * yScalingFactor))
bezier3Path.closePath()
UIColor.redColor().setFill()
bezier3Path.fill()
color2.setStroke()
bezier3Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier3Path.stroke()
endCenter()
}
func drawShift(bounds: CGRect, color: UIColor, withRect: Bool) {
let factors = getFactors(CGSizeMake(38, (withRect ? 34 + 4 : 32)), bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSizeMake(38 * xScalingFactor, (withRect ? 34 + 4 : 32) * yScalingFactor), bounds)
//// Color Declarations
let color2 = color
//// Bezier Drawing
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(28 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(19 * xScalingFactor, 0 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(10 * xScalingFactor, 18 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(10 * xScalingFactor, 28 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(14 * xScalingFactor, 32 * yScalingFactor), controlPoint1: CGPointMake(10 * xScalingFactor, 28 * yScalingFactor), controlPoint2: CGPointMake(10 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(24 * xScalingFactor, 32 * yScalingFactor), controlPoint1: CGPointMake(16 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(24 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(28 * xScalingFactor, 28 * yScalingFactor), controlPoint1: CGPointMake(24 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(28 * xScalingFactor, 32 * yScalingFactor))
bezierPath.addCurveToPoint(CGPointMake(28 * xScalingFactor, 18 * yScalingFactor), controlPoint1: CGPointMake(28 * xScalingFactor, 26 * yScalingFactor), controlPoint2: CGPointMake(28 * xScalingFactor, 18 * yScalingFactor))
bezierPath.closePath()
color2.setFill()
bezierPath.fill()
if withRect {
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRectMake(10 * xScalingFactor, 34 * yScalingFactor, 18 * xScalingFactor, 4 * yScalingFactor))
color2.setFill()
rectanglePath.fill()
}
endCenter()
}
func drawGlobe(bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSizeMake(41, 40), bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSizeMake(41 * xScalingFactor, 40 * yScalingFactor), bounds)
//// Color Declarations
let color = color
//// Oval Drawing
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0 * xScalingFactor, 0 * yScalingFactor, 40 * xScalingFactor, 40 * yScalingFactor))
color.setStroke()
ovalPath.lineWidth = 1 * lineWidthScalingFactor
ovalPath.stroke()
//// Bezier Drawing
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(20 * xScalingFactor, -0 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(20 * xScalingFactor, 40 * yScalingFactor))
bezierPath.addLineToPoint(CGPointMake(20 * xScalingFactor, -0 * yScalingFactor))
bezierPath.closePath()
color.setStroke()
bezierPath.lineWidth = 1 * lineWidthScalingFactor
bezierPath.stroke()
//// Bezier 2 Drawing
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(0.5 * xScalingFactor, 19.5 * yScalingFactor))
bezier2Path.addLineToPoint(CGPointMake(39.5 * xScalingFactor, 19.5 * yScalingFactor))
bezier2Path.addLineToPoint(CGPointMake(0.5 * xScalingFactor, 19.5 * yScalingFactor))
bezier2Path.closePath()
color.setStroke()
bezier2Path.lineWidth = 1 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
var bezier3Path = UIBezierPath()
bezier3Path.moveToPoint(CGPointMake(21.63 * xScalingFactor, 0.42 * yScalingFactor))
bezier3Path.addCurveToPoint(CGPointMake(21.63 * xScalingFactor, 39.6 * yScalingFactor), controlPoint1: CGPointMake(21.63 * xScalingFactor, 0.42 * yScalingFactor), controlPoint2: CGPointMake(41 * xScalingFactor, 19 * yScalingFactor))
bezier3Path.lineCapStyle = kCGLineCapRound;
color.setStroke()
bezier3Path.lineWidth = 1 * lineWidthScalingFactor
bezier3Path.stroke()
//// Bezier 4 Drawing
var bezier4Path = UIBezierPath()
bezier4Path.moveToPoint(CGPointMake(17.76 * xScalingFactor, 0.74 * yScalingFactor))
bezier4Path.addCurveToPoint(CGPointMake(18.72 * xScalingFactor, 39.6 * yScalingFactor), controlPoint1: CGPointMake(17.76 * xScalingFactor, 0.74 * yScalingFactor), controlPoint2: CGPointMake(-2.5 * xScalingFactor, 19.04 * yScalingFactor))
bezier4Path.lineCapStyle = kCGLineCapRound;
color.setStroke()
bezier4Path.lineWidth = 1 * lineWidthScalingFactor
bezier4Path.stroke()
//// Bezier 5 Drawing
var bezier5Path = UIBezierPath()
bezier5Path.moveToPoint(CGPointMake(6 * xScalingFactor, 7 * yScalingFactor))
bezier5Path.addCurveToPoint(CGPointMake(34 * xScalingFactor, 7 * yScalingFactor), controlPoint1: CGPointMake(6 * xScalingFactor, 7 * yScalingFactor), controlPoint2: CGPointMake(19 * xScalingFactor, 21 * yScalingFactor))
bezier5Path.lineCapStyle = kCGLineCapRound;
color.setStroke()
bezier5Path.lineWidth = 1 * lineWidthScalingFactor
bezier5Path.stroke()
//// Bezier 6 Drawing
var bezier6Path = UIBezierPath()
bezier6Path.moveToPoint(CGPointMake(6 * xScalingFactor, 33 * yScalingFactor))
bezier6Path.addCurveToPoint(CGPointMake(34 * xScalingFactor, 33 * yScalingFactor), controlPoint1: CGPointMake(6 * xScalingFactor, 33 * yScalingFactor), controlPoint2: CGPointMake(19 * xScalingFactor, 22 * yScalingFactor))
bezier6Path.lineCapStyle = kCGLineCapRound;
color.setStroke()
bezier6Path.lineWidth = 1 * lineWidthScalingFactor
bezier6Path.stroke()
endCenter()
}
| 39.238764 | 241 | 0.684086 |
d6ae675046e6a0845cb4ab700cf98720eeba6acc | 260 | // 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 < {
{
}
{
{
}
}
case
let {
protocol C {
deinit {
{
{
enum A {
struct S {
class
case ,
| 11.818182 | 87 | 0.684615 |
292397d502edee6af892becb38c69f2049dcd5c1 | 4,282 | //
// SettingsDataManager.swift
// goSellSDK
//
// Copyright © 2019 Tap Payments. All rights reserved.
//
import func TapSwiftFixes.synchronized
/// Settings data manager.
internal final class SettingsDataManager {
// MARK: - Internal -
internal typealias OptionalErrorClosure = (TapSDKError?) -> Void
// MARK: Properties
/// SDK settings.
internal private(set) var settings: SDKSettingsData? {
didSet {
if let deviceID = self.settings?.deviceID {
KeychainManager.deviceID = deviceID
}
}
}
// MARK: Methods
internal func checkInitializationStatus(_ completion: @escaping OptionalErrorClosure) {
synchronized(self) { [unowned self] in
switch self.status {
case .notInitiated:
self.append(completion)
self.callInitializationAPI()
case .initiated:
self.append(completion)
case .succeed:
guard self.settings != nil else {
completion(TapSDKUnknownError(dataTask: nil))
return
}
completion(nil)
}
}
}
internal static func resetAllSettings() {
self.storages?.values.forEach { $0.reset() }
}
// MARK: - Private -
// MARK: Properties
private var status: InitializationStatus = .notInitiated
private var pendingCompletions: [OptionalErrorClosure] = []
private static var storages: [SDKMode: SettingsDataManager]? = [:]
// MARK: Methods
private init() {}
private func append(_ completion: @escaping OptionalErrorClosure) {
self.pendingCompletions.append(completion)
}
private func callInitializationAPI() {
self.status = .initiated
APIClient.shared.initSDK { [unowned self] (settings, error) in
self.update(settings: settings, error: error)
}
}
private func update(settings updatedSettings: SDKSettings?, error: TapSDKError?) {
if let nonnullError = error {
self.status = .notInitiated
if self.pendingCompletions.count > 0 {
self.callAllPendingCompletionsAndEmptyStack(nonnullError)
}
else {
ErrorDataManager.handle(nonnullError, retryAction: { self.callInitializationAPI() }, alertDismissButtonClickHandler: nil)
}
}
else {
self.settings = updatedSettings?.data
self.status = .succeed
self.callAllPendingCompletionsAndEmptyStack(nil)
}
}
private func callAllPendingCompletionsAndEmptyStack(_ error: TapSDKError?) {
synchronized(self) { [unowned self] in
for completion in self.pendingCompletions {
completion(error)
}
self.pendingCompletions.removeAll()
}
}
private func reset() {
let userInfo: [String: String] = [
NSLocalizedDescriptionKey: "Merchant account data is missing."
]
let underlyingError = NSError(domain: ErrorConstants.internalErrorDomain, code: InternalError.noMerchantData.rawValue, userInfo: userInfo)
let error = TapSDKKnownError(type: .internal, error: underlyingError, response: nil, body: nil)
self.update(settings: nil, error: error)
}
}
// MARK: - Singleton
extension SettingsDataManager: Singleton {
internal static var shared: SettingsDataManager {
if let existing = self.storages?[GoSellSDK.mode] {
return existing
}
let instance = SettingsDataManager()
var stores = self.storages ?? [:]
stores[GoSellSDK.mode] = instance
self.storages = stores
return instance
}
}
// MARK: - ImmediatelyDestroyable
extension SettingsDataManager: ImmediatelyDestroyable {
internal static func destroyInstance() {
self.storages = nil
}
internal static var hasAliveInstance: Bool {
return !(self.storages?.isEmpty ?? true)
}
}
| 24.05618 | 140 | 0.586408 |
62102d4c88e18ec3ded8280e7dfc08f3bca98a8e | 3,682 |
import Foundation
/*:
## Error Handling in Swift
In this playground, we're going to convert data (imagine it coming from an API) into a value we can use in our future app
*/
// Consider this the data coming from the API (after it's been deserialized). This data tends to be very messy
let todoItemDictionary: [String : AnyObject] = [
"completed": false,
"due_on": "2015-07-08",
"description": "Facebook app and contest"
]
/*:
The goal is to convert the data into a very clean model that can be used throughout the application
*/
struct TodoItem {
// This is the description of the task that needs to be done
let description: String
// The due date here is optional, since not all tasks need to have timelines
let dueDate: String?
// Keeping track of whether the todo item is completed or not
// Note that when this item is set to complete, a brand new todo item copy gets created with the different complete value
var completed: Bool
}
/*:
The `TodoItemParser` is an in-between container for dealing with the messy data coming from the API and converting it into the clean model layer we can safely and cheerfully use within our future application
Read more about this concept here: http://www.jessesquires.com/swift-failable-initializers-revisited/
*/
struct TodoItemParser {
enum Error: ErrorType {
case InvalidData
}
func parse(fromData data: [String : AnyObject]) throws -> TodoItem {
// the defer statement will execute whether the parsing is successful or not!
// open up the Debug area to see it!
defer { print("parsing complete!") }
// use guard here to focus on the happy path
// read more about it on my blog here: http://natashatherobot.com/swift-guard-better-than-if/
guard let content = data["description"] as? String,
completed = data["completed"] as? Bool,
dueDate = data["due_on"] as? String?
else {
// handle the error case
throw Error.InvalidData
}
return TodoItem(description: content, dueDate: dueDate, completed: completed)
}
}
/*:
### Task: Refactor the TodoItemParser to throw a different error for each invalid field (e.g. DescriptionInvalid, CompletedInvalid, DueOnInvalid)
*/
/*:
Now, let's actually parse the data dictionary using the do / catch error handlign in Swift!
*/
// In Swift, we do this using the do / catch block
do {
// success!
let todoItem = try TodoItemParser().parse(fromData: todoItemDictionary)
print(todoItem)
} catch TodoItemParser.Error.InvalidData {
// failure
// note that you can specify which error you're catching
// or you can just use catch on it's own to catch all errors
print("😱 the data is invalid!!!")
}
/*:
Parse invalid data to see what happens!
*/
do {
let todoItem = try TodoItemParser().parse(fromData: ["badDataTroll" : "😈"])
print(todoItem)
} catch TodoItemParser.Error.InvalidData {
print("😱 the data is invalid!!!")
}
/*:
### Task: Refactor the error catching to catch your additonal errors (e.g. DescriptionInvalid, CompletedInvalid, DueOnInvalid).
*/
/*:
Now, let's try?
*/
// Instead of the do / catch block, you have the option of treating bad data as an optional
let todoItem = try? TodoItemParser().parse(fromData: todoItemDictionary)
// the todoItem is an optional, so don't forget to unwrap to use it!
if let todoItem = todoItem {
print("The todo item parsing was a success! 🎉")
}
/*:
## Task: Try? parsing the todo item from invalid data to see what happens
*/
// let invalidTodoTime = try? ...
| 30.429752 | 207 | 0.682781 |
28b145cb6b753cdfb1c3b809726b8a0f6537aa70 | 719 | // This class is automatically included in FastlaneRunner during build
// This autogenerated file will be overwritten or replaced during build time, or when you initialize `match`
//
// ** 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
//
class Matchfile: MatchfileProtocol {
// If you want to enable `match`, run `fastlane match init`
// After, this file will be replaced with a custom implementation that contains values you supplied
// during the `init` process, and you won't see this message
}
// Generated with fastlane 2.109.1
| 32.681818 | 108 | 0.746871 |
5d96796ab7e5cde9ae30b230cb8083808ba32fa2 | 2,425 | //
// dateSupport.swift
// Task-list
//
// Created by Никита Казанцев on 27.02.2021.
// Copyright © 2021 Sinapsic. All rights reserved.
//
import Foundation
extension Date {
var startOfDay: Date {
return Calendar.current.startOfDay(for: self)
}
var startOfMonth: Date {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.year, .month], from: self)
return calendar.date(from: components)!
}
var endOfDay: Date {
var components = DateComponents()
components.day = 1
components.second = -1
return Calendar.current.date(byAdding: components, to: startOfDay)!
}
var endOfMonth: Date {
var components = DateComponents()
components.month = 1
components.second = -1
return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfMonth)!
}
func isMonday() -> Bool {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.weekday], from: self)
return components.weekday == 2
}
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: self)
}
func getFormattedDate(_ format: String = "dd.MM", dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
dateformat.dateStyle = dateStyle
dateformat.timeStyle = timeStyle
dateformat.timeZone = TimeZone.current
dateformat.locale = Locale.init(identifier: Locale.preferredLanguages.first!)
return dateformat.string(from: self)
}
func UTCtoClockTimeOnly(currentDate: Date, format: String = "HH:mm") -> String {
// 4) Set the current date, altered by timezone.
let dateString = currentDate.getFormattedDate(format: format)
return dateString
}
/**
получение длительности сна как строка + форматирование с добавлением ведущих нулей когда нужно
*/
func MinutesToDateDescription(minutes: Int) -> String {
let hours = minutes / 60
let minutes = minutes % 60
let minutesStr = minutes > 9 ? String(minutes) : "0" + String(minutes)
return "\(hours):\(minutesStr)"
}
}
| 28.197674 | 129 | 0.646186 |
d716e6c9831e3557c32fa8681130f1e7fb67e818 | 482 | public struct TOMLDeserializerError: Error, CustomStringConvertible {
let summary: String
let location: Location
public var description: String {
return """
[TOMLDeserializer] Error: \(self.summary)
Line \(self.location.line) Column \(self.location.column) Character \(self.location.bufferOffset):
\(self.location.localText)
""" + String(cString: [CChar](repeating: cSpace, count: self.location.column) + [cCaret, 0])
}
}
| 30.125 | 106 | 0.665975 |
ab6bc7b0f30c5385b024510dff200827ea807d7b | 394 | //
// NetworkOperationExecutor.swift
// YourAnimeList-iOS
//
// Created by Nikita Khomitsevich on 10/18/18.
// Copyright © 2018 Nikita Khomitsevich. All rights reserved.
//
import Foundation
protocol NetworkOperationExecutor {
@discardableResult
func operation(from request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> NetworkOperation
}
| 23.176471 | 125 | 0.72335 |
e2fa34021aca8f9e5805f54703cc776a89464dbc | 6,774 | //
// LiveTextView.swift
// EhPanda
//
// Created by xioxin on 2022/2/12.
//
import SwiftUI
struct LiveTextView: View {
private let liveTextGroups: [LiveTextGroup]
private let focusedLiveTextGroup: LiveTextGroup?
private let tapAction: (LiveTextGroup) -> Void
init(
liveTextGroups: [LiveTextGroup],
focusedLiveTextGroup: LiveTextGroup?,
tapAction: @escaping (LiveTextGroup) -> Void
) {
self.liveTextGroups = liveTextGroups
self.focusedLiveTextGroup = focusedLiveTextGroup
self.tapAction = tapAction
}
var body: some View {
GeometryReader { proxy in
let size = proxy.size
let width = size.width
let height = size.height
ZStack {
Canvas { context, _ in
context.fill(
Path(CGRect(x: 0, y: 0, width: width, height: height)),
with: .color(.black.opacity(0.1))
)
let tuples: [(UUID, Path)] = liveTextGroups
.flatMap { group in
group.blocks.map { block in
(group.id, block)
}
}
.map { (id, block) in
let expandingSize = 4.0
let bounds = block.bounds
let topLeft = bounds.topLeft * size
let rect = CGRect(
x: 0, y: 0,
width: bounds.getWidth(size) + expandingSize * 2,
height: bounds.getHeight(size) + expandingSize * 2)
let path = Path(roundedRect: rect, cornerRadius: bounds.getHeight(size) / 5)
.applying(CGAffineTransform(rotationAngle: block.bounds.getRadian(size)))
.offsetBy(dx: topLeft.x - expandingSize, dy: topLeft.y - expandingSize)
return (id, path)
}
context.withCGContext { cgContext in
tuples.forEach { (_, path) in
cgContext.setFillColor(.init(red: 255, green: 255, blue: 255, alpha: 1))
cgContext.setShadow(
offset: .zero, blur: 15,
color: .init(red: 0, green: 0, blue: 0, alpha: 0.3)
)
cgContext.addPath(path.cgPath)
cgContext.drawPath(using: .fill)
}
}
context.blendMode = .destinationOut
tuples.forEach { (_, path) in
context.fill(path, with: .color(.red))
context.stroke(path, with: .color(.red))
}
if let focusedLiveTextGroup = focusedLiveTextGroup {
context.blendMode = .copy
tuples.forEach { (groupUUID, path) in
if groupUUID == focusedLiveTextGroup.id {
context.stroke(
path, with: .color(.accentColor.opacity(0.6)),
style: .init(lineWidth: 10)
)
}
}
context.blendMode = .destinationOut
tuples.forEach { (groupUUID, path) in
if groupUUID == focusedLiveTextGroup.id {
context.fill(path, with: .color(.accentColor))
}
}
}
}
ForEach(liveTextGroups) { textGroup in
HighlightView(text: textGroup.text) {
tapAction(textGroup)
}
.frame(width: textGroup.width * width, height: textGroup.height * height)
.position(
x: (textGroup.minX + textGroup.width / 2) * width,
y: (textGroup.minY + textGroup.height / 2) * height
)
}
}
}
}
}
// MARK: HighlightView
private struct HighlightView: UIViewRepresentable {
final class Coordinator: NSObject {
var textView: UITextView?
var highLightView: HighlightView
init(_ highLightView: HighlightView) {
self.highLightView = highLightView
}
@objc func onTap(sender: UIView) {
Logger.info("onTap", context: ["tappedText": textView?.text])
guard let textView = textView else { return }
let height = textView.contentSize.height
textView.contentInset = .init(
top: textView.frame.height / 2 - height / 2,
left: textView.frame.width / 2 ,
bottom: 0, right: 0
)
highLightView.tapAction()
textView.selectAll(nil)
textView.perform(NSSelectorFromString("_translate:"), with: nil)
}
}
private let text: String
private let tapAction: () -> Void
init(text: String, tapAction: @escaping () -> Void) {
self.text = text
self.tapAction = tapAction
}
func makeCoordinator() -> Coordinator {
.init(self)
}
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
context.coordinator.textView = textView
let text = text.unicodeScalars
.filter { !$0.properties.isEmojiPresentation }
.reduce("") { $0 + String($1)}
textView.text = text
textView.isEditable = false
textView.tintColor = .clear
textView.textColor = .clear
textView.backgroundColor = .clear
textView.font = .systemFont(ofSize: 0)
textView.isSelectable = false
textView.autocapitalizationType = .sentences
textView.isSelectable = true
textView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(
target: context.coordinator,
action: #selector(Coordinator.onTap(sender:))
)
textView.isUserInteractionEnabled = true
textView.addGestureRecognizer(tap)
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
}
}
// MARK: Definition
private func * (lhs: CGPoint, rhs: CGSize) -> CGPoint {
.init(x: lhs.x * rhs.width, y: lhs.y * rhs.height)
}
| 37.843575 | 105 | 0.484795 |
9b23d4cb67c0efd7cc36f7f65b34e1fc34d7a0cc | 283 | //
// ChecklistItem.swift
// Checklists
//
// Created by eseedo on 3/6/19.
// Copyright © 20
// 19 icode. All rights reserved.
//
import Foundation
class ChecklistItem{
var text = ""
var checked = false
func toggleChecked() {
checked = !checked
}
}
| 15.722222 | 34 | 0.60424 |
e0302a565684c3c32c37a596954146c426042a79 | 2,418 | // The MIT License (MIT)
//
// Copyright (c) 2020–2022 Alexander Grebenyuk (github.com/kean).
import SwiftUI
import CoreData
import PulseCore
import Combine
#if os(macOS)
struct PinsView: View {
@ObservedObject var model: ConsoleViewModel
@Environment(\.colorScheme) private var colorScheme: ColorScheme
@State private var isShowingShareSheet = false
private var context: AppContext { model.context }
public var body: some View {
messagesListView
.frame(minWidth: 300, idealWidth: 400, maxWidth: 700)
.toolbar(content: {
Button(action: model.removeAllPins) {
Image(systemName: "trash")
}
})
}
@ViewBuilder
private var messagesListView: some View {
if model.messages.isEmpty {
placeholder
.frame(maxWidth: 200)
} else {
ZStack {
let factory = ConsoleRowFactory(context: context, showInConsole: nil)
NotList(model: model.list, makeRowView: factory.makeRowView, onSelectRow: model.selectEntityAt, onDoubleClickRow: {
openMessage(model.list.elements[$0])
})
NavigationLink(destination: ConsoleDetailsRouter(model: model.details), isActive: .constant(true)) { EmptyView() }
.hidden()
}
}
}
private func openMessage(_ message: LoggerMessageEntity) {
ExternalEvents.open = AnyView(
model.details.makeDetailsRouter(for: message)
.frame(minWidth: 500, idealWidth: 700, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: 500, idealHeight: 800, maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/)
)
guard let url = URL(string: "com-github-kean-pulse://open-details") else { return }
NSWorkspace.shared.open(url)
}
private var placeholder: PlaceholderView {
PlaceholderView(imageName: "pin.circle", title: "No Pins", subtitle: "Pin messages using the context menu or from the details page")
}
}
#if DEBUG
struct PinsView_Previews: PreviewProvider {
static var previews: some View {
return Group {
PinsView(model: .init(store: .mock))
PinsView(model: .init(store: .mock))
.environment(\.colorScheme, .dark)
}
}
}
#endif
#endif
| 33.583333 | 215 | 0.617039 |
d6cb1204c61a50b0711069f53843bee19f5cc2c7 | 6,253 | //
// SendRootView.swift
// p2p_wallet
//
// Created by Chung Tran on 01/06/2021.
//
import UIKit
import RxSwift
import RxCocoa
extension SendToken {
class RootView: ScrollableVStackRootView {
// MARK: - Dependencies
@Injected private var analyticsManager: AnalyticsManagerType
// MARK: - Properties
private let viewModel: SendTokenViewModelType
private let disposeBag = DisposeBag()
// MARK: - Subviews
private lazy var walletView = WalletView(viewModel: viewModel)
private lazy var priceLabel = UILabel(textSize: 15, weight: .medium)
private lazy var renBTCNetworkSection = UIView.createSectionView(
title: L10n.destinationNetwork,
contentView: renBTCNetworkLabel,
addSeparatorOnTop: true
)
.onTap(self, action: #selector(chooseBTCNetwork))
private lazy var renBTCNetworkLabel = UILabel(textSize: 15, weight: .medium)
private lazy var feeLabel = UILabel(textSize: 15, weight: .medium)
private lazy var recipientView = RecipientView(viewModel: viewModel)
private lazy var errorLabel = UILabel(text: " ", textSize: 12, weight: .medium, textColor: .red, numberOfLines: 0, textAlignment: .center)
private lazy var feeInfoButton = UIImageView(width: 20, height: 20, image: .infoCircle, tintColor: .a3a5ba)
.onTap(self, action: #selector(showFeeInfo))
private lazy var sendButton = WLButton.stepButton(type: .blue, label: L10n.sendNow)
.onTap(self, action: #selector(authenticateAndSend))
// MARK: - Initializers
init(viewModel: SendTokenViewModelType) {
self.viewModel = viewModel
super.init(frame: .zero)
}
// MARK: - Methods
override func commonInit() {
super.commonInit()
layout()
bind()
}
// MARK: - Layout
private func layout() {
stackView.spacing = 20
stackView.addArrangedSubviews {
walletView
UIView.createSectionView(
title: L10n.currentPrice,
contentView: priceLabel,
rightView: nil,
addSeparatorOnTop: false
)
renBTCNetworkSection
UIView.createSectionView(
title: L10n.transferFee,
contentView: feeLabel,
rightView: feeInfoButton,
addSeparatorOnTop: true
)
recipientView
errorLabel
sendButton
BEStackViewSpacing(16)
UILabel(text: L10n.sendSOLOrAnySPLTokensOnOneAddress, textSize: 14, textColor: .textSecondary, numberOfLines: 0, textAlignment: .center)
.padding(.init(x: 20, y: 0))
}
feeInfoButton.isHidden = !Defaults.useFreeTransaction
}
private func bind() {
// price labels
viewModel.currentWalletDriver
.map {"\(Defaults.fiat.symbol)\(($0?.priceInCurrentFiat ?? 0).toString(maximumFractionDigits: 9)) \(L10n.per) \($0?.token.symbol ?? "")"}
.drive(priceLabel.rx.text)
.disposed(by: disposeBag)
// renBTC
viewModel.renBTCInfoDriver
.map {$0 == nil}
.drive(renBTCNetworkSection.rx.isHidden)
.disposed(by: disposeBag)
viewModel.renBTCInfoDriver
.map {$0?.network == .bitcoin}
.drive(feeInfoButton.rx.isHidden)
.disposed(by: disposeBag)
viewModel.renBTCInfoDriver
.map {$0?.network.rawValue.uppercaseFirst.localized()}
.drive(renBTCNetworkLabel.rx.text)
.disposed(by: disposeBag)
// fee
viewModel.feeDriver
.drive(feeLabel.rx.loadableText(onLoaded: { fee in
let fee = fee ?? 0
if fee == 0 {
return L10n.free
}
return "\(fee.toString(maximumFractionDigits: 9)) SOL"
}))
.disposed(by: disposeBag)
// error
viewModel.errorDriver
.map {
if $0 == L10n.insufficientFunds || $0 == L10n.amountIsNotValid
{
return nil
}
return $0
}
.asDriver(onErrorJustReturn: nil)
.drive(errorLabel.rx.text)
.disposed(by: disposeBag)
// send button
viewModel.isValidDriver
.drive(sendButton.rx.isEnabled)
.disposed(by: disposeBag)
Driver.combineLatest(
viewModel.amountDriver.map {($0 == nil || $0 == 0)},
viewModel.receiverAddressDriver.map {address in
guard let address = address else {return true}
return address.isEmpty
}
)
.map(generateSendButtonText)
.drive(sendButton.rx.title())
.disposed(by: disposeBag)
}
}
}
private extension SendToken.RootView {
@objc func showFeeInfo() {
viewModel.navigate(to: .feeInfo)
}
@objc func chooseBTCNetwork() {
viewModel.navigateToSelectBTCNetwork()
}
@objc func authenticateAndSend() {
viewModel.authenticateAndSend()
}
}
private func generateSendButtonText(
isAmountNil: Bool,
isRecipientNil: Bool
) -> String {
if isAmountNil {
return L10n.enterTheAmount
}
if isRecipientNil {
return L10n.enterTheRecipientSAddress
}
return L10n.sendNow
}
| 33.438503 | 153 | 0.516712 |
fff52ff7d57d53f7b423fdfc7fd124fe4fcf1e26 | 4,413 | //
// StepTableCellViewModel.swift
// Core
//
// Created by Kamil Tustanowski on 27/07/2019.
// Copyright © 2019 Kamil Tustanowski. All rights reserved.
//
import Foundation
import RxRelay
import RxSwift
public protocol StepCellViewModelProtocol {
var input: StepCellViewModelProtocolInputs { get }
var output: StepCellViewModelProtocolOutputs { get }
}
public protocol StepCellViewModelProtocolInputs {
func timerButtonTapped()
func doneButtonTapped()
}
public protocol StepCellViewModelProtocolOutputs {
var title: Observable<String> { get }
var duration: Observable<String> { get }
var endTime: Observable<String> { get }
var isDurationAvailable: Observable<Bool> { get }
var didTapDone: Observable<Void> { get }
var isDone: BehaviorRelay<Bool> { get }
var isCountdown: Observable<Bool> { get }
var currentDuration: Observable<TimeInterval?> { get }
}
public final class StepCellViewModel: StepCellViewModelProtocol, StepCellViewModelProtocolInputs, StepCellViewModelProtocolOutputs {
private var lastDate: Date?
public var input: StepCellViewModelProtocolInputs { return self }
public var output: StepCellViewModelProtocolOutputs { return self }
// MARK: - Inputs
public func timerButtonTapped() {
guard !isCountingDown else {
stopCountdown()
return
}
startCountdown()
}
public func doneButtonTapped() {
isDone.accept(true)
currentDurationRelay?.accept(0)
didTapDoneRelay.accept(())
}
// MARK: - Outputs
public let title: Observable<String>
public let duration: Observable<String>
public let endTime: Observable<String>
public let isDurationAvailable: Observable<Bool>
public let didTapDone: Observable<Void>
public let isDone = BehaviorRelay<Bool>(value: false)
public let isCountdown: Observable<Bool>
public var currentDuration: Observable<TimeInterval?> {
return currentDurationRelay?.asObservable() ?? .just(nil)
}
// MARK: Implementation
private let disposeBag = DisposeBag()
private let step: Step
private let isCountdownRelay = BehaviorRelay<Bool>(value: false)
private let didTapDoneRelay = PublishRelay<Void>()
private let currentDurationRelay: BehaviorRelay<TimeInterval?>?
private var timerDisposable: Disposable? {
willSet {
timerDisposable?.dispose()
}
didSet {
isCountdownRelay.accept(timerDisposable != nil)
}
}
public init(step: Step) {
self.step = step
currentDurationRelay = BehaviorRelay<TimeInterval?>(value: step.duration)
title = .just(step.description)
isDurationAvailable = .just(step.duration != nil)
duration = currentDurationRelay?
.compactMap { $0?.shortTime }
.map { "\($0)" } ?? .empty()
endTime = currentDurationRelay?
.compactMap { $0?.endTime }
.map { "\($0)" } ?? .empty()
didTapDone = didTapDoneRelay
.asObservable()
isCountdown = isCountdownRelay
.asObservable()
let durationReachedZero = currentDurationRelay?.filter { $0 == 0 }
durationReachedZero?
.subscribe(onNext: { [weak self] _ in
self?.timerDisposable?.dispose()
})
.disposed(by: disposeBag)
}
deinit {
timerDisposable?.dispose()
}
}
private extension StepCellViewModel {
var isCountingDown: Bool {
return timerDisposable != nil
}
func stopCountdown() {
timerDisposable?.dispose()
timerDisposable = nil
}
func startCountdown() {
lastDate = Date()
timerDisposable = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
.subscribe { [weak self] _ in
guard let duration = self?.currentDurationRelay?.value,
let lastDate = self?.lastDate else { return }
let now = Date()
let deltaTime = now.timeIntervalSince(lastDate)
let currentDuration = max(duration - deltaTime, 0)
self?.currentDurationRelay?.accept(currentDuration)
self?.lastDate = now
}
}
}
| 31.297872 | 132 | 0.631543 |
5ba71f2f9e0deb13628fbbe0e6e12f4e85f46ef9 | 4,786 | import AVFoundation
import Vision
class VideoFrameProcessing: NSObject {
typealias Callback = (FrameResult) -> Void
private let captureSession: AVCaptureSession
private let videoDataOutput = AVCaptureVideoDataOutput()
private let videoDataOutputQueue = DispatchQueue(label: "net.stuehrk.lukas.URLScanner.VideoDataOutputQueue")
private var request: VNRecognizeTextRequest!
private var statistics = StringStatistics(bufferSize: 30)
private let callback: Callback
/// - Parameters:
/// - captureSession: The capture session which is used to access the camera.
/// - regionOfInterest: The region in the camera image which is used for processing text. The rectangular uses
/// normalized coordinates where the origin is the upper-left corner.
/// - callback: A callback which is called for every processed frame with the result of the processing.
init(captureSession: AVCaptureSession, regionOfInterest: CGRect, callback: @escaping Callback) {
self.captureSession = captureSession
self.callback = callback
super.init()
videoDataOutput.alwaysDiscardsLateVideoFrames = true
videoDataOutput.setSampleBufferDelegate(self, queue: videoDataOutputQueue)
videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarFullRange]
if captureSession.canAddOutput(videoDataOutput) {
captureSession.addOutput(videoDataOutput)
// TODO: I did not check yet if video stabilization gives better results.
videoDataOutput.connection(with: .video)?.preferredVideoStabilizationMode = .off
} else {
print("Could not add output")
}
videoDataOutput.connection(with: .video)?.videoOrientation = .landscapeRight
self.request = VNRecognizeTextRequest(completionHandler: recognizeTextHandler(request:error:))
request.recognitionLevel = .fast
request.usesLanguageCorrection = false
// We need to use the region of interest, otherwise the OCR would take much longer than one frame to process.
// Also: AVFoundation and UIKit always use the upper-left corner as origin (0,0). Vision takes the lower-left
// corner, that's why we need to translate between.
request.regionOfInterest = CGRect(
x: regionOfInterest.origin.x,
y: 1 - regionOfInterest.origin.y - regionOfInterest.height,
width: regionOfInterest.width,
height: regionOfInterest.height
)
}
func start() {
statistics = StringStatistics(bufferSize: statistics.bufferSize)
captureSession.startRunning()
}
func stop() {
captureSession.stopRunning()
}
}
extension VideoFrameProcessing: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
// TODO: maybe assertion failure
return
}
// We don't support different device orientations for now and explicitly set the video orientation, so we can
// hardcode the orientation to "up" because our video stream always has the correct orientation. If we support
// device rotation, we might need to pass a different value for the orientation.
let requestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .up, options: [:])
do {
try requestHandler.perform([request])
} catch {
print(error)
}
}
func captureOutput(_ output: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
print("frame drop")
}
}
extension VideoFrameProcessing {
func recognizeTextHandler(request: VNRequest, error: Error?) {
guard let results = request.results as? [VNRecognizedTextObservation] else {
assertionFailure()
return
}
var candidates = [VNRecognizedText]()
for result in results {
guard let candidate = result.topCandidates(1).first else { continue }
candidates.append(candidate)
}
if let (url, regions) = candidates.extractUrl() {
statistics.processFrame(strings: [url.absoluteString])
callback(.urlExtracted(statistics.mostSeen.string, count: statistics.mostSeen.count, regions: regions))
} else {
callback(.noMatch)
}
}
enum FrameResult {
case urlExtracted(String, count: Int, regions: [CGRect])
case noMatch
}
}
| 41.617391 | 132 | 0.685541 |
d7a076bc70aa6d6366822fd594554a66cc4f2cea | 2,704 | import Foundation
struct TagFixture {
static func test(
name: String? = "test-name",
versions: [String]? = ["test"]
) -> Tag {
return .init(name: name, versions: versions)
}
}
struct UserFixture {
static func test(
id: String = "test-id",
name: String = "test-name",
descriptionField: String? = "test-description",
facebookId: String? = nil,
followeesCount: Int? = 0,
followersCount: Int? = 0,
githubLoginName: String? = nil,
itemsCount: Int? = 0,
linkedinId: String? = nil,
location: String? = nil,
organization: String? = nil,
permanentId: Int? = nil,
profileImageUrl: String = "https://google.com",
teamOnly: Bool? = nil,
twitterScreenName: String? = nil,
websiteUrl: String? = nil
) -> User {
return .init(
id: id,
name: name,
descriptionField: descriptionField,
facebookId: facebookId,
followeesCount: followeesCount,
followersCount: followersCount,
githubLoginName: githubLoginName,
itemsCount: itemsCount,
linkedinId: linkedinId,
location: location,
organization: organization,
permanentId: permanentId,
profileImageUrl: profileImageUrl,
teamOnly: teamOnly,
twitterScreenName: twitterScreenName,
websiteUrl: websiteUrl
)
}
}
struct ItemFixture {
static func test(
id: String = "test-id",
title: String = "test-title",
body: String = "test-body",
renderedBody: String = "test-renderedBody",
url: String = "https://google.com",
commentsCount: Int? = 0,
likesCount: Int? = 0,
pageViewsCount: String? = nil,
reactionsCount: Int? = 0,
user: User = UserFixture.test(),
tags: [Tag] = [TagFixture.test()],
privateField: Bool? = nil,
group: String? = nil,
coediting: Bool? = nil,
createdAt: String = "",
updatedAt: String = ""
) -> Item {
return .init(
id: id,
title: title,
body: body,
renderedBody: renderedBody,
url: url,
commentsCount: commentsCount,
likesCount: likesCount,
pageViewsCount: pageViewsCount,
reactionsCount: reactionsCount,
user: user,
tags: tags,
privateField: privateField,
group: group,
coediting: coediting,
createdAt: createdAt,
updatedAt: updatedAt)
}
}
| 30.044444 | 55 | 0.537722 |
8793a29d713467e97027231e0c5feb09d7fa6ea5 | 2,181 | //
// AppDelegate.swift
// FOXAdditions
//
// Created by ChristianFox on 05/13/2019.
// Copyright (c) 2019 ChristianFox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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:.
}
}
| 46.404255 | 285 | 0.755158 |
913e6830f3b1ab3122095b5af5fcaf2f20efc410 | 2,191 | //
// AppDelegate.swift
// Login
//
// Created by Guillermo Alcalá Gamero on 4/8/17.
// Copyright © 2017 Guillermo Alcalá Gamero. 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.617021 | 285 | 0.756276 |
e86d10adeb58c32679228b5e017d9d26780c57df | 322 | //
// AppDelegate.swift
// DeathCounter
//
// Created by Andrei Konstantinov on 05/01/2020.
// Copyright © 2020 8of. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
}
}
| 16.947368 | 70 | 0.71118 |
69def3ce096994f12b27769c52224c251307d72b | 537 | //
// Mother.swift
// Pods
//
// Created by wangcong on 30/06/2017.
//
//
import Foundation
open class Mother: NSObject, PersonProtocol {
var name: String
var kid: Kid
public init(name: String, kid: Kid) {
self.name = name
self.kid = kid
}
// 喂食
open func feed(_ food: String) {
print("\(name) is feeding \(kid.name ?? "kid") eat \(food)")
}
public func eat() {
print("\(name) is eating")
}
public func run() {
print("\(name) is runing")
}
}
| 15.342857 | 68 | 0.530726 |
7a1b1b9f2067a70ceeab5963c14bce393383c86b | 1,362 | //
// ReportSelectDateRangeVC.swift
// MyBankManagementApp
//
// Created by Rigoberto Sáenz Imbacuán on 1/31/16.
// Copyright © 2016 Rigoberto Saenz Imbacuan. All rights reserved.
//
import UIKit
class ReportSelectDateRangeVC: UIViewController {
@IBOutlet weak var datePickerStart: UIDatePicker!
@IBOutlet weak var datePickerEnd: UIDatePicker!
private var startDate = NSDate()
private var endDate = NSDate()
override func viewWillAppear(animated: Bool) { // Called when the view is about to made visible. Default does nothing
datePickerStart.date = NSDate()
datePickerEnd.date = datePickerStart.date
}
@IBAction func onClickGenerate(sender: UIButton, forEvent event: UIEvent) {
// Get dates from pickers
startDate = datePickerStart.date
endDate = datePickerEnd.date
// Validate if endDate is after startDate
if startDate.earlierDate(endDate).isEqualToDate(startDate) {
// StartDate is earlier than EndDate
}else {
View.showAlert(self, messageToShow: "The start date cannot be after end date.")
return
}
// Save selected dates
Bank.instance.selectedStartDateForReport = startDate
Bank.instance.selectedEndDateForReport = endDate
}
} | 30.954545 | 121 | 0.660793 |
db3621b4d436deebeee597c99ef969266a55f25b | 984 | //
// 118. 杨辉三角
//
// 题目链接:https://leetcode-cn.com/problems/pascals-triangle/
// 标签:数组
// 要点:根据杨辉三角规律迭代生成
// 时间复杂度:O(n^2)
// 空间复杂度:O(n^2)
import Foundation
class Solution {
func generate(_ numRows: Int) -> [[Int]] {
guard numRows > 0 else { return [] }
var triangle = [[Int]]()
triangle.append([1]) // 首行始终为 [1]
for rowIndex in 1..<numRows {
var row = [Int]()
var prevRow = triangle[rowIndex - 1]
row.append(1) // 行首始终为 1
for index in 1..<rowIndex {
row.append(prevRow[index - 1] + prevRow[index])
}
row.append(1) // 行尾始终为 1
triangle.append(row)
}
return triangle
}
}
// Tests
let s = Solution()
let input = 5
let expectation = [
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
assert(s.generate(input) == expectation)
| 19.68 | 63 | 0.465447 |
7161a3d77034b030c385a15ed14e3064a0cc6064 | 7,617 | //
// MQTToolConnections.swift
// MQTTool
//
// Created by Brent Petit on 2/17/16.
// Copyright © 2016-2019 Brent Petit. All rights reserved.
//
import Foundation
import Moscapsule
enum ConnectionState { case Disconnected, Connected, Connecting }
struct MyMQTTMessage {
let message: MQTTMessage
let timestamp: NSDate
}
class MQTToolConnection {
let mqttConfig: MQTTConfig
var mqttClient: MQTTClient?
var messageList: [MyMQTTMessage]
// List of recent messages from MQTT message callback
var maxMessageList = 50
var newMessage = false
let messageQueue = DispatchQueue(label: "com.brentpetit.MQTTool.messageQueue")
var subscriptionTopic: String = ""
var subscriptionQos: Int32 = 0
var hostName = ""
var hostPort = ""
// Counters
var messagesSent = 0
var messagesReceived = 0
var connectTime: NSDate?
let maxDisconnectsInMinute = 10 // If we see more than 10 disconnects in a minute, diconnect hard
var disconnectsInMinute = 0
var disconnectTimestamp: Date?
//
// Init takes clientId, host and port
// user and password can be nil, meaning anonymous connection
//
init?(hostname: String, port: String, username: String?, password: String?, clientId: String) {
moscapsule_init()
if let portNumber = Int32(port) {
print("port = \(portNumber)\n")
mqttConfig = MQTTConfig(clientId: clientId, host: hostname, port: portNumber, keepAlive: 60)
} else {
print("bad port\n")
return nil
}
if(username != nil && password != nil) {
mqttConfig.mqttAuthOpts = MQTTAuthOpts(username: username!, password: password!)
}
mqttClient = nil
connectTime = nil
hostName = hostname
hostPort = port
// Init an empty message list
messageList = [MyMQTTMessage]()
}
deinit {
disconnect()
hostName = ""
hostPort = ""
}
// Set the durability of the session
func setCleanSession(option: Bool) {
mqttConfig.cleanSession = option
}
func connect() -> Bool {
// create new MQTT Connection
mqttConfig.onMessageCallback = { mqttMessage in
self.handleNewMessage(message: mqttMessage)
}
mqttConfig.onPublishCallback = { messageId in
self.messagesSent += 1
print("Published \(messageId)")
}
// Clean Session, subscribed topic is reset
if(mqttConfig.cleanSession == true) {
subscriptionTopic = ""
}
// setupTlsCerts()
mqttClient = MQTT.newConnection(mqttConfig)
disconnectTimestamp = nil
disconnectsInMinute = 0
return (mqttClient!.isConnected)
}
func disconnect() {
if(mqttClient != nil) {
mqttClient!.disconnect()
mqttClient = nil
connectTime = nil
subscriptionTopic = ""
subscriptionQos = 0
disconnectTimestamp = nil
disconnectsInMinute = 0
}
}
//
// Set up TLS certificate handling
// TODO: Needs work...
// Should set up a cert management window
// To get the code below working with test.mosquitto.org stick their cert
// in the certs bundle in this project...
// Note: May need to deal with export goo if this is enabled.
// func setupTlsCerts() {
// let bundleURL = NSURL(fileURLWithPath: Bundle(for: type(of: self)).path(forResource: "certs", ofType: "bundle")!)
// let certFile = bundleURL.appendingPathComponent("mosquitto.crt")?.path
// var bundlePath = Bundle(for: type(of: self)).bundlePath as NSString
// bundlePath = bundlePath.appendingPathComponent("cert.bundle") as NSString
// let certFile = bundlePath.appendingPathComponent("mosquitto.org.crt")
// mqttConfig.mqttTlsOpts = MQTTTlsOpts(tls_insecure: true, cert_reqs: .ssl_verify_none, tls_version: nil, ciphers: nil)
// mqttConfig.mqttServerCert = MQTTServerCert(cafile: certFile, capath: nil)
// }
//
// Insert new message into the message list
func handleNewMessage(message: MQTTMessage) -> Void {
messageQueue.async {
let my_message = MyMQTTMessage(message: message, timestamp: NSDate())
self.messagesReceived += 1
self.messageList.insert(my_message, at: 0)
// If we've exceeded our max list size, prune the end of the list
while(self.messageList.count > self.maxMessageList) {
self.messageList.removeLast()
}
self.newMessage = true
}
}
// Given a particular topic
func getMessageListForTopic(topic: String) -> [MyMQTTMessage] {
var messageListForTopic = [MyMQTTMessage]()
for messageItem in messageList {
if (messageItem.message.topic == topic) {
messageListForTopic.append(messageItem)
}
}
return messageListForTopic
}
func setConnectCallback(callback: ((Int, String) -> Void)?) {
mqttConfig.onConnectCallback = { (returnCode: ReturnCode) -> () in
print("Handling connect... \(returnCode.description)")
callback!(returnCode.rawValue, returnCode.description)
self.connectTime = NSDate()
/* Re-subscribe */
if (self.subscriptionTopic != "") {
self.subscribe(topic: self.subscriptionTopic, qos: self.subscriptionQos)
}
}
}
func setDisconnectCallback(callback: ((Int, String) -> Void)?) {
mqttConfig.onDisconnectCallback = { (reasonCode: ReasonCode) -> () in
print("Handling disconnect... \(reasonCode.description)")
// Throttle reconnect storms...
if (self.disconnectTimestamp == nil) {
self.disconnectTimestamp = Date()
self.disconnectsInMinute = 1
} else {
if (self.disconnectTimestamp! < Date(timeIntervalSinceNow: -60)) {
self.disconnectTimestamp = nil
self.disconnectsInMinute = 0
} else {
self.disconnectsInMinute += 1
if (self.disconnectsInMinute > self.maxDisconnectsInMinute) {
self.disconnect()
self.mqttClient = nil
}
}
}
callback!(reasonCode.rawValue, reasonCode.description)
}
}
func subscribe(topic: String, qos: Int32) {
subscriptionTopic = topic
subscriptionQos = qos
mqttClient!.subscribe(subscriptionTopic, qos: qos)
}
func unsubscribe() {
mqttClient!.unsubscribe(subscriptionTopic)
subscriptionTopic = ""
subscriptionQos = 0
}
func publish(topic: String, message: NSData, qos: Int32, retain: Bool) -> (Int, Int) {
let semaphore = DispatchSemaphore(value: 0)
print("Publishing!!!")
var mosqRet = -1
var msgId = -1
mqttClient?.publish(message as Data, topic: topic, qos: qos, retain: retain) { mosqReturn, messageId in
mosqRet = mosqReturn.rawValue
msgId = messageId
semaphore.signal()
}
semaphore.wait()
print("mosqRet = \(mosqRet), msgeId = \(msgId)")
return (mosqRet, msgId)
}
}
| 32.974026 | 128 | 0.588027 |
03b96c2510513713c22403e9c8ed2fd0450d9ae1 | 4,011 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
public class Page: PageSummary {
/** Entries of a page */
public var entries: [PageEntry]
/** A map of custom fields defined by a curator for a page. */
public var customFields: [String: Any]?
/** When the page represents the detail of an item this property will contain the item detail.
For clients consuming an item detail page, any page row entry of type `ItemDetailEntry`
should look to obtain its data from the contents of this property.
*Note that you have to be using feature flag `idp` to enable this
on item detail pages. See `feature-flags.md` for further details.*
*/
public var item: ItemDetail?
/** When the page represents the detail of a List this property will contain the list in question.
For clients consuming a list detail page, any page row entry of type `ListDetailEntry`
should look to obtain its data from the contents of this property.
*Note that you have to be using feature flag `ldp` to enable this
on list detail pages. See `feature-flags.md` for further details.*
*/
public var list: ItemList?
public var metadata: PageMetadata?
public init(id: String, path: String, title: String, template: String, isStatic: Bool, isSystemPage: Bool, entries: [PageEntry], key: String? = nil, customFields: [String: Any]? = nil, item: ItemDetail? = nil, list: ItemList? = nil, metadata: PageMetadata? = nil) {
self.entries = entries
self.customFields = customFields
self.item = item
self.list = list
self.metadata = metadata
super.init(id: id, path: path, title: title, template: template, isStatic: isStatic, isSystemPage: isSystemPage, key: key)
}
private enum CodingKeys: String, CodingKey {
case entries
case customFields
case item
case list
case metadata
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
entries = try container.decodeArray(.entries)
customFields = try container.decodeAnyIfPresent(.customFields)
item = try container.decodeIfPresent(.item)
list = try container.decodeIfPresent(.list)
metadata = try container.decodeIfPresent(.metadata)
try super.init(from: decoder)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(entries, forKey: .entries)
try container.encodeAnyIfPresent(customFields, forKey: .customFields)
try container.encodeIfPresent(item, forKey: .item)
try container.encodeIfPresent(list, forKey: .list)
try container.encodeIfPresent(metadata, forKey: .metadata)
try super.encode(to: encoder)
}
override public func isEqual(to object: Any?) -> Bool {
guard let object = object as? Page else { return false }
guard self.entries == object.entries else { return false }
guard NSDictionary(dictionary: self.customFields ?? [:]).isEqual(to: object.customFields ?? [:]) else { return false }
guard self.item == object.item else { return false }
guard self.list == object.list else { return false }
guard self.metadata == object.metadata else { return false }
return super.isEqual(to: object)
}
}
| 23.45614 | 269 | 0.589629 |