repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
petrmanek/revolver | Examples/ExampleCar/ExampleCar/NSBezierPath+toCGPath.swift | 1 | 1127 | import AppKit
// Courtesy of https://gist.github.com/jorgenisaksson/76a8dae54fd3dc4e31c2
extension NSBezierPath {
func toCGPath () -> CGPath? {
if self.elementCount == 0 {
return nil
}
let path = CGPathCreateMutable()
var didClosePath = false
for i in 0...self.elementCount-1 {
var points = [NSPoint](count: 3, repeatedValue: NSZeroPoint)
switch self.elementAtIndex(i, associatedPoints: &points) {
case .MoveToBezierPathElement:CGPathMoveToPoint(path, nil, points[0].x, points[0].y)
case .LineToBezierPathElement:CGPathAddLineToPoint(path, nil, points[0].x, points[0].y)
case .CurveToBezierPathElement:CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y)
case .ClosePathBezierPathElement:CGPathCloseSubpath(path)
didClosePath = true;
}
}
if !didClosePath {
CGPathCloseSubpath(path)
}
return CGPathCreateCopy(path)
}
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/22022-no-stacktrace.swift | 11 | 249 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
}
{
func b {
deinit {
class A {
class c {
deinit {
class
case c,
case
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/07551-swift-substitutedtype-get.swift | 11 | 244 | // 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
protocol A:CollectionType let a{
protocol A{typealias e:a
func a | mit |
radex/swift-compiler-crashes | crashes-duplicates/09403-swift-modulefile-maybereadgenericparams.swift | 11 | 253 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B {
deinit {
class d {
protocol a {
{
}
func a
protocol A : b
typealias b : A
| mit |
timsawtell/SwiftAppStarter | App/Model/Person.swift | 1 | 833 | //
// Person.swift
// SwiftAppStarter
//
// Created by Tim Sawtell on 29/09/2015.
// Copyright © 2015 Tim Sawtell. All rights reserved.
//
import Foundation
class Person: NSObject, NSSecureCoding {
var name: String?
var bookshelf = Bookshelf()
override init() {
}
init (name: String) {
self.name = name
}
@objc func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.name, forKey: "name")
aCoder.encodeObject(self.bookshelf, forKey: "bookshelf")
}
@objc required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObjectForKey("name") as? String
self.bookshelf = aDecoder.decodeObjectForKey("bookshelf") as! Bookshelf
}
@objc static func supportsSecureCoding() -> Bool {
return true
}
}
| mit |
ddaguro/clintonconcord | OIMApp/DashboardCell.swift | 1 | 1807 | //
// DashboardCell.swift
// OIMApp
//
// Created by Linh NGUYEN on 7/6/15.
// Copyright (c) 2015 Persistent Systems. All rights reserved.
//
import UIKit
class DashboardCell: UITableViewCell {
@IBOutlet var profileImage: UIImageView!
@IBOutlet var titleLabel : UILabel!
@IBOutlet var statusLabel: UILabel!
@IBOutlet var assigneeHeadingLabel: UILabel!
@IBOutlet var assigneeLabel: UILabel!
@IBOutlet var clockImage: UIImageView!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var descriptionLabel: UILabel!
//@IBOutlet var approverLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.font = UIFont(name: MegaTheme.fontName, size: 16)
titleLabel.textColor = UIColor.blackColor()
statusLabel.layer.cornerRadius = 8
statusLabel.layer.masksToBounds = true
statusLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
statusLabel.textColor = UIColor.whiteColor()
assigneeHeadingLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
assigneeHeadingLabel.textColor = MegaTheme.darkColor
assigneeLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
assigneeLabel.textColor = MegaTheme.lightColor
clockImage.image = UIImage(named: "clock")
clockImage.alpha = 0.20
dateLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
dateLabel.textColor = MegaTheme.lightColor
descriptionLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
descriptionLabel.textColor = MegaTheme.lightColor
//approverLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
//approverLabel.textColor = MegaTheme.lightColor
}
}
| mit |
STMicroelectronics-CentralLabs/BlueSTSDK_iOS | BlueSTSDK/BlueSTSDK/Util/BlueSTSDKBoardFeatureMap.swift | 1 | 7650 | /*******************************************************************************
* COPYRIGHT(c) 2019 STMicroelectronics
*
* 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 STMicroelectronics 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 Foundation
/**
* For each board type contains a map for of pair ( {@link featureMask_t},
* {@link BlueSTSDKFeature } class )
*/
internal struct BlueSTSDKBoardFeatureMap{
/**
* if the board doesn't have a specific device id the map returned by this feature will be used
*
* @return the default map used to convert the bit in the advertise mask into feature.
*/
static let defaultMaskToFeatureMap = [
//NSNumber(0x80000000:
NSNumber(0x40000000) : BlueSTSDKFeatureAudioADPCMSync.self,
NSNumber(0x20000000) : BlueSTSDKFeatureSwitch.self,
NSNumber(0x10000000) : BlueSTSDKFeatureDirectionOfArrival.self, //Sound source of arrival
NSNumber(0x08000000) : BlueSTSDKFeatureAudioADPCM.self,
NSNumber(0x04000000) : BlueSTSDKFeatureMicLevel.self, //Mic Level
NSNumber(0x02000000) : BlueSTSDKFeatureProximity.self, //proximity
NSNumber(0x01000000) : BlueSTSDKFeatureLuminosity.self, //luminosity
NSNumber(0x00800000) : BlueSTSDKFeatureAcceleration.self, //acc
NSNumber(0x00400000) : BlueSTSDKFeatureGyroscope.self, //gyo
NSNumber(0x00200000) : BlueSTSDKFeatureMagnetometer.self, //mag
NSNumber(0x00100000) : BlueSTSDKFeaturePressure.self, //pressure
NSNumber(0x00080000) : BlueSTSDKFeatureHumidity.self, //humidity
NSNumber(0x00040000) : BlueSTSDKFeatureTemperature.self, //temperature
NSNumber(0x00020000) : BlueSTSDKFeatureBattery.self,
NSNumber(0x00010000) : BlueSTSDKFeatureTemperature.self, //temperature
NSNumber(0x00008000) : BlueSTSDKFeatureCOSensor.self,
//NSNumber(0x00004000:
//NSNumber(0x00002000:
NSNumber(0x00001000) : BlueSTSDKFeatureSDLogging.self,
NSNumber(0x00000800) : BlueSTSDKFeatureBeamForming.self,
NSNumber(0x00000400) : BlueSTSDKFeatureAccelerometerEvent.self, //Free fall detection
NSNumber(0x00000200) : BlueSTSDKFeatureFreeFall.self, //Free fall detection
NSNumber(0x00000100) : BlueSTSDKFeatureMemsSensorFusionCompact.self, //Mems sensor fusion compact
NSNumber(0x00000080) : BlueSTSDKFeatureMemsSensorFusion.self, //Mems sensor fusion
NSNumber(0x00000040) : BlueSTSDKFeatureCompass.self,
NSNumber(0x00000020) : BlueSTSDKFeatureMotionIntensity.self,
NSNumber(0x00000010) : BlueSTSDKFeatureActivity.self, //Actvity
NSNumber(0x00000008) : BlueSTSDKFeatureCarryPosition.self, //carry position recognition
NSNumber(0x00000004) : BlueSTSDKFeatureProximityGesture.self, //Proximity Gesture
NSNumber(0x00000002) : BlueSTSDKFeatureMemsGesture.self, //mems Gesture
NSNumber(0x00000001) : BlueSTSDKFeaturePedometer.self, //Pedometer
];
private static let SENSOR_TILE_BOX_FEATURE_MASK = [
NSNumber(value: UInt32(0x80000000)) : BlueSTSDKFeatureFFTAmplitude.self,
NSNumber(0x40000000) : BlueSTSDKFeatureAudioADPCMSync.self,
NSNumber(0x20000000) : BlueSTSDKFeatureSwitch.self,
NSNumber(0x10000000) : BlueSTSDKFeatureMemsNorm.self,
NSNumber(0x08000000) : BlueSTSDKFeatureAudioADPCM.self,
NSNumber(0x04000000) : BlueSTSDKFeatureMicLevel.self, //Mic Level
NSNumber(0x02000000) : BlueSTSDKFeatureAudioCalssification.self, //audio scene classification
NSNumber(0x01000000) : BlueSTSDKFeatureLuminosity.self, //luminosity
NSNumber(0x00800000) : BlueSTSDKFeatureAcceleration.self, //acc
NSNumber(0x00400000) : BlueSTSDKFeatureGyroscope.self, //gyo
NSNumber(0x00200000) : BlueSTSDKFeatureMagnetometer.self, //mag
NSNumber(0x00100000) : BlueSTSDKFeaturePressure.self, //pressure
NSNumber(0x00080000) : BlueSTSDKFeatureHumidity.self, //humidity
NSNumber(0x00040000) : BlueSTSDKFeatureTemperature.self, //temperature
NSNumber(0x00020000) : BlueSTSDKFeatureBattery.self,
NSNumber(0x00010000) : BlueSTSDKFeatureTemperature.self, //temperature
// NSNumber(0x00008000) :
NSNumber(0x00004000) : BlueSTSDKFeatureEulerAngle.self,
//NSNumber(0x00002000:
NSNumber(0x00001000) : BlueSTSDKFeatureSDLogging.self,
// NSNumber(0x00000800) :
NSNumber(0x00000400) : BlueSTSDKFeatureAccelerometerEvent.self,
NSNumber(0x00000200) : BlueSTSDKFeatureEventCounter.self,
NSNumber(0x00000100) : BlueSTSDKFeatureMemsSensorFusionCompact.self, //Mems sensor fusion compact
NSNumber(0x00000080) : BlueSTSDKFeatureMemsSensorFusion.self, //Mems sensor fusion
NSNumber(0x00000040) : BlueSTSDKFeatureCompass.self,
NSNumber(0x00000020) : BlueSTSDKFeatureMotionIntensity.self,
NSNumber(0x00000010) : BlueSTSDKFeatureActivity.self, //Actvity
NSNumber(0x00000008) : BlueSTSDKFeatureCarryPosition.self, //carry position recognition
NSNumber(0x00000004) : BlueSTSDKFeatureProximityGesture.self, //Proximity Gesture
NSNumber(0x00000002) : BlueSTSDKFeatureMemsGesture.self, //mems Gesture
NSNumber(0x00000001) : BlueSTSDKFeaturePedometer.self, //Pedometer
];
private static let bleStarNucleoFeatureMap = [
NSNumber(0x20000000): BlueSTSDKRemoteFeatureSwitch.self,
NSNumber(0x00100000): BlueSTSDKRemoteFeaturePressure.self, //pressure
NSNumber(0x00080000): BlueSTSDKRemoteFeatureHumidity.self, //humidity
NSNumber(0x00040000): BlueSTSDKRemoteFeatureTemperature.self, //temperature
];
/**
* return a map of type <boardId, map<{@link featureMask_t}, {@link BlueSTSDKFeature }> >
* from this data you can understand what class will be manage a specific characteristics
*
* @return map needed for build a feature class that manage a specific characteristics
*/
static var boardFeatureMap = [
NSNumber(0x06): SENSOR_TILE_BOX_FEATURE_MASK,
NSNumber(0x81): bleStarNucleoFeatureMap
];
}
| bsd-3-clause |
shirai/SwiftLearning | iOSTraining/Subject5/Dandori/Dandori/Controller/DandoriListViewController/DandoriListViewController.swift | 1 | 2619 | //
// DandoriListViewController.swift
// Dandori
//
// Created by 白井 誠 on 2017/09/06.
// Copyright © 2017年 Sample. All rights reserved.
//
import UIKit
class DandoriListCell: UITableViewCell {
// MARK: - IBOutlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var checkButton: UIButton!
@IBOutlet weak var genderSegment: UISegmentedControl!
// MARK: - IBActions
@IBAction func didTappedCheckButton(_ sender: UIButton) {
}
@IBAction func didChangedGenderSegment(_ sender: UISegmentedControl) {
}
}
class DandoriListViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let indexPathForSelectedRow = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPathForSelectedRow, animated: true)
}
}
}
extension DandoriListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "分類Aのダンドリ 3"
case 1:
return "分類Bのダンドリ 10"
default:
return nil
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "dandoriCell", for: indexPath) as! DandoriListCell
switch indexPath.section {
case 0:
cell.titleLabel.text = "A-\(indexPath.row + 1)のダンドリ"
case 1:
cell.titleLabel.text = "B-\(indexPath.row + 1)のダンドリ"
default:
break
}
cell.dateLabel.text = "2017/09/1\(indexPath.row + 3)"
if indexPath.row > 1 {
cell.genderSegment.selectedSegmentIndex = 1
} else {
cell.checkButton.titleLabel?.text = "■"
}
return cell
}
}
extension DandoriListViewController: UITableViewDelegate {
}
| mit |
kickstarter/ios-oss | Library/DateFormatterTests.swift | 1 | 172 | @testable import Library
import XCTest
final class DateFormatterTests: XCTestCase {
func testMonthYear() {
XCTAssertEqual("MMMMyyyy", DateFormatter.monthYear)
}
}
| apache-2.0 |
whiteshadow-gr/HatForIOS | HAT/Objects/Data Offers/HATDataOfferClaim.swift | 1 | 2643 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
public struct HATDataOfferClaim: HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `claimStatus` in JSON is `status`
* `isClaimConfirmed` in JSON is `confirmed`
* `dateCreated` in JSON is `dateCreated`
* `dataDebitID` in JSON is `dataDebitId`
*/
private enum CodingKeys: String, CodingKey {
case claimStatus = "status"
case isClaimConfirmed = "confirmed"
case dateCreated = "dateCreated"
case dataDebitID = "dataDebitId"
}
// MARK: - Variables
/// The data offer claim status. Can be `confirmed`, `claimed` and `completed`
public var claimStatus: String = ""
/// A flag indicating if the claim was confirmed
public var isClaimConfirmed: Bool = false
/// The date that the offer has been claimed as a unix time stamp
public var dateCreated: Int = -1
/// The `Data Debit` id that the offer is attached to
public var dataDebitID: String = ""
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
claimStatus = ""
isClaimConfirmed = false
dateCreated = -1
dataDebitID = ""
}
/**
It initialises everything from the received JSON file from the HAT
- dictionary: The JSON file received
*/
public init(dictionary: Dictionary<String, JSON>) {
if let tempStatus: String = dictionary[HATDataOfferClaim.CodingKeys.claimStatus.rawValue]?.string {
claimStatus = tempStatus
}
if let tempConfirmed: Bool = dictionary[HATDataOfferClaim.CodingKeys.isClaimConfirmed.rawValue]?.bool {
isClaimConfirmed = tempConfirmed
}
if let tempDataDebitID: String = dictionary[HATDataOfferClaim.CodingKeys.dataDebitID.rawValue]?.string {
dataDebitID = tempDataDebitID
}
if let tempDateStamp: Int = dictionary[HATDataOfferClaim.CodingKeys.dateCreated.rawValue]?.int {
dateCreated = tempDateStamp
}
}
}
| mpl-2.0 |
xdliu002/TAC_communication | PodsDemo/PodsDemo/LeftMenuViewController.swift | 1 | 3237 | //
// LeftMenuViewController.swift
// PodsDemo
//
// Created by Harold LIU on 3/16/16.
// Copyright © 2016 Tongji Apple Club. All rights reserved.
//
import UIKit
import RESideMenu
class LeftMenuViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,RESideMenuDelegate{
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
let tableView = UITableView(frame: CGRect(x: 0, y: (view.frame.size.height - 54*5)/2.0, width: view.frame.size.width, height: 54*5), style: UITableViewStyle.Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.separatorStyle = .None
tableView.bounces = false
tableView.scrollsToTop = false
view.addSubview(tableView)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView .deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row
{
case 0:
sideMenuViewController.setContentViewController(UINavigationController(rootViewController: (storyboard?.instantiateViewControllerWithIdentifier("firstViewController"))!), animated: true)
sideMenuViewController.hideMenuViewController()
break;
case 1:
sideMenuViewController.setContentViewController(UINavigationController(rootViewController: (storyboard?.instantiateViewControllerWithIdentifier("secondViewController"))!), animated: true)
sideMenuViewController.hideMenuViewController()
break;
default:
break;
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("LeftCell")
if cell == nil
{
cell = UITableViewCell(style: .Default, reuseIdentifier: "LeftCell")
cell?.backgroundColor = UIColor.clearColor()
cell?.textLabel?.textColor = UIColor.whiteColor()
cell?.textLabel?.highlightedTextColor = UIColor.grayColor()
cell?.selectedBackgroundView = UIView()
}
let titles = ["Home", "Calendar", "Profile", "Settings", "Log Out"]
let images = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty"]
cell?.textLabel?.text = titles[indexPath.row]
cell?.imageView?.image = UIImage(named: images[indexPath.row])
return cell!
}
}
| mit |
wireapp/wire-ios-data-model | Tests/Source/Model/PermissionsTests.swift | 1 | 5775 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import WireTesting
@testable import WireDataModel
class PermissionsTests: BaseZMClientMessageTests {
private let allPermissions: Permissions = [
.createConversation,
.deleteConversation,
.addTeamMember,
.removeTeamMember,
.addRemoveConversationMember,
.modifyConversationMetaData,
.getMemberPermissions,
.getTeamConversations,
.getBilling,
.setBilling,
.setTeamData,
.deleteTeam,
.setMemberPermissions
]
func testThatDefaultValueDoesNotHaveAnyPermissions() {
// given
let sut = Permissions.none
// then
XCTAssertFalse(sut.contains(.createConversation))
XCTAssertFalse(sut.contains(.deleteConversation))
XCTAssertFalse(sut.contains(.addTeamMember))
XCTAssertFalse(sut.contains(.removeTeamMember))
XCTAssertFalse(sut.contains(.addRemoveConversationMember))
XCTAssertFalse(sut.contains(.modifyConversationMetaData))
XCTAssertFalse(sut.contains(.getMemberPermissions))
XCTAssertFalse(sut.contains(.getTeamConversations))
XCTAssertFalse(sut.contains(.getBilling))
XCTAssertFalse(sut.contains(.setBilling))
XCTAssertFalse(sut.contains(.setTeamData))
XCTAssertFalse(sut.contains(.deleteTeam))
XCTAssertFalse(sut.contains(.setMemberPermissions))
}
func testMemberPermissions() {
XCTAssertEqual(Permissions.member, [.createConversation, .deleteConversation, .addRemoveConversationMember, .modifyConversationMetaData, .getMemberPermissions, .getTeamConversations])
}
func testPartnerPermissions() {
// given
let permissions: Permissions = [
.createConversation,
.getTeamConversations
]
// then
XCTAssertEqual(Permissions.partner, permissions)
}
func testAdminPermissions() {
// given
let adminPermissions: Permissions = [
.createConversation,
.deleteConversation,
.addRemoveConversationMember,
.modifyConversationMetaData,
.getMemberPermissions,
.getTeamConversations,
.addTeamMember,
.removeTeamMember,
.setTeamData,
.setMemberPermissions
]
// then
XCTAssertEqual(Permissions.admin, adminPermissions)
}
func testOwnerPermissions() {
XCTAssertEqual(Permissions.owner, allPermissions)
}
// MARK: - Transport Data
func testThatItCreatesPermissionsFromPayload() {
XCTAssertEqual(Permissions(rawValue: 5), [.createConversation, .addTeamMember])
XCTAssertEqual(Permissions(rawValue: 0x401), .partner)
XCTAssertEqual(Permissions(rawValue: 1587), .member)
XCTAssertEqual(Permissions(rawValue: 5951), .admin)
XCTAssertEqual(Permissions(rawValue: 8191), .owner)
}
func testThatItCreatesEmptyPermissionsFromEmptyPayload() {
XCTAssertEqual(Permissions.none, [])
}
// MARK: - TeamRole (Objective-C Interoperability)
func testThatItCreatesTheCorrectSwiftPermissions() {
XCTAssertEqual(TeamRole.partner.permissions, .partner)
XCTAssertEqual(TeamRole.member.permissions, .member)
XCTAssertEqual(TeamRole.admin.permissions, .admin)
XCTAssertEqual(TeamRole.owner.permissions, .owner)
}
func testThatItSetsTeamRolePermissions() {
// given
let member = Member.insertNewObject(in: uiMOC)
// when
member.setTeamRole(.admin)
// then
XCTAssertEqual(member.permissions, .admin)
}
func testTeamRoleIsARelationships() {
XCTAssert(TeamRole.none.isA(role: .none))
XCTAssertFalse(TeamRole.none.isA(role: .partner))
XCTAssertFalse(TeamRole.none.isA(role: .member))
XCTAssertFalse(TeamRole.none.isA(role: .admin))
XCTAssertFalse(TeamRole.none.isA(role: .owner))
XCTAssert(TeamRole.partner.isA(role: .none))
XCTAssert(TeamRole.partner.isA(role: .partner))
XCTAssertFalse(TeamRole.partner.isA(role: .member))
XCTAssertFalse(TeamRole.partner.isA(role: .admin))
XCTAssertFalse(TeamRole.partner.isA(role: .owner))
XCTAssert(TeamRole.member.isA(role: .none))
XCTAssert(TeamRole.member.isA(role: .partner))
XCTAssert(TeamRole.member.isA(role: .member))
XCTAssertFalse(TeamRole.member.isA(role: .admin))
XCTAssertFalse(TeamRole.member.isA(role: .owner))
XCTAssert(TeamRole.admin.isA(role: .none))
XCTAssert(TeamRole.admin.isA(role: .partner))
XCTAssert(TeamRole.admin.isA(role: .member))
XCTAssert(TeamRole.admin.isA(role: .admin))
XCTAssertFalse(TeamRole.admin.isA(role: .owner))
XCTAssert(TeamRole.owner.isA(role: .none))
XCTAssert(TeamRole.owner.isA(role: .partner))
XCTAssert(TeamRole.owner.isA(role: .member))
XCTAssert(TeamRole.owner.isA(role: .admin))
XCTAssert(TeamRole.owner.isA(role: .owner))
}
}
| gpl-3.0 |
johnno1962/eidolon | Kiosk/Bid Fulfillment/StripeManager.swift | 1 | 1590 | import Foundation
import RxSwift
import Stripe
class StripeManager: NSObject {
var stripeClient = STPAPIClient.sharedClient()
func registerCard(digits: String, month: UInt, year: UInt, securityCode: String, postalCode: String) -> Observable<STPToken> {
let card = STPCard()
card.number = digits
card.expMonth = month
card.expYear = year
card.cvc = securityCode
card.addressZip = postalCode
return Observable.create { [weak self] observer in
guard let me = self else {
observer.onCompleted()
return NopDisposable.instance
}
me.stripeClient.createTokenWithCard(card) { (token, error) in
if (token as STPToken?).hasValue {
observer.onNext(token!)
observer.onCompleted()
} else {
observer.onError(error!)
}
}
return NopDisposable.instance
}
}
func stringIsCreditCard(cardNumber: String) -> Bool {
return STPCard.validateCardNumber(cardNumber)
}
}
extension STPCardBrand {
var name: String? {
switch self {
case .Visa:
return "Visa"
case .Amex:
return "American Express"
case .MasterCard:
return "MasterCard"
case .Discover:
return "Discover"
case .JCB:
return "JCB"
case .DinersClub:
return "Diners Club"
default:
return nil
}
}
}
| mit |
jiapan1984/swift-datastructures-algorithms | RingBuffer.swift | 1 | 1425 | // 一个简单的环形缓冲区数据结构
#if swift(>=4.0)
print("Hello, Swift 4!")
public struct RingBuffer<T> {
fileprivate var array:[T?]
fileprivate var readIndex = 0
fileprivate var writeIndex = 0
public init(_ count: Int) {
array = [T?](repeating:nil, count:count)
}
public mutating func write(_ element: T) -> Bool {
if isFull {
return false
} else {
array[writeIndex % array.count] = element
writeIndex += 1
return true
}
}
public mutating func read() -> T? {
if !isEmpty {
let elem = array[readIndex % array.count]
array[readIndex % array.count] = nil
readIndex += 1
return elem
} else {
return nil
}
}
public var isFull: Bool {
return (writeIndex - readIndex) == array.count
}
public var isEmpty: Bool {
return writeIndex == readIndex
}
}
var a = RingBuffer<Int>(5)
for i in 1...5 {
_ = a.write(i)
}
assert(a.write(6) == false)
assert(a.write(7) == false)
assert(a.read() == 1)
assert(a.read() == 2)
assert(a.write(7))
assert(a.write(8))
assert(a.read() == 3)
assert(a.read() == 4)
assert(a.write(9))
assert(a.write(10))
assert(a.read() == 5)
assert(a.read() == 7)
assert(a.read() == 8)
assert(a.read() == 9)
assert(a.read() == 10)
assert(a.read() == nil)
#endif
| mit |
Ezimetzhan/Tropos | UnitTests/Tests/PrecipitationSpec.swift | 2 | 1008 | import Foundation
import Quick
import Nimble
class PrecipitationSpec: QuickSpec {
override func spec() {
describe("Precipitation") {
context("precipitation chance") {
it("returns none for 0% chance of precipitation") {
let precipitation = Precipitation(probability: 0.0, type: "")
expect(precipitation.chance).to(equal(PrecipitationChance.None))
}
it("returns slight for 1 - 30% chance of precipitation") {
let precipitation = Precipitation(probability: 0.2, type: "")
expect(precipitation.chance).to(equal(PrecipitationChance.Slight))
}
it("returns good for chance greater than 30% of precipitation") {
let precipitation = Precipitation(probability: 0.7, type: "")
expect(precipitation.chance).to(equal(PrecipitationChance.Good))
}
}
}
}
}
| mit |
fluidsonic/JetPack | Sources/Measures/Measure.swift | 1 | 1961 | public protocol Measure: Comparable, CustomDebugStringConvertible, CustomStringConvertible, Hashable {
associatedtype UnitType: Unit
init(rawValue: Double)
init(_ value: Double, unit: UnitType)
static var name: String { get }
static var rawUnit: UnitType { get }
var rawValue: Double { get mutating set }
func valueInUnit(_ unit: UnitType) -> Double
}
public extension Measure { // CustomDebugStringConvertible
var debugDescription: String {
return "\(rawValue.description) \(Self.rawUnit.debugDescription)"
}
}
public extension Measure { // CustomStringConvertible
var description: String {
return "\(rawValue.description) \(Self.rawUnit.abbreviation)"
}
}
public extension Measure { // Hashable
func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
}
public prefix func + <M: Measure>(measure: M) -> M {
return measure
}
public prefix func - <M: Measure>(measure: M) -> M {
return M(rawValue: -measure.rawValue)
}
public func + <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue + b.rawValue)
}
public func += <M: Measure>(a: inout M, b: M) {
a.rawValue += b.rawValue
}
public func - <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue - b.rawValue)
}
public func -= <M: Measure>(a: inout M, b: M) {
a.rawValue -= b.rawValue
}
public func * <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue * b.rawValue)
}
public func *= <M: Measure>(a: inout M, b: M) {
a.rawValue *= b.rawValue
}
public func / <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue / b.rawValue)
}
public func /= <M: Measure>(a: inout M, b: M) {
a.rawValue /= b.rawValue
}
public func % <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue.truncatingRemainder(dividingBy: b.rawValue))
}
public func == <M: Measure>(a: M, b: M) -> Bool {
return (a.rawValue == b.rawValue)
}
public func < <M: Measure>(a: M, b: M) -> Bool {
return (a.rawValue < b.rawValue)
}
| mit |
yoonapps/swift-corelibs-xctest | Tests/Functional/Asynchronous/Misuse/main.swift | 1 | 4258 | // RUN: %{swiftc} %s -o %{built_tests_dir}/Misuse
// RUN: %{built_tests_dir}/Misuse > %t || true
// RUN: %{xctest_checker} %t %s
#if os(Linux) || os(FreeBSD)
import XCTest
#else
import SwiftXCTest
#endif
// CHECK: Test Suite 'All tests' started at \d+:\d+:\d+\.\d+
// CHECK: Test Suite '.*\.xctest' started at \d+:\d+:\d+\.\d+
// CHECK: Test Suite 'MisuseTestCase' started at \d+:\d+:\d+\.\d+
class MisuseTestCase: XCTestCase {
// CHECK: Test Case 'MisuseTestCase.test_whenExpectationsAreMade_butNotWaitedFor_fails' started at \d+:\d+:\d+\.\d+
// CHECK: .*/Tests/Functional/Asynchronous/Misuse/main.swift:21: error: MisuseTestCase.test_whenExpectationsAreMade_butNotWaitedFor_fails : Failed due to unwaited expectations.
// CHECK: Test Case 'MisuseTestCase.test_whenExpectationsAreMade_butNotWaitedFor_fails' failed \(\d+\.\d+ seconds\).
func test_whenExpectationsAreMade_butNotWaitedFor_fails() {
self.expectation(withDescription: "the first expectation")
self.expectation(withDescription: "the second expectation (the file and line number for this one are included in the failure message")
}
// CHECK: Test Case 'MisuseTestCase.test_whenNoExpectationsAreMade_butTheyAreWaitedFor_fails' started at \d+:\d+:\d+\.\d+
// CHECK: .*/Tests/Functional/Asynchronous/Misuse/main.swift:28: error: MisuseTestCase.test_whenNoExpectationsAreMade_butTheyAreWaitedFor_fails : API violation - call made to wait without any expectations having been set.
// CHECK: Test Case 'MisuseTestCase.test_whenNoExpectationsAreMade_butTheyAreWaitedFor_fails' failed \(\d+\.\d+ seconds\).
func test_whenNoExpectationsAreMade_butTheyAreWaitedFor_fails() {
self.waitForExpectations(withTimeout: 0.1)
}
// CHECK: Test Case 'MisuseTestCase.test_whenExpectationIsFulfilledMultipleTimes_fails' started at \d+:\d+:\d+\.\d+
// CHECK: .*/Tests/Functional/Asynchronous/Misuse/main.swift:38: error: MisuseTestCase.test_whenExpectationIsFulfilledMultipleTimes_fails : API violation - multiple calls made to XCTestExpectation.fulfill\(\) for rob.
// CHECK: .*/Tests/Functional/Asynchronous/Misuse/main.swift:48: error: MisuseTestCase.test_whenExpectationIsFulfilledMultipleTimes_fails : API violation - multiple calls made to XCTestExpectation.fulfill\(\) for rob.
// CHECK: Test Case 'MisuseTestCase.test_whenExpectationIsFulfilledMultipleTimes_fails' failed \(\d+\.\d+ seconds\).
func test_whenExpectationIsFulfilledMultipleTimes_fails() {
let expectation = self.expectation(withDescription: "rob")
expectation.fulfill()
expectation.fulfill()
// FIXME: The behavior here is subtly different from Objective-C XCTest.
// Objective-C XCTest would stop executing the test on the line
// above, and so would not report a failure for this line below.
// In total, it would highlight one line as a failure in this
// test.
//
// swift-corelibs-xctest continues to execute the test, and so
// highlights both the lines above and below as failures.
// This should be fixed such that the behavior is identical.
expectation.fulfill()
self.waitForExpectations(withTimeout: 0.1)
}
static var allTests: [(String, MisuseTestCase -> () throws -> Void)] {
return [
("test_whenExpectationsAreMade_butNotWaitedFor_fails", test_whenExpectationsAreMade_butNotWaitedFor_fails),
("test_whenNoExpectationsAreMade_butTheyAreWaitedFor_fails", test_whenNoExpectationsAreMade_butTheyAreWaitedFor_fails),
("test_whenExpectationIsFulfilledMultipleTimes_fails", test_whenExpectationIsFulfilledMultipleTimes_fails),
]
}
}
// CHECK: Test Suite 'MisuseTestCase' failed at \d+:\d+:\d+\.\d+
// CHECK: \t Executed 3 tests, with 4 failures \(4 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds
XCTMain([testCase(MisuseTestCase.allTests)])
// CHECK: Test Suite '.*\.xctest' failed at \d+:\d+:\d+\.\d+
// CHECK: \t Executed 3 tests, with 4 failures \(4 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds
// CHECK: Test Suite 'All tests' failed at \d+:\d+:\d+\.\d+
// CHECK: \t Executed 3 tests, with 4 failures \(4 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds
| apache-2.0 |
gb-6k-house/YsSwift | Sources/Peacock/UIKit/YSPopView/YSBubbleView.swift | 1 | 20359 | /******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: 说明
** Copyright © 2017年 尧尚信息科技(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import SnapKit
enum YSBubbleDiretcion: Int {
case top
case left
case bottom
case right
case topLeft
case topRight
case leftTop
case leftBottom
case bottomLeft
case bottomRight
case rightTop
case rightBottom
case automatic
}
open class YSBubbleView: YSPopupView {
fileprivate(set) var cellAction: [YSActionItem] = [YSActionItem]()
let tableView = UITableView()
fileprivate let arrowView = UIImageView()
fileprivate var anchorView = UIView()
fileprivate var anchorDirection = YSBubbleDiretcion.automatic
fileprivate var popWidth: CGFloat = 0
fileprivate override init(frame: CGRect = CGRect.zero) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init(anchorView: UIView, titles: [String], anchorDirection: YSBubbleDiretcion = .automatic, action: @escaping ((_ index: Int) -> Void), width: CGFloat) {
var actions: [YSActionItem] = [YSActionItem]()
for title in titles {
let action = YSActionItem(title: title, action: action)
actions.append(action)
}
self.init(anchorView: anchorView, anchorDirection: anchorDirection, cellAction: actions, width: width)
}
convenience init(anchorView: UIView, titles: [String], anchorDirection: YSBubbleDiretcion = .automatic, action: @escaping ((_ index: Int) -> Void)) {
var actions: [YSActionItem] = [YSActionItem]()
for title in titles {
let action = YSActionItem(title: title, action: action)
actions.append(action)
}
self.init(anchorView: anchorView, anchorDirection: anchorDirection, cellAction: actions, width: YSBubbleViewConfig.width)
}
convenience init(anchorView: UIView, anchorDirection: YSBubbleDiretcion = .automatic, cellAction: [YSActionItem]) {
self.init(anchorView: anchorView, anchorDirection: anchorDirection, cellAction: cellAction, width: YSBubbleViewConfig.width)
}
convenience init(anchorView: UIView, anchorDirection: YSBubbleDiretcion = .automatic, cellAction: [YSActionItem], width: CGFloat) {
self.init(frame: CGRect.zero)
self.anchorView = anchorView
self.cellAction = cellAction
self.anchorDirection = anchorDirection
self.popWidth = width
if self.anchorDirection == .automatic {
self.anchorDirection = self.getAnchorDirection(self.anchorView)
}
self.buildUI()
}
fileprivate func buildUI() {
assert(self.cellAction.count > 0, "Need at least 1 action")
self.targetView = YSBubbleWindow
typealias Config = YSBubbleViewConfig
self.type = .custom
self.snp.makeConstraints { (make) in
make.width.equalTo(self.popWidth)
}
self.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical)
self.setContentHuggingPriority(UILayoutPriority.fittingSizeLevel, for: .horizontal)
({ (view: UIImageView) in
view.contentMode = .center
view.image = UIImage.YS_rhombusWithSize(CGSize(width: Config.arrowWidth + Config.cornerRadius, height: Config.arrowWidth + Config.cornerRadius), color: Config.cellBackgroundNormalColor)
self.addSubview(view)
}(self.arrowView))
({ (view: UITableView) in
view.delegate = self
view.dataSource = self
view.separatorStyle = .none
view.register(YSBubbleViewCell.self, forCellReuseIdentifier: "YSBubbleViewCell")
view.isScrollEnabled = self.cellAction.count > Config.maxNumberOfItems
view.canCancelContentTouches = false
view.delaysContentTouches = false
view.backgroundColor = Config.cellBackgroundNormalColor
view.layer.cornerRadius = Config.cornerRadius
view.layer.masksToBounds = true
view.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.0000001))
self.addSubview(view)
}(self.tableView))
self.tableView.snp.makeConstraints { (make) in
make.top.leading.bottom.trailing.equalTo(self).inset(UIEdgeInsets(top: Config.arrowWidth, left: Config.arrowWidth, bottom: Config.arrowWidth, right: Config.arrowWidth))
let count = CGFloat(min(CGFloat(Config.maxNumberOfItems) + 0.5, CGFloat(self.cellAction.count)))
make.height.equalTo(Config.cellHeight * count).priority(750)
}
self.layoutIfNeeded()
}
fileprivate func getAnchorWindow(_ anchorView: UIView) -> UIWindow {
var sv = anchorView.superview
while sv != nil {
if sv!.isKind(of: UIWindow.self) {
break
}
sv = sv!.superview
}
assert(sv != nil, "fatal: anchorView should be on some window")
let window = sv as! UIWindow
return window
}
fileprivate func getAnchorPosition(_ anchorView: UIView) -> CGPoint {
let window = self.getAnchorWindow(anchorView)
let center = CGPoint(x: anchorView.frame.width / 2.0, y: anchorView.frame.height / 2.0)
return anchorView.convert(center, to: window)
}
fileprivate func getAnchorDirection(_ anchorView: UIView) -> YSBubbleDiretcion {
let position = self.getAnchorPosition(anchorView)
let xRatio: CGFloat = position.x / UIScreen.main.bounds.width
let yRatio: CGFloat = position.y / UIScreen.main.bounds.height
switch (xRatio, yRatio) {
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(0.0 / 6.0)..<CGFloat(1.0 / 6.0)):
return .topLeft
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(0.0 / 6.0)..<CGFloat(1.0 / 6.0)):
return .topRight
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(1.0 / 6.0)..<CGFloat(2.0 / 6.0)):
return .leftTop
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(1.0 / 6.0)..<CGFloat(2.0 / 6.0)):
return .rightTop
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(2.0 / 6.0)..<CGFloat(4.0 / 6.0)):
return .left
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(2.0 / 6.0)..<CGFloat(4.0 / 6.0)):
return .right
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(4.0 / 6.0)..<CGFloat(5.0 / 6.0)):
return .leftBottom
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(4.0 / 6.0)..<CGFloat(5.0 / 6.0)):
return .rightBottom
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(5.0 / 6.0)...CGFloat(6.0 / 6.0)):
return .bottomLeft
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(5.0 / 6.0)...CGFloat(6.0 / 6.0)):
return .bottomRight
case (CGFloat(1.0 / 3.0)...CGFloat(2.0 / 3.0),
CGFloat(0.0 / 6.0)..<CGFloat(4.0 / 6.0)):
return .top
case (CGFloat(1.0 / 3.0)...CGFloat(2.0 / 3.0),
CGFloat(4.0 / 6.0)...CGFloat(6.0 / 6.0)):
return .bottom
default:
print("warning: anchorView is out of screen")
return .top
}
}
override func showAnimation(completion closure: ((_ popupView: YSPopupView, _ finished: Bool) -> Void)?) {
if self.superview == nil {
self.targetView!.YS_dimBackgroundView.addSubview(self)
self.targetView!.YS_dimBackgroundView.layoutIfNeeded()
self.targetView!.YS_dimBackgroundAnimatingDuration = 0.15
self.duration = self.targetView!.YS_dimBackgroundAnimatingDuration
}
typealias Config = YSBubbleViewConfig
let center = self.getAnchorPosition(self.anchorView)
let widthOffset = self.anchorView.frame.size.width / 2.0
let heightOffset = self.anchorView.frame.size.height / 2.0
let arrowOffset = Config.arrowWidth * 2 + Config.cornerRadius
let xOffsetRatio = arrowOffset / self.frame.width
let yOffsetRatio = arrowOffset / self.frame.height
switch self.anchorDirection {
case .topLeft:
self.layer.anchorPoint = CGPoint(x: xOffsetRatio, y: 0.0)
self.layer.position = CGPoint(x: center.x, y: center.y + heightOffset)
case .leftTop:
self.layer.anchorPoint = CGPoint(x: 0.0, y: yOffsetRatio)
self.layer.position = CGPoint(x: center.x + widthOffset, y: center.y)
case .topRight:
self.layer.anchorPoint = CGPoint(x: 1.0 - xOffsetRatio, y: 0.0)
self.layer.position = CGPoint(x: center.x, y: center.y + heightOffset)
case .rightTop:
self.layer.anchorPoint = CGPoint(x: 1.0, y: yOffsetRatio)
self.layer.position = CGPoint(x: center.x - widthOffset, y: center.y)
case .bottomLeft:
self.layer.anchorPoint = CGPoint(x: xOffsetRatio, y: 1.0)
self.layer.position = CGPoint(x: center.x, y: center.y - heightOffset)
case .leftBottom:
self.layer.anchorPoint = CGPoint(x: 0.0, y: 1.0 - yOffsetRatio)
self.layer.position = CGPoint(x: center.x + widthOffset, y: center.y)
case .bottomRight:
self.layer.anchorPoint = CGPoint(x: 1.0 - xOffsetRatio, y: 1.0)
self.layer.position = CGPoint(x: center.x, y: center.y - heightOffset)
case .rightBottom:
self.layer.anchorPoint = CGPoint(x: 1.0, y: 1.0 - yOffsetRatio)
self.layer.position = CGPoint(x: center.x - widthOffset, y: center.y)
case .top:
self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0)
self.layer.position = CGPoint(x: center.x, y: center.y + heightOffset)
case .bottom:
self.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0)
self.layer.position = CGPoint(x: center.x, y: center.y - heightOffset)
case .left:
self.layer.anchorPoint = CGPoint(x: 0.0, y: 0.5)
self.layer.position = CGPoint(x: center.x + widthOffset, y: center.y)
case .right:
self.layer.anchorPoint = CGPoint(x: 1.0, y: 0.5)
self.layer.position = CGPoint(x: center.x - widthOffset, y: center.y)
default:
break
}
self.arrowView.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 2.0 * (Config.arrowWidth + Config.cornerRadius), height: 2.0 * (Config.arrowWidth + Config.cornerRadius)))
switch self.anchorDirection {
case .topLeft:
make.centerY.equalTo(self.tableView.snp.top)
make.left.equalTo(self.tableView.snp.left)
case .leftTop:
make.centerX.equalTo(self.tableView.snp.left)
make.top.equalTo(self.tableView.snp.top)
case .topRight:
make.centerY.equalTo(self.tableView.snp.top)
make.right.equalTo(self.tableView.snp.right)
case .rightTop:
make.centerX.equalTo(self.tableView.snp.right)
make.top.equalTo(self.tableView.snp.top)
case .bottomLeft:
make.centerY.equalTo(self.tableView.snp.bottom)
make.left.equalTo(self.tableView.snp.left)
case .leftBottom:
make.centerX.equalTo(self.tableView.snp.left)
make.bottom.equalTo(self.tableView.snp.bottom)
case .bottomRight:
make.centerY.equalTo(self.tableView.snp.bottom)
make.right.equalTo(self.tableView.snp.right)
case .rightBottom:
make.centerX.equalTo(self.tableView.snp.right)
make.bottom.equalTo(self.tableView.snp.bottom)
case .top:
make.centerY.equalTo(self.tableView.snp.top)
make.centerX.equalTo(self.tableView.snp.centerX)
case .bottom:
make.centerY.equalTo(self.tableView.snp.bottom)
make.centerX.equalTo(self.tableView.snp.centerX)
case .left:
make.centerY.equalTo(self.tableView.snp.centerY)
make.centerX.equalTo(self.tableView.snp.left)
case .right:
make.centerY.equalTo(self.tableView.snp.centerY)
make.centerX.equalTo(self.tableView.snp.right)
default:
break
}
}
self.layer.transform = CATransform3DMakeScale(0.01, 0.01, 1.0)
UIView.animate(
withDuration: self.duration,
delay: 0.0,
options: [
UIViewAnimationOptions.curveEaseOut,
UIViewAnimationOptions.beginFromCurrentState
],
animations: {
self.layer.transform = CATransform3DIdentity
},
completion: { (finished: Bool) in
if let completionClosure = closure {
completionClosure(self, finished)
}
})
}
override func hideAnimation(completion closure: ((_ popupView: YSPopupView, _ finished: Bool) -> Void)?) {
UIView.animate(
withDuration: self.duration,
delay: 0.0,
options: [
UIViewAnimationOptions.curveEaseIn,
UIViewAnimationOptions.beginFromCurrentState
],
animations: {
self.layer.transform = CATransform3DMakeScale(0.01, 0.01, 1.0)
},
completion: { (finished: Bool) in
if finished {
self.removeFromSuperview()
}
if let completionClosure = closure {
completionClosure(self, finished)
}
})
}
}
extension YSBubbleView: UITableViewDelegate, UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cellAction.count
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return YSBubbleViewConfig.cellHeight
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "YSBubbleViewCell", for: indexPath) as! YSBubbleViewCell
let item = self.cellAction[indexPath.row]
cell.titleLabel.text = item.title
cell.showIcon = item.image != nil
cell.iconView.image = item.image
cell.split.isHidden = indexPath.row == self.cellAction.count - 1
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.cellAction[indexPath.row]
self.hide()
if let action = item.action {
action(indexPath.row)
}
}
}
private extension UIImage {
static func YS_rhombusWithSize(_ size: CGSize, color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
let path = UIBezierPath()
path.move(to: CGPoint(x: size.width / 2.0, y: 0.0))
path.addLine(to: CGPoint(x: size.width, y: size.height / 2.0))
path.addLine(to: CGPoint(x: size.width / 2.0, y: size.height))
path.addLine(to: CGPoint(x: 0, y: size.height / 2.0))
path.addLine(to: CGPoint(x: size.width / 2.0, y: 0.0))
path.close()
path.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
private class YSBubbleViewCell: UITableViewCell {
var showIcon = false {
didSet {
self.iconView.isHidden = !showIcon
self.titleLabel.snp.updateConstraints { (make) in
make.leading.equalTo(self.iconView.snp.trailing).offset(self.showIcon ? YSBubbleViewConfig.innerPadding : -YSBubbleViewConfig.iconSize.width)
}
}
}
let iconView = UIImageView()
let titleLabel = UILabel()
let split = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
typealias Config = YSBubbleViewConfig
self.selectionStyle = .none
self.contentView.backgroundColor = Config.cellBackgroundNormalColor
({ (view: UIImageView) in
self.contentView.addSubview(view)
}(self.iconView))
({ (view: UILabel) in
view.textColor = Config.cellTitleColor
view.font = Config.cellTitleFont
view.textAlignment = Config.cellTitleAlignment
view.adjustsFontSizeToFitWidth = true
self.contentView.addSubview(view)
}(self.titleLabel))
({ (view: UIView) in
view.backgroundColor = Config.cellSplitColor
self.contentView.addSubview(view)
}(self.split))
self.iconView.snp.makeConstraints { (make) in
make.centerY.equalTo(self.contentView)
make.leading.equalTo(self.contentView.snp.leading).offset(Config.innerPadding)
make.size.equalTo(Config.iconSize)
}
self.titleLabel.snp.makeConstraints { (make) in
make.leading.equalTo(self.iconView.snp.trailing).offset(self.showIcon ? Config.innerPadding : -Config.iconSize.width)
make.top.bottom.trailing.equalTo(self.contentView).inset(UIEdgeInsets(top: 0, left: Config.innerPadding, bottom: 0, right: Config.innerPadding))
}
self.split.snp.makeConstraints { (make) in
make.leading.bottom.trailing.equalTo(self.contentView)
make.height.equalTo(Config.splitWidth)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.contentView.backgroundColor = YSBubbleViewConfig.cellBackgroundHighlightedColor
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
self.contentView.backgroundColor = YSBubbleViewConfig.cellBackgroundNormalColor
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
self.contentView.backgroundColor = YSBubbleViewConfig.cellBackgroundNormalColor
}
}
public struct YSBubbleViewConfig {
static var maxNumberOfItems = 5
static var width: CGFloat = 120.0
static var cornerRadius: CGFloat = 5.0
static var cellHeight: CGFloat = 50.0
static var innerPadding: CGFloat = 10.0
static var splitWidth: CGFloat = 1.0 / UIScreen.main.scale
static var iconSize: CGSize = CGSize(width: 25, height: 25)
static var arrowWidth: CGFloat = 10.0
static var cellTitleAlignment: NSTextAlignment = .left
static var cellTitleFont: UIFont = UIFont.systemFont(ofSize: 14)
static var cellTitleColor: UIColor = UIColor.YS_hexColor(0x333333FF)
static var cellSplitColor: UIColor = UIColor.YS_hexColor(0xCCCCCCFF)
static var cellBackgroundNormalColor: UIColor = UIColor.YS_hexColor(0xFFFFFFFF)
static var cellBackgroundHighlightedColor: UIColor = UIColor.YS_hexColor(0xCCCCCCFF)
static var cellImageColor: UIColor = UIColor.YS_hexColor(0xFFFFFFFF)
}
| mit |
coaoac/GridView | CustomGridView/GridViewController.swift | 1 | 2151 | // Created by Amine Chaouki on 10/05/15.
// Copyright (c) 2015 chaouki. All rights reserved.
//
import UIKit
//Section = row, item = column
public class GridViewController: UICollectionViewController {
// let titleCellIdentifier = "TitleCellIdentifier"
// let contentCellIdentifier = "ContentCellIdentifier"
public var dataSource: GridViewLayoutDataSource!
//@IBOutlet weak var layout: GridViewLayout!
weak var layout: GridViewLayout!
public override func viewDidLoad() {
super.viewDidLoad()
layout = collectionViewLayout as! GridViewLayout
layout.dataSource = dataSource
}
// MARK - UICollectionViewDataSource
public override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return dataSource.numberOfRows() + dataSource.numberOfColumnTitles()
}
public override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.numberOfColumns() + dataSource.numberOfRowTitles()
}
public override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let row = indexPath.section
let column = indexPath.item
switch (row, column) {
case (0..<dataSource.numberOfColumnTitles(), 0..<dataSource.numberOfRowTitles()):
return dataSource.cornerCellForIndexPath(indexPath, cornerColumnIndex: column, cornerRowIndex: row)
case (_, 0..<dataSource.numberOfRowTitles()):
return dataSource.rowTitleCellForIndexPath(indexPath, rowtitleCellIndex: column, rowIndex: row - dataSource.numberOfColumnTitles())
case (0..<dataSource.numberOfColumnTitles(), _):
return dataSource.columnTitleCellForIndexPath(indexPath, columnTitleCellIndex: row, columnIndex: column - dataSource.numberOfRowTitles())
default:
return dataSource.contentCellForIndexPath(indexPath, columnIndex: column - dataSource.numberOfRowTitles(), rowIndex: row - dataSource.numberOfColumnTitles())
}
}
}
| mit |
jtsmrd/Intrview | ViewControllers/BusinessProfileInfoEditVC.swift | 1 | 7039 | //
// BusinessProfileInfoEditVC.swift
// SnapInterview
//
// Created by JT Smrdel on 1/16/17.
// Copyright © 2017 SmrdelJT. All rights reserved.
//
import UIKit
class BusinessProfileInfoEditVC: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var profileImageView: ProfileImageView!
@IBOutlet weak var addReplaceImageButton: UIButton!
@IBOutlet weak var companyNameTextField: UITextField!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var contactEmailTextField: UITextField!
@IBOutlet weak var websiteTextField: UITextField!
@IBOutlet weak var scrollView: UIScrollView!
let imageStore = ImageStore()
var profile = (UIApplication.shared.delegate as! AppDelegate).profile
var currentFirstResponder: UIView!
var navToolBar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
let saveBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveButtonAction))
saveBarButtonItem.tintColor = UIColor.white
navigationItem.rightBarButtonItem = saveBarButtonItem
let backBarButtonItem = UIBarButtonItem(image: UIImage(named: "left_icon"), style: .plain, target: self, action: #selector(backButtonAction))
backBarButtonItem.tintColor = UIColor.white
navigationItem.leftBarButtonItem = backBarButtonItem
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
navToolBar = createKeyboardToolBar()
configureView()
}
@objc func saveButtonAction() {
profile.businessProfile?.name = companyNameTextField.text
profile.businessProfile?.location = locationTextField.text
profile.businessProfile?.contactEmail = contactEmailTextField.text
profile.businessProfile?.website = websiteTextField.text
profile.save()
let _ = navigationController?.popViewController(animated: true)
}
@objc func backButtonAction() {
let _ = navigationController?.popViewController(animated: true)
}
@IBAction func addReplaceImageButtonAction(_ sender: Any) {
addProfileImage()
}
private func configureView() {
self.companyNameTextField.text = profile.businessProfile?.name
self.locationTextField.text = profile.businessProfile?.location
self.contactEmailTextField.text = profile.businessProfile?.contactEmail
self.websiteTextField.text = profile.businessProfile?.website
if let image = profile.businessProfile?.profileImage {
profileImageView.image = image
addReplaceImageButton.setTitle("Replace Image", for: .normal)
}
else {
profileImageView.image = UIImage(named: "default_profile_image")
addReplaceImageButton.setTitle("Add Image", for: .normal)
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
currentFirstResponder = textField
textField.inputAccessoryView = navToolBar
}
@objc func keyboardWillShow(notification: NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardHeight = keyboardFrame.cgRectValue.height
let currentTextFieldOrigin = currentFirstResponder.frame.origin
let currentTextFieldHeight = currentFirstResponder.frame.size.height
var visibleRect = view.frame
visibleRect.size.height -= keyboardHeight
let scrollPoint = CGPoint(x: 0.0, y: currentTextFieldOrigin.y - visibleRect.size.height + (currentTextFieldHeight * 3))
scrollView.setContentOffset(scrollPoint, animated: true)
}
@objc func keyboardWillHide(notification: NSNotification) {
scrollView.setContentOffset(CGPoint.zero, animated: true)
}
// MARK: - ImageView Delegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageKey = UUID().uuidString
profileImageView.image = image
imageStore.setImage(image, forKey: imageKey)
profile.businessProfile?.profileImage = image
profile.businessProfile?.saveImage(tempImageKey: imageKey)
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func addProfileImage() {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
// MARK: - Keyboard toolbar
@objc func doneAction() {
if currentFirstResponder != nil {
currentFirstResponder.resignFirstResponder()
}
}
@objc func previousAction() {
if let previousField = currentFirstResponder.superview!.viewWithTag(currentFirstResponder.tag - 100) {
previousField.becomeFirstResponder()
}
}
@objc func nextAction() {
if let nextField = currentFirstResponder.superview!.viewWithTag(currentFirstResponder.tag + 100) {
nextField.becomeFirstResponder()
}
}
fileprivate func createKeyboardToolBar() -> UIToolbar {
let keyboardToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
keyboardToolBar.barStyle = .default
let previous = UIBarButtonItem(image: UIImage(named: "left_icon"), style: .plain, target: self, action: #selector(previousAction))
previous.width = 50
previous.tintColor = Global.greenColor
let next = UIBarButtonItem(image: UIImage(named: "right_icon"), style: .plain, target: self, action: #selector(nextAction))
next.width = 50
next.tintColor = Global.greenColor
let done = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneAction))
done.tintColor = Global.greenColor
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
keyboardToolBar.items = [previous, next, flexSpace, done]
keyboardToolBar.sizeToFit()
return keyboardToolBar
}
}
| mit |
knutigro/AppReviews | AppReviews/ReviewPieChartController.swift | 1 | 1776 | //
// PieChart.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-05-04.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import AppKit
class ReviewPieChartController: NSViewController {
@IBOutlet weak var pieChart: PieChart?
var slices = [Float]()
var sliceColors: [NSColor]!
override func viewDidLoad() {
super.viewDidLoad()
sliceColors = [NSColor.reviewRed(), NSColor.reviewOrange(), NSColor.reviewYellow(), NSColor.reviewGreen(), NSColor.reviewBlue()]
if let pieChart = pieChart {
pieChart.dataSource = self
pieChart.delegate = self
pieChart.pieCenter = CGPointMake(240, 240)
pieChart.showPercentage = false
}
}
}
extension ReviewPieChartController: PieChartDataSource {
func numberOfSlicesInPieChart(pieChart: PieChart!) -> UInt {
return UInt(slices.count)
}
func pieChart(pieChart: PieChart!, valueForSliceAtIndex index: UInt) -> CGFloat {
return CGFloat(slices[Int(index)])
}
func pieChart(pieChart: PieChart!, colorForSliceAtIndex index: UInt) -> NSColor! {
return sliceColors[Int(index) % sliceColors.count]
}
func pieChart(pieChart: PieChart!, textForSliceAtIndex index: UInt) -> String! {
return (NSString(format: NSLocalizedString("%i Stars", comment: "review.slice.tooltip"), index + 1) as String)
}
}
extension ReviewPieChartController: PieChartDelegate {
func pieChart(pieChart: PieChart!, toopTipStringAtIndex index: UInt) -> String! {
let number = slices[Int(index)]
return (NSString(format: NSLocalizedString("Number of ratings: ", comment: "review.slice.tooltip"), number) as String)
}
}
| gpl-3.0 |
OHeroJ/twicebook | Sources/App/Models/UserToken.swift | 1 | 1189 | //
// UserToken.swift
// seesometop
//
// Created by laijihua on 29/08/2017.
//
//
import Foundation
import Vapor
import FluentProvider
final class UserToken: Model {
var token: String
var userId: Identifier
let storage: Storage = Storage()
struct Key {
static let token = "token"
static let userId = "user_id"
}
var user: Parent<UserToken, User> {
return parent(id: userId)
}
init(token: String, userId: Identifier) {
self.token = token
self.userId = userId
}
init(row: Row) throws {
token = try row.get(Key.token)
userId = try row.get(Key.userId)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Key.token, token)
try row.set(Key.userId, userId)
return row
}
}
extension UserToken: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { (builder) in
builder.id()
builder.string(Key.token)
builder.parent(User.self)
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
| mit |
Pyroh/Fluor | Fluor/Models/Enums.swift | 1 | 4282 | //
// Enums.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// 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 DefaultsWrapper
@objc enum FKeyMode: Int {
case media = 0
case function
var behavior: AppBehavior {
switch self {
case .media:
return .media
case .function:
return .function
}
}
var counterPart: FKeyMode {
switch self {
case .media: return .function
case .function: return .media
}
}
var label: String {
switch self {
case .media:
return NSLocalizedString("Media keys", comment: "")
case .function:
return NSLocalizedString("Function keys", comment: "")
}
}
}
@objc enum AppBehavior: Int {
case inferred = 0
case media
case function
var counterPart: AppBehavior {
switch self {
case .media:
return .function
case .function:
return .media
default:
return .inferred
}
}
var label: String {
switch self {
case .inferred:
return NSLocalizedString("Same as default", comment: "")
case .media:
return NSLocalizedString("Media keys", comment: "")
case .function:
return NSLocalizedString("Function keys", comment: "")
}
}
}
@objc enum SwitchMethod: Int {
case window = 0
case hybrid
case key
}
enum ItemKind {
case rule
case runningApp
var source: NotificationSource {
switch self {
case .rule:
return .rule
case .runningApp:
return .runningApp
}
}
}
enum NotificationSource {
case rule
case runningApp
case mainMenu
case fnKey
case behaviorManager
case undefined
}
struct UserNotificationEnablement: OptionSet {
let rawValue: Int
static let appSwitch: Self = .init(rawValue: 1 << 0)
static let appKey: Self = .init(rawValue: 1 << 1)
static let globalKey: Self = .init(rawValue: 1 << 2)
static let all: Self = [.appSwitch, .appKey, .globalKey]
static let none: Self = []
static func from(_ vc: UserNotificationEnablementViewController) -> Self {
guard !vc.everytime else { return .all }
return Self.none
.union(vc.activeAppSwitch ? .appSwitch : .none)
.union(vc.activeAppFnKey ? .appKey : .none)
.union(vc.globalFnKey ? .globalKey : .none)
}
func apply(to vc: UserNotificationEnablementViewController) {
if self == .all {
vc.everytime = true
vc.activeAppSwitch = true
vc.activeAppFnKey = true
vc.globalFnKey = true
} else if self == .none {
vc.everytime = false
vc.activeAppSwitch = false
vc.activeAppFnKey = false
vc.globalFnKey = false
} else {
vc.everytime = false
vc.activeAppSwitch = self.contains(.appSwitch)
vc.activeAppFnKey = self.contains(.appKey)
vc.globalFnKey = self.contains(.globalKey)
}
}
}
| mit |
lieonCX/TodayHeadline | TodayHealine/View/Find/HotCollectionViewCell.swift | 1 | 470 | //
// HotCollectionViewCell.swift
// TodayHealine
//
// Created by lieon on 2017/2/8.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import UIKit
class HotCollectionViewCell: UICollectionViewCell, OneLabelProtocol, OneImageOneLabelProtocol, View {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var sublabel: UILabel!
}
extension HotCollectionViewCell: ViewNameReusable {}
| mit |
ylankgz/safebook | Safebook/NewsListTableViewCell.swift | 1 | 444 |
import UIKit
class NewsListTableViewCell: UITableViewCell {
@IBOutlet weak var postTitle: UILabel!
@IBOutlet weak var postDate: UILabel!
@IBOutlet weak var postImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
postTitle.sizeToFit()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| mit |
adamontherun/Study-iOS-With-Adam-Live | PDFKitTest/PDFKitTest/AppDelegate.swift | 1 | 2054 | //😘 it is 8/18/17
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:.
}
}
| mit |
adelinofaria/Buildasaur | Buildasaur/AppDelegate.swift | 2 | 2528 | //
// AppDelegate.swift
// Buildasaur
//
// Created by Honza Dvorsky on 12/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Cocoa
/*
Please report any crashes on GitHub, I may optionally ask you to email them to me. Thanks!
You can find them at ~/Library/Logs/DiagnosticReports/Buildasaur-*
Also, you can find the log at ~/Library/Application Support/Buildasaur/Builda.log
*/
import BuildaUtils
import XcodeServerSDK
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let menuItemManager = MenuItemManager()
func applicationDidFinishLaunching(aNotification: NSNotification) {
self.setupLogging()
self.menuItemManager.setupMenuBarItem()
}
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
self.showMainWindow()
return true
}
func applicationDidBecomeActive(notification: NSNotification) {
self.showMainWindow()
}
func applicationWillTerminate(aNotification: NSNotification) {
StorageManager.sharedInstance.stop()
}
//MARK: Showing Window on Reactivation
func showMainWindow(){
NSApp.activateIgnoringOtherApps(true)
//first window. i wish there was a nicer way (please some tell me there is)
if let window = NSApplication.sharedApplication().windows.first as? NSWindow {
window.makeKeyAndOrderFront(self)
}
}
//MARK: Logging
func setupLogging() {
let path = Persistence.buildaApplicationSupportFolderURL().URLByAppendingPathComponent("Builda.log", isDirectory: false)
let fileLogger = FileLogger(filePath: path)
let consoleLogger = ConsoleLogger()
let loggers: [Logger] = [
consoleLogger,
fileLogger
]
Log.addLoggers(loggers)
let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
let ascii =
" ____ _ _ _\n" +
"| _ \\ (_) | | |\n" +
"| |_) |_ _ _| | __| | __ _ ___ __ _ _ _ _ __\n" +
"| _ <| | | | | |/ _` |/ _` / __|/ _` | | | | '__|\n" +
"| |_) | |_| | | | (_| | (_| \\__ \\ (_| | |_| | |\n" +
"|____/ \\__,_|_|_|\\__,_|\\__,_|___/\\__,_|\\__,_|_|\n"
Log.untouched("*\n*\n*\n\(ascii)\nBuildasaur \(version) launched at \(NSDate()).\n*\n*\n*\n")
}
}
| mit |
FabrizioBrancati/SwiftyBot | Sources/Messenger/Response/MessageResponseError.swift | 1 | 1362 | //
// MessageResponseError.swift
// SwiftyBot
//
// The MIT License (MIT)
//
// Copyright (c) 2016 - 2019 Fabrizio Brancati.
//
// 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
/// Message response error.
public enum MessageResponseError: Error {
/// Missing value error.
case missingValue
}
| mit |
PSSWD/psswd-ios | psswd/AuthSigninMasterpassVC.swift | 1 | 1359 | //
// AuthSigninMasterpassVC.swift
// psswd
//
// Created by Daniil on 09.01.15.
// Copyright (c) 2015 kirick. All rights reserved.
//
import UIKit
class AuthSigninMasterpassVC: UITableViewController
{
@IBOutlet weak var masterpassField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
}
@IBAction func nextPressed(sender: AnyObject) {
var masterpass = masterpassField.text!
var masterpass_getCodes_public = Crypto.Bytes(fromString: masterpass).append(API.constants.salt_masterpass_getcodes_public).getSHA1()
var params = [
"email": Storage.getString("email")!,
"masterpass_getcodes_public": masterpass_getCodes_public,
"app_id": API.app.app_id,
"app_secret": API.app.app_secret
] as [String: AnyObject]
API.call("device.create", params: params, callback: { rdata in
let code = rdata["code"] as! Int
switch code {
case 0:
Storage.set(rdata["data"] as! String, forKey: "device_id")
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("AuthSigninConfirmVC") as! AuthSigninConfirmVC
vc.masterpass = masterpass
self.navigationController!.pushViewController(vc, animated: true)
case 201:
Funcs.message("Неверный мастерпароль.")
self.masterpassField.text = ""
default:
API.unknownCode(rdata)
}
})
}
}
| gpl-2.0 |
PJayRushton/stats | Stats/SwipeTransitionDelegate.swift | 2 | 2735 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
public class SwipeTransitionDelegate: NSObject {
public var targetEdge: UIRectEdge
public var edgeForDragging: UIRectEdge
public var gestureRecognizer: UIPanGestureRecognizer?
public var scrollView: UIScrollView?
public var presentingCornerRadius: CGFloat
public var dimmingBackgroundColor: UIColor?
public init(targetEdge: UIRectEdge, edgeForDragging: UIRectEdge? = nil, gestureRecognizer: UIPanGestureRecognizer? = nil, scrollView: UIScrollView? = nil, presentingCornerRadius: CGFloat = 0.0, dimmingBackgroundColor: UIColor? = nil) {
self.targetEdge = targetEdge
if let edgeForDragging = edgeForDragging {
self.edgeForDragging = edgeForDragging
} else {
self.edgeForDragging = targetEdge
}
self.gestureRecognizer = gestureRecognizer
self.scrollView = scrollView
self.presentingCornerRadius = presentingCornerRadius
self.dimmingBackgroundColor = dimmingBackgroundColor
}
}
// MARK: - View controller transitioning delegate
extension SwipeTransitionDelegate: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SwipeTransitionAnimator(targetEdge: targetEdge, presentingCornerRadius: presentingCornerRadius, dimmingBackgroundColor: dimmingBackgroundColor)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SwipeTransitionAnimator(targetEdge: targetEdge, presentingCornerRadius: presentingCornerRadius, dimmingBackgroundColor: dimmingBackgroundColor)
}
public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if let gestureRecognizer = gestureRecognizer {
return SwipeTransitionInteractionController(edgeForDragging: edgeForDragging, gestureRecognizer: gestureRecognizer, scrollView: scrollView)
}
return nil
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if let gestureRecognizer = gestureRecognizer {
return SwipeTransitionInteractionController(edgeForDragging: edgeForDragging, gestureRecognizer: gestureRecognizer, scrollView: scrollView)
}
return nil
}
}
| mit |
lerigos/music-service | iOS_9/Application/LMCoreDataGet.swift | 1 | 440 | //
// LMCoreDataGet.swift
// Application
//
// Created by Dmitriy Groschovskiy on 7/1/16.
// Copyright © 2016 Lerigos Urban Developers Limited. All rights reserved.
//
import UIKit
import CoreData
class LMCoreDataGet: NSObject {
var personalIdent = [NSManagedObject]()
func getAccountUsernameData() -> String {
return "s"
}
func getAccountPasswordData() -> String {
return "p"
}
}
| apache-2.0 |
huonw/swift | validation-test/compiler_crashers_fixed/27076-swift-declcontext-getlocalconformances.swift | 65 | 462 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 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
let a{
{
{
class a
struct Q{
class a{
let:{
{
let a{
let a{
s=b
| apache-2.0 |
ludoded/ReceiptBot | Pods/Material/Sources/iOS/View.swift | 3 | 6116 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
open class View: UIView {
open override var intrinsicContentSize: CGSize {
return CGSize(width: width, height: height)
}
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
open let visualLayer = CAShapeLayer()
/**
A property that manages an image for the visualLayer's contents
property. Images should not be set to the backing layer's contents
property to avoid conflicts when using clipsToBounds.
*/
@IBInspectable
open var image: UIImage? {
get {
guard let v = visualLayer.contents else {
return nil
}
return UIImage(cgImage: v as! CGImage)
}
set(value) {
visualLayer.contents = value?.cgImage
}
}
/**
Allows a relative subrectangle within the range of 0 to 1 to be
specified for the visualLayer's contents property. This allows
much greater flexibility than the contentsGravity property in
terms of how the image is cropped and stretched.
*/
@IBInspectable
open var contentsRect: CGRect {
get {
return visualLayer.contentsRect
}
set(value) {
visualLayer.contentsRect = value
}
}
/**
A CGRect that defines a stretchable region inside the visualLayer
with a fixed border around the edge.
*/
@IBInspectable
open var contentsCenter: CGRect {
get {
return visualLayer.contentsCenter
}
set(value) {
visualLayer.contentsCenter = value
}
}
/**
A floating point value that defines a ratio between the pixel
dimensions of the visualLayer's contents property and the size
of the view. By default, this value is set to the Screen.scale.
*/
@IBInspectable
open var contentsScale: CGFloat {
get {
return visualLayer.contentsScale
}
set(value) {
visualLayer.contentsScale = value
}
}
/// A Preset for the contentsGravity property.
@IBInspectable
open var contentsGravityPreset: Gravity {
didSet {
contentsGravity = GravityToValue(gravity: contentsGravityPreset)
}
}
/// Determines how content should be aligned within the visualLayer's bounds.
@IBInspectable
open var contentsGravity: String {
get {
return visualLayer.contentsGravity
}
set(value) {
visualLayer.contentsGravity = value
}
}
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.cgColor
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
contentsGravityPreset = .resizeAspectFill
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
contentsGravityPreset = .resizeAspectFill
super.init(frame: frame)
prepare()
}
/// Convenience initializer.
public convenience init() {
self.init(frame: .zero)
prepare()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
contentScaleFactor = Screen.scale
backgroundColor = .white
prepareVisualLayer()
}
}
extension View {
/// Prepares the visualLayer property.
fileprivate func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
layer.addSublayer(visualLayer)
}
}
extension View {
/// Manages the layout for the visualLayer property.
fileprivate func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = cornerRadius
}
}
| lgpl-3.0 |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/CGFloatExtensions.swift | 1 | 3656 | //
// CGFloatExtensions.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import Foundation
import QuartzCore
extension CGFloat {
func isInRangeOrEqual(_ from: CGFloat, _ to: CGFloat) -> Bool {
return (from <= self && self <= to)
}
func isInRange(_ from: CGFloat, _ to: CGFloat) -> Bool {
return (from < self && self < to)
}
var squared: CGFloat {
return self * self
}
var cubed: CGFloat {
return self * self * self
}
var cubicRoot: CGFloat {
return CGFloat(pow(Double(self), 1.0 / 3.0))
}
fileprivate static func SolveQuadratic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat) -> CGFloat {
var result = (-b + sqrt(b.squared - 4 * a * c)) / (2 * a);
guard !result.isInRangeOrEqual(0, 1) else {
return result
}
result = (-b - sqrt(b.squared - 4 * a * c)) / (2 * a);
guard !result.isInRangeOrEqual(0, 1) else {
return result
}
return -1;
}
fileprivate static func SolveCubic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat, _ d: CGFloat) -> CGFloat {
if (a == 0) {
return SolveQuadratic(b, c, d)
}
if (d == 0) {
return 0
}
let a = a
var b = b
var c = c
var d = d
b /= a
c /= a
d /= a
var q = (3.0 * c - b.squared) / 9.0
let r = (-27.0 * d + b * (9.0 * c - 2.0 * b.squared)) / 54.0
let disc = q.cubed + r.squared
let term1 = b / 3.0
if (disc > 0) {
var s = r + sqrt(disc)
s = (s < 0) ? -((-s).cubicRoot) : s.cubicRoot
var t = r - sqrt(disc)
t = (t < 0) ? -((-t).cubicRoot) : t.cubicRoot
let result = -term1 + s + t;
if result.isInRangeOrEqual(0, 1) {
return result
}
} else if (disc == 0) {
let r13 = (r < 0) ? -((-r).cubicRoot) : r.cubicRoot;
var result = -term1 + 2.0 * r13;
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -(r13 + term1);
if result.isInRangeOrEqual(0, 1) {
return result
}
} else {
q = -q;
var dum1 = q * q * q;
dum1 = acos(r / sqrt(dum1));
let r13 = 2.0 * sqrt(q);
var result = -term1 + r13 * cos(dum1 / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -term1 + r13 * cos((dum1 + 2.0 * .pi) / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -term1 + r13 * cos((dum1 + 4.0 * .pi) / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
}
return -1;
}
func cubicBezierInterpolate(_ P0: CGPoint, _ P1: CGPoint, _ P2: CGPoint, _ P3: CGPoint) -> CGFloat {
var t: CGFloat
if (self == P0.x) {
// Handle corner cases explicitly to prevent rounding errors
t = 0
} else if (self == P3.x) {
t = 1
} else {
// Calculate t
let a = -P0.x + 3 * P1.x - 3 * P2.x + P3.x;
let b = 3 * P0.x - 6 * P1.x + 3 * P2.x;
let c = -3 * P0.x + 3 * P1.x;
let d = P0.x - self;
let tTemp = CGFloat.SolveCubic(a, b, c, d);
if (tTemp == -1) {
return -1;
}
t = tTemp
}
// Calculate y from t
return (1 - t).cubed * P0.y + 3 * t * (1 - t).squared * P1.y + 3 * t.squared * (1 - t) * P2.y + t.cubed * P3.y;
}
func cubicBezier(_ t: CGFloat, _ c1: CGFloat, _ c2: CGFloat, _ end: CGFloat) -> CGFloat {
let t_ = (1.0 - t)
let tt_ = t_ * t_
let ttt_ = t_ * t_ * t_
let tt = t * t
let ttt = t * t * t
return self * ttt_
+ 3.0 * c1 * tt_ * t
+ 3.0 * c2 * t_ * tt
+ end * ttt;
}
}
| mit |
Jnosh/swift | validation-test/compiler_crashers_fixed/02135-swift-metatypetype-get.swift | 65 | 593 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 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
let t: Array) -> Any, end: d where Optional<3] = d(self.Type
return ")
protocol d : a {
typealias d = c) -> T, U) -> U.advance(g() -> String {
t: Boolean>] = "
protocol a {
typealias b : d where
| apache-2.0 |
volodg/iAsync.utils | Sources/Array/HashableArray.swift | 1 | 2147 | //
// HashableArray.swift
// iAsync_utils
//
// Created by Vladimir Gorbenko on 02.10.14.
// Copyright © 2014 EmbeddedSources. All rights reserved.
//
import Foundation
public struct HashableArray<T: Equatable> : Hashable, Collection/*, MutableCollectionType*/, CustomStringConvertible, ExpressibleByArrayLiteral {
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return array.index(after: i)
}
public var array: Array<T>
// typealias SubSequence = MutableSlice<Self>
// public subscript (position: Self.Index) -> Self.Generator.Element { get set }
// public subscript (bounds: Range<Self.Index>) -> Self.SubSequence { get set }
public var last: T? {
return array.last
}
public typealias Iterator = Array<T>.Iterator
public typealias Index = Array<T>.Index
// public typealias Generator = Array<T>.Generator
public typealias Element = Array<T>.Element
public typealias _Element = Array<T>._Element
public var startIndex: Index { return array.startIndex }
public var endIndex: Index { return array.endIndex }
public subscript (position: Index) -> _Element {
return array[position]
}
public func makeIterator() -> Iterator {
return array.makeIterator()
}
public mutating func removeAll() {
array.removeAll()
}
public mutating func append(_ el: T) {
array.append(el)
}
public var hashValue: Int {
return array.count
}
public init(_ array: [T]) {
self.array = array
}
public init(arrayLiteral elements: Element...) {
self.init(Array(elements))
}
public init() {
self.init([])
}
public var description: String {
return "iAsync.utils.HashableArray: \(array)"
}
}
public func ==<T: Equatable>(lhs: HashableArray<T>, rhs: HashableArray<T>) -> Bool {
return lhs.array == rhs.array
}
| mit |
norio-nomura/RxSwift | RxSwift/Concurrency/Scheduler.swift | 1 | 2047 | //
// Scheduler.swift
// RxSwift
//
// Created by 野村 憲男 on 4/1/15.
// Copyright (c) 2015 Norio Nomura. All rights reserved.
//
import Foundation
public class Scheduler: IScheduler {
/**
Swift 1.2 can't allow overriding generic methods of non-generic class with generic class.
So, I use methods for overriding `scheduleCore()`
See: https://devforums.apple.com/thread/268824
*/
// MARK: ISchedulerCore
public final func schedule<TState>(#state: TState, action: (IScheduler, TState) -> IDisposable?) -> IDisposable? {
return scheduleCore(state: state, action: {return action($0, state)})
}
public final func schedule<TState>(#state: TState, dueTime: NSTimeInterval, action: (IScheduler, TState) -> IDisposable?) -> IDisposable? {
return scheduleCore(state: state, dueTime: dueTime, action: {return action($0, state)})
}
// MARK: IScheduler
public var now: NSDate {
return NSDate()
}
// MARK: internal
func scheduleCore(#state: Any, action: IScheduler -> IDisposable?) -> IDisposable? {
fatalError("Abstract method \(__FUNCTION__)")
}
func scheduleCore(#state: Any, dueTime: NSTimeInterval, action: IScheduler -> IDisposable?) -> IDisposable? {
fatalError("Abstract method \(__FUNCTION__)")
}
}
extension Scheduler {
// MARK: IScheduler
public final func schedule(#action: () -> ()) -> IDisposable? {
return schedule(state: action, action: invoke)
}
public final func schedule(#dueTime: NSTimeInterval, action: () -> ()) -> IDisposable? {
return schedule(state: action, dueTime: dueTime, action: invoke)
}
}
// MARK: private
private func invoke(_: IScheduler, action: () -> ()) -> IDisposable? {
action()
return nil
}
extension Scheduler {
public static var immediate = ImmediateScheduler()
public static func normalize(timeInterval: NSTimeInterval) -> NSTimeInterval {
return timeInterval < 0 ? 0 : timeInterval
}
}
| mit |
madbat/SwiftWorkshop | SwiftCommitTests/SwiftCommitTests.swift | 1 | 923 | //
// SwiftCommitTests.swift
// SwiftCommitTests
//
// Created by Matteo Battaglio on 18/03/15.
// Copyright (c) 2015 Matteo Battaglio. All rights reserved.
//
import UIKit
import XCTest
class SwiftCommitTests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
sunfei/realm-cocoa | examples/ios/swift-2.0/Backlink/AppDelegate.swift | 3 | 2243 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// 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 RealmSwift
class Dog: Object {
dynamic var name = ""
dynamic var age = 0
var owners: [Person] {
// Realm doesn't persist this property because it only has a getter defined
// Define "owners" as the inverse relationship to Person.dogs
return linkingObjects(Person.self, forProperty: "dogs")
}
}
class Person: Object {
dynamic var name = ""
let dogs = List<Dog>()
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
do {
try NSFileManager.defaultManager().removeItemAtPath(Realm.Configuration.defaultConfiguration.path!)
} catch {}
let realm = try! Realm()
realm.write {
realm.create(Person.self, value: ["John", [["Fido", 1]]])
realm.create(Person.self, value: ["Mary", [["Rex", 2]]])
}
// Log all dogs and their owners using the "owners" inverse relationship
let allDogs = realm.objects(Dog)
for dog in allDogs {
let ownerNames = dog.owners.map { $0.name }
print("\(dog.name) has \(ownerNames.count) owners (\(ownerNames))")
}
return true
}
}
| apache-2.0 |
ZakariyyaSv/LYNetwork | LYNetwork/Source/LYNetworkPrivate.swift | 1 | 9150 | //
// LYNetworkPrivate.swift
//
// Copyright (c) 2017 LYNetwork https://github.com/ZakariyyaSv/LYNetwork
//
// 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
// MARK: - Debug Logger
func lyDebugPrintLog<T>(message: T,
file: String = #file,
method: String = #function,
line: Int = #line) {
#if DEBUG
if !LYNetworkConfig.shared.debugLogEnabled {
return
}
print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
#endif
}
// MARK: - RequestAccessory
extension LYBaseRequest {
public func toggleAccessoriesWillStartCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStart(self)
})
}
}
public func toggleAccessoriesWillStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStop(self)
})
}
}
public func toggleAccessoriesDidStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestDidStop(self)
})
}
}
}
extension LYBatchRequest {
public func toggleAccessoriesWillStartCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStart(self)
})
}
}
public func toggleAccessoriesWillStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStop(self)
})
}
}
public func toggleAccessoriesDidStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestDidStop(self)
})
}
}
}
extension LYChainRequest {
public func toggleAccessoriesWillStartCallBack() {
if self.requestAccessories != nil {
self.requestAccessories?.forEach({ (accessory) in
accessory.requestWillStart(self)
})
}
}
public func toggleAccessoriesWillStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStop(self)
})
}
}
public func toggleAccessoriesDidStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestDidStop(self)
})
}
}
}
// MARK: - Equatable
extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(_ object: Element) {
if let index = index(of: object) {
remove(at: index)
}
}
}
extension LYBatchRequest: Equatable {
public static func ==(lhs: LYBatchRequest, rhs: LYBatchRequest) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
extension LYChainRequest: Equatable {
public static func ==(lhs: LYChainRequest, rhs: LYChainRequest) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
// MARK: - LYNetworkError
open class LYNetworkError {
open class func summaryFrom(error: Error, response: HTTPURLResponse?) -> String {
if let statusCode = response?.statusCode {
switch statusCode {
case 400..<500: // Client Errors
return "客户端错误(HTTP错误代码: \(statusCode))"
case 500..<600: // Server Errors
return "网络异常,请重试(HTTP错误代码: \(statusCode))"
default:
break
}
}
let nsError: NSError = error as NSError
return nsError.lyDescription()
}
}
public extension String {
public func MD5String() -> String? {
return MD5(self)
}
}
public extension NSError {
// This description should cover NSURLErrorDomain & CFNetworkErrors and
// give a easy understanding description with error code.
// view the details on http://nshipster.com/nserror/
func lyDescription() -> String {
switch self.domain {
case NSURLErrorDomain:
switch self.code {
case -1..<110: // Network Errors
return "网络异常,请重试(错误代码:\(self.code))"
case 110..<119: //SOCKS4 Errors
return "网络异常,请重试(错误代码:\(self.code))"
case 120..<130: //SOCKS5 Errors
return "网络异常,请重试(错误代码:\(self.code))"
case 200..<300: // FTP Errors
return "网络异常,请重试(错误代码:\(self.code))"
case 300..<400: // HTTP Errors
return "网络异常,请重试(错误代码:\(self.code))"
case -998: // kCFURLErrorUnknown An unknown error occurred.
return "网络异常,请重试(错误代码:\(self.code))"
case -999: // kCFURLErrorCancelled/NSURLErrorCancelled The connection was cancelled.
return ""
case -1000: // kCFURLErrorBadURL/NSURLErrorBadURL
return ""
case -1001: // kCFURLErrorTimedOut/NSURLErrorTimedOut
return ""
case -1002: // kCFURLErrorUnsupportedURL/NSURLErrorUnsupportedURL
return ""
case -1003: // kCFURLErrorCannotFindHost/NSURLErrorCannotFindHost
return ""
case -1004: // kCFURLErrorCannotConnectToHost/NSURLErrorCannotConnectToHost
return ""
case -1005: // kCFURLErrorNetworkConnectionLost/NSURLErrorNetworkConnectionLost
return ""
case -1006: // kCFURLErrorDNSLookupFailed/NSURLErrorDNSLookupFailed
return ""
case -1007: // kCFURLErrorHTTPTooManyRedirects/NSURLErrorHTTPTooManyRedirects
return ""
case -1008..<(-999): // CFURLConnection & CFURLProtocol Errors
return "网络异常,请重试(错误代码:\(self.code))"
case -1009: // kCFURLErrorNotConnectedToInternet/NSURLErrorNotConnectedToInternet The connection failed because the device is not connected to the internet.
return "网络连接错误,请检查网络设置"
case -1010: // kCFURLErrorRedirectToNonExistentLocation/NSURLErrorRedirectToNonExistentLocation The connection was redirected to a nonexistent location
return "网络异常,请重试(错误代码:\(self.code))"
case -1011: // kCFURLErrorBadServerResponse/NSURLErrorBadServerResponse
return ""
case -1012: // kCFURLErrorUserCancelledAuthentication/NSURLErrorUserCancelledAuthentication
return ""
case -1013: // kCFURLErrorUserAuthenticationRequired/NSURLErrorUserAuthenticationRequired
return ""
case -1014: // kCFURLErrorZeroByteResource/NSURLErrorZeroByteResource
return ""
case -1015: // kCFURLErrorCannotDecodeRawData/NSURLErrorCannotDecodeRawData
return ""
case -1016: // kCFURLErrorCannotDecodeContentData/NSURLErrorCannotDecodeContentData
return ""
case -1017: // kCFURLErrorCannotParseResponse/NSURLErrorCannotParseResponse
return ""
case -1018: // kCFURLErrorInternationalRoamingOff 国际漫游
return ""
case -1019: // kCFURLErrorCallIsActive
return ""
case -1020: // kCFURLErrorDataNotAllowed
return ""
case -1021: // kCFURLErrorRequestBodyStreamExhausted
return ""
case -1022: // kCFURLErrorAppTransportSecurityRequiresSecureConnection
return ""
case -1103..<(-1099): // FTP Errors
return "手机系统异常,请重装应用(错误代码:\(self.code))"
case -1999..<(-1199): // SSL Errors
return "网络异常,请重试(错误代码:\(self.code))"
case -3007..<(-1999): // Download and File I/O Errors
return "手机系统异常,请重装应用(错误代码:\(self.code))"
case -4000: // Cookie errors
return "网络异常,请重启应用(错误代码:\(self.code))"
case -73000..<(-71000): // CFNetServices Errors
return "网络异常,请重试(错误代码:\(self.code))"
default:
return self.localizedDescription
}
default:
return self.localizedDescription
}
}
}
| mit |
MakeSchool/TripPlanner | TripPlanner/UI/LocationSearch/PlaceWithLocation+MKAnnotation.swift | 1 | 675 | //
// PlaceWithLocation+MKAnnotation.swift
// TripPlanner
//
// Created by Benjamin Encz on 7/27/15.
// Copyright © 2015 Make School. All rights reserved.
//
import Foundation
import CoreLocation
import MapKit
class PlaceWithLocationAnnotation: NSObject, MKAnnotation {
let placeWithLocation: PlaceWithLocation
init(placeWithLocation: PlaceWithLocation) {
self.placeWithLocation = placeWithLocation
}
var coordinate: CLLocationCoordinate2D {
get {
return placeWithLocation.location
}
}
@objc var title: String? {
get {
return placeWithLocation.locationSearchEntry.terms.map{$0.value}.joinWithSeparator(", ")
}
}
} | mit |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/NativeComponents/Detectors/FaceDetector/FaceDetectorOutput.swift | 1 | 6518 | //
// FaceDetectorOutput.swift
// StripeIdentity
//
// Created by Mel Ludowise on 5/10/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import CoreGraphics
import CoreML
import Foundation
@_spi(STP) import StripeCameraCore
import Vision
/// Represents the output from the FaceDetector ML model.
struct FaceDetectorOutput: Equatable {
let predictions: [FaceDetectorPrediction]
}
struct FaceDetectorPrediction: Equatable {
/// The bounding box of the detected face
let rect: CGRect
/// The score of the detected face
let score: Float
}
// MARK: MLBoundingBox
extension FaceDetectorPrediction: MLBoundingBox {
// FaceDetector has no classification, so each prediction has the same classIndex
var classIndex: Int {
return 0
}
}
// MARK: - MultiArray
extension FaceDetectorOutput: VisionBasedDetectorOutput {
/// We want to know if 0, 1, or > 1 faces are returned by the model, so tell
/// NMS to return a max of 2 results.
static let nmsMaxResults: Int = 2
/// Expected feature names from the ML model output
private enum FeatureNames: String {
case scores
case boxes
}
init(
detector: FaceDetector,
observations: [VNObservation],
originalImageSize: CGSize
) throws {
let featureValueObservations = observations.compactMap {
$0 as? VNCoreMLFeatureValueObservation
}
guard
let scoresObservation = featureValueObservations.first(where: {
$0.featureName == FeatureNames.scores.rawValue
}),
let boxesObservation = featureValueObservations.first(where: {
$0.featureName == FeatureNames.boxes.rawValue
}),
let scoresMultiArray = scoresObservation.featureValue.multiArrayValue,
let boxesMultiArray = boxesObservation.featureValue.multiArrayValue,
FaceDetectorOutput.isValidShape(boxes: boxesMultiArray, scores: scoresMultiArray)
else {
throw MLModelUnexpectedOutputError(observations: featureValueObservations)
}
self.init(
boxes: boxesMultiArray,
scores: scoresMultiArray,
originalImageSize: originalImageSize,
configuration: detector.configuration
)
}
/// Initializes `FaceDetectorOutput` from multi arrays of boxes and scores using
/// the non-maximum-suppression algorithm to determine the best scores and
/// bounding boxes.
/// - Parameters:
/// - boxes: The multi array of the "boxes" with a shape of
/// 1 x numPredictions x 4 where `boxes[0][n]` returns an array of
/// `[minX, minY, maxX, maxY]`
/// - scores: The multi array of the "scores" with a shape of
/// 1 x numPredictions x 1
init(
boxes: MLMultiArray,
scores: MLMultiArray,
originalImageSize: CGSize,
configuration: FaceDetector.Configuration
) {
let numPredictions = scores.shape[1].intValue
let predictions: [FaceDetectorPrediction] = (0..<numPredictions).compactMap { index in
let score = scores[[0, index, 0]].floatValue
// Discard results that have a score lower than minScore
guard score >= configuration.minScore else {
return nil
}
let rect = CGRect(
x: boxes[[0, index, 0]].doubleValue,
y: boxes[[0, index, 1]].doubleValue,
width: boxes[[0, index, 2]].doubleValue,
height: boxes[[0, index, 3]].doubleValue
)
// Discard results that are outside the bounds of the image
guard CGRect.normalizedBounds.contains(rect) else {
return nil
}
return .init(
rect: rect,
score: score
)
}
// Use NMS to get the best bounding boxes
// NOTE: The result of `nonMaxSuppression` will be sorted by score
let bestPredictions = nonMaxSuppression(
boundingBoxes: predictions,
iouThreshold: configuration.minIOU,
maxBoxes: FaceDetectorOutput.nmsMaxResults
).map { index in
return predictions[index]
}
self.init(
centerCroppedSquarePredictions: bestPredictions,
originalImageSize: originalImageSize
)
}
/// Initializes `FaceDetectorOutput` from a list of predictions using a
/// center-cropped square coordinate space.
///
/// - Note:
/// Because the FaceDetector model is only scanning the center-cropped
/// square region of the original image, the bounding box returned by
/// the model is going to be relative to the center-cropped square.
/// We need to convert the bounding box into coordinates relative to
/// the original image size.
///
/// - Parameters:
/// - predictions: A list of predictions using a center-cropped square coordinate space.
/// - originalImageSize: The size of the original image.
init(
centerCroppedSquarePredictions predictions: [FaceDetectorPrediction],
originalImageSize: CGSize
) {
self.init(
predictions: predictions.map {
.init(
rect: $0.rect.convertFromNormalizedCenterCropSquare(
toOriginalSize: originalImageSize
),
score: $0.score
)
}
)
}
/// Determines if the multi-arrays output by the FaceDetector's ML model have a
/// valid shape that can be parsed into a list of predictions.
///
/// - Parameters:
/// - boxes: The multi array of the "boxes" with a shape of
/// 1 x numPredictions x 4 where `boxes[0][n]` returns an array of
/// `[minX, minY, maxX, maxY]`
/// - scores: The multi array of the "scores" with a shape of
/// 1 x numPredictions x 1
///
/// - Returns: True if the multi-arrays have a valid shape that can be parsed into predictions.
static func isValidShape(
boxes: MLMultiArray,
scores: MLMultiArray
) -> Bool {
return boxes.shape.count == 3 && boxes.shape[0] == 1 && boxes.shape[2] == 4
&& scores.shape.count == 3 && scores.shape[0] == 1 && scores.shape[2] == 1
&& boxes.shape[1] == scores.shape[1]
}
}
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceApplicationSession/Sources/EurofurenceApplicationSession/BuildConfigurationProviding.swift | 2 | 168 | public enum BuildConfiguration {
case debug
case release
}
public protocol BuildConfigurationProviding {
var configuration: BuildConfiguration { get }
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/11462-swift-sourcemanager-getmessage.swift | 11 | 253 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init(
= (
var {
var P {
{
}
protocol C {
struct S {
enum S {
class A {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/12963-swift-completegenerictyperesolver-resolvedependentmembertype.swift | 11 | 223 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class b<T {
class B<T {
func a( ) {
func a<I : B<T.j>
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/26211-swift-typechecker-coercepatterntotype.swift | 7 | 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
enum B{class A{class B{class B{struct B<T where k:A{class a{class B{let a=(class A{let s=V
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/20610-no-stacktrace.swift | 11 | 239 | // 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
{
if true {
extension NSSet {
deinit {
( {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/06186-swift-modulefile-getdecl.swift | 11 | 293 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
let t: b {
}
var _ = b<d {
}
protocol P {
protocol e : e))
func b<d where T : a<H : a {
return "
typealias e : e)
| mit |
austinzheng/swift-compiler-crashes | fixed/02477-swift-constraints-constraintsystem-matchtypes.swift | 11 | 183 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a{[[Void{ | mit |
CatchChat/Yep | Yep/ViewControllers/Show/ShowStepViewController.swift | 1 | 3326 | //
// ShowStepViewController.swift
// Yep
//
// Created by nixzhu on 15/8/12.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import Ruler
class ShowStepViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet private weak var titleLabelBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet private weak var subTitleLabelBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.textColor = UIColor.yepTintColor()
titleLabelBottomConstraint.constant = Ruler.iPhoneVertical(20, 30, 30, 30).value
subTitleLabelBottomConstraint.constant = Ruler.iPhoneVertical(120, 140, 160, 180).value
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
view.alpha = 0
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.view.alpha = 1
}, completion: { _ in })
}
func repeatAnimate(view: UIView, alongWithPath path: UIBezierPath, duration: CFTimeInterval, autoreverses: Bool = false) {
let animation = CAKeyframeAnimation(keyPath: "position")
animation.calculationMode = kCAAnimationPaced
animation.fillMode = kCAFillModeForwards
animation.duration = duration
animation.repeatCount = Float.infinity
animation.autoreverses = autoreverses
if autoreverses {
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
} else {
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
}
animation.path = path.CGPath
view.layer.addAnimation(animation, forKey: "Animation")
}
func animate(view: UIView, offset: UInt32, duration: CFTimeInterval) {
let path = UIBezierPath()
func flip() -> CGFloat {
return arc4random() % 2 == 0 ? -1 : 1
}
let beginPoint = CGPoint(x: view.center.x + CGFloat(arc4random() % offset) * flip(), y: view.center.y + CGFloat(arc4random() % offset) * 0.5 * flip())
let endPoint = CGPoint(x: view.center.x + CGFloat(arc4random() % offset) * flip(), y: view.center.y + CGFloat(arc4random() % offset) * 0.5 * flip())
path.moveToPoint(beginPoint)
path.addLineToPoint(endPoint)
repeatAnimate(view, alongWithPath: path, duration: duration, autoreverses: true)
repeatRotate(view, fromValue: -0.1, toValue: 0.1, duration: duration)
}
private func repeatRotate(view: UIView, fromValue: AnyObject, toValue: AnyObject, duration: CFTimeInterval) {
let rotate = CABasicAnimation(keyPath: "transform.rotation.z")
rotate.fromValue = fromValue
rotate.toValue = toValue
rotate.duration = duration
rotate.repeatCount = Float.infinity
rotate.autoreverses = true
rotate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
view.layer.allowsEdgeAntialiasing = true
view.layer.addAnimation(rotate, forKey: "Rotate")
}
}
| mit |
Zewo/HTTP | Sources/HTTP/Content/Response+Content.swift | 5 | 2192 | import Axis
extension Response {
public var content: Map? {
get {
return storage["content"] as? Map
}
set(content) {
storage["content"] = content
}
}
}
extension Response {
public init<T : MapRepresentable>(status: Status = .ok, headers: Headers = [:], content: T, contentType: MediaType? = nil) {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = content.map
if let contentType = contentType {
self.contentType = contentType
}
}
public init<T : MapRepresentable>(status: Status = .ok, headers: Headers = [:], content: T?, contentType: MediaType? = nil) {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = content.map
if let contentType = contentType {
self.contentType = contentType
}
}
public init<T : MapRepresentable>(status: Status = .ok, headers: Headers = [:], content: [T], contentType: MediaType? = nil) {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = content.map
if let contentType = contentType {
self.contentType = contentType
}
}
public init<T : MapRepresentable>(status: Status = .ok, headers: Headers = [:], content: [String: T], contentType: MediaType? = nil) {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = content.map
if let contentType = contentType {
self.contentType = contentType
}
}
public init<T : MapFallibleRepresentable>(status: Status = .ok, headers: Headers = [:], content: T, contentType: MediaType? = nil) throws {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = try content.asMap()
if let contentType = contentType {
self.contentType = contentType
}
}
}
| mit |
PonyGroup/PonyChatUI-Swift | PonyChatUI/Classes/User Interface/View/MessageCellNode.swift | 1 | 9924 | //
// MessageCellNode.swift
// PonyChatUIProject
//
// Created by 崔 明辉 on 15/10/27.
//
//
import Foundation
import AsyncDisplayKit
extension PonyChatUI.UserInterface {
public class MessageCellNode: ASCellNode, PCUMenuViewControllerDelegate {
weak var coreDelegate: PonyChatUIDelegate?
weak var messagingViewController: MainViewController?
let messageItem: PonyChatUI.Entity.Message
let messagingConfigure: Configure
let avatarNode = ASNetworkImageNode(cache: PonyChatUI.ImageCacheManager.sharedManager,
downloader: PonyChatUI.ImageDownloadManager.sharedManager)
let nicknameNode = ASTextNode()
var sendingIndicatorNode: ASDisplayNode? = nil
var sendingErrorNode: ASImageNode? = nil
let contentNode = ASDisplayNode()
var longPressGesture: UILongPressGestureRecognizer?
init(messageItem: PonyChatUI.Entity.Message, messagingConfigure: Configure) {
self.messageItem = messageItem
self.messagingConfigure = messagingConfigure
super.init()
configureNodes()
configureDatas()
}
var mainContentRect: CGRect = CGRect()
func configureNodes() {
selectionStyle = .None
addSubnode(contentNode)
contentNode.userInteractionEnabled = true
contentNode.addSubnode(avatarNode)
avatarNode.addTarget(self, action: "handleAvatarTapped",
forControlEvents: ASControlNodeEvent.TouchUpInside)
self.messageItem.userInterface = self
if self.messageItem.messageSender != nil {
self.messageItem.messageSender!.userInterface = self
}
if self.messagingConfigure.nicknameShow {
contentNode.addSubnode(nicknameNode)
}
longPressGesture = UILongPressGestureRecognizer(target: self, action: "handleLongPressed:")
longPressGesture!.minimumPressDuration = 0.25
}
func configureDatas() {
if let sender = messageItem.messageSender {
if let URL = NSURL(string: sender.senderAvatarURLString) {
avatarNode.URL = URL
}
if messagingConfigure.nicknameShow {
nicknameNode.attributedString = NSAttributedString(string: sender.senderNickname,
attributes: messagingConfigure.nicknameStyle)
}
if sender.isOwnSender {
configureSendingNodes()
}
}
}
func configureResumeStates() {
if let sendingIndicatorView = self.sendingIndicatorNode?.view as? UIActivityIndicatorView {
sendingIndicatorView.startAnimating()
}
}
func configureSendingNodes() {
if messageItem.messageSendingStatus == .Sending {
self.sendingIndicatorNode = ASDisplayNode(viewBlock: { () -> UIView! in
let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
indicatorView.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
indicatorView.startAnimating()
return indicatorView
})
contentNode.addSubnode(self.sendingIndicatorNode)
if let errorNode = self.sendingErrorNode {
errorNode.removeFromSupernode()
}
layoutSendingNodes()
}
else if messageItem.messageSendingStatus == .Failure {
self.sendingErrorNode = ASImageNode()
self.sendingErrorNode?.image = UIImage(named: "SenderNodeError", inBundle: NSBundle(forClass: PonyChatUICore.self), compatibleWithTraitCollection: nil)
contentNode.addSubnode(self.sendingErrorNode)
if let indicatorNode = self.sendingIndicatorNode {
indicatorNode.removeFromSupernode()
}
self.sendingErrorNode!.addTarget(self, action: "handleErrorNodeTapped", forControlEvents: .TouchUpInside)
layoutSendingNodes()
}
else {
if let indicatorNode = self.sendingIndicatorNode {
indicatorNode.removeFromSupernode()
}
if let errorNode = self.sendingErrorNode {
errorNode.removeFromSupernode()
}
}
}
func layoutSendingNodes() {
if let indicatorNode = self.sendingIndicatorNode {
indicatorNode.frame = CGRect(x: mainContentRect.origin.x - 44.0, y: mainContentRect.size.height / 2.0 + mainContentRect.origin.y - 22.0 - 4.0, width: 44.0, height: 44.0)
}
if let errorNode = self.sendingErrorNode {
errorNode.frame = CGRect(x: mainContentRect.origin.x - 44.0, y: mainContentRect.size.height / 2.0 + mainContentRect.origin.y - 22.0 - 4.0, width: 44.0, height: 44.0)
}
}
var nicknameHeight: CGFloat = 0.0
public override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize {
if messagingConfigure.nicknameShow {
nicknameNode.measure(constrainedSize)
nicknameHeight = nicknameNode.calculatedSize.height + messagingConfigure.nicknameEdge.top + messagingConfigure.nicknameEdge.bottom
}
contentNode.frame = CGRect(x: 0, y: 0.0, width: constrainedSize.width, height: messagingConfigure.avatarSize.height + messagingConfigure.avatarEdge.bottom + nicknameHeight)
return CGSize(width: constrainedSize.width, height: messagingConfigure.avatarSize.height + messagingConfigure.avatarEdge.top + messagingConfigure.avatarEdge.bottom + messagingConfigure.cellGaps)
}
public override func layout() {
if let sender = messageItem.messageSender {
if sender.isOwnSender {
avatarNode.frame = CGRect(x: calculatedSize.width - messagingConfigure.avatarEdge.right - messagingConfigure.avatarSize.width, y: messagingConfigure.avatarEdge.top, width: messagingConfigure.avatarSize.width, height: messagingConfigure.avatarSize.height)
if messagingConfigure.nicknameShow {
nicknameNode.frame = CGRect(x: avatarNode.frame.origin.x - messagingConfigure.avatarEdge.left - nicknameNode.calculatedSize.width - messagingConfigure.nicknameEdge.right, y: messagingConfigure.nicknameEdge.top, width: nicknameNode.calculatedSize.width, height: nicknameNode.calculatedSize.height + messagingConfigure.nicknameEdge.bottom)
}
}
else {
avatarNode.frame = CGRect(x: messagingConfigure.avatarEdge.left, y: messagingConfigure.avatarEdge.top, width: messagingConfigure.avatarSize.width, height: messagingConfigure.avatarSize.height)
if messagingConfigure.nicknameShow {
nicknameNode.frame = CGRect(x: avatarNode.frame.origin.x + messagingConfigure.avatarSize.width + messagingConfigure.avatarEdge.right + messagingConfigure.nicknameEdge.left, y: messagingConfigure.nicknameEdge.top, width: nicknameNode.calculatedSize.width, height: nicknameNode.calculatedSize.height + messagingConfigure.nicknameEdge.bottom)
}
}
avatarNode.layer.cornerRadius = messagingConfigure.avatarCornerRadius
avatarNode.layer.masksToBounds = true
}
else {
avatarNode.hidden = true
}
}
let _menuViewController = MenuViewController(titles: [])
func handleLongPressed(sender: UILongPressGestureRecognizer) {
var titles = _menuViewController.titles
for item in messagingConfigure.longPressItems {
titles.append(item.title)
}
_menuViewController.titles = titles
if sender.state == UIGestureRecognizerState.Began {
if let view = sender.view {
view.alpha = 0.75
}
_menuViewController.delegate = self
var thePoint = self.view.convertPoint(mainContentRect.origin, toView: UIApplication.sharedApplication().keyWindow)
thePoint.x += (mainContentRect.width / 2.0)
_menuViewController.showMenuView(thePoint)
}
else if sender.state == UIGestureRecognizerState.Ended || sender.state == UIGestureRecognizerState.Cancelled || sender.state == UIGestureRecognizerState.Failed {
if let view = sender.view {
view.alpha = 1.0
}
}
}
func menuItemDidPressed(menuViewController: PonyChatUI.UserInterface.MenuViewController, itemIndex: Int) {
if itemIndex < _menuViewController.titles.count {
let title = _menuViewController.titles[itemIndex]
for item in messagingConfigure.longPressItems {
if item.title == title {
item.executingBlock(message: messageItem, chatViewController: self.messagingViewController!)
}
}
}
}
func handleAvatarTapped() {
if let coreDelegate = coreDelegate, let sender = messageItem.messageSender {
coreDelegate.chatUIRequestOpenUserPage(sender)
}
}
func handleErrorNodeTapped() {
if let coreDelegate = coreDelegate {
coreDelegate.chatUIRequestResendMessage(messageItem)
}
}
}
} | mit |
Jnosh/SwiftBinaryHeapExperiments | Tests/CFBinaryHeapWrapper_Tests.swift | 1 | 1001 | //
// CFBinaryHeapWrapper_Tests.swift
// BinaryHeap
//
// Created by Janosch Hildebrand on 17/10/15.
// Copyright © 2015 Janosch Hildebrand. All rights reserved.
//
import XCTest
import Framework
class CFBinaryHeapWrapper_Tests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
// MARK: Tests
func testInsert() {
runInsertTest(CFBinaryHeapWrapper.self, element: TestElements.referenceElements[0])
}
func testRemove() {
runRemoveTest(CFBinaryHeapWrapper.self, element: TestElements.referenceElements[0])
}
func testRemoveAll() {
runRemoveAllTest(CFBinaryHeapWrapper.self, elements: TestElements.referenceElements)
}
func testOrder() {
runOrderTest(CFBinaryHeapWrapper.self, elements: TestElements.referenceElements)
}
func testCoW() {
runCoWTest(CFBinaryHeapWrapper.self, elements: TestElements.referenceElements)
}
}
| mit |
ThilinaHewagama/Pancha | Pancha/AppDelegate.swift | 1 | 2181 | //
// AppDelegate.swift
// Pancha
//
// Created by Thilina Chamin Hewagama on 3/28/17.
// Copyright © 2017 Pancha iOS. 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:.
}
}
| mit |
cdtschange/SwiftMKit | SwiftMKit/UI/Schema/BaseKitWebViewController.swift | 1 | 28382 | //
// BaseKitWebViewController.swift
// SwiftMKitDemo
//
// Created by Mao on 4/28/16.
// Copyright © 2016 cdts. All rights reserved.
//
import UIKit
import SnapKit
import CocoaLumberjack
import MJRefresh
import WebKit
import WebViewJavascriptBridge
@objcMembers
open class BaseKitWebViewController: BaseKitViewController, WKNavigationDelegate, SharePannelViewDelegate, UIScrollViewDelegate {
struct InnerConst {
static let RootViewBackgroundColor : UIColor = UIColor(hex6: 0xefeff4)
static let WebViewBackgroundColor : UIColor = UIColor.clear
static let PannelTitleColor : UIColor = UIColor.gray
static let BackGroundTitleColor : UIColor = UIColor.darkGray
}
weak var _webView: WKWebView?
public var webView: WKWebView {
if let webV = _webView {
return webV
}
let webV = self.createWebView()
_webView = webV
return webV
}
private func createWebView() -> WKWebView {
let wkContentVc = WKUserContentController()
let cookieScript = WKUserScript(source: "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);", injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
// let wkUScript = WKUserScript.init(source: "", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
wkContentVc.addUserScript(cookieScript)
let config = WKWebViewConfiguration()
config.userContentController = wkContentVc
let _webView = WKWebView(frame: CGRect.zero, configuration: config)
//声明scrollView的位置 添加下面代码
if #available(iOS 11.0, *) {
_webView.scrollView.contentInsetAdjustmentBehavior = .never
}
_webView.backgroundColor = InnerConst.WebViewBackgroundColor
self.view.addSubview(_webView)
if let progressView = self.progressView {
self.view.bringSubview(toFront: progressView)
}
_webView.scrollView.delegate = self
_webView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
return _webView
}
open lazy var webViewBridge: WKWebViewJavascriptBridge = {
var bridge: WKWebViewJavascriptBridge = WKWebViewJavascriptBridge(for: self.webView)
bridge.setWebViewDelegate(self)
return bridge
}()
open var userAgent: String? {
get {
if #available(iOS 9.0, *) {
return webView.customUserAgent
} else {
var ua: String?
let semaphore = DispatchSemaphore(value: 0)
webView.evaluateJavaScript("navigator.userAgent", completionHandler: { (result, error) in
ua = result as? String
semaphore.signal()
})
semaphore.wait()
return ua
}
}
set(value) {
if #available(iOS 9.0, *) {
webView.customUserAgent = value
} else {
webView.evaluateJavaScript("navigator.userAgent") { [weak self] (result, error) in
UserDefaults.standard.register(defaults: ["UserAgent": value ?? ""])
if let wv = self?.createWebView() {
self?._webView = wv
_ = self?.webViewBridge
self?.webView.evaluateJavaScript("navigator.userAgent", completionHandler: {_,_ in})
}
}
}
}
}
open var requestHeader: [String: String]? {
get {
return nil
}
}
open var progressView : UIProgressView?
let keyPathForProgress : String = "estimatedProgress"
let keyPathForTitle : String = "title"
open var needBackRefresh:Bool = false
open var disableUserSelect = false
open var disableLongTouch = false
open var showRefreshHeader: Bool = true
open var showBackgroundLab:Bool = true
open var showNavigationBarTopLeftCloseButton: Bool = true
open var shouldAllowRirectToUrlInView: Bool = true
open var showNavRightToolPannelItem: Bool = true {
didSet {
self.refreshNavigationBarTopRightMoreButton()
}
}
open var recordOffset: Bool = true
open static var webOffsets: [String: CGFloat] = [:]
open var url: String?
open var moreUrlTitle: String? {
get {
if let host = URL(string: url ?? "")?.host {
return host
}
return url
}
}
private var isTitleFixed: Bool = false
var webViewToolsPannelView :SharePannelView?
var needRefreshCallBack: WVJBResponseCallback?
var isAutoUpdateTitle:Bool = true
///跳转前用
var beforRouteBlock:(() -> UIViewController?)?
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
webViewToolsPannelView?.tappedCancel()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if needBackRefresh { //跳转到原生页面,返回时是否需要刷新
needBackRefresh = false
self.loadData()
}
if let needRefreshCallBack = needRefreshCallBack { //如果有刷新回调,调用之
needRefreshCallBack(nil)
self.needRefreshCallBack = nil
}
}
/// webView加载失败后,显示网络错误页面(如果有)
open func setupBadNetworkView() -> UIView? {
return nil
}
private var isBadNetwork = false
private func showBadNetworkView() {
guard let badNetwork_view = setupBadNetworkView() else { return }
guard badNetwork_view.superview == nil else { return }
badNetwork_view.frame = view.bounds
view.addSubview(badNetwork_view)
}
private func removeBadNetworkView() {
if let badNetwork_view = setupBadNetworkView() {
badNetwork_view.removeFromSuperview()
}
}
open override func setupUI() {
super.setupUI()
NetworkListener.listen()
isTitleFixed = (self.title?.length ?? 0) > 0
self.view.backgroundColor = InnerConst.RootViewBackgroundColor
if showBackgroundLab {
self.view.addSubview(self.getBackgroundLab())
}
progressView = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.screenW, height: 0))
progressView?.trackTintColor = UIColor.clear
self.view.addSubview(progressView!)
webView.addObserver(self, forKeyPath: keyPathForProgress, options: [NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.old], context: nil)
webView.addObserver(self, forKeyPath: keyPathForTitle, options: [NSKeyValueObservingOptions.new], context: nil)
_ = self.webViewBridge
bindEvents()
if showRefreshHeader {
self.webView.scrollView.mj_header = self.webViewWithRefreshingBlock { [weak self] in
self?.loadData()
}
}
loadData()
NetworkListener.networkStatus.producer.startWithValues {[weak self](sender) in
if sender == .reachableViaWWAN || sender == .reachableViaWiFi {
DDLogInfo("[Network Status] WIFI或者蜂窝网络, status: \(sender)")
if self?.isBadNetwork == true {
self?.isBadNetwork = false
self?.removeBadNetworkView()
self?.loadData()
}
} else {
DDLogInfo("[Network Status] 无网络, status: \(sender)")
self?.isBadNetwork = true
self?.showBadNetworkView()
}
}
}
open override func setupNavigation() {
super.setupNavigation()
if let btnBack = navBtnBack() {
self.navigationItem.leftBarButtonItems = [btnBack]
}
self.refreshNavigationBarTopRightMoreButton()
}
open func webViewWithRefreshingBlock(_ refreshingBlock:@escaping MJRefreshComponentRefreshingBlock)->MJRefreshHeader{
let header = MJRefreshNormalHeader(refreshingBlock:refreshingBlock);
header?.activityIndicatorViewStyle = .gray
header?.labelLeftInset = 0
header?.setTitle("", for: .idle)
header?.setTitle("", for: .pulling)
header?.setTitle("", for: .refreshing)
header?.lastUpdatedTimeLabel.text = ""
header?.lastUpdatedTimeText = { _ in return "" }
return header!
}
open override func loadData() {
super.loadData()
if url != nil {
requestUrl(url: self.url)
}
}
open func requestUrl(url: String?) {
let url = url?.trimmingCharacters(in: .whitespaces) //去除前后空格
guard let urlStr = url, urlStr.length > 0 ,let urlResult = URL(string: urlStr), UIApplication.shared.canOpenURL(urlResult) else {
DDLogError("Request Invalid Url: \(url ?? "")")
return
}
DDLogInfo("Request url: \(urlStr)")
//清除旧数据
webView.evaluateJavaScript("document.body.innerHTML='';") { [weak self] _,_ in
let request = URLRequest(url: urlResult)
if let request = self?.willLoadRequest(request) {
self?.webView.load(request)
}
}
}
open func willLoadRequest(_ request: URLRequest) -> URLRequest {
var request = request
if let header = requestHeader {
for (key, value) in header {
request.setValue(value, forHTTPHeaderField: key)
}
}
return request
}
///是否需要跳到热修复,只给 goToSomewhere用
///可以在自己项目中重写该方法
func needRouteHotfix(controllerName:String, params:[String:Any]? = [:], pop:Bool? = false, needBlock:()->(), notNeedBlock:()->()) {
//默认不需要热修复
notNeedBlock()
///重写示例
// let needRouteHotfix:Bool
// if needRouteHotfix {
// needBlock()
// }else {
// notNeedBlock()
// }
}
open func bindEvents() {
/**
* H5跳转到任意原生页面
* 事件名:goToSomewhere
* 参数:
* name:String 用.分割sbName和vcName,例如: sbName.vcName
* refresh:Bool 跳转到原生页面,返回时是否需要刷新
* pop:Bool 是否present方式弹出
* params:[String:Any] 作为控制器的params
*/
self.bindEvent("goToSomewhere", handler: { [weak self] data , responseCallback in
if let dic = data as? [String:Any] {
if let name = dic["name"] as? String , name.length > 0{
//获得Controller名和Sb名
var (sbName,vcName) = (self?.getVcAndSbName(name: name) ?? (nil,nil))
if let vcName = vcName , vcName.length > 0 {
let refresh = (dic["refresh"] as? Bool) ?? false
let pop = (dic["pop"] as? Bool) ?? false
sbName = (sbName?.length ?? 0) > 0 ? sbName : nil
//是否是热切换页面
self?.needRouteHotfix(controllerName:vcName,
params:dic["params"] as? [String:Any],
pop:pop,
needBlock: {
self?.needBackRefresh = refresh
self?.needRefreshCallBack = responseCallback
}, notNeedBlock: {
if let vc = self?.initialedViewController(vcName, storyboardName: sbName){
//获得需要的参数
let paramsDic = dic["params"] as? [String:Any]
self?.setObjectParams(vc: vc, paramsDic: paramsDic)
self?.needBackRefresh = refresh
self?.needRefreshCallBack = responseCallback
if let topViewController = self?.beforRouteBlock?() {
topViewController.toNextViewController(viewController: vc, pop: pop)
}else {
self?.toNextViewController(viewController: vc, pop: pop)
}
}
})
}
}
}
})
/**
* H5给Native的单例或者静态变量赋值,
* 不支持同时改变静态属性和成员变量。需要调用多次依次修改
* 事件名: changeVariables
* 参数:
* name:String 用.分割类名和单例变量名,例如: BaseService.sharedBaseService(.sharedBaseService为空时,表示修改静态属性)
* params:[String:Any] 要修改的参数列表 (注意:修改静态属性时params中的key一定是存在的静态属性,否则会奔溃,因为无法映射静态属性列表判断有无该属性)
*/
self.bindEvent("changeVariables", handler: {[weak self] data , responseCallback in
if let dic = data as? [String:Any] {
if let name = dic["name"] as? String, let paramsDic = dic["params"] as? [String:Any], name.length > 0{
let (className , instanceName):(String?,String?) = (self?.getClassAndInstance(name: name) ?? (nil,nil))
guard let objcName = className ,objcName.length > 0 else{
return
}
guard let instanceClass:NSObject.Type = NSObject.fullClassName(objcName) else { return }
if let instanceKey = instanceName ,instanceKey.length > 0{ //单例赋值
if let instance:NSObject = instanceClass.value(forKey: instanceKey) as? NSObject {
SwiftReflectionTool.setParams(paramsDic, for: instance)
}
}else { //静态属性赋值
for (key,value) in paramsDic {
instanceClass.setValue(value, forKey: key)
}
}
}
}
})
}
open func bindEvent(_ eventName: String, handler: @escaping WVJBHandler) {
webViewBridge.registerHandler(eventName, handler: handler)
}
/** 计算进度条 */
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if ((object as AnyObject).isEqual(webView) && ((keyPath ?? "") == keyPathForProgress)) {
let newProgress = (change?[NSKeyValueChangeKey.newKey] as AnyObject).floatValue ?? 0
let oldProgress = (change?[NSKeyValueChangeKey.oldKey] as AnyObject).floatValue ?? 0
if newProgress < oldProgress {
return
}
if newProgress >= 1 {
Async.main({ [weak self] in
self?.progressView?.isHidden = true
self?.progressView?.setProgress(0, animated: false)
})
} else {
Async.main({ [weak self] in
self?.progressView?.isHidden = false
self?.progressView?.setProgress(newProgress, animated: true)
})
}
} else if ((object as AnyObject).isEqual(webView) && ((keyPath ?? "") == keyPathForTitle)) {
if isAutoUpdateTitle {
if (!isTitleFixed && (object as AnyObject).isEqual(webView)) {
self.title = self.webView.title;
}
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void){
//存储返回的cookie
if let response = navigationResponse.response as? HTTPURLResponse, let url = response.url{
let cookies = HTTPCookie.cookies(withResponseHeaderFields: (response.allHeaderFields as? [String : String]) ?? [:] , for: url)
for cookie in cookies {
// DDLogInfo("保存的ResponseCookie Name:\(cookie.name) value:\(cookie.value)")
HTTPCookieStorage.shared.setCookie(cookie)
}
}
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
var ret = true
let urlStr = navigationAction.request.url?.absoluteString.removingPercentEncoding
if shouldAllowRirectToUrlInView {
DDLogInfo("Web view direct to url: \(urlStr ?? "")")
ret = true
} else {
DDLogWarn("Web view direct to url forbidden: \(urlStr ?? "")")
ret = false
}
//1.0 判断是不是打开App Store
if urlStr?.hasPrefix("itms-appss://") == true || urlStr?.hasPrefix("itms-apps://") == true{
if let url = navigationAction.request.url {
UIApplication.shared.openURL(url)
ret = false
}
}else if urlStr?.hasPrefix("http") == false && urlStr?.hasPrefix("https") == false{ // 2.0 判断是不是打开其他app,例如支付宝
if let url = navigationAction.request.url {
UIApplication.shared.openURL(url)
ret = false
}
}
//2.0 Cookie
//获得cookie
var cookStr = ""
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
cookStr += "document.cookie = '\(cookie.name)=\(cookie.value);domain=\(cookie.domain);sessionOnly=\(cookie.isSessionOnly);path=\(cookie.path);isSecure=\(cookie.isSecure)';"
}
}
//设置cookie
if cookStr.length > 0 {
let sc = WKUserScript(source:cookStr, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
webView.configuration.userContentController.addUserScript(sc)
}
if (navigationAction.targetFrame == nil) { //新窗口打不开的bug
webView.load(navigationAction.request)
}
refreshNavigationBarTopLeftCloseButton()
decisionHandler(ret ? .allow : .cancel)
}
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if let header = self.webView.scrollView.mj_header {
header.endRefreshing()//结束下拉刷新
}
if disableUserSelect {
webView.evaluateJavaScript("document.documentElement.style.webkitUserSelect='none';") {_,_ in}
}
if disableLongTouch {
webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';") {_,_ in}
}
refreshNavigationBarTopLeftCloseButton()
url = webView.url?.absoluteString
if recordOffset {
if let offset = BaseKitWebViewController.webOffsets[url ?? ""] {
webView.scrollView.setContentOffset(CGPoint(x: 0, y: offset), animated: false)
}
}
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
let tip = error.localizedDescription
if ((error as NSError).code == URLError.cancelled.rawValue){
return
}
self.showTip(tip)
showBadNetworkView()
}
open func refreshNavigationBarTopLeftCloseButton() {
if showNavigationBarTopLeftCloseButton {
if webView.canGoBack {
if self.navigationItem.leftBarButtonItems != nil {
if let btnBack = navBtnBack() {
if let btnClose = navBtnClose() {
self.navigationItem.leftBarButtonItems = [btnBack, btnClose]
}
}
}
} else {
if let btnBack = navBtnBack() {
self.navigationItem.leftBarButtonItems = [btnBack]
}
}
}
}
open func refreshNavigationBarTopRightMoreButton() {
if showNavRightToolPannelItem {
if let btnMore : UIBarButtonItem = navBtnMore() {
self.navigationItem.rightBarButtonItem = btnMore
}
} else {
self.navigationItem.rightBarButtonItem = nil
}
}
open func navBtnBack() -> UIBarButtonItem? {
if let btnBack = self.navigationItem.leftBarButtonItems?.first {
return btnBack
}
return UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(BaseKitWebViewController.click_nav_back(_:)))
}
open func navBtnClose() -> UIBarButtonItem? {
return UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(BaseKitWebViewController.click_nav_close(_:)))
}
open func navBtnMore() -> UIBarButtonItem? {
return UIBarButtonItem(title: "•••", style: .plain, target: self, action: #selector(BaseKitWebViewController.click_nav_more(_:)))
}
open func getToolMoreHeaderView() -> UIView {
let labHeaderView : UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.w, height: 30))
labHeaderView.clipsToBounds = true
if let urlTitle = moreUrlTitle {
labHeaderView.font = UIFont.systemFont(ofSize: 10)
labHeaderView.text = "网页由 \(urlTitle) 提供"
labHeaderView.textColor = InnerConst.PannelTitleColor
labHeaderView.textAlignment = NSTextAlignment.center
} else {
labHeaderView.h = 0
}
return labHeaderView
}
open func getBackgroundLab() -> UIView {
let labBackground : UILabel = UILabel(frame: CGRect(x: 0, y: 10, width: self.screenW, height: 30))
labBackground.clipsToBounds = true
if let urlTitle = moreUrlTitle {
labBackground.font = UIFont.systemFont(ofSize: 10)
labBackground.text = "网页由 \(urlTitle) 提供"
labBackground.textColor = InnerConst.BackGroundTitleColor
labBackground.textAlignment = NSTextAlignment.center
} else {
labBackground.h = 0
}
return labBackground
}
@objc open func click_nav_back(_ sender: UIBarButtonItem) {
if webView.canGoBack {
webView.goBack()
} else {
self.routeBack()
}
}
@objc open func click_nav_close(_ sender: UIBarButtonItem) {
self.routeBack()
}
@objc open func click_nav_more(_ sender: UIBarButtonItem) {
webViewToolsPannelView = SharePannelView(frame: CGRect(x: 0, y: 0, width: self.view.w, height: self.view.h+64))
webViewToolsPannelView?.delegate = self
webViewToolsPannelView!.headerView = getToolMoreHeaderView()
webViewToolsPannelView!.toolsArray =
[[
ToolsModel(image: "pannel_icon_safari", highlightedImage: "pannel_icon_safari", title: "在Safari中\n打开", shareObjectType: .webPage, used: .openBySafari),
ToolsModel(image: "pannel_icon_link", highlightedImage: "pannel_icon_link", title: "复制链接",shareObjectType: .webPage, used: .copyLink),
ToolsModel(image: "pannel_icon_refresh", highlightedImage: "pannel_icon_refresh", title: "刷新",shareObjectType: .webPage, used: .webRefresh)]]
self.navigationController?.view.addSubview(webViewToolsPannelView!)
}
//MARK : - WebViewToolsPannelViewDelegate
func sharePannelViewButtonAction(_ webViewToolsPannelView: SharePannelView, model: ToolsModel) {
switch model.used {
case .openBySafari:
if #available(iOS 10.0, *) {
UIApplication.shared.open((webView.url)!, options: [:], completionHandler: nil)
}else{
UIApplication.shared.openURL((webView.url)!)
}
break
case .copyLink:
UIPasteboard.general.string = url
self.showTip("已复制链接到剪切版")
break
case .webRefresh:
if showRefreshHeader {
self.webView.scrollView.mj_header.beginRefreshing()
}else{
webView.reload()
}
break
default:
break
}
}
fileprivate func saveWebOffsetY (_ scrollView : UIScrollView){
if let key_url = url {
BaseKitWebViewController.webOffsets[key_url] = scrollView.contentOffset.y
}
}
//MARK : - ScrollViewDelegate
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.saveWebOffsetY(scrollView)
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.saveWebOffsetY(scrollView)
}
//MARK: - Priavte
//MARK:用.分割vcName和sbName
func getVcAndSbName(name:String) -> (String?,String?) {
let nameList = name.split(".")
var vcName:String?
var sbName:String?
if nameList.count >= 2 {
sbName = nameList.first
vcName = nameList[1]
}else if nameList.count == 1 {
vcName = nameList.first
sbName = nil
}
return (sbName,vcName)
}
//MARK:用.分割 类名和单例名
func getClassAndInstance(name:String) -> (String?,String?) {
let nameList = name.split(".")
var className:String?
var instanceName:String?
if nameList.count >= 2 {
className = nameList.first
instanceName = nameList[1]
}else if nameList.count == 1 {
className = nameList.first
}
return (className,instanceName)
}
//MARK: 给对象赋值 ,传过来的paramsDic是[String:kindOfStirng]
func setObjectParams(vc: NSObject, paramsDic:[String:Any]?) {
if let paramsDic = paramsDic {
for (key,value) in paramsDic {
let type = vc.getTypeOfProperty(key)
if type == NSNull.Type.self{ //未找到
print("VC没有该参数")
}else if type == Bool.self || type == Bool?.self{
let toValue = (value as? String)?.toBool() ?? false
vc.setValue(toValue, forKey: key)
}else if type == Int.self || type == Int?.self{
let toValue = (value as? String)?.toInt() ?? 0
vc.setValue(toValue, forKey: key)
}else if type == Double.self || type == Double?.self{
let toValue = (value as? String)?.toDouble() ?? 0.0
vc.setValue(toValue, forKey: key)
}else if type == Float.self || type == Float?.self{
let toValue = (value as? String)?.toFloat() ?? 0.0
vc.setValue(toValue, forKey: key)
}else {
vc.setValue(value, forKey: key)
}
}
}
}
deinit {
_webView?.removeObserver(self, forKeyPath: keyPathForProgress)
_webView?.removeObserver(self, forKeyPath: keyPathForTitle)
_webView?.scrollView.delegate = nil
}
}
| mit |
apple/swift | validation-test/compiler_crashers_fixed/01218-void.swift | 65 | 704 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 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
right
import Foundation
extension NSSet {
convenience init<T>(array: Array<T>) {
self.init()
}
}
mutating
func n<p>() -> (p, p -> p) -> p {
b, l]
g(o(q))
h e {
j class func r()
}
class k: h{ class func r {}
var = 1
var s: r -> r t -> r) -> r m
u h>] {
u []
}
func r(e: () -> ()) {
}
class n {
var _ = r
| apache-2.0 |
Fluci/CPU-Spy | CPU Spy/lib/Icon/Protocols/IconDrawerDelegate.swift | 1 | 250 | //
// IconDrawerDelegate.swift
// CPU Spy
//
// Created by Felice Serena on 24.01.16.
// Copyright © 2016 Serena. All rights reserved.
//
import Foundation
public protocol IconDrawerDelegate {
func willRedraw(sender: IconDrawer) -> Bool
}
| mit |
KyoheiG3/RxSwift | Tests/RxCocoaTests/ControlEventTests.swift | 8 | 1261 | //
// ControlEventTests.swift
// Tests
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import XCTest
class ControlEventTests : RxTest {
func testObservingIsAlwaysHappeningOnMainQueue() {
let hotObservable = MainThreadPrimitiveHotObservable<Int>()
var observedOnMainQueue = false
let expectSubscribeOffMainQueue = expectation(description: "Did subscribe off main thread")
let controlProperty = ControlEvent(events: Observable.deferred { () -> Observable<Int> in
XCTAssertTrue(DispatchQueue.isMain)
observedOnMainQueue = true
return hotObservable.asObservable()
})
doOnBackgroundQueue {
let d = controlProperty.asObservable().subscribe { n in
}
let d2 = controlProperty.subscribe { n in
}
doOnMainQueue {
d.dispose()
d2.dispose()
expectSubscribeOffMainQueue.fulfill()
}
}
waitForExpectations(timeout: 1.0) { error in
XCTAssertNil(error)
}
XCTAssertTrue(observedOnMainQueue)
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/25119-swift-constraints-constraintsystem-finalize.swift | 7 | 197 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class b<T{class c:b
let f=(
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/18321-no-stacktrace.swift | 11 | 250 | // 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 {
class b {
let a {
{
for {
{
{
protocol b {
class
case c,
case
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/14571-swift-sourcemanager-getmessage.swift | 11 | 209 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a {
var d = ( {
for
{
class
case ,
| mit |
limsangjin12/Hero | Sources/Extensions/UIKit+Hero.swift | 4 | 2130 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <me@lkzhao.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
fileprivate let parameterRegex = "(?:\\-?\\d+(\\.?\\d+)?)|\\w+"
fileprivate let modifiersRegex = "(\\w+)(?:\\(([^\\)]*)\\))?"
internal extension NSObject {
func copyWithArchiver() -> Any? {
return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))!
}
}
internal extension UIImage {
class func imageWithView(view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
internal extension UIColor {
var components:(r:CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
var alphaComponent: CGFloat {
return components.a
}
}
| mit |
subangstrom/Ronchi | Ronchi/Potential.swift | 2 | 209 | //
// Potential.swift
// Ronchigram
//
// Created by James LeBeau on 5/24/17.
// Copyright © 2017 The Handsome Microscopist. All rights reserved.
//
import Foundation
class Potential: NSObject {
}
| gpl-3.0 |
alloy/realm-cocoa | Realm/Tests/Swift/SwiftLinkTests.swift | 1 | 7902 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
class SwiftLinkTests: SwiftTestCase {
// Swift models
func testBasicLink() {
let realm = realmWithTestPath()
let owner = SwiftOwnerObject()
owner.name = "Tim"
owner.dog = SwiftDogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
let owners = SwiftOwnerObject.allObjectsInRealm(realm)
let dogs = SwiftDogObject.allObjectsInRealm(realm)
XCTAssertEqual(owners.count, 1, "Expecting 1 owner")
XCTAssertEqual(dogs.count, 1, "Expecting 1 dog")
XCTAssertEqual((owners[0] as SwiftOwnerObject).name, "Tim", "Tim is named Tim")
XCTAssertEqual((dogs[0] as SwiftDogObject).dogName, "Harvie", "Harvie is named Harvie")
let tim = owners[0] as SwiftOwnerObject
XCTAssertEqual(tim.dog.dogName, "Harvie", "Tim's dog should be Harvie")
}
func testMultipleOwnerLink() {
let realm = realmWithTestPath()
let owner = SwiftOwnerObject()
owner.name = "Tim"
owner.dog = SwiftDogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, 1, "Expecting 1 owner")
XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, 1, "Expecting 1 dog")
realm.beginWriteTransaction()
let fiel = SwiftOwnerObject.createInRealm(realm, withObject: ["Fiel", NSNull()])
fiel.dog = owner.dog
realm.commitWriteTransaction()
XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, 2, "Expecting 2 owners")
XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, 1, "Expecting 1 dog")
}
func testLinkRemoval() {
let realm = realmWithTestPath()
let owner = SwiftOwnerObject()
owner.name = "Tim"
owner.dog = SwiftDogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
XCTAssertEqual(SwiftOwnerObject.allObjectsInRealm(realm).count, 1, "Expecting 1 owner")
XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, 1, "Expecting 1 dog")
realm.beginWriteTransaction()
realm.deleteObject(owner.dog)
realm.commitWriteTransaction()
XCTAssertNil(owner.dog, "Dog should be nullified when deleted")
// refresh owner and check
let owner2 = SwiftOwnerObject.allObjectsInRealm(realm).firstObject
XCTAssertNotNil(owner, "Should have 1 owner")
XCTAssertNil(owner.dog, "Dog should be nullified when deleted")
XCTAssertEqual(SwiftDogObject.allObjectsInRealm(realm).count, 0, "Expecting 0 dogs")
}
// FIXME - disabled until we fix commit log issue which break transacions when leaking realm objects
// func testCircularLinks() {
// let realm = realmWithTestPath()
//
// let obj = SwiftCircleObject()
// obj.data = "a"
// obj.next = obj
//
// realm.beginWriteTransaction()
// realm.addObject(obj)
// obj.next.data = "b"
// realm.commitWriteTransaction()
//
// let obj2 = SwiftCircleObject.allObjectsInRealm(realm).firstObject() as SwiftCircleObject
// XCTAssertEqual(obj2.data, "b", "data should be 'b'")
// XCTAssertEqual(obj2.data, obj2.next.data, "objects should be equal")
// }
// Objective-C models
func testBasicLink_objc() {
let realm = realmWithTestPath()
let owner = OwnerObject()
owner.name = "Tim"
owner.dog = DogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
let owners = OwnerObject.allObjectsInRealm(realm)
let dogs = DogObject.allObjectsInRealm(realm)
XCTAssertEqual(owners.count, 1, "Expecting 1 owner")
XCTAssertEqual(dogs.count, 1, "Expecting 1 dog")
XCTAssertEqual((owners[0] as OwnerObject).name!, "Tim", "Tim is named Tim")
XCTAssertEqual((dogs[0] as DogObject).dogName!, "Harvie", "Harvie is named Harvie")
let tim = owners[0] as OwnerObject
XCTAssertEqual(tim.dog.dogName!, "Harvie", "Tim's dog should be Harvie")
}
func testMultipleOwnerLink_objc() {
let realm = realmWithTestPath()
let owner = OwnerObject()
owner.name = "Tim"
owner.dog = DogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, 1, "Expecting 1 owner")
XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, 1, "Expecting 1 dog")
realm.beginWriteTransaction()
let fiel = OwnerObject.createInRealm(realm, withObject: ["Fiel", NSNull()])
fiel.dog = owner.dog
realm.commitWriteTransaction()
XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, 2, "Expecting 2 owners")
XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, 1, "Expecting 1 dog")
}
func testLinkRemoval_objc() {
let realm = realmWithTestPath()
let owner = OwnerObject()
owner.name = "Tim"
owner.dog = DogObject()
owner.dog.dogName = "Harvie"
realm.beginWriteTransaction()
realm.addObject(owner)
realm.commitWriteTransaction()
XCTAssertEqual(OwnerObject.allObjectsInRealm(realm).count, 1, "Expecting 1 owner")
XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, 1, "Expecting 1 dog")
realm.beginWriteTransaction()
realm.deleteObject(owner.dog)
realm.commitWriteTransaction()
XCTAssertNil(owner.dog, "Dog should be nullified when deleted")
// refresh owner and check
let owner2 = OwnerObject.allObjectsInRealm(realm).firstObject
XCTAssertNotNil(owner, "Should have 1 owner")
XCTAssertNil(owner.dog, "Dog should be nullified when deleted")
XCTAssertEqual(DogObject.allObjectsInRealm(realm).count, 0, "Expecting 0 dogs")
}
// FIXME - disabled until we fix commit log issue which break transacions when leaking realm objects
// func testCircularLinks_objc() {
// let realm = realmWithTestPath()
//
// let obj = CircleObject()
// obj.data = "a"
// obj.next = obj
//
// realm.beginWriteTransaction()
// realm.addObject(obj)
// obj.next.data = "b"
// realm.commitWriteTransaction()
//
// let obj2 = CircleObject.allObjectsInRealm(realm).firstObject() as CircleObject
// XCTAssertEqual(obj2.data, "b", "data should be 'b'")
// XCTAssertEqual(obj2.data, obj2.next.data, "objects should be equal")
// }
}
| apache-2.0 |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor/ProfileEditorHeaderView.swift | 1 | 22156 | //
// ProfileEditorHeaderView.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
class ProfileEditorHeaderView: NSObject {
// MARK: -
// MARK: Variables
weak var profile: Profile?
let headerView = NSView()
let textFieldTitle = NSTextField()
let textFieldTitleTopIndent: CGFloat = 28.0
let textFieldDescription = NSTextField()
let textFieldDescriptionTopIndent: CGFloat = 4.0
let textFieldPlatforms = NSTextField()
let textFieldScope = NSTextField()
let popUpButtonAppVersion = NSPopUpButton()
let imageViewIcon = NSImageView()
let buttonAddRemove = NSButton()
let buttonTitleEnable = NSLocalizedString("Add", comment: "")
let buttonTitleDisable = NSLocalizedString("Remove", comment: "")
var height: CGFloat = 0.0
var layoutConstraintHeight: NSLayoutConstraint?
weak var selectedPayloadPlaceholder: PayloadPlaceholder?
weak var profileEditor: ProfileEditor?
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(profile: Profile) {
super.init()
// ---------------------------------------------------------------------
// Setup Variables
// ---------------------------------------------------------------------
self.profile = profile
var constraints = [NSLayoutConstraint]()
// ---------------------------------------------------------------------
// Setup Notification Observers
// ---------------------------------------------------------------------
NotificationCenter.default.addObserver(self, selector: #selector(self.didChangePayloadSelected(_:)), name: .didChangePayloadSelected, object: nil)
// ---------------------------------------------------------------------
// Add subviews to headerView
// ---------------------------------------------------------------------
self.setupHeaderView(constraints: &constraints)
self.setupTextFieldTitle(constraints: &constraints)
self.setupTextFieldDescription(constraints: &constraints)
self.setupTextFieldPlatforms(constraints: &constraints)
self.setupTextFieldScope(constraints: &constraints)
self.setupPopUpButtonAppVersion(constraints: &constraints)
self.setupButtonAddRemove(constraints: &constraints)
// ---------------------------------------------------------------------
// Activate layout constraints
// ---------------------------------------------------------------------
NSLayoutConstraint.activate(constraints)
}
// MARK: -
// MARK: Private Functions
private func updateHeight(_ height: CGFloat) {
self.height += height
}
// MARK: -
// MARK: Functions
@objc func didChangePayloadSelected(_ notification: NSNotification?) {
guard
let userInfo = notification?.userInfo,
let payloadPlaceholder = userInfo[NotificationKey.payloadPlaceholder] as? PayloadPlaceholder,
let selected = userInfo[NotificationKey.payloadSelected] as? Bool else { return }
if self.selectedPayloadPlaceholder == payloadPlaceholder {
self.setButtonState(enabled: selected)
}
}
func setButtonState(enabled: Bool) {
if enabled {
self.buttonAddRemove.attributedTitle = NSAttributedString(string: self.buttonTitleDisable, attributes: [ .foregroundColor: NSColor.systemRed ])
} else {
self.buttonAddRemove.title = self.buttonTitleEnable // attributedTitle = NSAttributedString(string: "Add", attributes: [ NSAttributedStringKey.foregroundColor : NSColor.green ])
}
}
@objc func clicked(button: NSButton) {
if let selectedPayloadPlaceholder = self.selectedPayloadPlaceholder {
NotificationCenter.default.post(name: .changePayloadSelected, object: self, userInfo: [NotificationKey.payloadPlaceholder: selectedPayloadPlaceholder ])
}
}
@objc func toggleTitle(sender: NSGestureRecognizer) {
if let toolTip = self.textFieldTitle.toolTip {
self.textFieldTitle.toolTip = self.textFieldTitle.stringValue
self.textFieldTitle.stringValue = toolTip
}
}
func select(payloadPlaceholder: PayloadPlaceholder) {
if self.selectedPayloadPlaceholder != payloadPlaceholder {
self.selectedPayloadPlaceholder = payloadPlaceholder
// Hide button if it's the general settings
if payloadPlaceholder.payloadType == .custom || ( payloadPlaceholder.domain == kManifestDomainConfiguration && payloadPlaceholder.payloadType == .manifestsApple ) {
self.buttonAddRemove.isHidden = true
} else if let profile = self.profile {
self.buttonAddRemove.isHidden = false
self.setButtonState(enabled: profile.settings.isIncludedInProfile(payload: payloadPlaceholder.payload))
} else {
self.buttonAddRemove.isHidden = true
}
self.textFieldTitle.stringValue = payloadPlaceholder.title
if payloadPlaceholder.domain != kManifestDomainConfiguration {
self.textFieldTitle.toolTip = payloadPlaceholder.domain
} else { self.textFieldTitle.toolTip = nil }
self.textFieldDescription.stringValue = payloadPlaceholder.description
self.popUpButtonAppVersion.removeAllItems()
if payloadPlaceholder.payloadType == .managedPreferencesApplications, let payload = payloadPlaceholder.payload as? PayloadManagedPreference {
if let appVersions = payload.appVersions {
self.popUpButtonAppVersion.addItems(withTitles: appVersions)
}
}
self.textFieldPlatforms.stringValue = PayloadUtility.string(fromPlatforms: payloadPlaceholder.payload.platforms, separator: " ")
self.textFieldScope.stringValue = PayloadUtility.string(fromTargets: payloadPlaceholder.payload.targets, separator: " ")
}
}
}
// MARK: -
// MARK: Setup NSLayoutConstraints
extension ProfileEditorHeaderView {
private func setupHeaderView(constraints: inout [NSLayoutConstraint]) {
self.headerView.translatesAutoresizingMaskIntoConstraints = false
}
private func setupButtonAddRemove(constraints: inout [NSLayoutConstraint]) {
self.buttonAddRemove.translatesAutoresizingMaskIntoConstraints = false
self.buttonAddRemove.title = self.buttonTitleEnable
self.buttonAddRemove.bezelStyle = .roundRect
self.buttonAddRemove.setButtonType(.momentaryPushIn)
self.buttonAddRemove.isBordered = true
self.buttonAddRemove.isTransparent = false
self.buttonAddRemove.action = #selector(self.clicked(button:))
self.buttonAddRemove.target = self
// ---------------------------------------------------------------------
// Add Button to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.buttonAddRemove)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.buttonAddRemove,
attribute: .top,
relatedBy: .equal,
toItem: self.headerView,
attribute: .top,
multiplier: 1.0,
constant: self.textFieldTitleTopIndent))
// Trailing
constraints.append(NSLayoutConstraint(item: self.headerView,
attribute: .trailing,
relatedBy: .equal,
toItem: self.buttonAddRemove,
attribute: .trailing,
multiplier: 1.0,
constant: 24.0))
}
private func setupTextFieldPlatforms(constraints: inout [NSLayoutConstraint]) {
self.textFieldPlatforms.translatesAutoresizingMaskIntoConstraints = false
self.textFieldPlatforms.lineBreakMode = .byWordWrapping
self.textFieldPlatforms.isBordered = false
self.textFieldPlatforms.isBezeled = false
self.textFieldPlatforms.drawsBackground = false
self.textFieldPlatforms.isEditable = false
self.textFieldPlatforms.isSelectable = false
self.textFieldPlatforms.textColor = .secondaryLabelColor
self.textFieldPlatforms.preferredMaxLayoutWidth = kEditorTableViewColumnPayloadWidth
self.textFieldPlatforms.alignment = .right
self.textFieldPlatforms.font = NSFont.systemFont(ofSize: 12, weight: .regular)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.textFieldPlatforms)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.textFieldPlatforms,
attribute: .top,
relatedBy: .equal,
toItem: self.buttonAddRemove,
attribute: .bottom,
multiplier: 1.0,
constant: 6.0))
// Width
constraints.append(NSLayoutConstraint(item: self.textFieldPlatforms,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 97.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.headerView,
attribute: .trailing,
relatedBy: .equal,
toItem: self.textFieldPlatforms,
attribute: .trailing,
multiplier: 1.0,
constant: 24.0))
}
private func setupTextFieldScope(constraints: inout [NSLayoutConstraint]) {
self.textFieldScope.translatesAutoresizingMaskIntoConstraints = false
self.textFieldScope.lineBreakMode = .byWordWrapping
self.textFieldScope.isBordered = false
self.textFieldScope.isBezeled = false
self.textFieldScope.drawsBackground = false
self.textFieldScope.isEditable = false
self.textFieldScope.isSelectable = false
self.textFieldScope.textColor = .secondaryLabelColor
self.textFieldScope.preferredMaxLayoutWidth = kEditorTableViewColumnPayloadWidth
self.textFieldScope.alignment = .right
self.textFieldScope.font = NSFont.systemFont(ofSize: 12, weight: .regular)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.textFieldScope)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.textFieldScope,
attribute: .top,
relatedBy: .equal,
toItem: self.textFieldPlatforms,
attribute: .bottom,
multiplier: 1.0,
constant: 1.0))
// Width
constraints.append(NSLayoutConstraint(item: self.textFieldScope,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 76.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.headerView,
attribute: .trailing,
relatedBy: .equal,
toItem: self.textFieldScope,
attribute: .trailing,
multiplier: 1.0,
constant: 24.0))
}
private func setupTextFieldTitle(constraints: inout [NSLayoutConstraint]) {
self.textFieldTitle.translatesAutoresizingMaskIntoConstraints = false
self.textFieldTitle.lineBreakMode = .byWordWrapping
self.textFieldTitle.isBordered = false
self.textFieldTitle.isBezeled = false
self.textFieldTitle.drawsBackground = false
self.textFieldTitle.isEditable = false
self.textFieldTitle.isSelectable = false
self.textFieldTitle.textColor = .labelColor
self.textFieldTitle.alignment = .left
self.textFieldTitle.stringValue = "Title"
self.textFieldTitle.font = NSFont.systemFont(ofSize: 28, weight: .heavy)
self.textFieldTitle.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// ---------------------------------------------------------------------
// Setup GestureRecognizer
// ---------------------------------------------------------------------
let gesture = NSClickGestureRecognizer()
gesture.numberOfClicksRequired = 1
gesture.target = self
gesture.action = #selector(self.toggleTitle(sender:))
self.textFieldTitle.addGestureRecognizer(gesture)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.textFieldTitle)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.textFieldTitle,
attribute: .top,
relatedBy: .equal,
toItem: self.headerView,
attribute: .top,
multiplier: 1.0,
constant: self.textFieldTitleTopIndent))
// Leading
constraints.append(NSLayoutConstraint(item: self.textFieldTitle,
attribute: .leading,
relatedBy: .equal,
toItem: self.headerView,
attribute: .leading,
multiplier: 1.0,
constant: 24.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.textFieldPlatforms,
attribute: .leading,
relatedBy: .equal,
toItem: self.textFieldTitle,
attribute: .trailing,
multiplier: 1.0,
constant: 4.0))
}
private func setupPopUpButtonAppVersion(constraints: inout [NSLayoutConstraint]) {
self.popUpButtonAppVersion.translatesAutoresizingMaskIntoConstraints = false
self.popUpButtonAppVersion.isHidden = true
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.popUpButtonAppVersion)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.popUpButtonAppVersion,
attribute: .centerY,
relatedBy: .equal,
toItem: self.textFieldScope,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.popUpButtonAppVersion,
attribute: .trailing,
relatedBy: .equal,
toItem: self.textFieldScope,
attribute: .leading,
multiplier: 1.0,
constant: 4.0))
}
private func setupTextFieldDescription(constraints: inout [NSLayoutConstraint]) {
self.textFieldDescription.translatesAutoresizingMaskIntoConstraints = false
self.textFieldDescription.lineBreakMode = .byWordWrapping
self.textFieldDescription.isBordered = false
self.textFieldDescription.isBezeled = false
self.textFieldDescription.drawsBackground = false
self.textFieldDescription.isEditable = false
self.textFieldDescription.isSelectable = false
self.textFieldDescription.textColor = .labelColor
self.textFieldDescription.alignment = .left
self.textFieldDescription.stringValue = "Description"
self.textFieldDescription.font = NSFont.systemFont(ofSize: 17, weight: .ultraLight)
self.textFieldDescription.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.textFieldDescription)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.textFieldDescription,
attribute: .top,
relatedBy: .equal,
toItem: self.textFieldTitle,
attribute: .bottom,
multiplier: 1.0,
constant: self.textFieldDescriptionTopIndent))
// Leading
constraints.append(NSLayoutConstraint(item: self.textFieldDescription,
attribute: .leading,
relatedBy: .equal,
toItem: self.headerView,
attribute: .leading,
multiplier: 1.0,
constant: 24.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.textFieldPlatforms,
attribute: .leading,
relatedBy: .equal,
toItem: self.textFieldDescription,
attribute: .trailing,
multiplier: 1.0,
constant: 4.0))
// Bottom
constraints.append(NSLayoutConstraint(item: self.headerView,
attribute: .bottom,
relatedBy: .equal,
toItem: self.textFieldDescription,
attribute: .bottom,
multiplier: 1.0,
constant: 12.0))
//self.updateHeight(description.intrinsicContentSize.height)
}
}
| mit |
TonyStark106/NiceKit | Example/Pods/Siren/Sources/Siren.swift | 1 | 24326 | //
// Siren.swift
// Siren
//
// Created by Arthur Sabintsev on 1/3/15.
// Copyright (c) 2015 Sabintsev iOS Projects. All rights reserved.
//
import UIKit
// MARK: - Siren
/// The Siren Class. A singleton that is initialized using the shared() method.
public final class Siren: NSObject {
/// Current installed version of your app.
internal var currentInstalledVersion: String? = {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}()
/// The error domain for all errors created by Siren.
public let SirenErrorDomain = "Siren Error Domain"
/// The SirenDelegate variable, which should be set if you'd like to be notified:
///
/// When a user views or interacts with the alert
/// - sirenDidShowUpdateDialog(alertType: AlertType)
/// - sirenUserDidLaunchAppStore()
/// - sirenUserDidSkipVersion()
/// - sirenUserDidCancel()
///
/// When a new version has been detected, and you would like to present a localized message in a custom UI. use this delegate method:
/// - sirenDidDetectNewVersionWithoutAlert(message: String)
public weak var delegate: SirenDelegate?
/// The debug flag, which is disabled by default.
/// When enabled, a stream of println() statements are logged to your console when a version check is performed.
public lazy var debugEnabled = false
/// Determines the type of alert that should be shown.
/// See the Siren.AlertType enum for full details.
public var alertType = AlertType.option {
didSet {
majorUpdateAlertType = alertType
minorUpdateAlertType = alertType
patchUpdateAlertType = alertType
revisionUpdateAlertType = alertType
}
}
/// Determines the type of alert that should be shown for major version updates: A.b.c
/// Defaults to Siren.AlertType.option.
/// See the Siren.AlertType enum for full details.
public lazy var majorUpdateAlertType = AlertType.option
/// Determines the type of alert that should be shown for minor version updates: a.B.c
/// Defaults to Siren.AlertType.option.
/// See the Siren.AlertType enum for full details.
public lazy var minorUpdateAlertType = AlertType.option
/// Determines the type of alert that should be shown for minor patch updates: a.b.C
/// Defaults to Siren.AlertType.option.
/// See the Siren.AlertType enum for full details.
public lazy var patchUpdateAlertType = AlertType.option
/// Determines the type of alert that should be shown for revision updates: a.b.c.D
/// Defaults to Siren.AlertType.option.
/// See the Siren.AlertType enum for full details.
public lazy var revisionUpdateAlertType = AlertType.option
/// The name of your app.
/// By default, it's set to the name of the app that's stored in your plist.
public lazy var appName: String = Bundle.main.bestMatchingAppName()
/// The region or country of an App Store in which your app is available.
/// By default, all version checks are performed against the US App Store.
/// If your app is not available in the US App Store, set it to the identifier of at least one App Store within which it is available.
public var countryCode: String?
/// Overrides the default localization of a user's device when presenting the update message and button titles in the alert.
/// See the Siren.LanguageType enum for more details.
public var forceLanguageLocalization: Siren.LanguageType?
/// Overrides the tint color for UIAlertController.
public var alertControllerTintColor: UIColor?
/// When this is set, the alert will only show up if the current version has already been released for X days
/// Defaults to 1 day to avoid an issue where Apple updates the JSON faster than the app binary propogates to the App Store.
public var showAlertAfterCurrentVersionHasBeenReleasedForDays: Int = 1
/// The current version of your app that is available for download on the App Store
public internal(set) var currentAppStoreVersion: String?
internal var updaterWindow: UIWindow?
fileprivate var appID: Int?
fileprivate var lastVersionCheckPerformedOnDate: Date?
fileprivate lazy var alertViewIsVisible: Bool = false
/// The App's Singleton
public static let shared = Siren()
@available(*, deprecated: 1.2.0, unavailable, renamed: "shared")
public static let sharedInstance = Siren()
override init() {
lastVersionCheckPerformedOnDate = UserDefaults.standard.object(forKey: SirenDefaults.StoredVersionCheckDate.rawValue) as? Date
}
/// Checks the currently installed version of your app against the App Store.
/// The default check is against the US App Store, but if your app is not listed in the US,
/// you should set the `countryCode` property before calling this method. Please refer to the countryCode property for more information.
///
/// - Parameters:
/// - checkType: The frequency in days in which you want a check to be performed. Please refer to the Siren.VersionCheckType enum for more details.
public func checkVersion(checkType: VersionCheckType) {
guard let _ = Bundle.bundleID() else {
printMessage(message: "Please make sure that you have set a `Bundle Identifier` in your project.")
return
}
if checkType == .immediately {
performVersionCheck()
} else {
guard let lastVersionCheckPerformedOnDate = lastVersionCheckPerformedOnDate else {
performVersionCheck()
return
}
if Date.days(since: lastVersionCheckPerformedOnDate) >= checkType.rawValue {
performVersionCheck()
} else {
postError(.recentlyCheckedAlready, underlyingError: nil)
}
}
}
}
// MARK: - Helpers (Networking)
private extension Siren {
func performVersionCheck() {
do {
let url = try iTunesURLFromString()
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 30)
URLSession.shared.dataTask(with: request, completionHandler: { [unowned self] (data, response, error) in
self.processResults(withData: data, response: response, error: error)
}).resume()
} catch let error as NSError {
postError(.malformedURL, underlyingError: error)
}
}
func processResults(withData data: Data?, response: URLResponse?, error: Error?) {
if let error = error {
postError(.appStoreDataRetrievalFailure, underlyingError: error)
} else {
guard let data = data else {
postError(.appStoreDataRetrievalFailure, underlyingError: nil)
return
}
do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: [])
guard let appData = jsonData as? [String: Any],
isUpdateCompatibleWithDeviceOS(appData: appData) else {
postError(.appStoreJSONParsingFailure, underlyingError: nil)
return
}
DispatchQueue.main.async { [unowned self] in
// Print iTunesLookup results from appData
self.printMessage(message: "JSON results: \(appData)")
// Process Results (e.g., extract current version that is available on the AppStore)
self.processVersionCheck(with: appData)
}
} catch let error as NSError {
postError(.appStoreDataRetrievalFailure, underlyingError: error)
}
}
}
func processVersionCheck(with payload: [String: Any]) {
storeVersionCheckDate() // Store version comparison date
guard let results = payload[JSONKeys.results] as? [[String: Any]] else {
postError(.appStoreVersionNumberFailure, underlyingError: nil)
return
}
/// Condition satisfied when app not in App Store
guard !results.isEmpty else {
postError(.appStoreDataRetrievalFailure, underlyingError: nil)
return
}
guard let info = results.first else {
postError(.appStoreDataRetrievalFailure, underlyingError: nil)
return
}
guard let appID = info[JSONKeys.appID] as? Int else {
postError(.appStoreAppIDFailure, underlyingError: nil)
return
}
self.appID = appID
guard let currentAppStoreVersion = info[JSONKeys.version] as? String else {
postError(.appStoreVersionArrayFailure, underlyingError: nil)
return
}
self.currentAppStoreVersion = currentAppStoreVersion
guard isAppStoreVersionNewer() else {
delegate?.sirenLatestVersionInstalled()
postError(.noUpdateAvailable, underlyingError: nil)
return
}
guard let currentVersionReleaseDate = info[JSONKeys.currentVersionReleaseDate] as? String,
let daysSinceRelease = Date.days(since: currentVersionReleaseDate) else {
return
}
guard daysSinceRelease >= showAlertAfterCurrentVersionHasBeenReleasedForDays else {
let message = "Your app has been released for \(daysSinceRelease) days, but Siren cannot prompt the user until \(showAlertAfterCurrentVersionHasBeenReleasedForDays) days have passed."
self.printMessage(message: message)
return
}
showAlertIfCurrentAppStoreVersionNotSkipped()
}
func iTunesURLFromString() throws -> URL {
var components = URLComponents()
components.scheme = "https"
components.host = "itunes.apple.com"
components.path = "/lookup"
var items: [URLQueryItem] = [URLQueryItem(name: "bundleId", value: Bundle.bundleID())]
if let countryCode = countryCode {
let item = URLQueryItem(name: "country", value: countryCode)
items.append(item)
}
components.queryItems = items
guard let url = components.url, !url.absoluteString.isEmpty else {
throw SirenError.malformedURL
}
return url
}
}
// MARK: - Helpers (Alert)
private extension Siren {
func showAlertIfCurrentAppStoreVersionNotSkipped() {
alertType = setAlertType()
guard let previouslySkippedVersion = UserDefaults.standard.object(forKey: SirenDefaults.StoredSkippedVersion.rawValue) as? String else {
showAlert()
return
}
if let currentAppStoreVersion = currentAppStoreVersion, currentAppStoreVersion != previouslySkippedVersion {
showAlert()
}
}
func showAlert() {
let updateAvailableMessage = Bundle().localizedString(stringKey: "Update Available", forceLanguageLocalization: forceLanguageLocalization)
let newVersionMessage = localizedNewVersionMessage()
let alertController = UIAlertController(title: updateAvailableMessage, message: newVersionMessage, preferredStyle: .alert)
if let alertControllerTintColor = alertControllerTintColor {
alertController.view.tintColor = alertControllerTintColor
}
switch alertType {
case .force:
alertController.addAction(updateAlertAction())
case .option:
alertController.addAction(nextTimeAlertAction())
alertController.addAction(updateAlertAction())
case .skip:
alertController.addAction(nextTimeAlertAction())
alertController.addAction(updateAlertAction())
alertController.addAction(skipAlertAction())
case .none:
delegate?.sirenDidDetectNewVersionWithoutAlert(message: newVersionMessage)
}
if alertType != .none && !alertViewIsVisible {
alertController.show()
alertViewIsVisible = true
delegate?.sirenDidShowUpdateDialog(alertType: alertType)
}
}
func updateAlertAction() -> UIAlertAction {
let title = localizedUpdateButtonTitle()
let action = UIAlertAction(title: title, style: .default) { [unowned self] _ in
self.hideWindow()
self.launchAppStore()
self.delegate?.sirenUserDidLaunchAppStore()
self.alertViewIsVisible = false
return
}
return action
}
func nextTimeAlertAction() -> UIAlertAction {
let title = localizedNextTimeButtonTitle()
let action = UIAlertAction(title: title, style: .default) { [unowned self] _ in
self.hideWindow()
self.delegate?.sirenUserDidCancel()
self.alertViewIsVisible = false
return
}
return action
}
func skipAlertAction() -> UIAlertAction {
let title = localizedSkipButtonTitle()
let action = UIAlertAction(title: title, style: .default) { [unowned self] _ in
if let currentAppStoreVersion = self.currentAppStoreVersion {
UserDefaults.standard.set(currentAppStoreVersion, forKey: SirenDefaults.StoredSkippedVersion.rawValue)
UserDefaults.standard.synchronize()
}
self.hideWindow()
self.delegate?.sirenUserDidSkipVersion()
self.alertViewIsVisible = false
return
}
return action
}
func setAlertType() -> Siren.AlertType {
guard let currentInstalledVersion = currentInstalledVersion,
let currentAppStoreVersion = currentAppStoreVersion else {
return .option
}
let oldVersion = (currentInstalledVersion).characters.split {$0 == "."}.map { String($0) }.map {Int($0) ?? 0}
let newVersion = (currentAppStoreVersion).characters.split {$0 == "."}.map { String($0) }.map {Int($0) ?? 0}
guard let newVersionFirst = newVersion.first, let oldVersionFirst = oldVersion.first else {
return alertType // Default value is .Option
}
if newVersionFirst > oldVersionFirst { // A.b.c.d
alertType = majorUpdateAlertType
} else if newVersion.count > 1 && (oldVersion.count <= 1 || newVersion[1] > oldVersion[1]) { // a.B.c.d
alertType = minorUpdateAlertType
} else if newVersion.count > 2 && (oldVersion.count <= 2 || newVersion[2] > oldVersion[2]) { // a.b.C.d
alertType = patchUpdateAlertType
} else if newVersion.count > 3 && (oldVersion.count <= 3 || newVersion[3] > oldVersion[3]) { // a.b.c.D
alertType = revisionUpdateAlertType
}
return alertType
}
}
// MARK: - Helpers (Localization)
private extension Siren {
func localizedNewVersionMessage() -> String {
let newVersionMessageToLocalize = "A new version of %@ is available. Please update to version %@ now."
let newVersionMessage = Bundle().localizedString(stringKey: newVersionMessageToLocalize, forceLanguageLocalization: forceLanguageLocalization)
guard let currentAppStoreVersion = currentAppStoreVersion else {
return String(format: newVersionMessage, appName, "Unknown")
}
return String(format: newVersionMessage, appName, currentAppStoreVersion)
}
func localizedUpdateButtonTitle() -> String {
return Bundle().localizedString(stringKey: "Update", forceLanguageLocalization: forceLanguageLocalization)
}
func localizedNextTimeButtonTitle() -> String {
return Bundle().localizedString(stringKey: "Next time", forceLanguageLocalization: forceLanguageLocalization)
}
func localizedSkipButtonTitle() -> String {
return Bundle().localizedString(stringKey: "Skip this version", forceLanguageLocalization: forceLanguageLocalization)
}
}
// MARK: - Helpers (Version)
extension Siren {
func isAppStoreVersionNewer() -> Bool {
var newVersionExists = false
if let currentInstalledVersion = currentInstalledVersion,
let currentAppStoreVersion = currentAppStoreVersion,
(currentInstalledVersion.compare(currentAppStoreVersion, options: .numeric) == .orderedAscending) {
newVersionExists = true
}
return newVersionExists
}
fileprivate func storeVersionCheckDate() {
lastVersionCheckPerformedOnDate = Date()
if let lastVersionCheckPerformedOnDate = lastVersionCheckPerformedOnDate {
UserDefaults.standard.set(lastVersionCheckPerformedOnDate, forKey: SirenDefaults.StoredVersionCheckDate.rawValue)
UserDefaults.standard.synchronize()
}
}
}
// MARK: - Helpers (Misc.)
private extension Siren {
func isUpdateCompatibleWithDeviceOS(appData: [String: Any]) -> Bool {
guard let results = appData[JSONKeys.results] as? [[String: Any]],
let info = results.first,
let requiredOSVersion = info[JSONKeys.minimumOSVersion] as? String else {
postError(.appStoreOSVersionNumberFailure, underlyingError: nil)
return false
}
let systemVersion = UIDevice.current.systemVersion
guard systemVersion.compare(requiredOSVersion, options: .numeric) == .orderedDescending ||
systemVersion.compare(requiredOSVersion, options: .numeric) == .orderedSame else {
postError(.appStoreOSVersionUnsupported, underlyingError: nil)
return false
}
return true
}
func hideWindow() {
if let updaterWindow = updaterWindow {
updaterWindow.isHidden = true
self.updaterWindow = nil
}
}
func launchAppStore() {
guard let appID = appID,
let iTunesURL = URL(string: "https://itunes.apple.com/app/id\(appID)") else {
return
}
DispatchQueue.main.async {
UIApplication.shared.openURL(iTunesURL)
}
}
func printMessage(message: String) {
if debugEnabled {
print("[Siren] \(message)")
}
}
}
// MARK: - Enumerated Types (Public)
public extension Siren {
/// Determines the type of alert to present after a successful version check has been performed.
enum AlertType {
/// Forces user to update your app (1 button alert).
case force
/// (DEFAULT) Presents user with option to update app now or at next launch (2 button alert).
case option
/// Presents user with option to update the app now, at next launch, or to skip this version all together (3 button alert).
case skip
/// Doesn't show the alert, but instead returns a localized message
/// for use in a custom UI within the sirenDidDetectNewVersionWithoutAlert() delegate method.
case none
}
/// Determines the frequency in which the the version check is performed and the user is prompted to update the app.
///
enum VersionCheckType: Int {
/// Version check performed every time the app is launched.
case immediately = 0
/// Version check performed once a day.
case daily = 1
/// Version check performed once a week.
case weekly = 7
}
/// Determines the available languages in which the update message and alert button titles should appear.
///
/// By default, the operating system's default lanuage setting is used. However, you can force a specific language
/// by setting the forceLanguageLocalization property before calling checkVersion()
enum LanguageType: String {
case Arabic = "ar"
case Armenian = "hy"
case Basque = "eu"
case ChineseSimplified = "zh-Hans"
case ChineseTraditional = "zh-Hant"
case Croatian = "hr"
case Danish = "da"
case Dutch = "nl"
case English = "en"
case Estonian = "et"
case Finnish = "fi"
case French = "fr"
case German = "de"
case Greek = "el"
case Hebrew = "he"
case Hungarian = "hu"
case Indonesian = "id"
case Italian = "it"
case Japanese = "ja"
case Korean = "ko"
case Latvian = "lv"
case Lithuanian = "lt"
case Malay = "ms"
case Norwegian = "nb-NO"
case Polish = "pl"
case PortugueseBrazil = "pt"
case PortuguesePortugal = "pt-PT"
case Russian = "ru"
case SerbianCyrillic = "sr-Cyrl"
case SerbianLatin = "sr-Latn"
case Slovenian = "sl"
case Spanish = "es"
case Swedish = "sv"
case Thai = "th"
case Turkish = "tr"
case Vietnamese = "vi"
}
}
// MARK: - Enumerated Types (Private)
private extension Siren {
/// Siren-specific Error Codes
enum ErrorCode: Int {
case malformedURL = 1000
case recentlyCheckedAlready
case noUpdateAvailable
case appStoreDataRetrievalFailure
case appStoreJSONParsingFailure
case appStoreOSVersionNumberFailure
case appStoreOSVersionUnsupported
case appStoreVersionNumberFailure
case appStoreVersionArrayFailure
case appStoreAppIDFailure
case appStoreReleaseDateFailure
}
/// Siren-specific Throwable Errors
enum SirenError: Error {
case malformedURL
case missingBundleIdOrAppId
}
/// Siren-specific UserDefaults Keys
enum SirenDefaults: String {
/// Key that stores the timestamp of the last version check in UserDefaults
case StoredVersionCheckDate
/// Key that stores the version that a user decided to skip in UserDefaults.
case StoredSkippedVersion
}
struct JSONKeys {
static let appID = "trackId"
static let currentVersionReleaseDate = "currentVersionReleaseDate"
static let minimumOSVersion = "minimumOsVersion"
static let results = "results"
static let version = "version"
}
}
// MARK: - Error Handling
private extension Siren {
func postError(_ code: ErrorCode, underlyingError: Error?) {
let description: String
switch code {
case .malformedURL:
description = "The iTunes URL is malformed. Please leave an issue on http://github.com/ArtSabintsev/Siren with as many details as possible."
case .recentlyCheckedAlready:
description = "Not checking the version, because it already checked recently."
case .noUpdateAvailable:
description = "No new update available."
case .appStoreDataRetrievalFailure:
description = "Error retrieving App Store data as an error was returned."
case .appStoreJSONParsingFailure:
description = "Error parsing App Store JSON data."
case .appStoreOSVersionNumberFailure:
description = "Error retrieving iOS version number as there was no data returned."
case .appStoreOSVersionUnsupported:
description = "The version of iOS on the device is lower than that of the one required by the app verison update."
case .appStoreVersionNumberFailure:
description = "Error retrieving App Store version number as there was no data returned."
case .appStoreVersionArrayFailure:
description = "Error retrieving App Store verson number as the JSON does not contain a 'version' key."
case .appStoreAppIDFailure:
description = "Error retrieving trackId as the JSON does not contain a 'trackId' key."
case .appStoreReleaseDateFailure:
description = "Error retrieving trackId as the JSON does not contain a 'currentVersionReleaseDate' key."
}
var userInfo: [String: Any] = [NSLocalizedDescriptionKey: description]
if let underlyingError = underlyingError {
userInfo[NSUnderlyingErrorKey] = underlyingError
}
let error = NSError(domain: SirenErrorDomain, code: code.rawValue, userInfo: userInfo)
delegate?.sirenDidFailVersionCheck(error: error)
printMessage(message: error.localizedDescription)
}
}
| mit |
hooman/swift | test/decl/typealias/fully_constrained.swift | 13 | 1809 | // RUN: %target-typecheck-verify-swift
struct OtherGeneric<U> {}
struct Generic<T> {
// FIXME: Should work with 'T' as well
typealias NonGeneric = Int where T == Int
typealias Unbound = OtherGeneric where T == Int
typealias Generic = OtherGeneric where T == Int
}
extension Generic where T == Int {
// FIXME: Should work with 'T' as well
typealias NonGenericInExtension = Int
typealias UnboundInExtension = OtherGeneric
typealias GenericInExtension = OtherGeneric
}
func use(_: Generic.NonGeneric,
_: Generic.Unbound<String>,
_: Generic.Generic<String>,
_: Generic.NonGenericInExtension,
_: Generic.UnboundInExtension<String>,
_: Generic.GenericInExtension<String>) {
// FIXME: Get these working too
#if false
let _ = Generic.NonGeneric.self
let _ = Generic.Unbound<String>.self
let _ = Generic.Generic<String>.self
let _ = Generic.NonGenericInExtension.self
let _ = Generic.UnboundInExtension<String>.self
let _ = Generic.GenericInExtension<String>.self
let _: Generic.NonGeneric = 123
let _: Generic.NonGenericInExtension = 123
#endif
let _: Generic.Unbound = OtherGeneric<String>()
let _: Generic.Generic = OtherGeneric<String>()
let _: Generic.UnboundInExtension = OtherGeneric<String>()
let _: Generic.GenericInExtension = OtherGeneric<String>()
}
struct Use {
let a1: Generic.NonGeneric
let b1: Generic.Unbound<String>
let c1: Generic.Generic<String>
let a2: Generic.NonGenericInExtension
let b2: Generic.UnboundInExtension<String>
let c2: Generic.GenericInExtension<String>
}
extension Generic.NonGeneric {}
extension Generic.Unbound {}
extension Generic.Generic {}
extension Generic.NonGenericInExtension {}
extension Generic.UnboundInExtension {}
extension Generic.GenericInExtension {}
| apache-2.0 |
brightify/torch | Source/Utils/ManagedObject.swift | 1 | 216 | //
// ManagedObject.swift
// Torch
//
// Created by Filip Dolnik on 02.08.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public protocol ManagedObject: AnyObject {
var id: Int { get set }
} | mit |
JiriTrecak/Warp | Example/WarpExample/Classes/Launcher/AppDelegate.swift | 1 | 2411 | //
// AppDelegate.swift
// Warp Example Project
//
// Created by Jiří Třečák.
// Copyright © 2016 Jiri Trecak. All rights reserved.
//
// This is main entrypoint to the application. Every call from this class is forwarded to different classes,
// As this file is always messy if not done this way.
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Imports
import UIKit
import Foundation
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Definitions
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Extension
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Protocols
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Implementation
@UIApplicationMain
class CSAppDelegate: UIResponder, UIApplicationDelegate {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
var window : UIWindow?
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Application initialization
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Location Manager
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Remote notifications
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Watchkit integration
}
| mit |
andreacipriani/tableview-headerview | TestTableViewHeader/ViewController.swift | 1 | 2897 | import UIKit
class ViewController: UIViewController {
// MARK: - Outlets
@IBOutlet fileprivate weak var tableView: UITableView!
// MARK: - Private properties
fileprivate let customCellIdentifier = "CustomCell"
private let tableViewHeaderInitialFrame = CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 200))
private let tableViewHeaderUpdatedFrame = CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 500))
fileprivate let headerView: CustomTableViewHeader = UINib(nibName: "CustomTableViewHeader", bundle: nil).instantiate(withOwner: self, options: nil).first! as! CustomTableViewHeader
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupTableViewHeaderView()
tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
simulateLongOperation() {
DispatchQueue.main.sync {
self.headerView.activityIndicator.isHidden = true
self.headerView.label.text = "I'm the updated HeaderView"
self.updateTableViewHeaderFrame() //updateTableViewHeaderWithIOS9BugFix()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Private func
private func setupTableView() {
tableView.dataSource = self
tableView.register(UINib(nibName: customCellIdentifier, bundle: nil), forCellReuseIdentifier: customCellIdentifier)
}
private func setupTableViewHeaderView() {
headerView.frame = tableViewHeaderInitialFrame
tableView.tableHeaderView = headerView
}
private func simulateLongOperation(completion: @escaping(() -> Void)){
headerView.activityIndicator.startAnimating()
DispatchQueue.global(qos: .background).async {
sleep(3)
completion()
}
}
// Use this function to see the bug on iOS 9
private func updateTableViewHeaderFrame() {
tableView.tableHeaderView!.frame = tableViewHeaderUpdatedFrame
}
// Use this function to fix the bug
private func updateTableViewHeaderWithIOS9BugFix() {
headerView.frame = tableViewHeaderUpdatedFrame
tableView.tableHeaderView = headerView
}
}
extension ViewController: UITableViewDataSource {
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: customCellIdentifier, for: indexPath) as! CustomCell
cell.label.text = "Cell \(indexPath.row)"
return cell
}
}
| mit |
RedMadRobot/DAO | Example/DAO/Classes/Model/CoreDataDatabase/CDFolder+CoreDataProperties.swift | 1 | 833 | //
// CDFolder+CoreDataProperties.swift
// DAO
//
// Created by Ivan Vavilov on 5/2/17.
// Copyright © 2017 RedMadRobot LLC. All rights reserved.
//
import Foundation
import CoreData
extension CDFolder {
@nonobjc
class func fetchRequest() -> NSFetchRequest<CDFolder> {
return NSFetchRequest<CDFolder>(entityName: "CDFolder")
}
@NSManaged var name: String
@NSManaged var messages: NSSet?
}
// MARK: Generated accessors for messages
extension CDFolder {
@objc(addMessagesObject:)
@NSManaged func addToMessages(_ value: CDMessage)
@objc(removeMessagesObject:)
@NSManaged func removeFromMessages(_ value: CDMessage)
@objc(addMessages:)
@NSManaged func addToMessages(_ values: NSSet)
@objc(removeMessages:)
@NSManaged func removeFromMessages(_ values: NSSet)
}
| mit |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/Models/RecognitionJobs.swift | 1 | 1058 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** RecognitionJobs. */
public struct RecognitionJobs: Decodable {
/// An array of objects that provides the status for each of the user's current jobs. The array is empty if the user has no current jobs.
public var recognitions: [RecognitionJob]
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case recognitions = "recognitions"
}
}
| mit |
StachkaConf/ios-app | StachkaIOS/StachkaIOS/Classes/Helpers/Extensions/UIColor.swift | 1 | 308 | //
// UIColor.swift
// StachkaIOS
//
// Created by m.rakhmanov on 26.03.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import UIKit
extension UIColor {
static var tabBarTintColor: UIColor {
return UIColor(red: 49/255.0, green: 94/255.0, blue: 251/255.0, alpha: 1.0)
}
}
| mit |
SD10/Nora | Sources/NRStorageRequest.swift | 1 | 533 | //
// NRStorageRequest.swift
// Nora
//
// Created by Steven on 4/8/17.
// Copyright © 2017 NoraFirebase. All rights reserved.
//
import Foundation
import FirebaseStorage
// MARK: - NRStorageRequest
struct NRStorageRequest {
let reference: StorageReference
let task: NRStorageTask
}
extension NRStorageRequest {
init(_ target: NRStorageTarget) {
self.reference = target.path == "" ? target.baseReference : target.baseReference.child(target.path)
self.task = target.task
}
}
| mit |
min/Lay | Example/Example/CollectionViewCell.swift | 1 | 972 | //
// CollectionViewCell.swift
// Example
//
// Created by Min Kim on 2/11/17.
// Copyright © 2017 Min Kim. All rights reserved.
//
import UIKit
final class CollectionViewCell: UICollectionViewCell {
class var reuseIdentifier: String {
return "\(type(of: self))ReuseIdentifier"
}
let titleLabel: UILabel = .init()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.textAlignment = .center
titleLabel.textColor = .white
titleLabel.font = UIFont(name: "Courier-Bold", size: 14)
contentView.addSubview(titleLabel)
contentView.layer.borderColor = UIColor.black.cgColor
contentView.layer.borderWidth = 1 / UIScreen.main.scale
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = contentView.bounds
}
}
| mit |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/PaymentSheet/ViewControllers/PaymentSheetViewController.swift | 1 | 23759 | //
// PaymentSheetViewController.swift
// StripePaymentSheet
//
// Created by Yuki Tokuhiro on 9/12/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
import Foundation
import PassKit
import UIKit
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
@_spi(STP) import StripePayments
protocol PaymentSheetViewControllerDelegate: AnyObject {
func paymentSheetViewControllerShouldConfirm(
_ paymentSheetViewController: PaymentSheetViewController, with paymentOption: PaymentOption,
completion: @escaping (PaymentSheetResult) -> Void)
func paymentSheetViewControllerDidFinish(
_ paymentSheetViewController: PaymentSheetViewController, result: PaymentSheetResult)
func paymentSheetViewControllerDidCancel(
_ paymentSheetViewController: PaymentSheetViewController)
func paymentSheetViewControllerDidSelectPayWithLink(
_ paymentSheetViewController: PaymentSheetViewController)
}
/// For internal SDK use only
@objc(STP_Internal_PaymentSheetViewController)
class PaymentSheetViewController: UIViewController {
// MARK: - Read-only Properties
let savedPaymentMethods: [STPPaymentMethod]
let isApplePayEnabled: Bool
let configuration: PaymentSheet.Configuration
let isLinkEnabled: Bool
var isWalletEnabled: Bool {
return isApplePayEnabled || isLinkEnabled
}
var shouldShowWalletHeader: Bool {
switch mode {
case .addingNew:
return isWalletEnabled
case .selectingSaved:
// When selecting saved we only add the wallet header for Link -- ApplePay by itself is inlined
return isLinkEnabled
}
}
// MARK: - Writable Properties
weak var delegate: PaymentSheetViewControllerDelegate?
private(set) var intent: Intent
enum Mode {
case selectingSaved
case addingNew
}
private var mode: Mode
private(set) var error: Error?
private var isPaymentInFlight: Bool = false
private(set) var isDismissable: Bool = true
// MARK: - Views
private lazy var addPaymentMethodViewController: AddPaymentMethodViewController = {
let shouldDisplaySavePaymentMethodCheckbox: Bool = {
switch intent {
case .paymentIntent:
return configuration.customer != nil
case .setupIntent:
return false
}
}()
return AddPaymentMethodViewController(
intent: intent,
configuration: configuration,
delegate: self
)
}()
private lazy var savedPaymentOptionsViewController: SavedPaymentOptionsViewController = {
let showApplePay = !shouldShowWalletHeader && isApplePayEnabled
let showLink = !shouldShowWalletHeader && isLinkEnabled
let autoSelectsDefaultPaymentMethod = !shouldShowWalletHeader
return SavedPaymentOptionsViewController(
savedPaymentMethods: savedPaymentMethods,
configuration: .init(
customerID: configuration.customer?.id,
showApplePay: showApplePay,
showLink: showLink,
autoSelectDefaultBehavior: autoSelectsDefaultPaymentMethod ? .defaultFirst : .none
),
appearance: configuration.appearance,
delegate: self
)
}()
internal lazy var navigationBar: SheetNavigationBar = {
let navBar = SheetNavigationBar(isTestMode: configuration.apiClient.isTestmode,
appearance: configuration.appearance)
navBar.delegate = self
return navBar
}()
private lazy var walletHeader: WalletHeaderView = {
var walletOptions: WalletHeaderView.WalletOptions = []
if isApplePayEnabled {
walletOptions.insert(.applePay)
}
if isLinkEnabled {
walletOptions.insert(.link)
}
let header = WalletHeaderView(
options: walletOptions,
appearance: configuration.appearance,
applePayButtonType: configuration.applePay?.buttonType ?? .plain,
delegate: self)
return header
}()
private lazy var headerLabel: UILabel = {
return PaymentSheetUI.makeHeaderLabel(appearance: configuration.appearance)
}()
private lazy var paymentContainerView: DynamicHeightContainerView = {
return DynamicHeightContainerView()
}()
private lazy var errorLabel: UILabel = {
return ElementsUI.makeErrorLabel(theme: configuration.appearance.asElementsTheme)
}()
private lazy var bottomNoticeTextField: UITextView = {
return ElementsUI.makeNoticeTextField(theme: configuration.appearance.asElementsTheme)
}()
private lazy var buyButton: ConfirmButton = {
let callToAction: ConfirmButton.CallToActionType = {
if let customCtaLabel = configuration.primaryButtonLabel {
return .customWithLock(title: customCtaLabel)
}
switch intent {
case .paymentIntent(let paymentIntent):
return .pay(amount: paymentIntent.amount, currency: paymentIntent.currency)
case .setupIntent:
return .setup
}
}()
let button = ConfirmButton(
callToAction: callToAction,
applePayButtonType: configuration.applePay?.buttonType ?? .plain,
appearance: configuration.appearance,
didTap: { [weak self] in
self?.didTapBuyButton()
}
)
return button
}()
// MARK: - Init
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(
intent: Intent,
savedPaymentMethods: [STPPaymentMethod],
configuration: PaymentSheet.Configuration,
isApplePayEnabled: Bool,
isLinkEnabled: Bool,
delegate: PaymentSheetViewControllerDelegate
) {
self.intent = intent
self.savedPaymentMethods = savedPaymentMethods
self.configuration = configuration
self.isApplePayEnabled = isApplePayEnabled
self.isLinkEnabled = isLinkEnabled
self.delegate = delegate
if savedPaymentMethods.isEmpty {
self.mode = .addingNew
} else {
self.mode = .selectingSaved
}
super.init(nibName: nil, bundle: nil)
self.view.backgroundColor = configuration.appearance.colors.background
}
deinit {
LinkAccountContext.shared.removeObserver(self)
}
// MARK: UIViewController Methods
override func viewDidLoad() {
super.viewDidLoad()
// One stack view contains all our subviews
let stackView = UIStackView(arrangedSubviews: [
headerLabel, walletHeader, paymentContainerView, errorLabel, buyButton, bottomNoticeTextField
])
stackView.directionalLayoutMargins = PaymentSheetUI.defaultMargins
stackView.isLayoutMarginsRelativeArrangement = true
stackView.spacing = PaymentSheetUI.defaultPadding
stackView.axis = .vertical
stackView.bringSubviewToFront(headerLabel)
stackView.setCustomSpacing(32, after: paymentContainerView)
stackView.setCustomSpacing(0, after: buyButton)
// Hack: Payment container needs to extend to the edges, so we'll 'cancel out' the layout margins with negative padding
paymentContainerView.directionalLayoutMargins = .insets(
leading: -PaymentSheetUI.defaultSheetMargins.leading,
trailing: -PaymentSheetUI.defaultSheetMargins.trailing
)
[stackView].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
}
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: view.topAnchor),
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
stackView.bottomAnchor.constraint(
equalTo: view.bottomAnchor, constant: -PaymentSheetUI.defaultSheetMargins.bottom),
])
updateUI(animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
STPAnalyticsClient.sharedClient.logPaymentSheetShow(
isCustom: false,
paymentMethod: mode.analyticsValue,
linkEnabled: intent.supportsLink,
activeLinkSession: LinkAccountContext.shared.account?.sessionState == .verified,
currency: intent.currency
)
}
func set(error: Error?) {
self.error = error
self.errorLabel.text = error?.nonGenericDescription
UIView.animate(withDuration: PaymentSheetUI.defaultAnimationDuration) {
self.errorLabel.setHiddenIfNecessary(self.error == nil)
}
}
// MARK: Private Methods
private func configureNavBar() {
navigationBar.setStyle(
{
switch mode {
case .selectingSaved:
if self.savedPaymentOptionsViewController.hasRemovablePaymentMethods {
self.configureEditSavedPaymentMethodsButton()
return .close(showAdditionalButton: true)
} else {
self.navigationBar.additionalButton.removeTarget(
self, action: #selector(didSelectEditSavedPaymentMethodsButton),
for: .touchUpInside)
return .close(showAdditionalButton: false)
}
case .addingNew:
self.navigationBar.additionalButton.removeTarget(
self, action: #selector(didSelectEditSavedPaymentMethodsButton),
for: .touchUpInside)
return savedPaymentMethods.isEmpty ? .close(showAdditionalButton: false) : .back
}
}())
}
// state -> view
private func updateUI(animated: Bool = true) {
// Disable interaction if necessary
let shouldEnableUserInteraction = !isPaymentInFlight
if shouldEnableUserInteraction != view.isUserInteractionEnabled {
sendEventToSubviews(
shouldEnableUserInteraction ? .shouldEnableUserInteraction : .shouldDisableUserInteraction,
from: view
)
}
view.isUserInteractionEnabled = shouldEnableUserInteraction
isDismissable = !isPaymentInFlight
navigationBar.isUserInteractionEnabled = !isPaymentInFlight
// Update our views (starting from the top of the screen):
configureNavBar()
// Content header
walletHeader.isHidden = !shouldShowWalletHeader
walletHeader.showsCardPaymentMessage = (
addPaymentMethodViewController.paymentMethodTypes == [.card]
)
switch mode {
case .addingNew:
headerLabel.isHidden = isWalletEnabled
headerLabel.text = STPLocalizedString(
"Add your payment information",
"Title shown above a form where the customer can enter payment information like credit card details, email, billing address, etc."
)
case .selectingSaved:
headerLabel.isHidden = false
headerLabel.text = shouldShowWalletHeader && intent.isPaymentIntent
? STPLocalizedString(
"Pay using",
"Title shown above a section containing various payment options")
: STPLocalizedString(
"Select your payment method",
"Title shown above a carousel containing the customer's payment methods")
}
// Content
switchContentIfNecessary(
to: mode == .selectingSaved
? savedPaymentOptionsViewController : addPaymentMethodViewController,
containerView: paymentContainerView
)
// Error
switch mode {
case .addingNew:
if addPaymentMethodViewController.setErrorIfNecessary(for: error) == false {
errorLabel.text = error?.nonGenericDescription
}
case .selectingSaved:
errorLabel.text = error?.nonGenericDescription
}
UIView.animate(withDuration: PaymentSheetUI.defaultAnimationDuration) {
self.errorLabel.setHiddenIfNecessary(self.error == nil)
}
// Buy button
let buyButtonStyle: ConfirmButton.Style
var buyButtonStatus: ConfirmButton.Status
var showBuyButton: Bool = true
var callToAction = self.intent.callToAction
if let customCtaLabel = configuration.primaryButtonLabel {
callToAction = .customWithLock(title: customCtaLabel)
}
switch mode {
case .selectingSaved:
if case .applePay = savedPaymentOptionsViewController.selectedPaymentOption {
buyButtonStyle = .applePay
} else {
buyButtonStyle = .stripe
}
buyButtonStatus = .enabled
showBuyButton = savedPaymentOptionsViewController.selectedPaymentOption != nil
case .addingNew:
buyButtonStyle = .stripe
if let overrideCallToAction = addPaymentMethodViewController.overrideCallToAction {
callToAction = overrideCallToAction
buyButtonStatus = addPaymentMethodViewController.overrideCallToActionShouldEnable ? .enabled : .disabled
} else {
buyButtonStatus =
addPaymentMethodViewController.paymentOption == nil ? .disabled : .enabled
}
}
// Notice
updateBottomNotice()
if isPaymentInFlight {
buyButtonStatus = .processing
}
self.buyButton.update(
state: buyButtonStatus,
style: buyButtonStyle,
callToAction: callToAction,
animated: animated,
completion: nil
)
let updateButtonVisibility = {
self.buyButton.isHidden = !showBuyButton
}
if animated {
animateHeightChange(updateButtonVisibility)
} else {
updateButtonVisibility()
}
}
func updateBottomNotice() {
switch mode {
case .selectingSaved:
self.bottomNoticeTextField.attributedText = savedPaymentOptionsViewController.bottomNoticeAttributedString
case .addingNew:
self.bottomNoticeTextField.attributedText = addPaymentMethodViewController.bottomNoticeAttributedString
}
UIView.animate(withDuration: PaymentSheetUI.defaultAnimationDuration) {
self.bottomNoticeTextField.setHiddenIfNecessary(self.bottomNoticeTextField.attributedText?.length == 0)
}
}
@objc
private func didTapBuyButton() {
switch mode {
case .addingNew:
if let buyButtonOverrideBehavior = addPaymentMethodViewController.overrideBuyButtonBehavior {
addPaymentMethodViewController.didTapCallToActionButton(behavior: buyButtonOverrideBehavior, from: self)
} else {
guard let newPaymentOption = addPaymentMethodViewController.paymentOption else {
assertionFailure()
return
}
pay(with: newPaymentOption)
}
case .selectingSaved:
guard
let selectedPaymentOption = savedPaymentOptionsViewController.selectedPaymentOption
else {
assertionFailure()
return
}
pay(with: selectedPaymentOption)
}
}
private func pay(with paymentOption: PaymentOption) {
view.endEditing(true)
isPaymentInFlight = true
// Clear any errors
error = nil
updateUI()
// Confirm the payment with the payment option
let startTime = NSDate.timeIntervalSinceReferenceDate
self.delegate?.paymentSheetViewControllerShouldConfirm(self, with: paymentOption) {
result in
let elapsedTime = NSDate.timeIntervalSinceReferenceDate - startTime
DispatchQueue.main.asyncAfter(
deadline: .now() + max(PaymentSheetUI.minimumFlightTime - elapsedTime, 0)
) {
STPAnalyticsClient.sharedClient.logPaymentSheetPayment(
isCustom: false,
paymentMethod: paymentOption.analyticsValue,
result: result,
linkEnabled: self.intent.supportsLink,
activeLinkSession: LinkAccountContext.shared.account?.sessionState == .verified,
paymentOption: paymentOption,
currency: self.intent.currency
)
self.isPaymentInFlight = false
switch result {
case .canceled:
// Do nothing, keep customer on payment sheet
self.updateUI()
case .failed(let error):
UINotificationFeedbackGenerator().notificationOccurred(.error)
// Update state
self.error = error
// Handle error
if PaymentSheetError.isUnrecoverable(error: error) {
self.delegate?.paymentSheetViewControllerDidFinish(self, result: result)
}
self.updateUI()
UIAccessibility.post(notification: .layoutChanged, argument: self.errorLabel)
case .completed:
// We're done!
let delay: TimeInterval =
self.presentedViewController?.isBeingDismissed == true ? 1 : 0
// Hack: PaymentHandler calls the completion block while SafariVC is still being dismissed - "wait" until it's finished before updating UI
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
UINotificationFeedbackGenerator().notificationOccurred(.success)
self.buyButton.update(state: .succeeded, animated: true) {
// Wait a bit before closing the sheet
self.delegate?.paymentSheetViewControllerDidFinish(self, result: .completed)
}
}
}
}
}
}
}
// MARK: - Wallet Header Delegate
extension PaymentSheetViewController: WalletHeaderViewDelegate {
func walletHeaderViewApplePayButtonTapped(_ header: WalletHeaderView) {
set(error: nil)
pay(with: .applePay)
}
func walletHeaderViewPayWithLinkTapped(_ header: WalletHeaderView) {
set(error: nil)
delegate?.paymentSheetViewControllerDidSelectPayWithLink(self)
}
}
// MARK: - BottomSheetContentViewController
/// :nodoc:
extension PaymentSheetViewController: BottomSheetContentViewController {
var allowsDragToDismiss: Bool {
return isDismissable
}
func didTapOrSwipeToDismiss() {
if isDismissable {
delegate?.paymentSheetViewControllerDidCancel(self)
}
}
var requiresFullScreen: Bool {
return false
}
}
// MARK: - SavedPaymentOptionsViewControllerDelegate
/// :nodoc:
extension PaymentSheetViewController: SavedPaymentOptionsViewControllerDelegate {
func didUpdateSelection(
viewController: SavedPaymentOptionsViewController,
paymentMethodSelection: SavedPaymentOptionsViewController.Selection
) {
STPAnalyticsClient.sharedClient.logPaymentSheetPaymentOptionSelect(isCustom: false, paymentMethod: paymentMethodSelection.analyticsValue)
if case .add = paymentMethodSelection {
mode = .addingNew
error = nil // Clear any errors
}
updateUI()
}
func didSelectRemove(
viewController: SavedPaymentOptionsViewController,
paymentMethodSelection: SavedPaymentOptionsViewController.Selection
) {
guard case .saved(let paymentMethod) = paymentMethodSelection,
let ephemeralKey = configuration.customer?.ephemeralKeySecret
else {
return
}
configuration.apiClient.detachPaymentMethod(
paymentMethod.stripeId, fromCustomerUsing: ephemeralKey
) { (_) in
// no-op
}
if !savedPaymentOptionsViewController.hasRemovablePaymentMethods {
savedPaymentOptionsViewController.isRemovingPaymentMethods = false
// calling updateUI() at this point causes an issue with the height of the add card vc
// if you do a subsequent presentation. Since bottom sheet height stuff is complicated,
// just update the nav bar which is all we need to do anyway
configureNavBar()
}
updateBottomNotice()
}
// MARK: Helpers
func configureEditSavedPaymentMethodsButton() {
if savedPaymentOptionsViewController.isRemovingPaymentMethods {
navigationBar.additionalButton.setTitle(UIButton.doneButtonTitle, for: .normal)
buyButton.update(state: .disabled)
} else {
buyButton.update(state: .enabled)
navigationBar.additionalButton.setTitle(UIButton.editButtonTitle, for: .normal)
}
navigationBar.additionalButton.accessibilityIdentifier = "edit_saved_button"
navigationBar.additionalButton.titleLabel?.adjustsFontForContentSizeCategory = true
navigationBar.additionalButton.addTarget(
self, action: #selector(didSelectEditSavedPaymentMethodsButton), for: .touchUpInside)
}
@objc
func didSelectEditSavedPaymentMethodsButton() {
savedPaymentOptionsViewController.isRemovingPaymentMethods.toggle()
configureEditSavedPaymentMethodsButton()
}
}
// MARK: - AddPaymentMethodViewControllerDelegate
/// :nodoc:
extension PaymentSheetViewController: AddPaymentMethodViewControllerDelegate {
func didUpdate(_ viewController: AddPaymentMethodViewController) {
error = nil // clear error
updateUI()
}
func shouldOfferLinkSignup(_ viewController: AddPaymentMethodViewController) -> Bool {
guard isLinkEnabled else {
return false
}
return LinkAccountContext.shared.account.flatMap({ !$0.isRegistered }) ?? true
}
func updateErrorLabel(for error: Error?) {
set(error: error)
}
}
// MARK: - SheetNavigationBarDelegate
/// :nodoc:
extension PaymentSheetViewController: SheetNavigationBarDelegate {
func sheetNavigationBarDidClose(_ sheetNavigationBar: SheetNavigationBar) {
delegate?.paymentSheetViewControllerDidCancel(self)
// If the customer was editing saved payment methods, exit edit mode
if savedPaymentOptionsViewController.isRemovingPaymentMethods {
savedPaymentOptionsViewController.isRemovingPaymentMethods = false
configureEditSavedPaymentMethodsButton()
}
}
func sheetNavigationBarDidBack(_ sheetNavigationBar: SheetNavigationBar) {
// This is quite hardcoded. Could make some generic "previous state" or "previous VC" that we always go back to
switch mode {
case .addingNew:
error = nil
mode = .selectingSaved
updateUI()
default:
assertionFailure()
}
}
}
| mit |
KeithPiTsui/Pavers | Pavers/Sources/Argo/Functions/flatReduce.swift | 2 | 1033 | import PaversFRP
/**
Reduce a sequence with a combinator that returns a `Decoded` type, flattening
the result.
This function is a helper function to make it easier to deal with combinators
that return `Decoded` types without ending up with multiple levels of nested
`Decoded` values.
For example, it can be used to traverse a JSON structure with an array of
keys. See the implementations of `<|` and `<||` that take an array of keys for
a real-world example of this use case.
- parameter sequence: Any `SequenceType` of values
- parameter initial: The initial value for the accumulator
- parameter combine: The combinator, which returns a `Decoded` type
- returns: The result of iterating the combinator over every element of the
sequence and flattening the result
*/
public func flatReduce<S: Sequence, U>(_ sequence: S, initial: U, combine: (U, S.Iterator.Element) -> Decoded<U>) -> Decoded<U> {
return sequence.reduce(pure(initial)) { accum, x in
accum >>- { combine($0, x) }
}
}
| mit |
Yoseob/Trevi | Lime/Lime/Layer.swift | 1 | 2972 | //
// Layer.swift
// Trevi
//
// Created by LeeYoseob on 2016. 3. 2..
// Copyright © 2016년 LeeYoseob. All rights reserved.
//
import Foundation
import Trevi
/*
Reuse for becoming more useful results Middleware and all the routes that object is wrapped with this class.
*/
public class Layer {
private var handle: HttpCallback?
public var path: String! = ""
public var regexp: RegExp!
public var name: String!
public var route: Route?
public var method: HTTPMethodType! = .UNDEFINED
public var keys: [String]? // params key ex path/:name , name is key
public var params: [String: String]?
public init(path: String ,name: String? = "function", options: Option? = nil, fn: HttpCallback){
setupAfterInit(path, opt: options, name: name, fn: fn)
}
public init(path: String, options: Option? = nil, module: Middleware){
setupAfterInit(path, opt: options, name: module.name.rawValue, fn: module.handle)
}
private func setupAfterInit(p: String, opt: Option? = nil, name: String?, fn: HttpCallback){
self.handle = fn
self.path = p
self.name = name
//create regexp
regexp = self.pathRegexp(path, option: opt)
if path == "/" && opt?.end == false {
regexp.fastSlash = true
}
}
private func pathRegexp(path: String, option: Option!) -> RegExp{
// create key, and append key when create regexp
keys = [String]()
if path.length() > 1 {
for param in searchWithRegularExpression(path, pattern: ":([^\\/]*)") {
keys!.append(param["$1"]!.text)
}
}
return RegExp(path: path)
}
//handle mathed route module
public func handleRequest(req: IncomingMessage , res: ServerResponse, next: NextCallback){
let function = self.handle
function!(req,res,next)
}
//Request url meching.
public func match(path: String?) -> Bool{
guard path != nil else {
self.params = nil
self.path = nil
return false
}
guard (self.regexp.fastSlash) == false else {
self.path = ""
self.params = [String: String]()
return true
}
var ret: [String]! = self.regexp.exec(path!)
guard ret != nil else{
self.params = nil
self.path = nil
return false
}
self.path = ret[0]
self.params = [String: String]()
ret.removeFirst()
var idx = 0
var key: String! = ""
for value in ret {
key = keys![idx]
idx += 1
if key == nil {
break
}
params![key] = value
key = nil
}
return true
}
}
| apache-2.0 |
practicalswift/swift | test/ParseableInterface/ModuleCache/force-module-loading-mode.swift | 2 | 6798 | // RUN: %empty-directory(%t)
// XFAIL: CPU=powerpc64le
// 1. Not finding things is okay.
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// 2. Only interface is present.
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %S/Inputs/force-module-loading-mode/ 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %S/Inputs/force-module-loading-mode/ 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %S/Inputs/force-module-loading-mode/ 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %S/Inputs/force-module-loading-mode/ 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %S/Inputs/force-module-loading-mode/ %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// 3. Only module is present.
// RUN: sed -e 's/FromInterface/FromSerialized/g' %S/Inputs/force-module-loading-mode/Lib.swiftinterface | %target-swift-frontend -parse-stdlib -module-cache-path %t/MCP -emit-module-path %t/Lib.swiftmodule - -module-name Lib
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// 4. Both are present.
// RUN: cp %S/Inputs/force-module-loading-mode/Lib.swiftinterface %t
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=FROM-SERIALIZED %s
// 5. Both are present but the module is invalid.
// RUN: rm %t/Lib.swiftmodule && touch %t/Lib.swiftmodule
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=BAD-MODULE %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=BAD-MODULE %s
// 6. Both are present but the module can't be opened.
// RUN: chmod a-r %t/Lib.swiftmodule
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=prefer-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-parseable %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=FROM-INTERFACE %s
// RUN: not env SWIFT_FORCE_MODULE_LOADING=only-serialized %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP %s -I %t 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
// (default)
// RUN: not %target-swift-frontend -typecheck -parse-stdlib -module-cache-path %t/MCP -I %t %s 2>&1 | %FileCheck -check-prefix=NO-SUCH-MODULE %s
import Lib
// NO-SUCH-MODULE: [[@LINE-1]]:8: error: no such module 'Lib'
// BAD-MODULE: [[@LINE-2]]:8: error: malformed module file: {{.*}}Lib.swiftmodule
struct X {}
let _: X = Lib.testValue
// FROM-INTERFACE: [[@LINE-1]]:16: error: cannot convert value of type 'FromInterface' to specified type 'X'
// FROM-SERIALIZED: [[@LINE-2]]:16: error: cannot convert value of type 'FromSerialized' to specified type 'X'
| apache-2.0 |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Tests/ScheduleComponentTests/Presenter Tests/Test Doubles/FakeScheduleInteractor.swift | 1 | 783 | import EurofurenceModel
import Foundation
import ScheduleComponent
import XCTScheduleComponent
class FakeScheduleViewModelFactory: ScheduleViewModelFactory {
private let viewModel: ScheduleViewModel
private let searchViewModel: ScheduleSearchViewModel
init(viewModel: CapturingScheduleViewModel = .random,
searchViewModel: CapturingScheduleSearchViewModel = CapturingScheduleSearchViewModel()) {
self.viewModel = viewModel
self.searchViewModel = searchViewModel
}
func makeViewModel(completionHandler: @escaping (ScheduleViewModel) -> Void) {
completionHandler(viewModel)
}
func makeSearchViewModel(completionHandler: @escaping (ScheduleSearchViewModel) -> Void) {
completionHandler(searchViewModel)
}
}
| mit |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/Vision/BarcodesVision/BarcodesVisionVC.swift | 1 | 9865 | /// Copyright (c) 2020 Razeware LLC
///
/// 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 Vision
import AVFoundation
import SafariServices
// https://www.raywenderlich.com/12663654-vision-framework-tutorial-for-ios-scanning-barcodes
class BarcodesVisionVC: UIViewController {
// MARK: - Private Variables
var captureSession = AVCaptureSession()
// TODO: Make VNDetectBarcodesRequest variable
lazy var detectBarcodeRequest = VNDetectBarcodesRequest { request, error in
guard error == nil else {
self.showAlert(withTitle: "Barcode error", message: error?.localizedDescription ?? "error")
return
}
self.processClassification(request)
}
// MARK: - Override Functions
override func viewDidLoad() {
super.viewDidLoad()
checkPermissions()
setupCameraLiveView()
view.addSubview(annotationOverlayView)
NSLayoutConstraint.activate([
annotationOverlayView.topAnchor.constraint(equalTo: view.topAnchor),
annotationOverlayView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
annotationOverlayView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
annotationOverlayView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
private lazy var annotationOverlayView: UIView = {
precondition(isViewLoaded)
let annotationOverlayView = UIView(frame: .zero)
annotationOverlayView.translatesAutoresizingMaskIntoConstraints = false
return annotationOverlayView
}()
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// TODO: Stop Session
captureSession.stopRunning()
}
var cameraPreviewLayer: AVCaptureVideoPreviewLayer!
}
extension BarcodesVisionVC {
// MARK: - Camera
private func checkPermissions() {
// TODO: Checking permissions
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { [self] granted in
if !granted {
self.showPermissionsAlert()
}
}
case .denied, .restricted:
showPermissionsAlert()
default:
return
}
}
private func setupCameraLiveView() {
// TODO: Setup captureSession
captureSession.sessionPreset = .hd1280x720
// TODO: Add input
let videoDevice = AVCaptureDevice
.default(.builtInWideAngleCamera, for: .video, position: .back)
guard
let device = videoDevice,
let videoDeviceInput = try? AVCaptureDeviceInput(device: device),
captureSession.canAddInput(videoDeviceInput) else {
showAlert(
withTitle: "Cannot Find Camera",
message: "There seems to be a problem with the camera on your device.")
return
}
captureSession.addInput(videoDeviceInput)
// TODO: Add output
let captureOutput = AVCaptureVideoDataOutput()
// TODO: Set video sample rate
captureOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
captureOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))
captureSession.addOutput(captureOutput)
configurePreviewLayer()
// TODO: Run session
captureSession.startRunning()
}
// MARK: - Vision
func processClassification(_ request: VNRequest) {
// TODO: Main logic
guard let barcodes = request.results else { return }
DispatchQueue.main.async { [self] in
if captureSession.isRunning {
view.layer.sublayers?.removeSubrange(1...)
let set: Set<VNBarcodeSymbology> = [.QR, .EAN13, .EAN8, .Code128]
for barcode in barcodes {
guard
// TODO: Check for QR Code symbology and confidence score
let potentialQRCode = barcode as? VNBarcodeObservation,
set.contains(potentialQRCode.symbology),
potentialQRCode.confidence > 0.9
else { return }
// https://github.com/jeffreybergier/Blog-Getting-Started-with-Vision/issues/2
let t = CGAffineTransform(translationX: 0.5, y: 0.5)
.rotated(by: CGFloat.pi / 2)
.translatedBy(x: -0.5, y: -0.5)
.translatedBy(x: 1.0, y: 0)
.scaledBy(x: -1, y: 1)
let box = potentialQRCode.boundingBox.applying(t)
let convertedRect = self.cameraPreviewLayer.layerRectConverted(
fromMetadataOutputRect: box
)
UIUtilities.addRectangle(
convertedRect,
to: view,
text: potentialQRCode.payloadStringValue
)
// observationHandler(payload: potentialQRCode.payloadStringValue)
}
}
}
}
// MARK: - Handler
func observationHandler(payload: String?) {
// TODO: Open it in Safari
guard
let payloadString = payload,
let url = URL(string: payloadString),
["http", "https"].contains(url.scheme?.lowercased())
else { return }
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
let safariVC = SFSafariViewController(url: url, configuration: config)
safariVC.delegate = self
present(safariVC, animated: true)
}
}
// MARK: - AVCaptureDelegation
extension BarcodesVisionVC: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// TODO: Live Vision
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
let imageRequestHandler = VNImageRequestHandler(
cvPixelBuffer: pixelBuffer,
orientation: .right)
do {
try imageRequestHandler.perform([detectBarcodeRequest])
} catch {
print(error)
}
}
}
// MARK: - Helper
extension BarcodesVisionVC {
private func configurePreviewLayer() {
let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.cameraPreviewLayer = cameraPreviewLayer
cameraPreviewLayer.videoGravity = .resizeAspectFill
cameraPreviewLayer.connection?.videoOrientation = .portrait
cameraPreviewLayer.frame = view.frame
view.layer.insertSublayer(cameraPreviewLayer, at: 0)
}
private func showAlert(withTitle title: String, message: String) {
DispatchQueue.main.async {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true)
}
}
private func showPermissionsAlert() {
showAlert(
withTitle: "Camera Permissions",
message: "Please open Settings and grant permission for this app to use your camera.")
}
}
// MARK: - SafariViewControllerDelegate
extension BarcodesVisionVC: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
captureSession.startRunning()
}
}
| mit |
aotian16/SwiftGameDemo | Cat/Cat/GameViewController.swift | 1 | 1463 | //
// GameViewController.swift
// Cat
//
// Created by 童进 on 15/11/25.
// Copyright (c) 2015年 qefee. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .ResizeFill
// scene.size = UIScreen.mainScreen().bounds.size
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1209-llvm-errs.swift | 13 | 430 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func n<w>() -> (w, w -> w) -> w {
o m o.q = {
}
{
w) {
k }
}
protocol n {
}
class o: n{ class func q {}
func p(e: Int = x) {
}
let c = p
protocol p : p {
}
protocol p {
}
class e: p {
}
k e.w == l> {
}
func p(c {
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/24742-swift-constraints-solution-solution.swift | 9 | 235 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a=0
protocol a{
extension b{
func c
{var a{
{
class
case c,
{
| mit |
AynurGaliev/Books-Shop | Sources/App/Request + Extensions.swift | 1 | 115 | import HTTP
import Vapor
extension Request {
func isValidVersion() -> Bool {
return true
}
}
| mit |
cz-it/cz_base_app | File Templates/CZ's Source/Cocoa Touch Class.xctemplate/UICollectionViewControllerSwift/___FILEBASENAME___.swift | 2 | 3256 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
import UIKit
private let reuseIdentifier = "Cell"
class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_cocoaTouchSubclass___ {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return 0
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
// Configure the cell
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
| mit |
jkascend/free-blur | free-blurTests/free_blurTests.swift | 1 | 917 | //
// free_blurTests.swift
// free-blurTests
//
// Created by Justin Kambic on 6/1/17.
//
import XCTest
@testable import free_blur
class free_blurTests: 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.
}
}
}
| mit |
barteljan/VISPER | VISPER-Entity/Classes/FunctionalEntityStore.swift | 1 | 9164 | //
// FunctionalEntityStore.swift
// Pods-VISPER-Entity-Example
//
// Created by bartel on 09.04.18.
//
import Foundation
open class FunctionalEntityStore<EntityType: CanBeIdentified>: EntityStore {
public enum StoreError: Error {
case functionNotImplementedYet
}
let persistEntites: (_ entities: [EntityType]) throws -> Void
let deleteEntites: (_ entities: [EntityType]) throws -> Void
let getEntities: ()->[EntityType]
let getEntity: (_ identifier: String) -> EntityType?
let deleteEntity: (_ identifier: String) throws -> Void
public convenience init(persistEntites: @escaping (_ entities: [EntityType]) throws -> Void,
deleteEntites: @escaping (_ entities: [EntityType]) throws -> Void,
getEntities: @escaping ()->[EntityType]) {
let getEntity = { (aIdentifier) -> EntityType? in
return getEntities().filter({ return $0.identifier() == aIdentifier }).first
}
self.init(persistEntites: persistEntites,
deleteEntites: deleteEntites,
getEntities: getEntities,
getEntity: getEntity)
}
public convenience init(persistEntites: @escaping (_ entities: [EntityType]) throws -> Void,
deleteEntites: @escaping (_ entities: [EntityType]) throws -> Void,
getEntities: @escaping ()->[EntityType],
getEntity: @escaping (_ identifier: String) -> EntityType?){
let deleteEntity = { (identifier: String) throws -> Void in
if let entity = getEntity(identifier) {
try deleteEntites([entity])
}
}
self.init(persistEntites: persistEntites,
deleteEntites: deleteEntites,
getEntities: getEntities,
getEntity: getEntity,
deleteEntity: deleteEntity)
}
public convenience init(persistEntites: @escaping (_ entities: [EntityType]) throws -> Void,
getEntities: @escaping ()->[EntityType],
getEntity: @escaping (_ identifier: String) -> EntityType?,
deleteEntity: @escaping (_ identifier: String) throws -> Void ){
let deleteEntities = { (_ entities: [EntityType]) throws -> Void in
for entity in entities {
try deleteEntity(entity.identifier())
}
}
self.init(persistEntites: persistEntites,
deleteEntites: deleteEntities,
getEntities: getEntities,
getEntity: getEntity,
deleteEntity: deleteEntity)
}
public init(persistEntites: @escaping (_ entities: [EntityType]) throws -> Void,
deleteEntites: @escaping (_ entities: [EntityType]) throws -> Void,
getEntities: @escaping ()->[EntityType],
getEntity: @escaping (_ identifier: String) -> EntityType?,
deleteEntity: @escaping (_ identifier: String) throws -> Void ){
self.persistEntites = persistEntites
self.deleteEntites = deleteEntites
self.getEntities = getEntities
self.getEntity = getEntity
self.deleteEntity = deleteEntity
}
public func isResponsible<T>(for object: T) -> Bool {
return object is EntityType
}
public func isResponsible<T>(forType type: T.Type) -> Bool {
return type.self is EntityType.Type
}
public func delete<T>(_ item: T!) throws {
if let item = item as? EntityType {
try self.deleteEntites([item])
}
}
public func delete<T>(_ items: [T]) throws {
if T.self is EntityType.Type {
let convertedItems = items.map({ return $0 as! EntityType})
try self.deleteEntites(convertedItems)
}
}
public func delete<T>(_ item: T!,
completion: @escaping () -> ()) throws {
try self.delete(item)
completion()
}
public func delete<T>(_ identifier: String, type: T.Type) throws {
try self.deleteEntity(identifier)
}
public func get<T>(_ identifier: String) throws -> T? {
return self.getEntity(identifier) as? T
}
public func get<T>(_ identifier: String,
completion: @escaping (T?) -> Void) throws {
let item: T? = try self.get(identifier)
completion(item)
}
public func persist<T>(_ item: T!) throws {
if let item = item as? EntityType {
try self.persistEntites([item])
}
}
public func persist<T>(_ item: T!,
completion: @escaping () -> ()) throws {
try self.persist(item)
completion()
}
public func persist<T>(_ items: [T]) throws {
if T.self is EntityType.Type {
let convertedItems = items.map({ return $0 as! EntityType})
try self.persistEntites(convertedItems)
}
}
public func getAll<T>(_ type: T.Type) throws -> [T] {
if T.self is EntityType.Type {
return self.getEntities().map { (entity) -> T in
return entity as! T
}
} else {
return [T]()
}
}
public func getAll<T>(_ type: T.Type,
completion: @escaping ([T]) -> Void) throws {
let items = try self.getAll(type)
completion(items)
}
public func getAll<T>(_ viewName: String) throws -> [T] {
throw StoreError.functionNotImplementedYet
}
public func getAll<T>(_ viewName: String,
completion: @escaping ([T]) -> Void) throws {
throw StoreError.functionNotImplementedYet
}
public func getAll<T>(_ viewName: String,
groupName: String) throws -> [T] {
throw StoreError.functionNotImplementedYet
}
public func getAll<T>(_ viewName: String,
groupName: String,
completion: @escaping ([T]) -> Void) throws {
throw StoreError.functionNotImplementedYet
}
public func exists<T>(_ item: T!) throws -> Bool {
guard T.self is EntityType.Type else {
return false
}
if let item = item as? EntityType {
let identifier = item.identifier()
if let _ : T = try self.get(identifier) {
return true
}
}
return false
}
public func exists<T>(_ item: T!,
completion: @escaping (Bool) -> Void) throws {
let isExistent = try self.exists(item)
completion(isExistent)
}
public func exists<T>(_ identifier: String,
type: T.Type) throws -> Bool {
guard T.self is EntityType.Type else {
return false
}
if let _ : T = try self.get(identifier) {
return true
}
return false
}
public func exists<T>(_ identifier: String,
type: T.Type,
completion: @escaping (Bool) -> Void) throws {
let isExistent = try self.exists(identifier, type: type)
completion(isExistent)
}
public func filter<T>(_ type: T.Type,
includeElement: @escaping (T) -> Bool) throws -> [T] {
return try self.getAll(type).filter(includeElement)
}
public func filter<T>(_ type: T.Type,
includeElement: @escaping (T) -> Bool,
completion: @escaping ([T]) -> Void) throws {
let items: [T] = try self.filter(type, includeElement: includeElement)
completion(items)
}
public func addView<T>(_ viewName: String,
groupingBlock: @escaping ((String, String, T) -> String?),
sortingBlock: @escaping ((String, String, String, T, String, String, T) -> ComparisonResult)) throws {
throw StoreError.functionNotImplementedYet
}
public func transaction(transaction: @escaping (EntityStore) throws -> Void) throws {
let items = self.getEntities()
let transactionStore = try MemoryEntityStore([items])
try transaction(transactionStore)
for item in transactionStore.deletedEntities() {
if let item = item as? EntityType {
try self.delete(item)
}
}
for item in transactionStore.updatedEntities() {
if let item = item as? EntityType {
try self.persist(item)
}
}
}
public func toTypedEntityStore() throws -> TypedEntityStore<EntityType> {
return try TypedEntityStore(entityStore: self)
}
}
| mit |
antelope-app/Antelope | Antelope-ios/Antelope/TutorialStepZero.swift | 1 | 4067 | //
// TutorialStepZero.swift
// AdShield
//
// Created by Jae Lee on 9/1/15.
// Copyright © 2015 AdShield. All rights reserved.
//
import UIKit
class TutorialStepZero: TutorialStep
{
@IBOutlet weak var logoImage: UIImageView!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var stepZeroHeader: UITextView!
@IBOutlet weak var stepZeroSubheader: UITextView!
@IBOutlet weak var stepZeroHeaderImage: UIImageView!
@IBOutlet weak var secondSubHeader: UITextView!
@IBOutlet weak var thirdSubHeader: UITextView!
var overlaySoft: UIView = UIView()
var overlayHard: UIView = UIView()
@IBOutlet weak var barTwo: UIView!
@IBOutlet weak var barOne: UIView!
override func viewDidLoad() {
super.viewDidLoad()
stepZeroSubheader = self.paragraphStyle(stepZeroSubheader)
stepZeroSubheader.userInteractionEnabled = false
secondSubHeader.hidden = true
secondSubHeader.text = "You'll use less data, see way fewer ads, have better battery life, and stop being tracked on the web."
secondSubHeader = self.paragraphStyle(secondSubHeader)
secondSubHeader.userInteractionEnabled = false
thirdSubHeader.hidden = true
thirdSubHeader.text = "Antelope receives none of your browsing data, and it's entirely open-source."
thirdSubHeader = self.paragraphStyle(thirdSubHeader)
thirdSubHeader.userInteractionEnabled = false
self.constrainButton(nextButton)
self.view.layoutSubviews()
}
override func viewDidAppear(animated: Bool) {
}
func initialize() {
let translationDistance: CGFloat = 140.0
let headerFrame = self.stepZeroHeader.frame
self.stepZeroSubheader.frame.origin.y = headerFrame.origin.y + headerFrame.size.height
self.secondSubHeader.frame = stepZeroSubheader.frame
self.secondSubHeader.frame.origin.x = self.view.frame.size.width
self.secondSubHeader.hidden = false
/*self.delay(7.0, closure: {
UIView.animateWithDuration(0.5, animations: {
let anchor = self.stepZeroSubheader.frame.origin.x
self.stepZeroSubheader.frame.origin.x = 0 - self.stepZeroSubheader.frame.size.width
self.secondSubHeader.frame.origin.x = anchor
})
})*/
self.thirdSubHeader.frame = self.secondSubHeader.frame
self.thirdSubHeader.frame.origin.x = self.view.frame.size.width
self.thirdSubHeader.hidden = false
/*self.delay(14.0, closure: {
UIView.animateWithDuration(0.5, animations: {
let anchor = self.secondSubHeader.frame.origin.x
self.secondSubHeader.frame.origin.x = 0 - self.secondSubHeader.frame.size.width
self.thirdSubHeader.frame.origin.x = anchor
})
})*/
UIView.animateWithDuration(0.7, delay: 0, options: .CurveEaseInOut, animations: {
// LOGO MOVING
let currentPosY = self.logoImage.frame.origin.y
self.logoImage.frame.origin.y = currentPosY - translationDistance
//self.stepZeroHeaderImage.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, distanceFromToBeLogoToTop + inset)
}, completion: {(Bool) in
// LOGO MOVED
UIView.animateWithDuration(0.7, animations: {
self.stepZeroHeader.alpha = 1.0
}, completion: {(Bool) in
})
// sub header, then bars
self.delay(1.0) {
UIView.animateWithDuration(0.7, animations: {
self.nextButton.alpha = 0.5
self.stepZeroSubheader.alpha = 1.0
})
}
})
}
}
| gpl-2.0 |
benlangmuir/swift | test/Interpreter/Inputs/dynamic_replacement_chaining_B.swift | 34 | 112 | import A
extension Impl {
@_dynamicReplacement(for: foo())
func repl() -> Int {
return foo() + 1
}
}
| apache-2.0 |
fgulan/letter-ml | project/LetterML/Frameworks/framework/Source/Operations/Dilation.swift | 9 | 1516 | public class Dilation: TwoStageOperation {
public var radius:UInt {
didSet {
switch radius {
case 0, 1:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation1VertexShader, fragmentShader:Dilation1FragmentShader)}
case 2:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation2VertexShader, fragmentShader:Dilation2FragmentShader)}
case 3:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation3VertexShader, fragmentShader:Dilation3FragmentShader)}
case 4:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation4VertexShader, fragmentShader:Dilation4FragmentShader)}
default:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation4VertexShader, fragmentShader:Dilation4FragmentShader)}
}
}
}
public init() {
radius = 1
let initialShader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation1VertexShader, fragmentShader:Dilation1FragmentShader)}
super.init(shader:initialShader, numberOfInputs:1)
}
} | mit |
silence0201/Swift-Study | Swifter/28Lazy.playground/Contents.swift | 1 | 780 | //: Playground - noun: a place where people can play
import Foundation
class ClassA {
lazy var str: String = {
let str = "Hello"
print("只在首次访问输出")
return str
}()
}
print("Creating object")
let obj = ClassA()
print("Accessing str")
obj.str
print("Accessing str again")
obj.str
let data1 = 1...3
let result1 = data1.map { (i) -> Int in
print("正在处理\(i)")
return i*2
}
print("准备访问结果")
for i in result1 {
print("操作后结果为 \(i)")
}
print("操作完毕")
let data2 = 1...3
let result2 = data2.lazy.map {
(i: Int) -> Int in
print("正在处理 \(i)")
return i * 2
}
print("准备访问结果")
for i in result2 {
print("操作后结果为 \(i)")
}
print("操作完毕")
| mit |
HabitRPG/habitrpg-ios | HabitRPG/TabBarController/MainTabBarController.swift | 1 | 10166 | //
// MainTabBarController.swift
// Habitica
//
// Created by Phillip Thelen on 25.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
import FirebaseAnalytics
#if DEBUG
import FLEX
#endif
class MainTabBarController: UITabBarController, Themeable {
private let userRepository = UserRepository()
private let taskRepository = TaskRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
@objc public var selectedTags = [String]()
private var dueDailiesCount = 0
private var dueToDosCount = 0
private var tutorialDailyCount = 0
private var tutorialToDoCount = 0
private var badges: [Int: PaddedView]? {
set {
if let badges = newValue {
(tabBar as? MainTabBar)?.badges = badges
}
}
get { return (tabBar as? MainTabBar)?.badges }
}
private var showAdventureGuideBadge = false {
didSet {
let badge = badges?[4]
if showAdventureGuideBadge {
if badge == nil || badge?.containedView is UILabel {
badge?.removeFromSuperview()
let newBadge = PaddedView()
badges?[4] = newBadge
newBadge.verticalPadding = 4
newBadge.horizontalPadding = 4
newBadge.backgroundColor = .yellow10
newBadge.containedView = UIImageView(image: Asset.adventureGuideStar.image)
newBadge.isUserInteractionEnabled = false
tabBar.addSubview(newBadge)
(tabBar as? MainTabBar)?.layoutBadges()
} else {
return
}
} else {
if !(badge?.containedView is UILabel) {
badge?.removeFromSuperview()
badges?.removeValue(forKey: 4)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
#if DEBUG
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(showDebugMenu))
swipe.direction = .up
swipe.delaysTouchesBegan = true
swipe.numberOfTouchesRequired = 1
tabBar.addGestureRecognizer(swipe)
#endif
ThemeService.shared.addThemeable(themable: self)
}
func applyTheme(theme: Theme) {
tabBar.items?.forEach({
$0.badgeColor = theme.badgeColor
if theme.badgeColor.isLight() {
$0.setBadgeTextAttributes([.foregroundColor: UIColor.gray50], for: .normal)
} else {
$0.setBadgeTextAttributes([.foregroundColor: UIColor.gray700], for: .normal)
}
})
tabBar.tintColor = theme.fixedTintColor
tabBar.barTintColor = theme.contentBackgroundColor
tabBar.backgroundColor = theme.contentBackgroundColor
tabBar.backgroundImage = UIImage.from(color: theme.contentBackgroundColor)
tabBar.shadowImage = UIImage.from(color: theme.contentBackgroundColor)
tabBar.barStyle = .black
if #available(iOS 13.0, *) {
if ThemeService.shared.themeMode == "dark" {
self.overrideUserInterfaceStyle = .dark
} else if ThemeService.shared.themeMode == "light" {
self.overrideUserInterfaceStyle = .light
} else {
self.overrideUserInterfaceStyle = .unspecified
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
presentingViewController?.willMove(toParent: nil)
presentingViewController?.removeFromParent()
}
private func fetchData() {
disposable.inner.add(userRepository.getUser().on(value: {[weak self] user in
var badgeCount = 0
// swiftlint:disable:next empty_count
if let count = user.inbox?.numberNewMessages, count > 0 {
badgeCount += count
}
if user.flags?.hasNewStuff == true {
badgeCount += 1
}
if let partyID = user.party?.id {
if user.hasNewMessages.first(where: { (newMessages) -> Bool in
return newMessages.id == partyID
})?.hasNewMessages == true {
badgeCount += 1
}
}
self?.showAdventureGuideBadge = user.achievements?.hasCompletedOnboarding != true
self?.setBadgeCount(index: 4, count: badgeCount)
if let tutorials = user.flags?.tutorials {
self?.updateTutorialSteps(tutorials)
}
if user.flags?.welcomed != true {
self?.userRepository.updateUser(key: "flags.welcomed", value: true).observeCompleted {}
}
}).start())
disposable.inner.add(taskRepository.getDueTasks().on(value: {[weak self] tasks in
self?.dueDailiesCount = 0
self?.dueToDosCount = 0
let calendar = Calendar(identifier: .gregorian)
let today = Date()
for task in tasks.value where !task.completed {
if task.type == TaskType.daily {
self?.dueDailiesCount += 1
} else if task.type == TaskType.todo, let duedate = task.duedate {
if duedate < today || calendar.isDate(today, inSameDayAs: duedate) {
self?.dueToDosCount += 1
}
}
}
self?.updateDailyBadge()
self?.updateToDoBadge()
self?.updateAppBadge()
}).start())
}
private func updateTutorialSteps(_ tutorials: [TutorialStepProtocol]) {
for tutorial in tutorials {
if tutorial.key == "habits" {
setBadgeCount(index: 0, count: tutorial.wasSeen ? 0 : 1)
}
if tutorial.key == "dailies" {
tutorialDailyCount = tutorial.wasSeen ? 0 : 1
updateDailyBadge()
}
if tutorial.key == "todos" {
tutorialToDoCount = tutorial.wasSeen ? 0 : 1
updateToDoBadge()
}
if tutorial.key == "rewards" {
setBadgeCount(index: 3, count: tutorial.wasSeen ? 0 : 1)
}
}
}
private func updateDailyBadge() {
setBadgeCount(index: 1, count: dueDailiesCount + tutorialDailyCount)
}
private func updateToDoBadge() {
setBadgeCount(index: 2, count: dueToDosCount + tutorialToDoCount)
}
private func setBadgeCount(index: Int, count: Int) {
if index == 4 && showAdventureGuideBadge {
return
}
let badge = badges?[index] ?? PaddedView()
badges?[index] = badge
if !(badge.containedView is UILabel) {
badge.verticalPadding = 2
badge.horizontalPadding = 6
let label = UILabel()
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .center
badge.containedView = label
}
badge.backgroundColor = .gray50
if let label = badge.containedView as? UILabel {
label.text = "\(count)"
}
// swiftlint:disable:next empty_count
badge.isHidden = count == 0
badge.isUserInteractionEnabled = false
tabBar.addSubview(badge)
(tabBar as? MainTabBar)?.layoutBadges()
}
private func updateAppBadge() {
let defaults = UserDefaults.standard
if defaults.bool(forKey: "appBadgeActive") == true {
UIApplication.shared.applicationIconBadgeNumber = dueDailiesCount + dueToDosCount
} else {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if #available(iOS 13.0, *) {
ThemeService.shared.updateInterfaceStyle(newStyle: traitCollection.userInterfaceStyle)
}
}
#if DEBUG
@objc
private func showDebugMenu(_ recognizer: UISwipeGestureRecognizer) {
if recognizer.state = .recognizer {
FLEXManager.sharedManager.showExplorer()
}
}
#endif
}
class MainTabBar: UITabBar {
var badges = [Int: PaddedView]()
override open func sizeThatFits(_ size: CGSize) -> CGSize {
var sizeThatFits = super.sizeThatFits(size)
guard let window = UIApplication.shared.keyWindow else {
return sizeThatFits
}
if #available(iOS 11.0, *) {
if window.safeAreaInsets.bottom > 0 {
sizeThatFits.height = 42 + window.safeAreaInsets.bottom
}
}
return sizeThatFits
}
override func layoutSubviews() {
super.layoutSubviews()
layoutBadges()
}
func layoutBadges() {
for entry in badges {
let frame = frameForTab(atIndex: entry.key)
let size = entry.value.intrinsicContentSize
let width = max(size.height, size.width)
// Find the edge of the icon and then center the badge there
entry.value.frame = CGRect(x: frame.origin.x + (frame.size.width/2) + 15 - (width/2), y: frame.origin.y + 4, width: width, height: size.height)
entry.value.cornerRadius = size.height / 2
}
}
private func frameForTab(atIndex index: Int) -> CGRect {
var frames = subviews.compactMap { (view: UIView) -> CGRect? in
if let view = view as? UIControl {
return view.frame
}
return nil
}
frames.sort { $0.origin.x < $1.origin.x }
if frames.count > index {
return frames[index]
}
return frames.last ?? CGRect.zero
}
}
| gpl-3.0 |
jmgc/swift | test/decl/protocol/special/Actor.swift | 1 | 2227 | // RUN: %target-typecheck-verify-swift -enable-experimental-concurrency
// REQUIRES: concurrency
// Synthesis of for actor classes.
actor class A1 {
var x: Int = 17
}
actor class A2: Actor {
var x: Int = 17
}
actor class A3<T>: Actor {
var x: Int = 17
}
actor class A4: A1 {
}
actor class A5: A2 {
}
actor class A6: A1, Actor { // expected-error{{redundant conformance of 'A6' to protocol 'Actor'}}
// expected-note@-1{{'A6' inherits conformance to protocol 'Actor' from superclass here}}
}
// Explicitly satisfying the requirement.
actor class A7 {
// Okay: satisfy the requirement explicitly
@actorIndependent func enqueue(partialTask: PartialAsyncTask) { }
}
// A non-actor class can conform to the Actor protocol, if it does it properly.
class C1: Actor {
func enqueue(partialTask: PartialAsyncTask) { }
}
// Bad actors, that incorrectly try to satisfy the various requirements.
// Method that is not usable as a witness.
actor class BA1 {
func enqueue(partialTask: PartialAsyncTask) { } // expected-error{{actor-isolated instance method 'enqueue(partialTask:)' cannot be used to satisfy a protocol requirement}}
//expected-note@-1{{add '@asyncHandler' to function 'enqueue(partialTask:)' to create an implicit asynchronous context}}{{3-3=@asyncHandler }}
//expected-note@-2{{add '@actorIndependent' to 'enqueue(partialTask:)' to make this instance method independent of the actor}}{{3-3=@actorIndependent }}
}
// Method that isn't part of the main class definition cannot be used to
// satisfy the requirement, because then it would not have a vtable slot.
actor class BA2 { }
extension BA2 {
// expected-error@+1{{'enqueue(partialTask:)' can only be implemented in the definition of actor class 'BA2'}}
@actorIndependent func enqueue(partialTask: PartialAsyncTask) { }
}
// No synthesis for non-actor classes.
class C2: Actor { // expected-error{{type 'C2' does not conform to protocol 'Actor'}}
}
// Make sure the conformances actually happen.
func acceptActor<T: Actor>(_: T.Type) { }
func testConformance() {
acceptActor(A1.self)
acceptActor(A2.self)
acceptActor(A3<Int>.self)
acceptActor(A4.self)
acceptActor(A5.self)
acceptActor(A6.self)
acceptActor(A7.self)
}
| apache-2.0 |
Liqiankun/DLSwift | Swift/Swift数据类型.playground/Contents.swift | 1 | 1663 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
/** 基础数据类型 */
var numberOne : Int = 30;
//int的最大值
Int.max
//int的最小值
Int.min
var numberTwo : UInt = 3000;
UInt.max
UInt.min
Int8.max
Int8.min
Int64.max
Int64.min
let numberThree = 100_100_000
let nbFloat : Float = 233333.33;
let nbDouble : Double = 23.3333;
//12.25乘以十的十次方
let nb = 12.25e10;
//12.25乘以十的负8次方
let nc = 12.25e-8
//类型装换
let x : Int64 = 100;
let y : Int8 = 100;
let m = x + Int64(y)
let i :Double = 2.33;
let z : Float = 2.3;
let j = i + Double(z);
let red : CGFloat = 0;
let green : CGFloat = 0;
let blue : CGFloat = 0.3;
UIColor(red: red, green: green, blue: blue, alpha: 1.0)
//布尔
let imTrue = true
let imFalse = false
if imFalse{
print("I'm True")
}else{
print("I'm False")
}
//元组
var point = (4 , 5)
var httpRep = (404 , "Not found")
var httpRe : (Int64 , String) = (202 , "OK")
//元组解包
let(pX , pY) = point;
print(pX)
print(pY)
print(httpRep.1)
let pointOne = (p:2 , q : 3)
pointOne.p
let pointTwo : (pointP:Int, pointQ:Int) = (2,4)
pointTwo.pointP
//使用下划线忽略一些值
let loginResult = (true , "Success")
let (login,_) = loginResult
if login{
print("登录成功")
}
/** String */
//变量名称可以是中文
var 名字 = "David Lee"
print(名字)
//变量名称可以是表情
var 😀 = "Smile"
print(名字 + 😀)
let One = 1,Two = 2, Three = 3,bool = true
//separator分隔符,terminator(默认为回车)
print(One,Two,Three,bool,separator:"__",terminator:":)")
print(One, "*",Two,"=",One * Two)
| mit |
apple/swift-package-manager | Tests/WorkspaceTests/ManifestSourceGenerationTests.swift | 1 | 22833 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import PackageGraph
import PackageLoading
import PackageModel
import SPMTestSupport
import TSCBasic
import Workspace
import XCTest
extension String {
fileprivate func nativePathString(escaped: Bool) -> String {
#if _runtime(_ObjC)
return self
#else
let fsr = self.fileSystemRepresentation
defer { fsr.deallocate() }
if escaped {
return String(cString: fsr).replacingOccurrences(of: "\\", with: "\\\\")
}
return String(cString: fsr)
#endif
}
}
class ManifestSourceGenerationTests: XCTestCase {
/// Private function that writes the contents of a package manifest to a temporary package directory and then loads it, then serializes the loaded manifest back out again and loads it once again, after which it compares that no information was lost. Return the source of the newly generated manifest.
@discardableResult
private func testManifestWritingRoundTrip(
manifestContents: String,
toolsVersion: ToolsVersion,
toolsVersionHeaderComment: String? = .none,
additionalImportModuleNames: [String] = [],
fs: FileSystem = localFileSystem
) throws -> String {
try withTemporaryDirectory { packageDir in
let observability = ObservabilitySystem.makeForTesting()
// Write the original manifest file contents, and load it.
let manifestPath = packageDir.appending(component: Manifest.filename)
try fs.writeFileContents(manifestPath, string: manifestContents)
let manifestLoader = ManifestLoader(toolchain: try UserToolchain.default)
let identityResolver = DefaultIdentityResolver()
let manifest = try tsc_await {
manifestLoader.load(
manifestPath: manifestPath,
manifestToolsVersion: toolsVersion,
packageIdentity: .plain("Root"),
packageKind: .root(packageDir),
packageLocation: packageDir.pathString,
packageVersion: nil,
identityResolver: identityResolver,
fileSystem: fs,
observabilityScope: observability.topScope,
delegateQueue: .sharedConcurrent,
callbackQueue: .sharedConcurrent,
completion: $0
)
}
XCTAssertNoDiagnostics(observability.diagnostics)
// Generate source code for the loaded manifest,
let newContents = try manifest.generateManifestFileContents(
packageDirectory: packageDir,
toolsVersionHeaderComment: toolsVersionHeaderComment,
additionalImportModuleNames: additionalImportModuleNames)
// Check that the tools version was serialized properly.
let versionSpacing = (toolsVersion >= .v5_4) ? " " : ""
XCTAssertMatch(newContents, .prefix("// swift-tools-version:\(versionSpacing)\(toolsVersion.major).\(toolsVersion.minor)"))
// Write out the generated manifest to replace the old manifest file contents, and load it again.
try fs.writeFileContents(manifestPath, string: newContents)
let newManifest = try tsc_await {
manifestLoader.load(
manifestPath: manifestPath,
manifestToolsVersion: toolsVersion,
packageIdentity: .plain("Root"),
packageKind: .root(packageDir),
packageLocation: packageDir.pathString,
packageVersion: nil,
identityResolver: identityResolver,
fileSystem: fs,
observabilityScope: observability.topScope,
delegateQueue: .sharedConcurrent,
callbackQueue: .sharedConcurrent,
completion: $0
)
}
XCTAssertNoDiagnostics(observability.diagnostics)
// Check that all the relevant properties survived.
let failureDetails = "\n--- ORIGINAL MANIFEST CONTENTS ---\n" + manifestContents + "\n--- REWRITTEN MANIFEST CONTENTS ---\n" + newContents
XCTAssertEqual(newManifest.toolsVersion, manifest.toolsVersion, failureDetails)
XCTAssertEqual(newManifest.displayName, manifest.displayName, failureDetails)
XCTAssertEqual(newManifest.defaultLocalization, manifest.defaultLocalization, failureDetails)
XCTAssertEqual(newManifest.platforms, manifest.platforms, failureDetails)
XCTAssertEqual(newManifest.pkgConfig, manifest.pkgConfig, failureDetails)
XCTAssertEqual(newManifest.providers, manifest.providers, failureDetails)
XCTAssertEqual(newManifest.products, manifest.products, failureDetails)
XCTAssertEqual(newManifest.dependencies, manifest.dependencies, failureDetails)
XCTAssertEqual(newManifest.targets, manifest.targets, failureDetails)
XCTAssertEqual(newManifest.swiftLanguageVersions, manifest.swiftLanguageVersions, failureDetails)
XCTAssertEqual(newManifest.cLanguageStandard, manifest.cLanguageStandard, failureDetails)
XCTAssertEqual(newManifest.cxxLanguageStandard, manifest.cxxLanguageStandard, failureDetails)
// Return the generated manifest so that the caller can do further testing on it.
return newContents
}
}
func testBasics() throws {
let manifestContents = """
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MyPackage",
platforms: [
.macOS(.v10_14),
.iOS(.v13)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "MyPackage",
targets: ["MyPackage"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "MyPackage",
dependencies: []),
.testTarget(
name: "MyPackageTests",
dependencies: ["MyPackage"]),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
}
func testCustomPlatform() throws {
let manifestContents = """
// swift-tools-version:5.6
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MyPackage",
platforms: [
.custom("customOS", versionString: "1.0")
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "MyPackage",
targets: ["MyPackage"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "MyPackage",
dependencies: []),
.testTarget(
name: "MyPackageTests",
dependencies: ["MyPackage"]),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_6)
}
func testAdvancedFeatures() throws {
let manifestContents = """
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "MyPackage",
targets: ["MyPackage"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(path: "/a/b/c"),
.package(name: "abc", path: "/a/b/d"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.systemLibrary(
name: "SystemLibraryTarget",
pkgConfig: "libSystemModule",
providers: [
.brew(["SystemModule"]),
]),
.target(
name: "MyPackage",
dependencies: [
.target(name: "SystemLibraryTarget", condition: .when(platforms: [.macOS]))
],
linkerSettings: [
.unsafeFlags(["-Xlinker", "-rpath", "-Xlinker", "@executable_path/../../../lib/swift/macosx"], .when(platforms: [.iOS])),
]),
.testTarget(
name: "MyPackageTests",
dependencies: ["MyPackage"]),
],
swiftLanguageVersions: [.v5],
cLanguageStandard: .c11,
cxxLanguageStandard: .cxx11
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
}
func testPackageDependencyVariations() throws {
let manifestContents = """
// swift-tools-version:5.4
import PackageDescription
#if os(Windows)
let absolutePath = "file:///C:/Users/user/SourceCache/path/to/MyPkg16"
#else
let absolutePath = "file:///path/to/MyPkg16"
#endif
let package = Package(
name: "MyPackage",
dependencies: [
.package(url: "https://example.com/MyPkg1", from: "1.0.0"),
.package(url: "https://example.com/MyPkg2", .revision("58e9de4e7b79e67c72a46e164158e3542e570ab6")),
.package(url: "https://example.com/MyPkg5", .exact("1.2.3")),
.package(url: "https://example.com/MyPkg6", "1.2.3"..<"2.0.0"),
.package(url: "https://example.com/MyPkg7", .branch("main")),
.package(url: "https://example.com/MyPkg8", .upToNextMinor(from: "1.3.4")),
.package(url: "ssh://git@example.com/MyPkg9", .branch("my branch with spaces")),
.package(url: "../MyPkg10", from: "0.1.0"),
.package(path: "../MyPkg11"),
.package(path: "packages/path/to/MyPkg12"),
.package(path: "~/path/to/MyPkg13"),
.package(path: "~MyPkg14"),
.package(path: "~/path/to/~/MyPkg15"),
.package(path: "~"),
.package(path: absolutePath),
]
)
"""
let newContents = try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
// Check some things about the contents of the manifest.
XCTAssertTrue(newContents.contains("url: \"\("../MyPkg10".nativePathString(escaped: true))\""), newContents)
XCTAssertTrue(newContents.contains("path: \"\("../MyPkg11".nativePathString(escaped: true))\""), newContents)
XCTAssertTrue(newContents.contains("path: \"\("packages/path/to/MyPkg12".nativePathString(escaped: true))"), newContents)
}
func testResources() throws {
let manifestContents = """
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "Resources",
defaultLocalization: "is",
targets: [
.target(
name: "SwiftyResource",
resources: [
.copy("foo.txt"),
.process("a/b/c/"),
]
),
.target(
name: "SeaResource",
resources: [
.process("foo.txt", localization: .base),
]
),
.target(
name: "SieResource",
resources: [
.copy("bar.boo"),
]
),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
}
func testBuildSettings() throws {
let manifestContents = """
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "Localized",
targets: [
.target(name: "exe",
cxxSettings: [
.headerSearchPath("ProjectName"),
.headerSearchPath("../../.."),
.define("ABC=DEF"),
.define("GHI", to: "JKL")
]
),
.target(
name: "MyTool",
dependencies: ["Utility"],
cSettings: [
.headerSearchPath("path/relative/to/my/target"),
.define("DISABLE_SOMETHING", .when(platforms: [.iOS], configuration: .release)),
],
swiftSettings: [
.define("ENABLE_SOMETHING", .when(configuration: .release)),
],
linkerSettings: [
.linkedLibrary("openssl", .when(platforms: [.linux])),
]
),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
}
func testPluginTargets() throws {
let manifestContents = """
// swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "Plugins",
targets: [
.plugin(
name: "MyPlugin",
capability: .buildTool(),
dependencies: ["MyTool"]
),
.executableTarget(
name: "MyTool"
),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5)
}
func testCustomToolsVersionHeaderComment() throws {
let manifestContents = """
// swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "Plugins",
targets: [
.plugin(
name: "MyPlugin",
capability: .buildTool(),
dependencies: ["MyTool"]
),
.executableTarget(
name: "MyTool"
),
]
)
"""
let newContents = try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5, toolsVersionHeaderComment: "a comment")
XCTAssertTrue(newContents.hasPrefix("// swift-tools-version: 5.5; a comment\n"), "contents: \(newContents)")
}
func testAdditionalModuleImports() throws {
let manifestContents = """
// swift-tools-version:5.5
import PackageDescription
import Foundation
let package = Package(
name: "MyPkg",
targets: [
.executableTarget(
name: "MyExec"
),
]
)
"""
let newContents = try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5, additionalImportModuleNames: ["Foundation"])
XCTAssertTrue(newContents.contains("import Foundation\n"), "contents: \(newContents)")
}
func testCustomProductSourceGeneration() throws {
// Create a manifest containing a product for which we'd like to do custom source fragment generation.
let packageDir = AbsolutePath(path: "/tmp/MyLibrary")
let manifest = Manifest(
displayName: "MyLibrary",
path: packageDir.appending(component: "Package.swift"),
packageKind: .root(AbsolutePath(path: "/tmp/MyLibrary")),
packageLocation: packageDir.pathString,
platforms: [],
toolsVersion: .v5_5,
products: [
try .init(name: "Foo", type: .library(.static), targets: ["Bar"])
]
)
// Generate the manifest contents, using a custom source generator for the product type.
let contents = manifest.generateManifestFileContents(packageDirectory: packageDir, customProductTypeSourceGenerator: { product in
// This example handles library types in a custom way, for testing purposes.
var params: [SourceCodeFragment] = []
params.append(SourceCodeFragment(key: "name", string: product.name))
if !product.targets.isEmpty {
params.append(SourceCodeFragment(key: "targets", strings: product.targets))
}
// Handle .library specially (by not emitting as multiline), otherwise asking for default behavior.
if case .library(let type) = product.type {
if type != .automatic {
params.append(SourceCodeFragment(key: "type", enum: type.rawValue))
}
return SourceCodeFragment(enum: "library", subnodes: params, multiline: false)
}
else {
return nil
}
})
// Check that we generated what we expected.
XCTAssertTrue(contents.contains(".library(name: \"Foo\", targets: [\"Bar\"], type: .static)"), "contents: \(contents)")
}
func testModuleAliasGeneration() throws {
let manifest = Manifest.createRootManifest(
name: "thisPkg",
path: .init(path: "/thisPkg"),
toolsVersion: .v5_7,
dependencies: [
.localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")),
.localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "2.0.0")),
],
targets: [
try TargetDescription(name: "exe",
dependencies: ["Logging",
.product(name: "Foo",
package: "fooPkg",
moduleAliases: ["Logging": "FooLogging"]
),
.product(name: "Bar",
package: "barPkg",
moduleAliases: ["Logging": "BarLogging"]
)
]),
try TargetDescription(name: "Logging", dependencies: []),
])
let contents = try manifest.generateManifestFileContents(packageDirectory: manifest.path.parentDirectory)
let parts =
"""
dependencies: [
"Logging",
.product(name: "Foo", package: "fooPkg", moduleAliases: [
"Logging": "FooLogging"
]),
.product(name: "Bar", package: "barPkg", moduleAliases: [
"Logging": "BarLogging"
])
]
"""
let trimmedContents = contents.components(separatedBy: CharacterSet.whitespacesAndNewlines)
let trimmedParts = parts.components(separatedBy: CharacterSet.whitespacesAndNewlines)
let isContained = trimmedParts.allSatisfy(trimmedContents.contains(_:))
XCTAssertTrue(isContained)
try testManifestWritingRoundTrip(manifestContents: contents, toolsVersion: .v5_8)
}
}
| apache-2.0 |
wishzhouhe/Miler | swift_3.0_study/swift_3.0_study/AppDelegate.swift | 1 | 2212 | //
// AppDelegate.swift
// swift_3.0_study
//
// Created by myzj2004 on 16/10/13.
// Copyright © 2016年 myzj2004. All rights reserved.
//
import UIKit
//程序入口之前是main方法
@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:.
}
}
| mit |
overtake/TelegramSwift | Telegram-Mac/InstantPageImageItem.swift | 1 | 2666 | //
// InstantPageImageItem.swift
// Telegram
//
// Created by Mikhail Filimonov on 12/12/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import Postbox
import TelegramCore
protocol InstantPageImageAttribute {
}
struct InstantPageMapAttribute: InstantPageImageAttribute {
let zoom: Int32
let dimensions: CGSize
}
final class InstantPageImageItem: InstantPageItem {
let hasLinks: Bool = false
let isInteractive: Bool
let separatesTiles: Bool = false
func linkSelectionViews() -> [InstantPageLinkSelectionView] {
return []
}
var frame: CGRect
let webPage: TelegramMediaWebpage
let media: InstantPageMedia
let attributes: [InstantPageImageAttribute]
var medias: [InstantPageMedia] {
return [self.media]
}
let roundCorners: Bool
let fit: Bool
let wantsView: Bool = true
init(frame: CGRect, webPage: TelegramMediaWebpage, media: InstantPageMedia, attributes: [InstantPageImageAttribute] = [], interactive: Bool, roundCorners: Bool, fit: Bool) {
self.frame = frame
self.webPage = webPage
self.media = media
self.isInteractive = interactive
self.attributes = attributes
self.roundCorners = roundCorners
self.fit = fit
}
func view(arguments: InstantPageItemArguments, currentExpandedDetails: [Int : Bool]?) -> (InstantPageView & NSView)? {
let viewArguments: InstantPageMediaArguments
if let _ = media.media as? TelegramMediaMap, let attribute = attributes.first as? InstantPageMapAttribute {
viewArguments = .map(attribute)
} else {
viewArguments = .image(interactive: self.isInteractive, roundCorners: self.roundCorners, fit: self.fit)
}
return InstantPageMediaView(context: arguments.context, media: media, arguments: viewArguments)
}
func matchesAnchor(_ anchor: String) -> Bool {
return false
}
func matchesView(_ node: InstantPageView) -> Bool {
if let node = node as? InstantPageMediaView {
return node.media == self.media
} else {
return false
}
}
func distanceThresholdGroup() -> Int? {
return 1
}
func distanceThresholdWithGroupCount(_ count: Int) -> CGFloat {
if count > 3 {
return 400.0
} else {
return CGFloat.greatestFiniteMagnitude
}
}
func drawInTile(context: CGContext) {
}
func linkSelectionRects(at point: CGPoint) -> [CGRect] {
return []
}
}
| gpl-2.0 |
overtake/TelegramSwift | Telegram-Mac/ChatUnreadRowItem.swift | 1 | 2919 | //
// ChatUnreadRowItem.swift
// Telegram-Mac
//
// Created by keepcoder on 15/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import InAppSettings
import Postbox
class ChatUnreadRowItem: ChatRowItem {
override var height: CGFloat {
return 32
}
override var canBeAnchor: Bool {
return false
}
public var text:NSAttributedString;
override init(_ initialSize:NSSize, _ chatInteraction:ChatInteraction, _ context: AccountContext, _ entry:ChatHistoryEntry, _ downloadSettings: AutomaticMediaDownloadSettings, theme: TelegramPresentationTheme) {
let titleAttr:NSMutableAttributedString = NSMutableAttributedString()
let _ = titleAttr.append(string: strings().messagesUnreadMark, color: theme.colors.grayText, font: .normal(.text))
text = titleAttr.copy() as! NSAttributedString
super.init(initialSize,chatInteraction,entry, downloadSettings, theme: theme)
}
override var messageIndex:MessageIndex? {
switch entry {
case .UnreadEntry(let index, _, _):
return index
default:
break
}
return super.messageIndex
}
override var instantlyResize: Bool {
return true
}
override func viewClass() -> AnyClass {
return ChatUnreadRowView.self
}
}
private class ChatUnreadRowView: TableRowView {
private var text:TextNode = TextNode()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.layerContentsRedrawPolicy = .onSetNeedsDisplay
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
// Drawing code here.
}
override func updateColors() {
layer?.backgroundColor = .clear
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
needsDisplay = true
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
ctx.setFillColor(theme.colors.grayBackground.cgColor)
ctx.fill(NSMakeRect(0, 6, frame.width, frame.height - 12))
if let item = self.item as? ChatUnreadRowItem {
let (layout, apply) = TextNode.layoutText(maybeNode: text, item.text, nil, 1, .end, NSMakeSize(NSWidth(self.frame), NSHeight(self.frame)), nil,false, .left)
apply.draw(NSMakeRect(round((NSWidth(layer.bounds) - layout.size.width)/2.0), round((NSHeight(layer.bounds) - layout.size.height)/2.0), layout.size.width, layout.size.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor)
}
}
deinit {
var bp:Int = 0
bp += 1
}
}
| gpl-2.0 |
timominous/StatefulTableView | Sources/StatefulTableView+UIScrollView.swift | 1 | 1222 | //
// StatefulTableView+UIScrollView.swift
// Pods-Demo
//
// Created by Tim on 19/11/2017.
//
import UIKit
extension StatefulTableView {
/**
The point which the origin of the content view is offset from the origin of the scroll view.
- Discussion: Visit this [link](https://developer.apple.com/documentation/uikit/uiscrollview/1619404-contentoffset) for more details
*/
public var contentOffset: CGPoint {
set { tableView.contentOffset = newValue }
get { return tableView.contentOffset }
}
/**
The size of the content view.
- Discussion: Visit this [link](https://developer.apple.com/documentation/uikit/uiscrollview/1619399-contentsize) for more details
*/
public var contentSize: CGSize {
set { tableView.contentSize = newValue }
get { return tableView.contentSize }
}
/**
The custom distance that the content view is inset from the safe area or scroll view edges.
- Discussion: Visit this [link](https://developer.apple.com/documentation/uikit/uiscrollview/1619406-contentinset) for more details
*/
public var contentInset: UIEdgeInsets {
set { tableView.contentInset = newValue }
get { return tableView.contentInset }
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.